Index: /issm/branches/trunk-jpl-ad2-integrated/AUTHORS
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/AUTHORS	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/AUTHORS	(revision 18231)
@@ -0,0 +1,27 @@
+Ice Sheet System Model is a JPL/UCI collaboration to develop a massively-parallelized
+multi-purpose finite element framework dedicated to ice sheet modeling
+
+Project Scientist: 
+   Eric Rignot <eric.rignot@jpl.nasa.gov>
+
+Project Manager: 
+   Eric Larour <eric.larour@jpl.nasa.gov>
+
+Current core developers:
+   * Eric Larour <eric.larour@jpl.nasa.gov>
+   * Helene Seroussi <helene.seroussi@jpl.nasa.gov>
+   * Mathieu Morlighem <mathieu.morlighem@uci.edu>
+
+Contributors:
+	We thank the following contributors for their help in making ISSM better!
+
+	Robert Crippen, Jet Propulsion Laboratory.  robbert.crippen@jpl.nasa.gov
+	HoleFiller routines to plug incomplete datasets. See HoleFiller module in src/m/matlab/utils
+
+	Point Inclusion in Polygon Test (pnpoly.c used in Utils/Arguscontourtomesh/IsInPoly.c)
+	W. Randolph Franklin (WRF)
+	http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
+
+	DACE: A Matlab Kriging toolbox, Søren N.Lophaen, Hans Bruun Nielsen and Jacob
+	Søndergaard (Technical University of Denmark)
+	http://www2.imm.dtu.dk/~hbn/dace/
Index: /issm/branches/trunk-jpl-ad2-integrated/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/Makefile.am	(revision 18231)
@@ -0,0 +1,5 @@
+EXTRA_DIST = reconf scripts test m4 examples cron etc doc packages contributors.txt 
+SUBDIRS = src
+bin_SCRIPTS= README.rtf
+
+ACLOCAL_AMFLAGS = -I m4
Index: /issm/branches/trunk-jpl-ad2-integrated/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/README	(revision 18231)
@@ -0,0 +1,61 @@
+------------------------------------------------------------------------------
+
+ISSM
+Ice Sheet System Modeling: a framework for modeling ice flow on ice sheet/ice shelf
+systems using Finite Elemenent Analysis, and parallel technologies.
+
+------------------------------------------------------------------------------
+
+Jet Propulsion Laboratory
+
+Eric    Larour (Project Manager)
+Mathieu Morlighem (Core Developer, Anisotropic Meshing, Control Methods)
+Helene  Seroussi (Core Develper Coupling 2D-3D, Multi-model, full-Stokes)
+Nicole  Schlegel (Developer, Atmospheric Forcing)
+Chris   Borstad (Developer, Rifting/Faulting/Crack Propagation)
+Feras   Habbal (Developer, Solver Technologies)
+Daria   Halkides (Analyst, Atmospheric Forcing)
+Ala     Khazendar (Analyst, Ice Sheet Processes)
+
+Email: issm@jpl.nasa.gov
+
+------------------------------------------------------------------------------
+
+Website: http://issm.jpl.nasa.gov/ for additional information.
+
+------------------------------------------------------------------------------
+
+License
+
+ISSM is California Institute of Technology Copyright, Distributed under BSD Three Clause License.
+
+
+Copyright (c) 2002-2011, California Institute of Technology.
+All rights reserved.  Based on Government Sponsored Research under contracts
+NAS7-1407 and/or NAS7-03001.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the California Institute of Technology (Caltech),
+   its operating division the Jet Propulsion Laboratory (JPL), the National
+   Aeronautics and Space Administration (NASA), nor the names of its
+   contributors may be used to endorse or promote products derived from
+   this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE CALIFORNIA INSTITUTE OF TECHNOLOGY BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+------------------------------------------------------------------------------
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-arm-linux.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-arm-linux.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-arm-linux.sh	(revision 18231)
@@ -0,0 +1,14 @@
+#!/bin/sh
+
+./configure \
+   --prefix=$ISSM_DIR\
+   --libdir=$ISSM_DIR/../mobile/android/ISSM_APP/libs/armeabi\
+   --build="i386-apple-darwin10.8.0"\
+   --host="arm-linux-androideabi"\
+   --enable-shared\
+   --with-android=jni\
+   --with-android-ndk=$ISSM_DIR/externalpackages/android/android-ndk/install\
+   --without-fortran\
+   --without-wrappers\
+   --without-kriging\
+   --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-discover.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/csh
+
+#PETSc 3.2
+#MPI /usr/local/intel/mpi/4.0.3.008/lib64/
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+ --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mkl-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-mpi-include="/usr/local/intel/mpi/4.0.3.008/include64/" \
+ --with-mpi-libflags="-L/usr/local/intel/mpi/4.0.3.008/lib64/ -lmpi -lmpiif" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-scalapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-blacs-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-blas-lapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -xS -DMPICH_IGNORE_CXX_SEEK" \
+ --with-vendor=intel-discover
+
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-greenplanet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-greenplanet.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+#PETSc 3.2
+#MPI /sopt/mpi/openmpi-1.5.4_psm/intel
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-wrappers=no \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+ --with-mpi-include="/sopt/mpi/openmpi-1.5.4_psm/intel/include/" \
+ --with-mpi-libflags="-L/sopt/mpi/openmpi-1.5.4_psm/intel/lib/ -lmpi -lmpi_f77" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-mkl-dir=/opt/intel/mkl/10.2.4.032/ \
+ --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3" \
+ --with-vendor=intel-linux
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-hoffman2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-hoffman2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-hoffman2.sh	(revision 18231)
@@ -0,0 +1,18 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-wrappers=no \
+ --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mpi-include=/u/local/intel/11.1/openmpi/1.4.5/include \
+ --with-mpi-libflags="-L/u/local/intel/11.1/openmpi/1.4.5/include -lmpi" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -L/u/local/intel/11.1/openmpi/1.4.5/lib -lmpi -lmpi_f77 -lmpi_cxx"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-ios-linux.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-ios-linux.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-ios-linux.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+export DEVROOT="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/"
+export SDKROOT="$DEVROOT/SDKs/iPhoneOS6.0.sdk/"
+export CC=$DEVROOT/usr/bin/gcc
+export LD=$DEVROOT/usr/bin/ld
+export CPP=$DEVROOT/usr/bin/cpp
+export CXX=$DEVROOT/usr/bin/g++
+export CXXFLAGS="-O -arch armv7 -isysroot $SDKROOT" 
+export CFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export AR=$DEVROOT/usr/bin/ar
+export AS=$DEVROOT/usr/bin/as
+export LDFLAGS="-lstdc++ -arch armv7 -isysroot $SDKROOT" 
+export LIBTOOL=$DEVROOT/usr/bin/libtool
+export STRIP=$DEVROOT/usr/bin/strip
+export RANLIB=$DEVROOT/usr/bin/ranlib
+
+./configure \
+	--prefix=$ISSM_DIR \
+    --build="i386-apple-darwin10.8.0" \
+    --host="arm-apple-darwin10" \
+    --enable-shared \
+    --with-ios=yes \
+    --without-fortran \
+	--without-wrappers \
+	--without-kriging \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-acenet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-acenet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-acenet.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+./configure \
+ --prefix=/home/klemorza/issm/trunk-jpl \
+ --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mpi-include=$OPENMPI/include  \
+ --with-mpi-libflags="-L$OPENMPI/lib -lmpi" \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-cxxoptflags="-O2" \
+ --with-numthreads=32 \
+ --with-serial=no \
+ --with-modules=no \
+ --enable-debugging CC=mpicc CXX=mpiCC F77=mpif77
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ad.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ad.sh	(revision 18231)
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-wrappers\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--without-thermal \
+	--without-control \
+	--without-hydrology \
+	--without-stressbalance \
+	--without-balanced \
+	--without-responses \
+	--without-slope \
+	--without-rifts \
+	--without-steadystate \
+	--without-transient \
+	--without-3d \
+	--without-groundingline \
+	--without-kriging  \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cloud.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cloud.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cloud.sh	(revision 18231)
@@ -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/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-cxxoptflags=" -O2 -fpermissive" 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cmake.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cmake.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-cmake.sh	(revision 18231)
@@ -0,0 +1,2 @@
+rm $ISSM_DIR/CMakeCache.txt
+cmake -D GSL_DIR=${GSL_DIR} ${ISSM_DIR}
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-ad.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-ad.sh	(revision 18231)
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging  \
+	--without-kml  \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+	--with-adolc-version=3 \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-gia.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-gia.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen-gia.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir=$ISSM_DIR/externalpackages/matlab/install \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-python-dir=$ISSM_DIR/externalpackages/python/install\
+ --with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+ --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+ --with-shapelib-dir="$ISSM_DIR/externalpackages/shapelib/install" \
+ --with-math77-dir="$ISSM_DIR/externalpackages/math77/install" \
+ --with-gia="yes"\
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+ --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-numthreads=16 \
+ --enable-debugging
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-larsen.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir=$ISSM_DIR/externalpackages/matlab/install \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-python-dir=$ISSM_DIR/externalpackages/python/install\
+ --with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
+ --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+ --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-numthreads=16 \
+ --enable-debugging
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-ad.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-ad.sh	(revision 18231)
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+./configure \
+	 --prefix=$ISSM_DIR \
+	 --without-kriging \
+	 --without-kml \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-nopetsc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-nopetsc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo-nopetsc.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/sh
+./configure \
+	--prefix=$ISSM_DIR\
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-numthreads=18  \
+	--enable-debugging 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-murdo.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--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-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-numthreads=18 \
+	--enable-debugging 
+	#--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi-gcc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi-gcc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi-gcc.sh	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-wrappers=no \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+	--with-adolc-dir="$ISSM_DIR/externalpackages/adolc/install"\
+	--with-ampi-dir="$ISSM_DIR/externalpackages/adjoinablempi/install"\
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags=" -O3 -march=corei7-avx" \
+	--with-vendor="intel-pleiades-gcc"  \
+	CFLAGS="-O3 -march=corei7-avx" \
+	CXXFLAGS="-O3 -march=corei7-avx" \
+	FFLAGS="-O3 -march=corei7-avx" 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-ampi.sh	(revision 18231)
@@ -0,0 +1,19 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-wrappers=no \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+	--with-mpi-libflags="-L/nasa/sgi/mpt/2.06rp16/ -lmpi -lmpi++" \
+	--with-adolc-dir="$ISSM_DIR/externalpackages/adolc/install"\
+	--with-ampi-dir="$ISSM_DIR/externalpackages/adjoinablempi/install"\
+	--with-mkl-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+	--with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-O3" \
+	--with-vendor="intel-pleiades"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.4.4.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/mvapich2/1.4.1/gcc.sles11/include"\
+	--with-mpi-libflags=" -L/nasa/mvapich2/1.4.1/gcc.sles11/lib -lmpichcxx -lmpich -lpthread -lrdmacm -libverbs -libumad -lrt" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades-gcc"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.7.0.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 18231)
@@ -0,0 +1,18 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/mvapich2/1.6.sles11/gcc/include" \
+	--with-mpi-libflags="-L/nasa/mvapich2/1.6.sles11/gcc/lib -lmpich -lopa -lpthread -lrdmacm -libverbs -libumad -ldl -lrt" \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades-gcc"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh	(revision 18231)
@@ -0,0 +1,18 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+	--with-mpi-libflags="-L/nasa/sgi/mpt/2.06rp16/ -lmpi" \
+	--with-mkl-dir="/nasa/intel/Compiler/2012.0.032/composer_xe_2011_sp1/mkl/lib/intel64"\
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-graphics-lib="/usr/lib64/libX11.so" \
+	--with-cxxoptflags="-g -O2" \
+	--with-vendor="intel-pleiades"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-skylla.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-skylla.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-skylla.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir=$ISSM_DIR/externalpackages/matlab/install \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install/ \
+ --with-scalapack-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.2/ -lgfortran" \
+ --with-graphics-lib="/usr/lib64/libX11.so.6" \
+ --with-cxxoptflags="-g -O2" \
+ --with-numthreads=8
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ubuntu64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ubuntu64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-linux64-ubuntu64.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mpi-include="/usr/lib/mpich/include" \
+ --with-mpi-libflags="-L/usr/lib/mpich/lib -lmpich -lmpl -ldl" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --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-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+ --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.7/ -lgfortran"\
+ --with-numthreads=8 \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --enable-debugging
+ 
+ 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64-ad.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64-ad.sh	(revision 18231)
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-wrappers\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--without-thermal \
+	--without-control \
+	--without-hydrology \
+	--without-stressbalance \
+	--without-balanced \
+	--without-responses \
+	--without-slope \
+	--without-rifts \
+	--without-steadystate \
+	--without-transient \
+	--without-3d \
+	--without-groundingline
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-macosx64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/sh
+
+#petsc 3.4
+#mpich 3.0.4
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags=" $ISSM_DIR/externalpackages/mpich/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-fortran-lib="/usr/lib/gcc/i686-apple-darwin10/4.2.1/x86_64/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petsc3.4.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petsc3.4.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petsc3.4.sh	(revision 18231)
@@ -0,0 +1,20 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-wrappers=no \
+ --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+ --with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-tao-dir="$ISSM_DIR/externalpackages/tao/install" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-mpi-libflags="-L/nasa/sgi/mpt/2.06rp16/ -lmpi" \
+ --with-mkl-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+ --with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
+ --with-dakota-dir="$ISSM_DIR/externalpackages/dakota/install" \
+ --with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-graphics-lib="/usr/lib64/libX11.so" \
+ --with-cxxoptflags="-O3" \
+ --with-vendor="intel-pleiades"
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petscdev.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petscdev.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-pleiades-petscdev.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/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.04/include \
+ --with-mpi-libflags="-L/nasa/sgi/mpt/2.04/lib/ -lmpi -lpthread -lgfortran" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-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" \
+ --with-vendor=intel-pleiades
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-32.sh	(revision 18231)
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+#get configure.sh to pick up the win7 Visual Studio compiler 
+./configure --prefix=$ISSM_DIR \
+   --disable-static \
+   --with-vendor=intel-win7-32  \
+   --with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
+   --with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+   --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+   --with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
+   --with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+   --with-petsc-arch=$ISSM_ARCH  \
+   --with-mpi-libdir="$ISSM_DIR/externalpackages/petsc/install/lib" \
+   --with-mpi-libflags="-Wl,libpetsc.lib" \
+   --with-mpi-include="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64-parallel.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64-parallel.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64-parallel.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+#Dos style path needed for the windows sdk 7.1 cl compiler: 
+ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#get configure.sh to pick up the win7 Visual Studio compiler 
+./configure --prefix=$ISSM_DIR \
+	--with-vendor=intel-win7-64  \
+	--with-matlab-dir="C:/MATLAB/R2012b/"\
+	--with-triangle-dir="$ISSM_DIR_WIN/externalpackages/triangle/install" \
+	--with-metis-dir="$ISSM_DIR_WIN/externalpackages/metis/install" \
+	--with-petsc-dir="$ISSM_DIR_WIN/externalpackages/petsc/install" \
+	--with-petsc-arch=$ISSM_ARCH  \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install/lib"  \
+	--with-mpi-include="C:/MPICH2/include" \
+	--with-mpi-libflags="-LC:/MPICH2/lib mpi.lib"
+
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/config-win7-64.sh	(revision 18231)
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+#get configure.sh to pick up the win7 Visual Studio compiler 
+./configure --prefix=$ISSM_DIR \
+   --disable-static \
+	--with-vendor=intel-win7-64  \
+	--with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-petsc-arch=$ISSM_ARCH  \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
+	--with-mpi-libflags-dir="$ISSM_DIR/externalpackages/petsc/install/lib" \
+   --with-mpi-libflagss="-Wl,libpetsc.lib" \
+	--with-mpi-include-dir="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" 
Index: /issm/branches/trunk-jpl-ad2-integrated/configs/configure.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configs/configure.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configs/configure.sh	(revision 18231)
@@ -0,0 +1,19 @@
+#!/bin/sh
+
+#Default configuration script
+#petsc 3.4
+#mpich 1.4
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="$ISSM_DIR/externalpackages/mpich/install/include"  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-petsc-arch="$ISSM_ARCH" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install/" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install/" \
+	--with-numthreads=2
Index: /issm/branches/trunk-jpl-ad2-integrated/configure.ac
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/configure.ac	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/configure.ac	(revision 18231)
@@ -0,0 +1,48 @@
+# Process this file with autoconf to produce a configure script.
+
+#AUTOCONF
+AC_INIT([Ice Sheet System Model (ISSM)],[4.7],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
+AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
+m4_include([m4/issm_options.m4])
+AC_CANONICAL_TARGET                       #Determine the system type
+
+#Compilers
+AC_PROG_CC([icc cccl cl icl gcc])
+AC_PROG_CPP
+AC_PROG_CXX([icpc cccl cl icl g++])
+AC_PROG_F77([ifort g77 gfortran])
+
+#Libraries and linking
+AC_F77_LIBRARY_LDFLAGS
+AC_PATH_XTRA      #figure out X library and include paths
+
+#AUTOMAKE
+#Initialize automake and declare foreign so that we don't need a ChangeLog, INSTALL, etc
+AM_INIT_AUTOMAKE([foreign])
+AC_CONFIG_HEADERS([./config.h])   #Config file must be config.h
+AM_SILENT_RULES([yes])           #Do not show compilation command by default
+AM_PROG_CC_C_O
+AM_PROG_AR
+
+#Libtool
+LT_INIT
+
+#Run issm_options.m4
+ISSM_OPTIONS
+
+#List all Makefiles
+AC_CONFIG_FILES([
+					  Makefile
+					  src/Makefile
+					  src/c/Makefile 
+					  src/wrappers/Makefile
+					  src/wrappers/python/Makefile
+					  src/wrappers/matlab/Makefile
+					  src/mobile/Makefile
+					  src/mobile/native/Makefile
+					  src/m/Makefile
+					  ])
+
+#End of configure.ac
+AC_OUTPUT
Index: /issm/branches/trunk-jpl-ad2-integrated/etc/environment.csh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/etc/environment.csh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/etc/environment.csh	(revision 18231)
@@ -0,0 +1,103 @@
+#ISSM_DIR should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+#Load ISSM scripts
+setenv PATH {$PATH}:{$ISSM_DIR}/scripts
+
+#MATLAB
+set MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+if (-d MATLAB_DIR) then
+	setenv MATLAB_DIR {$MATLAB_DIR}
+	setenv PATH {$MATLAB_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
+endif
+
+#MPI
+set MPI_DIR="$ISSM_DIR/externalpackages/mpich/install"
+if (-d $MPI_DIR) then
+	setenv MPI_DIR {$MPI_DIR}
+	setenv PATH {$MPI_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
+	setenv MANPATH {$MANPATH}:$MPI_DIR/man
+endif
+
+#PETSC
+set PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+if (-d $PETSC_DIR) then
+	setenv PETSC_DIR {$PETSC_DIR}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib
+endif
+
+#SLEPC
+set SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+if (-d $SLEPC_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib
+endif
+
+#PETSC
+set TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+if (-d $TAO_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$TAO_DIR/lib
+endif
+
+#Dakota
+set DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+if (-d $DAKOTA_DIR) then
+	setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
+	setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
+endif
+
+#Doxygen
+set DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+if (-d $DOXYGEN_DIR) then
+	setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
+	setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
+endif
+
+#AUTOTOOLS
+set AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+if (-d $AUTOTOOLS_DIR) then
+	setenv PATH {$AUTOTOOLS_DIR}/bin:{$PATH}
+endif
+
+#SSH
+set SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+if (-d $SSH_DIR) then
+	setenv PATH {$PATH}:{$SSH_DIR}
+endif
+
+#VALGRIND
+set VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install/bin"
+if (-d $VALGRIND_DIR) then
+	setenv PATH {$PATH}:{$VALGRIND_DIR}
+endif
+
+#MERCURIAL
+set MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if (-d $MERCURIAL_DIR) then
+	setenv PYTHONPATH {$MERCURIAL_DIR}/mercurial/pure/
+	setenv PATH {$PATH}:{$MERCURIAL_DIR}
+endif
+
+#GSL
+set GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+if (-d $GSL_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$GSL_DIR}/lib
+endif
+
+#CMAKE
+set CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+if (-d $CMAKE_DIR) then
+	setenv PATH {$CMAKE_DIR}/bin:{$PATH}
+endif
+
+#YAMS
+set YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+if (-d $YAMS_DIR) then
+	setenv PATH {$PATH}:{$YAMS_DIR}/bin
+endif
+
+#SHELL2JUNIT
+set SHELL2JUNIT_DIR="$ISSM_DIR/externalpackages/shell2junit"
+if (-d $SHELL2JUNIT_DIR) then
+	setenv PATH {$PATH}:{$SHELL2JUNIT_DIR}/install
+endif
Index: /issm/branches/trunk-jpl-ad2-integrated/etc/environment.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/etc/environment.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/etc/environment.sh	(revision 18231)
@@ -0,0 +1,307 @@
+#ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+pathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		name=$1
+		if [[ "$ISSM_ARCH" == "cygwin-intel" ]]; then
+			#export path using the cygwin convention
+			name=`cygpath -u $1`
+		fi
+		export PATH="$name:$PATH"
+	fi
+} #}}}
+pathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		name=$1
+		if [[ "$ISSM_ARCH" == "cygwin-intel" ]]; then
+			#export path in cygwin convention
+			name=`cygpath -u $1`
+		fi
+		export PATH="$PATH:$name"
+	fi
+} #}}}
+libpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$1:$LD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+libpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+dylibpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$1:$DYLD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+dylibpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+
+#FIXME: during installation packages are installed one by one but environment.sh was sourced
+#before so new packages are NOT in the path.
+#may resource environment.sh with:
+#if [ -z $(echo "$PATH" | grep "$MATLAB_DIR") ]; then export $PATH...; fi
+
+#Windows compilers: 
+if [[ "$ISSM_ARCH" == "cygwin-intel" ]]; then
+	source $ISSM_DIR/externalpackages/windows/windows_environment.sh
+fi
+
+#Load ISSM scripts
+pathappend "$ISSM_DIR/scripts"
+
+MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+export MATLAB_DIR
+pathprepend   "$MATLAB_DIR/bin" #take precedence over /usr/local/bin/matlab
+libpathappend "$MATLAB_DIR/lib"
+
+#legacy mpich2 (To be removed)
+MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+MPI_DIR="$ISSM_DIR/externalpackages/mpich/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+export MPI_INC_DIR="$MPI_DIR/include"
+
+PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+export PETSC_DIR
+libpathappend "$PETSC_DIR/lib"
+
+SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+libpathappend "$SLEPC_DIR/lib"
+
+TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+libpathappend "$TAO_DIR/lib"
+
+DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+pathappend "$DAKOTA_DIR/bin"
+libpathappend "$DAKOTA_DIR/lib"
+dylibpathprepend "$DAKOTA_DIR/lib"
+
+DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+pathprepend "$DOXYGEN_DIR/bin"
+
+AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+pathprepend "$AUTOTOOLS_DIR/bin"
+
+SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+pathappend "$SDK_DIR"
+
+SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+pathappend "$SSH_DIR"
+
+VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install"
+pathprepend "$VALGRIND_DIR/bin"
+
+CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
+pathappend "$CPPCHECK_DIR/bin"
+
+GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
+pathprepend "$GDAL_DIR/bin"
+libpathappend "$GDAL_DIR/lib"
+
+PROJ4_DIR="$ISSM_DIR/externalpackages/proj.4/install"
+dylibpathprepend "$PROJ4_DIR/lib"
+libpathprepend "$PROJ4_DIR/lib"
+
+MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if [ -d "$MERCURIAL_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+	pathappend "$MERCURIAL_DIR"
+fi
+
+BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if [ -d "$BOOST_DIR" ]; then
+	export BOOSTROOT
+	export BOOST_DIR
+	libpathappend   "$BOOST_DIR/lib"
+	dylibpathappend "$BOOST_DIR/lib"
+	pathappend      "$BOOST_DIR/bin"
+fi
+
+XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
+if [ -d "$XERCESROOT" ]; then
+	export XERCESROOT 
+	export XERCESCROOT
+fi
+
+XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
+XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+PLATFORM="x86-Linux"
+if [ -d "$XAIF_DIR" ]; then
+	export XAIFBOOSTERROOT
+	export XAIFBOOSTER_HOME
+	export XAIF_DIR
+	export PLATFORM
+fi
+
+ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
+if [ -d "$ANGELROOT" ]; then
+	export ANGELROOT
+fi
+
+OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
+if [ -d "$OPENANALYSISROOT" ]; then
+	export OPENANALYSISROOT
+	libpathappend "$OPENANALYSISROOT/lib"
+fi
+
+JVM_DIR="/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/"
+libpathappend "$JVM_DIR"
+
+BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
+pathappend "$BBFTP_DIR/bin"
+
+ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
+pathappend "$ADIC_DIR/bin"
+libpathappend "$ADIC_DIR/lib"
+
+COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
+libpathappend "$COLPACK_DIR/lib"
+
+ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
+pathappend "$ECLIPSE_DIR"
+
+APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan/install"
+pathappend "$APPSCAN_DIR/bin"
+
+RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
+pathappend "$RATS_DIR/bin"
+
+DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
+pathappend "$DYSON_DIR"
+
+CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+pathprepend "$CMAKE_DIR/bin"
+
+SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
+pathappend "$SHAPELIB_DIR/exec"
+
+CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
+pathappend "$CCCL_DIR/bin"
+
+PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
+pathappend "$PACKAGEMAKER_DIR"
+
+#android-dev-dir
+export ANDROID_DIR="$ISSM_DIR/externalpackages/android"
+
+export ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
+pathappend "$ANDROID_NDK_DIR/arm-linux-android-install/bin"
+
+export ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install"
+pathappend "$ANDROID_SDK_DIR/"
+
+GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+libpathappend "$GSL_DIR/lib"
+
+GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
+pathprepend "$GMAKE_DIR/bin"
+
+PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
+if [ -d "$PYTHON_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
+	pathprepend    "$PYTHON_DIR/bin"
+	libpathprepend "$PYTHON_DIR/lib"
+	libpathprepend "$ISSM_DIR/lib"
+fi
+
+MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
+pathappend "$MODELE_DIR/src/exec"
+
+GIT_DIR="$ISSM_DIR/externalpackages/git/install"
+pathprepend "$GIT_DIR/bin"
+
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
+pathappend "$NCVIEW_DIR"
+
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+libpathappend "$TCLX_DIR"
+
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/install"
+pathappend "$ASPELL_DIR/bin"
+
+HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+dylibpathappend "$HDF5_DIR/lib"
+libpathappend "$HDF5_DIR/lib"
+if [ -d "$HDF5_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+fi
+
+NETCDF_DIR="$ISSM_DIR/externalpackages/netcdf/install"
+pathappend "$NETCDF_DIR/bin"
+dylibpathappend "$NETCDF_DIR/lib"
+libpathappend "$NETCDF_DIR/lib"
+if [ -d "$NETCDF_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$NETCDF_DIR/lib"
+	dylibpathappend "$NETCDF_DIR/lib"
+	libpathappend "$NETCDF_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$NETCDF_DIR/include"
+fi
+
+NETCDF_CXX_DIR="$ISSM_DIR/externalpackages/netcdf-cxx/install"
+libpathappend "$NETCDF_CXX_DIR/lib"
+
+SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
+pathprepend   "$SVN_DIR/bin"
+libpathappend "$SVN_DIR/lib"
+
+APR_DIR="$ISSM_DIR/externalpackages/apr/install"
+pathappend    "$APR_DIR/bin"
+libpathappend "$APR_DIR/lib"
+
+APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
+pathappend   "$APR_UTIL_DIR/bin:$PATH"
+libpathappend "$APR_UTIL_DIR/lib"
+
+SQLITE_DIR="$ISSM_DIR/externalpackages/sqlite/install"
+pathappend   "$SQLITE_DIR/bin"
+libpathappend "$SQLITE_DIR/lib"
+
+YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+pathappend   "$YAMS_DIR"
+
+SWIG_DIR="$ISSM_DIR/externalpackages/swig/install"
+pathappend   "$SWIG_DIR"
+
+#AUX-CONFIG
+pathappend   "$ISSM_DIR/aux-config"
+
+#INISHELL
+pathappend   "$ISSM_DIR/externalpackages/inishell/install"
+
+#SHELL2JUNIT
+pathappend   "$ISSM_DIR/externalpackages/shell2junit/install"
+
+#EXPAT
+libpathprepend   "$ISSM_DIR/externalpackages/expat/install"
+dylibpathprepend   "$ISSM_DIR/externalpackages/expat/install"
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Data/Download.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Data/Download.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Data/Download.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+echo "Downloading Square shelf dataset"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/SquareShelf.nc' 'SquareShelf.nc'
+
+echo "Downloading SeaRISE dataset - Antarctica"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/c/cc/Antarctica_5km_withshelves_v0.75.nc' 'Antarctica_5km_withshelves_v0.75.nc'
+
+echo "Downloading InSAR Antarctic velocities"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'ftp://sidads.colorado.edu/pub/DATASETS/nsidc0484_MEASURES_antarc_vel_V01/900m/antarctica_ice_velocity.nc' 'Antarctica_ice_velocity.nc' 
+
+echo "Downloading PIG errors"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/CrossOvers2009.mat' 'CrossOvers2009.mat'
+
+echo "Downloading SeaRISE dataset - Greenland"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/e/e9/Greenland_5km_dev1.2.nc' 'Greenland_5km_dev1.2.nc'
+
+echo "Downloading Jason Box's SMB"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc' 'Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc'
+
+echo "Downloading IceBridge Jakobshavn bedrock"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'https://data.cresis.ku.edu/data/grids/old_versions/Jakobshavn_2008_2011_Composite.zip' 'Jakobshavn_2008_2011_Composite.zip'
+unzip Jakobshavn_2008_2011_Composite.zip
+mv Jakobshavn_2008_2011_Composite/grids/Jakobshavn_2008_2011_Composite_XYZGrid.txt .
+rm -rf Jakobshavn_2008_2011_Composite Jakobshavn_2008_2011_Composite.zip
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/DomainOutline.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/DomainOutline.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/DomainOutline.exp	(revision 18231)
@@ -0,0 +1,733 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count Value
+727 1.000000
+# X pos Y pos
+47662.8073760000 -2621047.2585999998
+39869.9055420000 -2638077.6292949999
+26037.5047870000 -2644088.3483640002
+24868.5695120000 -2659115.1460360000
+25647.8596950000 -2674141.9437079998
+16880.8451320000 -2687666.0616130000
+515.7512810000 -2685662.4885900002
+-7666.7956450000 -2672639.2639410002
+-22083.6640370000 -2677147.3032430001
+-30071.3884170000 -2690170.5278920000
+-44683.0793550000 -2694678.5671930001
+-41760.7411680000 -2709705.3648660001
+-37669.4677050000 -2724231.2692820001
+-44488.2568100000 -2738757.1736989999
+-55787.9644690000 -2753283.0781149999
+-67672.1397650000 -2742263.4264890002
+-87154.3943500000 -2741762.5332330000
+-105078.0685680000 -2741011.1933490001
+-97090.3441880000 -2760546.0303230002
+-99817.8598300000 -2780581.7605530000
+-82478.6532500000 -2789096.9459000002
+-77218.4445120000 -2804123.7435730002
+-77023.6219660000 -2820152.3277560002
+-95336.9412760000 -2829669.2996149999
+-112870.9704020000 -2832674.6591500002
+-123196.5653320000 -2818649.6479890002
+-122417.2751480000 -2834177.3389170002
+-120274.2271440000 -2849204.1365890000
+-105662.5362060000 -2854713.9624020001
+-89492.2649000000 -2850706.8163560000
+-77997.7346950000 -2860724.6814710000
+-92024.9579960000 -2867737.1870519998
+-84816.5238000000 -2890277.3835600000
+-94752.4736380000 -2901797.9284419999
+-114234.7282230000 -2894284.5296060001
+-127677.4838860000 -2883765.7712349999
+-146964.9159250000 -2888774.7037930000
+-139951.3042750000 -2905805.0744880000
+-154173.3501210000 -2916824.7261140002
+-165667.8803260000 -2904302.3947210000
+-162550.7195930000 -2920330.9789040000
+-152809.5923000000 -2934355.9900650000
+-147744.2061080000 -2949883.6809930000
+-163719.6548680000 -2950384.5742489998
+-175603.8301650000 -2963908.6921540000
+-189825.8760110000 -2956896.1865730002
+-195670.5523870000 -2971422.0909899999
+-210282.2433250000 -2966413.1584319999
+-222750.8862590000 -2978301.3022220000
+-214763.1618800000 -2995247.5385030000
+-222750.8862590000 -3011386.8111520000
+-206970.2600460000 -3016228.5929470002
+-217295.8549760000 -3027122.6019839998
+-232686.8360980000 -3031964.3837790000
+-212035.6462380000 -3035192.2383090002
+-212814.9364210000 -3050928.0291410000
+-197229.1327540000 -3048910.6200600001
+-185344.9574570000 -3058190.7018329999
+-174824.5399810000 -3071102.1199520002
+-182812.2643610000 -3084820.5017030002
+-192163.7465610000 -3098942.3652710002
+-176577.9428940000 -3092486.6562120002
+-184955.3123650000 -3105801.5561469998
+-182617.4418150000 -3121537.3469790001
+-199372.1807580000 -3120326.9015310002
+-218464.7902510000 -3115888.6015519998
+-205022.0345870000 -3126782.6105900002
+-189825.8760110000 -3128800.0196710001
+-198592.8905740000 -3146149.7377680000
+-213009.7589670000 -3140904.4741580002
+-225283.5793550000 -3131220.9105679998
+-222750.8862590000 -3146149.7377680000
+-208334.0178670000 -3151395.0013790000
+-195670.5523870000 -3161078.5649680002
+-213009.7589670000 -3171569.0921900002
+-227621.4499060000 -3161078.5649680002
+-242622.7859360000 -3157850.7104389998
+-240090.0928400000 -3174393.4649040001
+-220023.3706180000 -3185690.9557579998
+-233076.4811890000 -3193357.1102660000
+-258013.7670580000 -3188111.8466550000
+-275158.1510920000 -3196181.4829790001
+-258208.5896040000 -3198198.8920600000
+-252753.5583200000 -3213127.7192600002
+-270482.4099920000 -3215952.0919740000
+-258793.0572410000 -3226442.6191960000
+-275547.7961840000 -3232969.1157640000
+-276521.9089130000 -3248275.5695210001
+-293276.6478560000 -3241868.2167850002
+-282561.4078340000 -3256818.7065010001
+-288211.2616640000 -3273549.0164200002
+-302433.3075110000 -3267141.6636850000
+-305745.2907900000 -3251479.2458879999
+-313733.0151700000 -3237596.6482950002
+-310810.6769820000 -3218018.6260489998
+-325812.0130120000 -3213747.0575589999
+-338280.6559470000 -3203780.0644160002
+-336527.2530340000 -3187761.6825779998
+-321720.7395500000 -3185269.9342919998
+-325812.0130120000 -3165691.9120459999
+-313538.1926240000 -3155368.9548610002
+-329708.4639290000 -3158928.5952699999
+-338085.8334010000 -3173167.1569030001
+-351723.4116100000 -3164268.0558819999
+-342566.7519550000 -3151809.3144530002
+-325812.0130120000 -3153233.1706160000
+-310615.8544360000 -3148249.6740450002
+-329123.9962920000 -3150029.4942490002
+-343151.2195930000 -3144334.0695949998
+-361854.1839940000 -3145401.9617180000
+-377634.8102080000 -3142910.2134320000
+-388350.0502290000 -3154657.0267800000
+-397701.5324300000 -3178150.6534750001
+-417573.4321060000 -3179930.4736790000
+-432720.8850460000 -3186308.0579260001
+-451813.4945390000 -3187438.8412219998
+-467788.9432980000 -3177261.7915590000
+-482985.1018740000 -3173492.5139070000
+-490583.1811620000 -3158792.3310610000
+-492726.2291670000 -3141453.6538590002
+-490193.5360710000 -3119214.9157079998
+-505389.6946470000 -3113560.9992289999
+-489803.8909790000 -3110922.5048719998
+-478309.3607740000 -3100368.5274439999
+-495648.5673540000 -3101122.3829750000
+-512792.9513890000 -3108660.9382799999
+-501103.5986380000 -3097353.1053220001
+-493895.1644420000 -3083783.7057719999
+-486491.9077000000 -3068329.6673960001
+-503636.2917340000 -3066068.1008040002
+-522728.9012270000 -3064183.4619780001
+-521559.9659520000 -3046467.8570099999
+-531301.0932440000 -3029506.1075729998
+-543769.7361790000 -3012167.4303710000
+-545912.7841830000 -2992944.1143419999
+-550004.0576459999 -2974474.6538439998
+-567538.0867720000 -2983897.8479749998
+-585851.4060810000 -2995959.5364640001
+-589942.6795440000 -2981259.3536189999
+-572213.8278720001 -2975982.3649050002
+-565200.2162220000 -2959397.5432330002
+-548055.8321870000 -2954120.5545190000
+-545717.9616370000 -2933389.5274290000
+-536561.3019820000 -2920197.0556450002
+-545523.1390910000 -2907758.4393910002
+-533444.1412490000 -2898335.2452590000
+-530568.0950890000 -2883304.2548420001
+-545624.1658510000 -2879383.1998239998
+-559750.8495300000 -2868110.1666489998
+-577223.3267109999 -2867129.9028940001
+-590606.5007220000 -2859287.7928590002
+-573319.9009570000 -2851445.6828239998
+-551572.2431889999 -2846054.2321750000
+-530939.8499220000 -2834781.1989989998
+-528337.5660870000 -2817626.5832969998
+-543765.3916830000 -2804883.1544900001
+-528151.6886699999 -2802432.4951040000
+-528151.6886699999 -2785768.0112790000
+-513467.3727410000 -2778416.0331210000
+-513839.1275750000 -2760771.2855420001
+-525735.2822510001 -2749498.2523670001
+-509563.9469880000 -2738225.2191909999
+-517184.9210780000 -2724501.5266300002
+-532240.9918400000 -2725971.9222610001
+-524248.2629170000 -2707837.0428050002
+-512537.9856570000 -2694113.3502429998
+-521088.3468310000 -2678429.1301730000
+-538189.0691780000 -2669606.7563829999
+-556033.3011930001 -2677448.8664190001
+-539676.0885130001 -2666175.8332429999
+-526664.6693360000 -2658333.7232080000
+-517556.6759110000 -2639708.7118739998
+-526107.0370850000 -2626965.2830670001
+-538932.5788460000 -2618142.9092779998
+-550456.9786890000 -2607360.0079790000
+-565698.9268680000 -2599517.8979440001
+-581126.7524640000 -2600988.2935759998
+-583110.5023000001 -2578346.1085480000
+-572583.8192940000 -2566324.6704099998
+-556315.3091930000 -2558811.2715739999
+-538132.8567270000 -2571333.6029679999
+-524735.2601730000 -2578346.1085480000
+-519759.0100240000 -2594875.5859869998
+-503107.7114500000 -2585859.5073839999
+-486456.4128760000 -2576342.5355250002
+-477843.6722340000 -2559312.1648300001
+-474015.7875040000 -2536771.9683220000
+-473441.6047950000 -2521244.2773940000
+-474972.7586870000 -2504714.7999539999
+-485690.8359300000 -2491691.5753049999
+-486073.6244030000 -2476664.7776330002
+-492581.0284430000 -2459634.4069380001
+-474207.1817410000 -2447112.0755440001
+-465594.4410990000 -2434589.7441509999
+-462340.7390790000 -2418060.2667109999
+-462914.9217880000 -2399026.3229930000
+-468465.3546460000 -2375484.3399729999
+-473058.8163220000 -2360457.5423010001
+-478417.8549440000 -2343427.1716060000
+-504256.0768690000 -2331405.7334679998
+-489901.5091330000 -2322389.6548649999
+-475164.1529230000 -2307863.7504480002
+-462577.4401970000 -2287577.5735909999
+-457317.2314590000 -2269044.5231289999
+-439783.2023330000 -2268042.7366169998
+-436666.0415990000 -2252014.1524330000
+-435886.7514160000 -2233481.1019710000
+-448550.2168960000 -2220457.8773220000
+-440172.8474240000 -2206933.7594170002
+-429262.7848570000 -2193409.6415120000
+-433743.7034120000 -2176880.1640720000
+-426730.0917610000 -2162354.2596560000
+-419716.4801110000 -2147327.4619840002
+-428678.3172200000 -2134805.1305900002
+-427314.5593990000 -2110762.2543150000
+-426535.2692150000 -2094733.6701310000
+-427509.3819440000 -2067184.5410650000
+-428093.8495820000 -2050655.0636260000
+-425366.3339400000 -2035628.2659539999
+-432379.9455910000 -2021102.3615369999
+-446017.5238000000 -2003571.0975860001
+-430821.3652240000 -2002569.3110750001
+-428678.3172200000 -1986039.8336360001
+-424197.3986650000 -1971013.0359630000
+-418060.4884710000 -1957238.4714309999
+-433451.4695930000 -1950225.9658500000
+-426243.0353960000 -1933696.4884110000
+-441634.0165180000 -1943714.3535259999
+-433841.1146840000 -1926683.9828300001
+-448647.6281690000 -1933696.4884110000
+-464428.2543820000 -1948222.3928270000
+-465402.3671120000 -1933195.5951550000
+-463843.7867450000 -1914662.5446929999
+-456245.7074570000 -1901138.4267879999
+-468714.3503910000 -1892122.3481840000
+-480208.8805960000 -1905646.4660890000
+-479429.5904130000 -1888616.0953939999
+-478455.4776830000 -1871585.7246989999
+-478650.3002290000 -1856558.9270270001
+-484494.9766050000 -1841031.2360990001
+-494430.9264430000 -1822498.1856370000
+-505925.4566480000 -1807972.2812200000
+-508847.7948350000 -1791442.8037810000
+-504172.0537350000 -1776416.0061079999
+-510990.8428400000 -1759886.5286689999
+-502223.8282770000 -1745861.5175079999
+-512939.0682980000 -1728330.2535570001
+-511964.9555690000 -1712802.5626300001
+-505340.9890100000 -1697775.7649570000
+-506315.1017390000 -1681747.1807740000
+-507289.2144690000 -1662713.2370559999
+-508446.9486300000 -1645056.7497910000
+-502180.9448550000 -1623518.3397939999
+-505662.0580630000 -1602480.8230530000
+-505836.1137240000 -1586953.1321250000
+-509317.2269320000 -1571425.4411970000
+-516105.3976870000 -1557400.4300360000
+-530552.0175000000 -1537865.5930620001
+-533336.9080660000 -1513321.8235309999
+-522719.5127820000 -1498295.0258589999
+-506532.3363650000 -1492284.3067900001
+-522893.5684430000 -1484770.9079539999
+-515757.2863660000 -1469744.1102819999
+-532118.5184440000 -1465236.0709800001
+-535947.7429720000 -1449708.3800520001
+-544476.4703320001 -1428670.8633109999
+-551960.8637290000 -1415146.7454059999
+-565363.1495800000 -1405629.7735470000
+-567277.7618440000 -1386094.9365729999
+-582420.6042990000 -1384091.3635499999
+-593212.0552430000 -1370066.3523899999
+-606266.2297730000 -1362052.0602980000
+-613793.7528780000 -1344395.5730330001
+-621618.1005840000 -1359923.2639609999
+-634079.0987820000 -1369440.2358200001
+-633354.6221430000 -1354413.4381480000
+-638860.6446030000 -1339386.6404760000
+-649438.0035390001 -1351908.9718690000
+-667405.0241970000 -1352409.8651250000
+-679431.3364110000 -1363429.5167510000
+-679721.1270670000 -1346900.0393119999
+-676533.4298540000 -1330370.5618720001
+-690008.6953470000 -1339386.6404760000
+-701165.6355950000 -1327365.2023380001
+-688994.4280520000 -1315844.6574560001
+-709279.7739560000 -1318349.1237339999
+-717249.0169900000 -1331372.3483839999
+-735216.0376480001 -1329869.6686160001
+-741420.6668040000 -1315969.8807699999
+-750947.3474350000 -1299440.4033299999
+-734597.5036490000 -1299440.4033299999
+-722496.0444700000 -1284413.6056580001
+-707948.5456690000 -1288420.7517039999
+-689023.9233340001 -1290424.3247270000
+-678209.8534290000 -1276399.3135660000
+-672545.3406220000 -1262374.3024060000
+-693401.0468670001 -1264377.8754280000
+-709493.4127980000 -1260871.6226379999
+-725971.9955110000 -1250853.7575240000
+-725714.5176560000 -1234825.1733400000
+-720951.1773400001 -1215290.3363659999
+-737172.2821980000 -1218295.6958999999
+-749402.4803050000 -1205272.4712510000
+-736399.8486340001 -1196757.2859040000
+-720822.4384130000 -1191247.4600899999
+-710652.0631450000 -1204771.5779949999
+-697906.9093280000 -1218796.5891559999
+-684131.8440910000 -1227812.6677590001
+-668940.6506530000 -1229816.2407819999
+-666237.1331770000 -1253358.2238020001
+-653620.7182870000 -1262374.3024060000
+-648471.1611900000 -1247347.5047330000
+-634696.0959530000 -1258868.0496149999
+-632625.0227419999 -1243541.0164699999
+-618416.8083510000 -1233878.1370890001
+-601000.2874830000 -1228080.4094600000
+-615361.2783740000 -1217451.2421410000
+-598861.4165000001 -1216968.0981719999
+-610625.2069099999 -1201990.6351310001
+-617652.9258560000 -1185080.5962139999
+-631708.3637490000 -1178799.7246160000
+-648666.5551200000 -1183631.1643070001
+-656458.1565610000 -1169136.8452349999
+-653708.1795820000 -1154159.3821950001
+-665166.4169950000 -1166237.9814210001
+-676166.3249110000 -1153193.0942569999
+-676166.3249110000 -1133384.1915249999
+-689305.1038110000 -1118406.7284850001
+-709013.2721609999 -1111159.5689490000
+-711610.4726409999 -1091833.8101870001
+-716346.5441050000 -1074440.6273010001
+-701527.2237180000 -1070092.3315790000
+-680291.2903790000 -1068642.8996720000
+-664096.9815030000 -1078788.9230219999
+-650958.2026030000 -1100530.4016300000
+-628041.7277770001 -1095698.9619390001
+-611236.3129050001 -1091350.6662170000
+-588930.9440750000 -1094732.6740009999
+-577319.9301640000 -1078305.7790530000
+-565250.5867559999 -1066710.3237960001
+-550431.2663680000 -1071541.7634860000
+-540042.4644469999 -1060429.4521979999
+-531203.6819710000 -1047613.0696300000
+-510357.6695660000 -1037937.0529810000
+-498473.4942690000 -1027821.2173940000
+-486199.6738810000 -1015066.4681760001
+-487953.0767930000 -994834.7970020000
+-464964.0163830000 -990876.4265550000
+-449378.2127160000 -998353.3485110000
+-430285.6032230000 -1001432.0810810000
+-417622.1377430000 -1012427.5545450000
+-399308.8184330000 -1004950.6325890000
+-384697.1274945000 -1000332.5337340001
+-370085.4365560000 -995714.4348789999
+-375540.4678400000 -980760.5909680000
+-380021.3863940000 -966246.5659950000
+-383528.1922200000 -949973.2652690000
+-383528.1922200000 -930181.4130330000
+-384112.6598570000 -911709.0176140000
+-380216.2089400000 -883560.6055450001
+-366919.5701860000 -892846.9764360000
+-353087.1694310000 -880338.0618260000
+-336527.2530340000 -873692.7009390000
+-322694.8522790000 -888547.0370390000
+-307888.3387940000 -897146.9158330000
+-294835.2282230000 -913564.8662580000
+-275937.4412760000 -919037.5164000000
+-252169.0906820000 -915128.4805850000
+-245350.3015780000 -901446.8552300000
+-244181.3663030000 -918646.6128190000
+-231615.3120950000 -930563.0925760000
+-215445.0407900000 -924017.9382920000
+-206872.8487730000 -937108.2468600000
+-190507.7549220000 -933426.5975750000
+-186611.3040050000 -912972.9904390000
+-185961.8955186667 -896882.8194913333
+-185312.4870323333 -880792.6485436666
+-184663.0785460000 -864702.4775960000
+-175311.5963460000 -883519.7961620000
+-174532.3061620000 -902337.1147280000
+-172584.0807040000 -918700.0004370000
+-168882.4523330000 -933835.6697180000
+-152322.5359360000 -933835.6697180000
+-142581.4086430000 -921563.5054359999
+-127969.7177050000 -912154.8461530000
+-131086.8784390000 -930563.0925760000
+-115501.0747710000 -924427.0104349999
+-112189.0914910000 -905609.6918690000
+-114916.6071330000 -887610.5175890001
+-101473.8514700000 -899882.6818710000
+-84329.4674350000 -896610.1047290000
+-100110.0936490000 -892110.3111590000
+-87836.2732610000 -879838.1468770000
+-74685.7514160000 -869305.2030530000
+-57541.3673810000 -863251.9975030000
+-49553.6430020000 -850388.9357080000
+-34357.4844260000 -846227.3568920000
+-47995.0626350000 -825797.7881600000
+-30071.3884170000 -835255.9218320000
+-18771.6807580000 -850767.2610550000
+-6303.0378240000 -859847.0693810000
+7139.7178400000 -852658.8877899999
+22141.0538700000 -862873.6721560000
+31297.7135250000 -877628.3606850000
+47662.8073760000 -874601.7579100000
+49611.0328340000 -893518.0252550000
+66365.7717770000 -886708.1690110000
+81123.5796250000 -882220.1151260000
+97683.4960220000 -884202.5846670000
+80149.4668960000 -888960.5115630000
+65537.7759570000 -896493.8958170000
+68460.1141450000 -914732.6155880000
+84435.5629050000 -917508.0729450000
+100605.8342100000 -907595.7252430000
+120282.9113400000 -911957.1582320000
+129049.9259030000 -927420.4206470000
+153402.7441340000 -925437.9511060000
+169767.8379850000 -920680.0242090001
+180677.9005530000 -910371.1825990001
+192367.2533040000 -899269.3531730000
+201134.2678670000 -912353.6521400000
+182626.1260110000 -920680.0242090001
+169183.3703480000 -936539.7805320000
+163338.6939720000 -950417.0673150000
+182820.9485570000 -955174.9942120000
+187301.8671120000 -970241.7627180000
+200744.6227750000 -980550.6043280000
+198796.3973170000 -995617.3728350000
+211118.9233410000 -983385.4589040000
+211508.5684330000 -999969.0227530000
+225146.1466420000 -1008484.9068910000
+240731.9503100000 -1009829.5201760000
+238588.9023060000 -1032239.7415930000
+253785.0608820000 -1029550.5150230000
+273072.4929210000 -1036273.5814480000
+281255.0398460000 -1056890.9851510001
+286320.4260380000 -1071681.7312860000
+305413.0355310000 -1086024.2729930000
+316907.5657360000 -1095884.7704169999
+326453.8704830000 -1081990.4331380001
+341260.3839670000 -1076611.9799980000
+355677.2523600000 -1064958.6648609999
+372319.0245690000 -1056006.2810410000
+387981.0391590000 -1068027.7191780000
+383779.0352450000 -1084056.3033620000
+366207.0188750000 -1085558.9831290001
+366971.0195860000 -1102088.4605690001
+352646.0062410000 -1113108.1121950001
+362960.0158500000 -1126131.3368440000
+380914.0325760000 -1133143.8424249999
+394093.0448530000 -1123626.8705660000
+409182.0589100000 -1113108.1121950001
+409182.0589100000 -1131641.1626569999
+404407.0544620000 -1158689.3984670001
+386262.0375580000 -1153179.5726540000
+374229.0263480000 -1166202.7973030000
+364488.0172730000 -1182732.2747430000
+377285.0291950000 -1191748.3533460000
+388172.0393370000 -1202768.0049719999
+392947.0437860000 -1219798.3756680000
+380341.0320420000 -1228814.4542710001
+383588.0350670000 -1251354.6507790000
+389509.0405830000 -1265880.5551960000
+389509.0405830000 -1282910.9258910001
+399632.0500130000 -1295934.1505400001
+408609.0583760000 -1313966.3077469999
+410137.0598000000 -1333000.2514650000
+413526.9681570000 -1350406.2921020000
+416526.2265730000 -1367436.6627970000
+415776.4119690000 -1385468.8200040001
+419900.3922910000 -1406005.4434890000
+430960.1577010000 -1421032.2411610000
+431897.4259560000 -1436059.0388330000
+448018.4399430000 -1436559.9320890000
+448580.8008960000 -1456094.7690630001
+438458.3037410000 -1469117.9937120001
+432459.7869090000 -1486148.3644069999
+449705.5228020000 -1494663.5497550000
+448393.3472450000 -1513196.6002170001
+463202.1856750000 -1521210.8923090000
+447830.9862920000 -1525218.0383550001
+458140.9370980000 -1539243.0495160001
+462639.8247220000 -1554269.8471880001
+473887.0437820000 -1564287.7123030000
+458703.2980510000 -1557275.2067219999
+463014.7320240000 -1574305.5774170000
+478948.2923600000 -1567293.0718370001
+484009.5409370000 -1584824.3357879999
+475011.7656880000 -1597346.6671819999
+484009.5409370000 -1614877.9311319999
+488508.4285610000 -1630906.5153160000
+470512.8780640000 -1618384.1839230000
+461702.5564670000 -1631407.4085720000
+474074.4974330000 -1641926.1669419999
+488883.3358630000 -1648938.6725230000
+495661.8324810000 -1662963.6836830000
+478923.6439970000 -1667471.7229849999
+463095.1396700000 -1663965.4701950001
+449449.8773190000 -1652945.8185690001
+455817.6664170000 -1670477.0825199999
+441626.5935720000 -1662963.6836830000
+433439.4361610000 -1648437.7792670000
+409690.0603430000 -1652315.3206390000
+394504.9542530000 -1655951.1781029999
+411243.1427370000 -1662462.7904280000
+426707.7734010000 -1676487.8015880000
+437260.1096190000 -1691514.5992610001
+455999.6032480000 -1702534.2508870000
+441626.5935720000 -1710047.6497229999
+428891.0153770000 -1692516.3857720001
+435076.8676430000 -1708544.9699560001
+419976.1106410000 -1704036.9306540000
+408696.0270980000 -1692516.3857720001
+395050.7647470000 -1701532.4643750000
+388501.0388190000 -1718562.8350710000
+378494.5130940000 -1731085.1664640000
+376129.3342870000 -1713553.9025129999
+361938.2614420000 -1720566.4080940001
+373582.2186480000 -1732086.9529760000
+358481.4616460000 -1738598.5652999999
+369397.6715270000 -1754627.1494839999
+352659.4830430000 -1751621.7899490001
+335805.3526830000 -1754501.9261700001
+338338.0457790000 -1777042.1226780000
+354897.9621760000 -1775539.4429110000
+349053.2858010000 -1792569.8136060000
+330739.9664910000 -1791568.0270950000
+344182.7221550000 -1806093.9315110000
+341455.2065130000 -1823625.1954620001
+351780.8014430000 -1809600.1843010001
+344377.5447010000 -1826129.6617409999
+356066.8974510000 -1836147.5268550001
+345546.4799760000 -1853678.7908059999
+363080.5091020000 -1853678.7908059999
+371847.5236650000 -1841156.4594129999
+370288.9432980000 -1859689.5098750000
+386848.8596950000 -1868204.6952229999
+404772.5339130000 -1856183.2570849999
+415098.1288430000 -1867703.8019669999
+428735.7070520000 -1860691.2963870000
+421137.6277640000 -1874215.4142920000
+413929.1935680000 -1888741.3187080000
+418799.7572140000 -1903768.1163800000
+428735.7070520000 -1916791.3410300000
+415098.1288430000 -1935825.2847480001
+398148.5673540000 -1926809.2061439999
+380030.0705910000 -1929814.5656790000
+364444.2669230000 -1929814.5656790000
+348468.8181630000 -1924304.7398659999
+333077.8370420000 -1919796.7005640001
+348079.1730720000 -1935825.2847480001
+332883.0144960000 -1939832.4307939999
+318855.7911950000 -1951853.8689309999
+331908.9017660000 -1964376.2003250001
+349442.9308930000 -1959868.1610230000
+358209.9454560000 -1943338.6835840000
+358404.7680020000 -1958365.4812560000
+345936.1250670000 -1971388.7059050000
+345351.6574300000 -1987918.1833450000
+330739.9664910000 -1991925.3293910001
+337753.5781420000 -2005449.4472960001
+353534.2043550000 -2007453.0203180001
+365223.5571060000 -1997435.1552040000
+385679.9244200000 -1986415.5035770000
+399317.5026290000 -1977399.4249740001
+399122.6800840000 -1993928.9024139999
+381393.8284120000 -1998436.9417150000
+399512.3251750000 -1999939.6214820000
+395615.8742580000 -2018973.5652000001
+387822.9724240000 -2032998.5763610001
+383975.2271440000 -2048275.8206610000
+398976.5631740000 -2062801.7250780000
+397223.1602620000 -2078830.3092610000
+379299.4860440000 -2080833.8822840001
+362739.5696470000 -2085842.8148419999
+374428.9223980000 -2097363.3597240001
+390599.1937030000 -2089849.9608880000
+379299.4860440000 -2103374.0787930000
+364492.9725590000 -2111388.3708839999
+355531.1354500000 -2097363.3597240001
+343257.3150620000 -2111889.2641400001
+351829.5070790000 -2127917.8483239999
+365661.9078340000 -2119402.6629760000
+357284.5383630000 -2133928.5673929998
+374039.2773060000 -2136933.9269269998
+385533.8075110000 -2147452.6852980000
+375792.6802180000 -2160976.8032030002
+390988.8387940000 -2162479.4829699998
+378520.1958600000 -2174000.0278520002
+394105.9995280000 -2164983.9492489998
+409107.3355580000 -2161978.5897140000
+421186.3334010000 -2149957.1515759998
+437941.0723440000 -2150958.9380879998
+450409.7152780000 -2171495.5615730002
+454695.8112860000 -2156969.6571570002
+471645.3727750000 -2159975.0166910002
+459566.3749330000 -2147452.6852980000
+465605.8738540000 -2132425.8876260002
+477490.0491500000 -2120404.4494880000
+485867.4186220000 -2133427.6741370000
+493264.3211700000 -2119402.6629760000
+495978.8328800000 -2102873.1855370002
+509098.9728100000 -2110386.5843730001
+523877.9810080000 -2104876.7585600000
+541371.5009160000 -2109885.6911169998
+529608.6168400000 -2096862.4664680001
+544990.8498620000 -2099366.9327469999
+561579.5325330000 -2107381.2248390000
+576509.3469370001 -2104876.7585600000
+596868.1847600000 -2102873.1855370002
+611948.8053700000 -2108883.9046060001
+597622.2157910001 -2119402.6629760000
+580430.3082950000 -2125413.3820449999
+599130.2778520000 -2126916.0618119999
+583144.8200050000 -2134930.3539040000
+568818.2304260000 -2148454.4718089998
+582843.2075930000 -2161477.6964580002
+566706.9435400000 -2162980.3762260000
+552983.5787850000 -2170994.6683180002
+543331.9815950000 -2188025.0390130002
+547554.5553660000 -2207058.9827310001
+538053.7643820000 -2193033.9715700001
+525084.4306570000 -2209062.5557539999
+516036.0582910000 -2221083.9938920001
+529910.2292520000 -2214572.3815669999
+541220.6947100000 -2225091.1399369999
+526140.0741000000 -2223087.5669140001
+526743.2989240000 -2239617.0443540001
+521615.8879170000 -2256647.4150490002
+506233.6548950000 -2255144.7352820002
+508194.1355740000 -2275681.3587670000
+489343.3598110000 -2268167.9599310001
+488740.1349870000 -2283695.6508590002
+475770.8012620000 -2293212.6227179999
+460539.3744460000 -2281692.0778359999
+449228.9089890000 -2296217.9822519999
+448022.4593400000 -2314250.1394590000
+440180.5366230000 -2298722.4485309999
+441085.3738600000 -2277184.0385340001
+426000.8914760000 -2286450.5637659999
+431125.9775380000 -2301477.3614380001
+426190.7094780000 -2317505.9456210001
+424672.1654600000 -2332532.7432940002
+421445.2594210000 -2313498.7995750001
+409296.9072740000 -2298472.0019029998
+411764.5413040000 -2318006.8388769999
+403222.7312010000 -2304983.6142279999
+411005.2692950000 -2289956.8165560002
+393542.0130840000 -2293463.0693460000
+378356.5729000000 -2295967.5356250000
+388416.9270220000 -2308489.8670180002
+405880.1832330000 -2317005.0523660001
+417838.7173770000 -2328525.5972480001
+402463.4591910000 -2342049.7151529999
+385000.2029800000 -2341047.9286409998
+375699.1208680000 -2327022.9174799998
+384240.9309710000 -2314500.5860870001
+368865.6727850000 -2321012.1984120002
+373421.3048400000 -2337541.6758510000
+363360.9507190000 -2353069.3667790000
+351402.4165740000 -2336539.8893400002
+340392.9724410000 -2324518.4512020000
+329573.3463100000 -2313999.6928309998
+335267.8863790000 -2329527.3837589999
+336216.9763910000 -2347058.6477100002
+337166.0664020000 -2362085.4453819999
+318374.0841750000 -2366593.4846839998
+303758.0979980000 -2362586.3386380002
+290314.2882280000 -2354697.2698599999
+292067.6911410000 -2339670.4721880001
+275702.5972900000 -2347684.7642799998
+277880.2580262116 -2321542.8592617917
+269420.4169677348 -2331176.2138948478
+260960.5759092579 -2323294.3782859840
+252500.7348507810 -2343436.8470641924
+254834.4841082919 -2357157.0794203631
+258918.5453089359 -2372336.9109633607
+266740.7601810000 -2359706.2024170002
+271754.1662252456 -2369125.7927523423
+266545.9376350000 -2379241.0393909998
+291483.2235030000 -2386253.5449720002
+275897.4198350000 -2396271.4100859999
+288755.7078610000 -2404786.5954339998
+276871.5325650000 -2415806.2470600000
+263818.4219930000 -2423820.5391520001
+259532.3259840000 -2445358.9491490000
+250570.4888750000 -2432836.6177559998
+248817.0859630000 -2452371.4547290001
+247258.5055960000 -2470403.6119360002
+229919.2990160000 -2474911.6512380000
+226022.8480990000 -2490439.3421660000
+239660.4263080000 -2499956.3140250002
+227776.2510110000 -2510975.9656509999
+220178.1717230000 -2523999.1902999999
+205761.3033310000 -2533015.2689029998
+210631.8669770000 -2560063.5047129998
+203228.6102350000 -2545036.7070410000
+194266.7731260000 -2558560.8249459998
+199624.3931360000 -2581101.0214539999
+185791.9923810000 -2568077.7968049999
+189493.6207520000 -2583104.5944770002
+186571.2825650000 -2601136.7516839998
+185207.5247440000 -2584106.3809890002
+169816.5436220000 -2595126.0326149999
+156568.6105040000 -2586610.8472679998
+134748.4853690000 -2581101.0214539999
+149749.8214000000 -2579598.3416869999
+136112.2431900000 -2592120.6730809999
+146437.8381200000 -2612657.2965660002
+130462.3893610000 -2620671.5886579999
+137281.1784650000 -2635197.4930739999
+125007.3580770000 -2621172.4819140001
+106888.8613130000 -2617666.2291230001
+91887.5252830000 -2609151.0437759999
+109031.9093180000 -2607648.3640089999
+92277.1703750000 -2603641.2179629998
+97537.3791130000 -2587111.7405229998
+88380.7194580000 -2573587.6226180000
+74743.1412490000 -2567076.0102940002
+61105.5630390000 -2577093.8754090001
+66950.2394150000 -2594124.2461040001
+57598.7572140000 -2581101.0214539999
+53117.8386600000 -2598131.3921500002
+41818.1310010000 -2586610.8472679998
+30810.6571600000 -2599133.1786610000
+44253.4128240000 -2608650.1505200001
+47662.8073760000 -2621047.2585999998
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Greenland.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Greenland.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Greenland.par	(revision 18231)
@@ -0,0 +1,82 @@
+%Name and hemisphere
+md.miscellaneous.name='SeaRISEgreenland';
+md.mesh.hemisphere='n';
+
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+gflux = ncread(ncdata,'bheatflx')';
+
+disp('   Interpolating surface and bedrock');
+md.geometry.base     = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+disp('   Interpolating velocities ');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vz = zeros(md.mesh.numberofvertices,1);
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15;
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0; %no friction applied on floating ice
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+
+disp('   Set other boundary conditions');
+md.mask.ice_levelset(md.mesh.vertexonboundary==1)=0;
+md.basalforcings.floatingice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.thermal.spctemperature     = [md.initialization.temperature;1]; %impose observed temperature on surface
+md.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+disp('   Single point constraint for continental model');
+%Set at least one vertex to velocity 0 so as to not get a singular problem (point on the wet peninsula)
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+location = 1.0e+06 *[.32011 -2.2039];
+[dist pos]=min(sqrt((md.mesh.x - location(1)).^2 + (md.mesh.y - location(2)).^2));
+md.stressbalance.spcvx(pos) = 0;
+md.stressbalance.spcvy(pos) = 0;
+md.stressbalance.spcvz(pos) = 0;
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_grounded.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_grounded.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_grounded.exp	(revision 18231)
@@ -0,0 +1,19 @@
+## Name:Jak_grouded
+## Icon:0
+# Points Count Value
+13 1.000000
+# X pos Y pos
+-414397.6663804040 -2243466.6708395295
+-421486.9037621063 -2215731.3059818177
+-342860.8164377716 -2178965.8223332223
+-275835.2993744044 -2209281.2211311869
+-226210.6377024883 -2262816.9253914217
+-228144.0660793162 -2295067.3496445753
+-333193.6745536321 -2328607.7908678548
+-379595.9555975018 -2325382.7484425395
+-422775.8560133249 -2285392.2223686292
+-427287.1888925899 -2265396.9593316740
+-411819.7618779668 -2254431.8150856020
+-413108.7141291854 -2243466.6708395295
+-414397.6663804040 -2243466.6708395295
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_outline.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_outline.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/Jak_outline.exp	(revision 18231)
@@ -0,0 +1,17 @@
+## Name:Jak
+## Icon:0
+# Points Count Value
+11 1.000000
+# X pos Y pos
+-421561.7247949215 -2216716.3488182197
+-386019.6416099078 -2203459.4896082953
+-351446.8879663036 -2185999.2360147359
+-289086.6874689616 -2214129.6445821370
+-255160.1535196303 -2282353.9688088228
+-340138.0433165266 -2317597.8140254519
+-383306.1449952667 -2302506.6581698526
+-416391.9672407377 -2279120.5885137189
+-448056.7322601135 -2246463.4475331730
+-429126.8716234095 -2231167.6696134652
+-421561.7247949215 -2216716.3488182197
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Greenland/runme.m	(revision 18231)
@@ -0,0 +1,272 @@
+clear all;
+steps=[1];
+
+%Location of SeaRISE dataset
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+
+if any(steps==1)
+	disp('   Step 1: Mesh creation');
+
+	%Generate initial uniform mesh (resolution = 20000 m)
+	md=triangle(model,'./DomainOutline.exp',20000);
+
+	% Get velocities (Note: You can use ncdisp('file') to see an ncdump)
+	x1   = ncread(ncdata,'x1');
+	y1   = ncread(ncdata,'y1');
+	velx = ncread(ncdata,'surfvelx');
+	vely = ncread(ncdata,'surfvely');
+	vx   = InterpFromGridToMesh(x1,y1,velx',md.mesh.x,md.mesh.y,0);
+	vy   = InterpFromGridToMesh(x1,y1,vely',md.mesh.x,md.mesh.y,0);
+	vel  = sqrt(vx.^2+vy.^2);
+
+	%Mesh Greenland
+	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.7,'field',vel,'err',8);
+	
+	%convert x,y coordinates (Polar stereo) to lat/lon
+	[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+
+	save ./Models/Greenland.Mesh_generation md;
+
+	plotmodel (md,'data','mesh');
+end
+
+if any(steps==2)
+	disp('   Step 2: Parameterization');
+	md = loadmodel('./Models/Greenland.Mesh_generation');
+
+	md = setmask(md,'','');
+	md = parameterize(md,'./Greenland.par');
+	md = setflowequation(md,'SSA','all');
+
+	save ./Models/Greenland.Parameterization md; 
+end
+
+if any(steps==3)
+	disp('   Step 3: Control method friction');
+	md = loadmodel('./Models/Greenland.Parameterization');
+
+	%Control general
+	md.inversion.iscontrol=1;
+	md.inversion.nsteps=30;
+	md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step=5*ones(md.inversion.nsteps,1);
+
+	%Cost functions
+	md.inversion.cost_functions=[101 103 501];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
+	md.inversion.cost_functions_coefficients(:,1)=350;
+	md.inversion.cost_functions_coefficients(:,2)=0.6;
+	md.inversion.cost_functions_coefficients(:,3)=2e-6;
+
+	%Controls
+	md.inversion.control_parameters={'FrictionCoefficient'};
+	md.inversion.gradient_scaling(1:md.inversion.nsteps)=50;
+	md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+
+	%Additional parameters
+	md.stressbalance.restol=0.01; md.stressbalance.reltol=0.1; 
+	md.stressbalance.abstol=NaN;
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md.toolkits=toolkits;
+	md.verbose=verbose('solution',true,'control',true);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	%Update model friction fields accordingly
+	md.friction.coefficient=md.results.StressbalanceSolution.FrictionCoefficient;
+
+	save ./Models/Greenland.Control_drag md; 
+end
+
+if any(steps==4)
+	disp('   Step 4: Transient run');
+	md = loadmodel('./Models/Greenland.Control_drag');
+
+	%Set surface mass balance
+	x1  = ncread(ncdata,'x1');
+	y1  = ncread(ncdata,'y1');
+	smb = ncread(ncdata,'smb');
+	smb = InterpFromGridToMesh(x1,y1,smb',md.mesh.x,md.mesh.y,0);
+	smb = smb*md.materials.rho_freshwater/md.materials.rho_ice;
+	smb = [smb smb smb-1.0];
+	md.surfaceforcings.mass_balance = [smb;1 10 20];
+
+	%Set transient options, run for 20 years, saving every timestep
+	md.timestepping.time_step=0.2;
+	md.timestepping.final_time=20;
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		                             'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true,'convergence',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.Transient md; 
+end
+
+if any(steps==5)
+	disp('   Step 5: Plotting'); 
+	md = loadmodel('./Models/Greenland.Transient');
+	%md = loadmodel('./Models/Greenland.HistoricTransient');
+
+	%Planview plots
+	plotmodel(md,'data',md.results.TransientSolution(end).Vel,'caxis',[1e-1 6000],...
+		'log', 10, 'title', 'Velocity (m/y)','gridded',1, ...
+		'data', md.results.TransientSolution(1).SurfaceforcingsMassBalance, ...
+		'title', 'Surface mass balance (m/y)', 'gridded',1,...
+		'data',md.results.TransientSolution(end).Thickness,...
+		'title','Thickness (m)', 'gridded',1, ...
+		'data',md.results.TransientSolution(end).Surface, ...
+		'title', 'Surface (m)', 'gridded',1);
+
+	%Line Plots
+	figure
+
+	%Plot surface mass balance
+	surfmb=[]; for i=1:100; surfmb=[surfmb ...
+		md.results.TransientSolution(i).SurfaceforcingsMassBalance]; end
+	subplot(3,1,1); plot([0.2:0.2:20],mean(surfmb)); title('Mean Surface mass balance');
+
+	%Plot velocity
+	vel=[]; for i=1:100; vel=[vel md.results.TransientSolution(i).Vel]; end
+	subplot(3,1,2); plot([0.2:0.2:20],mean(vel)); title('Mean Velocity');
+
+	%Plot Volume
+	volume=[]; for i=1:100; volume=[volume md.results.TransientSolution(i).IceVolume]; end
+	subplot(3,1,3); plot([0.2:0.2:20],volume); title('Ice Volume');
+	xlabel('years')
+end
+
+if any(steps==6)
+	disp('   Step 6: Historical Relaxation run');
+	md = loadmodel('./Models/Greenland.Control_drag');
+
+	ncbox='../Data/Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc';
+
+	%convert mesh x,y into the Box projection
+	[md.mesh.lat,md.mesh.long]  = xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+	[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+
+	%Set surface mass balance
+	lat  = ncread(ncbox,'lat');
+	lon  = ncread(ncbox,'lon');
+	smbbox = ncread(ncbox,'SMB');
+	[x1 y1]=ll2xy(lat,lon,+1,45,70);
+
+	%surface mass balance
+	smbmean = mean(mean(smbbox,3),4);
+	save -v7.3 smbbox smbbox x1 y1;
+	clear smbbox
+
+	%Interpolate and set surface mass balance
+	index = BamgTriangulate(x1(:),y1(:));
+	smb_mo = InterpFromMeshToMesh2d(index,x1(:),y1(:),smbmean(:),xi,yi);
+	smb = smb_mo*12/1000*md.materials.rho_freshwater/md.materials.rho_ice;
+	md.surfaceforcings.mass_balance = [smb;1 ];
+
+	%Set transient options, run for 20 years, saving every timestep
+	md.timestepping.time_step=0.2;
+	md.timestepping.final_time=200;
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.HistoricTransient md;
+end
+
+if any(steps==7)
+	disp('   Step 7: Box Transient run');
+	md = loadmodel('./Models/Greenland.HistoricTransient');
+
+	%load past transient results
+	md.geometry.base=md.results.TransientSolution(end).Base;
+	md.geometry.thickness=md.results.TransientSolution(end).Thickness;
+	md.geometry.surface=md.geometry.base+md.geometry.thickness;
+	md.initialization.vx=(md.results.TransientSolution(end).Vx);
+	md.initialization.vy=(md.results.TransientSolution(end).Vy);
+	md.results=[];
+
+	%convert mesh x,y into the Box projection
+	[md.mesh.lat,md.mesh.long]  = xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+	[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+
+	%Set surface mass balance
+	load smbbox
+	index = BamgTriangulate(x1(:),y1(:));
+
+	%Set years to run
+	years_of_simulation = 2003:2012;
+
+	%initialize surface mass balance matrix
+	smb = nan*ones(md.mesh.numberofvertices,length(years_of_simulation)*12);
+
+	%Interpolate and set surface mass balance
+	for year=years_of_simulation
+		for month=1:12
+			smb_mo = griddata(double(x1),double(y1),...
+				double(squeeze(smbbox(:,:,month,year-1839))),xi,yi,'nearest');
+			smb(:,(year-years_of_simulation(1))*12+month) = smb_mo;
+		end
+	end
+	md.surfaceforcings.mass_balance = ...
+		[smb*12/1000*md.materials.rho_freshwater/md.materials.rho_ice; ...
+		[1/24:1/12:length(years_of_simulation)]];
+
+	%Set transient options, monthly timestep, saving every month
+	md.timestepping.time_step=1/12;
+	md.timestepping.final_time=length(years_of_simulation);
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.BoxTransient md;
+end
+
+if any(steps==8)
+	disp('   Step 8: Plot Box Transient');
+	md = loadmodel('./Models/Greenland.BoxTransient');
+
+	%Set years run
+	years_of_simulation = 2003:2012;
+	t = [years_of_simulation(1):1/12:years_of_simulation(end)+11/12];
+
+	%Line Plots
+	figure
+
+	%Plot surface mass balance
+	surfmb=[]; for i=1:length(t); surfmb=[surfmb ...
+		md.results.TransientSolution(i).TotalSmb]; end
+	subplot(3,1,1); plot(t,surfmb); title('Total Surface mass balance');
+
+	%Plot velocity
+	vel=[]; for i=1:length(t); vel=[vel md.results.TransientSolution(i).Vel]; end
+	subplot(3,1,2); plot(t,max(vel)); title('Max Velocity');
+
+	%Plot Volume
+	volume=[]; for i=1:length(t); volume=[volume md.results.TransientSolution(i).IceVolume]; end
+	subplot(3,1,3); plot(t,volume); title('Ice Volume');
+	xlabel('years')
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipA.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipA.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipA.par	(revision 18231)
@@ -0,0 +1,52 @@
+%Parameterization for ISMIP A experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(0.5*pi/180)] #md.mesh
+%->
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180.);
+%base is [surface-1000+500*sin(x*2*pi/L).*sin(y*2*pi/L)]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+L=max(md.mesh.x)-min(md.mesh.x);
+md.geometry.base=md.geometry.surface-1000.0+500.0*sin(md.mesh.x*2.0*pi/L).*sin(md.mesh.y*2.0*pi/L);
+%thickness is the difference between surface and base #md.geometry
+%->
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%plot the geometry to check it out
+%->
+plotmodel(md,'data',md.geometry.thickness);
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%->
+md.friction.coefficient=200.0*ones(md.mesh.numberofvertices,1);
+%one friciton exponent (p,q) per element
+%->
+md.friction.p=ones(md.mesh.numberofelements,1);
+%->
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+md.materials.rheology_B=6.8067e7*ones(md.mesh.numberofvertices,1);
+%n has one value per element
+%->
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipF.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipF.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyIsmipF.par	(revision 18231)
@@ -0,0 +1,66 @@
+%Parameterization for ISMIP F experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(3.0*pi/180)] #md.mesh
+%->
+md.geometry.surface=md.mesh.x*tan(3.0*pi/180.0);
+%base is [surface-1000+100*exp(-((x-L/2).^2+(y-L/2).^2)/(10000.^2))]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+L=max(md.mesh.x)-min(md.mesh.x);
+%->
+md.geometry.base=md.geometry.surface-1000.0+100.0*exp(-((md.mesh.x-L/2.0).^2.0+(md.mesh.y-L/2.0).^2.0)/(10000.^2.0));
+%thickness is the difference between surface and base #md.geometry
+%->
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%plot the geometry to check it out
+%->
+plotmodel(md,'data',md.geometry.thickness);
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%conversion form year to seconds with #md.constants.yts
+%->
+md.friction.coefficient=sqrt(md.constants.yts/(1000*2.140373*10^-7))*ones(md.mesh.numberofvertices,1);
+%one friciton exponent (p,q) per element
+%->
+md.friction.p=ones(md.mesh.numberofelements,1);
+%->
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+md.materials.rheology_B=(1/(2.140373*10^-7/md.constants.yts))*ones(md.mesh.numberofvertices,1);
+%n has one value per element
+%->
+md.materials.rheology_n=1*ones(md.mesh.numberofelements,1);
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+md=SetIceSheetBC(md);
+
+disp('   Initializing velocity and pressure');
+
+%initialize the velocity and pressurefields of #md.initialization
+%->
+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);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyRunme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyRunme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/CheatyRunme.m	(revision 18231)
@@ -0,0 +1,229 @@
+%wich steps to perform steps are from 1 to 8 
+%step 7 is specific to ISMIPA
+%step 8 is specific to ISMIPF
+
+steps=[1:7];
+
+% parameter file to be used, choose between CheatyIsmipA.par or CheatyIsmipF.par
+ParamFile='CheatyIsmipF.par'
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1)
+
+	%initialize md as a new model #help model
+	%->
+	md=model();
+	% generate a squaremesh #help squaremesh
+	% Side is 80 km long with 20 points
+	%->
+	if(ParamFile=='CheatyIsmipA.par'),
+		md=squaremesh(md,80000,80000,20,20);
+	elseif(ParamFile=='CheatyIsmipF.par'),
+		md=squaremesh(md,100000,100000,30,30);
+  end
+	% plot the given mesh #plotdoc
+	%->
+	plotmodel(md,'data','mesh')
+	% save the given model
+	%->
+	save ./Models/ISMIP.Mesh_generation md;
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Mesh_generation');
+	% set the mask #help setmask
+	% all MISMIP nodes are grounded
+	%->
+	md=setmask(md,'','');
+	% plot the given mask #md.mask to locate the field
+	%->
+	plotmodel(md,'data',md.mask.groundedice_levelset);
+	% save the given model
+	%->
+	save ./Models/ISMIP.SetMask md;
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.SetMask');
+	% parametrize the model # help parameterize
+	% you will need to fil-up the parameter file defined by the
+	% ParamFile variable
+	%->
+	md=parameterize(md,ParamFile);
+	% save the given model
+	%->
+	save ./Models/ISMIP.Parameterization md;
+end
+% }}}
+
+% {{{ Extrusion #4
+if any(steps==4)
+	
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Parameterization');
+	% vertically extrude the preceding mesh #help extrude
+	% only 5 layers exponent 1
+	%->
+	md=extrude(md,9,1);
+	% plot the 3D geometry #plotdoc
+	%->
+	plotmodel(md,'data',md.geometry.base)
+	% save the given model
+	%->
+	save ./Models/ISMIP.Extrusion md;
+end
+% }}}
+
+% {{{ Set the flow computing method #5
+if any(steps==5)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Extrusion');
+	% set the approximation for the flow computation #help setflowequation
+	% We will be using the Higher Order Model (HO)
+	%->
+	md=setflowequation(md,'HO','all');
+	% save the given model
+	%->
+	save ./Models/ISMIP.SetFlow md;
+end
+% }}}
+
+% {{{ Set Boundary Conditions #6
+if any(steps==6)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.SetFlow');
+	% dirichlet boundary condition are known as SPCs
+	% ice frozen to the base, no velocity	#md.stressbalance
+	% SPCs are initialized at NaN one value per vertex
+	%->
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	%->
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	%->
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	% extract the nodenumbers at the base #md.mesh.vertexonbase
+	%->
+	basalnodes=find(md.mesh.vertexonbase);
+	% set the sliding to zero on the bed
+	%->
+	md.stressbalance.spcvx(basalnodes)=0.0;
+	%->
+	md.stressbalance.spcvy(basalnodes)=0.0;
+	% periodic boundaries have to be fixed on the sides
+	% create tabs with the side of the domain
+	% for x
+	% create maxX #help find
+	%->
+	maxX=find(md.mesh.x==max(md.mesh.x));
+	% create minX
+	%->
+	minX=find(md.mesh.x==min(md.mesh.x));
+	% for y, max X and minX should be excluded
+	% create maxY
+	%->
+	maxY=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=max(md.mesh.x) & md.mesh.x~=min(md.mesh.x));
+	% create minY
+	%->
+	minY=find(md.mesh.y==min(md.mesh.y) & md.mesh.x~=max(md.mesh.x) & md.mesh.x~=min(md.mesh.x));
+	% set the node that should be paired together
+	% #md.stressbalance.vertex_pairing
+	%->
+	md.stressbalance.vertex_pairing=[minX,maxX;minY,maxY];
+	if (ParamFile=='CheatyIsmipF.par')
+		% if we are dealing with IsmipF the solution is in
+		% masstransport
+		md.masstransport.vertex_pairing=md.stressbalance.vertex_pairing;
+  end
+	% save the given model
+	%->
+	save ./Models/ISMIP.BoundaryCondition md;
+end
+% }}}
+
+% {{{ Solving #7
+if any(steps==7)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.BoundaryCondition');
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+	md.cluster=generic('name',oshostname(),'np',2);
+	% Set which control message you want to see #help verbose
+	%->
+	md.verbose=verbose('convergence',true);
+	% Solve #help solve
+	% we are solving a StressBalanc
+	%->
+	md=solve(md,StressbalanceSolutionEnum());
+	% save the given model
+	%->
+	save ./Models/ISMIP.StressBalance md;
+	% plot the surface velocities #plotdoc
+	%->
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel)
+end
+% }}}
+
+% {{{ Solving #8
+if any(steps==8)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.BoundaryCondition');
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+	md.cluster=generic('name',oshostname(),'np',2);
+	% Set which control message you want to see #help verbose
+	%->
+	md.verbose=verbose('convergence',true);
+	% set the transient model to ignore the thermal model
+	% #md.transient 
+	%->
+	md.transient.isthermal=0;
+	% define the timestepping scheme
+	% everything here should be provided in years #md.timestepping
+	% give the length of the time_step (4 years)
+	%->
+	md.timestepping.time_step=4;
+	% give final_time (20*4 years time_steps)
+	%->
+	md.timestepping.final_time=4*20;
+	% Solve #help solve
+	% we are solving a TransientSolution
+	%->
+	md=solve(md,TransientSolutionEnum);
+	% save the given model
+	%->
+	save ./Models/ISMIP.Transient md;
+	% plot the surface velocities #plotdoc
+	%->
+	plotmodel(md,'data',md.results.TransientSolution(20).Vel)
+end
+% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipA.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipA.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipA.par	(revision 18231)
@@ -0,0 +1,52 @@
+%Parameterization for ISMIP A experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(0.5*pi/180)] #md.mesh
+%->
+
+%base is [surface-1000+500*sin(x*2*pi/L).*sin(y*2*pi/L)]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+
+%->
+
+%thickness is the difference between surface and base #md.geometry
+%->
+
+%plot the geometry to check it out
+%->
+
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%->
+
+%one friciton exponent (p,q) per element
+%->
+
+%->
+
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+
+%n has one value per element
+%->
+
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipF.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipF.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/IsmipF.par	(revision 18231)
@@ -0,0 +1,64 @@
+%Parameterization for ISMIP F experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(3.0*pi/180)] #md.mesh
+%->
+
+%base is [surface-1000+100*exp(-((x-L/2).^2+(y-L/2).^2)/(0.1*L^2))]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+
+%->
+
+%thickness is the difference between surface and base #md.geometry
+%->
+
+%plot the geometry to check it out
+%->
+
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%conversion form year to seconds with #md.constants.yts
+%->
+
+%one friciton exponent (p,q) per element
+%->
+
+%->
+
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+
+%n has one value per element
+%->
+
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+
+disp('   Initializing velocity and pressure');
+
+%initialize the velocity and pressurefields of #md.initialization
+%->
+
+%->
+
+%->
+
+%->
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/ISMIP/runme.m	(revision 18231)
@@ -0,0 +1,224 @@
+%wich steps to perform steps are from 1 to 8 
+%step 7 is specific to ISMIPA
+%step 8 is specific to ISMIPF
+
+steps=[1];
+
+% parameter file to be used, choose between IsmipA.par or IsmipF.par
+ParamFile='IsmipA.par'
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1) 
+
+	%initialize md as a new model #help model
+	%->
+
+	% generate a squaremesh #help squaremesh
+	% Side is 80 km long with 20 points
+	%->
+
+	% plot the given mesh #plotdoc
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2) 
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% set the mask #help setmask
+	% all MISMIP nodes are grounded
+	%->
+
+	% plot the given mask #md.mask to locate the field
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3) 
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% parametrize the model # help parameterize
+	% you will need to fil-up the parameter file (given by the
+  % ParamFile variable)
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Extrusion #4
+if any(steps==4)
+	
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% vertically extrude the preceding mesh #help extrude
+	% only 5 layers exponent 1
+	%->
+
+	% plot the 3D geometry #plotdoc
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Set the flow computing method #5
+
+if any(steps==5)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% set the approximation for the flow computation #help setflowequation
+	% We will be using the Higher Order Model (HO)
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Set Boundary Conditions #6
+if any(steps==6)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% dirichlet boundary condition are known as SPCs
+	% ice frozen to the base, no velocity	#md.stressbalance
+	% SPCs are initialized at NaN one value per vertex
+	%->
+
+	%->
+
+	%->
+
+	% extract the nodenumbers at the base #md.mesh.vertexonbase
+	%->
+
+  % set the sliding to zero on the bed (Vx and Vy)
+	%->
+
+	%->
+
+	% periodic boundaries have to be fixed on the sides
+	% create tabs with the side of the domain
+	% for x
+	% create maxX #help find
+	%->
+
+	% create minX
+	%->
+
+	% for y, max X and minX should be excluded
+	% create maxY
+	%->
+
+	% create minY
+	%->
+
+	% set the node that should be paired together
+	% #md.stressbalance.vertex_pairing
+	%->
+
+	if (ParamFile=='IsmipF.par')
+		% if we are dealing with IsmipF the solution is in masstransport
+		md.masstransport.vertex_pairing=md.stressbalance.vertex_pairing;
+  end
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Solving #7
+if any(steps==7)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+
+	% Set which control message you want to see #help verbose
+	%->
+
+	% Solve #help solve
+	% we are solving a StressBalanc
+	%->
+
+	% save the given model
+	%->
+
+	% plot the surface velocities #plotdoc
+	%->
+end
+% }}}
+
+% {{{ Solving #8
+if any(steps==8)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+
+	% Set which control message you want to see #help verbose
+	%->
+
+	% set the transient model to ignore the thermal model
+	% #md.transient 
+	%->
+
+	% define the timestepping scheme
+	% everything here should be provided in years #md.timestepping
+	% give the length of the time_step (4 years)
+	%->
+
+	% give final_time (20*4 years time_steps)
+	%->
+
+	% Solve #help solve
+	% we are solving a TransientSolution
+	%->
+
+	% save the given model
+	%->
+
+	% plot the surface velocities #plotdoc
+	%->
+
+end
+% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Contour.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Contour.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Contour.exp	(revision 18231)
@@ -0,0 +1,11 @@
+## Name:Contour
+## Icon:0
+# Points Count Value
+5 1.000000
+# X pos Y pos
+260815.7808871837 745919.4159004869
+712422.3484428506 757574.3645213632
+640499.8210173184 195805.8409951325
+342774.0098139530 279721.4710654409
+260815.7808871837 745919.4159004869
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/EISMINT.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/EISMINT.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/EISMINT.par	(revision 18231)
@@ -0,0 +1,53 @@
+disp('      creating thickness');
+hmin=0.01;
+hmax=2756.7;
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+radiusmax=max(radius);
+radius(find(radius>(1.-10^-9)*radiusmax))=radiusmax;    %eliminate roundoff issues in next statement
+md.geometry.thickness=hmin*ones(size(md.mesh.x,1),1)+hmax*(4.*((1./2.)^(4./3.)*ones(size(md.mesh.x,1),1)-((radius)./(2.*radiusmax)).^(4./3.))).^(3./8.);
+md.geometry.base=0.*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating temperatures');
+tmin=238.15; %K
+st=1.67*10^-2/1000.; %k/m
+md.initialization.temperature=tmin+st*radius;
+md.basalforcings.geothermalflux=4.2*10^-2*ones(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.81*10^7*ones(md.mesh.numberofvertices,1); %to have the same B as the analytical solution 
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+smb_max=0.5; %m/yr
+sb=10^-2/1000.; %m/yr/m
+rel=450.*1000.; %m
+md.surfaceforcings.mass_balance=min(smb_max,sb*(rel-radius));
+
+disp('      creating velocities');
+constant=0.3;
+md.inversion.vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+md.inversion.vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+md.inversion.vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+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);
+
+%Deal with boundary conditions:
+disp('      boundary conditions for stressbalance model:');
+md=SetMarineIceSheetBC(md,'./RoundFront.exp');
+
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+pos=find(radius==min(radius));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/RoundFront.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/RoundFront.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/RoundFront.exp	(revision 18231)
@@ -0,0 +1,47 @@
+## Name:
+## Icon:0
+# Points Count Value
+41 1
+# X pos Y pos
+1000000.000000 0.000000
+987688.340595 156434.465040
+951056.516295 309016.994375
+891006.524188 453990.499740
+809016.994375 587785.252292
+707106.781187 707106.781187
+587785.252292 809016.994375
+453990.499740 891006.524188
+309016.994375 951056.516295
+156434.465040 987688.340595
+0.000000 1000000.000000
+-156434.465040 987688.340595
+-309016.994375 951056.516295
+-453990.499740 891006.524188
+-587785.252292 809016.994375
+-707106.781187 707106.781187
+-809016.994375 587785.252292
+-891006.524188 453990.499740
+-951056.516295 309016.994375
+-987688.340595 156434.465040
+-1000000.000000 0.000000
+-987688.340595 -156434.465040
+-951056.516295 -309016.994375
+-891006.524188 -453990.499740
+-809016.994375 -587785.252292
+-707106.781187 -707106.781187
+-587785.252292 -809016.994375
+-453990.499740 -891006.524188
+-309016.994375 -951056.516295
+-156434.465040 -987688.340595
+-0.000000 -1000000.000000
+156434.465040 -987688.340595
+309016.994375 -951056.516295
+453990.499740 -891006.524188
+587785.252292 -809016.994375
+707106.781187 -707106.781187
+809016.994375 -587785.252292
+891006.524188 -453990.499740
+951056.516295 -309016.994375
+987688.340595 -156434.465040
+1000000.000000 0.000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Square.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Square.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/Square.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareFront.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareFront.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareFront.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 900000
+-1000 1100000
+1100000 1100000
+1100000 900000
+-1000 900000
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareShelf.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareShelf.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/SquareShelf.par	(revision 18231)
@@ -0,0 +1,55 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity and pressure
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.stressbalance.restol=0.10;
+md.steadystate.reltol=0.02;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'./SquareFront.exp');
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/eismint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/eismint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/eismint.m	(revision 18231)
@@ -0,0 +1,51 @@
+md=model();
+
+%Create mesh with roundmesh
+md=roundmesh(md,750000,30000);
+
+%Set mask
+md=setmask(md,'','');
+
+%Parameterize model
+md=parameterize(md,'EISMINT.par');
+
+%We extrude the model to have a 3d model
+md=extrude(md,10,1);
+
+%Set ice flow approximation
+md=setflowequation(md,'SIA','all');
+
+%Create boundary conditions: zero velocity on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+md.stressbalance.spcvz(pos)=0;
+
+%Go Solve
+md.cluster=generic('np',2);
+md.verbose.convergence=1;
+md=solve(md,StressbalanceSolutionEnum());
+vel=DepthAverage(md,sqrt(md.results.StressbalanceSolution.Vx.^2+md.results.StressbalanceSolution.Vy.^2));
+
+%Calculate analytical velocity
+constant=0.3;
+vx_obs=constant/2*md.mesh.x.*(md.geometry.thickness).^-1;
+vy_obs=constant/2*md.mesh.y.*(md.geometry.thickness).^-1;
+vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+vel_obs=project2d(md,vel_obs,1);
+
+plotmodel(md,...
+	'data',vel    ,'view',2,'caxis',[0 200],'title','Modelled velocity',...
+	'data',vel_obs,'view',2,'caxis',[0 200],'title','Analytical velocity',...
+	'data',abs(vel-vel_obs)./(vel_obs+eps)*100,'caxis',[0 30],'view',2,'title','Relative misfit (%)');
+
+subplot(2,2,4)
+hold on;
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel,'r.');
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+title('Analytical vs calculated velocity');
+xlabel('distance to the center of the icesheet [m]');
+ylabel('velocity (m/yr)');
+legend('calculated velocity','exact velocity');
+axis([0 750000 0 200]);
+hold off;
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/IceflowModels/runme.m	(revision 18231)
@@ -0,0 +1,8 @@
+md=triangle(model(),'Square.exp',80000.);
+md=setmask(md,'all','');
+md=parameterize(md,'SquareShelf.par');
+md=extrude(md,3,1);
+%Set flow equation
+md=setflowequation(md,'HO','Contour.exp','fill','SSA','coupling','tiling');
+%Solve
+md=solve(md,StressbalanceSolutionEnum);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/DomainOutline.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/DomainOutline.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/DomainOutline.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count  Value
+5 1.000000
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Front.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Front.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Front.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 900000
+-1000 1100000
+1100000 1100000
+1100000 900000
+-1000 900000
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Square.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Square.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/Square.par	(revision 18231)
@@ -0,0 +1,24 @@
+%Start defining model parameters here
+
+disp('      creating thickness');
+hmin = 300;
+hmax = 1000;
+ymin = min(md.mesh.y);
+ymax = max(md.mesh.y);
+md.geometry.thickness = hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+md.geometry.base      = -md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface   = md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p = ones(md.mesh.numberofelements,1);
+md.friction.q = ones(md.mesh.numberofelements,1);
+
+disp('      creating flow law paramter');
+md.materials.rheology_B=1.8*10^8*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B(find(md.mesh.x<md.mesh.y))=1.4*10^8;
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('      creating boundary conditions');
+md=SetIceShelfBC(md,'Front.exp');
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Inversion/runme.m	(revision 18231)
@@ -0,0 +1,61 @@
+step=3;
+if step==1
+	%Generate observation
+	md = model;
+	md = triangle(md,'DomainOutline.exp',100000);
+    
+	md = setmask(md,'','');
+    
+	md = parameterize(md,'Square.par');
+	md = setflowequation(md,'SSA','all');
+	md.cluster = generic('np',2);
+    
+    md.geometry.surface=md.geometry.surface+100;
+    md.geometry.base = md.geometry.base+100;
+    md.materials.rheology_B(:)=1.8*10^8;
+    md.friction.coefficient(:)=50;
+    md.friction.coefficient(find(md.mesh.x>400000 & md.mesh.x<600000))=10;
+    
+	md = solve(md,StressbalanceSolutionEnum);
+	plotmodel(md,'data',md.friction.coefficient,'caxis',[0 100],'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+	save model1 md
+end
+if step==2
+	%Modify rheology, now constant
+	loadmodel('model1.mat');
+	md.friction.coefficient(:)=50;
+
+	%results of previous run are taken as observations
+	md.inversion=m1qn3inversion();
+	md.inversion.vx_obs  = md.results.StressbalanceSolution.Vx;
+	md.inversion.vy_obs  = md.results.StressbalanceSolution.Vy;
+	md.inversion.vel_obs = md.results.StressbalanceSolution.Vel;
+
+	md = solve(md,StressbalanceSolutionEnum);
+	plotmodel(md,'data',md.friction.coefficient,'caxis',[0 100],'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+	save model2 md
+end
+if step==3
+	%invert for ice rigidity
+	loadmodel('model2.mat');
+
+	%Set up inversion parameters
+	maxsteps = 20;
+	md.inversion.iscontrol = 1;
+	md.inversion.control_parameters = {'FrictionCoefficient'};
+	md.inversion.maxsteps = maxsteps;
+	md.inversion.dxmin=10^-6;
+	md.inversion.cost_functions = [103 501];
+	md.inversion.cost_functions_coefficients = ones(md.mesh.numberofvertices,2);
+	md.inversion.cost_functions_coefficients(:,2)=0;
+	md.inversion.min_parameters    = 10^-5*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters    = 100*ones(md.mesh.numberofvertices,1);
+
+	%Go solve!
+	md.verbose=verbose(0);
+	md=solve(md,StressbalanceSolutionEnum);
+	plotmodel(md,'data',md.results.StressbalanceSolution.FrictionCoefficient,'caxis',[0 100],'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Domain.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Domain.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Domain.exp	(revision 18231)
@@ -0,0 +1,34 @@
+## Name:JksOutline
+## Icon:0
+# Points Count Value
+28 1.000000
+# X pos Y pos
+-442320.3882147236 -2277080.6549030584
+-415649.3149820761 -2315476.9356749961
+-356259.6577274340 -2351834.4758754564
+-309585.2795717255 -2384114.5349311619
+-279812.9187561168 -2353193.6362587260
+-274850.8586214480 -2287953.9379578433
+-294854.1635456266 -2263149.2609987380
+-309585.2795753506 -2232228.3623235333
+-348041.2456311518 -2191113.7607873622
+-376728.1557929466 -2197909.5626934194
+-391614.3362011510 -2203685.9943137392
+-417355.0231571503 -2206404.3150757281
+-420122.3381705935 -2211830.0535394503
+-421889.2049176788 -2218344.8015625700
+-420705.1891998384 -2226200.5387845989
+-425774.4833068820 -2230306.5097973733
+-429242.2244052034 -2235353.9400299159
+-427025.7933000360 -2240741.0910965428
+-431045.5636035603 -2255158.9014255330
+-424708.0734753361 -2261343.7626088522
+-423137.8820362946 -2268466.9593191240
+-428054.2739333302 -2272589.0010017036
+-432362.3262468725 -2272393.9161962867
+-435068.8255516959 -2273140.2906106352
+-437641.3726878429 -2272612.1952726739
+-439529.7800752302 -2272929.1351353633
+-442475.4525940326 -2275381.7044264446
+-442320.3882147236 -2277080.6549030584
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Front.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Front.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Front.exp	(revision 18231)
@@ -0,0 +1,15 @@
+## Name:Front
+## Icon:0
+# Points Count Value
+9 1.000000
+# X pos Y pos
+-443691.7204476296 -2241744.0087129781
+-444020.9148401438 -2244124.0631026439
+-443856.3176438867 -2245205.9060070375
+-441551.9568962874 -2244773.1688452801
+-440399.7765224879 -2243474.9573600078
+-439905.9849337166 -2240662.1658085845
+-441387.3597000304 -2238065.7428380400
+-443856.3176438867 -2237633.0056762826
+-443691.7204476296 -2241744.0087129781
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Jks.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Jks.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/Jks.par	(revision 18231)
@@ -0,0 +1,61 @@
+
+%Name and hemisphere
+md.mesh.hemisphere='n';
+md.miscellaneous.name='Jakobshavn';
+
+%Load SeaRISE dataset
+disp('   Loading SeaRISE data from NetCDF');
+ncdata = '../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+thk   = ncread(ncdata,'thk')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+
+disp('   Interpolating thicknesses');
+md.geometry.thickness=InterpFromGridToMesh(x1,y1,thk,md.mesh.x,md.mesh.y,0);
+pos0=find(md.geometry.thickness<=10);
+md.geometry.thickness(pos0)=10;
+
+disp('   Interpolating bedrock topography');
+md.geometry.base = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing surface elevation');
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+disp('   Interpolating velocities');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15; %convert to Kelvin
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+%Reduce viscosity along the shear margins
+weakb=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,'WeakB.exp','node',2);
+pos=find(weakb);md.materials.rheology_B(pos)=.3*md.materials.rheology_B(pos);
+
+disp('   Set other boundary conditions');
+md=SetMarineIceSheetBC(md,'./Front.exp');
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/WeakB.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/WeakB.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/WeakB.exp	(revision 18231)
@@ -0,0 +1,60 @@
+## Name:WeakB
+## Icon:0
+# Points Count Value
+24 1.000000
+# X pos Y pos
+-441022.7144520371 -2238435.7116546673
+-441639.8422268176 -2239053.0142011684
+-439171.3311276956 -2240699.1543251718
+-437319.9478033541 -2241727.9919026736
+-435879.9829955329 -2241933.7594181742
+-432382.9256051101 -2242756.8294801759
+-430942.9607972889 -2242962.5969956759
+-429708.7052477279 -2243991.4345731782
+-428680.1589564271 -2245020.2721506800
+-427651.6126651262 -2246049.1097281822
+-425800.2293407847 -2247077.9473056840
+-424565.9737912237 -2247695.2498521851
+-419341.0001274022 -2251604.8326466926
+-416049.6519952395 -2253868.2753171972
+-416049.6519952395 -2252222.1351931938
+-418312.4538361013 -2249341.3899761885
+-423331.7182416627 -2245843.3422126817
+-425594.5200825246 -2245226.0396661805
+-426623.0663738254 -2244402.9696041788
+-427445.9034068661 -2243991.4345731782
+-428885.8682146872 -2242756.8294801759
+-431148.6700555491 -2241522.2243871735
+-436497.1107703134 -2239670.3167476696
+-441022.7144520371 -2238435.7116546673
+
+## Name:WeakB
+## Icon:0
+# Points Count Value
+24 1.000000
+# X pos Y pos
+-442668.3885181184 -2245226.0396661805
+-440405.5866772566 -2245843.3422126817
+-438759.9126111752 -2246049.1097281822
+-437525.6570616142 -2246460.6447591828
+-435879.9829955329 -2246872.1797901839
+-434028.5996711914 -2248106.7848831862
+-431354.3793138092 -2249547.1574916886
+-430120.1237642482 -2249341.3899761885
+-429297.2867312076 -2250164.4600381902
+-427857.3219233864 -2249958.6925226897
+-426623.0663738254 -2250164.4600381902
+-424771.6830494839 -2250575.9950691909
+-423537.4274999229 -2250781.7625846914
+-422714.5904668822 -2251399.0651311926
+-415226.8149621988 -2259629.7657512082
+-419135.2908691420 -2259218.2307202076
+-422838.0575178250 -2255720.1829567007
+-424977.3923077441 -2252016.3676776937
+-426623.0663738254 -2251810.6001621932
+-428268.7404399067 -2251399.0651311926
+-429708.7052477279 -2251399.0651311926
+-431560.0885720694 -2251399.0651311926
+-443902.6440676794 -2246460.6447591828
+-442668.3885181184 -2245226.0396661805
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Jakobshavn/runme.m	(revision 18231)
@@ -0,0 +1,90 @@
+steps=[4];
+
+if any(steps==1)
+	disp('	Step 1: Mesh creation'); 
+	md=triangle(model,'Domain.exp',2000);
+
+	%Get observed velocity field on mesh nodes
+	ncdata='../Data/Greenland_5km_dev1.2.nc';
+	if ~exist(ncdata,'file'), 
+		error('File Greenland_5km_dev1.2.nc not downloaded in Data Directory.  Please cd ../Data and run the download script.');
+	end
+	x1   = ncread(ncdata,'x1');
+	y1   = ncread(ncdata,'y1');
+	velx = ncread(ncdata,'surfvelx');
+	vely = ncread(ncdata,'surfvely');
+	vx   = InterpFromGridToMesh(x1,y1,velx',md.mesh.x,md.mesh.y,0);
+	vy   = InterpFromGridToMesh(x1,y1,vely',md.mesh.x,md.mesh.y,0);
+	vel  = sqrt(vx.^2+vy.^2);
+
+	%refine mesh using surface velocities as metric
+	md=bamg(md,'hmin',1200,'hmax',15000,'field',vel,'err',5);
+	[md.mesh.lat,md.mesh.long]  = xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+	
+	save JksMesh.mdl md
+end 
+if any(steps==2)
+	disp('	Step 2: Parameterization');
+	md=loadmodel('JksMesh.mdl');
+	
+	md=setmask(md,'','');
+	md=parameterize(md,'Jks.par'); 
+
+	%zones of shear margin softening
+	weakb=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,'WeakB.exp','node',2);
+	pos=find(weakb);
+	md.materials.rheology_B(pos)=.3*md.materials.rheology_B(pos);
+
+	save JksPar.mdl md
+end 
+if any(steps==3)
+	disp('	Step 3: Control method friction');
+	md=loadmodel('JksPar.mdl');
+
+	md=setflowequation(md,'SSA','all');
+
+	%Control general
+	md.inversion.iscontrol=1;
+	md.inversion.nsteps=20;
+	md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step=5*ones(md.inversion.nsteps,1);
+	md.verbose=verbose('solution',true,'control',true);
+
+	%Cost functions
+	md.inversion.cost_functions=[101 103];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2);
+	md.inversion.cost_functions_coefficients(:,1)=40;
+	md.inversion.cost_functions_coefficients(:,2)=1;
+
+	%Controls
+	md.inversion.control_parameters={'FrictionCoefficient'};
+	md.inversion.gradient_scaling(1:md.inversion.nsteps)=30;
+	md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+
+	%Additional parameters
+	md.stressbalance.restol=0.01;
+	md.stressbalance.reltol=0.1;
+	md.stressbalance.abstol=NaN;
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',4);
+	md=solve(md,StressbalanceSolutionEnum);
+	
+	save JksControl.mdl md
+end 
+if any(steps==4)
+	disp('	Plotting')
+	md=loadmodel('JksControl.mdl');
+
+	plotmodel(md,'unit#all','km','axis#all','equal',...
+		'FontSize#all',12,...
+		'data',md.inversion.vel_obs,'title','Observed velocity',...
+		'data',md.results.StressbalanceSolution.Vel,'title','Modeled Velocity',...
+		'colorbar#1','off','colorbar#2','on','colorbartitle#2','[m/yr]',...
+		'caxis#1-2',[0,7000],...
+		'data',md.geometry.base,'title','Base elevation',...
+		'data',md.results.StressbalanceSolution.FrictionCoefficient,...
+		'title','Friction Coefficient',...
+		'colorbar#3','on','colorbartitle#3','[m]','colorbar#4','on');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/Square.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/Square.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/Square.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:Square
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1 0
+1 1
+0 1
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/circles.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/circles.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/circles.m	(revision 18231)
@@ -0,0 +1,7 @@
+function vel=circles(x,y),
+
+u=4*x-2; v=4*y-2;
+
+vel=tanh(30*(u.^2+v.^2-0.25)) ...
+	+tanh(30*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30*((u+0.75).^2+(v+0.75).^2-0.25)) ;
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/shock.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/shock.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Mesh/shock.m	(revision 18231)
@@ -0,0 +1,3 @@
+function vel=shock(x,y),
+
+vel=exp(-(sqrt((x+0.1).^2+(y+0.1).^2)-0.75).^2*10^6)+((x+0.1).^2+(y+0.1).^2)/2;
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/CheatSheet.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/CheatSheet.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/CheatSheet.m	(revision 18231)
@@ -0,0 +1,18 @@
+if perform(org,'ModelHO')
+  % Load Model
+  mdHO = loadmodel('./Models/PIG.Control_drag');
+  md.inversion.iscontrol=0;
+
+  disp('   Extruding mesh')
+  number_of_layers=3;
+  md=extrude(md,number_of_layers,0.9);
+
+  disp('   Using HO Ice Flow Model')
+  md=setflowequation(md, 'HO', 'all');
+
+  % Solve
+  md=solve(md,StressbalanceSolutionEnum);
+
+  % Save Model
+  save ./Models/PIG.ModelHO md;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.bkp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.bkp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.bkp	(revision 18231)
@@ -0,0 +1,120 @@
+## Name:
+## Icon:0
+# Points Count Value
+114 25000.000000
+# X pos Y pos
+-1712113.0179281300 -349656.0205056490
+-1711509.1917759699 -349354.1074295690
+-1709240.6586108401 -349354.1074295690
+-1707080.1508345299 -348922.0058743060
+-1705459.7700022999 -347193.5996532570
+-1703083.2114483600 -345249.1426545770
+-1701138.7544496800 -344168.8887664210
+-1698438.1197292900 -343952.8379887900
+-1698006.0181740201 -341900.3556012940
+-1693793.0280102200 -340279.9747690600
+-1691092.3932898301 -339631.8224361670
+-1688391.7585694401 -339415.7716585360
+-1686447.3015707601 -340063.9239914290
+-1683530.6160727399 -341036.1524907690
+-1682558.3875734000 -343304.6856558960
+-1682134.7209454600 -344182.1487658350
+-1682126.2860181299 -345681.2442098390
+-1681072.0444963200 -345932.4393879640
+-1680634.4718407800 -346682.5639403050
+-1680571.9614614199 -348557.8753211580
+-1677446.4424933300 -348370.3441830730
+-1675508.6207331200 -349495.5310115840
+-1676616.9911885399 -353567.0975933760
+-1672991.8601872099 -353799.6175753630
+-1668839.1631938200 -353999.1991486380
+-1667132.2298986400 -355121.4651541420
+-1666069.5534494901 -357496.8595698890
+-1662944.0344814099 -358309.4945015920
+-1660756.1712037399 -358747.0671571240
+-1657922.9836098100 -361682.8074238540
+-1656579.2228470000 -364003.8487410000
+-1653004.8841628900 -364748.0635758530
+-1653442.4568184200 -361622.5446077650
+-1651129.5727820301 -355684.0585683980
+-1648929.2928810001 -350845.9692010000
+-1646260.7698359799 -347802.2804785470
+-1644571.8968503401 -341785.6704672340
+-1643503.3064999001 -340869.0986596620
+-1643190.7546030900 -336680.9032424240
+-1642690.6715682000 -335243.1645171040
+-1641913.0916588283 -332341.0814454452
+-1640683.9739821283 -330436.6112348017
+-1637816.0327364956 -328532.1410241582
+-1635241.2508976001 -328652.8685499910
+-1631765.4107996500 -327017.1790921330
+-1625934.5618617306 -322342.6128395668
+-1620608.3852626982 -320438.1426289233
+-1616101.6204481323 -320438.1426289233
+-1611594.8556335662 -320914.2601815842
+-1607907.5026034669 -321866.4952869060
+-1602991.0318966676 -324723.2006028712
+-1599713.3847588014 -327579.9059188365
+-1593977.5022675355 -328532.1410241582
+-1590699.8551296694 -334721.6692087495
+-1589259.8391499999 -338300.0840570000
+-1588627.0898328500 -343572.9950327750
+-1588056.6000060199 -345432.3563530700
+-1586993.9235568701 -347432.6884926460
+-1589259.8391499999 -349315.9832070000
+-1585493.6744521901 -352996.1122558430
+-1585118.6121760199 -354496.3613605250
+-1585861.9157163899 -356240.3342513760
+-1586368.8197632500 -358747.0671571240
+-1587889.0972700799 -360996.6006787950
+-1586681.3716600600 -363935.4286441500
+-1585806.2263489999 -365748.2296456410
+-1586743.8820394201 -368373.6655788350
+-1586056.2678664399 -370123.9562009640
+-1585493.6744521901 -371124.1222707520
+-1586243.7990045301 -373562.0270658610
+-1428620.2472997301 -364425.2597226670
+-1414257.6683934701 -327460.5482541260
+-1412220.4351378100 -325972.8942023180
+-1404515.9240538401 -296165.1737279960
+-1387984.9332285200 -267002.0106682320
+-1375329.9306695000 -287124.5773036880
+-1374139.7661228001 -286331.1342725540
+-1347030.4625590600 -322432.7921891520
+-1351262.1587251101 -326267.7668396330
+-1381809.7154237600 -297174.8556980530
+-1381677.4749185799 -295852.4506461620
+-1382481.1222932001 -294804.4361498400
+-1398663.5713381099 -316073.2308695170
+-1409694.4697897099 -363328.2128408530
+-1202495.3746585899 -351317.7619567180
+-1191463.4809399999 -350233.9748030000
+-1232161.1083569999 -292094.5070650000
+-1231243.1167609999 -288422.5406810000
+-1360067.9373810000 -107884.1934940000
+-1423274.3497420000 -81217.9259650000
+-1402446.7987670000 -45916.9921070000
+-1478343.8065599999 60338.8188030000
+-1513291.7310790000 4210.3339700000
+-1523175.9925589999 11976.5394190000
+-1503760.4789370000 36334.1837800000
+-1528509.5619775900 63667.6809196406
+-1623055.4918765700 62841.1506965373
+-1648011.3012850001 32874.5178730000
+-1638219.3909290000 20634.6299280000
+-1650153.2816760000 31038.5346810000
+-1725734.5897359999 -61372.6193030000
+-1719614.6457630000 -69022.5492690000
+-1759088.2843859999 -114004.1374660000
+-1755416.3180020000 -117064.1094530000
+-1761230.2647760001 -126856.0198080000
+-1758170.2927900001 -130527.9861920000
+-1762148.2563720001 -135423.9413700000
+-1764902.2311590000 -131445.9777880000
+-1769798.1863370000 -134199.9525750000
+-1775000.1387139999 -131445.9777880000
+-1794277.9622269999 -153477.7760890000
+-1712576.7101950001 -225081.1205660000
+-1729939.5891459100 -335652.4567604720
+-1712113.0179281300 -349656.0205056490
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/DomainOutline.exp	(revision 18231)
@@ -0,0 +1,101 @@
+## Name:
+## Icon:0
+# Points Count Value
+95 25000.000000
+# X pos Y pos
+-1712113.0179281300 -349656.0205056490
+-1711509.1917759699 -349354.1074295690
+-1709240.6586108401 -349354.1074295690
+-1707080.1508345299 -348922.0058743060
+-1705459.7700022999 -347193.5996532570
+-1703083.2114483600 -345249.1426545770
+-1701138.7544496800 -344168.8887664210
+-1698438.1197292900 -343952.8379887900
+-1698006.0181740201 -341900.3556012940
+-1693793.0280102200 -340279.9747690600
+-1691092.3932898301 -339631.8224361670
+-1688391.7585694401 -339415.7716585360
+-1686447.3015707601 -340063.9239914290
+-1683530.6160727399 -341036.1524907690
+-1682558.3875734000 -343304.6856558960
+-1682134.7209454600 -344182.1487658350
+-1682126.2860181299 -345681.2442098390
+-1681072.0444963200 -345932.4393879640
+-1680634.4718407800 -346682.5639403050
+-1680571.9614614199 -348557.8753211580
+-1677446.4424933300 -348370.3441830730
+-1675508.6207331200 -349495.5310115840
+-1676616.9911885399 -353567.0975933760
+-1672991.8601872099 -353799.6175753630
+-1668839.1631938200 -353999.1991486380
+-1667132.2298986400 -355121.4651541420
+-1666069.5534494901 -357496.8595698890
+-1662944.0344814099 -358309.4945015920
+-1660756.1712037399 -358747.0671571240
+-1657922.9836098100 -361682.8074238540
+-1656579.2228470000 -364003.8487410000
+-1653004.8841628900 -364748.0635758530
+-1653442.4568184200 -361622.5446077650
+-1651129.5727820301 -355684.0585683980
+-1648929.2928810001 -350845.9692010000
+-1646260.7698359799 -347802.2804785470
+-1644571.8968503401 -341785.6704672340
+-1643503.3064999001 -340869.0986596620
+-1643190.7546030900 -336680.9032424240
+-1642690.6715682000 -335243.1645171040
+-1641913.0916588283 -332341.0814454452
+-1640683.9739821283 -330436.6112348017
+-1637816.0327364956 -328532.1410241582
+-1635241.2508976001 -328652.8685499910
+-1631765.4107996500 -327017.1790921330
+-1625934.5618617306 -322342.6128395668
+-1620608.3852626982 -320438.1426289233
+-1616101.6204481323 -320438.1426289233
+-1611594.8556335662 -320914.2601815842
+-1607907.5026034669 -321866.4952869060
+-1602991.0318966676 -324723.2006028712
+-1599713.3847588014 -327579.9059188365
+-1593977.5022675355 -328532.1410241582
+-1590699.8551296694 -334721.6692087495
+-1589259.8391499999 -338300.0840570000
+-1588627.0898328500 -343572.9950327750
+-1588056.6000060199 -345432.3563530700
+-1586993.9235568701 -347432.6884926460
+-1589259.8391499999 -349315.9832070000
+-1585493.6744521901 -352996.1122558430
+-1585118.6121760199 -354496.3613605250
+-1585861.9157163899 -356240.3342513760
+-1586368.8197632500 -358747.0671571240
+-1587889.0972700799 -360996.6006787950
+-1586681.3716600600 -363935.4286441500
+-1585806.2263489999 -365748.2296456410
+-1586743.8820394201 -368373.6655788350
+-1586056.2678664399 -370123.9562009640
+-1585493.6744521901 -371124.1222707520
+-1586243.7990045301 -373562.0270658610
+-1414257.6683934701 -327460.5482541260
+-1412220.4351378100 -325972.8942023180
+-1404515.9240538401 -296165.1737279960
+-1387984.9332285200 -267002.0106682320
+-1360067.9373810000 -107884.1934940000
+-1423274.3497420000 -81217.9259650000
+-1402446.7987670000 -45916.9921070000
+-1478343.8065599999 60338.8188030000
+-1503760.4789370000 36334.1837800000
+-1528509.5619775900 63667.6809196406
+-1623055.4918765700 62841.1506965373
+-1725734.5897359999 -61372.6193030000
+-1719614.6457630000 -69022.5492690000
+-1759088.2843859999 -114004.1374660000
+-1755416.3180020000 -117064.1094530000
+-1761230.2647760001 -126856.0198080000
+-1758170.2927900001 -130527.9861920000
+-1762148.2563720001 -135423.9413700000
+-1764902.2311590000 -131445.9777880000
+-1769798.1863370000 -134199.9525750000
+-1775000.1387139999 -131445.9777880000
+-1794277.9622269999 -153477.7760890000
+-1712576.7101950001 -225081.1205660000
+-1729939.5891459100 -335652.4567604720
+-1712113.0179281300 -349656.0205056490
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/Pig.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/Pig.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/Pig.par	(revision 18231)
@@ -0,0 +1,135 @@
+% Parameters to change/Try
+friction_coefficient = 10; % default [10]
+Temp_change          =  0;  % default [0 K]
+
+%Name and hemisphere
+md.miscellaneous.name='PIG';
+md.mesh.hemisphere='s';
+
+% {{{ NetCdf Loading
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Antarctica_5km_withshelves_v0.75.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+temp  = ncread(ncdata,'presartm')';
+smb   = ncread(ncdata,'presprcp')';
+gflux = ncread(ncdata,'bheatflx_fox')';
+
+disp('   Loading velocities data from NetCDF');
+nsidc_vel='../Data/Antarctica_ice_velocity.nc';
+
+xmin = ncreadatt(nsidc_vel,'/','xmin');
+xmin = strtrim(xmin);  %this is a string, and we need to recover the double value
+xmin = xmin(1:end-2);  %get rid of the unit
+xmin = str2num(xmin);  %convert to double
+
+ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+ymax = strtrim(ymax);  
+ymax = ymax(1:end-2);  
+ymax = str2num(ymax); 
+
+nx = ncreadatt(nsidc_vel,'/','nx');
+ny = ncreadatt(nsidc_vel,'/','ny');
+
+spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+spacing = strtrim(spacing);  
+spacing = spacing(1:end-2);  
+spacing = str2num(spacing); 
+
+velx = double(ncread(nsidc_vel,'vx'));
+vely = double(ncread(nsidc_vel,'vy'));
+
+x2=xmin+(0:1:nx)'*spacing; 
+x2=double(x2);
+
+y2=(ymax-ny*spacing)+(0:1:ny)'*spacing; 
+y2=double(y2);
+% }}}
+% {{{ Geometry
+disp('   Interpolating surface and ice base');
+md.geometry.base    = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+clear usrf, topg;
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%ensure hydrostatic equilibrium on ice shelf: 
+di=md.materials.rho_ice/md.materials.rho_water;
+
+%Get the node numbers of floating nodes
+pos=find(md.mask.groundedice_levelset<0); 
+
+%apply a flotation criterion on the precedingly defined nodes and
+%redefine base and thickness accordingly
+md.geometry.thickness(pos)=1/(1-di)*md.geometry.surface(pos);
+md.geometry.base(pos)=md.geometry.surface(pos)-md.geometry.thickness(pos);
+md.geometry.hydrostatic_ratio=ones(md.mesh.numberofvertices,1);
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+% }}} 
+% {{{ Initialization parameters
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15+Temp_change;
+clear temp;
+
+disp('   Set observed velocities')
+vx_obs=InterpFromGridToMesh(x2,y2,flipud(velx'),md.mesh.x,md.mesh.y,0);
+vy_obs=InterpFromGridToMesh(x2,y2,flipud(vely'),md.mesh.x,md.mesh.y,0);
+clear velx vely;
+
+vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+md.initialization.vx=vx_obs;
+md.initialization.vy=vy_obs;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.vel=vel_obs;
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+% }}}
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+
+% {{{ Forcings
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+clear smb;
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+clear gflux;
+% }}}
+
+% {{{ Friction and inversion set up
+disp('   Construct basal friction parameters');
+md.friction.coefficient=friction_coefficient*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%no friction applied on floating ice
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0;
+
+md.inversion=m1qn3inversion();
+md.inversion.vx_obs=vx_obs;
+md.inversion.vy_obs=vy_obs;
+md.inversion.vel_obs=vel_obs;
+% }}}
+
+
+disp('   Set boundary conditions');
+md=SetMarineIceSheetBC(md);
+md.basalforcings.floatingice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.thermal.spctemperature     = [md.initialization.temperature;1]; %impose observed temperature on surface
+md.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/PigRegion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/PigRegion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/PigRegion.m	(revision 18231)
@@ -0,0 +1,54 @@
+% {{{ Getting the velocity in PIG vicinity for the ExpDraw
+
+% Load Velocities
+% http://nsidc.org/data/nsidc-0484.html
+nsidc_vel='../Data/Antarctica_ice_velocity.nc'; 	
+
+% Get necessary data to build up the velocity grid
+xmin = ncreadatt(nsidc_vel,'/','xmin');
+xmin = strtrim(xmin);  % this is a string, and we need to recover the double value
+xmin = xmin(1:end-2);  % get rid of the unit
+xmin = str2num(xmin);  % convert to double
+
+ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+ymax = strtrim(ymax);  
+ymax = ymax(1:end-2);  
+ymax = str2num(ymax); 
+	
+nx = ncreadatt(nsidc_vel,'/','nx');
+ny = ncreadatt(nsidc_vel,'/','ny');
+
+spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+spacing = strtrim(spacing);
+spacing = spacing(1:end-2);  
+spacing = str2num(spacing); 
+
+
+x=xmin+(0:1:nx-1)'*spacing; 
+x=double(x);
+y=(ymax)-(0:1:ny-1)'*spacing; 
+y=double(y);
+
+posx=find(x<=-12.0e5);
+id1x=find(x>=-18.0e5,1);
+id2x=posx(end);
+
+posy=find(y>=-4.0e5);
+id1y=find(y<=1.0e5,1);
+id2y=posy(end);
+
+%Get velocity subset
+vx = double(ncread(nsidc_vel,'vx'));
+vx_obs = vx(id1x:id2x,id1y:id2y);
+vx_obs = flipud(vx_obs');
+
+vy = double(ncread(nsidc_vel,'vy'));
+vy_obs = vy (id1x:id2x,id1y:id2y);
+vy_obs = flipud(vy_obs');
+
+xred=x(id1x:id2x);
+yred=y(id1y:id2y);
+vel_obs=sqrt(vx_obs.^2.+vy_obs.^2.);
+imagesc(xred,yred,vel_obs)
+
+%}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/Pig/runme.m	(revision 18231)
@@ -0,0 +1,228 @@
+%Which steps to be performed
+steps=[1:5] ;
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1)
+
+	md.miscellaneous.name='PIG.Mesh_generation';
+
+	%Mesh parameters
+	domain =['./DomainOutline.exp'];
+	hmax=40000;    % maximum element size of the final mesh
+	hmin=5000;     % minimum element size of the final mesh
+	hinit=10000;   % element size for the initial mesh
+	gradation=1.7; % maximum size ratio between two neighboring elements
+	err=8;         % maximum error between interpolated and control field
+
+	% Generate an initial uniform mesh (resolution = hinit m)
+	md=bamg(model,'domain',domain,'hmax',hinit,'MaxCornerAngle',1);
+
+	%ploting
+	plotmodel(md,'data','mesh')
+
+	% Load Velocities
+	% http://nsidc.org/data/nsidc-0484.html
+	nsidc_vel='../Data/Antarctica_ice_velocity.nc'; 	
+
+	% Get necessary data to build up the velocity grid
+	xmin = ncreadatt(nsidc_vel,'/','xmin');
+	xmin = strtrim(xmin);  % this is a string, and we need to recover the double value
+	xmin = xmin(1:end-2);  % get rid of the unit
+	xmin = str2num(xmin);  % convert to double
+	
+	ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+	ymax = strtrim(ymax);  
+	ymax = ymax(1:end-2);  
+	ymax = str2num(ymax); 
+	
+	nx = ncreadatt(nsidc_vel,'/','nx');
+	ny = ncreadatt(nsidc_vel,'/','ny');
+	
+	spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+	spacing = strtrim(spacing);
+	spacing = spacing(1:end-2);  
+	spacing = str2num(spacing); 
+	
+	% Get velocities (Note: You can use ncdisp('file') to see an ncdump)
+	vx = double(ncread(nsidc_vel,'vx'));
+	vy = double(ncread(nsidc_vel,'vy'));
+	
+	x=xmin+(0:1:nx)'*spacing; 
+	x=double(x);
+	y=(ymax-ny*spacing)+(0:1:ny)'*spacing; 
+	y=double(y);
+
+	% Interpolate velocities onto coarse mesh
+	vx_obs=InterpFromGridToMesh(x,y,flipud(vx'),md.mesh.x,md.mesh.y,0);
+	vy_obs=InterpFromGridToMesh(x,y,flipud(vy'),md.mesh.x,md.mesh.y,0);
+	vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+	clear vx vy x y;
+
+	% Adapt the mesh to minimize error in velocity interpolation
+	md=bamg(md,'hmax',hmax,'hmin',hmin,'gradation',gradation,'field',vel_obs,'err',err);
+	
+	%ploting
+	plotmodel(md,'data','mesh')
+
+	% Convert x,y coordinates (Polar stereo) to lat/lon
+	[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,-1);
+	
+	% Save model
+	save ./Models/PIG.Mesh_generation md;
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2) 
+
+	md = loadmodel('./Models/PIG.Mesh_generation');	
+
+	% Load SeaRISe dataset for Antarctica  
+	% http://websrv.cs.umt.edu/isis/index.php/Present_Day_Antarctica
+	searise='../Data/Antarctica_5km_withshelves_v0.75.nc';
+	
+	%read thickness mask from SeaRISE
+	x1=double(ncread(searise,'x1'));
+	y1=double(ncread(searise,'y1'));
+	thkmask=double(ncread(searise,'thkmask'));
+	
+	%interpolate onto our mesh vertices
+	groundedice=double(InterpFromGridToMesh(x1,y1,thkmask',md.mesh.x,md.mesh.y,0));
+	groundedice(groundedice<=0)=-1;
+	clear thkmask;
+
+	%fill in the md.mask structure
+	md.mask.groundedice_levelset=groundedice; %ice is grounded for mask equal one
+	md.mask.ice_levelset=-1*ones(md.mesh.numberofvertices,1);%ice is present when negatvie
+
+	%ploting
+	plotmodel(md,'data',md.mask.groundedice_levelset,'title','grounded/floating','data',md.mask.ice_levelset,'title','ice/no-ice')
+	
+	% Save model
+	save ./Models/PIG.SetMask md;
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3) 
+
+	md = loadmodel('./Models/PIG.SetMask');
+	md = parameterize(md,'./Pig.par');
+
+	% Use a MacAyeal flow model
+	md = setflowequation(md,'SSA','all');
+	
+	% Save model
+	save ./Models/PIG.Parameterization md;
+end
+% }}}
+
+% {{{ Control Method #4
+if any(steps==4)
+
+	md = loadmodel('./Models/PIG.Parameterization');
+
+	% Control general
+	md.inversion.iscontrol=1;
+	md.inversion.maxsteps=20;
+	md.inversion.maxiter=40;
+	md.inversion.dxmin=0.1;
+	md.inversion.gttol=1.0e-4;
+	md.verbose=verbose('solution',true,'control',true);
+
+	% Cost functions
+	md.inversion.cost_functions=[101 103 501];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
+	md.inversion.cost_functions_coefficients(:,1)=1;
+	md.inversion.cost_functions_coefficients(:,2)=1;
+	md.inversion.cost_functions_coefficients(:,3)=8e-15;
+
+	% Controls
+	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);
+
+	% Additional parameters
+	md.stressbalance.restol=0.01;
+	md.stressbalance.reltol=0.1;
+	md.stressbalance.abstol=NaN;
+
+	% Solve
+	md.toolkits=toolkits;
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	% Update model friction fields accordingly
+	md.friction.coefficient=md.results.StressbalanceSolution.FrictionCoefficient;
+
+	plotmodel(md,'data',md.friction.coefficient)
+
+	% Save model
+	save ./Models/PIG.Control_drag md;
+end
+% }}}
+
+% {{{ Plot #5
+if any(steps==5)
+
+	md = loadmodel('./Models/PIG.Control_drag');
+
+	plotmodel(md,'nlines',2,'ncols',2,'unit#all','km','axis#all','equal',...
+		'xlim#all',[min(md.mesh.x) max(md.mesh.x)]/10^3,...
+		'ylim#all',[min(md.mesh.y) max(md.mesh.y)]/10^3,...
+		'FontSize#all',12,...
+		'data',md.initialization.vel,'title','Observed velocity',...
+		'data',md.results.StressbalanceSolution.Vel,'title','Modeled Velocity',...
+		'data',md.geometry.base,'title','Bed elevation',...
+		'data',md.results.StressbalanceSolution.FrictionCoefficient,'title','Friction Coefficient',...
+		'colorbar#all','on','colorbartitle#1-2','[m/yr]',...
+		'caxis#1-2',([1.5,4000]),...
+		'colorbartitle#3','[m]', 'log#1-2',10);
+end
+% }}}
+
+% {{{ HO #6
+if any(steps==6)
+
+	% Load Model
+
+	% Disable inversion
+
+	%Extrude Mesh
+
+	% Set Flowequation
+
+	% Solve
+
+	% Save Model
+
+end
+% }}}
+
+% {{{ Plot #7
+if any(steps==7)
+
+	mdHO = loadmodel('./Models/PIG.ModelHO');
+	mdSSA = loadmodel('./Models/PIG.Control_drag');
+
+	basal=find(mdHO.mesh.vertexonbase);
+	surf=find(mdHO.mesh.vertexonsurface);
+
+	plotmodel(md,'nlines',3,'ncols',2,'unit#all','km','axis#all','equal',...
+						'xlim#all',[min(md.mesh.x) max(md.mesh.x)]/10^3,...
+						'ylim#all',[min(md.mesh.y) max(md.mesh.y)]/10^3,...
+						'FontSize#all',12,...
+						'data',mdHO.initialization.vel,'title','Observed velocity',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdHO.initialization.vel(surf)),'title','(HO-observed) velocities',...
+						'data',mdSSA.results.StressbalanceSolution.Vel,'title','Modeled SSA Velocity',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdSSA.results.StressbalanceSolution.Vel),'title','(HO-SSA) velocities',...
+						'data',mdHO.results.StressbalanceSolution.Vel,'title','Modeled HO surface Velocities',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdHO.results.StressbalanceSolution.Vel(basal)),'title','(HOsurf-HO base) velocities',...
+						'caxis#1',([1.5,4000]),'caxis#3',([1.5,4000]),'caxis#5',([1.5,4000]),...
+						'colorbar#all','on','view#all',2,...
+						'colorbartitle#all','[m/yr]',...
+						'layer#5',1, 'log#1', 10,'log#3', 10,'log#5', 10);
+end
+% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/DomainOutline.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/DomainOutline.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/DomainOutline.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count  Value
+5 1.000000
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Front.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Front.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Front.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 999999
+-1000 1100000
+1100000 1100000
+1100000 999999
+-1000 999999
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/README	(revision 18231)
@@ -0,0 +1,6 @@
+md=model;
+md=mesh(md,'DomainOutline.exp',50000);
+md=geography(md,'all','');
+md=parameterize(md,'Square.par');
+md=setelementstype(md,'macayeal','all');
+md=solve(md,DiagnosticSolutionEnum);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Square.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Square.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/Square.par	(revision 18231)
@@ -0,0 +1,30 @@
+%Start defining model parameters here
+
+disp('      creating thickness');
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+md.geometry.thickness = hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+md.geometry.base      = -md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface   = md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      initial velocity');
+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.vel=zeros(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=paterson((273-20)*ones(md.mesh.numberofvertices,1));
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+
+disp('      creating boundary conditions');
+md=SetIceShelfBC(md,'Front.exp');
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/SquareIceShelf/runme.m	(revision 18231)
@@ -0,0 +1,7 @@
+md=model;
+md=triangle(md,'DomainOutline.exp',100000);
+md=setmask(md,'all','');
+md=parameterize(md,'Square.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname,'np',2);
+md=solve(md,StressbalanceSolutionEnum);
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/ErrorContour.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/ErrorContour.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/ErrorContour.exp	(revision 18231)
@@ -0,0 +1,24 @@
+## Name:ErrorContour
+## Icon:0
+# Points Count Value
+18 1.000000
+# X pos Y pos
+-1642090.6657102096 -328038.7002928721
+-1665417.0018035804 -319119.8070807009
+-1681882.6508106657 -304712.3641995014
+-1666103.0705122089 -245710.4552574461
+-1632485.7037894099 -232675.1497935036
+-1616020.0547823247 -224442.3252899610
+-1598182.2683579824 -200429.9204879618
+-1596810.1309407253 -181219.9966463624
+-1615333.9860736963 -160637.9353875059
+-1559762.4206747836 -147602.6299235635
+-1527517.1913692418 -188080.6837326479
+-1566623.1077610692 -218953.7756209326
+-1533691.8097468987 -229244.8062503609
+-1523400.7791174706 -309514.8451599012
+-1533691.8097468987 -350678.9676776142
+-1594751.9248148398 -371261.0289364707
+-1636602.1160411814 -349306.8302603571
+-1642090.6657102096 -328038.7002928721
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp	(revision 18231)
@@ -0,0 +1,22 @@
+## Name:MassFlux1
+## Icon:0
+# Points Count Value
+16 1.000000
+# X pos Y pos
+-1638344.3538415846 -328022.1178486745
+-1636175.0592654669 -328022.1178486745
+-1634647.1933393457 -327710.7373731936
+-1631836.4701132313 -326087.2311287920
+-1629847.9500851235 -324428.7567974643
+-1626413.2336729371 -321756.7703747695
+-1622074.6445207016 -320098.2960434417
+-1618278.3790124957 -319637.6087291840
+-1614210.9516822749 -319729.7461920356
+-1609601.2007080249 -320466.8458948479
+-1604539.5133637502 -322954.5573918396
+-1602370.2187876324 -324613.0317231673
+-1599206.6641974607 -326824.3308316044
+-1595681.5605112694 -327008.6057573075
+-1593150.7168391321 -327653.5679972683
+-1590710.2604409996 -330786.2417342208
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux11
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1539536.1089629673 -171232.8272031187
+-1540384.1546699132 -200614.0179257037
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux12
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1559431.5986180613 -236969.7272119786
+-1549112.1094185982 -261719.2194756830
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux13
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1572656.1032135738 -292391.9615161452
+-1573651.1418990945 -315407.7936937447
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux14
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1579674.9916810417 -321516.2892665596
+-1587436.3185859676 -337140.9687259690
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux14
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1579674.9916810417 -321516.2892665596
+-1587436.3185859676 -337140.9687259690
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp	(revision 18231)
@@ -0,0 +1,127 @@
+## Name:
+## Icon:0
+# Points Count Value
+121 25000.000000
+# X pos Y pos
+-1712012.0818103175 -348661.1275967784
+-1711738.9446965172 -348380.8584401013
+-1709339.1962288069 -348358.9741029009
+-1707566.1624406802 -348048.0535193763
+-1706142.6423542583 -346463.0619396989
+-1703644.8906504354 -344421.7875470470
+-1701428.0245438961 -343211.6412474416
+-1699098.6802015656 -343202.0651453367
+-1698767.2671226400 -341251.8958583454
+-1694089.8466347910 -339325.0408948531
+-1691249.4280928215 -338644.2293668062
+-1688271.0930389061 -338423.0784381799
+-1686131.0738047434 -339115.2406933784
+-1682853.5065837551 -340300.2702040364
+-1681648.3224467863 -342890.2203795200
+-1681160.5378740367 -343956.3892846339
+-1681343.2453770319 -345059.2736684235
+-1680476.2008784728 -345129.3389066600
+-1679673.6094558411 -346405.5378093903
+-1679898.5797234357 -347818.5803631411
+-1677215.4777375804 -347397.3820658240
+-1674583.5118423651 -349115.8291018623
+-1675803.3920552148 -352985.6713725598
+-1672935.8509424068 -352801.1873251720
+-1668529.5198238282 -353048.3463822120
+-1666370.5689502691 -354473.4893832008
+-1665423.6161039397 -356733.4691418489
+-1662720.0686237188 -357334.8975107344
+-1660276.4961961196 -357869.6209268258
+-1657124.6115999895 -361080.6428832713
+-1655993.6074009922 -363193.2597271361
+-1653688.2093358042 -364017.9494011777
+-1654435.7188006472 -361506.6539926908
+-1652050.9793420888 -355295.4585798742
+-1649364.4081354018 -349945.5944371450
+-1645761.7354861272 -350839.5079576963
+-1645996.5509334437 -351783.7951824765
+-1645345.5744557772 -351250.5634369315
+-1644300.2406060672 -352221.4198542684
+-1644633.1139884400 -348521.7302174515
+-1647057.7191411837 -348406.3266729190
+-1645415.0137059502 -341247.9400814587
+-1644395.7076754270 -340417.8557739360
+-1644169.8943326229 -336477.7151767056
+-1643216.0658811626 -334392.3056475453
+-1641434.0471865973 -334447.2336099123
+-1641190.7738541283 -334332.2252321915
+-1641050.9552025823 -333796.1902735520
+-1639787.1689887117 -331073.8439645328
+-1637807.1154673321 -329711.1825533187
+-1635805.1587214153 -327827.0308139678
+-1632065.9795259857 -326063.4189332099
+-1625929.4636559838 -324999.2470617331
+-1619584.9279456623 -324892.7557348280
+-1615193.9710026928 -325097.1546172730
+-1611296.7956007582 -324995.1262699560
+-1608304.4173934418 -325211.0183405159
+-1603316.9037486394 -326424.5673739603
+-1600245.1111844976 -328836.3685103582
+-1595818.7639296530 -331148.7367850624
+-1591649.1976614639 -334787.7632693424
+-1588371.5600852505 -337840.7799059978
+-1587648.7608976758 -343365.9382903088
+-1587132.8425864622 -345049.3782468919
+-1586012.7810109658 -347625.9740446581
+-1588260.6470941922 -349356.1732009141
+-1584626.3352827206 -352498.3947002917
+-1584121.7278491815 -354575.2387267592
+-1584906.9380743054 -356537.0120279597
+-1585446.5634405916 -359133.6460951389
+-1586894.3150289655 -361098.6217195836
+-1585768.2162689434 -363527.8170254802
+-1584807.6500740163 -365694.8871387623
+-1585744.0045738907 -368358.0113804646
+-1585152.9531241022 -369694.9777909298
+-1584499.3876485692 -371017.3807505022
+-1585456.9434211247 -372944.8898924028
+-1429208.6248950495 -363616.6734221856
+-1415050.5145378630 -326851.1264040734
+-1413047.7406149551 -325411.1419014899
+-1405442.9810691341 -295790.2533492565
+-1388007.7873070226 -266002.2718567938
+-1375120.7873420289 -286146.6923060659
+-1373971.2210923850 -285345.4403176561
+-1346034.9931278315 -322527.8743193840
+-1351274.5360716779 -327267.6902373450
+-1382747.3419384742 -297522.4999399224
+-1382639.2845126297 -296126.1700367680
+-1382479.2357768724 -295804.4343703665
+-1397758.7640077863 -316499.0520702488
+-1408929.4248104726 -362684.2359936420
+-1202573.2098436793 -350320.7957165864
+-1192371.9994205239 -349816.1301302491
+-1233144.4335198263 -292276.3631183850
+-1232225.6096719459 -288608.8406540032
+-1360692.9373680721 -108664.8182541504
+-1424223.8165527256 -81531.7934136631
+-1403445.8481024427 -45960.5859752788
+-1478312.1378749039 59339.3203815984
+-1513118.6444103392 3225.4273728387
+-1524169.2804273698 11860.8708815790
+-1504759.9852699745 36302.7657860445
+-1528911.0294425790 62751.8076344339
+-1622627.2364271644 61937.4929792271
+-1647011.3496706884 32864.6807476235
+-1637527.3859760596 19912.7371761968
+-1650069.2631712460 30042.0704865309
+-1724734.6043381831 -61378.0233897057
+-1718614.9048978437 -69045.3133313945
+-1758091.3164752426 -113926.3236823874
+-1754430.7541207569 -116894.8054778867
+-1760233.4203404333 -126776.6398906443
+-1757170.3120773330 -130521.7753713153
+-1762186.6328915418 -136423.2047200473
+-1765126.7323215308 -132420.4516091067
+-1769785.4415677825 -135199.8713571306
+-1774818.6171028516 -132429.3647437230
+-1793280.1507095622 -153411.6536596067
+-1711636.5537849038 -224740.3773715630
+-1729008.9305659365 -335286.5679692774
+-1712012.0818103175 -348661.1275967784
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp	(revision 18231)
@@ -0,0 +1,171 @@
+## Name:MassFlux2
+## Icon:0
+# Points Count Value
+165 1.000000
+# X pos Y pos
+-1609993.8450579999 -266189.3103270000
+-1609790.4465310001 -265898.8271340000
+-1609587.0480040000 -265608.3439410000
+-1609383.6494770001 -265317.8607480000
+-1609136.7086169999 -265274.3184150000
+-1608933.3100900000 -264983.8352220000
+-1608686.3692300001 -264940.2928890000
+-1608236.0298430000 -264606.2673630000
+-1607989.0889830000 -264562.7250310000
+-1607785.6904559999 -264272.2418380000
+-1607538.7495960000 -264228.6995050000
+-1607291.8087370000 -264185.1571720000
+-1607044.8678770000 -264141.6148390000
+-1606797.9270170000 -264098.0725060000
+-1606304.0452970001 -264010.9878410000
+-1606057.1044369999 -263967.4455080000
+-1605810.1635769999 -263923.9031750000
+-1605563.2227179999 -263880.3608420000
+-1605316.2818580000 -263836.8185100000
+-1605069.3409980000 -263793.2761770000
+-1604778.8578049999 -263996.6747040000
+-1604531.9169449999 -263953.1323710000
+-1604038.0352250000 -263866.0477060000
+-1603791.0943660000 -263822.5053730000
+-1603500.6111730000 -264025.9039000000
+-1603253.6703130000 -263982.3615680000
+-1602963.1871199999 -264185.7600950000
+-1602716.2462599999 -264142.2177620000
+-1602425.7630680001 -264345.6162900000
+-1601888.3390150000 -264505.4724840000
+-1601641.3981550001 -264461.9301510000
+-1601350.9149630000 -264665.3286790000
+-1601060.4317699999 -264868.7272060000
+-1600479.4653840000 -265275.5242610000
+-1600188.9821919999 -265478.9227880000
+-1599898.4989990001 -265682.3213160000
+-1599608.0158060000 -265885.7198430000
+-1599027.0494210001 -266292.5168980000
+-1598736.5662280000 -266495.9154250000
+-1598446.0830349999 -266699.3139520000
+-1598402.5407030000 -266946.2548130000
+-1598605.9392299999 -267236.7380050000
+-1598518.8545639999 -267730.6197260000
+-1598722.2530910000 -268021.1029190000
+-1598678.7107579999 -268268.0437790000
+-1598635.1684250000 -268514.9846390000
+-1598591.6260919999 -268761.9254990000
+-1598795.0246190000 -269052.4086920000
+-1598751.4822869999 -269299.3495520000
+-1598707.9399540001 -269546.2904130000
+-1598620.8552880001 -270040.1721330000
+-1598577.3129550000 -270287.1129930000
+-1598533.7706220001 -270534.0538530000
+-1598737.1691490000 -270824.5370460000
+-1598693.6268170001 -271071.4779060000
+-1598650.0844840000 -271318.4187660000
+-1598606.5421509999 -271565.3596270000
+-1598316.0589580000 -271768.7581540000
+-1598228.9742930001 -272262.6398740000
+-1597938.4911000000 -272466.0384020000
+-1597648.0079069999 -272669.4369290000
+-1597067.0415220000 -273076.2339840000
+-1597023.4991890001 -273323.1748440000
+-1596979.9568560000 -273570.1157040000
+-1596936.4145229999 -273817.0565640000
+-1596892.8721900000 -274063.9974240000
+-1596805.7875250001 -274557.8791450000
+-1596762.2451919999 -274804.8200050000
+-1596718.7028590001 -275051.7608650000
+-1596675.1605260000 -275298.7017250000
+-1596631.6181930001 -275545.6425850000
+-1596341.1350010000 -275749.0411130000
+-1596297.5926679999 -275995.9819730000
+-1595963.5671420000 -276446.3213600000
+-1595920.0248090001 -276693.2622210000
+-1595629.5416170000 -276896.6607480000
+-1595339.0584239999 -277100.0592750000
+-1595048.5752310001 -277303.4578030000
+-1594467.6088459999 -277710.2548570000
+-1594177.1256530001 -277913.6533850000
+-1593886.6424600000 -278117.0519120000
+-1593392.7607410001 -278029.9672470000
+-1593102.2775480000 -278233.3657740000
+-1592898.8790209999 -277942.8825810000
+-1592695.4804940000 -277652.3993880000
+-1592201.5987740001 -277565.3147220000
+-1591998.2002470000 -277274.8315290000
+-1592041.7425800001 -277027.8906690000
+-1591838.3440530000 -276737.4074760000
+-1591881.8863860001 -276490.4666160000
+-1591722.0301910001 -275953.0425630000
+-1591765.5725240000 -275706.1017030000
+-1591562.1739970001 -275415.6185100000
+-1591605.7163300000 -275168.6776500000
+-1591402.3178030001 -274878.1944570000
+-1591198.9192760000 -274587.7112640000
+-1591242.4616090001 -274340.7704040000
+-1591039.0630820000 -274050.2872110000
+-1591082.6054150001 -273803.3463510000
+-1590922.7492209999 -273265.9222970000
+-1590966.2915530000 -273018.9814370000
+-1590762.8930259999 -272728.4982440000
+-1590806.4353590000 -272481.5573840000
+-1590603.0368319999 -272191.0741910000
+-1590399.6383050000 -271900.5909980000
+-1590443.1806379999 -271653.6501380000
+-1590239.7821110000 -271363.1669450000
+-1590036.3835839999 -271072.6837520000
+-1590123.4682499999 -270578.8020320000
+-1589920.0697230001 -270288.3188390000
+-1589716.6711960000 -269997.8356460000
+-1589760.2135280001 -269750.8947860000
+-1589556.8150010000 -269460.4115930000
+-1589600.3573340001 -269213.4707330000
+-1589440.5011400001 -268676.0466800000
+-1589484.0434729999 -268429.1058190000
+-1589280.6449460001 -268138.6226260000
+-1589077.2464190000 -267848.1394340000
+-1588873.8478920001 -267557.6562410000
+-1588423.5085050000 -267223.6307150000
+-1588220.1099779999 -266933.1475220000
+-1587973.1691180000 -266889.6051890000
+-1587726.2282580000 -266846.0628560000
+-1587479.2873980000 -266802.5205230000
+-1586985.4056780001 -266715.4358580000
+-1586738.4648190001 -266671.8935250000
+-1586491.5239589999 -266628.3511920000
+-1586244.5830989999 -266584.8088590000
+-1585997.6422389999 -266541.2665270000
+-1585750.7013790000 -266497.7241940000
+-1585256.8196590000 -266410.6395280000
+-1585009.8787990001 -266367.0971960000
+-1584762.9379400001 -266323.5548630000
+-1584472.4547470000 -266526.9533900000
+-1584428.9124139999 -266773.8942500000
+-1584138.4292210001 -266977.2927780000
+-1583804.4036960001 -267427.6321650000
+-1583760.8613630000 -267674.5730250000
+-1583470.3781699999 -267877.9715530000
+-1583179.8949770001 -268081.3700800000
+-1583136.3526450000 -268328.3109400000
+-1582845.8694519999 -268531.7094680000
+-1582802.3271190000 -268778.6503280000
+-1582468.3015940001 -269228.9897150000
+-1582424.7592610000 -269475.9305750000
+-1582134.2760679999 -269679.3291030000
+-1582090.7337350000 -269926.2699630000
+-1581800.2505419999 -270129.6684900000
+-1581509.7673500001 -270333.0670180000
+-1581219.2841570000 -270536.4655450000
+-1581132.1994910000 -271030.3472650000
+-1580841.7162990000 -271233.7457930000
+-1580551.2331060001 -271437.1443200000
+-1580507.6907730000 -271684.0851800000
+-1580217.2075799999 -271887.4837080000
+-1580173.6652470001 -272134.4245680000
+-1579839.6397220001 -272584.7639550000
+-1579796.0973890000 -272831.7048160000
+-1579505.6141959999 -273035.1033430000
+-1579462.0718640001 -273282.0442030000
+-1579418.5295309999 -273528.9850630000
+-1579128.0463380001 -273732.3835910000
+-1579084.5040050000 -273979.3244510000
+-1578750.4784800000 -274429.6638380000
+-1578706.9361469999 -274676.6046980000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:MassFlux4
+## Icon:0
+# Points Count Value
+4 1.000000
+# X pos Y pos
+-1605390.0162510793 -209047.7381093690
+-1592454.5133393104 -208141.0538114636
+-1574086.0992045982 -208918.2117810968
+-1560891.8862345938 -210472.5277203633
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux5
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1660144.8928561222 -319887.0521198768
+-1630434.8468677206 -298387.4931837295
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux6
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1635925.9455644884 -157610.4872330402
+-1625288.0602165582 -120861.2411445094
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux7
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1642052.5574172530 -95522.7999921589
+-1610982.9267521810 -78949.7704229522
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux8
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1605014.5365509845 -81707.1563440522
+-1566756.1417461073 -82763.2940976564
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux9
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1555378.1885604258 -45179.9925785796
+-1550583.9034971579 -68415.0231578706
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp	(revision 18231)
@@ -0,0 +1,8 @@
+## Name:MassFlux10
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1565010.6613481115 -111795.8673475993
+-1537474.3225972611 -138442.9656094175
+
Index: /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/examples/UncertaintyQuantification/runme.m	(revision 18231)
@@ -0,0 +1,290 @@
+%PIG Uncertainty Quantification Application
+steps=[1]; 
+
+if any(steps==1) 
+	disp('   Step 1: plot flux gates'); 
+	
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	texts=cell(1,13);
+	textpositions=cell(1,13);
+
+	for i=1:13,
+		contour=expread(['./MassFluxes/MassFlux' num2str(i) '.exp']);
+		textpositions{i}=[contour.x(end) contour.y(end)];
+	end
+
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'log',10,'expdisp',...
+		{'MassFluxes/MassFlux1.exp','MassFluxes/MassFlux2.exp',...
+		'MassFluxes/MassFlux3.exp','MassFluxes/MassFlux4.exp',...
+		'MassFluxes/MassFlux5.exp','MassFluxes/MassFlux6.exp',...
+		'MassFluxes/MassFlux7.exp','MassFluxes/MassFlux8.exp',...
+		'MassFluxes/MassFlux9.exp','MassFluxes/MassFlux10.exp',...
+		'MassFluxes/MassFlux11.exp','MassFluxes/MassFlux12.exp',...
+		'MassFluxes/MassFlux13.exp'},...
+		'expstyle',{'k-','k-','k-','k-','k-','k-','k-',...
+		'k-','k-','k-','k-','k-','k-'},'linewidth',2,...
+		'text',{'1','2','3','4','5','6','7',...
+		'8','9','10','11','12','13'},...
+		'textposition',textpositions);
+
+end
+if any(steps==2) 
+	disp('   Step 2: compute cross overs from CRESIS'); 
+	
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	%load cross overs: CRESIS McCord Antarctica, 2009 (courtesy of John Paden)
+	load('../Data/CrossOvers2009.mat');
+	
+	%interpolate cross over errors over our mesh vertices
+	DeltaHH=InterpFromMeshToMesh2d(index,x,y,dhh,md.mesh.x,md.mesh.y);
+
+	%avoid NaN values
+	pos=find(isnan(DeltaHH)); DeltaHH(pos)=0;
+
+	%filter out unrealistic error ranges
+	flags=ContourToNodes(md.mesh.x,md.mesh.y,'ErrorContour.exp',1);
+	pos=find(~flags); DeltaHH(pos)=0; 
+
+	%avoid large unrealistic values
+	pos=find(DeltaHH>1); DeltaHH(pos)=1;
+	pos=find(DeltaHH<-1); DeltaHH(pos)=-1;
+	
+	%transform into absolute errors and setup a minimum error everywhere.
+	DeltaHH=abs(DeltaHH);
+	pos=find(DeltaHH==0); pos2=find(DeltaHH~=0); 
+	DeltaHH(pos)=min(DeltaHH(pos2));
+
+	save Models/PIG.CrossOvers DeltaHH
+
+end
+if any(steps==3) 
+	disp('   Step 3: sampling analysis'); 
+	
+	%load model and cross over errors
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+	load -mat Models/PIG.CrossOvers
+
+	%partition the mesh
+	md.qmu.numberofpartitions=50;
+	md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,...
+	'weighting','on');
+	md.qmu.partition=md.qmu.partition-1; %switch partition to c-indexing
+
+	%make DeltaHH into our 3 sigma deviation
+	DeltaHH=DeltaHH/6; %2 (to transform DeltaHH into a radius) x 3 (for 3 sigma)
+	DeltaHH_on_partition=AreaAverageOntoPartition(md,DeltaHH);
+	DeltaHH_on_grids=DeltaHH_on_partition(md.qmu.partition+1); %just to check in case
+	
+	md.qmu.variables.thickness=normal_uncertain('scaled_Thickness',1,1);
+	md.qmu.variables.thickness.stddev=DeltaHH_on_partition;
+
+	%responses
+	md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]); %grounding line
+	md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux8=response_function('indexed_MassFlux_8',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux9=response_function('indexed_MassFlux_9',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux10=response_function('indexed_MassFlux_10',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux11=response_function('indexed_MassFlux_11',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux12=response_function('indexed_MassFlux_12',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux13=response_function('indexed_MassFlux_13',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+	%mass flux profiles
+	md.qmu.mass_flux_profiles={'MassFlux1.exp',...
+	                           'MassFlux2.exp',...
+	                           'MassFlux3.exp',...
+	                           'MassFlux4.exp',...
+	                           'MassFlux5.exp',...
+	                           'MassFlux6.exp',...
+	                           'MassFlux7.exp',...
+	                           'MassFlux8.exp',...
+	                           'MassFlux9.exp',...
+	                           'MassFlux10.exp',...
+	                           'MassFlux11.exp',...
+	                           'MassFlux12.exp',...
+	                           'MassFlux13.exp'};
+	md.qmu.mass_flux_profile_directory='../MassFluxes/';
+
+	%%  sampling analysis
+	md.qmu.method     =dakota_method('nond_samp');
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+	'seed',1234,...
+	'samples',30,...
+	'sample_type','lhs'); %random or lhs
+
+	%%  a variety of parameters
+	md.qmu.params.evaluation_concurrency=1;
+	md.qmu.params.analysis_driver='';
+	md.qmu.params.analysis_components='';
+	md.qmu.params.tabular_graphics_data=true;
+	md.verbose=verbose('qmu',true);
+
+	md.stressbalance.restol=10^-5; %tighten tolerances for UQ analyses
+	
+	%solve
+	md.qmu.isdakota=1; md.inversion.iscontrol=0;
+	md.cluster=generic('name',oshostname,'np',4);
+	md=solve(md,StressbalanceSolutionEnum,'overwrite','y');
+
+	save ./Models/PIG.Sampling md; 
+end
+if any(steps==4) 
+	disp('   Step 4: sensitivity analysis'); 
+	
+	%load model
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	%partition the mesh
+	md.qmu.numberofpartitions=10;
+	md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+	md.qmu.partition=md.qmu.partition-1; %switch partition to c-indexing
+
+	%all types of variables and responses: scaled_Thickness, indexed_MassFlux_i,MaxVel,nodal_DragCoefficient_i. scaled variables are expanded.
+
+	%variables
+	md.qmu.variables.DragCoefficient=normal_uncertain(...
+	'scaled_FrictionCoefficient',1,0.05);
+	md.qmu.variables.rheology_B=normal_uncertain(...
+	'scaled_MaterialsRheologyB',1,0.05);
+	md.qmu.variables.Thickness=normal_uncertain('scaled_Thickness',1,0.05);
+
+	%responses
+	md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux8=response_function('indexed_MassFlux_8',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux9=response_function('indexed_MassFlux_9',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux10=response_function('indexed_MassFlux_10',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux11=response_function('indexed_MassFlux_11',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux12=response_function('indexed_MassFlux_12',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux13=response_function('indexed_MassFlux_13',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+	%mass flux profiles
+	md.qmu.mass_flux_profiles={'MassFlux1.exp',...
+	                           'MassFlux2.exp',...
+	                           'MassFlux3.exp',...
+	                           'MassFlux4.exp',...
+	                           'MassFlux5.exp',...
+	                           'MassFlux6.exp',...
+	                           'MassFlux7.exp',...
+	                           'MassFlux8.exp',...
+	                           'MassFlux9.exp',...
+	                           'MassFlux10.exp',...
+	                           'MassFlux11.exp',...
+	                           'MassFlux12.exp',...
+	                           'MassFlux13.exp'};
+	md.qmu.mass_flux_profile_directory='../MassFluxes/';
+
+	%method: local reliability
+	md.qmu.method     =dakota_method('nond_l');
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+	'output','quiet');
+
+	%parameters
+	md.qmu.params.evaluation_concurrency=1;
+	md.qmu.params.analysis_driver='';
+	md.qmu.params.analysis_components='';
+	md.qmu.params.tabular_graphics_data=false;
+
+	md.stressbalance.restol=10^-5; %tighten for qmu analyses
+	
+	%solve
+	md.qmu.isdakota=1; 
+	md.inversion.iscontrol=0;
+	md.cluster=generic('name',oshostname,'np',2);
+	md.verbose=verbose('qmu',true);
+	md=solve(md,StressbalanceSolutionEnum,'overwrite','y');
+	
+	save ./Models/PIG.Sensitivity md; 
+end
+if any(steps==5) 
+	disp('   Step 5: plot partition');
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sampling');
+	
+	plotmodel(md,'data','mesh','partitionedges','on','meshlinewidth',1.5,...
+	'linewidth',2, 'axis#all','image','unit','km','colorbar','off',...
+	'title','','meshcolor','b','grid','on');
+
+end 
+if any(steps==6) 
+	disp('   Step 6: plot histogram'); 
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sampling');
+
+	%which profile are we looking at?
+	index=1; 	
+
+	%retrieve results for the specific profile, mass flux in m^3 water equiv/s
+	result=md.results.dakota.dresp_dat(md.qmu.numberofpartitions+index);
+	result.sample=result.sample/1e12*60*60*24*365;
+		
+	%plot histogram
+	plot_hist_norm(result,'cdfleg','off','cdfplt','off','nrmplt','off',...
+	'xlabelplt','M (Gt/yr)','ylabelplt','F','FontSize',8,'FaceColor',...
+	'none','EdgeColor','red');
+
+end
+if any(steps==7) 
+	disp('   Step 7: plot sensitivity'); 
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sensitivity');
+	%copy dakota results into model qmu
+	md.qmu.results=md.results.dakota;
+
+	%which profile are we looking at?
+	index=1; 	
+
+	%To plot sensitivities
+	sa=md.results.dakota.dresp_out(index).sens(1:10); sa=sa(md.qmu.partition+1)/1e12*60*60*24*365;
+	sb=md.results.dakota.dresp_out(index).sens(11:20); sb=sb(md.qmu.partition+1)/1e12*60*60*24*365;
+	sh=md.results.dakota.dresp_out(index).sens(21:30); sh=sh(md.qmu.partition+1)/1e12*60*60*24*365;
+
+	plotmodel(md,'data',sh,'data',sa,'data',sb,'expdisp#all',...
+		['MassFluxes/MassFlux' num2str(index) '.exp'],...
+		'expstyle#all','b-','linewidth#all',2,...
+		'nlines',3,'ncols',1, 'axis#all','image',...
+		'colorbar#all','on','colorbarfontsize#all',10,...
+		'colorbartitle#1','S_{H}', 'colorbartitle#2','S_{\alpha}',...
+		'colorbartitle#3','S_{B}','unit#all','km','figure',1);
+
+	%To plot importance factors
+	ifa=importancefactors(md,'scaled_FrictionCoefficient',['indexed_MassFlux_' num2str(index)]);
+	ifb=importancefactors(md,'scaled_MaterialsRheologyB',['indexed_MassFlux_' num2str(index)]);
+	ifh=importancefactors(md,'scaled_Thickness',['indexed_MassFlux_' num2str(index)]);
+
+	plotmodel(md,'data',ifh,'data',ifa,'data',ifb,'expdisp#all',...
+		['MassFluxes/MassFlux' num2str(index) '.exp'],...
+		'expstyle#all','b-','linewidth#all',2,'log#all',10,...
+		'nlines',3,'ncols',1, 'axis#all','image','caxis#all',[1e-10 1],...
+		'colorbar#all','on','colorbarfontsize#all',10,...
+		'colorbartitle#1','If_{H}', 'colorbartitle#2','If_{\alpha}',...
+		'colorbartitle#3','If_{B}','unit#all','km','figure',2);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/README	(revision 18231)
@@ -0,0 +1,22 @@
+To install all the ISSM libraries:
+
+1/ go into each library folder and type install.sh . 
+
+2/ There is no guarantee the compilation will work on all systems. A lot of tweaking of the 
+install.sh files will probably be involved. Especially, the configuration part of the install.
+
+Update: 
+now install.sh can call configure.sh for the most complex libraries, ie Petsc and Dakota. For those 
+libraries, go in the configs/ directory, pick up the correct configuration file and copy it to the top 
+folder of the library compilation. Tweak if necessary.
+
+machine characteristics:
+
+-astrid: linux 64 bits
+-castor: altix 64 bits
+-cosmos: JPL cluster 32 bits
+-macmathieu: iMac 24" 2009 32 bits
+-macbookmathieu: MacBook Pro 13" 2010; OS X 10.6.7; 2.4GHz Intel Core 2 Duo 64 bits
+-maceric: MacBook Pro 15" 2010 32 bits
+-ogive: Mac Pro 2008 32 bits
+-pleiades: AMES cluster
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/install.sh	(revision 18231)
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf source build install
+
+#Download code
+hg clone http://mercurial.mcs.anl.gov/ad/ADIC -r 631 source
+
+#Then update to -r 631
+cd source 
+hg update -r 631
+
+#Configure and Compile
+cd source
+./autogen.sh
+./aclocal
+cd ..
+mkdir build
+cd build
+../source/configure \
+	--with-rose=$ISSM_DIR/externalpackages/rose/install \
+	--with-openanalysis=$ISSM_DIR/externalpackages/openanalysis/openanalysis/x86_64-Linux \
+	--with-boost=$ISSM_DIR/externalpackages/boost/install \
+	--with-xerces=$ISSM_DIR/externalpackages/xerces/src \
+	--with-xaifbooster=$ISSM_DIR/externalpackages/xaifbooster/xaifBooster \
+	--with-colpack=$ISSM_DIR/externalpackages/colpack/install\
+	--prefix=$ISSM_DIR/externalpackages/adic/install 
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/tests/notes
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/tests/notes	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adic/tests/notes	(revision 18231)
@@ -0,0 +1,143 @@
+mini1.c is:
+7:37 PM
+#include <math.h>
+
+void mini1(double *y, double *x)
+{
+ int i;
+  for (i = 0; i < 2; i=i+1) {
+    y[i] = x[i] + sin(x[i]*x[i]);
+	 }
+	 }
+	 Eric Larour 7:37 PM 
+	 ok
+	 Sri Hari Krishna Narayanan 7:37 PM 
+	 If you cat any of  mini1_grad_length.ad.c mini1_dense_forward.ad.c mini1_sparse_forward.ad.c
+	 7:37 PM
+	 You should be able to see the forward mode output
+	 Eric Larour 7:38 PM 
+	 ok
+	 Sri Hari Krishna Narayanan 7:38 PM 
+	 First the makefile compiles mini1_grad_length.ad.c with a runtime library to estimate the number of columns in the Jacobian.
+	 Eric Larour 7:39 PM 
+	 ok, makes sense
+	 Sri Hari Krishna Narayanan 7:39 PM 
+	 That generates the output : ADIC_GRADVEC_LENGTH 2
+	 Eric Larour 7:39 PM 
+	 where?
+	 7:39 PM
+	 ok, sorry, got it
+	 Sri Hari Krishna Narayanan 7:40 PM 
+	 The value is also written to : runtime_dense/adic_gradvec_length.h
+	 Eric Larour 7:40 PM 
+	 where is the main for this?
+	 7:40 PM
+	 oh, it creates a .h directly
+	 Sri Hari Krishna Narayanan 7:40 PM 
+	 mini1_driver.c
+	 7:40 PM
+	 yes.
+	 7:40 PM
+	 The runtime library takes care of that
+	 7:40 PM
+	 There is alot or #defined compilation going on
+	 Eric Larour 7:41 PM 
+	 wraps around mini1_forward_array.exe ?
+	 Sri Hari Krishna Narayanan 7:41 PM 
+	 /*intermediary: */ creates mini1_grad_length.exe
+	 Eric Larour 7:41 PM 
+	 Isn't that the Makefile? what is the runtime library ?
+	 7:42 PM
+	 ok, the Makefile launches the runtime library
+	 Sri Hari Krishna Narayanan 7:42 PM 
+	 Makefile copies versions of the runtime library (bunch of macros in most cases)
+	 Eric Larour 7:42 PM 
+	 what is the name of the runtime library?
+	 Sri Hari Krishna Narayanan 7:43 PM 
+	 form $adicsrc/runtime/
+	 7:43 PM
+	 There are multiple versions
+	 Eric Larour 7:44 PM 
+	 ah, I see the grad_length dir
+	 7:44 PM
+	 is all that stuff compiled into adic2?
+	 Sri Hari Krishna Narayanan 7:44 PM 
+	 The one used to estimate the grad_lengh is :  $adicinstall/grad_length
+	 7:44 PM
+	 yes
+	 Eric Larour 7:44 PM 
+	 ok, makes sense
+	 Sri Hari Krishna Narayanan 7:45 PM 
+	 For the next step though
+	 7:45 PM
+	 the 'dense' case
+	 7:45 PM
+	 the runtime library cannot be precompiled
+	 7:45 PM
+	 the .h file has been created in the previous step
+	 7:46 PM
+	 So we copy the runtime/dense to the local directory
+	 Eric Larour 7:46 PM 
+	 because we can't guess the size of the gradient right?
+	 Sri Hari Krishna Narayanan 7:46 PM 
+	 and copy the .h into it
+	 7:46 PM
+	 correct
+	 Eric Larour 7:46 PM 
+	 nice
+	 Sri Hari Krishna Narayanan 7:46 PM 
+	 Then we compile it and create a .la file
+	 7:46 PM
+	 which is then linked to create mini1_dense_forward.exe
+	 7:47 PM
+	 When we run this, it also happens to run the analyticla derivates (the driver is built this way)
+	 7:47 PM
+	 Also diveded differences
+	 7:47 PM
+	 So you get the output:
+	 7:47 PM
+	 Analytic result is:       [1.968912]
+	 Analytic result is:     [1.968912]  
+	 DD result is:           [1.968997]      error {-8.45e-05}
+	 DD result is:           [1.968997]      error {-8.45e-05}
+	 AD result is:           [1.968912]      error {0.000000}
+	 AD result is:           [1.968912]      error {0.000000}
+	 7:48 PM
+	 The next step is to detect sparsity in the Jacobian and possibly compress it using Colpack (create a seed matrix).
+	 7:49 PM
+	 The gradient computation takes place on the compressed matrix.
+	 7:49 PM
+	 The output : ADIC_GRADVEC_LENGTH 1
+	 7:49 PM
+	 means that the seed matrix  has one column.
+	 7:50 PM
+	 After the calculation of the elements of the compressed matrix, it is then extracted to form the 'full Jacobian' (sorry if these tems are inexact).
+	 7:51 PM
+	 The extracted output is then printed out:
+	 7:51 PM
+	 AD result is:           [1.968912]
+	 AD result is:           [1.968912]
+	 7:51 PM
+	 And we are done!
+	 Eric Larour 7:51 PM 
+	 This is a lot for me to take in at once  I'm going to have to look through the makefile,
+	 7:51 PM
+	 and your explanations, and figure it out
+	 Sri Hari Krishna Narayanan 7:51 PM 
+	 Sure.
+	 Eric Larour 7:52 PM 
+	 I'll get back to you as soon as I have injested all of this
+	 Sri Hari Krishna Narayanan 7:52 PM 
+	 No problem.
+	 Eric Larour 7:52 PM 
+	 I'll probably have a million questions 
+	 Sri Hari Krishna Narayanan 7:52 PM 
+	 This is an exhaustive test
+	 7:52 PM
+	 FOr m ost purposes, we wil not need all of this
+	 Eric Larour 7:52 PM 
+	 this is really nice, I'm pretty exited !
+	 Sri Hari Krishna Narayanan 7:52 PM 
+	 Jean belives for example the the grad_length version is pointless. I find it interesting though.
+	 7:53 PM
+	 Okay. There are more interesting examples we can try
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+export C_INCLUDE_PATH=:/usr/include/sys/:$C_INCLUDE_PATH
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides-gcc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides-gcc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides-gcc.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-requestOnTrace CFLAGS="-g -O0"
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install-pleaides.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="/nasa/sgi/mpt/2.06rp16/" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adjoinablempi/install.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-macosx64.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+export CFLAGS="-O2 -L$ISSM_DIR/externalpackages/mpich/install/lib -lpmpich"
+export CXXFLAGS="-O2 -L$ISSM_DIR/externalpackages/mpich/install/lib -lpmpich"
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root=$ISSM_DIR/externalpackages/mpich/install \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+        --with-soname=adolc \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades-gcc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades-gcc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades-gcc.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root=$ISSM_DIR/externalpackages/mpich/install \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+        --with-soname=adolc \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi-pleiades.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root="/nasa/sgi/mpt/2.06rp16/" \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+        --with-soname=adolc \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install-withampi.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+ 
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root=$ISSM_DIR/externalpackages/mpich/install \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+	--with-soname=adolc \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/install.sh	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib 
+
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/install-2.2.0.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/install-2.2.0.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/install-2.2.0.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/update.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/update.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/old/update.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/update-existing.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/update-existing.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/adolc/update-existing.sh	(revision 18231)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#This script is very specific to the larour larsen nightly using adolc. 
+#It relies on just an update of adolc, and symlink to an existing adolc 
+#repo. 
+
+#Some cleanup
+rm -rf install src
+
+#symlink: 
+ln -s /proj/ice/larour2/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./src
+
+#update and compile
+cd src
+git pull origin
+git checkout ampi
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/android_aux.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/android_aux.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/android_aux.sh	(revision 18231)
@@ -0,0 +1,43 @@
+#!/bin/bash
+#
+# android_aux.sh serves as an auxiliary script for all installation
+# scripts with the Android suffix.
+#
+# TODO: include M4 macros for generic options.
+#
+
+sdk_rev=22.6.2
+ndk_rev=9
+api_levels="android-14,android-15,android-16"
+host_triplet="arm-linux-androideabi"
+default_droid="android-4.1"
+
+step=0;
+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 
+    if [[ "$arg" =~ --step=([0-9])* ]]; then
+        step=${BASH_REMATCH[1]}; 
+        echo "Setting step to: " $step
+    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/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/install.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+# This installs the Android NDK (Native Development Kit)
+# which is needed for the compilation of C/C++ code into the 
+# native architecture of the Android device.
+
+# The android-ndk-r8-darwin-x86.tar.bz2 ndk.tar.bz2 file was downloaded 
+# from the android developer website: 
+source $ANDROID_DIR/android_aux.sh
+
+if [[ $step == "1" || $step == "0" ]]; then
+    # Cleanup the install
+    rm -rf install
+    rm -rf $ANDROID_DIR/arm-linux-android-${default_droid}
+
+    # Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-ndk-r'${ndk_rev}'-darwin-x86.tar.bz2' 'ndk.tar.bz2'
+
+    # Untar
+    tar -zxvf ndk.tar.bz2
+    rm -rf ndk.tar ndk.tar.bz2
+
+    # Move to install
+    mv android-ndk-r${ndk_rev} install
+fi
+
+# Create Standalone Development Directory
+# Note: API-14 corresponds to Android 4.0.
+if [[ $step == "2" || $step == "0" ]]; then
+    $ANDROID_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/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/installNDK-linux-x86.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/installNDK-linux-x86.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-ndk/installNDK-linux-x86.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+# This installs the Android NDK (Native Development Kit)
+# which is needed for the compilation of C/C++ code into the 
+# native architecture of the Android device.
+
+# The android-ndk-r8-darwin-x86.tar.bz2 ndk.tar.bz2 file was downloaded 
+# from the android developer website: 
+source $ANDROID_DIR/android_aux.sh
+
+if [[ $step == "1" || $step == "0" ]]; then
+    # Cleanup the install
+    rm -rf install
+    rm -rf $ANDROID_DIR/arm-linux-android-${default_droid}
+
+    # Download from ISSM server
+#    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-ndk-r'${ndk_rev}'-darwin-x86.tar.bz2' 'ndk.tar.bz2'
+    # Download from google
+#    if ["$(uname -m)" = "x86_64"]; then
+#	wget 'https://dl.google.com/android/ndk/android-ndk-r'${ndk_rev}'d-linux-x86_64.tar.bz2' 'ndk.tar.bz2'
+#   fi
+
+#    if ["$(uname -m)" = "x86"]; then
+	wget 'https://dl.google.com/android/ndk/android-ndk-r'${ndk_rev}'d-linux-x86.tar.bz2'
+ #   fi
+    # Install Android NDK
+    mv 'android-ndk-r'${ndk_rev}'d-linux-x86.tar.bz2' ndk.tar.bz2
+    tar -xvf ndk.tar.bz2
+    rm -rf ndk.tar ndk.tar.bz2
+
+    # Move to install
+    mv android-ndk-r${ndk_rev}d install
+fi
+
+# Create Standalone Development Directory
+# Note: API-14 corresponds to Android 4.0.
+if [[ $step == "2" || $step == "0" ]]; then
+    $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/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/install.sh	(revision 18231)
@@ -0,0 +1,82 @@
+#!/bin/bash
+
+# This installs the Android SDK (Software Development Kit)
+# which is needed for the compilation of the Java project. 
+
+source $ANDROID_DIR/android_aux.sh
+
+# Different steps here. 
+#   0: do all
+#   1: install sdk, ant and sdk tools
+#   2: install an emulator.
+#   3: test the emulator
+#   4: cleanup
+
+present_dir=`pwd`;
+sd_card="issm-sdcard"
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+	# Cleanup the install
+	rm -rf install
+
+	# Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-sdk_r'$sdk_rev'-macosx.zip' 'android-sdk_r'${sdk_rev}'-macosx.zip'
+
+	# Install Android SDK and NDK.
+	unzip -o android-sdk_r${sdk_rev}-macosx.zip
+
+	# Move to install
+	mv -f android-sdk-macosx install
+
+	# Post_install configuration: 
+	# We need specific settings for specific platforms, for the SDK to 
+	# function properly
+
+	# For now, we need to install:  
+	# android sdk platform tools  
+	# and a specific android api: API 16, API 15 and API 14
+	# Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
+
+	cd install/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
+
+fi
+
+if [[ $step == "2" || $step == "0" ]]; then
+
+	# Once this is done, we need to install an emulator. Location will default to ~/.android/avd, 
+	# which we will move to $ISSM_DIR/externalpackages/android-emulators.  
+	# For now, it's called: Android-4.0.3
+
+	# Here we delete the Android-4.0.3 device if it already exists.
+	cd $present_dir/install/tools
+
+    if [ -e $ANDROID_DIR/android-emulators/$default_droid ] 
+    then
+        echo "Deleting previously created device: $default_droid"
+	    ./android delete avd -n $default_droid
+    fi
+
+	# Android will prompt the user to specify hardware emulation options. For now, default
+	# default settings will suffice. Press 'enter' to take default settings or enter 'no'.
+
+	./android create avd -f -n $default_droid -t 1 -p $ANDROID_DIR/android-emulators/$default_droid --abi armeabi-v7a
+    echo "Creating an SD Card"
+    ./mksdcard -l $sd_card 2G $ANDROID_DIR/android-emulators/$sd_card.img
+fi
+
+if [[ $step == "3" || $step == "0" ]]; then
+    # Here we will start up our default emulator to test that it is working properly.
+    # Once the device has booted we will use the Android Debug Bridge tool to gain
+    # a terminal in our device.
+
+	cd $present_dir/install/tools
+	./emulator -avd $default_droid -sdcard $ANDROID_DIR/android-emulators/$sd_card.img &
+
+    cd ../platform-tools
+    ./adb wait-for-device shell
+fi
+
+if [[ $step == "4" || $step == "0" ]]; then
+	rm -rf install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/installSDK-linux-x86.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/installSDK-linux-x86.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android-sdk/installSDK-linux-x86.sh	(revision 18231)
@@ -0,0 +1,85 @@
+#!/bin/bash
+
+# This installs the Android SDK (Software Development Kit)
+# which is needed for the compilation of the Java project. 
+
+source $ANDROID_DIR/android_aux.sh
+
+# Different steps here. 
+#   0: do all
+#   1: install sdk, ant and sdk tools
+#   2: install an emulator.
+#   3: test the emulator
+#   4: cleanup
+
+present_dir=`pwd`;
+sd_card="issm-sdcard"
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+	# Cleanup the install
+	rm -rf install
+
+	# Download from ISSM server
+#	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://developer.android.com/sdk/index.html#download' 'android-sdk-linux.zip'
+	
+	#Download from Google server
+	wget https://dl.google.com/android/android-sdk_r$sdk_rev-linux.tgz
+
+	# Install Android SDK.
+	tar -zxvf android-sdk_r$sdk_rev-linux.tgz
+	rm -rf android-sdk_r$sdk_rev-linux.tgz
+	# Move to install
+	mv -f android-sdk-linux install
+
+	# Post_install configuration: 
+	# We need specific settings for specific platforms, for the SDK to 
+	# function properly
+
+	# For now, we need to install:  
+	# android sdk platform tools  
+	# and a specific android api: API 16, API 15 and API 14
+	# Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
+
+	cd install/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
+
+fi
+
+if [[ $step == "2" || $step == "0" ]]; then
+
+	# Once this is done, we need to install an emulator. Location will default to ~/.android/avd, 
+	# which we will move to $ISSM_DIR/externalpackages/android-emulators.  
+	# For now, it's called: Android-4.0.3
+
+	# Here we delete the Android-4.0.3 device if it already exists.
+	cd $present_dir/install/tools
+
+    if [ -e $ANDROID_DIR/android-emulators/$default_droid ] 
+    then
+        echo "Deleting previously created device: $default_droid"
+	    ./android delete avd -n $default_droid
+    fi
+
+	# Android will prompt the user to specify hardware emulation options. For now, default
+	# default settings will suffice. Press 'enter' to take default settings or enter 'no'.
+
+	./android create avd -f -n $default_droid -t 1 -p $ANDROID_DIR/android-emulators/$default_droid --abi armeabi-v7a
+    echo "Creating an SD Card"
+    ./mksdcard -l $sd_card 2G $ANDROID_DIR/android-emulators/$sd_card.img
+fi
+
+if [[ $step == "3" || $step == "0" ]]; then
+    # Here we will start up our default emulator to test that it is working properly.
+    # Once the device has booted we will use the Android Debug Bridge tool to gain
+    # a terminal in our device.
+
+	cd $present_dir/install/tools
+	./emulator -avd $default_droid -sdcard $ANDROID_DIR/android-emulators/$sd_card.img &
+
+    cd ../platform-tools
+    ./adb wait-for-device shell
+fi
+
+#if [[ $step == "4" || $step == "0" ]]; then
+#	rm -rf install
+#fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android_aux.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android_aux.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/android/android_aux.sh	(revision 18231)
@@ -0,0 +1,43 @@
+#!/bin/bash
+#
+# android_aux.sh serves as an auxiliary script for all installation
+# scripts with the Android suffix.
+#
+# TODO: include M4 macros for generic options.
+#
+
+sdk_rev=20
+ndk_rev=8
+api_levels="android-14,android-15,android-16"
+host_triplet="arm-linux-androideabi"
+default_droid="android-4.1"
+
+step=0;
+j=1;
+
+echo ""
+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 
+    if [[ "$arg" =~ --step=([0-9])* ]]; then
+        step=${BASH_REMATCH[1]}; 
+        echo "Setting step to: " $step
+    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/branches/trunk-jpl-ad2-integrated/externalpackages/angel/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/angel/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/angel/install.sh	(revision 18231)
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf angel
+
+#download 
+svn co -r 82 https://angellib.svn.sourceforge.net/svnroot/angellib/trunk angel
+
+#Compile
+cd angel 
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/bin/genouncemakePFile.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/bin/genouncemakePFile.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/bin/genouncemakePFile.sh	(revision 18231)
@@ -0,0 +1,593 @@
+#!/bin/bash
+
+#----------------------------------------------------------------------
+#VARIABLES containing information to generate OunceMake Properties file
+#----------------------------------------------------------------------
+XMLHEADER="<?xml version=\""1.0\"" encoding=\"UTF-8\"?>"
+OUNCEHEADER="<OunceMakeProperties xmlns=\"http://www.ouncelabs.com/namespace\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+MAKEOPT="<MakeOptions>-f Makefile</MakeOptions>"
+
+COMPILER_TAG="Compiler"
+COMPILER_MACRO="macro"
+
+C_COMPILER_MVALUE="\"CC\""
+CPP_COMPILER_MVALUE="\"CXX\""
+
+MAKE_TAG="Make"
+MAKE_MACRO="macro"
+MAKE_MVALUE="\"MAKE\""
+
+
+LINKER_TAG="Linker"
+LINKER_MACRO="macro"
+LINKER_MVALUE="\"LD\""
+
+
+ARCHIVE_TAG="Executable"
+ARCHIVE_MACRO="macro"
+ARCHIVE_MVALUE="\"ARCHIVE\""
+
+OUNCEOPT="<Options recursive=\"true\" single_project=\"false\" verbose=\"false\" clean=\"make clean\" no_clean=\"false\" build=\"true\"/>"
+
+OUNCE_MAIN_TAG="OunceMakeProperties"
+OUNCE_COMPILER_GPO_TAG="GlobalProjectOptions"
+OUNCE_COMPILER_OPT="compiler_options"
+OUNCE_COMPILER_OPT_gpp="\"-g++_linux_i386\""
+OUNCE_COMPILER_OPT_gcc="\"-gcc_linux_i386\""
+
+OUNCE_INCLUDE_PATH="include_paths"
+OUNCE_MACRO_PATH="macros"
+
+OUNCE_COMPILER_FO_TAG="FileOptions"
+OUNCE_COMPILER_EXT="extensions"
+
+OUNCE_COMPILER_EXT_CPP="cpp;cxx"
+OUNCE_COMPILER_EXT_C="c"
+
+#Did the search for a particular tool pass/fail
+FAIL_FILE="failed.status"
+
+#---------------------------------
+#COMPILER data extraction function
+#---------------------------------
+
+function initialize {
+#Create Directory for info
+ echo;echo
+ echo -e "Initialization....\t\t\t[\c "
+ echo -e "\E[33mSTARTED\c "; tput sgr0
+ echo "]"
+ search_tool which
+ FILEPRE=${1}
+
+ case "$1" in
+	"gcc"|"cc")
+	  TESTFILE="testfoo.c"
+	;;
+	"g++"|"CC")
+	  TESTFILE="testfoo.cpp"
+	;;
+	*)
+	 echo "Error setting prefix"
+	;;
+ esac
+
+ DATAFOLDER="${FILEPRE}results"
+#Declare files to generate and store results
+ RESULTFILE="${DATAFOLDER}/${FILEPRE}libinc.result"
+ SLIMFILE="${DATAFOLDER}/${FILEPRE}slim.inc"
+ SLIM2FILE="${DATAFOLDER}/${FILEPRE}slim2.inc"
+
+#Declare the Tags that enclose the information needed
+ START_TAG="#include <...> search starts here:"
+ END_TAG="End of search list."
+
+#Declare Variable to track Tags
+ MARK_FOUND=0
+
+#For Macros
+ MACROSDUMPFILE="${DATAFOLDER}/${FILEPRE}macrosd.result"
+ INTFILE1="${DATAFOLDER}/${FILEPRE}interf1.result"
+ INTFILE2="${DATAFOLDER}/${FILEPRE}interf2.result"
+
+
+#The file extensions for (both) options
+CONFIG_FOLDER="config"
+C_EXT="${CONFIG_FOLDER}/cext.data"
+CPP_EXT="${CONFIG_FOLDER}/cppext.data"
+
+if [ -d ${CONFIG_FOLDER} ]; then
+	echo
+else
+	mkdir ${CONFIG_FOLDER}
+	echo ${OUNCE_COMPILER_EXT_CPP} > ${C_EXT}
+	echo ${OUNCE_COMPILER_EXT_C} > ${CPP_EXT}
+fi
+
+ echo -e "Initialization....\t\t\t[\c "
+ echo -e "\E[33mDONE\c "; tput sgr0
+ echo "]"
+}
+
+function purgefiles {
+ echo -e "Purging files....\t\t\t[\c "
+ echo -e "\E[33mSTARTED\c "; tput sgr0
+ echo "]"
+  if [ -e ${DATAFOLDER} ]; then
+	rm -R ${DATAFOLDER}
+	mkdir ${DATAFOLDER}
+  else
+	mkdir ${DATAFOLDER}
+  fi
+ echo -e "Purging files....\t\t\t[\c "
+ echo -e "\E[33mDONE\c "; tput sgr0
+ echo "]"
+}
+
+
+function processGNUInclude {
+echo
+#Create the dummy file is does not exist
+if [ -e ${TESTFILE} ]; then
+	echo "Will use an existing ${TESTFILE} file"
+else 
+	echo -e "int main(){\n return 0;\n}" &>  ${TESTFILE}
+	if [ -e ${TESTFILE} ]; then
+	  echo -e "Generating new test file\t\t[\c "
+	  echo -e "\E[31m${TESTFILE}\c " ; tput sgr0 
+	  echo "]"
+	else
+	  echo -e "Error generating new test file\t\t[\c "
+	  echo -e "\E[31m${TESTFILE}\c " ; tput sgr0 
+	  echo "]"
+   	#TO DO
+   	#Will the user like to continue or exit?
+	fi
+fi
+
+
+ echo
+ echo -e "Generating information for Compiler\t\t[\c "
+ echo -e "\E[31m${COMPILER}\c " ; tput sgr0 
+ echo "]"
+
+${COMPILER} -v ${TESTFILE} &> ${RESULTFILE}
+
+
+cat ${RESULTFILE} | while read line
+do 
+
+	if [ "${line}" = "${START_TAG}" ] 
+	then
+		MARK_FOUND=1
+	fi
+
+	
+	if [ "${line}" = "${END_TAG}" ] 
+	then
+		MARK_FOUND=0
+	fi
+
+	
+	if [ "${MARK_FOUND}" = 1 ] && [ "${line}" != "${START_TAG}" ] 
+	then
+		let "inclib +=  1"
+		echo ${line} 1>> ${SLIMFILE}
+	fi
+done
+
+if [ -e ${SLIMFILE} ]; then
+	sed -e :a -e N -e 's/\n/; /' -e ta  ${SLIMFILE}  > ${RESULTFILE}
+	echo -e "Inc & Lib results are in file...\t\t[\c "
+	echo -e "\033[1m\E[31m${RESULTFILE}\033[0m\c " ; tput sgr0
+	echo "]"
+fi
+
+#String to contatenate the include path
+concatpath="include_paths=\""
+#Merge file content
+sed -e 's/\n/;/'  ${SLIMFILE} > ${SLIM2FILE}
+
+}
+
+
+function processGNUMacro {
+#*****************************
+#Generate macros for system
+#*****************************
+ echo
+ echo -e "Generating Macro data for Compiler\t\t[\c "
+ echo -e "\E[31m${COMPILER} \c " ; tput sgr0 
+ echo "]"
+
+ ${COMPILER} -dM -E ${TESTFILE} >> ${MACROSDUMPFILE}
+ sed 's/#define //' ${MACROSDUMPFILE} > ${INTFILE1}
+ if [ -e ${INTFILE1} ]; then
+	sed 's/ /=/' ${INTFILE1} > ${INTFILE2}
+ else
+	echo -e "\033[1m Sorry <${INTFILE1}> was not created.. \033[0m"
+ fi
+
+ if [ -e ${INTFILE2} ]; then
+	#Remove the Macro's that have no values
+	sed '/^_.*=$/d' ${INTFILE2} > ${INTFILE1} 
+	#Join the individual line and delimit with a (; )
+	sed -e :a -e N  -e 's/\n/; /' -e ta  ${INTFILE1}  > ${MACROSDUMPFILE}
+	#All done display the results file
+	echo -e "Macro results are in file...\t\t\t[\c "
+	echo -e "\033[1m\E[31m${MACROSDUMPFILE}\033[0m\c " ; tput sgr0
+	echo "]"
+ else
+	echo -e "\033[1m Sorry <${MACROSDUMPFILE}> was not created.. \033[0m"
+ fi
+}
+
+function processSUNMacro {
+#*******************************************
+#This function is for the SUN Compilers ONLY
+#*******************************************
+ echo
+ echo -e "Generating Macro data for Compiler\t\t[\c "
+ echo -e "\E[31m${COMPILER} \c " ; tput sgr0 
+ echo "]"
+
+ ${COMPILER} -xdumpmacros ${TESTFILE} &> ${MACROSDUMPFILE}
+ sed 's/#define //' ${MACROSDUMPFILE} > ${INTFILE1}
+ if [ -e ${INTFILE1} ]; then
+	sed 's/ /=/' ${INTFILE1} > ${INTFILE2}
+ else
+	echo -e "\033[1m Sorry <${INTFILE1}> was not created.. \033[0m"
+ fi
+
+ if [ -e ${INTFILE2} ]; then
+	#Remove the Macro's that have no values
+	sed '/^_.*=$/d' ${INTFILE2} > ${INTFILE1} 
+	#Join the individual line and delimit with a (; )
+	sed -e :a -e N  -e 's/\n/; /' -e ta  ${INTFILE1}  > ${MACROSDUMPFILE}
+	#All done display the results file
+	echo -e "Macro results are in file...\t\t\t[\c "
+	echo -e "\033[1m\E[31m${MACROSDUMPFILE}\033[0m\c " ; tput sgr0
+	echo "]"
+ else
+	echo -e "\033[1m Sorry <${MACROSDUMPFILE}> was not created.. \033[0m"
+ fi
+}
+
+#--------------------------
+#DATA Processing variables
+#--------------------------
+PROPFILE="ouncemake_properties.xml"
+PROBEFILE="probe.results"
+ERRORLOG="error.log"
+
+#---------------------------------------
+#FUNCTION TO CREATE FILE
+#--------------------------------------
+
+function create_file {
+#If a previous copy of file exist, delete it
+if [ -e ${PROPFILE} ]; then
+	rm ${PROPFILE}
+fi
+
+echo;echo
+echo "CREATING THE PROPERTIES XML FILE"
+#insert file headers
+echo ${XMLHEADER} >> ${PROPFILE}
+echo ${OUNCEHEADER} >> ${PROPFILE}
+echo ${MAKEOPT} >> ${PROPFILE}
+case "${1}" in
+	'gcc')
+	  search_tool gcc
+	;;
+	'g++')
+	  search_tool g++
+	;;
+	'bothGNU')
+	  search_tool gcc
+	  search_tool g++
+	;;
+	'cc')
+	  search_tool cc
+	;;
+	'CC')
+	  search_tool CC
+	;;
+	'bothSUN')
+	  search_tool gcc
+	  search_tool g++
+	;;
+	'*')
+	;;
+esac
+search_tool make
+search_tool ld
+search_tool ar
+echo "	${OUNCEOPT}" >> ${PROPFILE}
+
+case "${1}" in
+	'gcc')
+	  singleGNUC gcc
+	;;
+	'g++')
+	  singleGNUC g++
+	;;
+	'bothGNU')
+	  bothGNUC gcc
+	  bothGNUC g++
+	;;
+	'cc')
+	  singleSUNC cc
+	;;
+	'CC')
+	  singleSUNC CC
+	;;
+	'bothSUN')
+	  bothSUNC cc
+	  bothSUNC CC
+	;;
+	'*')
+	;;
+esac
+
+echo "</${OUNCE_MAIN_TAG}>" >> ${PROPFILE}
+
+echo
+echo -e "Successully created Properties file\t\t[\c "
+echo -e "\033[1m\E[31m${PROPFILE}\033[0m\c " ; tput sgr0
+echo "]"
+echo
+}
+
+#when the system is unable to locate the tool
+#the user is prompted to provide that information
+function usersupplypath {
+	echo "Please provide the path to ${1}."
+	read TOOLPATH
+}
+
+
+function search_tool {
+which $1 &> ${PROBEFILE}
+#Why this approach? I had to be able to non-interactively  
+#know if the pattern was successfully found. 
+
+sed -n -e "/.*no[ ]${1}[ ]in[ ].*/w $FAIL_FILE" ${PROBEFILE} 
+
+#If the file is empty, the process PASSED
+#else the Fail criteria was found. Process FAILED
+if [ -e ${FAIL_FILE} ]; then
+	exec < ${FAIL_FILE}
+	read FAILPASS
+	if [${FAILPASS} = ""]; then
+	  SEARCHTOOL="PASSED"
+	  rm ${FAIL_FILE}
+	else
+	 SEARCHTOOL="FAILED"
+	fi
+fi
+
+
+if [ ${SEARCHTOOL} == "FAILED" ] ; then
+  echo "Failed to find ${1} in PATH" >> ${ERRORLOG}
+  echo -e "check for $1 in ${TLOC}\t\t\t[$SEARCHTOOL]"
+elif [ ${SEARCHTOOL} == "PASSED" ]; then
+  #Redirects stdin to a file so that
+  exec < ${PROBEFILE}
+  #I can read line by line
+  read TLOC
+  echo -e "check for $1 in ${TLOC}\t\t\t[\c "
+  echo -e "\E[33m${SEARCHTOOL}\c "; tput sgr0
+  echo "]"
+else
+  echo "Unable to process the request"
+  #exit
+fi
+
+case "$1" in
+	'gcc')
+	#set up the sub strings 
+	  TAG_L="<${COMPILER_TAG} ${COMPILER_MACRO}=${C_COMPILER_MVALUE}>"
+	  MVALUE="$TLOC"
+	  TAG_R="</${COMPILER_TAG}>"
+	;;
+	'g++')
+	  TAG_L="<${COMPILER_TAG} ${COMPILER_MACRO}=${CPP_COMPILER_MVALUE}>"
+	  MVALUE="$TLOC"
+	  TAG_R="</${COMPILER_TAG}>"
+	;;
+	'make')
+	  TAG_L="<${MAKE_TAG} ${MAKE_MACRO}=${MAKE_MVALUE}>"
+	  MVALUE="$TLOC"
+	  TAG_R="</${MAKE_TAG}>"
+	;;
+	'ld')
+	  TAG_L="<${LINKER_TAG} ${LINKER_MACRO}=${LINKER_MVALUE}>"
+	  MVALUE="$TLOC"
+	  TAG_R="</${LINKER_TAG}>"
+	;;
+	'ar')
+	  TAG_L="<${ARCHIVE_TAG} ${ARCHIVE_MACRO}=${ARCHIVE_MVALUE}>"
+	  MVALUE="$TLOC"
+	  TAG_R="</${ARCHIVE_TAG}>"
+	;;
+	'*')
+	;;	
+esac
+
+#then concatenate
+FULL_STRING="${TAG_L}${MVALUE}${TAG_R}"
+#and store in file
+echo "	$FULL_STRING" >> ${PROPFILE}
+}
+function singleGNUC {
+
+echo "	<${OUNCE_COMPILER_GPO_TAG}" >> ${PROPFILE}
+
+case "$1" in 
+	'gcc')
+	  echo -e "\t  ${OUNCE_COMPILER_OPT}=${OUNCE_COMPILER_OPT_gcc}" >> ${PROPFILE}
+	;;
+	'g++')
+	  echo -e "\t  ${OUNCE_COMPILER_OPT}=${OUNCE_COMPILER_OPT_gpp}" >> ${PROPFILE}
+	;;
+	'*')
+	;;	
+esac
+
+exec < ${RESULTFILE}
+read INCLUDE_DATA
+echo -e "\t  ${OUNCE_INCLUDE_PATH}=\"${INCLUDE_DATA}\"" >> ${PROPFILE}
+exec < ${MACROSDUMPFILE}
+read MACRO_DATA
+#Using single quotes to wrap double quotes in data
+echo -e "\t  ${OUNCE_MACRO_PATH}='${MACRO_DATA}' />" >> ${PROPFILE}
+
+}
+
+
+function bothGNUC {
+
+echo -e "\t<${OUNCE_COMPILER_FO_TAG}" >> ${PROPFILE}
+
+case "$1" in 
+	'gcc')
+	  FILEPRE="$1"
+	  exec < ${C_EXT}
+	  read CEXTENSIONS
+	  if [ ${CEXTENSIONS} = "" ]; then
+	  	CEXTENSIONS=${OUNCE_COMPILER_EXT_C}
+	  else
+		OUNCE_COMPILER_EXT_C=${CEXTENSIONS}
+	  fi
+	  echo -e "\t  ${OUNCE_COMPILER_EXT}=\"${OUNCE_COMPILER_EXT_C}\"" >> ${PROPFILE}
+	;;
+	'g++')
+	  FILEPRE="$1"
+	  exec < ${CPP_EXT}
+	  read CPPEXTENSIONS
+	  if [ ${CPPEXTENSIONS} = "" ]; then
+	  	CPPEXTENSIONS=${OUNCE_COMPILER_EXT_CPP}
+	  else
+		OUNCE_COMPILER_EXT_CPP=${CPPEXTENSIONS}
+	  fi
+	  echo -e "\t  ${OUNCE_COMPILER_EXT}=\"${OUNCE_COMPILER_EXT_CPP}\"" >> ${PROPFILE}
+	;;
+	'*')
+	;;	
+esac
+
+#To make sure that the correct folder and file is read
+DATAFOLDER="${FILEPRE}results"
+#Declare files to generate and store results
+RESULTFILE="${DATAFOLDER}/${FILEPRE}libinc.result"
+
+exec < ${RESULTFILE}
+read INCLUDE_DATA
+echo -e "\t  ${OUNCE_INCLUDE_PATH}=\"${INCLUDE_DATA}\"" >> ${PROPFILE}
+exec < ${MACROSDUMPFILE}
+read MACRO_DATA
+echo -e "\t  ${OUNCE_MACRO_PATH}='${MACRO_DATA}'/>" >> ${PROPFILE}
+
+}
+
+
+clear
+echo
+echo -e "\t \E[34m\033[1mOUNCEMAKE PROPERTIES FILE GENERATOR (1.0)b\033[0m";tput sgr0
+
+#Start of the program
+case "$1" in
+	'-t')
+	  case "$2" in 
+		"gcc")
+		  COMPILER=${2}
+		 initialize ${2}
+		 purgefiles
+		 processGNUInclude
+		 processGNUMacro
+		 create_file ${2}
+		;;
+		"g++")
+		  COMPILER=${2}
+		 initialize ${2}
+		 purgefiles
+		 processGNUInclude
+		 processGNUMacro
+		 create_file ${2}
+		;;
+		"bothGNU")
+		  COMPILER="gcc"
+		 initialize ${2}
+		 purgefiles
+		 processGNUInclude
+		 processGNUMacro
+		  COMPILER="g++"
+		 initialize ${2}
+		 purgefiles
+		 processGNUInclude
+		 processGNUMacro
+		 create_file ${2}
+		;;
+		"cc")
+		  COMPILER=${2}
+		 initialize ${2}
+		 purgefiles
+		 processSUNInclude
+		 processSUNMacro
+		 create_file ${2}
+		;;
+		"CC")
+		  COMPILER=${2}
+		 initialize ${2}
+		 purgefiles
+		# processSUNInclude
+		 processSUNMacro
+		# create_file ${2}
+		;;
+		"bothSUN")
+		  COMPILER="cc"
+		 initialize cc
+		 purgefiles
+		 processSUNInclude
+		 processSUNMacro
+		  COMPILER="CC"
+		 initialize CC
+		 purgefiles
+		 processSUNInclude
+		 processSUNMacro
+		 create_file both
+		;;
+		'*')
+		  echo "Usage: -t [gcc|g++|bothGNU]"
+		  exit $?
+		;;
+	  esac  
+	;;
+	'-h')
+	  echo -e "Usage: -t [Options] -v "
+	  echo -e "Options:"
+	  echo -e "\t[gcc]\tC project only";
+	  echo -e "\t[g++]\tCPP project only"
+	  echo -e "\t[bothGNU]\tMixed C and CPP project"
+	  echo
+	  echo -e "\t-v \tDisplay version information"
+	  exit $?
+	;;
+	'-v')
+	  echo "Version 1.0 beta"
+	  exit $?
+	;;
+	*)
+	  echo -e "Usage: -t [Options] -v "
+	  echo -e "Options:"
+	  echo -e "\t[gcc]\tC project only";
+	  echo -e "\t[g++]\tCPP project only"
+	  echo -e "\t[both]\tMixed C and CPP project"
+	  echo
+	  echo -e "\t-v \tDisplay version information"
+	  exit $?
+	;;
+esac
+echo "[ P R O C E S S  C O M P L E T E !!! ]"
+echo
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/hostname
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/hostname	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/hostname	(revision 18231)
@@ -0,0 +1,1 @@
+jplsec-codescan.jpl.nasa.gov
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/appscan/install.sh	(revision 18231)
@@ -0,0 +1,10 @@
+#!/bin/bash
+set -eu
+
+#AppScan install directory. Just symlink to your existing AppScan software
+
+#Erase symlink
+rm -rf install
+
+#Select or create a new simlink
+ln -s /opt/IBM/AppScan_Source ./install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr-util/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr-util/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr-util/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-util-1.4.1
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-util-1.4.1.tar.gz' 'apr-util-1.4.1.tar.gz'
+
+#Untar 
+tar -zxvf  apr-util-1.4.1.tar.gz
+
+#Move apr-util into src directory
+mv apr-util-1.4.1/* src
+rm -rf apr-util-1.4.1
+
+#Configure apr-util
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr-util/install" --with-apr="$ISSM_DIR/externalpackages/apr/install"
+
+#Compile and install apr-util
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/apr/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-1.4.6
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-1.4.6.tar.gz' 'apr-1.4.6.tar.gz'
+
+#Untar 
+tar -zxvf  apr-1.4.6.tar.gz
+
+#Move apr into src directory
+mv apr-1.4.6/* src
+rm -rf apr-1.4.6
+
+#Configure apr
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr/install" 
+
+#Compile and install apr
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/aspell/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/aspell/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/aspell/install.sh	(revision 18231)
@@ -0,0 +1,62 @@
+#!/bin/bash
+set -eu
+
+#0: cleanup
+#1:  install aspell
+#2:  install en dictionary
+step=2
+
+
+#Some cleanup
+if  [[ $step  == "0" ]]; then
+	rm -rf src install dicts
+	rm -rf aspell-0.50.5
+	rm -rf aspell5-en-6.0.0
+fi
+
+#install aspell
+if  [[ $step  == "1" ]]; then
+
+	mkdir src install dicts
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/aspell-0.50.5.tar.gz' 'aspell-0.50.5.tar.gz'
+
+	#Untar 
+	tar -zxvf  aspell-0.50.5.tar.gz
+
+	#Move aspell into src directory
+	mv aspell-0.50.5/* src
+	rm -rf aspell-0.50.5
+
+	#Configure aspell
+	cd src
+	./configure \
+		--prefix="$ISSM_DIR/externalpackages/aspell/install" \
+
+	#Compile and install aspell
+	if [ -z $1 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install
+fi
+
+#languages
+if  [[ $step  == "2" ]]; then
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/aspell5-en-6.0.0.tar.gz' 'aspell5-en-6.0.0.tar.gz'
+
+	#Untar 
+	tar -zxvf  aspell5-en-6.0.0.tar.gz
+
+	#Move aspell into src directory
+	mv aspell5-en-6.0.0 dicts
+
+	#install
+	cd dicts/aspell5-en-6.0.0
+	./configure
+	make install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/atlas/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/atlas/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/atlas/install.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install ATLAS build
+mkdir src install build
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/atlas3.10.0.tar.bz2' 'atlas3.10.0.tar.bz2'
+
+#Untar 
+tar -zxvf  atlas3.10.0.tar.bz2
+
+#Move atlas into src directory
+mv ATLAS/* src
+rm -rf ATLAS
+
+#Configure atlas
+cd build
+
+export CFLAGS=" -arch x86_64"
+
+../src/configure \
+	--prefix="$ISSM_DIR/externalpackages/atlas/install" 
+
+#Compile atlas
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install-win.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install-win.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install-win.sh	(revision 18231)
@@ -0,0 +1,46 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+mkdir install
+
+export PATH="$ISSM_DIR/externalpackages/autotools/install/bin:$PATH"
+
+#install autoconf
+echo " === INSTALLING AUTOCONF =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.68.tar.gz' 'autoconf-2.68.tar.gz'
+tar -zxvf autoconf-2.68.tar.gz
+mv autoconf-2.68 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install automake
+echo " === INSTALLING AUTOMAKE =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.11.3.tar.gz' 'automake-1.11.3.tar.gz'
+tar -zxvf  automake-1.11.3.tar.gz
+mv automake-1.11.3 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install libtool
+echo " === INSTALLING LIBTOOL =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool-2.4.2.tar.gz' 'libtool-2.4.2.tar.gz'
+tar -zxvf  libtool-2.4.2.tar.gz
+rm libtool-2.4.2.tar.gz
+mv libtool-2.4.2 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+patch ./install/share/aclocal/libtool.m4 < ./patches/libtool.m4.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/install.sh	(revision 18231)
@@ -0,0 +1,44 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+mkdir install
+
+export PATH="$ISSM_DIR/externalpackages/autotools/install/bin:$PATH"
+
+#install autoconf
+echo " === INSTALLING AUTOCONF =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.69.tar.gz' 'autoconf-2.69.tar.gz'
+tar -zxvf autoconf-2.69.tar.gz
+mv autoconf-2.69 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install automake
+echo " === INSTALLING AUTOMAKE =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.14.tar.gz' 'automake-1.14.tar.gz'
+tar -zxvf  automake-1.14.tar.gz
+mv automake-1.14 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install libtool
+echo " === INSTALLING LIBTOOL =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool-2.4.2.tar.gz' 'libtool-2.4.2.tar.gz'
+tar -zxvf  libtool-2.4.2.tar.gz
+rm libtool-2.4.2.tar.gz
+mv libtool-2.4.2 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/patches/libtool.m4.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/patches/libtool.m4.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/autotools/patches/libtool.m4.patch	(revision 18231)
@@ -0,0 +1,38 @@
+--- m4/libtool.m4	2013-06-19 22:19:27.313488900 -0700
++++ m4/libtool.m4.bak	2013-06-18 18:45:55.766285300 -0700
+@@ -4752,7 +4752,7 @@
+       _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+ 
+       if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++        _LT_TAGVAR(archive_cmds, $1)='$CC /LD $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	# If the export-symbols file already is a .def file (1st line
+ 	# is EXPORTS), use it as is; otherwise, prepend...
+ 	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+@@ -4761,7 +4761,7 @@
+ 	  echo EXPORTS > $output_objdir/$soname.def;
+ 	  cat $export_symbols >> $output_objdir/$soname.def;
+ 	fi~
+-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	$CC /LD $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+       else
+ 	_LT_TAGVAR(ld_shlibs, $1)=no
+       fi
+@@ -6168,7 +6168,7 @@
+ 	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ 
+ 	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	    _LT_TAGVAR(archive_cmds, $1)='$CC /LD -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	    # If the export-symbols file already is a .def file (1st line
+ 	    # is EXPORTS), use it as is; otherwise, prepend...
+ 	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+@@ -6177,7 +6177,7 @@
+ 	      echo EXPORTS > $output_objdir/$soname.def;
+ 	      cat $export_symbols >> $output_objdir/$soname.def;
+ 	    fi~
+-	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	    $CC /LD -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	  else
+ 	    _LT_TAGVAR(ld_shlibs, $1)=no
+ 	  fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bbftp/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bbftp/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bbftp/install.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install bbftp-client-3.2.0
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/bbftp-client-3.2.0.tar.gz' 'bbftp-client-3.2.0.tar.gz'
+
+#Create install directories
+mkdir install src
+
+#Untar 
+tar -zxvf  bbftp-client-3.2.0.tar.gz
+
+#Move bbftp-client into install directory
+mv bbftp-client-3.2.0/* src
+rm -rf bbftp-client-3.2.0
+
+#Apply patches
+cd src 
+
+#Configure and compile
+cd bbftpc
+./configure --prefix=$ISSM_DIR/externalpackages/bbftp/install
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/linux64/make.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/linux64/make.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/linux64/make.inc	(revision 18231)
@@ -0,0 +1,34 @@
+####################################################################
+#  BLAS make include file.                                         #
+#  March 2007                                                      #
+####################################################################
+#
+SHELL = /bin/sh
+#
+#  The machine (platform) identifier to append to the library names
+#
+PLAT = _LINUX
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran
+OPTS     = -fPIC -O3
+DRVOPTS  = $(OPTS)
+NOOPT    =
+LOADER   = gfortran
+LOADOPTS =
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  The location and name of the Reference BLAS library.
+#
+BLASLIB      = blas$(PLAT).a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/macosx64/make.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/macosx64/make.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/configs/macosx64/make.inc	(revision 18231)
@@ -0,0 +1,34 @@
+####################################################################
+#  BLAS make include file.                                         #
+#  March 2007                                                      #
+####################################################################
+#
+SHELL = /bin/sh
+#
+#  The machine (platform) identifier to append to the library names
+#
+PLAT = _LINUX
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran
+OPTS     = -fPIC -O3
+DRVOPTS  = $(OPTS)
+NOOPT    =
+LOADER   = gfortran
+LOADOPTS =
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  The location and name of the Reference BLAS library.
+#
+BLASLIB      = blas$(PLAT).a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-linux64.sh	(revision 18231)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu 
+
+#Some cleanup
+rm -rf src install BLAS blas.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/blas.tgz' 'blas.tgz'
+
+#Untar 
+tar -zxvf  blas.tgz
+
+#Move blas into install directory
+mv BLAS/* src
+rm -rf BLAS
+
+#install
+cd src 
+cp ../configs/linux64/make.inc ./
+make 
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/*.a .
+ln -s blas_LINUX.a blas.a
+ln -s blas_LINUX.a libblas.a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/blas/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu 
+
+#Some cleanup
+rm -rf src install BLAS blas.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/blas.tgz' 'blas.tgz'
+
+#Untar 
+tar -zxvf  blas.tgz
+
+#Move blas into install directory
+mv BLAS/* src
+rm -rf BLAS
+
+#install
+cd src 
+cp ../configs/macosx64/make.inc ./
+make 
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/*.a .
+ln -s blas_LINUX.a blas.a
+ln -s blas_LINUX.a libblas.a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/cas128strong.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/cas128strong.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/cas128strong.hpp.patch	(revision 18231)
@@ -0,0 +1,17 @@
+199c199
+<     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0)
+---
+>     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT 
+200a201
+> 	memset(&v_, 0, sizeof(v_));
+207c208,209
+<         storage_type value_s = 0;
+---
+> 	storage_type value_s;
+> 	memset(&value_s, 0, sizeof(value_s));
+250c252,254
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s; 
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch	(revision 18231)
@@ -0,0 +1,28 @@
+961c961
+<     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0)
+---
+>     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT
+962a963
+>         memset(&v_, 0, sizeof(v_));
+968c969,970
+<         storage_type tmp = 0;
+---
+>         storage_type tmp;
+>         memset(&tmp, 0, sizeof(tmp));
+983c985,986
+<         storage_type tmp = 0;
+---
+>         storage_type tmp;
+>         memset(&tmp, 0, sizeof(tmp));
+997c1000,1002
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s;
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
+1013c1018,1020
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s;
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.49-linux.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.49-linux.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.49-linux.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_49_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_49_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_49_0/* src
+rm -rf boost_1_49_0
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python3.2 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+./bjam install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.55-macosx-mavericks.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_55_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_55_0.tar.gz' 'boost_1_55_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_55_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_55_0/* src
+rm -rf boost_1_55_0
+
+patch src/boost/atomic/detail/cas128strong.hpp ./configs/1.55/cas128strong.hpp.patch
+patch src/boost/atomic/detail/gcc-atomic.hpp ./configs/1.55/gcc-atomic.hpp.patch
+
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python3.2 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+./b2 toolset=clang cxxflags=-stdlib=libstdc++ linkflags=-stdlib=libstdc++ -j2 variant=release link=static threading=multi install
+#./bjam install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-macosx-snowleopard.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install-macosx-snowleopard.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_49_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_49_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_49_0/* src
+rm -rf boost_1_49_0
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python2.7 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+#./b2 address-model=32 architecture=x86 cxxflags="-arch i386" variant=release threading=multi install
+./b2 toolset=darwin address-model=32 architecture=x86 variant=release threading=multi install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/boost/install.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_49_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_49_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_49_0/* src
+rm -rf boost_1_49_0
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python3.2 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+./bjam install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bsdtar/install-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bsdtar/install-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/bsdtar/install-win7.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src libarchive-3.0.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libarchive-3.0.3.tar.gz' 'libarchive-3.0.3.tar.gz'
+
+#Untar 
+tar -zxvf  libarchive-3.0.3.tar.gz
+
+#Move libarchive into src directory
+mv libarchive-3.0.3/* src
+rm -rf libarchive-3.0.3
+
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/bsdtar/install" 
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/InterX.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/InterX.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/InterX.m	(revision 18231)
@@ -0,0 +1,82 @@
+function P = InterX(L1,varargin)
+%INTERX Intersection of curves
+%   P = INTERX(L1,L2) returns the intersection points of two curves L1 
+%   and L2. The curves L1,L2 can be either closed or open and are described
+%   by two-row-matrices, where each row contains its x- and y- coordinates.
+%   The intersection of groups of curves (e.g. contour lines, multiply 
+%   connected regions etc) can also be computed by separating them with a
+%   column of NaNs as for example
+%
+%         L  = [x11 x12 x13 ... NaN x21 x22 x23 ...;
+%               y11 y12 y13 ... NaN y21 y22 y23 ...]
+%
+%   P has the same structure as L1 and L2, and its rows correspond to the
+%   x- and y- coordinates of the intersection points of L1 and L2. If no
+%   intersections are found, the returned P is empty.
+%
+%   P = INTERX(L1) returns the self-intersection points of L1. To keep
+%   the code simple, the points at which the curve is tangent to itself are
+%   not included. P = INTERX(L1,L1) returns all the points of the curve 
+%   together with any self-intersection points.
+%   
+%   Example:
+%       t = linspace(0,2*pi);
+%       r1 = sin(4*t)+2;  x1 = r1.*cos(t); y1 = r1.*sin(t);
+%       r2 = sin(8*t)+2;  x2 = r2.*cos(t); y2 = r2.*sin(t);
+%       P = InterX([x1;y1],[x2;y2]);
+%       plot(x1,y1,x2,y2,P(1,:),P(2,:),'ro')
+
+%   Author : NS
+%   Version: 3.0, 21 Sept. 2010
+
+%   Two words about the algorithm: Most of the code is self-explanatory.
+%   The only trick lies in the calculation of C1 and C2. To be brief, this
+%   is essentially the two-dimensional analog of the condition that needs
+%   to be satisfied by a function F(x) that has a zero in the interval
+%   [a,b], namely
+%           F(a)*F(b) <= 0
+%   C1 and C2 exactly do this for each segment of curves 1 and 2
+%   respectively. If this condition is satisfied simultaneously for two
+%   segments then we know that they will cross at some point. 
+%   Each factor of the 'C' arrays is essentially a matrix containing 
+%   the numerators of the signed distances between points of one curve
+%   and line segments of the other.
+
+    %...Argument checks and assignment of L2
+    error(nargchk(1,2,nargin));
+    if nargin == 1,
+        L2 = L1;    hF = @lt;   %...Avoid the inclusion of common points
+    else
+        L2 = varargin{1}; hF = @le;
+    end
+       
+    %...Preliminary stuff
+    x1  = L1(1,:)';  x2 = L2(1,:);
+    y1  = L1(2,:)';  y2 = L2(2,:);
+    dx1 = diff(x1); dy1 = diff(y1);
+    dx2 = diff(x2); dy2 = diff(y2);
+    
+    %...Determine 'signed distances'   
+    S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
+    S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);
+    
+    C1 = feval(hF,D(bsxfun(@times,dx1,y2)-bsxfun(@times,dy1,x2),S1),0);
+    C2 = feval(hF,D((bsxfun(@times,y1,dx2)-bsxfun(@times,x1,dy2))',S2'),0)';
+
+    %...Obtain the segments where an intersection is expected
+    [i,j] = find(C1 & C2); 
+    if isempty(i),P = zeros(2,0);return; end;
+    
+    %...Transpose and prepare for output
+    i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
+    L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
+    i = i(L~=0); j=j(L~=0); L=L(L~=0);  %...Avoid divisions by 0
+    
+    %...Solve system of eqs to get the common points
+    P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
+                dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';
+              
+    function u = D(x,y)
+        u = bsxfun(@minus,x(:,1:end-1),y).*bsxfun(@minus,x(:,2:end),y);
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/license.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/license.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/license.txt	(revision 18231)
@@ -0,0 +1,25 @@
+Copyright (c) 2006, Antoni J. Canós
+Copyright (c) 2008, Douglas M. Schwarz
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without 
+modification, are permitted provided that the following conditions are 
+met:
+
+    * Redistributions of source code must retain the above copyright 
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright 
+      notice, this list of conditions and the following disclaimer in 
+      the documentation and/or other materials provided with the distribution
+      
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+POSSIBILITY OF SUCH DAMAGE.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/licenseNS.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/licenseNS.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/licenseNS.txt	(revision 18231)
@@ -0,0 +1,24 @@
+Copyright (c) 2009, NS
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without 
+modification, are permitted provided that the following conditions are 
+met:
+
+    * Redistributions of source code must retain the above copyright 
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright 
+      notice, this list of conditions and the following disclaimer in 
+      the documentation and/or other materials provided with the distribution
+      
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+POSSIBILITY OF SUCH DAMAGE.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/selfintersect.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/selfintersect.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/canos/selfintersect.m	(revision 18231)
@@ -0,0 +1,174 @@
+function [x0,y0,segments]=selfintersect(x,y)
+
+%SELFINTERSECT Self-intersections of a curve.
+%
+%    [X0,Y0,SEGMENTS] = SELFINTERSECT(X,Y) computes the locations where
+%    a curve self-intersects in a fast and robust way.
+%    The curve can be broken with NaNs or have vertical segments.
+%    Segments of the curve involved in each of the self-interesections are
+%    also provided.
+%
+%    Vectors X and Y are equal-length vectors of at least four points defining
+%    the curve.
+%    X0 and Y0 are column vectors with the x- and y- coordinates, respectively
+%    of the N self-intersections.
+%    SEGMENTS is an N x 2 matrix containing the pairs of segments involved in
+%    each self-intersection.
+%
+%    This program uses the theory of operation of the file "Fast and Robust Curve
+%    Intersections" submitted by Douglas M. Schwartz (intersections.m, F.Id: 11837).
+%
+%    Example of use
+% 	 N=201;
+% 	 th=linspace(-3*pi,4*pi,N);
+% 	 R=1;
+% 	 x=R*cos(th)+linspace(0,6,N);
+% 	 y=R*sin(th)+linspace(0,1,N);
+%    t0=clock;
+%    [x0,y0,segments]=selfintersect(x,y)
+% 	 etime(clock,t0)
+%    plot(x,y,'b',x0,y0,'.r');
+% 	 axis ('equal'); grid
+
+%
+%    See also INTERSECTIONS.
+%
+%Version: 1.0, December 11, 2006
+%Tested under MATLAB 6.5.0. R13.
+%
+% (c) Antoni J. Canos.
+% ITACA. Techincal University of Valencia (Spain)
+% Email:   ancama2@dcom.upv.es
+
+
+% Input checks.
+error(nargchk(2,2,nargin))
+% x and y must be vectors with same number of points (at least 4 for self-intersection).
+if sum(size(x) > 3) ~= 1 || sum(size(y) > 3) ~= 1 || ...
+		length(x) ~= length(y)
+	error('X and Y must be equal-length vectors of at least 4 points.')
+end
+
+x0=[];
+y0=[];
+segments=[];
+
+% Two similar curves are firstly created.
+x1=x; x2=x;
+y1=y; y2=y;
+
+x1 = x1(:);
+y1 = y1(:);
+x2 = x2(:);
+y2 = y2(:);
+
+% Compute number of line segments in each curve and some differences we'll
+% need later.
+n1 = length(x1) - 1;
+n2 = length(x2) - 1;
+
+dxy1 = diff([x1 y1]);
+dxy2 = diff([x2 y2]);
+
+% Determine the combinations of i and j where the rectangle enclosing the
+% i'th line segment of curve 1 overlaps with the rectangle enclosing the
+% j'th line segment of curve 2.
+[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...
+	repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...
+	repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...
+	repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...
+	repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...
+	repmat(min(y2(1:end-1),y2(2:end)).',n1,1));
+
+% Removing coincident and adjacent segments.
+remove=find(abs(i-j)<2);
+i(remove)=[];
+j(remove)=[];
+
+% Removing duplicate combinations of segments.
+remove=[];
+for ii=1:size(i,1)
+	ind=find((i(ii)==j(ii:end))&(j(ii)==i(ii:end)));
+	remove=[remove;ii-1+ind];
+end
+i(remove)=[];
+j(remove)=[];
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+i(remove) = [];
+j(remove) = [];
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+i(remove) = [];
+j(remove) = [];
+
+% Initialize matrices.  We'll put the T's and B's in matrices and use them
+% one column at a time.  For some reason, the \ operation below is faster
+% on my machine when A is sparse so we'll initialize a sparse matrix with
+% the fixed values and then assign the changing values in the loop.
+n = length(i);
+T = zeros(4,n);
+A = sparse([1 2 3 4],[3 3 4 4],-1,4,4,8);
+B = -[x1(i) x2(j) y1(i) y2(j)].';
+index_dxy1 = [1 3];  %  A(1) = A(1,1), A(3) = A(3,1)
+index_dxy2 = [6 8];  %  A(6) = A(2,2), A(8) = A(4,2)
+
+% Loop through possibilities.  Set warning not to trigger for anomalous
+% results (i.e., when A is singular).
+warning_state = warning('off','MATLAB:singularMatrix');
+try
+	for k = 1:n
+		A(index_dxy1) = dxy1(i(k),:);
+		A(index_dxy2) = dxy2(j(k),:);
+		T(:,k) = A\B(:,k);
+	end
+	warning(warning_state)
+catch
+	warning(warning_state)
+	rethrow(lasterror)
+end
+
+% Find where t1 and t2 are between 0 and 1 and return the corresponding x0
+% and y0 values.  Anomalous segment pairs can be segment pairs that are
+% colinear (overlap) or the result of segments that are degenerate (end
+% points the same).  The algorithm will return an intersection point that
+% is at the center of the overlapping region.  Because of the finite
+% precision of floating point arithmetic it is difficult to predict when
+% two line segments will be considered to overlap exactly or even intersect
+% at an end point.  For this algorithm, an anomaly is detected when any
+% element of the solution (a single column of T) is a NaN.
+
+in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1;
+anomalous = any(isnan(T));
+if any(anomalous)
+	ia = i(anomalous);
+	ja = j(anomalous);
+	% set x0 and y0 to middle of overlapping region.
+	T(3,anomalous) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
+		min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1))))/2;
+	T(4,anomalous) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
+		min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1))))/2;
+	x0 = T(3,in_range | anomalous).';
+	y0 = T(4,in_range | anomalous).';
+	i=i(in_range | anomalous);
+	j=j(in_range | anomalous);
+else
+	x0 = T(3,in_range).';
+	y0 = T(4,in_range).';
+	i=i(in_range);
+	j=j(in_range);
+end
+
+segments=sort([i,j],2);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.orig.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.orig.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.orig.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install cccl-0.03
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/cccl-0.03.tar.gz' 'cccl-0.03.tar.gz'
+
+#Untar 
+tar -zxvf  cccl-0.03.tar.gz
+
+#Move cccl into install directory
+mv cccl-0.03/* src
+rm -rf cccl-0.03
+
+cd src 
+
+#Compile
+./configure --prefix="$ISSM_DIR/externalpackages/cccl/install"
+
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/install-win7.sh	(revision 18231)
@@ -0,0 +1,11 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src cccl-0.03
+mkdir install 
+mkdir install/bin
+
+#Move cccl into install directory
+cp issm/cccl install/bin
+chmod 755 install/bin/cccl
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/issm/cccl
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/issm/cccl	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cccl/issm/cccl	(revision 18231)
@@ -0,0 +1,113 @@
+#!/bin/sh
+
+# cccl 
+# Wrapper around MS's cl.exe and link.exe to make them act more like
+# Unix cc and ld
+#
+# Copyright (C) 2000-2003 Geoffrey Wossum (gwossum@acm.org)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your optsion) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+usage()
+{
+    cat <<EOF
+Usage: cccl [OPTIONS]
+
+cccl is a wrapper around Microsoft's cl.exe and link.exe.  It translates
+parameters that Unix cc's and ld's understand to parameters that cl and link
+understand.
+EOF
+    exit $1
+}
+
+prog=cl
+
+### Run through every optsion and convert it to the proper MS one
+while test $# -gt 0; do
+
+    case "$1" in
+    --version)
+	cat <<EOF
+cccl 0.03
+
+Copyright 2000-2003 Geoffrey Wossum
+This is free software; see the source for copying conditions.  There is NO
+waranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+EOF
+	exit 1;
+	;;
+
+    -o)
+	# specifying output file, is it an object or an executable
+	shift
+	case "$1" in
+			
+		*.exe)
+			opts="$opts /Fe$1";
+		;;
+
+
+		*.mex*)
+			opts="$opts /OUT:$1"
+		;;
+
+		*.o | *.obj)
+			opts="$opts /Fo$1"
+		;;
+
+		*)
+			opts="$opts /Fo$1"
+		;;
+    esac
+	;;
+	-fPIC)
+	#do nothing
+	;;
+	-g)
+	#do nothing
+	;;
+	-pthread)
+	#do nothing
+	;;
+	-fno-omit-frame-pointer)
+	#do nothing
+	;;
+   -I*)
+	   include=`echo $1 | sed 's/-I//g'`
+	   include=`cygpath -m "$include"`
+	   include="/I\"$include\""
+	   includeopts="$includeopts $include"
+   ;;
+	-L*)
+		library=`echo $1 | sed 's/-L//g'`
+		library=`cygpath -m $library`
+		string="/link /LIBPATH:\"$library\""
+		opts="$opts $string"
+	;;
+	*)
+		#do nothing
+		opts="$opts $1"
+	;;
+
+	
+    esac
+    shift
+done
+			
+#pass all our processing through the echo command, so we are sure that the string has no quirk, 
+#and that once passed by exec to cl, everything works fine.
+command=`echo "$prog "$includeopts" $opts /nologo"`
+exec $command
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file: chaco.h
+ * \brief prototypes for chaco library
+ */ 
+
+#ifndef _CHACO_INCLUDES_H_
+#define  _CHACO_INCLUDES_H_
+
+#include "./defs.h"
+#include "./params.h"
+
+extern "C" int       interface( int       nvtxs,		/* number of vertices in full graph */
+		int      *start,		/* start of edge list for each vertex */
+		int      *adjacency,		/* edge list data */
+		int      *vwgts,		/* weights for all vertices */
+		float    *ewgts,		/* weights for all edges */
+		float    *x, 
+		float    *y, 
+		float    *z,		/* coordinates for inertial method */
+		char     *outassignname,	/* name of assignment output file */
+		char     *outfilename,		/* output file name */
+		short    *assignment,		/* set number of each vtx (length n) */
+		int       architecture,		/* 0 => hypercube, d => d-dimensional mesh */
+		int       ndims_tot,		/* total number of cube dimensions to divide */
+		int       mesh_dims[3],		/* dimensions of mesh of processors */
+		double   *goal,			/* desired set sizes for each set */
+		int       global_method,	/* global partitioning algorithm */
+		int       local_method,		/* local partitioning algorithm */
+		int       rqi_flag,		/* should I use RQI/Symmlq eigensolver? */
+		int       vmax,			/* how many vertices to coarsen down to? */
+		int       ndims,		/* number of eigenvectors (2^d sets) */
+		double    eigtol,		/* tolerance on eigenvectors */
+		long      seed);			/* for random graph mutations */
+
+extern "C" void      read_params(FILE* pfile);	/* file with new user parameters */
+extern "C" void      smalloc_stats(void);
+extern "C" double*   smalloc(unsigned int n); /* number of bytes to be allocated */
+
+#endif //ifndef _CHACO_INCLUDES_H_
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco.patch	(revision 18231)
@@ -0,0 +1,572 @@
+Only in src/code/assign: assign.o
+diff -rc src/code/assign/assign_out.c old/code/assign/assign_out.c
+*** src/code/assign/assign_out.c	2010-07-16 16:28:47.352242454 -0700
+--- old/code/assign/assign_out.c	1995-08-08 14:32:10.000000000 -0700
+***************
+*** 3,9 ****
+   * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+  
+  #include	<stdio.h>
+- #include	"defs.h"
+  
+  static void assign_out_normal(), assign_out_inv();
+  
+--- 3,8 ----
+Only in src/code/assign: assign_out.o
+Only in src/code/assign: mapper.o
+Only in src/code/assign: median.o
+Only in src/code/assign: merge_assign.o
+Only in src/code/assign: rec_median.o
+Only in src/code/assign: rotate.o
+Only in src/code/assign: y2x.o
+Only in src/code/bpmatch: checkbp.o
+Only in src/code/bpmatch: genvals2d.o
+Only in src/code/bpmatch: genvals3d.o
+Only in src/code/bpmatch: inits2d.o
+Only in src/code/bpmatch: inits3d.o
+Only in src/code/bpmatch: map2d.o
+Only in src/code/bpmatch: map3d.o
+Only in src/code/bpmatch: movevtxs.o
+Only in src/code/bpmatch: sorts2d.o
+Only in src/code/bpmatch: sorts3d.o
+Only in src/code: chacominusblas.a
+Only in src/code/coarsen: coarsen1.o
+Only in src/code/coarsen: coarsen.o
+Only in src/code/coarsen: interpolate.o
+Only in src/code/coarsen: makeccoords.o
+Only in src/code/coarsen: makefgraph.o
+Only in src/code/coarsen: makev2cv.o
+Only in src/code/coarsen: maxmatch1.o
+Only in src/code/coarsen: maxmatch2.o
+Only in src/code/coarsen: maxmatch3.o
+Only in src/code/coarsen: maxmatch4.o
+Only in src/code/coarsen: maxmatch5.o
+Only in src/code/coarsen: maxmatch.o
+Only in src/code/connect: add_edges.o
+Only in src/code/connect: connected.o
+Only in src/code/connect: find_edges.o
+Only in src/code/eigen: bidir.o
+Only in src/code/eigen: bisect.o
+Only in src/code/eigen: checkeig_ext.o
+Only in src/code/eigen: checkeig.o
+Only in src/code/eigen: checkorth.o
+Only in src/code/eigen: cksturmcnt.o
+Only in src/code/eigen: eigensolve.o
+diff -rc src/code/eigen/get_extval.c old/code/eigen/get_extval.c
+*** src/code/eigen/get_extval.c	2010-07-16 16:28:47.353242463 -0700
+--- old/code/eigen/get_extval.c	1995-08-08 14:32:20.000000000 -0700
+***************
+*** 4,10 ****
+  
+  #include <math.h>
+  #include <stdio.h>
+- #include "defs.h"
+  
+  /* Finds first extended eigenpair of system corresponding to
+     tridiagonal T using using Rafael's bisection technique. */
+--- 4,9 ----
+Only in src/code/eigen: get_extval.o
+Only in src/code/eigen: get_ritzvals.o
+Only in src/code/eigen: lanc_seconds.o
+Only in src/code/eigen: lanczos_ext_float.o
+Only in src/code/eigen: lanczos_ext.o
+Only in src/code/eigen: lanczos_FO.o
+Only in src/code/eigen: lanczos_SO_float.o
+Only in src/code/eigen: lanczos_SO.o
+Only in src/code/eigen: lanpause.o
+Only in src/code/eigen: makeorthlnk.o
+Only in src/code/eigen: mkeigvecs.o
+Only in src/code/eigen: mkscanlist.o
+Only in src/code/eigen: orthog1.o
+Only in src/code/eigen: orthogonalize.o
+Only in src/code/eigen: orthogvec.o
+Only in src/code/eigen: ql.o
+Only in src/code/eigen: rqi_ext.o
+Only in src/code/eigen: rqi.o
+Only in src/code/eigen: scale_diag.o
+Only in src/code/eigen: scanmax.o
+Only in src/code/eigen: scanmin.o
+Only in src/code/eigen: solistout.o
+Only in src/code/eigen: sorthog.o
+Only in src/code/eigen: splarax.o
+Only in src/code/eigen: sturmcnt.o
+Only in src/code/eigen: Tevec.o
+Only in src/code/eigen: tri_solve.o
+Only in src/code/eigen: warnings.o
+Only in src/code/graph: check_graph.o
+Only in src/code/graph: free_graph.o
+Only in src/code/graph: graph_out.o
+Only in src/code/graph: reformat.o
+Only in src/code/graph: subgraph.o
+Only in src/code/inertial: eigenvec2.o
+Only in src/code/inertial: eigenvec3.o
+Only in src/code/inertial: inertial1d.o
+Only in src/code/inertial: inertial2d.o
+Only in src/code/inertial: inertial3d.o
+Only in src/code/inertial: inertial.o
+Only in src/code/inertial: make_subgeom.o
+Only in src/code/input: check_input.o
+Only in src/code/input: input_assign.o
+Only in src/code/input: input_geom.o
+Only in src/code/input: input_graph.o
+Only in src/code/input: input.o
+Only in src/code/input: read_params.o
+Only in src/code/input: read_val.o
+Only in src/code/input: reflect_input.o
+Only in src/code/internal: check_internal.o
+Only in src/code/internal: force_internal.o
+Only in src/code/internal: improve_internal.o
+Only in src/code/klspiff: bilistops.o
+Only in src/code/klspiff: buckets1.o
+Only in src/code/klspiff: buckets_bi.o
+Only in src/code/klspiff: buckets.o
+Only in src/code/klspiff: coarsen_kl.o
+Only in src/code/klspiff: compress_ewgts.o
+Only in src/code/klspiff: count_weights.o
+Only in src/code/klspiff: kl_init.o
+Only in src/code/klspiff: kl_output.o
+Only in src/code/klspiff: klspiff.o
+Only in src/code/klspiff: make_bndy_list.o
+Only in src/code/klspiff: make_kl_list.o
+Only in src/code/klspiff: nway_kl.o
+Only in src/code/klvspiff: bpm_improve.o
+Only in src/code/klvspiff: bucketsv.o
+Only in src/code/klvspiff: clear_dvals.o
+Only in src/code/klvspiff: coarsen_klv.o
+Only in src/code/klvspiff: countup_vtx_sep.o
+Only in src/code/klvspiff: find_bndy.o
+Only in src/code/klvspiff: flatten.o
+Only in src/code/klvspiff: flow.o
+Only in src/code/klvspiff: klv_init.o
+Only in src/code/klvspiff: klvspiff.o
+Only in src/code/klvspiff: make_bpgraph.o
+Only in src/code/klvspiff: make_sep_list.o
+diff -rc src/code/klvspiff/matching.c old/code/klvspiff/matching.c
+*** src/code/klvspiff/matching.c	2010-07-16 16:28:47.356242493 -0700
+--- old/code/klvspiff/matching.c	1996-03-11 10:24:25.000000000 -0800
+***************
+*** 6,12 ****
+     code provided by Ed Rothberg at SGI. */
+  
+  #include <stdio.h>
+- #include "defs.h"
+  
+  #define  TRUE  1
+  #define  FALSE 0
+--- 6,11 ----
+Only in src/code/klvspiff: matching.o
+Only in src/code/klvspiff: nway_klv.o
+diff -rc src/code/main/defs.h old/code/main/defs.h
+*** src/code/main/defs.h	2010-07-16 16:28:47.359242522 -0700
+--- old/code/main/defs.h	1995-08-08 14:32:41.000000000 -0700
+***************
+*** 1,39 ****
+! #ifndef _CHACO_DEFS_H_
+! #define _CHACO_DEFS_H_
+! 
+  #define TRUE		1
+  #define FALSE		0
+  
+! #ifndef _HAVE_CHACO_ //protect ISSM compilation. This symbol is defined when we compile ISSM
+! 
+! 	#define	max(A, B)	((A) > (B) ? (A) : (B))
+! 	#define	min(A, B)	((A) < (B) ? (A) : (B))
+! 	#define sign(A)		((A) <  0  ? -1  :  1)
+! 	#define absval(A)	((A) <  0  ? -(A): (A))
+! 
+! 	/* Define constants that are needed in various places */
+! 	#define	PI	3.141592653589793
+! 	#define	TWOPI	6.283185307179586
+! 	#define HALFPI  1.570796326794896
+! 
+!     #define check_graph chaco_check_graph
+! 
+! 
+! 	#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  //#ifndef _HAVE_CHACO_ 
+! 
+! #endif //ifndef _CHACO_DEFS_H_
+--- 1,11 ----
+! #define	max(A, B)	((A) > (B) ? (A) : (B))
+! #define	min(A, B)	((A) < (B) ? (A) : (B))
+! #define sign(A)		((A) <  0  ? -1  :  1)
+! #define absval(A)	((A) <  0  ? -(A): (A))
+  #define TRUE		1
+  #define FALSE		0
+  
+! /* Define constants that are needed in various places */
+! #define	PI	3.141592653589793
+! #define	TWOPI	6.283185307179586
+! #define HALFPI  1.570796326794896
+Only in src/code/main: interface.o
+Only in src/code/main: main.o
+diff -rc src/code/main/params.h old/code/main/params.h
+*** src/code/main/params.h	2010-07-16 16:28:47.361242541 -0700
+--- old/code/main/params.h	1995-08-08 14:32:43.000000000 -0700
+***************
+*** 1,12 ****
+- #ifndef _CHACO_PARAMS_H_
+- #define _CHACO_PARAMS_H_
+- 
+- 
+  #define NAME_LENGTH	80	/* Maximum length of file name */
+  #define LINE_LENGTH	200	/* Length of input files read at once */
+  
+  #define MAXDIMS		3	/* Most cuts allowed at one time */
+  #define MAXSETS		8	/* 2^MAXDIMS */
+- 
+- 
+- #endif //ifndef _CHACO_PARAMS_H_
+--- 1,5 ----
+Only in src/code/main: user_params.o
+diff -rc src/code/Makefile old/code/Makefile
+*** src/code/Makefile	2010-07-21 18:22:19.909939194 -0700
+--- old/code/Makefile	1997-10-02 10:23:22.000000000 -0700
+***************
+*** 2,18 ****
+  DEST=		${DEST_DIR}/chaco
+  CC = 		gcc
+  IFLAG =		-Imain
+! #IFLAG =		-Imain -I/usr/local/pkgs/matlab-7.6/extern/include
+! #CFLAGS =	-O2
+! #OFLAGS =	-O2
+! #CFLAGS =	-fPIC -fno-omit-frame-pointer -D_GNU_SOURCE -pthread -fexceptions
+! CFLAGS =	-fPIC -fno-omit-frame-pointer -pthread -fexceptions -g
+! #CFLAGS =	-fPIC -fno-omit-frame-pointer -pthread -fexceptions -DMATLAB
+! OFLAGS =	-O2 
+! #AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+! AR =             /usr/bin/ar rcv
+! #RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+! RANLIB =         /usr/bin/ranlib
+  
+  FILES.c=	main/user_params.c main/interface.c main/main.c \
+  		submain/balance.c submain/divide.c submain/submain.c \
+--- 2,9 ----
+  DEST=		${DEST_DIR}/chaco
+  CC = 		gcc
+  IFLAG =		-Imain
+! CFLAGS =	-O2
+! OFLAGS =	-O2
+  
+  FILES.c=	main/user_params.c main/interface.c main/main.c \
+  		submain/balance.c submain/divide.c submain/submain.c \
+***************
+*** 96,196 ****
+  		util/update.c  util/vecout.c util/vecran.c \
+                  util/vecscale.c 
+  
+- 
+- FILESMINUSBLAS.c=	main/user_params.c main/interface.c main/main.c \
+- 		submain/balance.c submain/divide.c submain/submain.c \
+- 		input/input_assign.c \
+- 		input/check_input.c input/input.c input/input_geom.c \
+- 		input/input_graph.c input/read_params.c input/reflect_input.c \
+- 		input/read_val.c \
+- 		graph/check_graph.c graph/free_graph.c \
+- 		graph/reformat.c graph/subgraph.c graph/graph_out.c \
+- 		inertial/eigenvec2.c inertial/eigenvec3.c inertial/inertial.c \
+- 		inertial/inertial1d.c inertial/inertial2d.c \
+- 		inertial/inertial3d.c inertial/make_subgeom.c \
+- 		klspiff/buckets.c klspiff/buckets_bi.c klspiff/buckets1.c \
+- 		klspiff/bilistops.c klspiff/coarsen_kl.c klspiff/count_weights.c \
+- 		klspiff/compress_ewgts.c klspiff/kl_init.c klspiff/kl_output.c \
+- 		klspiff/klspiff.c klspiff/make_bndy_list.c \
+- 		klspiff/make_kl_list.c klspiff/nway_kl.c \
+- 		klvspiff/bpm_improve.c klvspiff/bucketsv.c \
+- 		klvspiff/clear_dvals.c klvspiff/coarsen_klv.c \
+- 		klvspiff/countup_vtx_sep.c klvspiff/find_bndy.c klvspiff/flow.c \
+- 		klvspiff/klv_init.c klvspiff/klvspiff.c klvspiff/make_bpgraph.c \
+- 		klvspiff/make_sep_list.c klvspiff/matching.c klvspiff/nway_klv.c \
+- 		klvspiff/flatten.c \
+- 		coarsen/coarsen.c coarsen/interpolate.c coarsen/makefgraph.c \
+- 		coarsen/makeccoords.c \
+- 		coarsen/coarsen1.c coarsen/makev2cv.c \
+- 		coarsen/maxmatch.c coarsen/maxmatch1.c coarsen/maxmatch2.c \
+- 		coarsen/maxmatch3.c coarsen/maxmatch4.c coarsen/maxmatch5.c \
+- 		connect/add_edges.c connect/connected.c connect/find_edges.c \
+- 		eigen/bidir.c eigen/bisect.c eigen/checkeig.c \
+- 		eigen/checkeig_ext.c \
+- 		eigen/checkorth.c eigen/cksturmcnt.c eigen/mkeigvecs.c\
+- 		eigen/eigensolve.c eigen/get_extval.c eigen/get_ritzvals.c \
+- 		eigen/lanczos_FO.c eigen/lanczos_SO.c eigen/lanczos_SO_float.c \
+- 		eigen/lanczos_ext.c eigen/lanczos_ext_float.c eigen/lanc_seconds.c\
+- 		eigen/lanpause.c eigen/makeorthlnk.c eigen/mkscanlist.c \
+- 		eigen/orthog1.c eigen/orthogonalize.c eigen/orthogvec.c \
+- 		eigen/ql.c eigen/rqi.c eigen/rqi_ext.c eigen/scale_diag.c \
+- 		eigen/scanmax.c eigen/scanmin.c eigen/solistout.c \
+-                 eigen/sorthog.c eigen/splarax.c eigen/sturmcnt.c \
+- 		eigen/Tevec.c eigen/tri_solve.c eigen/warnings.c \
+- 		symmlq/aprod.c symmlq/msolve.c symmlq/pow_dd.c \
+- 		symmlq/symmlq.c  \
+- 		tinvit/tinvit.c tinvit/pythag.c tinvit/epslon.c \
+- 		optimize/determinant.c optimize/func2d.c \
+- 		optimize/func3d.c optimize/opt2d.c optimize/opt3d.c \
+- 		assign/assign.c assign/assign_out.c assign/mapper.c \
+- 		assign/median.c assign/merge_assign.c \
+- 		assign/rec_median.c assign/rotate.c assign/y2x.c \
+- 		bpmatch/checkbp.c bpmatch/inits2d.c bpmatch/inits3d.c \
+- 		bpmatch/genvals2d.c bpmatch/genvals3d.c bpmatch/map2d.c \
+- 		bpmatch/map3d.c bpmatch/movevtxs.c \
+- 		bpmatch/sorts2d.c bpmatch/sorts3d.c \
+- 		refine_map/compute_cube_edata.c refine_map/compute_cube_vdata.c \
+- 		refine_map/refine_cube.c refine_map/update_cube_edata.c \
+- 		refine_map/update_cube_vdata.c refine_map/find_edge_cube.c \
+- 		refine_map/init_cube_edata.c refine_map/compute_mesh_edata.c \
+- 		refine_map/compute_mesh_vdata.c refine_map/find_edge_mesh.c \
+- 		refine_map/init_mesh_edata.c refine_map/refine_mesh.c \
+- 		refine_map/update_mesh_edata.c refine_map/update_mesh_vdata.c \
+- 		refine_map/refine_map.c refine_map/make_comm_graph.c \
+- 		refine_part/refine_part.c refine_part/kl_refine.c \
+- 		refine_part/make_maps_ref.c refine_part/make_terms_ref.c \
+- 		internal/force_internal.c internal/improve_internal.c \
+- 		internal/check_internal.c \
+- 		misc/define_subcubes.c misc/define_submeshes.c \
+- 		misc/divide_procs.c misc/merge_goals.c misc/make_term_props.c \
+- 		misc/count.c misc/countup.c misc/countup_cube.c \
+- 		misc/countup_mesh.c misc/make_subgoal.c \
+- 		misc/find_maxdeg.c misc/make_maps.c misc/make_setlists.c \
+- 		misc/sequence.c misc/perturb.c misc/simple_part.c \
+- 		misc/time_kernels.c misc/timing.c \
+- 		util/affirm.c util/array_alloc_2D.c util/bit_reverse.c \
+- 		util/checkpnt.c util/cpvec.c util/dot.c \
+- 		util/doubleout.c util/input_int.c util/gray.c \
+- 		util/machine_params.c util/makevwsqrt.c util/mkvec.c util/norm.c \
+-                 util/normalize.c util/mergesort.c \
+-                 util/randomize.c util/smalloc.c util/bail.c \
+- 		util/scadd.c util/seconds.c util/setvec.c util/shell_sort.c \
+- 		util/strout.c util/tri_prod.c util/true_or_false.c \
+- 		util/update.c  util/vecout.c util/vecran.c \
+-                 util/vecscale.c 
+- 
+  FILES.o=	$(FILES.c:.c=.o) 
+- FILESMINUSBLAS.o=	$(FILESMINUSBLAS.c:.c=.o) 
+- 
+- 
+- ${DEST}:	${FILES.c} chaco.a Makefile
+- 		${CC} ${OFLAGS} chaco.a -lm -o ${DEST}
+  
+- chaco.a:	${FILES.o}
+- 		${AR} chaco.a ${FILES.o} ; ${RANLIB} chaco.a
+  
+! chacominusblas.a:	${FILESMINUSBLAS.o}
+! 		${AR} chacominusblas.a ${FILESMINUSBLAS.o} ; ${RANLIB} chacominusblas.a
+  
+  lint:
+  		lint ${IFLAG} ${FILES.c} -lm
+--- 87,97 ----
+  		util/update.c  util/vecout.c util/vecran.c \
+                  util/vecscale.c 
+  
+  FILES.o=	$(FILES.c:.c=.o) 
+  
+  
+! ${DEST}:	${FILES.o} Makefile
+! 		${CC} ${OFLAGS} ${FILES.o} -lm -o ${DEST}
+  
+  lint:
+  		lint ${IFLAG} ${FILES.c} -lm
+Only in src/code/misc: count.o
+Only in src/code/misc: countup_cube.o
+Only in src/code/misc: countup_mesh.o
+Only in src/code/misc: countup.o
+Only in src/code/misc: define_subcubes.o
+Only in src/code/misc: define_submeshes.o
+Only in src/code/misc: divide_procs.o
+Only in src/code/misc: find_maxdeg.o
+Only in src/code/misc: make_maps.o
+Only in src/code/misc: make_setlists.o
+Only in src/code/misc: make_subgoal.o
+Only in src/code/misc: make_term_props.o
+Only in src/code/misc: merge_goals.o
+Only in src/code/misc: perturb.o
+Only in src/code/misc: sequence.o
+Only in src/code/misc: simple_part.o
+Only in src/code/misc: time_kernels.o
+diff -rc src/code/misc/timing.c old/code/misc/timing.c
+*** src/code/misc/timing.c	2010-07-16 16:28:47.366242590 -0700
+--- old/code/misc/timing.c	1997-01-03 09:10:52.000000000 -0800
+***************
+*** 3,9 ****
+   * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+  
+  #include   <stdio.h>
+- #include   "defs.h"
+  
+  /* Timing parameters. */
+  
+--- 3,8 ----
+Only in src/code/misc: timing.o
+Only in src/code/optimize: determinant.o
+Only in src/code/optimize: func2d.o
+Only in src/code/optimize: func3d.o
+Only in src/code/optimize: opt2d.o
+Only in src/code/optimize: opt3d.o
+Only in src/code/refine_map: compute_cube_edata.o
+Only in src/code/refine_map: compute_cube_vdata.o
+Only in src/code/refine_map: compute_mesh_edata.o
+Only in src/code/refine_map: compute_mesh_vdata.o
+Only in src/code/refine_map: find_edge_cube.o
+Only in src/code/refine_map: find_edge_mesh.o
+Only in src/code/refine_map: init_cube_edata.o
+Only in src/code/refine_map: init_mesh_edata.o
+Only in src/code/refine_map: make_comm_graph.o
+Only in src/code/refine_map: refine_cube.o
+Only in src/code/refine_map: refine_map.o
+Only in src/code/refine_map: refine_mesh.o
+Only in src/code/refine_map: update_cube_edata.o
+Only in src/code/refine_map: update_cube_vdata.o
+Only in src/code/refine_map: update_mesh_edata.o
+Only in src/code/refine_map: update_mesh_vdata.o
+Only in src/code/refine_part: kl_refine.o
+Only in src/code/refine_part: make_maps_ref.o
+Only in src/code/refine_part: make_terms_ref.o
+Only in src/code/refine_part: refine_part.o
+Only in src/code/submain: balance.o
+Only in src/code/submain: divide.o
+Only in src/code/submain: submain.o
+Only in src/code/symmlq: aprod.o
+Only in src/code/symmlq: msolve.o
+Only in src/code/symmlq: pow_dd.o
+diff -rc src/code/symmlq/symmlqblas.f old/code/symmlq/symmlqblas.f
+*** src/code/symmlq/symmlqblas.f	2010-07-21 18:09:10.370123273 -0700
+--- old/code/symmlq/symmlqblas.f	2010-07-21 14:02:09.633743650 -0700
+***************
+*** 16,22 ****
+  c     uses unrolled loops for increments equal to one.
+  c     jack dongarra, linpack, 3/11/78.
+  c
+!       double precision dx(1),dy(1),da
+        integer i,incx,incy,ix,iy,m,mp1,n
+  c
+        if(n.le.0)return
+--- 16,22 ----
+  c     uses unrolled loops for increments equal to one.
+  c     jack dongarra, linpack, 3/11/78.
+  c
+!       double precision dx(*),dy(*),da
+        integer i,incx,incy,ix,iy,m,mp1,n
+  c
+        if(n.le.0)return
+Only in src/code/symmlq: symmlqblas.o
+Only in src/code/symmlq: symmlq.o
+Only in src/code/tinvit: epslon.o
+Only in src/code/tinvit: pythag.o
+Only in src/code/tinvit: tinvit.o
+Only in src/code/util: affirm.o
+Only in src/code/util: array_alloc_2D.o
+diff -rc src/code/util/bail.c old/code/util/bail.c
+*** src/code/util/bail.c	2010-07-16 16:28:47.368242609 -0700
+--- old/code/util/bail.c	1995-08-08 14:33:01.000000000 -0700
+***************
+*** 4,10 ****
+  
+  #include	<stdio.h>
+  #include	<string.h>
+- #include	"defs.h"
+  
+  /* Wrapper for exit() - print message and exit with status code. Exit code
+     of 0 indicates normal termination. Exit code of 1 indicates early 
+--- 4,9 ----
+***************
+*** 15,20 ****
+--- 14,20 ----
+  int       status;
+  {
+      extern FILE *Output_File;		/* Output file or NULL */
++     void      exit();
+  
+      if (msg != NULL && (int) strlen(msg) > 0) {
+          printf("%s\n", msg);
+Only in src/code/util: bail.o
+Only in src/code/util: bit_reverse.o
+diff -rc src/code/util/checkpnt.c old/code/util/checkpnt.c
+*** src/code/util/checkpnt.c	2010-07-16 16:28:47.370242629 -0700
+--- old/code/util/checkpnt.c	1995-08-08 14:33:01.000000000 -0700
+***************
+*** 4,10 ****
+  
+  #include	<stdio.h>
+  #include	<string.h>
+- #include	"defs.h"
+  
+  /* Debug break point. */
+  void      checkpnt(tag)
+--- 4,9 ----
+Only in src/code/util: checkpnt.o
+Only in src/code/util: cpvec.o
+Only in src/code/util: dot.o
+diff -rc src/code/util/doubleout.c old/code/util/doubleout.c
+*** src/code/util/doubleout.c	2010-07-16 16:28:47.372242648 -0700
+--- old/code/util/doubleout.c	1995-08-08 14:33:02.000000000 -0700
+***************
+*** 3,9 ****
+   * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+  
+  #include  <stdio.h>
+- #include  "defs.h"
+  
+  /* Print a double precision number with filtering format to screen. */
+  void      doubleout(number, mode)
+--- 3,8 ----
+Only in src/code/util: doubleout.o
+Only in src/code/util: gray.o
+Only in src/code/util: input_int.o
+Only in src/code/util: machine_params.o
+Only in src/code/util: makevwsqrt.o
+Only in src/code/util: mergesort.o
+Only in src/code/util: mkvec.o
+Only in src/code/util: normalize.o
+Only in src/code/util: norm.o
+Only in src/code/util: randomize.o
+Only in src/code/util: scadd.o
+Only in src/code/util: seconds.o
+Only in src/code/util: setvec.o
+Only in src/code/util: shell_sort.o
+diff -rc src/code/util/smalloc.c old/code/util/smalloc.c
+*** src/code/util/smalloc.c	2010-07-16 16:28:47.375242677 -0700
+--- old/code/util/smalloc.c	1996-03-11 10:44:07.000000000 -0800
+***************
+*** 4,10 ****
+  
+  #include <stdio.h>
+  #include <malloc.h>
+- #include "defs.h"
+  
+  static int nmalloc = 0;		/* number of calls to malloc */
+  static int nfree = 0;		/* number of calls to free */
+--- 4,9 ----
+Only in src/code/util: smalloc.o
+diff -rc src/code/util/strout.c old/code/util/strout.c
+*** src/code/util/strout.c	2010-07-16 16:28:47.377242697 -0700
+--- old/code/util/strout.c	1995-08-08 14:33:05.000000000 -0700
+***************
+*** 4,10 ****
+  
+  #include	<stdio.h>
+  #include	<string.h>
+- #include	"defs.h"
+  
+  /* Wrapper for a printf statement with a string as only arg.
+     Prints to screen and to output file if there is one. */
+--- 4,9 ----
+Only in src/code/util: strout.o
+Only in src/code/util: tri_prod.o
+Only in src/code/util: true_or_false.o
+Only in src/code/util: update.o
+Only in src/code/util: vecout.o
+Only in src/code/util: vecran.o
+Only in src/code/util: vecscale.o
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_README.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_README.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_README.txt	(revision 18231)
@@ -0,0 +1,55 @@
+Chaco-2.2.tar (5/03/00? -- 2.0 was 2/95)
+http://www.sandia.gov/~bahendr/chaco.html
+
+
+Note that meshpart pulls the object files from here, compiled with
+the MATLAB flag for use in the mlchaco mex function, and assembles
+them into a library in its own directory.  This means that any
+objects compiled for the mlchaco mex function and left here should
+not be used for the stand-alone chaco executable, and vice versa.
+
+
+[jschierm@astrid main]$ diff defs_old.h defs.h
+11a12,27  [for running as a matlab mex function]
+> 
+> #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 check_graph chaco_check_graph
+> #endif
+> 
+
+
+added #include "defs.h" to the following:
+assign/assign_out.c
+eigen/get_extval.c
+klvspiff/matching.c
+misc/timing.c
+util/bail.c
+util/checkpnt.c
+util/doubleout.c
+util/smalloc.c
+util/strout.c
+
+
+[jschierm@astrid code]$ diff Makefile_old Makefile
+4,5c4,9  [fPIC required, CFLAGS and OFLAGS copied from Cielo gccopts_v75.sh for glnxa64]
+< IFLAG =               -Imain
+< CFLAGS =      -O2
+---
+> IFLAG =               -Imain -I/usr/local/pkgs/matlab-7.6/extern/include
+> #CFLAGS =     -O2
+> #OFLAGS =     -O2
+> #CFLAGS =     -fPIC -fno-omit-frame-pointer -D_GNU_SOURCE -pthread -fexceptions
+> CFLAGS =      -fPIC -fno-omit-frame-pointer -pthread -fexceptions -DMATLAB
+> #CFLAGS =     -fPIC -fno-omit-frame-pointer -pthread -fexceptions
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_jes_notes.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_jes_notes.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_jes_notes.txt	(revision 18231)
@@ -0,0 +1,86 @@
+7/13/09:
+
+[jschierm@astrid Chaco-2.2]$ diff ../chaco/code/Makefile code
+5,6c5,8  [fPIC required, CFLAGS and OFLAGS copied from Cielo gccopts_v75.sh for glnxa64]
+< CFLAGS =      -O2
+< OFLAGS =      -O2
+---
+> #CFLAGS =     -O2
+> #OFLAGS =     -O2
+> CFLAGS =      -fPIC -fno-omit-frame-pointer -D_GNU_SOURCE -pthread -fexceptions
+> OFLAGS =      -O -DNDEBUG
+34a37,38  [added for meshpart chaco.a library, specified by its makefile]
+>               coarsen/makecgraph.c \
+>               coarsen/countcedges.c \
+
+7/30/09:
+
+[jschierm@astrid main]$ diff defs_old.h defs.h
+11a12,26  [for running as a matlab mex function]
+> 
+> #ifdef MATLAB
+>     #include "mat.h"
+>     #include "mex.h"
+>     #include "matrix.h"
+>    
+>     #define printf mexPrintf
+>     #define malloc mxMalloc
+>     #define calloc mxCalloc
+>     #define realloc mxRealloc
+>     #define free mxFree
+> 
+>     #define check_graph chaco_check_graph
+> #endif
+> 
+
+added #include "defs.h" to the following:
+assign/assign_out.c
+eigen/get_extval.c
+klvspiff/matching.c
+misc/timing.c
+util/bail.c
+util/checkpnt.c
+util/doubleout.c
+util/smalloc.c
+util/strout.c
+
+[jschierm@astrid code]$ diff Makefile_old Makefile | more
+4,5c4,9
+< IFLAG =               -Imain
+< CFLAGS =      -O2
+---
+> IFLAG =               -Imain -I/usr/local/pkgs/matlab-7.6/extern/include
+> #CFLAGS =     -O2
+> #OFLAGS =     -O2
+> #CFLAGS =     -fPIC -fno-omit-frame-pointer -D_GNU_SOURCE -pthread
+> -fexceptions
+> CFLAGS =      -fPIC -fno-omit-frame-pointer -pthread -fexceptions -DMATLAB
+> #CFLAGS =     -fPIC -fno-omit-frame-pointer -pthread -fexceptions
+
+8/25/09:
+
+added macro for fprintf to capture missing output:
+[jschierm@astrid main]$ diff defs_old.h defs.h
+11a12,27
+> 
+> #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 check_graph chaco_check_graph
+> #endif
+> 
+
+6/15/10:
+
+- moved check_graph rename outside of MATLAB compiler directive.
+- created library chaco.a (without MATLAB compiler directive) for Chaco x-layer to link and implemented it in chaco stand-alone link.
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_njs_notes.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_njs_notes.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/chaco_njs_notes.txt	(revision 18231)
@@ -0,0 +1,3 @@
+chaco build must be able to see malloc.h
+sudo ln -s /usr/include/malloc/malloc.h /usr/include/malloc.h
+or else make sure you include the malloc directory in path
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/install.sh	(revision 18231)
@@ -0,0 +1,51 @@
+#!/bin/bash
+set -eu
+
+# Some cleanup
+rm -rf Chaco-2.2
+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/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 
+tar -xvzf Chaco-2.2.tar.gz
+
+# Move chaco to src directory
+mv Chaco-2.2/* src
+rm -rf Chaco-2.2
+
+# Apply patches (all at once)
+# (written by diff -rc src ~/Libs/Chaco-2.2 > chaco.patch)
+patch -R -p0 < chaco.patch
+
+# Build chaco
+cd src/code
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make chacominusblas.a
+
+# Clean up objects (but not library or executable)
+make clean
+cd ../..
+
+# Populate install directory
+cp -p src/exec/README install
+cp -p src/exec/User_Params install
+cp -p src/exec/*.coords install
+cp -p src/exec/*.graph install
+mkdir install/include
+cp -p src/code/main/defs.h install/include/defs.h
+cp -p src/code/main/params.h install/include/params.h
+cp -p chaco.h install/include/chaco.h
+mkdir install/lib
+mv src/code/chaco.a install/lib/libchaco.a
+mv src/code/chacominusblas.a install/lib/libchacominusblas.a
+mkdir install/exec
+mv src/exec/chaco install/exec
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco.c	(revision 18231)
@@ -0,0 +1,244 @@
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "mex.h"
+
+
+#define THISFUNCTION "Chaco"
+
+/* Input Arguments */
+
+#define    A_IN         prhs[0]
+#define    VWGTS_IN     prhs[1]
+#define    EWGTS_IN     prhs[2]
+#define    XYZ_IN       prhs[3]
+#define    OPTNS_IN     prhs[4]
+#define    NPARTS_IN    prhs[5]
+#define    GOAL_IN      prhs[6]
+
+/* Output Arguments */
+
+#define    ASSGN_OUT    plhs[0]
+
+
+void ChacoUsage( void );
+
+int Chacox(
+    int       nvtxs,		/* number of vertices in graph */
+    int      *start,		/* start of edge list for each vertex */
+    int      *adjacency,	/* edge list data */
+    int      *vwgts,		/* weights for all vertices */
+    float    *ewgts,		/* weights for all edges */
+    float    *x,
+    float    *y,
+    float    *z,			/* coordinates for inertial method */
+    short    *assignment,	/* set number of each vtx (length nvtxs+1) */
+    double   options[10],	/* architecture and partitioning options */
+    int      *nparts,		/* number of parts options */
+    double   *goal			/* desired set sizes */
+);
+
+
+void mexFunction(
+	int           nlhs,           /* number of outputs */
+	mxArray       *plhs[],        /* array of pointers to output arguments */
+	int           nrhs,           /* number of inputs */
+	const mxArray *prhs[]         /* array of pointers to input arguments */
+)
+{
+    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 */
+    float    *ewgts=NULL;	/* weights for all edges */
+    float    *x=NULL;
+    float    *y=NULL;
+    float    *z=NULL;		/* coordinates for inertial method */
+    short    *assignment=NULL;	/* set number of each vtx (length nvtxs+1) */
+    double   options[10]={1,1,0,0,1,1,50,0,.001,7654321};
+							/* architecture and partitioning options */
+    int      *nparts=NULL;	/* number of parts options */
+    double   *goal=NULL;	/* desired set sizes */
+
+	int    i, nedges, nterms, ncols, ierr=0;
+	double *p;
+	mwIndex *mwstart, *mwadjacency;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	/* Check for proper number of arguments */
+
+	if      (nrhs == 0 && nlhs == 0) {
+		ChacoUsage();
+		return;
+	}
+	else if (nrhs <  1 || nlhs >  1) {
+		ChacoUsage();
+		mexErrMsgTxt(" ");
+	}
+
+	clock0=clock();
+	time0 =time(NULL);
+	mexPrintf("\nChaco Module -- %s",ctime(&time0));
+
+	/* Assign pointers to the various parameters */
+	/* and convert to the appropriate format for Chaco */
+
+	if (!mxIsEmpty(A_IN) && mxIsNumeric(A_IN) && mxIsSparse(A_IN)) {
+		nvtxs = mxGetN(A_IN);
+		mwstart = mxGetJc(A_IN);
+		start = mxMalloc((mxGetN(A_IN)+1)*sizeof(int));
+		for (i=0; i<(mxGetN(A_IN)+1); i++)
+			start[i]= (int)mwstart[i];
+		nedges = start[nvtxs];
+		mwadjacency = mxGetIr(A_IN);
+		adjacency = mxMalloc(mxGetNzmax(A_IN)*sizeof(int));
+		for (i=0; i<mxGetNzmax(A_IN); i++)
+			adjacency[i]= (int)mwadjacency[i];
+	}
+	else {
+		mexPrintf("%s -- Adjacency matrix must be numeric and sparse.\n",
+				  THISFUNCTION);
+		mexErrMsgTxt(" ");
+	}
+
+	if (nrhs >= 2 && !mxIsEmpty(VWGTS_IN)) {
+		if (mxIsNumeric(VWGTS_IN) && !mxIsSparse(VWGTS_IN) &&
+			(nterms=mxGetM(VWGTS_IN)*mxGetN(VWGTS_IN)) == nvtxs) {
+			vwgts = (int *) mxCalloc(nvtxs, sizeof(int));
+			p = mxGetPr(VWGTS_IN);
+			for (i = 0; i < nvtxs; vwgts[i++] = (int) *p++);
+		}
+		else {
+			mexPrintf("%s -- Vertex weight vector must be numeric, full, and length=%d.\n",
+					  THISFUNCTION,nvtxs);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	if (nrhs >= 3 && !mxIsEmpty(EWGTS_IN)) {
+		if (mxIsNumeric(EWGTS_IN) && mxIsSparse(EWGTS_IN) &&
+			(nterms=mxGetNzmax(EWGTS_IN)) == nedges) {
+			ewgts = (float *) mxCalloc(nedges, sizeof(float));
+			p = mxGetPr(A_IN);
+			for (i = 0; i < nedges; ewgts[i++] = (float) *p++);
+		}
+		else {
+			mexPrintf("%s -- Edge weight matrix must be numeric, sparse, and nonzeroes=%d.\n",
+					  THISFUNCTION,nedges);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	if (nrhs >= 4 && (ncols = mxGetN(XYZ_IN)) >= 1) {
+		if (mxIsNumeric(XYZ_IN) && !mxIsSparse(XYZ_IN) &&
+			mxGetM(XYZ_IN) == nvtxs) {
+			x = (float *) mxCalloc(nvtxs, sizeof(float));
+			p = mxGetPr(XYZ_IN);
+			for (i = 0; i < nvtxs; x[i++] = (float) *p++);
+		}
+		else {
+			mexPrintf("%s -- XYZ coordinate matrix must be numeric, full, and length=%d.\n",
+					  THISFUNCTION,nvtxs);
+			mexErrMsgTxt(" ");
+		}
+		if ((ncols                 ) >= 2) {
+			y = (float *) mxCalloc(nvtxs, sizeof(float));
+			for (i = 0; i < nvtxs; y[i++] = (float) *p++);
+			if ((ncols                 ) >= 3) {
+				z = (float *) mxCalloc(nvtxs, sizeof(float));
+				for (i = 0; i < nvtxs; z[i++] = (float) *p++);
+			}
+		}
+	}
+
+	if (nrhs >= 5 && !mxIsEmpty(OPTNS_IN)) {
+		if (mxIsNumeric(OPTNS_IN) && !mxIsSparse(OPTNS_IN) &&
+			(nterms=mxGetM(OPTNS_IN)*mxGetN(OPTNS_IN))) {
+			p = mxGetPr(OPTNS_IN);
+			for (i = 0; i < (nterms<10 ? nterms : 10); options[i++] = *p++);
+		}
+		else {
+			mexPrintf("%s -- Options vector must be numeric and full.\n",
+					  THISFUNCTION);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	if (nrhs >= 6 && !mxIsEmpty(NPARTS_IN)) {
+		if (mxIsNumeric(NPARTS_IN) && !mxIsSparse(NPARTS_IN) &&
+			(nterms=mxGetM(NPARTS_IN)*mxGetN(NPARTS_IN))) {
+			nparts = (int *) mxCalloc(nterms, sizeof(int));
+			p = mxGetPr(NPARTS_IN);
+			for (i = 0; i < nterms; nparts[i++] = (int) *p++);
+		}
+		else {
+			mexPrintf("%s -- Parts vector must be numeric and full.\n",
+					  THISFUNCTION);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	if (nrhs >= 7 && !mxIsEmpty(GOAL_IN)) {
+		if (mxIsNumeric(GOAL_IN) && !mxIsSparse(GOAL_IN) &&
+			(nterms=mxGetM(GOAL_IN)*mxGetN(GOAL_IN))) {
+			goal = (double *) mxCalloc(nterms, sizeof(double));
+			p = mxGetPr(GOAL_IN);
+			for (i = 0; i < nterms; goal[i++] = *p++);
+		}
+		else {
+			mexPrintf("%s -- Goal vector must be numeric and full.\n",
+					  THISFUNCTION);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	assignment = (short *) mxCalloc(nvtxs, sizeof(short));
+
+    /* Do the actual computations in a subroutine */
+
+	ierr = Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z,
+		assignment, options, nparts, goal);
+
+    /* Create matrices for the return arguments */
+
+	if (!ierr) {
+		ASSGN_OUT = mxCreateDoubleMatrix(1,nvtxs,mxREAL);
+		p = mxGetPr(ASSGN_OUT);
+		for (i = 0; i < nvtxs; *p++ = (double) assignment[i++]);
+	}
+	else
+		ASSGN_OUT = mxCreateDoubleMatrix(0,0,mxREAL);
+
+	/* Free what we allocated */
+   
+	if (!assignment) mxFree((void *) assignment);
+	if (!goal)       mxFree((void *) goal);
+	if (!nparts)     mxFree((void *) nparts);
+	if (!z)          mxFree((void *) z);
+	if (!y)          mxFree((void *) y);
+	if (!x)          mxFree((void *) x);
+	if (!ewgts)      mxFree((void *) ewgts);
+	if (!vwgts)      mxFree((void *) vwgts);
+	if (!adjacency)  mxFree((void *) adjacency);
+	if (!start)      mxFree((void *) start);
+
+    clock1=clock();
+    time1 =time(NULL);
+    mexPrintf("Chaco Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+              ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return;
+}
+
+void ChacoUsage( void )
+{
+	mexPrintf("\n");
+	mexPrintf("Usage: [assgn] = Chaco(A,vwgts,ewgts,xyz,options,nparts,goal);\n");
+	mexPrintf("\n");
+
+	return;
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco_m.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco_m.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chaco_m.m	(revision 18231)
@@ -0,0 +1,217 @@
+function  [part1,part2,chaco_time] = chaco(A,xy,method,nparts,goal)
+% CHACO : Hendrickson/Leland's graph partitioner.
+% 
+%  [part1,part2,chaco_time] = chaco(A) returns a 50/50 vertex partition of the mesh
+%  whose symmetric adjacency matrix is A.  
+%
+%  Optional arguments:
+%  map = chaco(A, xy, method, nparts, goal);
+%  map = chaco(A, xy, method, inmap, goal);
+%
+%  A:          Depending on "method", A may contain vertex and edge weights.
+%
+%  xy:         Each row of xy is the coordinates of a vertex.
+%              If xy is non-null and there is no output, draw a picture.
+%
+%  method:     Scalar or vector describing the desired method.  
+%              Default is multilevel Kernighan-Lin; other possibilities below.
+%
+%  nparts      Number of parts to divide into.  Default is 2.  If nparts is 
+%    or        present, the output is a "map vector", see below.  (If method(5) 
+%  inmap:      is specified, nparts is interpreted differently; see below.  In
+%              any case, the default is to divide into two parts.)
+%              If method(1) = 7 (see below), this argument is a map vector
+%              specifying an initial 2-way partition, and Chaco refines it.
+%
+%  goal:       Optionally, a vector of desired sizes (or total vertex weights)
+%              for each of the nparts parts.  Default is all sizes equal.
+%
+%  map:        If nparts and inmap are not present, the output is a vector of 
+%              the n/2 vertex numbers in one part of the 2-way partition, for
+%              compatibility with geopart and specpart.
+%              If nparts or imap is present, the output is a vector of the
+%              n part numbers, from 0 to nparts-1, assigned to the vertices.
+%
+% This is a Matlab interface to the graph partitioning software described
+% in B. Hendrickson and R. Leland, "The Chaco User's Guide (Version 2.0)",
+% Sandia National Laboratories report SAND94-2692, October 1994.
+% This interface was written by John Gilbert, Xerox PARC, and is
+% Copyright (c) 1994-1996 by Xerox Corporation.  All rights reserved.
+% HELP COPYRIGHT for complete copyright and licensing notice.
+%
+% Modified by Tim Davis, for Matlab 5.1.  July 6, 1998.
+%   05/28/10    jes    Reorganization into Matlab-layer and x-layer.
+%
+% See also GEOPART, SPECPART.
+%
+% "method" is a vector of flags as follows.  Not all combinations are supported.
+% See Section 6.10 of the Chaco manual for more details on all the arguments.
+% If "method" is shorter than 10, we use the defaults for unspecified entries.
+%
+% method(1):  Global partitioning method  ("global_method" in the Chaco manual).
+%             1 Multilevel Kernighan-Lin (default)
+%             2 Spectral
+%             3 Inertial
+%             4 Linear
+%             5 Random
+%             6 Scattered
+%             7 Use "inmap" as the global (2-way) partition
+%
+% method(2):  Local refinement method  ("local_method" in the Chaco manual).
+%             1 Kernighan-Lin (default)
+%             2 None
+%
+% method(3):  Vertex weighting.
+%             0 No weights (default)
+%             1 Use diag(A) as (positive integer) vertex weights
+%
+% method(4):  Edge weighting.
+%             0 No weights (default)
+%             1 Use off-diagonals of A as (positive integer) edge weights
+%
+% method(5):  Target architecture  ("architecture" in the Chaco manual).
+%             If method(5) = 0, the target is a hypercube, "nparts" is the 
+%             number of dimensions, and the partition is into 2^nparts parts.  
+%             If method(5) = 1, 2, or 3, the target is a 1-, 2-, or 3-D grid,
+%             "nparts" is a vector of the sizes of the grid in each dimension,
+%             and the partition is into prod(nparts) parts.
+%             Default is method(5) = 1, so nparts is the number of parts.
+%
+% method(6):  Partitioning dimension  ("ndims" in the Chaco manual).
+%             1 Bisection (default)
+%             2 Quadrisection
+%             3 Octasection
+%
+% method(7):  Number of vertices to coarsen to  ("vmax" in the Chaco manual).
+%             Default is 50.
+%
+% method(8):  Eigensolver  ("rqi_flag" in the Chaco manual).
+%             0 RQI/Symmlq (default)
+%             1 Lanczos 
+%
+% method(9):  Eigensolver convergence tolerance  ("eigtol" in the Chaco manual).
+%             Default is .001
+%
+% method(10): Seed for random number generator  ("seed" in the Chaco manual).
+%             Default is 7654321.
+%
+% Many esoteric details of Chaco's behavior can be changed by placing a file
+% called "User_Params" in the same directory as the executable mlchaco.mex.
+% As always, see the manual for details.
+
+DefaultMethod = [1 1 0 0 1 1 50 0 .001 7654321];
+
+% Fill in default arguments.
+if nargin < 2, xy = []; end;
+if nargin < 3, method = DefaultMethod; end;
+if nargin < 4, nparts = []; end;
+if nargin < 5, goal = []; end;
+if length(method) < length(DefaultMethod)
+    method = [method DefaultMethod(length(method)+1 : length(DefaultMethod))];
+end;
+
+% Decide on output and graphics.
+if (isempty (nparts))
+    mapvector = 0;
+else
+    mapvector = 1;
+end;
+picture = (nargout == 0) & (size(xy,2) >= 2);
+
+% Chaco numbers vertices from 1 and the Matlab sparse data structure 
+% numbers rows from 0, so we add an empty first row to make things line up.
+% This code also makes sure the arg to Chaco will be sparse.
+[n,n] = size(A);
+Adiag = diag(diag(A));
+%Aout = [sparse(1,n) ; A-Adiag];
+Aout = sparse(A-Adiag);
+
+% Make sure all args except the adj matrix are full;
+if issparse(xy)
+    xy = full(xy);
+end;
+if issparse(method)
+    method = full(method);
+end;
+if issparse(nparts)
+    nparts = full(nparts);
+end;
+if issparse(goal)
+    goal = full(goal);
+end;
+
+% Decode "method" to get the actual args to Chaco.
+% Note that "nparts" may correspond to any of several Chaco
+% parameters, depending on the method.
+
+if method(3)
+    vwgts = full(diag(A));
+    totalvwgt = sum(vwgts);
+else
+    vwgts = [];
+    totalvwgt = size(A,2);
+end;
+if method(4)
+    ewgts = Aout;
+else
+    ewgts = [];
+end;
+if method(1) == 7
+    % Refine an input partition: "nparts" is the input partition.
+    % This seems to work only for hypercube architecture,
+    % so we force a 1-D hypercube with 2-way partitioning.
+    nsets = 2;
+elseif method(5) == 0
+    % Partition for hypercube: "nparts" is # of dimensions (default 1).
+    if (isempty (nparts))
+    	nsets = 2^1;
+    else
+    	nsets = 2^nparts;
+    end;
+else
+    % Partition for mesh: "nparts" is vector of mesh sizes in each
+    % dimension, default [2 1 ... 1] with "architecture" dimensions.
+    if (isempty (nparts))
+    	nsets = prod(2);
+    else
+    	nsets = prod(nparts);
+    end;
+end;
+if length(goal) ~= nsets
+    goal = totalvwgt/nsets * ones(1,nsets);
+end;
+
+[map,chaco_time]=Chaco(Aout, vwgts, ewgts, xy, method, nparts, goal);
+
+% Draw the picture.
+if picture
+    if size(xy,2) >= 3 && unique(xy(:,3)) == 0
+        xy=xy(:,1:2);
+    end
+    if length(unique(map)) == 2
+        gplotpart(A,xy,find(map==0));
+    else
+        gplotmap(A,xy,map);
+    end;
+    if     method(1)==1, heading = 'Multilevel Kernighan-Lin';
+    elseif method(1)==2, heading = 'Spectral';
+    elseif method(1)==3, heading = 'Inertial';
+    elseif method(1)==4, heading = 'Linear';
+    elseif method(1)==5, heading = 'Random';
+    elseif method(1)==6, heading = 'Scattered';
+    elseif method(1)==7, heading = 'Input'; 
+    end;
+    heading = [heading ' Partition'];
+    if method(2)==1 & method(1) ~= 1 
+        heading =[heading ' Refined by KL'];
+    end;
+    title(heading);
+end;
+
+% Put output in the right form.
+if mapvector
+    part1 = map;
+else
+    part1 = find(map==0);
+    part2 = find(map==1);
+end;
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chacox.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chacox.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Chacox.c	(revision 18231)
@@ -0,0 +1,471 @@
+/* This software was developed by Bruce Hendrickson and Robert Leland   *
+ * at Sandia National Laboratories under US Department of Energy        *
+ * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+
+#include <stdio.h>
+#include <string.h>
+#include "defs.h"
+#include "params.h"
+
+#define THISFUNCTION "Chacox"
+
+#define    OPT_GLOBAL    0
+#define    OPT_LOCAL     1
+#define    OPT_VWGTS     2
+#define    OPT_EWGTS     3
+#define    OPT_ARCH      4
+#define    OPT_NDIMS     5
+#define    OPT_VMAX      6
+#define    OPT_RQI       7
+#define    OPT_EIGTOL    8
+#define    OPT_SEED      9
+
+int      input_parse(
+	char     *outassignname,	/* name of assignment output file */
+	char     *outfilename,		/* name of file for outputing run results */
+	int      *architecture,		/* 0=> hypercube, d=> d-dimensional mesh */
+	int      *ndims_tot,		/* target number of hypercube dimensions */
+	int       mesh_dims[3],		/* mesh dimensions */
+	int      *global_method,	/* what global partitioning strategy to use? */
+	int      *local_method,		/* what local refinement strategy to use? */
+	int      *rqi_flag,		/* should I use multilevel eigensolver? */
+	int      *vmax,			/* if so, how far should I coarsen? */
+	int      *ndims,		/* number of divisions at each stage */
+	int      *nprocs,		/* number of processors being divided into */
+	double   options[10],	/* architecture and partitioning options */
+	int      *nparts		/* number of parts options */
+);
+
+
+int Chacox(
+	int       nvtxs,		/* number of vertices in graph */
+	int      *start,		/* start of edge list for each vertex */
+	int      *adjacency,	/* edge list data */
+	int      *vwgts,		/* weights for all vertices */
+	float    *ewgts,		/* weights for all edges */
+	float    *x,
+	float    *y,
+	float    *z,			/* coordinates for inertial method */
+	short    *assignment,	/* set number of each vtx (length nvtxs+1) */
+	double   options[10],	/* architecture and partitioning options */
+	int      *nparts,		/* number of parts options */
+	double   *goal			/* desired set sizes */
+)
+{
+	extern int Using_Main;	/* is main routine being called? */
+	extern char *PARAMS_FILENAME;	/* name of file with parameter updates */
+	extern double EIGEN_TOLERANCE;	/* tolerance for eigen calculations */
+	extern int OUTPUT_ASSIGN;	/* whether to write assignment to file */
+	extern int DEBUG_MEMORY;	/* debug memory allocation and freeing? */
+	extern int DEBUG_TRACE;	/* trace main execution path */
+	extern int DEBUG_PARAMS;	/* debug flag for reading parameters */
+	extern long RANDOM_SEED;	/* seed for random number generators */
+	extern int ECHO;		/* controls amount of output */
+	extern int PROMPT;		/* prompt for input or not? */
+	extern int PRINT_HEADERS;	/* print lines for output sections? */
+	extern int MATCH_TYPE;      /* matching routine to call */
+	extern double input_time;	/* times data file input */
+	extern double start_time;	/* time partitioning starts */
+	FILE     *params_file;	/* file with parameter value updates */
+	int       global_method;	/* global partitioning method */
+	int       local_method;	/* local partitioning method */
+	double    eigtol;		/* tolerance in eigenvector calculation */
+	int       ndims;		/* dimension of recursive partitioning */
+	int       architecture;	/* 0 => hypercube, d => d-dimensional mesh */
+	int       ndims_tot;	/* total number of cube dimensions to divide */
+	int       mesh_dims[3];	/* dimensions of mesh of processors */
+	long      seed;		/* for random graph mutations */
+	int       rqi_flag;		/* use RQI/Symmlq eigensolver? */
+	int       vmax;		/* if so, how many vertices to coarsen down to? */
+	char      outassignname[NAME_LENGTH];	/* assignment output file name */
+	char      outfilename[NAME_LENGTH];	/* name of output file */
+	char     *outassignptr;	/* name or null pointer for output assignment */
+	char     *outfileptr;	/* name or null pointer for output file */
+	int       nprocs;		/* number of processors being divided into */
+	double    time;		/* timing marker */
+	int       flag;		/* return code from input routines */
+	double   *smalloc();	/* safe version of malloc */
+	double    seconds();	/* returns elapsed time in seconds */
+	int       sfree(), interface(), affirm();
+	void      input_queries(), smalloc_stats(), read_params(), clear_timing();
+
+	int i,tvwgt;
+	double tgoal;
+
+	if (DEBUG_TRACE > 0) {
+		printf("<Entering main>\n");
+	}
+
+	if (PRINT_HEADERS) {
+		printf("\n                    Chaco 2.0\n");
+		printf("          Sandia National Laboratories\n\n");
+	}
+
+	Using_Main = TRUE;
+	params_file = fopen(PARAMS_FILENAME, "r");
+	if (params_file == NULL && DEBUG_PARAMS > 1) {
+		printf("Parameter file `%s' not found; using default parameters.\n",
+			   PARAMS_FILENAME);
+	}
+
+	start_time = time = seconds();
+
+	read_params(params_file);
+
+	flag = input_parse(outassignname, outfilename,
+			  &architecture, &ndims_tot, mesh_dims,
+			  &global_method, &local_method, &rqi_flag, &vmax, &ndims, &nprocs,
+			  options, nparts);
+	if (flag)
+		return(flag);
+
+	if (OUTPUT_ASSIGN > 0)
+		outassignptr = outassignname;
+	else
+		outassignptr = NULL;
+
+	if (ECHO < 0)
+		outfileptr = outfilename;
+	else
+		outfileptr = NULL;
+
+	if ((int)options[OPT_VWGTS] && vwgts) {
+		printf("%s -- Applying weights for %d vertices.\n",
+			   THISFUNCTION,nvtxs);
+		tvwgt = 0.;
+		for (i=0; i<nvtxs; i++)
+			tvwgt += vwgts[i];
+	}
+	else {
+		tvwgt = nvtxs;
+		if      ( (int)options[OPT_VWGTS] && !vwgts)
+			printf("%s -- Vertex weight flag=%d, but no vertex weights specified.\n",
+				   THISFUNCTION,options[OPT_VWGTS]);
+		else if (!(int)options[OPT_VWGTS] &&  vwgts)
+			printf("%s -- Vertex weight flag=%d, so specified vertex weights ignored.\n",
+				   THISFUNCTION,options[OPT_VWGTS]);
+	}
+
+	if ((int)options[OPT_EWGTS] && ewgts) {
+		printf("%s -- Applying weights for %d edges.\n",
+			   THISFUNCTION,start[nvtxs]/2);
+	}
+	else {
+		if      ( (int)options[OPT_EWGTS] && !ewgts)
+			printf("%s -- Edge weight flag=%d, but no edge weights specified.\n",
+				   THISFUNCTION,options[OPT_EWGTS]);
+		else if (!(int)options[OPT_EWGTS] &&  ewgts)
+			printf("%s -- Edge weight flag=%d, so specified edge weights ignored.\n",
+				   THISFUNCTION,options[OPT_EWGTS]);
+	}
+
+    if (goal) {
+        printf("%s -- Applying goals for %d sets.\n",
+               THISFUNCTION,nprocs);
+        tgoal = 0.;
+        for (i=0; i<nprocs; i++)
+            tgoal += goal[i];
+        for (i=0; i<nprocs; i++)
+            goal[i] *= (double)tvwgt/tgoal;
+    }
+
+	input_time += seconds() - time;
+
+	if (options[OPT_EIGTOL] > 0)
+		eigtol = options[OPT_EIGTOL];
+	else
+		eigtol = EIGEN_TOLERANCE;
+	if ((int)options[OPT_SEED] > 0)
+		seed = (int)options[OPT_SEED];
+	else
+		seed = RANDOM_SEED;
+
+/*  Chaco numbers vertices from 1 and the Matlab sparse data structure
+	numbers rows from 0, so increment the row indices for each column. */
+
+	for (i=0; i<start[nvtxs]; adjacency[i++]++);
+
+	printf("\n%s -- Calling Chaco interface:\n\n",
+		   THISFUNCTION);
+	flag = interface(nvtxs, start, adjacency,
+		  ((int)options[OPT_VWGTS] && vwgts ? vwgts : NULL),
+		  ((int)options[OPT_EWGTS] && ewgts ? ewgts : NULL),
+		  x, y, z,
+		  outassignptr, outfileptr,
+		  assignment,
+		  architecture, ndims_tot, mesh_dims, goal,
+		  global_method, local_method, rqi_flag, vmax, ndims,
+		  eigtol, seed);
+	printf("\n%s -- Chaco interface returning flag=%d.\n",
+		   THISFUNCTION,flag);
+
+/*  Reset adjacency matrix in case calling function needs it.  */
+
+	for (i=0; i<start[nvtxs]; adjacency[i++]--);
+
+	if (DEBUG_MEMORY > 0) {
+		printf("\n");
+		smalloc_stats();
+	}
+
+	if (params_file != NULL)
+		fclose(params_file);
+
+	if (DEBUG_TRACE > 1) {
+		printf("<Leaving main>\n");
+	}
+	
+	return(0);
+}
+
+
+int      input_parse(
+	char     *outassignname,	/* name of assignment output file */
+	char     *outfilename,		/* name of file for outputing run results */
+	int      *architecture,		/* 0=> hypercube, d=> d-dimensional mesh */
+	int      *ndims_tot,		/* target number of hypercube dimensions */
+	int       mesh_dims[3],		/* mesh dimensions */
+	int      *global_method,	/* what global partitioning strategy to use? */
+	int      *local_method,		/* what local refinement strategy to use? */
+	int      *rqi_flag,		/* should I use multilevel eigensolver? */
+	int      *vmax,			/* if so, how far should I coarsen? */
+	int      *ndims,		/* number of divisions at each stage */
+	int      *nprocs,		/* number of processors being divided into */
+	double   options[10],	/* architecture and partitioning options */
+	int      *nparts		/* number of parts options */
+)
+{
+	extern int SEQUENCE;	/* sequence instead of partition graph? */
+	extern int ARCHITECTURE;	/* 0=> hypercube, d=> d-dimensional mesh */
+	extern int OUTPUT_ASSIGN;	/* write assignments to file? */
+	extern int ECHO;		/* copy input to screen? results to file? */
+	extern int DEBUG_TRACE;	/* trace main execution path */
+	extern int PROMPT;		/* prompt for input? */
+	extern int MATCH_TYPE;      /* max-matching routine to call */
+	int       eigensolver;	/* which kind of eigensolver to use */
+
+	if (DEBUG_TRACE > 0) {
+		printf("<Entering input_parse>\n");
+	}
+
+	if (PROMPT) {
+		printf("Parallel machine architecture:\n");
+		printf("  (0) Hypercube\n");
+		printf("  (1) One-dimensional mesh\n");
+		printf("  (2) Two-dimensional mesh\n");
+		printf("  (3) Three-dimensional mesh\n");
+	}
+	*architecture = (int)options[OPT_ARCH];
+	if (*architecture < 0 || *architecture > 3) {
+		printf("%s -- Architecture %d must be between 0 and 3.\n",
+			   THISFUNCTION,options[OPT_ARCH]);
+		return(-1);
+	}
+
+	/* Name output assignment file. */
+	if (PROMPT)
+		printf("Assignment output file: ");
+	outassignname = NULL;
+
+	/* Name output results file. */
+	if (PROMPT)
+		printf("File name for saving run results: ");
+	outfilename = NULL;
+
+	/* Initialize the method flags */
+	*rqi_flag = 0;
+	*global_method = 0;
+
+	/* Get global method, if any. */
+	if (SEQUENCE) {
+		*global_method = 2;
+	}
+	else {
+		if (PROMPT) {
+			printf("Global partitioning method:\n");
+			printf("  (1) Multilevel-KL\n");
+			printf("  (2) Spectral\n");
+			printf("  (3) Inertial\n");
+			printf("  (4) Linear\n");
+			printf("  (5) Random\n");
+			printf("  (6) Scattered\n");
+			printf("  (7) Read-from-file\n");
+		}
+		*global_method = (int)options[OPT_GLOBAL];
+		if (*global_method < 1 || *global_method > 7) {
+			printf("%s -- Global method %d must be between 1 and 7.\n",
+				   THISFUNCTION,options[OPT_GLOBAL]);
+			return(-1);
+		}
+	}
+
+	if (*global_method == 7) {	/* Name and open input assignment file. */
+		if (PROMPT)
+			printf("Assignment input file: ");
+	}
+
+	else if (*global_method == 3) {
+		if (PROMPT)
+			printf("Geometry input file name: ");
+	}
+
+	else if (*global_method == 2) {
+		if (PROMPT) {
+			printf("Eigensolver:\n");
+			printf("  (1) Multilevel RQI/Symmlq\n");
+			printf("  (2) Lanczos\n"); 
+		}
+		eigensolver = (int)options[OPT_RQI];
+		if (eigensolver < 0 || eigensolver > 2) {
+			printf("%s -- RQI/Symmlq flag %d must be between 0 and 2.\n",
+				   THISFUNCTION,options[OPT_RQI]);
+			return(-1);
+		}
+		if (eigensolver == 1) {
+			if (MATCH_TYPE == 5) {	/* geometric matching */
+				if (PROMPT)
+					printf("Geometry input file name: ");
+			}
+			*rqi_flag = 1;
+			if (PROMPT)
+				printf("Number of vertices to coarsen down to: ");
+			*vmax = (int)options[OPT_VMAX];
+			if (*vmax <= 0) {
+				printf("%s -- Vmax %d must be greater then 0.\n",
+					   THISFUNCTION,options[OPT_VMAX]);
+				return(-1);
+			}
+		}
+		else if (eigensolver == 0 || eigensolver == 2) {
+			*rqi_flag = 0;
+		}
+	}
+
+	else if (*global_method == 1) {
+		if (MATCH_TYPE == 5) {		/* geometric matching */
+			if (PROMPT)
+				printf("Geometry input file name: ");
+		}
+		if (PROMPT)
+			printf("Number of vertices to coarsen down to: ");
+		*vmax = (int)options[OPT_VMAX];
+		if (*vmax <= 0) {
+			printf("%s -- Vmax %d must be greater then 0.\n",
+				   THISFUNCTION,options[OPT_VMAX]);
+			return(-1);
+		}
+	}
+
+	if (SEQUENCE) {
+		*local_method = 2;
+		if (*architecture == 0) {
+			*ndims_tot = 1;
+		}
+		else if (*architecture > 0) {
+			mesh_dims[0] = 2;
+			mesh_dims[1] = mesh_dims[2] = 1;
+		}
+		*ndims = 1;
+		goto End_Label;
+	}
+
+	/* Get local method, if any */
+	*local_method = 0;
+	if (*global_method == 1)
+		*local_method = 1;
+	else {
+		if (PROMPT) {
+			printf("Local refinement method:\n");
+			printf("  (1) Kernighan-Lin\n");
+			printf("  (2) None\n");
+		}
+		*local_method = (int)options[OPT_LOCAL];
+		if (*local_method < 1 || *local_method > 2) {
+			printf("%s -- Local method %d must be 1 and 2.\n",
+				   THISFUNCTION,options[OPT_LOCAL]);
+			return(-1);
+		}
+	}
+
+	/* Now learn about the parallel architecture. */
+	if (*architecture == 0) {
+	/* Get total number of hypercube dimensions in which to partition. */
+		*ndims_tot = 0;
+		if (PROMPT)
+			printf("Total number of target hypercube dimensions: ");
+		*ndims_tot = nparts[0];
+		if (*ndims_tot < 1) {
+			printf(" Number of divisions must be at least 1\n");
+			printf("%s -- Number of divisions %d must be at least 1.\n",
+				   THISFUNCTION,nparts[0]);
+			return(-1);
+		}
+		*nprocs = 1 << (*ndims_tot);
+	}
+
+	else {			/* Get dimensions of mesh. */
+		mesh_dims[1] = mesh_dims[2] = 1;
+		if (*architecture == 2) {
+			if (PROMPT)
+				printf("X and Y extent of of 2-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			mesh_dims[1] = nparts[1];
+		}
+		else if (*architecture == 3) {
+			if (PROMPT)
+				printf("X, Y and Z extent of 3-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			mesh_dims[1] = nparts[1];
+			mesh_dims[2] = nparts[2];
+		}
+		else {			/* Anything else => 1-D mesh */
+			if (PROMPT)
+				printf("Size of 1-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			*architecture = 1;
+		}
+		*nprocs = mesh_dims[0] * mesh_dims[1] * mesh_dims[2];
+	}
+
+	/* Get number of dimensions in which to partition at each level. */
+	*ndims = 0;
+	if (*nprocs <= 3) {
+		*ndims = 1;
+	}
+	else if (*nprocs <= 7) {
+		if (PROMPT) {
+			printf("Partitioning dimension: \n");
+			printf("  (1) Bisection\n");
+			printf("  (2) Quadrisection\n");
+		}
+		*ndims = (int)options[OPT_NDIMS];
+		if (*ndims < 1 || *ndims > 2) {
+			printf("%s -- Ndims %d must be 1 or 2 for %d processors.\n",
+				   THISFUNCTION,options[OPT_NDIMS],*nprocs);
+			return(-1);
+		}
+	}
+	else {
+		if (PROMPT) {
+			printf("Partitioning dimension: \n");
+			printf("  (1) Bisection\n");
+			printf("  (2) Quadrisection\n");
+			printf("  (3) Octasection\n");
+		}
+		*ndims = (int)options[OPT_NDIMS];
+		if (*ndims < 1 || *ndims > 3) {
+			printf("%s -- Ndims %d must be between 1 and 3 for %d processors.\n",
+				   THISFUNCTION,options[OPT_NDIMS],*nprocs);
+			return(-1);
+		}
+	}
+End_Label: 
+
+	if (*global_method == 1 || *rqi_flag) {
+		if (*vmax < 2 * (1 << *ndims)) {
+			*vmax = 2 * (1 << *ndims);
+		}
+	}
+
+	return(0);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/Makefile	(revision 18231)
@@ -0,0 +1,293 @@
+# This is the Makefile for the mex-file version of Chaco, to be dynamically 
+# linked with Matlab using the interface in the "meshpart" toolbox.  
+# See file "README" for more information.
+#
+# You may need to change the following variables:
+# 
+# MATLAB      Matlab's top-level directory, often "/usr/matlab" or similar.
+# CHACO       Chaco's source directory, normally the "code" subdirectory
+#             of the Chaco distribution.
+# MLCHACO     Directory with Chaco files modified for Matlab, normally
+#             the directory containing this Makefile.
+# DEST_DIR    Directory for the executable mlchaco.mex, normally the 
+#             "meshpart" directory, which is normally the parent of the 
+#             directory containing this Makefile.
+# CC          Choice of C compiler.  gcc seems to work best for Matlab for me.
+# IFLAGS, CFLAGS, OFLAGS  Flags to go with the compiler and linker.
+#
+# This Makefile works under Solaris 2.  To use it with a different Unix, 
+# you may need to change the references to "ar" and/or "ranlib" and
+# possibly other things.
+#
+# John Gilbert, 1996.
+# Copyright (c) 1990-1996 by Xerox Corporation.  All rights reserved.
+# See file ../copyright.m for complete copyright and licensing notice.
+
+#MATLAB =        /import/matlab
+#MATLAB =        /usr/local/libexec/matlab
+#MATLAB =        /usr/local/pkgs/matlab-7.6
+MATLAB =        ${MATLAB_DIR}
+
+#CHACO =         /project/sparse/chaco/version2/code
+#CHACO =         ../../Chaco-2.0/code
+#CHACO =         ../../Chaco-2.2/code
+#CHACO =         ../../../chaco/src/code
+CHACO =         ${CHACO_DIR}/../src/code
+
+MLCHACO =       .
+DEST_DIR =      ..
+CC =            gcc 
+#CC =            cc 
+IFLAGS =	-I${MATLAB}/extern/include -I${CHACO}/main
+#CFLAGS =        -Xa -G -xO4 -xcg92
+#CFLAGS =        -fPIC -fno-omit-frame-pointer -pthread -fexceptions -DMATLAB
+CFLAGS =        -fPIC -fno-omit-frame-pointer -pthread -fexceptions
+#OFLAGS =        -xO4 -xcg92
+OFLAGS =        -O2
+#AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+AR =             /usr/bin/ar rcv   # for solaris 2
+#RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+RANLIB =         /usr/bin/ranlib   # for solaris 2
+
+
+MLFILES.c=	${MLCHACO}/Chacox.c \
+                ${MLCHACO}/user_params.c
+#		${MLCHACO}/bail.c \  # redefined original with -DMATLAB
+#		${MLCHACO}/chaco_check_graph.c \  # redefined original with -DMATLAB
+#		${MLCHACO}/check_input.c \  # redefined original with -DMATLAB
+#                ${MLCHACO}/smalloc.c \  # redefined original with -DMATLAB
+
+CHFILES.c=	${CHACO}/main/interface.c \
+		${CHACO}/main/main.c \
+		${CHACO}/submain/balance.c \
+		${CHACO}/submain/divide.c \
+		${CHACO}/submain/submain.c \
+		${CHACO}/input/input_assign.c \
+		${CHACO}/input/check_input.c \
+		${CHACO}/input/input.c \
+		${CHACO}/input/input_geom.c \
+		${CHACO}/input/input_graph.c \
+		${CHACO}/input/read_params.c \
+		${CHACO}/input/reflect_input.c \
+		${CHACO}/input/read_val.c \
+		${CHACO}/graph/check_graph.c \
+		${CHACO}/graph/free_graph.c \
+		${CHACO}/graph/reformat.c \
+		${CHACO}/graph/subgraph.c \
+		${CHACO}/graph/graph_out.c \
+		${CHACO}/inertial/eigenvec2.c \
+		${CHACO}/inertial/eigenvec3.c \
+		${CHACO}/inertial/inertial.c \
+		${CHACO}/inertial/inertial1d.c \
+		${CHACO}/inertial/inertial2d.c \
+		${CHACO}/inertial/inertial3d.c \
+		${CHACO}/inertial/make_subgeom.c \
+		${CHACO}/klspiff/buckets.c \
+		${CHACO}/klspiff/buckets_bi.c \
+		${CHACO}/klspiff/buckets1.c \
+		${CHACO}/klspiff/bilistops.c \
+		${CHACO}/klspiff/coarsen_kl.c \
+		${CHACO}/klspiff/count_weights.c \
+		${CHACO}/klspiff/compress_ewgts.c \
+		${CHACO}/klspiff/kl_init.c \
+		${CHACO}/klspiff/kl_output.c \
+		${CHACO}/klspiff/klspiff.c \
+		${CHACO}/klspiff/make_bndy_list.c \
+		${CHACO}/klspiff/make_kl_list.c \
+		${CHACO}/klspiff/nway_kl.c \
+		${CHACO}/klvspiff/bpm_improve.c \
+		${CHACO}/klvspiff/bucketsv.c \
+		${CHACO}/klvspiff/clear_dvals.c \
+		${CHACO}/klvspiff/coarsen_klv.c \
+		${CHACO}/klvspiff/countup_vtx_sep.c \
+		${CHACO}/klvspiff/find_bndy.c \
+		${CHACO}/klvspiff/flow.c \
+		${CHACO}/klvspiff/klv_init.c \
+		${CHACO}/klvspiff/klvspiff.c \
+		${CHACO}/klvspiff/make_bpgraph.c \
+		${CHACO}/klvspiff/make_sep_list.c \
+		${CHACO}/klvspiff/matching.c \
+		${CHACO}/klvspiff/nway_klv.c \
+		${CHACO}/klvspiff/flatten.c \
+		${CHACO}/coarsen/coarsen.c \
+		${CHACO}/coarsen/interpolate.c \
+		${CHACO}/coarsen/makefgraph.c \
+		${CHACO}/coarsen/makeccoords.c \
+		${CHACO}/coarsen/coarsen1.c \
+		${CHACO}/coarsen/makev2cv.c \
+		${CHACO}/coarsen/maxmatch.c \
+		${CHACO}/coarsen/maxmatch1.c \
+		${CHACO}/coarsen/maxmatch2.c  \
+		${CHACO}/coarsen/maxmatch3.c \
+		${CHACO}/coarsen/maxmatch4.c \
+		${CHACO}/coarsen/maxmatch5.c \
+		${CHACO}/connect/add_edges.c \
+		${CHACO}/connect/connected.c \
+		${CHACO}/connect/find_edges.c \
+		${CHACO}/eigen/bidir.c \
+		${CHACO}/eigen/bisect.c \
+		${CHACO}/eigen/checkeig.c \
+		${CHACO}/eigen/checkeig_ext.c \
+		${CHACO}/eigen/checkorth.c \
+		${CHACO}/eigen/cksturmcnt.c \
+		${CHACO}/eigen/mkeigvecs.c\
+		${CHACO}/eigen/eigensolve.c \
+		${CHACO}/eigen/get_extval.c \
+		${CHACO}/eigen/get_ritzvals.c \
+		${CHACO}/eigen/lanczos_FO.c \
+		${CHACO}/eigen/lanczos_SO.c \
+		${CHACO}/eigen/lanczos_SO_float.c \
+		${CHACO}/eigen/lanczos_ext.c \
+		${CHACO}/eigen/lanczos_ext_float.c \
+		${CHACO}/eigen/lanc_seconds.c\
+		${CHACO}/eigen/lanpause.c \
+		${CHACO}/eigen/makeorthlnk.c \
+		${CHACO}/eigen/mkscanlist.c \
+		${CHACO}/eigen/orthog1.c \
+		${CHACO}/eigen/orthogonalize.c \
+		${CHACO}/eigen/orthogvec.c \
+		${CHACO}/eigen/ql.c \
+		${CHACO}/eigen/rqi.c \
+		${CHACO}/eigen/rqi_ext.c \
+		${CHACO}/eigen/scale_diag.c \
+		${CHACO}/eigen/scanmax.c \
+		${CHACO}/eigen/scanmin.c \
+		${CHACO}/eigen/solistout.c \
+		${CHACO}/eigen/sorthog.c \
+		${CHACO}/eigen/splarax.c \
+		${CHACO}/eigen/sturmcnt.c \
+		${CHACO}/eigen/Tevec.c \
+		${CHACO}/eigen/tri_solve.c \
+		${CHACO}/eigen/warnings.c \
+		${CHACO}/symmlq/aprod.c \
+		${CHACO}/symmlq/msolve.c \
+		${CHACO}/symmlq/pow_dd.c \
+		${CHACO}/symmlq/symmlq.c \
+		${CHACO}/symmlq/symmlqblas.c \
+		${CHACO}/tinvit/tinvit.c \
+		${CHACO}/tinvit/pythag.c \
+		${CHACO}/tinvit/epslon.c \
+		${CHACO}/optimize/determinant.c \
+		${CHACO}/optimize/func2d.c \
+		${CHACO}/optimize/func3d.c \
+		${CHACO}/optimize/opt2d.c \
+		${CHACO}/optimize/opt3d.c \
+		${CHACO}/assign/assign.c \
+		${CHACO}/assign/assign_out.c \
+		${CHACO}/assign/mapper.c \
+		${CHACO}/assign/median.c \
+		${CHACO}/assign/merge_assign.c \
+		${CHACO}/assign/rec_median.c \
+		${CHACO}/assign/rotate.c \
+		${CHACO}/assign/y2x.c \
+		${CHACO}/bpmatch/checkbp.c \
+		${CHACO}/bpmatch/inits2d.c \
+		${CHACO}/bpmatch/inits3d.c \
+		${CHACO}/bpmatch/genvals2d.c \
+		${CHACO}/bpmatch/genvals3d.c \
+		${CHACO}/bpmatch/map2d.c \
+		${CHACO}/bpmatch/map3d.c \
+		${CHACO}/bpmatch/movevtxs.c \
+		${CHACO}/bpmatch/sorts2d.c \
+		${CHACO}/bpmatch/sorts3d.c \
+		${CHACO}/refine_map/compute_cube_edata.c \
+		${CHACO}/refine_map/compute_cube_vdata.c \
+		${CHACO}/refine_map/refine_cube.c \
+		${CHACO}/refine_map/update_cube_edata.c \
+		${CHACO}/refine_map/update_cube_vdata.c \
+		${CHACO}/refine_map/find_edge_cube.c \
+		${CHACO}/refine_map/init_cube_edata.c \
+		${CHACO}/refine_map/compute_mesh_edata.c \
+		${CHACO}/refine_map/compute_mesh_vdata.c \
+		${CHACO}/refine_map/find_edge_mesh.c \
+		${CHACO}/refine_map/init_mesh_edata.c \
+		${CHACO}/refine_map/refine_mesh.c \
+		${CHACO}/refine_map/update_mesh_edata.c \
+		${CHACO}/refine_map/update_mesh_vdata.c \
+		${CHACO}/refine_map/refine_map.c \
+		${CHACO}/refine_map/make_comm_graph.c \
+		${CHACO}/refine_part/refine_part.c \
+		${CHACO}/refine_part/kl_refine.c \
+		${CHACO}/refine_part/make_maps_ref.c \
+		${CHACO}/refine_part/make_terms_ref.c \
+		${CHACO}/internal/force_internal.c \
+		${CHACO}/internal/improve_internal.c \
+		${CHACO}/internal/check_internal.c \
+		${CHACO}/misc/define_subcubes.c \
+		${CHACO}/misc/define_submeshes.c \
+		${CHACO}/misc/divide_procs.c \
+		${CHACO}/misc/merge_goals.c \
+		${CHACO}/misc/make_term_props.c \
+		${CHACO}/misc/count.c \
+		${CHACO}/misc/countup.c \
+		${CHACO}/misc/countup_cube.c \
+		${CHACO}/misc/countup_mesh.c \
+		${CHACO}/misc/make_subgoal.c \
+		${CHACO}/misc/find_maxdeg.c \
+		${CHACO}/misc/make_maps.c \
+		${CHACO}/misc/make_setlists.c \
+		${CHACO}/misc/sequence.c \
+		${CHACO}/misc/perturb.c \
+		${CHACO}/misc/simple_part.c \
+		${CHACO}/misc/time_kernels.c \
+		${CHACO}/misc/timing.c \
+		${CHACO}/util/affirm.c \
+		${CHACO}/util/array_alloc_2D.c \
+		${CHACO}/util/bit_reverse.c \
+		${CHACO}/util/checkpnt.c \
+		${CHACO}/util/cpvec.c \
+		${CHACO}/util/dot.c \
+		${CHACO}/util/doubleout.c \
+		${CHACO}/util/input_int.c \
+		${CHACO}/util/gray.c \
+		${CHACO}/util/machine_params.c \
+		${CHACO}/util/makevwsqrt.c \
+		${CHACO}/util/mkvec.c \
+		${CHACO}/util/norm.c \
+		${CHACO}/util/normalize.c \
+		${CHACO}/util/mergesort.c \
+		${CHACO}/util/randomize.c \
+		${CHACO}/util/smalloc.c \
+		${CHACO}/util/bail.c \
+		${CHACO}/util/scadd.c \
+		${CHACO}/util/seconds.c \
+		${CHACO}/util/setvec.c \
+		${CHACO}/util/shell_sort.c \
+		${CHACO}/util/strout.c \
+		${CHACO}/util/tri_prod.c \
+		${CHACO}/util/true_or_false.c \
+		${CHACO}/util/update.c  \
+		${CHACO}/util/vecout.c \
+		${CHACO}/util/vecran.c \
+		${CHACO}/util/vecscale.c 
+#		${CHACO}/main/user_params.c \
+
+MLFILES.o=      $(MLFILES.c:.c=.o)
+
+CHFILES.o=      $(CHFILES.c:.c=.o)
+
+#mlchaco:        ${MLFILES.o} chaco.a Makefile
+#		${MATLAB}/bin/cmex CC='gcc -G' -lm ${OFLAGS} ${MLFILES.o} chaco.a; \
+#                 mv mlchaco.mex* ${DEST_DIR}
+
+#mlchaco:	${MLFILES.c} chaco.a Makefile
+#		mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+#		mv mlchaco.mex* ${DEST_DIR}
+
+#mlchaco:	${MLFILES.c} ${CHFILES.c} ${CHACO}/chaco.a Makefile
+#		${MATLAB}/bin/mex mlchaco.c -largeArrayDims -DMATLAB ${MLFILES.c} ${CHACO}/chaco.a -I${CHACO}/main
+#		mv mlchaco.mex* ${DEST_DIR}
+
+Chaco:	${MLFILES.c} ${CHFILES.c} ${CHACO}/chaco.a Makefile
+		${MATLAB}/bin/mex Chaco.c -largeArrayDims ${MLFILES.c} ${CHACO}/chaco.a -I${CHACO}/main
+#		mv Chaco.mex* ${DEST_DIR}
+
+chaco.a:        ${CHFILES.o}
+		${AR} ${CHACO}/chaco.a ${CHFILES.o} ; ${RANLIB} ${CHACO}/chaco.a
+
+clean:
+		rm -f ${CHACO}/*/*.o chaco.a ${MLCHACO}/*.o ${DEST_DIR}/core
+
+.c.o:
+		${CC} -c ${IFLAGS} ${CFLAGS} -o $*.o $*.c
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.debug
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.debug	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.debug	(revision 18231)
@@ -0,0 +1,27 @@
+% This file, User_Params, is read at runtime to modify Chaco's defaults.
+% The purpose of this version is to turn on some debugging stuff that
+% the Matlab version will normally have off.
+
+ECHO = 2
+OUTPUT_METRICS = 2
+OUTPUT_TIME = 2
+PRINT_HEADERS = 1
+
+DEBUG_EVECS = 1
+DEBUG_KL = 1
+DEBUG_INERTIAL = 1
+DEBUG_CONNECTED = 1
+DEBUG_PERTURB = 1
+DEBUG_ASSIGN = 1
+DEBUG_OPTIMIZE = 1
+DEBUG_BPMATCH = 1
+DEBUG_COARSEN = 1
+DEBUG_MEMORY = 1
+DEBUG_INPUT = 0
+DEBUG_PARAMS = 1
+DEBUG_INTERNAL = 1
+DEBUG_REFINE_PART = 1
+DEBUG_REFINE_MAP = 1
+DEBUG_SIMULATOR = 1
+DEBUG_TRACE = 1
+DEBUG_MACH_PARAMS = 1
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.verbose
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.verbose	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/User_Params.verbose	(revision 18231)
@@ -0,0 +1,8 @@
+% This file, User_Params, is read at runtime to modify Chaco's defaults.
+% The purpose of this version is to turn on some verbose output that
+% the Matlab version will normally have off.
+
+ECHO = 1
+OUTPUT_METRICS = 1
+OUTPUT_TIME = 1
+PRINT_HEADERS = 1
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/user_params.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/user_params.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mex/user_params.c	(revision 18231)
@@ -0,0 +1,142 @@
+/* This software was developed by Bruce Hendrickson and Robert Leland   *
+ * at Sandia National Laboratories under US Department of Energy        *
+ * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+
+/* Modified by John Gilbert 25 Aug 1995 for Matlab mex-file interface   */
+/* Modified by Tim Davis, July 6, 1998, for Matlab 5.1 interface, and */
+/* a more picky compiler (cc) that complains about duplicate global */
+/* declarations. */
+
+#include "params.h"
+
+#define  TRUE  1
+#define  FALSE 0
+
+
+/* Input and ouput control parameters */
+
+int       CHECK_INPUT = TRUE;	 /* Check input for consistency? (TRUE/FALSE) */
+int       ECHO = 0;		 /* Print input/param options? to file? (-2..2) */
+int       OUTPUT_METRICS = 0;	 /* Controls displaying of results (-2..2) */
+int       OUTPUT_TIME = 0;	 /* At what level to display timings (0..2) */
+int       OUTPUT_ASSIGN = FALSE; /* Write assignments to file? (TRUE/FALSE) */
+int       OUT_ASSIGN_INV = FALSE;/* If so, use inverse form? (TRUE/FALSE) */
+int       IN_ASSIGN_INV = FALSE; /* Input file in inverse form? (TRUE/FALSE) */
+int       PROMPT = FALSE;	 /* Prompt for input? (TRUE/FALSE) */
+int       PRINT_HEADERS = FALSE; /* Print pretty output headers (TRUE/FALSE) */
+
+
+/* Eigenvector calculation parameters */
+
+int       LANCZOS_TYPE = 3;	/* type of Lanczos to use */
+				/* 1 => full orthog, 2 => full inverse operator */
+				/* 3 =>  selective orthogonalization */
+double    EIGEN_TOLERANCE = 1e-3;	/* Numerical eigen-tolerance */
+double    SRESTOL = -1.;		/* Rel resid tol on T evec; autoset if <= 0 */
+int       LANCZOS_SO_INTERVAL = 10;	/* Itns. between SO orthog checks; set >= 2 */
+int       LANCZOS_MAXITNS = -1;		/* Max Lanczos its; autoset if <= 0 */
+double    BISECTION_SAFETY = 10;	/* Divides Lanczos bisection tol */
+int       LANCZOS_CONVERGENCE_MODE = 0;	/* Lanczos convergence test type: */
+					/* 0=> residual,  1=> partition */
+int       RQI_CONVERGENCE_MODE = 1;	/* RQI convergence test type: */
+					/* 0=> residual,  1=> partition */
+int       LANCZOS_SO_PRECISION = 2;	/* 2 => double Lanczos, 1 => float */
+int       WARNING_EVECS = 2;	/* Warnings in eigenvector generation (0..3) */
+double    WARNING_ORTHTOL = 2;	/* Warning if Ares and bjitol have this ratio */
+double    WARNING_MISTOL = 100;	/* Warning if Ares and bjitol have this ratio */
+int       LANCZOS_TIME = FALSE;	/* Detailed Lanczos times? (TRUE/FALSE) */
+int       TIME_KERNELS = FALSE;	/* Time numerical kernels? (TRUE/FALSE) */
+
+
+/* Other parameters for spectral methods */
+
+int       MAKE_CONNECTED = TRUE;/* Connect graph if using spectral method? */
+int       PERTURB = TRUE;	/* Randomly perturb matrix in spectral method? */
+int       NPERTURB = 2;		/* If so, how many edges to modify? */
+double    PERTURB_MAX = 3.0e-3;	/* Largest value for perturbation */
+int       MAPPING_TYPE = 1;	/* How to map from eigenvectors to partition */
+				/* 0 => cut at origin, 1 => min-cost assign */
+int       COARSE_NLEVEL_RQI = 2;/* # levels between RQI calls in uncoarsening */
+int       OPT3D_NTRIES = 5;	/* # local opts to look for global min in opt3d */
+
+
+/* Kernighan--Lin/Fiduccia--Mattheyses parameters */
+
+int       KL_METRIC = 2;	/* KL interset cost: 1=>cuts, 2=>hops */
+int       KL_RANDOM = TRUE;	/* Use randomness in Kernighan-Lin? (TRUE/FALSE)*/
+int       KL_BAD_MOVES = 20;	/* Number of unhelpful moves in a row allowed */
+int       KL_NTRIES_BAD = 1;	/* # unhelpful passes before quitting KL */
+int       KL_UNDO_LIST = TRUE;	/* Only resort changed vtxs? (TRUE/FALSE) */
+double    KL_IMBALANCE = 0.0;	/* Fractional imbalance allowed by KL */
+
+
+/* Coarsening parameters */
+
+double    COARSEN_RATIO_MIN = .7;  /* Min vtx reduction each coarsen stage */
+int       COARSE_NLEVEL_KL = 2;	   /* # levels between KL calls in uncoarsening */
+int       MATCH_TYPE = 1;	   /* Type of contraction matching (1..4) */
+int       HEAVY_MATCH = FALSE;	   /* Encourage heavy match edges? (TRUE/FALSE) */
+int       COARSE_KL_BOTTOM = TRUE; /* Force KL at lowest level (TRUE/FALSE) */
+int       COARSEN_VWGTS = TRUE;	   /* Sum vtx weights in coarsening? (TRUE/FALSE) */
+int       COARSEN_EWGTS = TRUE;	   /* Sum edge weights in coarsening? (TRUE/FALSE) */
+int       KL_ONLY_BNDY = TRUE;	   /* Start moving vtxs on boundary? (TRUE/FALSE) */
+
+
+/* Parameters for post-processing options */
+
+int       REFINE_PARTITION = FALSE;	/* Postprocess to improve cuts? */
+int       INTERNAL_VERTICES = FALSE;	/* ... to up internal vtxs? (TRUE/FALSE) */
+int       REFINE_MAP = FALSE;		/* ... to reduce hops? (TRUE/FALSE) */
+
+
+/* Architecture and simulator parameters */
+
+int       ARCHITECTURE = 0;	/* 0=> hypercube, d=> d-dimensional mesh (0..3)*/
+
+/* Modified by Tim Davis:  remove duplicate definitions */
+#ifdef DUPLICATE_DEFINITIONS_REMOVED
+int       SIMULATOR = 0;	/* Run simulator? In what mode? */
+int       SIMULATION_ITNS = 1;	/* # iterations simulator is to imitate. */
+int       PERCENTAGE_OUTPUT = FALSE;	/* Output in percent? (TRUE/FALSE) */
+double    CUT_COST = 0.0;	/* Communication cost of a cut-edge. */
+double    HOP_COST = 0.0;	/* Communication cost of a hop. */
+double    BDY_COST = 0.0;	/* Cost associated with boundary vertices.  */
+double    BDY_HOP_COST = 0.0;	/* Cost associated with boundary hops. */
+double    STARTUP_COST = 0.0;	/* Communication cost of a message startup. */
+	/* Note: nCUBE2 startup: 112e-6, per byte: 4.6e-6, buffering 5.6e-6 */
+	/* Intel Paragon startup: 70e-6, per byte: 5.3e-8 */
+#endif
+
+/* Miscellaneous parameters */
+
+int       TERM_PROP = FALSE;	/* Invoke terminal propagation? (TRUE/FALSE) */
+double    CUT_TO_HOP_COST = 1;	/* ..if so, relative importance of cuts/hops */
+int       SEQUENCE = FALSE;	/* Only do spectral ordering? (TRUE/FALSE) */
+char      SEQ_FILENAME[NAME_LENGTH] = "Sequence.out";	/* If so, file name */
+long      RANDOM_SEED = 7654321L;	/* Seed for random number generator */
+int       NSQRTS = 1000;	/* # square roots to precompute if coarsening */
+int       MAKE_VWGTS = FALSE;	/* Make vtx weights degrees+1? (TRUE/FALSE) */
+int       FREE_GRAPH = FALSE;	/* Free input graph data? (TRUE/FALSE) */
+char     *PARAMS_FILENAME = "User_Params";	/* File of parameter changes */
+
+
+/* Parameters that control debugging output */
+
+int       DEBUG_EVECS = 0;	/* Debug flag for eigenvector generation (0..5) */
+int       DEBUG_KL = 0;		/* Debug flag for Kernighan-Lin (0..3) */
+int       DEBUG_INERTIAL = 0;	/* Debug flag for inertial method (0..1) */
+int       DEBUG_CONNECTED = 0;	/* Debug flag for connected components (0..1) */
+int       DEBUG_PERTURB = 0;	/* Debug flag for matrix perturbation (0..1) */
+int       DEBUG_ASSIGN = 0;	/* Debug flag for assignment to sets (0..1) */
+int       DEBUG_OPTIMIZE = 0;	/* Debug flag for optimization/rotation (0..2) */
+int       DEBUG_BPMATCH = 0;	/* Debug flag for bipartite matching code (0..2) */
+int       DEBUG_COARSEN = 0;	/* Debug flag for coarsening/uncoarsening (0..1) */
+int       DEBUG_MEMORY = 0;	/* Debug flag for smalloc/sfree (0..3) */
+int       DEBUG_INPUT = 0;	/* Debug flag for having read input files (0..1) */
+int       DEBUG_PARAMS = 1;	/* Debug flag for reading parameter file (0..2) */
+int       DEBUG_INTERNAL = 0;	/* Debug flag for internal vertices (0..2) */
+int       DEBUG_REFINE_PART = 0;/* Debug flag for refine partition (0..1) */
+int       DEBUG_REFINE_MAP = 0;	/* Debug flag for refining mapping (0..1) */
+int       DEBUG_SIMULATOR = 0;	/* Debug flag for comm simulator (0..2) */
+int       DEBUG_TRACE = 0;	/* Trace main execution path (0..2) */
+int       DEBUG_MACH_PARAMS = 0;/* Print computed machine params? (0..1) */
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_README.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_README.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_README.txt	(revision 18231)
@@ -0,0 +1,136 @@
+mlchaco (from meshpartdist.tar, 2/08/02)
+http://www.cerfacs.fr/algor/Softs/MESHPART/
+
+
+[jschierm@astrid chaco]$ diff mlchaco_old.c mlchaco.c
+34a35  [CLK_TCK undefined, so use CLOCKS_PER_SEC]
+> #include <time.h>      /*  CLOCKS_PER_SEC  */
+56,61c57,62  [update for current Matlab]
+< void mexFunction(    
+<     int         nlhs,           /* number of expected outputs */
+<     Matrix      *plhs[],        /* matrix pointer array returning outputs */
+<     int         nrhs,           /* number of inputs */
+<     Matrix      *prhs[]         /* matrix pointer array for inputs */
+<     )
+---
+> void mexFunction(
+>     int           nlhs,           /* number of expected outputs */
+>     mxArray       *plhs[],        /* array of pointers to output arguments
+>     */
+>     int           nrhs,           /* number of inputs */
+>     const mxArray *prhs[]         /* array of pointers to input arguments */
+> )
+87a89  [update for current Matlab]
+>     mwIndex *mwstart,*mwadjacency;
+104c106,110  [update for current Matlab]
+<     start = mxGetJc(A_in);
+---
+> /*    start = mxGetJc(A_in);*/
+>     mwstart = mxGetJc(A_in);
+>     start = mxMalloc((mxGetN(A_in)+1)*sizeof(int));
+>     for (i=0; i<(mxGetN(A_in)+1); i++)
+>         start[i]= (int)mwstart[i];
+106c112,116  [update for current Matlab]
+<     adjacency = mxGetIr(A_in);
+---
+> /*    adjacency = mxGetIr(A_in);*/
+>     mwadjacency = mxGetIr(A_in);
+>     adjacency = mxMalloc(mxGetNzmax(A_in)*sizeof(int));
+>     for (i=0; i<mxGetNzmax(A_in); i++)
+>         adjacency[i]= (int)mwadjacency[i];
+131,132c141,144  [provide default filenames, since no way to input]
+<     outassignname = NULL;
+<     outfilename = NULL;
+---
+> /*    outassignname = NULL;
+>     outfilename = NULL;*/
+>     outassignname = "chaco_assign.txt";
+>     outfilename = "chaco_out.txt";
+169c181  [update for current Matlab]
+<       plhs [1] = mxCreateFull (1, 1, REAL) ;
+---
+>       plhs [1] = mxCreateDoubleMatrix (1, 1, mxREAL) ;
+173c185  [CLK_TCK undefined, so use CLOCKS_PER_SEC]
+<       ((double) CLK_TCK) ;
+---
+>       ((double) CLOCKS_PER_SEC) ;
+179c191  [update for current Matlab]
+<         map_out = mxCreateFull(1,nvtxs,REAL);
+---
+>         map_out = mxCreateDoubleMatrix(1,nvtxs,mxREAL);
+185a198,199  [update for current Matlab]
+>     if (start != NULL) mxFree((char *) start);
+>     if (adjacency != NULL) mxFree((char *) adjacency);
+
+
+[jschierm@astrid chaco]$ diff Makefile_old Makefile
+27c27,28  [current Matlab location]
+< MATLAB =        /usr/local/libexec/matlab
+---
+> #MATLAB =        /usr/local/libexec/matlab
+> MATLAB =        /usr/local/pkgs/matlab-7.6
+30c31,32  [current Chaco 2.2 location]
+< CHACO =         ../../Chaco-2.0/code
+---
+> #CHACO =         ../../Chaco-2.0/code
+> CHACO =         ../../Chaco-2.2/code
+34,35c36,37  [use gcc instead of cc]
+< #CC =            gcc 
+< CC =            cc 
+---
+> CC =            gcc 
+> #CC =            cc 
+37c39,40  [add MATLAB flag to compile for mex-function]
+< CFLAGS =        -Xa -G -xO4 -xcg92
+---
+> #CFLAGS =        -Xa -G -xO4 -xcg92
+> CFLAGS =        -Xa -G -xO4 -xcg92 -DMATLAB
+39,40c42,45  [current function locations]
+< AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+< RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+---
+> #AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+> AR =             /usr/bin/ar rcv   # for solaris 2
+> #RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+> RANLIB =         /usr/bin/ranlib   # for solaris 2
+45,47d49  [use Chaco versions with MATLAB switch rather than local versions]
+<               ${MLCHACO}/chaco_check_graph.c \
+<               ${MLCHACO}/check_input.c \
+<                 ${MLCHACO}/smalloc.c \
+48a51,53
+> #             ${MLCHACO}/chaco_check_graph.c \
+> #             ${MLCHACO}/check_input.c \
+> #                ${MLCHACO}/smalloc.c \
+55a61  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/input/check_input.c \
+61a68  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/graph/check_graph.c \
+91a99  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/klvspiff/flow.c \
+97a106  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/klvspiff/flatten.c \
+100c109,110  [update CHLIST to match Chaco 2.2]
+<               ${CHACO}/coarsen/makecgraph.c \
+---
+>               ${CHACO}/coarsen/makefgraph.c \
+>               ${CHACO}/coarsen/makeccoords.c \
+102d111  [update CHLIST to match Chaco 2.2]
+<               ${CHACO}/coarsen/countcedges.c \
+108a118  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/coarsen/maxmatch5.c \
+234a245  [update CHLIST to match Chaco 2.2]
+>               ${CHACO}/util/smalloc.c \
+245a257,258  [use local versions rather than Chaco versions (added for clarity)]
+> #             ${CHACO}/main/user_params.c \
+> #             ${CHACO}/util/bail.c \
+254a268,271  [update for current mex]
+> #mlchaco:     ${MLFILES.c} chaco.a Makefile
+> #             mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+> #             mv mlchaco.mex* ${DEST_DIR}
+> 
+256c273  [update for current mex]
+<               mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+---
+>               mex -output mlchaco -largeArrayDims -DMATLAB ${MLFILES.c}
+>               chaco.a -I${CHACO}/main
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_jes_notes.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_jes_notes.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/chaco/mlchaco_jes_notes.txt	(revision 18231)
@@ -0,0 +1,182 @@
+7/15/09:
+
+[jschierm@astrid chaco]$ diff Makefile_old Makefile
+27c27,28
+< MATLAB =        /usr/local/libexec/matlab
+---
+> #MATLAB =        /usr/local/libexec/matlab
+> MATLAB =        /usr/local/matlab780
+30c31,32
+< CHACO =         ../../Chaco-2.0/code
+---
+> #CHACO =         ../../Chaco-2.0/code
+> CHACO =         ../../Chaco-2.2/code
+34,35c36,37
+< #CC =            gcc 
+< CC =            cc 
+---
+> CC =            gcc 
+> #CC =            cc 
+39,40c41,44
+< AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+< RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+---
+> #AR =             /usr/ccs/bin/ar rcv   # for solaris 2
+> AR =             /usr/bin/ar rcv   # for solaris 2
+> #RANLIB =         /usr/ccs/bin/ranlib   # for solaris 2
+> RANLIB =         /usr/bin/ranlib   # for solaris 2
+91a96,97  [missing symbols]
+>               ${CHACO}/klvspiff/flatten.c \
+>               ${CHACO}/klvspiff/flow.c \
+99a106  [missing symbols]
+>               ${CHACO}/coarsen/makeccoords.c \
+102a110  [missing symbols]
+>               ${CHACO}/coarsen/makefgraph.c \
+108a117  [missing symbols]
+>               ${CHACO}/coarsen/maxmatch5.c \
+254a264,267
+> #mlchaco:     ${MLFILES.c} chaco.a Makefile
+> #             mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+> #             mv mlchaco.mex* ${DEST_DIR}
+> 
+256c269
+<               mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+---
+>               mex -output mlchaco -largeArrayDims ${MLFILES.c} chaco.a -I${CHACO}/main
+
+[jschierm@astrid chaco]$ diff mlchaco_old.c mlchaco.c
+34a35
+> #include <time.h>      /*  CLOCKS_PER_SEC  */
+56,61c57,62
+< void mexFunction(    
+<     int         nlhs,           /* number of expected outputs */
+<     Matrix      *plhs[],        /* matrix pointer array returning outputs */
+<     int         nrhs,           /* number of inputs */
+<     Matrix      *prhs[]         /* matrix pointer array for inputs */
+<     )
+---
+> void mexFunction(
+>     int           nlhs,           /* number of expected outputs */
+>     mxArray       *plhs[],        /* array of pointers to output arguments
+>     */
+>     int           nrhs,           /* number of inputs */
+>     const mxArray *prhs[]         /* array of pointers to input arguments */
+> )
+87a89
+>     mwIndex *mwstart,*mwadjacency;
+104c106,110
+<     start = mxGetJc(A_in);
+---
+> /*    start = mxGetJc(A_in);*/
+>     mwstart = mxGetJc(A_in);
+>     start = mxMalloc((mxGetN(A_in)+1)*sizeof(int));
+>     for (i=0; i<(mxGetN(A_in)+1); i++)
+>         start[i]= (int)mwstart[i];
+106c112,116
+<     adjacency = mxGetIr(A_in);
+---
+> /*    adjacency = mxGetIr(A_in);*/
+>     mwadjacency = mxGetIr(A_in);
+>     adjacency = mxMalloc(mxGetNzmax(A_in)*sizeof(int));
+>     for (i=0; i<mxGetNzmax(A_in); i++)
+>         adjacency[i]= (int)mwadjacency[i];
+169c181
+<       plhs [1] = mxCreateFull (1, 1, REAL) ;
+---
+>       plhs [1] = mxCreateDoubleMatrix (1, 1, mxREAL) ;
+173c185
+<       ((double) CLK_TCK) ;
+---
+>       ((double) CLOCKS_PER_SEC) ;
+179c191
+<         map_out = mxCreateFull(1,nvtxs,REAL);
+---
+>         map_out = mxCreateDoubleMatrix(1,nvtxs,mxREAL);
+185a198,199
+>     if (start != NULL) mxFree((char *) start);
+>     if (adjacency != NULL) mxFree((char *) adjacency);
+
+
+7/29/09:
+
+[jschierm@astrid chaco]$ diff mlchaco_old.c mlchaco.c
+131,132c141,144
+<     outassignname = NULL;
+<     outfilename = NULL;
+---
+> /*    outassignname = NULL;
+>     outfilename = NULL;*/
+>     outassignname = "chaco_assign.txt";
+>     outfilename = "chaco_out.txt";
+
+7/30/09:
+
+[jschierm@astrid chaco]$ diff Makefile_old Makefile
+27c27,28
+< MATLAB =        /usr/local/libexec/matlab
+---
+> #MATLAB =        /usr/local/libexec/matlab
+> MATLAB =        /usr/local/pkgs/matlab-7.6
+37c39,40
+< CFLAGS =        -Xa -G -xO4 -xcg92
+---
+> #CFLAGS =        -Xa -G -xO4 -xcg92
+> CFLAGS =        -Xa -G -xO4 -xcg92 -DMATLAB
+45,47d49  [using Chaco versions with MATLAB switch]
+<               ${MLCHACO}/chaco_check_graph.c \
+<               ${MLCHACO}/check_input.c \
+<                 ${MLCHACO}/smalloc.c \
+48a51,53
+> #             ${MLCHACO}/chaco_check_graph.c \
+> #             ${MLCHACO}/check_input.c \
+> #                ${MLCHACO}/smalloc.c \
+55a61
+>               ${CHACO}/input/check_input.c \
+61a68
+>               ${CHACO}/graph/check_graph.c \
+91a99  [compared CHFILES with Chaco Makefile CHFILES]
+>               ${CHACO}/klvspiff/flow.c \
+97a106  [compared CHFILES with Chaco Makefile CHFILES]
+>               ${CHACO}/klvspiff/flatten.c \
+100c109,110  [compared CHFILES with Chaco Makefile CHFILES]
+<               ${CHACO}/coarsen/makecgraph.c \
+---
+>               ${CHACO}/coarsen/makefgraph.c \
+>               ${CHACO}/coarsen/makeccoords.c \
+102d111  [compared CHFILES with Chaco Makefile CHFILES]
+<               ${CHACO}/coarsen/countcedges.c \
+108a118  [compared CHFILES with Chaco Makefile CHFILES]
+>               ${CHACO}/coarsen/maxmatch5.c \
+234a245
+>               ${CHACO}/util/smalloc.c \
+245a257,258
+> #             ${CHACO}/main/user_params.c \
+> #             ${CHACO}/util/bail.c \
+254a268,271
+> #mlchaco:     ${MLFILES.c} chaco.a Makefile
+> #             mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+> #             mv mlchaco.mex* ${DEST_DIR}
+> 
+256c273
+<               mex -V4 -output mlchaco ${MLFILES.c} chaco.a -I${CHACO}/main
+---
+>               mex -output mlchaco -largeArrayDims -DMATLAB ${MLFILES.c}
+>               chaco.a -I${CHACO}/main
+
+5/25/10:
+
+- reorganized chaco.m and mlchaco.c drivers into Chaco.c matlab-layer (independent of chaco) and Chacox.c x-layer (independent of matlab).
+
+5/26/10:
+
+- added mexchaco target to Makefile (and related changes).
+
+5/27/10
+
+- added define for exit(status) to ${CHACO}/main/defs.h so that local bail.c is
+  unnecessary.
+
+6/15/10:
+
+- separated chaco x-layer from meshpart build.
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cmake/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cmake/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cmake/install.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu 
+
+#Some cleanup
+rm -rf install cmake-2.8.11.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/cmake-2.8.11.2.tar.gz' 'cmake-2.8.11.2.tar.gz'
+
+#Untar 
+tar -zxvf  cmake-2.8.11.2.tar.gz
+
+#Move cmake into install directory
+mv cmake-2.8.11.2/* install
+rm -rf cmake-2.8.11.2
+
+#Compile cmake
+cd install 
+./bootstrap --prefix=$ISSM_DIR/externalpackages/cmake/install
+if [ $# -eq 0 ]; then
+	make
+else 
+	make -j $1; 
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/colpack/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/colpack/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/colpack/install.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src ColPack
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ColPack-1.0.3.tar.gz' 'ColPack-1.0.3.tar.gz'
+
+#install directory
+mkdir src
+tar -zxvf ColPack-1.0.3.tar.gz 
+mv ColPack/* src
+rm -rf ColPack
+
+#compile
+cd src
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+cd ..
+
+#install
+ln -s src/build ./install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install-dev.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install-dev.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install-dev.sh	(revision 18231)
@@ -0,0 +1,18 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src 
+
+#Download
+git clone git://github.com/danmar/cppcheck.git src
+
+#compile
+cd src
+if [ $# -eq 0 ]; then
+	make 
+else 
+	make -j $1
+fi  
+make install PREFIX=$ISSM_DIR/externalpackages/cppcheck/install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cppcheck/install.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src cppcheck-1.48
+mkdir src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/cppcheck-1.48.tar' 'cppcheck-1.48.tar'
+tar -xvf cppcheck-1.48.tar
+
+mv cppcheck-1.48/* src
+rm -rf cppcheck-1.48
+
+#compile
+cd src
+if [ $# -eq 0 ]; then
+	make 
+else 
+	make -j $1
+fi  
+make install PREFIX=$ISSM_DIR/externalpackages/cppcheck/install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-18.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-18.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-18.sh	(revision 18231)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#clean up
+rm -rf Cython-0.18
+
+#download numpy first
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Cython-0.18.tar.gz' 'cython.tar.gz'
+
+#install numpy
+tar -zxvf cython.tar.gz
+cd Cython-0.18
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-19.2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-19.2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install-19.2.sh	(revision 18231)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#clean up
+rm -rf Cython-0.19.2
+
+#download numpy first
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Cython-0.19.2.tar.gz' 'cython.tar.gz'
+
+#install numpy
+tar -zxvf cython.tar.gz
+cd Cython-0.19.2
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/cython/install.sh	(revision 18231)
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+
+#clean up
+rm -rf cython
+
+#download cython first
+git clone https://github.com/cython/cython.git
+
+#install cython
+cd cython
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dace/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dace/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dace/install.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install dace
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dace.zip' 'dace.zip'
+
+#uncompress
+unzip dace.zip
+
+#move to install directory
+mv dace/* install
+rm -rf dace
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/LHSDriver.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/LHSDriver.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/LHSDriver.cpp.patch	(revision 18231)
@@ -0,0 +1,8 @@
+766c766
+<   /*char output_string[32], message_string[32], title_string[32],
+---
+>   char output_string[32], message_string[32], title_string[32],
+802c802
+<   check_error(err_code, "lhs_files");*/
+---
+>   check_error(err_code, "lhs_files");
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NIDRProblemDescDB.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NIDRProblemDescDB.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NIDRProblemDescDB.C.patch	(revision 18231)
@@ -0,0 +1,4 @@
+95a96,98
+>   
+>   //close the input file
+>   fclose(nidrin);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDLocalReliability.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDLocalReliability.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDLocalReliability.C.patch	(revision 18231)
@@ -0,0 +1,7 @@
+2276a2277
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2280c2281,2282
+< 	    << impFactor[i][j] << '\n';
+---
+> 	    << impFactor[i][j] << "  Sensitivity = " << setw(write_precision+7)
+> 	    << fnGradsMeanX(i, j) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDSampling.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDSampling.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDSampling.C.patch	(revision 18231)
@@ -0,0 +1,15 @@
+656a657,658
+> 
+> 
+659a662,663
+>    
+> 	return; //don't compute for now, too expensive.
+705c709
+<   //calculate simple rank correlation coeff
+---
+>   //calculate simple correlation coeff
+710a715
+> 
+1071a1077,1078
+> 
+> 	return; //don't output for now.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDUnilevelRBDO.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDUnilevelRBDO.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/NonDUnilevelRBDO.C.patch	(revision 18231)
@@ -0,0 +1,10 @@
+1052,1053c1052,1057
+< 	  s << "  Importance Factor for variable " << setw(11)
+< 	    << uv_labels[j].data() << " = " << impFactor[i][j] << '\n';
+---
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+> 	  s << "  Importance Factor for variable " << setiosflags(ios::left)
+> 	    << setw(11) << uv_labels[j].data() << " = "
+> 	    << resetiosflags(ios::adjustfield) << setw(write_precision+7)
+> 	    << impFactor[i][j] << "  Sensitivity = " << setw(write_precision+7)
+> 	    << fnGradsMeanX(i, j) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.C.patch	(revision 18231)
@@ -0,0 +1,34 @@
+134a135
+>   initialized=0; //we run serially all the time!
+165a167,197
+> /** This constructor is provided for the Issm software, to run serial 
+>  * Dakota in a parallel MPI ring: */
+> ParallelLibrary::ParallelLibrary(char* serial_mode): worldRank(0), worldSize(1),
+>   mpirunFlag(false), ownMPIFlag(false), dryRunFlag(false), dummyFlag(false),
+>   stdOutputFlag(false), stdErrorFlag(false), startClock(0),
+>   stdOutputFilename(NULL), stdErrorFilename(NULL), readRestartFilename(NULL),
+>   writeRestartFilename(NULL), stopRestartEvals(0),
+>   currPLIter(parallelLevels.end()), currPCIter(parallelConfigurations.end())
+> {
+>   startClock   = clock();
+> #ifdef DAKOTA_UTILIB
+>   utilib::exception_mngr::set_mode(utilib::exception_mngr::Abort);
+>   startCPUTime = CPUSeconds();       // see utilib/src/sys/seconds.cpp
+>   startWCTime  = WallClockSeconds(); // see utilib/src/sys/seconds.cpp
+> #endif // DAKOTA_UTILIB
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #ifdef HAVE_MPI // mpi available, we still don't want to run in parallel for  Dakota!
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota in serial mode on CPU 0, inside an MPI ring.";
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota in serial mode.\n";
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.insert(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.H.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.H.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/4.2/ParallelLibrary.H.patch	(revision 18231)
@@ -0,0 +1,3 @@
+346a347,348
+>   /// library mode constructor, serial mode
+>   ParallelLibrary(char*  serial_mode);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NIDRProblemDescDB.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NIDRProblemDescDB.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NIDRProblemDescDB.C.patch	(revision 18231)
@@ -0,0 +1,5 @@
+109a110,113
+> 
+>   //close the input file
+>   fclose(nidrin);
+> 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDLocalReliability.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDLocalReliability.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDLocalReliability.C.patch	(revision 18231)
@@ -0,0 +1,9 @@
+2218a2219
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2223c2224,2227
+< 	    << std::setw(width) << impFactor(j,i) << '\n';
+---
+> 	    << std::setw(width) << impFactor(j,i)
+> 	    << "  Sensitivity = "
+> 	    << std::resetiosflags(std::ios::adjustfield)
+> 	    << std::setw(width) << fnGradsMeanX(j,i) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDSampling.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDSampling.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDSampling.C.patch	(revision 18231)
@@ -0,0 +1,14 @@
+438,439c438,440
+<   if (!subIteratorFlag)
+<     nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+---
+> //don't compute for now, too expensive.
+> //  if (!subIteratorFlag)
+> //    nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+894,895c895,897
+<     nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+<       iteratedModel.response_labels());
+---
+> //don't output for now.
+> //    nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+> //      iteratedModel.response_labels());
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDUnilevelRBDO.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDUnilevelRBDO.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/NonDUnilevelRBDO.C.patch	(revision 18231)
@@ -0,0 +1,7 @@
+1046a1047
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+1048c1049,1050
+< 	    << uv_labels[j].data() << " = " << impFactor[i][j] << '\n';
+---
+> 	    << uv_labels[j].data() << " = " << impFactor[i][j]
+> 	    << "  Sensitivity = " << fnGradsMeanX(i,j) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.C.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.C.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.C.patch	(revision 18231)
@@ -0,0 +1,36 @@
+178a179
+>   initialized=0; //we run serially all the time!
+214a216,248
+> /** This constructor is provided for the Issm software, to run serial
+>  * Dakota in a parallel MPI ring: */
+> ParallelLibrary::ParallelLibrary(char* serial_mode):
+>   worldRank(0), worldSize(1), 
+>   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
+>   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
+>   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false), 
+>   startClock(0), stopRestartEvals(0),
+>   currPLIter(parallelLevels.end()), currPCIter(parallelConfigurations.end())
+> {
+>   startClock   = clock();
+> #ifdef DAKOTA_UTILIB
+>   utilib::exception_mngr::set_mode(utilib::exception_mngr::Abort);
+>   startCPUTime = CPUSeconds();       // see utilib/src/sys/seconds.cpp
+>   startWCTime  = WallClockSeconds(); // see utilib/src/sys/seconds.cpp
+> #endif // DAKOTA_UTILIB
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #ifdef HAVE_MPI // mpi available, we still don't want to run in parallel for Dakota!
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.2 MPI executable in serial mode on CPU 0 for ISSM.";
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.2 serial executable in serial mode for ISSM.\n";
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.push_back(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
+> 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.H.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.H.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/ParallelLibrary.H.patch	(revision 18231)
@@ -0,0 +1,3 @@
+358a359,360
+>   /// library mode constructor, serial mode (for the Issm software)
+>   ParallelLibrary(char*  serial_mode);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch	(revision 18231)
@@ -0,0 +1,2 @@
+87a88
+> #include <stddef.h>
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/pecos_global_defs.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/pecos_global_defs.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.2/pecos_global_defs.hpp.patch	(revision 18231)
@@ -0,0 +1,4 @@
+24a25
+> #ifndef PI
+25a27
+> #endif
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch	(revision 18231)
@@ -0,0 +1,26 @@
+64,65c64,65
+< #set( DAKOTA_HAVE MPI ON
+< #     CACHE BOOL "Build with MPI enabled" FORCE)
+---
+> set( DAKOTA_HAVE MPI OFF
+>      CACHE BOOL "Build with MPI disabled" FORCE)
+73,77c73,77
+< #set(BOOST_ROOT
+< #    "path/to/custom/Boost/install/directory"
+< #    CACHE PATH "Use non-standard Boost install" FORCE)
+< #set( Boost_NO_SYSTEM_PATHS TRUE
+< #     CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+---
+> set(BOOST_ROOT
+>     "$ENV{ISSM_DIR}/externalpackages/boost/install"
+>     CACHE PATH "Use non-standard Boost install" FORCE)
+> set( Boost_NO_SYSTEM_PATHS TRUE
+>      CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+91,93c91,93
+< #set( CMAKE_INSTALL_PREFIX
+< #     "/path/to/Dakota/installation"
+< #     CACHE PATH "Path to Dakota installation" )
+---
+> set( CMAKE_INSTALL_PREFIX
+>      "$ENV{ISSM_DIR}/externalpackages/dakota/install"
+>      CACHE PATH "Path to Dakota installation" )
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch	(revision 18231)
@@ -0,0 +1,16 @@
+4,8c4,8
+< set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+< set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+< set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+<   "Enable DAKOTA specification maintenance mode?")
+< set(PECOS_ENABLE_TESTS TRUE CACHE BOOL "Enable Pecos-specific tests?")
+---
+> #set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+> #set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+> #set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+> #  "Enable DAKOTA specification maintenance mode?")
+> #set(PECOS_ENABLE_TESTS TRUE CACHE BOOL "Enable Pecos-specific tests?")
+14c14
+< #set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
+---
+> set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch	(revision 18231)
@@ -0,0 +1,9 @@
+2587a2588
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2592c2593,2596
+< 	    << std::setw(width) << impFactor(j,i) << '\n';
+---
+> 	    << std::setw(width) << impFactor(j,i)
+> 	    << "  Sensitivity = "
+> 	    << std::resetiosflags(std::ios::adjustfield)
+> 	    << std::setw(width) << fnGradsMeanX(j,i) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch	(revision 18231)
@@ -0,0 +1,25 @@
+703,709c703,710
+<   if (!subIteratorFlag) {
+<     nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+<     // archive the correlations to the results DB
+<     nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+< 				      cv_labels, div_labels, drv_labels,
+< 				      iteratedModel.response_labels());
+<   }
+---
+> //don't compute for now, too expensive.
+> //  if (!subIteratorFlag) {
+> //    nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+> //    // archive the correlations to the results DB
+> //    nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+> //				      cv_labels, div_labels, drv_labels,
+> //				      iteratedModel.response_labels());
+> //  }
+1196,1197c1197,1200
+<     nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+< 				    iteratedModel.response_labels());
+---
+> 
+> //don't output for now.
+> //    nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+> //				    iteratedModel.response_labels());
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 18231)
@@ -0,0 +1,35 @@
+107a108
+>   initialized=0; //we run serially all the time!
+133a135
+>   initialized=0; //we run serially all the time!
+141a144,171
+> /** This constructor is provided for the ISSM software, to run serial
+>  * Dakota in a parallel MPI ring: */
+> ParallelLibrary::ParallelLibrary(char* serial_mode):
+>   dakotaMPIComm(MPI_COMM_WORLD), worldRank(0), worldSize(1),
+>   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
+>   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
+>   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false),
+>   outputTimings(true), startClock(0), stopRestartEvals(0),
+>   currPLIter(parallelLevels.end()), currPCIter(parallelConfigurations.end())
+> {
+>   initialize_timers();
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #ifdef HAVE_MPI // mpi available, we still don't want to run in parallel for Dakota!
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3.1 MPI executable in serial mode on CPU 0 for ISSM." << std::endl;
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3.1 serial executable in serial mode for ISSM." << std::endl;
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.push_back(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
+> 
+1536a1567
+>   initialized=0; //we run serially all the time!
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch	(revision 18231)
@@ -0,0 +1,3 @@
+358a359,360
+>   /// library mode constructor, serial mode (for the ISSM software)
+>   ParallelLibrary(char* serial_mode);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch	(revision 18231)
@@ -0,0 +1,4 @@
+25a26
+> #ifndef PI
+26a28
+> #endif
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch	(revision 18231)
@@ -0,0 +1,40 @@
+41,46c41,46
+< #set( BLAS_LIBS 
+< #      "/usr/lib64"
+< #      CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+< #set( LAPACK_LIBS 
+< #      "/usr/lib64"
+< #      CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+---
+> set( BLAS_LIBS 
+>       "/usr/lib64/libblas.so.3.0.3"
+>       CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+> set( LAPACK_LIBS 
+>       "/usr/lib64/liblapack.so.3.0.3"
+>       CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+64,65c64,65
+< #set( DAKOTA_HAVE MPI ON
+< #     CACHE BOOL "Build with MPI enabled" FORCE)
+---
+> set( DAKOTA_HAVE MPI OFF
+>      CACHE BOOL "Build with MPI disabled" FORCE)
+73,77c73,77
+< #set(BOOST_ROOT
+< #    "path/to/custom/Boost/install/directory"
+< #    CACHE PATH "Use non-standard Boost install" FORCE)
+< #set( Boost_NO_SYSTEM_PATHS TRUE
+< #     CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+---
+> set(BOOST_ROOT
+>     "$ENV{ISSM_DIR}/externalpackages/boost/install"
+>     CACHE PATH "Use non-standard Boost install" FORCE)
+> set( Boost_NO_SYSTEM_PATHS TRUE
+>      CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+91,93c91,93
+< #set( CMAKE_INSTALL_PREFIX
+< #     "/path/to/Dakota/installation"
+< #     CACHE PATH "Path to Dakota installation" )
+---
+> set( CMAKE_INSTALL_PREFIX
+>      "$ENV{ISSM_DIR}/externalpackages/dakota/install"
+>      CACHE PATH "Path to Dakota installation" )
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch	(revision 18231)
@@ -0,0 +1,14 @@
+4,7c4,7
+< set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+< set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+< set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+<   "Enable DAKOTA specification maintenance mode?")
+---
+> #set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+> #set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+> #set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+> #  "Enable DAKOTA specification maintenance mode?")
+13c13
+< #set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
+---
+> set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch	(revision 18231)
@@ -0,0 +1,9 @@
+2579a2580
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2584c2585,2588
+< 	    << std::setw(width) << impFactor(j,i) << '\n';
+---
+> 	    << std::setw(width) << impFactor(j,i)
+> 	    << "  Sensitivity = "
+> 	    << std::resetiosflags(std::ios::adjustfield)
+> 	    << std::setw(width) << fnGradsMeanX(j,i) << '\n';
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch	(revision 18231)
@@ -0,0 +1,25 @@
+703,709c703,710
+<   if (!subIteratorFlag) {
+<     nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+<     // archive the correlations to the results DB
+<     nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+< 				      cv_labels, div_labels, drv_labels,
+< 				      iteratedModel.response_labels());
+<   }
+---
+> //don't compute for now, too expensive.
+> //  if (!subIteratorFlag) {
+> //    nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+> //    // archive the correlations to the results DB
+> //    nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+> //				      cv_labels, div_labels, drv_labels,
+> //				      iteratedModel.response_labels());
+> //  }
+1196,1197c1197,1200
+<     nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+< 				    iteratedModel.response_labels());
+---
+> 
+> //don't output for now.
+> //    nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+> //				    iteratedModel.response_labels());
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch	(revision 18231)
@@ -0,0 +1,40 @@
+103a104
+>   initialized=0; //we run serially all the time!
+129a131
+>   initialized=0; //we run serially all the time!
+137a140,172
+> /** This constructor is provided for the ISSM software, to run serial
+>  * Dakota in a parallel MPI ring: */
+> ParallelLibrary::ParallelLibrary(char* serial_mode):
+>   worldRank(0), worldSize(1),
+>   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
+>   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
+>   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false),
+>   startClock(0), stopRestartEvals(0),
+>   currPLIter(parallelLevels.end()), currPCIter(parallelConfigurations.end())
+> {
+>   startClock   = clock();
+> #ifdef DAKOTA_UTILIB
+>   utilib::exception_mngr::set_mode(utilib::exception_mngr::Abort);
+>   startCPUTime = CPUSeconds();       // see utilib/src/sys/seconds.cpp
+>   startWCTime  = WallClockSeconds(); // see utilib/src/sys/seconds.cpp
+> #endif // DAKOTA_UTILIB
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #ifdef HAVE_MPI // mpi available, we still don't want to run in parallel for Dakota!
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3 MPI executable in serial mode on CPU 0 for ISSM.";
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3 serial executable in serial mode for ISSM.\n";
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.push_back(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
+> 
+1517a1553
+>   initialized=0; //we run serially all the time!
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch	(revision 18231)
@@ -0,0 +1,3 @@
+358a359,360
+>   /// library mode constructor, serial mode (for the ISSM software)
+>   ParallelLibrary(char* serial_mode);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch	(revision 18231)
@@ -0,0 +1,4 @@
+25a26
+> #ifndef PI
+26a28
+> #endif
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt	(revision 18231)
@@ -0,0 +1,58 @@
+Index: CMakeLists.txt
+===================================================================
+--- CMakeLists.txt	(revision 1968)
++++ CMakeLists.txt	(working copy)
+@@ -30,6 +30,17 @@
+ if(UTILIB_YES_MEMDEBUG)
+   add_definitions(-DUTILIB_YES_MEMDEBUG=1)
+ endif()
++option(UTILIB_HAVE_EXPAT "Enable expat in utilib" OFF)
++if (UTILIB_HAVE_EXPAT)
++  find_package(EXPAT)
++  if (EXPAT_FOUND)
++    # Use the same definition as autotools build
++    add_definitions("-DUTILIB_HAVE_EXPAT_H")
++    # TODO: add include path (EXPAT_INCLUDE_DIRS) in relevant subdirs?
++  else()
++    message(WARNING "expat requested, but not found")
++  endif()
++endif()
+ 
+ #inspect the system so that we can generate utilib_config.h 
+ include(CheckFunctionExists)
+@@ -47,7 +58,6 @@
+ CHECK_INCLUDE_FILES("windows.h;dbghelp.h" UTILIB_HAVE_DBGHELP_H)
+ CHECK_INCLUDE_FILE(err.h UTILIB_HAVE_ERR_H)
+ CHECK_INCLUDE_FILE(execinfo.h UTILIB_HAVE_EXECINFO_H)
+-CHECK_INCLUDE_FILE(expat.h UTILIB_HAVE_EXPAT_H)
+ CHECK_INCLUDE_FILE(float.h UTILIB_HAVE_FLOAT_H)
+ CHECK_INCLUDE_FILE(limits.h UTILIB_HAVE_LIMITS_H)
+ CHECK_INCLUDE_FILE(strings.h UTILIB_HAVE_STRINGS_H)
+@@ -57,9 +67,7 @@
+ CHECK_INCLUDE_FILE(values.h UTILIB_HAVE_VALUES_H)
+ CHECK_INCLUDE_FILE(windows.h UTILIB_HAVE_WINDOWS_H)
+ 
+-find_library(EXPAT_LIB expat)
+ 
+-
+ # Use common HAVE_BOOST to indicate usage of Boost across packages
+ # Ultimately need to #define UTILIB_HAVE_BOOST if used 
+ set(HAVE_BOOST OFF CACHE BOOL "Should Utilib use BOOST?")
+
+
+Index: CMakeLists.txt
+===================================================================
+--- src/libs/CMakeLists.txt	2013/03/25 19:19:06	1970
++++ src/libs/CMakeLists.txt	2013/03/25 19:51:47	1971
+@@ -77,8 +77,9 @@
+   list(APPEND libs ${MPI_LIBRARY})
+ endif()
+ 
+-if(UTILIB_HAVE_EXPAT_H AND EXPAT_LIB)
+-  list(APPEND libs ${EXPAT_LIB})
++if(UTILIB_HAVE_EXPAT AND EXPAT_FOUND)
++  include_directories(${EXPAT_INCLUDE_DIRS})
++  list(APPEND libs ${EXPAT_LIBRARIES})
+ endif()
+ if(MSVC)
+   list(APPEND libs dbghelp)
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-altix64-cosmos.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-altix64-cosmos.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-altix64-cosmos.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \ 
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-blas=/opt/intel/mkl/9.1.023/lib/64/libmkl.so \
+	--with-lapack=/opt/intel/mkl/9.1.023/lib/64/libmkl_lapack.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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-discover.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread" \
+--with-lapack="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread"
+cd ..
+
+#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
+#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
+#flag to the compilation.
+cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
+mv temp ./src/methods/NCSUOpt/Makefile
+
+cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/pebbl/src/Makefile
+
+cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-nappspack/Makefile
+
+cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-cddlib/Makefile
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile
+
+cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-conveyor/Makefile
+
+cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-appspack/Makefile
+
+cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/colin/src/Makefile
+
+cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/coliny/src/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile
+
+cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/packages/ampl/Makefile
+
+#Compile and install dakota
+cd src
+if [ $# -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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-cloud.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-cloud.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-cloud.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-blas=/usr/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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-murdo.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-murdo.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-linux64-murdo.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-blas=/usr/lib64/libblas.so.3.1.1 \
+	--with-lapack=/usr/lib64/liblapack.so.3.1.1
+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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-macosx64.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+   --prefix="$ISSM_DIR/externalpackages/dakota/install" \
+   --without-graphics  \
+   --with-pic \
+   --disable-mpi \
+   --with-blas="-L$ISSM_DIR/externalpackages/petsc/install/lib -lfblas " \
+   --with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack "
+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 -D_NONSTD_SOURCE/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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades-petsc3.3.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades-petsc3.3.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades-petsc3.3.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-4.2-pleiades.sh	(revision 18231)
@@ -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 configs/4.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+cd ..
+
+#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/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-discover.sh	(revision 18231)
@@ -0,0 +1,52 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src
+rm -rf install
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-plugin \
+--with-blas="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread" \
+--with-lapack="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread"
+
+cd ..
+
+#Compile and install dakota
+cd src
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-linux64-larsen.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-linux64-larsen.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-linux64-larsen.sh	(revision 18231)
@@ -0,0 +1,49 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+patch src/packages/teuchos/src/Teuchos_ConfigDefs.hpp configs/5.2/Teuchos_ConfigDefs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-plugin \
+	--with-blas="$ISSM_DIR/externalpackages/petsc/install/lib/libfblas.a" \
+	--with-lapack="$ISSM_DIR/externalpackages/petsc/install/lib/libflapack.a"
+
+#Compile and install dakota
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-macosx64.sh	(revision 18231)
@@ -0,0 +1,51 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-plugin \
+	--with-blas="-L$ISSM_DIR/externalpackages/petsc/install/lib -lfblas " \
+	--with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack "
+cd ..
+
+#Compile and install dakota
+cd src 
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh	(revision 18231)
@@ -0,0 +1,59 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src
+rm -rf install
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-plugin \
+--with-blas="-L/nasa/intel/mkl/10.0.011/lib/em64t/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/em64t/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+
+#--with-blas=/nasa/intel/Compiler/2012.0.032/mkl/lib/intel64/libmkl_intel_lp64.a \
+#--with-lapack=/nasa/intel/Compiler/2012.0.032/mkl/lib/intel64/libmkl_intel_lp64.a 
+#--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+#--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+#--with-blas="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack" \
+#--with-lapack="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack"
+
+cd ..
+
+#Compile and install dakota
+cd src
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-linux64.sh	(revision 18231)
@@ -0,0 +1,50 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-5.3.1-public-src.tar.gz' 'dakota-5.3.1-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-5.3.1-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-5.3.1.src/* src
+rm -rf dakota-5.3.1.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+
+#Apply patches
+patch src/src/ParallelLibrary.cpp configs/5.3.1/ParallelLibrary.cpp.patch
+patch src/src/ParallelLibrary.hpp configs/5.3.1/ParallelLibrary.hpp.patch
+patch src/src/NonDSampling.cpp configs/5.3.1/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/5.3.1/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd $DAK_BUILD
+cmake -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+cd ..
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-macosx64_mavericks.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-macosx64_mavericks.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dakota/install-5.3.1-macosx64_mavericks.sh	(revision 18231)
@@ -0,0 +1,50 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-5.3.1-public-src.tar.gz' 'dakota-5.3.1-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-5.3.1-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-5.3.1.src/* src
+rm -rf dakota-5.3.1.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+
+#Apply patches
+patch src/src/ParallelLibrary.cpp configs/5.3.1/ParallelLibrary.cpp.patch
+patch src/src/ParallelLibrary.hpp configs/5.3.1/ParallelLibrary.hpp.patch
+patch src/src/NonDSampling.cpp configs/5.3.1/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/5.3.1/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd $DAK_BUILD
+cmake -D CMAKE_C_COMPILER=/usr/local/gfortran/bin/gcc -D CMAKE_CXX_COMPILER=/usr/local/gfortran/bin/g++ -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+cd ..
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/dem.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/dem.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/dem.m	(revision 18231)
@@ -0,0 +1,530 @@
+function [h,I]=dem(x,y,z,varargin)
+%DEM Shaded relief image plot
+%	DEM(X,Y,Z) plots the Digital Elevation Model defined by X and Y 
+%	coordinate vectors and elevation matrix Z, as a lighted image using
+%	specific "landcolor" and "seacolor" colormaps. DEM uses IMAGESC 
+%	function which is much faster than SURFL when dealing with large 
+%	high-resolution DEM.
+%
+%	DEM(X,Y,Z,OPT) specifies options with OPT = [A,C,SCUT,ZMIN,ZMAX,ZCUT],
+%	where sorted optional scalars are:
+%	  A = azimuth light (in degrees relative to North). Default is A = -45
+%	      for a natural northwestern illumination.
+%	  C = controls contrast, as the exponent of the gradient value. Default
+%	      is C = 1 for linear contrast; use C = 0 to remove lighting, 
+%	      C = 0.5 for moderate lighting, C = 2 or more for strong contrast.
+%	  SCUT = controls lighting scale saturation with a median-style filter
+%	      in % of elements. Default is SCUT = 0.2 (0.2% maximum gradient 
+%	      values is ignored). Use SCUT = 0 for full scale gradient.
+%	  ZMIN,ZMAX = fixes min and max elevation values for colormap. Use NaN
+%	      to keep real min and/or max data values.
+%	  ZCUT = median-style filter to cut extremes values (in % of elements).
+%	      Default is ZCUT = 0.5 to ignore the 0.5% of most min/max 
+%	      elevation values. Use ZCUT = 0 for full scale.
+%	Use OPT=[] to keep default values and define following arguments.
+%
+%	DEM(...,CMAP) uses CMAP colormap instead of default (landcolor, if 
+%	exists or jet). Note that defining CMAP disables the default SEACOLOR
+%	colormap attribution for Z<=0 elevations.
+%
+%	DEM(...,NOVALUE) defines the values that will be replaced by NaN. This 
+%	might be mandatory for DEM that use a value like -99999 or -32768 if 
+%	you don't want a flat image...
+%
+%	DEM(...,SEACOLOR) sets the colormap used for zero and negative values.
+%	Default is seacolor (if exists) or single color [0.7,0.9,1] (a light 
+%	cyan) to simulate sea color. Use [] to apply colormap CMAP on the full
+%	elevation scale.
+%
+%	DEM(...,'interp') interpolates linearly NaN values (fills the gaps).
+%
+%	DEM(...,'lake') detects automaticaly flat areas different from sea 
+%	level (non-zero elevations) and draws them as lake surfaces.
+%
+%	DEM(...,'dec') plots classic basemap-style axis, considering 
+%	coordinates as cartesian (decimal).
+%
+%	DEM(...,'dms') plots geographic basemap-style axis in deg/min/sec,
+%	considering coordinates X as longitude and Y as latitude. Axis aspect 
+%	ratio will be adjusted to approximatively preserve distances (this is  
+%	not a real projection!).
+%
+%	DEM(...,'scale') adds a legend to the right of graph, with elevation 
+%	scale (colormap) and a distance scale if 'dms' option is used.
+%
+%	[H,I]=DEM(...) returns graphic handle H and illuminated image as I, an
+%	MxNx3 matrix (if Z is MxN).
+%
+%	Informations:
+%	 - For optimization purpose, DEM will automatically decimate data to
+%	   limit to a total of 1500x1500 pixels images. To avoid it, use option
+%	   DEM(...,'nodecim') or DEM(...,'decim',N) where N is an integer, but 
+%	   be aware that large grids may require computer ressources and induce  
+%	   disk swap or memory errors.
+%	 - Colormaps are Mx3 RGB matrix so it is easy to modify saturation 
+%	   (CMAP.^N), set darker (CMAP/N), lighter ((N - 1 + CMAP)/N), inverse
+%	    it (flipud(CMAP)), etc...
+%	 - To get free worldwide topographic data (SRTM), see READHGT function.
+%
+%	Author: François Beauducel <beauducel@ipgp.fr>
+%	Created: 2007-05-17
+%	Updated: 2013-01-05
+
+%	Copyright (c) 2013, François Beauducel, covered by BSD License.
+%	All rights reserved.
+%
+%	Redistribution and use in source and binary forms, with or without 
+%	modification, are permitted provided that the following conditions are 
+%	met:
+%
+%	   * Redistributions of source code must retain the above copyright 
+%	     notice, this list of conditions and the following disclaimer.
+%	   * Redistributions in binary form must reproduce the above copyright 
+%	     notice, this list of conditions and the following disclaimer in 
+%	     the documentation and/or other materials provided with the distribution
+%	                           
+%	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+%	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+%	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+%	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+%	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+%	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+%	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+%	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+%	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+%	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+%	POSSIBILITY OF SUCH DAMAGE.
+
+if nargin < 3
+	error('Not enough input arguments.');
+end
+
+% default OPT arguments
+a = -45;
+c = 1;
+scut = 0.2;
+zmin = NaN;
+zmax = NaN;
+zcut = 0.5;
+grey = 0.2*[1,1,1];
+csea = [];
+fs = 10;	% tick label fontsize
+
+dec = 0;
+dms = 0;
+scale = 0;
+inter = 0;
+lake = 0;
+decimflag = 0;
+decim = 0;
+
+novalue_color = [0,0,0];
+
+if ~isnumeric(x) | ~isnumeric(y) | ~isnumeric(z)
+	error('X,Y and Z must be numeric.')
+end
+
+if all(size(x) ~= 1) | all(size(y) ~= 1)
+	error('X and Y must be vectors, not matrix.')
+end
+
+if length(x) ~= size(z,2) | length(y) ~= size(z,1)
+	error('If Z has a size of [M,N], X must have a length of N, and Y a length of M.')
+end
+
+if nargin > 3
+	dec = any(strcmp(varargin,'dec'));
+	dms = any(strcmp(varargin,'dms'));
+	if dms & any(abs(y) > 91)
+		error('With DMS option Y must be in valid latitudes interval (decimal degrees).')
+	end
+	scale = any(strcmp(varargin,'scale'));
+	inter = any(strcmp(varargin,'interp'));
+	lake = any(strcmp(varargin,'lake'));
+	if any(strcmp(varargin,'nodecim'))
+		decim = 1;
+		decimflag = 1;
+	end
+	kdecim = find(strcmp(varargin,'decim'));
+	if ~isempty(kdecim)
+		decimflag = 1;
+		if (kdecim + 1) <= nargin & isnumeric(varargin{kdecim+1})
+			decim = round(varargin{kdecim+1});
+			decimflag = 2;
+		end
+	end
+end
+nargs = decimflag + dec + dms + scale + lake + inter;
+
+if (nargin - nargs) > 3
+	opt = varargin{1};
+	if ~isnumeric(opt)
+		error('OPT = [A,C,S,ZMIN,ZMAX] argument must be numeric.');
+	end
+	if ~isempty(opt)
+		a = opt(1);
+	end
+	if length(opt) > 1
+		c = opt(2);
+		if c < 0
+			error('C argument must be positive.');
+		end
+	end
+	if length(opt) > 2
+		scut = opt(3);
+		if scut < 0 | scut >= 100
+			error('SCUT argument must be a positive percentage.');
+		end
+	end
+	if length(opt) > 4
+		zmin = opt(4);
+		zmax = opt(5);
+	end
+	if length(opt) > 5
+		zcut = opt(6);
+		if zcut < 0 | zcut >= 100
+			error('ZCUT argument must be a positive percentage.');
+		end
+	end
+end
+
+if (nargin - nargs) < 5
+	cmap = [];
+else
+	cmap = varargin{2};
+	if ~isnumeric(cmap) | (~isempty(cmap) & (size(cmap,2) ~= 3 | min(cmap(:)) < 0 | max(cmap(:)) > 1))
+		error('CMAP must be a valid colormap (3-column [R,G,B] matrix with 0.0 to 1.0 values).')
+	end
+end
+
+if (nargin - nargs) < 6
+	novalue = NaN;
+else
+	novalue = varargin{3};
+	if ~isnumeric(novalue) | numel(novalue) > 1
+		error('NOVALUE must be scalar.')
+	end
+end
+
+if (nargin - nargs) < 7
+	if isempty(cmap)
+		if exist('seacolor','file')
+			csea = seacolor(256);
+		else
+			csea = [.7,.9,1];
+		end
+	end
+else
+	csea = varargin{4};
+	if ~isnumeric(csea)
+		error('Unknown option')
+	elseif (~isempty(csea) & (size(csea,2) ~= 3 | min(csea) < 0 | max(csea) > 1))
+		error('SEACOLOR must be a valid [R,G,B] vector with 0.0 to 1.0 values).')
+	end
+end
+
+if isempty(cmap)
+	if exist('landcolor','file')
+		cmap = landcolor.^1.3;
+	else
+		cmap = jet(256);
+	end
+end
+
+
+
+% decimates data to avoid disk swap/out of memory...
+nmax = 1500;
+if decim
+	n = decim;
+else
+	n = ceil(sqrt(numel(z))/nmax);
+end
+if n > 1
+	x = x(1:n:end);
+	y = y(1:n:end);
+	z = z(1:n:end,1:n:end);
+	fprintf('DEM: on the plot data has been decimated by a factor of %d...\n',n);
+end
+
+z = double(z); % necessary for most of the following calculations...
+z(z==novalue) = NaN;
+
+if inter
+	z = fillgap(x,y,z);
+end
+
+if isempty(csea)
+	k = (z~=0 & ~isnan(z));
+else
+	k = ~isnan(z);
+end
+
+if isnan(zmin)
+	zmin = nmedian(z(k),zcut/100);
+end
+if isnan(zmax)
+	zmax = nmedian(z(k),1 - zcut/100);
+end
+dz = zmax - zmin;
+
+if dz > 0
+	% builds the colormap: concatenates seacolor and landcolor around 0
+	if ~isempty(csea) & zmin < 0 & zmax > 0
+		l = size(csea,1);
+		r = size(cmap,1)*abs(zmin)/zmax/l;
+		cmap = cat(1,interp1(1:l,csea,linspace(1,l,round(l*r)),'*linear'),cmap);
+	end
+	
+	% normalisation of Z using CMAP and convertion to RGB
+	I = ind2rgb(uint16((z - zmin)*(length(cmap)/dz)),cmap);
+	
+	if c > 0
+		% computes lighting from elevation gradient
+		[fx,fy] = gradient(z,x,y);
+		%fx = filter([1,0,0,0,-1],1,rf(z'))';
+		%fy = filter([1,0,0,0,-1],1,rf(z));
+		fxy = -fx*sind(a) - fy*cosd(a);
+		clear fx fy	% free some memory...
+		
+		% lake option: zero gradient
+		if lake
+			dx = diff(z,1,2);
+			dy = diff(z,1,1);
+			u1 = ones(size(z,1),1);
+			u2 = ones(1,size(z,2));
+			z(cat(1,u2,dy)==0 & cat(1,dy,u2)==0 & cat(2,dx,u1)==0 & cat(2,u1,dx)==0) = 0;
+			clear dx dy	% free some memory...
+		end
+
+		fxy(isnan(fxy)) = 0;
+
+		% computes maximum absolute gradient (median-style), normalizes, saturates and duplicates in 3-D matrix
+		r = repmat(max(min(fxy/nmedian(abs(fxy),1 - scut/100),1),-1),[1,1,3]);
+	
+		% applies contrast using exponent
+		rp = (1 - abs(r)).^c;
+		I = I.*rp;
+	
+		% lighter for positive gradient
+		k = find(r > 0);
+		I(k) = I(k) + (1 - rp(k));
+				
+	end
+	
+	% set novalues / NaN to black color
+	[i,j] = find(isnan(z));
+	if ~isempty(i)
+		I(sub2ind(size(I),repmat(i,1,3),repmat(j,1,3),repmat(1:3,size(i,1),1))) = repmat(novalue_color,size(i,1),1);
+	end
+	% set the seacolor for 0 values
+	if ~isempty(csea)
+		[i,j] = find(z==0);
+		if ~isempty(i)
+			I(sub2ind(size(I),repmat(i,1,3),repmat(j,1,3),repmat(1:3,size(i,1),1))) = repmat(csea(end,:),size(i,1),1);
+		end
+	end
+
+	hh = imagesc(x,y,I);
+else
+	hh = imagesc(x,y,z);
+	colormap(cmap);
+	text(mean(x),mean(y),'SPLASH!','Color','c','FontWeight','bold','HorizontalAlignment','center')
+end
+
+orient tall
+axis xy, axis equal, axis tight
+
+xlim = [min(x),max(x)];
+ylim = [min(y),max(y)];
+zlim = [min(z(:)),max(z(:))];
+
+% axis basemap style
+if dec | dms
+	axis off
+
+	if dms
+		% approximates X-Y aspect ratio for this latitude (< 20-m precision for 1x1° grid)
+		xyr = cos(mean(y)*pi/180);
+	else
+		xyr = 1;
+	end
+	set(gca,'DataAspectRatio',[1,xyr,1])
+	bwy = 0.008*diff(ylim); % Y border width = 1%
+	bwx = bwy/xyr; % border width (in degree of longitude)
+
+	% transparent borders
+	patch([xlim(1)-bwx,xlim(2)+bwx,xlim(2)+bwx,xlim(1)-bwx],ylim(1) - bwy*[0,0,1,1],'k','FaceColor','none','clipping','off')
+	patch([xlim(1)-bwx,xlim(2)+bwx,xlim(2)+bwx,xlim(1)-bwx],ylim(2) + bwy*[0,0,1,1],'k','FaceColor','none','clipping','off')
+	patch(xlim(1) - bwx*[0,0,1,1],[ylim(1)-bwy,ylim(2)+bwy,ylim(2)+bwy,ylim(1)-bwy],'k','FaceColor','none','clipping','off')
+	patch(xlim(2) + bwx*[0,0,1,1],[ylim(1)-bwy,ylim(2)+bwy,ylim(2)+bwy,ylim(1)-bwy],'k','FaceColor','none','clipping','off')
+
+	dlon = {'E','W'};
+	dlat = {'N','S'};
+
+	if dec
+		ddx = dtick(diff(xlim));
+		ddy = dtick(diff(ylim));
+	else
+		ddx = dtick(diff(xlim),1);
+		ddy = dtick(diff(ylim),1);
+	end
+
+	xtick = (ddx*ceil(xlim(1)/ddx)):ddx:xlim(2);
+	for xt = xtick(1:2:end)
+		dt = ddx - max(0,xt + ddx - xlim(2));
+		patch(repmat(xt + dt*[0,1,1,0]',[1,2]),[ylim(1) - bwy*[0,0,1,1];ylim(2) + bwy*[0,0,1,1]]','k','clipping','off')
+		text(xt,ylim(1) - bwy,deg2dms(xt,dlon,dec),'FontSize',fs,'HorizontalAlignment','center','VerticalAlignment','top');
+	end
+
+	ytick = (ddy*ceil(ylim(1)/ddy)):ddy:ylim(2);
+	for yt = ytick(1:2:end)
+		dt = ddy - max(0,yt + ddy - ylim(2));
+		patch([xlim(1) - bwx*[0,0,1,1];xlim(2) + bwx*[0,0,1,1]]',repmat(yt + dt*[0,1,1,0]',[1,2]),'k','clipping','off')
+		text(xlim(1) - 1.1*bwx,yt,deg2dms(yt,dlat,dec),'FontSize',fs,'HorizontalAlignment','right','VerticalAlignment','middle');
+	end
+end
+
+% scale legend
+if scale
+	%wsc = diff(xlim)*0.01;
+	wsc = bwx;
+	xsc = xlim(2) + wsc*4;
+
+	% elevation scale (colorbar)
+	zscale = linspace(zlim(1),zlim(2),length(cmap));
+	yscale = linspace(0,diff(ylim)/2,length(cmap));
+	ysc = ylim(1);
+	ddz = dtick(dz*max(0.5*xyr*diff(xlim)/yscale(end),1));
+	ztick = (ddz*ceil(zlim(1)/ddz)):ddz:zlim(2);
+	patch(xsc + repmat(wsc*[-1;1;1;-1],[1,length(cmap)]), ...
+		ysc + [repmat(yscale,[2,1]);repmat(yscale + diff(yscale(1:2)),[2,1])], ...
+		repmat(zscale,[4,1]), ...
+		'EdgeColor','flat','LineWidth',.1,'FaceColor','flat','clipping','off')
+	colormap(cmap)
+	caxis([zmin,zmax])
+	patch(xsc + wsc*[-1,1,1,-1],ysc + yscale(end)*[0,0,1,1],'k','FaceColor','none','Clipping','off')
+	text(xsc + 2*wsc + zeros(size(ztick)),ysc + (ztick - zlim(1))*0.5*diff(ylim)/diff(zlim),num2str(ztick'), ...
+		'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',8)
+	
+	% distance scale (in case of DMS only)
+	if dms
+		degkm = 6370*pi/180;
+		dkm = dtick(diff(ylim)*degkm);
+		ysc = ylim(2) - 0.5*dkm/degkm;
+		patch(xsc + wsc*[-1,-1,0,0],ysc + dkm*0.5*[-1,1,1,-1]/degkm,'k','FaceColor',grey,'clipping','off')
+		if dkm > 1
+			skm = sprintf('%g km',dkm);
+		else
+			skm = sprintf('%g m',dkm*1000);
+		end
+		text(xsc,ysc,skm,'rotation',-90,'HorizontalAlignment','center','VerticalAlignment','bottom', ...
+			'Color',grey,'FontWeight','bold')
+	end
+
+end
+
+
+if nargout > 0
+	h = hh;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function y = nmedian(x,n)
+%NMEDIAN Generalized median filter
+%	NMEDIAN(X,N) sorts elemets of X and returns N-th value (N normalized).
+%	So:
+%	   N = 0 is minimum value
+%	   N = 0.5 is median value
+%	   N = 1 is maximum value
+
+if nargin < 2
+	n = 0.5;
+end
+y = sort(x(:));
+y = interp1(sort(y),n*(length(y)-1) + 1);
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function dd = dtick(dlim,deg)
+%DTICK Tick intervals
+
+if nargin < 2
+	deg = 0;
+end
+
+if deg & dlim <= 2/60
+	% less than 2 minutes: base 36
+	m = 10^floor(log10(dlim*36))/36;
+elseif deg & dlim <= 2
+	% less than 2 degrees: base 6
+	m = 10^floor(log10(dlim*6))/6;
+else
+	% more than few degrees or not degrees: decimal rules
+	m = 10^floor(log10(dlim));
+end
+p = ceil(dlim/m);
+if p <= 1
+	dd = .1*m;
+elseif p == 2
+	dd = .2*m;
+elseif p <= 5
+	dd = .5*m;
+else
+	dd = m;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function s = deg2dms(x,ll,dec)
+%DEG2DMS Degree/minute/second display
+
+if dec
+	s = sprintf('%7.7g',x);
+else
+	xa = abs(x) + 1/360000;
+	sd = sprintf('%d%c',floor(xa),176);	% ASCII char 176 is the degree sign
+	sm = '';
+	ss = '';
+	if mod(x,1)
+		sm = sprintf('%02d''',floor(mod(60*xa,60)));
+		sa = floor(mod(3600*xa,60));
+		if sa
+			ss = sprintf('%02d"',sa);
+		else
+			if strcmp(sm,'00''')
+				sm = '';
+			end
+		end
+	end
+	s = [sd,sm,ss,ll{1+int8(x<0)}];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function z = fillgap(x,y,z)
+% GRIDDATA is not efficient for large arrays, but has great advantage to be
+% included in Matlab core functions! To optimize interpolation, we
+% reduce the number of relevant data by building a mask of surrounding
+% pixels of novalue areas... playing with linear index!
+
+sz = size(z);
+k = find(isnan(z));
+k(k == 1 | k == numel(z)) = []; % removes first and last index (if exist)
+if ~isempty(k)
+	[xx,yy] = meshgrid(x,y);
+	mask = zeros(sz,'int8');
+	k2 = ind90(sz,k); % k2 is linear index in the row order
+	% sets to 1 every previous and next index, both in column and row order
+	mask([k-1;k+1;ind90(fliplr(sz),[k2-1;k2+1])]) = 1; 
+	mask(k) = 0; % removes the novalue index
+	kb = find(mask); % keeps only border values
+	z(k) = griddata(xx(kb),yy(kb),z(kb),xx(k),yy(k));
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function k2 = ind90(sz,k)
+
+[i,j] = ind2sub(sz,k);
+k2 = sub2ind(fliplr(sz),j,i); % switched i and j: k2 is linear index in row order
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/landcolor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/landcolor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/landcolor.m	(revision 18231)
@@ -0,0 +1,78 @@
+function y = landcolor(n)
+%LANDCOLOR Land colormap
+%
+%	Author: Francois Beauducel <beauducel@ipgp.fr>
+%	$Revision: 1.0.0 $   $Date: 2012/05/17 11:22:44 $
+
+J = [ ...
+0.095678 0.53427 0.21682 
+0.15785 0.5979 0.23274 
+0.21286 0.64673 0.2514 
+0.26411 0.68789 0.27268 
+0.32959 0.72416 0.31308 
+0.39794 0.75695 0.36038 
+0.46153 0.7871 0.40624 
+0.52108 0.81516 0.45135 
+0.57702 0.84152 0.49547 
+0.62973 0.86645 0.53891 
+0.67946 0.89016 0.58187 
+0.72647 0.91282 0.62427 
+0.77095 0.93455 0.66619 
+0.81306 0.95546 0.70772 
+0.85292 0.97563 0.7489 
+0.89066 0.99514 0.78976 
+0.88379 0.98595 0.77038 
+0.86389 0.96758 0.73236 
+0.84615 0.94972 0.69623 
+0.8303 0.93233 0.66186 
+0.81612 0.91536 0.6291 
+0.80341 0.8988 0.59784 
+0.79201 0.8826 0.56795 
+0.78191 0.86676 0.53946 
+0.7729 0.85123 0.51224 
+0.76479 0.83602 0.48615 
+0.75747 0.8211 0.46111 
+0.75084 0.80645 0.43704 
+0.74506 0.79206 0.41414 
+0.73981 0.77792 0.39211 
+0.73501 0.76401 0.37089 
+0.73068 0.75033 0.35052 
+0.72683 0.73685 0.33106 
+0.72042 0.72074 0.31228 
+0.71032 0.70085 0.29417 
+0.69761 0.67821 0.27694 
+0.68489 0.65558 0.26026 
+0.67235 0.63313 0.24418 
+0.65997 0.61082 0.22889 
+0.64775 0.58874 0.21406 
+0.63568 0.56689 0.19983 
+0.62376 0.54527 0.18622 
+0.61197 0.52391 0.17299 
+0.60033 0.50283 0.16046 
+0.58881 0.48203 0.14832 
+0.57742 0.46151 0.13667 
+0.56616 0.44133 0.12555 
+0.55502 0.4214 0.11472 
+0.54398 0.4019 0.10456 
+0.53306 0.38266 0.094633 
+0.52226 0.36382 0.085242 
+0.51155 0.3453 0.076179 
+0.50095 0.32714 0.067515 
+0.49045 0.30938 0.059259 
+0.48005 0.29193 0.051294 
+0.46973 0.27495 0.043796 
+0.45951 0.25823 0.0365 
+0.44938 0.24206 0.029715 
+0.43934 0.22609 0.023063 
+0.42938 0.21074 0.016949 
+0.41951 0.19556 0.010917 
+0.40971 0.18105 0.0054326 
+0.4 0.16667 0 
+];
+
+l = length(J);
+if nargin < 1
+	n = 256;
+end
+y = interp1(1:l,J,linspace(1,l,n),'*linear');
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/license.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/license.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/license.txt	(revision 18231)
@@ -0,0 +1,24 @@
+Copyright (c) 2013, François Beauducel
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without 
+modification, are permitted provided that the following conditions are 
+met:
+
+    * Redistributions of source code must retain the above copyright 
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright 
+      notice, this list of conditions and the following disclaimer in 
+      the documentation and/or other materials provided with the distribution
+      
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+POSSIBILITY OF SUCH DAMAGE.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/seacolor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/seacolor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dem/seacolor.m	(revision 18231)
@@ -0,0 +1,58 @@
+function y = seacolor(n)
+%SEACOLOR Sea colormap adapted from NGDC ETOPO1
+%
+%	Author: Francois Beauducel <beauducel@ipgp.fr>
+
+J = [ ...
+    0.0392         0    0.4745
+    0.1020         0    0.5373
+    0.1020         0    0.5373
+    0.1490         0    0.5961
+    0.1490         0    0.5961
+    0.1059    0.0118    0.6510
+    0.1059    0.0118    0.6510
+    0.0627    0.0235    0.7059
+    0.0627    0.0235    0.7059
+    0.0196    0.0353    0.7569
+    0.0196    0.0353    0.7569
+         0    0.0549    0.7961
+         0    0.0549    0.7961
+         0    0.0863    0.8235
+         0    0.0863    0.8235
+         0    0.1176    0.8471
+         0    0.1176    0.8471
+         0    0.1529    0.8745
+         0    0.1529    0.8745
+    0.0471    0.2667    0.9059
+    0.0471    0.2667    0.9059
+    0.1020    0.4000    0.9412
+    0.1020    0.4000    0.9412
+    0.0745    0.4588    0.9569
+    0.0745    0.4588    0.9569
+    0.0549    0.5216    0.9765
+    0.0549    0.5216    0.9765
+    0.0824    0.6196    0.9882
+    0.0824    0.6196    0.9882
+    0.1176    0.6980    1.0000
+    0.1176    0.6980    1.0000
+    0.1686    0.7294    1.0000
+    0.1686    0.7294    1.0000
+    0.2157    0.7569    1.0000
+    0.2157    0.7569    1.0000
+    0.2549    0.7843    1.0000
+    0.2549    0.7843    1.0000
+    0.3098    0.8235    1.0000
+    0.3098    0.8235    1.0000
+    0.3686    0.8745    1.0000
+    0.3686    0.8745    1.0000
+    0.5412    0.8902    1.0000
+    0.5412    0.8902    1.0000
+    0.7373    0.9020    1.0000
+];
+
+l = length(J);
+if nargin < 1
+	n = 256;
+end
+y = interp1(1:l,J,linspace(1,l,n),'*linear');
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/distribute/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/distribute/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/distribute/install.sh	(revision 18231)
@@ -0,0 +1,6 @@
+#!/bin/bash
+set -eu
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://python-distribute.org/distribute_setup.py' 'distribute_setup.py'
+python distribute_setup.py
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/doxygen/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/doxygen/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/doxygen/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+mkdir install
+
+#Download latest version
+svn co https://svn.code.sf.net/p/doxygen/code/trunk src
+
+#Configure doxygen
+cd src && ./configure --prefix "$ISSM_DIR/externalpackages/doxygen/install"
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+
+#Install doxygen
+make install
+make install_docs
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/ldap.pl
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/ldap.pl	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/ldap.pl	(revision 18231)
@@ -0,0 +1,25 @@
+#!/usr/bin/perl
+#
+# LDAP.PL - Acquire JPL LDAP data and pare down to user IDs - 2011-08-01
+#
+$cat="/bin/cat"; $srt="/bin/sort"; $ldb="/usr/bin/ldapsearch";                 # Binary locations (change as needed)
+$lds="ldap.jpl.nasa.gov"; $ou="ou=personnel,dc=dir,dc=jpl,dc=nasa,dc=gov"; # Define LDAP server & organization
+$bn="jplbadgenumber"; $txt="$bn".".txt"; $db="jplusers.db";                # Initialize values
+#
+system(`$ldb -x -h $lds -b $ou uid=* uid > $txt`);                         # Execute LDAPsearch, write to file
+#
+open(I,"<$txt");                                                           # Open input file handle
+  open(O,">badges.tmp");                                                   # Open output file handle
+    while (<I>) { chomp($_);                                               # Spool through input file
+      if ($_ =~ "^uid: ") {                                                # If line begins with UID value,
+        $_=~s/uid: //; $_=~s/,(.*)$//; $_=~s/\n//;                         #   strip line of extraneous data
+        if (!($_=~/^\d\d\d\d\d\d/)) { print O "$_\n"; }                    # If UID is non-numeric, print output
+      }                                                                    # Close condition
+    }                                                                      # Close spool
+  close(O);                                                                # Close output file handle
+close(I);                                                                  # Close input file handle
+#
+system(`$cat badges.tmp |$srt -u > $db 2>/dev/null`);                      # Sort output
+unlink("badges.tmp"); unlink("$txt");                                      # Unlink temp files
+#
+# EOF - 2011-08-01 - Jay Dyson <jdyson@jpl.nasa.gov>
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/readme.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/readme.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/readme.txt	(revision 18231)
@@ -0,0 +1,38 @@
+-- ARCHIVE MANIFEST ------------------------------------------ 2011-08-19 --
+
+  Filename        Description
+  --------------  ----------------------------------------------------------
+  readme.txt      This file: describes script functions.
+  ldap.pl         PERL script for acquiring JPL user IDs via cron job.
+  source_seek.sh  Code-scanning script.  Surveys scripts for hard-coded IP
+                  addresses, password callouts, and user IDs.
+
+-- SCRIPT INFORMATION ------------------------------------------------------
+
+  LDAP.PL (requires PERL, UNIX ldapsearch, and related utilities)
+  --------------------------------------------------------------------------
+  The LDAP.PL script is intended solely for twice-daily invocation via cron.
+  This script should be run once at noon, once at midnight.  This script 
+  generates the jplusers.db file on which the SOURCE_SEEK.SH shell script 
+  relies for its scanning of source files.
+
+  SOURCE_SEEK.SH (requires UNIX shell and related utilities)
+  --------------------------------------------------------------------------
+  The SOURCE_SEEK.SH shell script is intended for regular cron invocation,
+  but may be run at system administrator discretion.  This script uses UNIX
+  'find' and 'grep' utilities to scan code files for hard-coded JPL Internet
+  Protocol (IP) addresses, password callouts, and JPL user IDs.  This script
+  accepts the path where source code files reside as a command line
+  argument (e.g., ./source_seek.sh /path/to/sourcecode/files).
+
+-- AUTHOR CONTACT INFO -----------------------------------------------------
+
+  Please direct questions regarding these files to the developer.
+ 
+  Name   : Jay Dyson, CISSP
+  Role   : IT Security Engineer
+  Group  : JPL IT Security
+  E-mail : jdyson@jpl.nasa.gov
+  Phone  : 818-397-4960
+
+------------------------------------------------ LAST UPDATED: 2011-08-19 --
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/source_seek.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/source_seek.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/dyson/source_seek.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/sh
+#
+# SOURCE_SEEK.SH - Look for IP addresses and mention of 'password' in source files - 2009-10-05
+#
+if [ -n "${1}" ]; then
+  clear
+  echo "Checking for IP addresses"
+  echo "--------------------------------------------"
+  find $1 -name "*" -exec grep -il "128\.149\." {} \;
+  find $1 -name "*" -exec grep -il "137\.78\."  {} \;
+  find $1 -name "*" -exec grep -il "137\.79\."  {} \;
+  find $1 -name "*" -exec grep -il "137\.228\." {} \;
+  echo "--------------------------------------------"
+  echo "\nChecking for 'password'"
+  echo "--------------------------------------------"
+  find $1 -name "*" -exec grep -il "password"   {} \;
+  echo "--------------------------------------------"
+  echo "\nChecking for JPL user IDs"
+  echo "--------------------------------------------"
+  find $1 -name "*" -exec grep -ilf jplusers.db {} \;
+  echo "--------------------------------------------"
+else
+  echo -e "\nUSE: $0 <directory_of_source_files>\n";
+fi
+#
+# EOF - 2011-08-05 - Jay Dyson <jdyson@jpl.nasa.gov>
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ec2ami/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ec2ami/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ec2ami/install.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/ec2api/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ec2api/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ec2api/install.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/esmf/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/esmf/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/esmf/install.sh	(revision 18231)
@@ -0,0 +1,38 @@
+#!/bin/bash
+set -eu
+
+export ESMF_DIR=$ISSM_DIR/externalpackages/esmf/esmf
+export ESMF_COMPILER=gfortran
+export ESMF_COMM=mpich2
+
+#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
+
+cd esmf
+if [ $# -eq 0 ]; then
+	make all_tests
+else
+	make -j $1 all_tests
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/copyfig.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/copyfig.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/copyfig.m	(revision 18231)
@@ -0,0 +1,33 @@
+%COPYFIG Create a copy of a figure, without changing the figure
+%
+% Examples:
+%   fh_new = copyfig(fh_old)
+%
+% This function will create a copy of a figure, but not change the figure,
+% as copyobj sometimes does, e.g. by changing legends.
+%
+% IN:
+%    fh_old - The handle of the figure to be copied. Default: gcf.
+%
+% OUT:
+%    fh_new - The handle of the created figure.
+
+% Copyright (C) Oliver Woodford 2012
+
+function fh = copyfig(fh)
+% Set the default
+if nargin == 0
+    fh = gcf;
+end
+% Is there a legend?
+if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend'))
+    % Safe to copy using copyobj
+    fh = copyobj(fh, 0);
+else
+    % copyobj will change the figure, so save and then load it instead
+    tmp_nam = [tempname '.fig'];
+    hgsave(fh, tmp_nam);
+    fh = hgload(tmp_nam);
+    delete(tmp_nam);
+end
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/eps2pdf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/eps2pdf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/eps2pdf.m	(revision 18231)
@@ -0,0 +1,134 @@
+%EPS2PDF  Convert an eps file to pdf format using ghostscript
+%
+% Examples:
+%   eps2pdf source dest
+%   eps2pdf(source, dest, crop)
+%   eps2pdf(source, dest, crop, append)
+%   eps2pdf(source, dest, crop, append, gray)
+%   eps2pdf(source, dest, crop, append, gray, quality)
+%
+% This function converts an eps file to pdf format. The output can be
+% optionally cropped and also converted to grayscale. If the output pdf
+% file already exists then the eps file can optionally be appended as a new
+% page on the end of the eps file. The level of bitmap compression can also
+% optionally be set.
+%
+% This function requires that you have ghostscript installed on your
+% system. Ghostscript can be downloaded from: http://www.ghostscript.com
+%
+%IN:
+%   source - filename of the source eps file to convert. The filename is
+%            assumed to already have the extension ".eps".
+%   dest - filename of the destination pdf file. The filename is assumed to
+%          already have the extension ".pdf".
+%   crop - boolean indicating whether to crop the borders off the pdf.
+%          Default: true.
+%   append - boolean indicating whether the eps should be appended to the
+%            end of the pdf as a new page (if the pdf exists already).
+%            Default: false.
+%   gray - boolean indicating whether the output pdf should be grayscale or
+%          not. Default: false.
+%   quality - scalar indicating the level of image bitmap quality to
+%             output. A larger value gives a higher quality. quality > 100
+%             gives lossless output. Default: ghostscript prepress default.
+
+% Copyright (C) Oliver Woodford 2009-2011
+
+% Suggestion of appending pdf files provided by Matt C at:
+% http://www.mathworks.com/matlabcentral/fileexchange/23629
+
+% Thank you to Fabio Viola for pointing out compression artifacts, leading
+% to the quality setting.
+% Thank you to Scott for pointing out the subsampling of very small images,
+% which was fixed for lossless compression settings.
+
+% 9/12/2011 Pass font path to ghostscript.
+
+function eps2pdf(source, dest, crop, append, gray, quality)
+% Intialise the options string for ghostscript
+options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
+% Set crop option
+if nargin < 3 || crop
+    options = [options ' -dEPSCrop'];
+end
+% Set the font path
+fp = font_path();
+if ~isempty(fp)
+    options = [options ' -sFONTPATH="' fp '"'];
+end
+% Set the grayscale option
+if nargin > 4 && gray
+    options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
+end
+% Set the bitmap quality
+if nargin > 5 && ~isempty(quality)
+    options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
+    if quality > 100
+        options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
+    else
+        options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
+        v = 1 + (quality < 80);
+        quality = 1 - quality / 100;
+        s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
+        options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
+    end
+end
+% Check if the output file exists
+if nargin > 3 && append && exist(dest, 'file') == 2
+    % File exists - append current figure to the end
+    tmp_nam = tempname;
+    % Copy the file
+    copyfile(dest, tmp_nam);
+    % Add the output file names
+    options = [options ' -f "' tmp_nam '" "' source '"'];
+    try
+        % Convert to pdf using ghostscript
+        [status message] = ghostscript(options);
+    catch
+        % Delete the intermediate file
+        delete(tmp_nam);
+        rethrow(lasterror);
+    end
+    % Delete the intermediate file
+    delete(tmp_nam);
+else
+    % File doesn't exist or should be over-written
+    % Add the output file names
+    options = [options ' -f "' source '"'];
+    % Convert to pdf using ghostscript
+    [status message] = ghostscript(options);
+end
+% Check for error
+if status
+    % Report error
+    if isempty(message)
+        error('Unable to generate pdf. Check destination directory is writable.');
+    else
+        error(message);
+    end
+end
+return
+
+% Function to return (and create, where necessary) the font path
+function fp = font_path()
+fp = user_string('gs_font_path');
+if ~isempty(fp)
+    return
+end
+% Create the path
+% Start with the default path
+fp = getenv('GS_FONTPATH');
+% Add on the typical directories for a given OS
+if ispc
+    if ~isempty(fp)
+        fp = [fp ';'];
+    end
+    fp = [fp getenv('WINDIR') filesep 'Fonts'];
+else
+    if ~isempty(fp)
+        fp = [fp ':'];
+    end
+    fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
+end
+user_string('gs_font_path', fp);
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/export_fig.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/export_fig.m	(revision 18231)
@@ -0,0 +1,810 @@
+%EXPORT_FIG  Exports figures suitable for publication
+%
+% Examples:
+%   im = export_fig
+%   [im alpha] = export_fig
+%   export_fig filename
+%   export_fig filename -format1 -format2
+%   export_fig ... -nocrop
+%   export_fig ... -transparent
+%   export_fig ... -native
+%   export_fig ... -m<val>
+%   export_fig ... -r<val>
+%   export_fig ... -a<val>
+%   export_fig ... -q<val>
+%   export_fig ... -<renderer>
+%   export_fig ... -<colorspace>
+%   export_fig ... -append
+%   export_fig ... -bookmark
+%   export_fig(..., handle)
+%
+% This function saves a figure or single axes to one or more vector and/or
+% bitmap file formats, and/or outputs a rasterized version to the
+% workspace, with the following properties:
+%   - Figure/axes reproduced as it appears on screen
+%   - Cropped borders (optional)
+%   - Embedded fonts (vector formats)
+%   - Improved line and grid line styles
+%   - Anti-aliased graphics (bitmap formats)
+%   - Render images at native resolution (optional for bitmap formats)
+%   - Transparent background supported (pdf, eps, png)
+%   - Semi-transparent patch objects supported (png only)
+%   - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
+%   - Variable image compression, including lossless (pdf, eps, jpg)
+%   - Optionally append to file (pdf, tiff)
+%   - Vector formats: pdf, eps
+%   - Bitmap formats: png, tiff, jpg, bmp, export to workspace 
+%   
+% This function is especially suited to exporting figures for use in
+% publications and presentations, because of the high quality and
+% portability of media produced.
+%
+% Note that the background color and figure dimensions are reproduced
+% (the latter approximately, and ignoring cropping & magnification) in the
+% output file. For transparent background (and semi-transparent patch
+% objects), use the -transparent option or set the figure 'Color' property
+% to 'none'. To make axes transparent set the axes 'Color' property to
+% 'none'. Pdf, eps and png are the only file formats to support a
+% transparent background, whilst the png format alone supports transparency
+% of patch objects.
+%
+% The choice of renderer (opengl, zbuffer or painters) has a large impact
+% on the quality of output. Whilst the default value (opengl for bitmaps,
+% painters for vector formats) generally gives good results, if you aren't
+% satisfied then try another renderer.  Notes: 1) For vector formats (eps,
+% pdf), only painters generates vector graphics. 2) For bitmaps, only
+% opengl can render transparent patch objects correctly. 3) For bitmaps,
+% only painters will correctly scale line dash and dot lengths when
+% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
+% using painters.
+%
+% When exporting to vector format (pdf & eps) and bitmap format using the
+% painters renderer, this function requires that ghostscript is installed
+% on your system. You can download this from:
+%   http://www.ghostscript.com
+% When exporting to eps it additionally requires pdftops, from the Xpdf
+% suite of functions. You can download this from:
+%   http://www.foolabs.com/xpdf
+%
+%IN:
+%   filename - string containing the name (optionally including full or
+%              relative path) of the file the figure is to be saved as. If
+%              a path is not specified, the figure is saved in the current
+%              directory. If no name and no output arguments are specified,
+%              the default name, 'export_fig_out', is used. If neither a
+%              file extension nor a format are specified, a ".png" is added
+%              and the figure saved in that format.
+%   -format1, -format2, etc. - strings containing the extensions of the
+%                              file formats the figure is to be saved as.
+%                              Valid options are: '-pdf', '-eps', '-png',
+%                              '-tif', '-jpg' and '-bmp'. All combinations
+%                              of formats are valid.
+%   -nocrop - option indicating that the borders of the output are not to
+%             be cropped.
+%   -transparent - option indicating that the figure background is to be
+%                  made transparent (png, pdf and eps output only).
+%   -m<val> - option where val indicates the factor to magnify the
+%             on-screen figure dimensions by when generating bitmap
+%             outputs. Default: '-m1'.
+%   -r<val> - option val indicates the resolution (in pixels per inch) to
+%             export bitmap outputs at, keeping the dimensions of the
+%             on-screen figure. Default: sprintf('-r%g', get(0,
+%             'ScreenPixelsPerInch')). Note that the -m and -r options
+%             change the same property.
+%   -native - option indicating that the output resolution (when outputting
+%             a bitmap format) should be such that the vertical resolution
+%             of the first suitable image found in the figure is at the
+%             native resolution of that image. To specify a particular
+%             image to use, give it the tag 'export_fig_native'. Notes:
+%             This overrides any value set with the -m and -r options. It
+%             also assumes that the image is displayed front-to-parallel
+%             with the screen. The output resolution is approximate and
+%             should not be relied upon. Anti-aliasing can have adverse
+%             effects on image quality (disable with the -a1 option).
+%   -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
+%                        use for bitmap outputs. '-a1' means no anti-
+%                        aliasing; '-a4' is the maximum amount (default).
+%   -<renderer> - option to force a particular renderer (painters, opengl
+%                 or zbuffer) to be used over the default: opengl for
+%                 bitmaps; painters for vector formats.
+%   -<colorspace> - option indicating which colorspace color figures should
+%                   be saved in: RGB (default), CMYK or gray. CMYK is only
+%                   supported in pdf, eps and tiff output.
+%   -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
+%             files only).  Larger val, in the range 0-100, gives higher
+%             quality/lower compression. val > 100 gives lossless
+%             compression. Default: '-q95' for jpg, ghostscript prepress
+%             default for pdf & eps. Note: lossless compression can
+%             sometimes give a smaller file size than the default lossy
+%             compression, depending on the type of images.
+%   -append - option indicating that if the file (pdfs only) already
+%             exists, the figure is to be appended as a new page, instead
+%             of being overwritten (default).
+%   -bookmark - option to indicate that a bookmark with the name of the
+%               figure is to be created in the output file (pdf only).
+%   handle - The handle of the figure, axes or uipanels (can be an array of
+%            handles, but the objects must be in the same figure) to be
+%            saved. Default: gcf.
+%
+%OUT:
+%   im - MxNxC uint8 image array of the figure.
+%   alpha - MxN single array of alphamatte values in range [0,1], for the
+%           case when the background is transparent.
+%
+%   Some helpful examples and tips can be found at:
+%      http://sites.google.com/site/oliverwoodford/software/export_fig
+%
+%   See also PRINT, SAVEAS.
+
+% Copyright (C) Oliver Woodford 2008-2012
+
+% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
+% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
+% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
+% The idea of editing the EPS file to change line styles comes from Jiro
+% Doke's FIXPSLINESTYLE (fex id: 17928).
+% The idea of changing dash length with line width came from comments on
+% fex id: 5743, but the implementation is mine :)
+% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
+% 20979).
+% The idea of appending figures in pdfs came from Matt C in comments on the
+% FEX (id: 23629)
+
+% Thanks to Roland Martin for pointing out the colour MATLAB
+% bug/feature with colorbar axes and transparent backgrounds.
+% Thanks also to Andrew Matthews for describing a bug to do with the figure
+% size changing in -nodisplay mode. I couldn't reproduce it, but included a
+% fix anyway.
+% Thanks to Tammy Threadgill for reporting a bug where an axes is not
+% isolated from gui objects.
+
+% 23/02/12: Ensure that axes limits don't change during printing
+% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
+%           reporting it).
+% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
+%           bookmarking of figures in pdf files.
+% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
+%           tick marks fixed.
+% 12/12/12: Add support for isolating uipanels. Thanks to michael for
+%           suggesting it.
+
+function [im, alpha] = export_fig(varargin)
+% Make sure the figure is rendered correctly _now_ so that properties like
+% axes limits are up-to-date.
+drawnow;
+% Parse the input arguments
+[fig, options] = parse_args(nargout, varargin{:});
+% Isolate the subplot, if it is one
+cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
+if cls
+    % Given handles of one or more axes, so isolate them from the rest
+    fig = isolate_axes(fig);
+else
+    % Check we have a figure
+    if ~isequal(get(fig, 'Type'), 'figure');
+        error('Handle must be that of a figure, axes or uipanel');
+    end
+    % Get the old InvertHardcopy mode
+    old_mode = get(fig, 'InvertHardcopy');
+end
+% Hack the font units where necessary (due to a font rendering bug in
+% print?). This may not work perfectly in all cases. Also it can change the
+% figure layout if reverted, so use a copy.
+magnify = options.magnify * options.aa_factor;
+if isbitmap(options) && magnify ~= 1
+    fontu = findobj(fig, 'FontUnits', 'normalized');
+    if ~isempty(fontu)
+        % Some normalized font units found
+        if ~cls
+            fig = copyfig(fig);
+            set(fig, 'Visible', 'off');
+            fontu = findobj(fig, 'FontUnits', 'normalized');
+            cls = true;
+        end
+        set(fontu, 'FontUnits', 'points');
+    end
+end
+% MATLAB "feature": axes limits and tick marks can change when printing
+Hlims = findall(fig, 'Type', 'axes');
+if ~cls
+    % Record the old axes limit and tick modes
+    Xlims = make_cell(get(Hlims, 'XLimMode'));
+    Ylims = make_cell(get(Hlims, 'YLimMode'));
+    Zlims = make_cell(get(Hlims, 'ZLimMode'));
+    Xtick = make_cell(get(Hlims, 'XTickMode'));
+    Ytick = make_cell(get(Hlims, 'YTickMode'));
+    Ztick = make_cell(get(Hlims, 'ZTickMode'));
+end
+% Set all axes limit and tick modes to manual, so the limits and ticks can't change
+set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
+% Set to print exactly what is there
+set(fig, 'InvertHardcopy', 'off');
+% Set the renderer
+switch options.renderer
+    case 1
+        renderer = '-opengl';
+    case 2
+        renderer = '-zbuffer';
+    case 3
+        renderer = '-painters';
+    otherwise
+        renderer = '-opengl'; % Default for bitmaps
+end
+% Do the bitmap formats first
+if isbitmap(options)
+    % Get the background colour
+    if options.transparent && (options.png || options.alpha)
+        % Get out an alpha channel
+        % MATLAB "feature": black colorbar axes can change to white and vice versa!
+        hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar');
+        if isempty(hCB)
+            yCol = [];
+            xCol = [];
+        else
+            yCol = get(hCB, 'YColor');
+            xCol = get(hCB, 'XColor');
+            if iscell(yCol)
+                yCol = cell2mat(yCol);
+                xCol = cell2mat(xCol);
+            end
+            yCol = sum(yCol, 2);
+            xCol = sum(xCol, 2);
+        end
+        % MATLAB "feature": apparently figure size can change when changing
+        % colour in -nodisplay mode
+        pos = get(fig, 'Position');
+        % Set the background colour to black, and set size in case it was
+        % changed internally
+        tcol = get(fig, 'Color');
+        set(fig, 'Color', 'k', 'Position', pos);
+        % Correct the colorbar axes colours
+        set(hCB(yCol==0), 'YColor', [0 0 0]);
+        set(hCB(xCol==0), 'XColor', [0 0 0]);
+        % Print large version to array
+        B = print2array(fig, magnify, renderer);
+        % Downscale the image
+        B = downsize(single(B), options.aa_factor);
+        % Set background to white (and set size)
+        set(fig, 'Color', 'w', 'Position', pos);
+        % Correct the colorbar axes colours
+        set(hCB(yCol==3), 'YColor', [1 1 1]);
+        set(hCB(xCol==3), 'XColor', [1 1 1]);
+        % Print large version to array
+        A = print2array(fig, magnify, renderer);
+        % Downscale the image
+        A = downsize(single(A), options.aa_factor);
+        % Set the background colour (and size) back to normal
+        set(fig, 'Color', tcol, 'Position', pos);
+        % Compute the alpha map
+        alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
+        A = alpha;
+        A(A==0) = 1;
+        A = B ./ A(:,:,[1 1 1]);
+        clear B
+        % Convert to greyscale
+        if options.colourspace == 2
+            A = rgb2grey(A);
+        end
+        A = uint8(A);
+        % Crop the background
+        if options.crop
+            [alpha, v] = crop_background(alpha, 0);
+            A = A(v(1):v(2),v(3):v(4),:);
+        end
+        if options.png
+            % Compute the resolution
+            res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
+            % Save the png
+            imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
+            % Clear the png bit
+            options.png = false;
+        end
+        % Return only one channel for greyscale
+        if isbitmap(options)
+            A = check_greyscale(A);
+        end
+        if options.alpha
+            % Store the image
+            im = A;
+            % Clear the alpha bit
+            options.alpha = false;
+        end
+        % Get the non-alpha image
+        if isbitmap(options)
+            alph = alpha(:,:,ones(1, size(A, 3)));
+            A = uint8(single(A) .* alph + 255 * (1 - alph));
+            clear alph
+        end
+        if options.im
+            % Store the new image
+            im = A;
+        end
+    else
+        % Print large version to array
+        if options.transparent
+            % MATLAB "feature": apparently figure size can change when changing
+            % colour in -nodisplay mode
+            pos = get(fig, 'Position');
+            tcol = get(fig, 'Color');
+            set(fig, 'Color', 'w', 'Position', pos);
+            A = print2array(fig, magnify, renderer);
+            set(fig, 'Color', tcol, 'Position', pos);
+            tcol = 255;
+        else
+            [A, tcol] = print2array(fig, magnify, renderer);
+        end
+        % Crop the background
+        if options.crop
+            A = crop_background(A, tcol);
+        end
+        % Downscale the image
+        A = downsize(A, options.aa_factor);
+        if options.colourspace == 2
+            % Convert to greyscale
+            A = rgb2grey(A);
+        else
+            % Return only one channel for greyscale
+            A = check_greyscale(A);
+        end
+        % Outputs
+        if options.im
+            im = A;
+        end
+        if options.alpha
+            im = A;
+            alpha = zeros(size(A, 1), size(A, 2), 'single');
+        end
+    end
+    % Save the images
+    if options.png
+        res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
+        imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
+    end
+    if options.bmp
+        imwrite(A, [options.name '.bmp']);
+    end
+    % Save jpeg with given quality
+    if options.jpg
+        quality = options.quality;
+        if isempty(quality)
+            quality = 95;
+        end
+        if quality > 100
+            imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
+        else
+            imwrite(A, [options.name '.jpg'], 'Quality', quality);
+        end
+    end
+    % Save tif images in cmyk if wanted (and possible)
+    if options.tif
+        if options.colourspace == 1 && size(A, 3) == 3
+            A = double(255 - A);
+            K = min(A, [], 3);
+            K_ = 255 ./ max(255 - K, 1);
+            C = (A(:,:,1) - K) .* K_;
+            M = (A(:,:,2) - K) .* K_;
+            Y = (A(:,:,3) - K) .* K_;
+            A = uint8(cat(3, C, M, Y, K));
+            clear C M Y K K_
+        end
+        append_mode = {'overwrite', 'append'};
+        imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
+    end
+end
+% Now do the vector formats
+if isvector(options)
+    % Set the default renderer to painters
+    if ~options.renderer
+        renderer = '-painters';
+    end
+    % Generate some filenames
+    tmp_nam = [tempname '.eps'];
+    if options.pdf
+        pdf_nam = [options.name '.pdf'];
+    else
+        pdf_nam = [tempname '.pdf'];
+    end
+    % Generate the options for print
+    p2eArgs = {renderer};
+    if options.colourspace == 1
+        p2eArgs = [p2eArgs {'-cmyk'}];
+    end
+    if ~options.crop
+        p2eArgs = [p2eArgs {'-loose'}];
+    end
+    try
+        % Generate an eps
+        print2eps(tmp_nam, fig, p2eArgs{:});
+        % Remove the background, if desired
+        if options.transparent && ~isequal(get(fig, 'Color'), 'none')
+            eps_remove_background(tmp_nam);
+        end
+        % Add a bookmark to the PDF if desired
+        if options.bookmark
+            fig_nam = get(fig, 'Name');
+            if isempty(fig_nam)
+                warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
+            end
+            add_bookmark(tmp_nam, fig_nam);
+        end
+        % Generate a pdf
+        eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
+    catch ex
+        % Delete the eps
+        delete(tmp_nam);
+        rethrow(ex);
+    end
+    % Delete the eps
+    delete(tmp_nam);
+    if options.eps
+        try
+            % Generate an eps from the pdf
+            pdf2eps(pdf_nam, [options.name '.eps']);
+        catch ex
+            if ~options.pdf
+                % Delete the pdf
+                delete(pdf_nam);
+            end
+            rethrow(ex);
+        end
+        if ~options.pdf
+            % Delete the pdf
+            delete(pdf_nam);
+        end
+    end
+end
+if cls
+    % Close the created figure
+    close(fig);
+else
+    % Reset the hardcopy mode
+    set(fig, 'InvertHardcopy', old_mode);
+    % Reset the axes limit and tick modes
+    for a = 1:numel(Hlims)
+        set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
+    end
+end
+return
+
+function [fig, options] = parse_args(nout, varargin)
+% Parse the input arguments
+% Set the defaults
+fig = get(0, 'CurrentFigure');
+options = struct('name', 'export_fig_out', ...
+                 'crop', true, ...
+                 'transparent', false, ...
+                 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
+                 'pdf', false, ...
+                 'eps', false, ...
+                 'png', false, ...
+                 'tif', false, ...
+                 'jpg', false, ...
+                 'bmp', false, ...
+                 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
+                 'append', false, ...
+                 'im', nout == 1, ...
+                 'alpha', nout == 2, ...
+                 'aa_factor', 3, ...
+                 'magnify', 1, ...
+                 'bookmark', false, ...
+                 'quality', []);
+native = false; % Set resolution to native of an image
+
+% Go through the other arguments
+for a = 1:nargin-1
+    if all(ishandle(varargin{a}))
+        fig = varargin{a};
+    elseif ischar(varargin{a}) && ~isempty(varargin{a})
+        if varargin{a}(1) == '-'
+            switch lower(varargin{a}(2:end))
+                case 'nocrop'
+                    options.crop = false;
+                case {'trans', 'transparent'}
+                    options.transparent = true;
+                case 'opengl'
+                    options.renderer = 1;
+                case 'zbuffer'
+                    options.renderer = 2;
+                case 'painters'
+                    options.renderer = 3;
+                case 'pdf'
+                    options.pdf = true;
+                case 'eps'
+                    options.eps = true;
+                case 'png'
+                    options.png = true;
+                case {'tif', 'tiff'}
+                    options.tif = true;
+                case {'jpg', 'jpeg'}
+                    options.jpg = true;
+                case 'bmp'
+                    options.bmp = true;
+                case 'rgb'
+                    options.colourspace = 0;
+                case 'cmyk'
+                    options.colourspace = 1;
+                case {'gray', 'grey'}
+                    options.colourspace = 2;
+                case {'a1', 'a2', 'a3', 'a4'}
+                    options.aa_factor = str2double(varargin{a}(3));
+                case 'append'
+                    options.append = true;
+                case 'bookmark'
+                    options.bookmark = true;
+                case 'native'
+                    native = true;
+                otherwise
+                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
+                    if ~isscalar(val)
+                        error('option %s not recognised', varargin{a});
+                    end
+                    switch lower(varargin{a}(2))
+                        case 'm'
+                            options.magnify = val;
+                        case 'r'
+                            options.magnify = val ./ get(0, 'ScreenPixelsPerInch');
+                        case 'q'
+                            options.quality = max(val, 0);
+                    end
+            end
+        else
+            [p, options.name, ext] = fileparts(varargin{a});
+            if ~isempty(p)
+                options.name = [p filesep options.name];
+            end
+            switch lower(ext)
+                case {'.tif', '.tiff'}
+                    options.tif = true;
+                case {'.jpg', '.jpeg'}
+                    options.jpg = true;
+                case '.png'
+                    options.png = true;
+                case '.bmp'
+                    options.bmp = true;
+                case '.eps'
+                    options.eps = true;
+                case '.pdf'
+                    options.pdf = true;
+                otherwise
+                    options.name = varargin{a};
+            end
+        end
+    end
+end
+
+% Check we have a figure handle
+if isempty(fig)
+    error('No figure found');
+end
+
+% Set the default format
+if ~isvector(options) && ~isbitmap(options)
+    options.png = true;
+end
+
+% Check whether transparent background is wanted (old way)
+if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none')
+    options.transparent = true;
+end
+
+% If requested, set the resolution to the native vertical resolution of the
+% first suitable image found
+if native && isbitmap(options)
+    % Find a suitable image
+    list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native');
+    if isempty(list)
+        list = findobj(fig, 'Type', 'image', 'Visible', 'on');
+    end
+    for hIm = list(:)'
+        % Check height is >= 2
+        height = size(get(hIm, 'CData'), 1);
+        if height < 2
+            continue
+        end
+        % Account for the image filling only part of the axes, or vice
+        % versa
+        yl = get(hIm, 'YData');
+        if isscalar(yl)
+            yl = [yl(1)-0.5 yl(1)+height+0.5];
+        else
+            if ~diff(yl)
+                continue
+            end
+            yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
+        end
+        hAx = get(hIm, 'Parent');
+        yl2 = get(hAx, 'YLim');
+        % Find the pixel height of the axes
+        oldUnits = get(hAx, 'Units');
+        set(hAx, 'Units', 'pixels');
+        pos = get(hAx, 'Position');
+        set(hAx, 'Units', oldUnits);
+        if ~pos(4)
+            continue
+        end
+        % Found a suitable image
+        % Account for stretch-to-fill being disabled
+        pbar = get(hAx, 'PlotBoxAspectRatio');
+        pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
+        % Set the magnification to give native resolution
+        options.magnify = (height * diff(yl2)) / (pos * diff(yl));
+        break
+    end
+end
+return
+
+function A = downsize(A, factor)
+% Downsample an image
+if factor == 1
+    % Nothing to do
+    return
+end
+try
+    % Faster, but requires image processing toolbox
+    A = imresize(A, 1/factor, 'bilinear');
+catch
+    % No image processing toolbox - resize manually
+    % Lowpass filter - use Gaussian as is separable, so faster
+    % Compute the 1d Gaussian filter
+    filt = (-factor-1:factor+1) / (factor * 0.6);
+    filt = exp(-filt .* filt);
+    % Normalize the filter
+    filt = single(filt / sum(filt));
+    % Filter the image
+    padding = floor(numel(filt) / 2);
+    for a = 1:size(A, 3)
+        A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
+    end
+    % Subsample
+    A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
+end
+return
+
+function A = rgb2grey(A)
+A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
+return
+
+function A = check_greyscale(A)
+% Check if the image is greyscale
+if size(A, 3) == 3 && ...
+        all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
+        all(reshape(A(:,:,2) == A(:,:,3), [], 1))
+    A = A(:,:,1); % Save only one channel for 8-bit output
+end
+return
+
+function [A, v] = crop_background(A, bcol)
+% Map the foreground pixels
+[h, w, c] = size(A);
+if isscalar(bcol) && c > 1
+    bcol = bcol(ones(1, c));
+end
+bail = false;
+for l = 1:w
+    for a = 1:c
+        if ~all(A(:,l,a) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bail = false;
+for r = w:-1:l
+    for a = 1:c
+        if ~all(A(:,r,a) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bail = false;
+for t = 1:h
+    for a = 1:c
+        if ~all(A(t,:,a) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bail = false;
+for b = h:-1:t
+    for a = 1:c
+        if ~all(A(b,:,a) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+% Crop the background, leaving one boundary pixel to avoid bleeding on
+% resize
+v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
+A = A(v(1):v(2),v(3):v(4),:);
+return
+
+function eps_remove_background(fname)
+% Remove the background of an eps file
+% Open the file
+fh = fopen(fname, 'r+');
+if fh == -1
+    error('Not able to open file %s.', fname);
+end
+% Read the file line by line
+while true
+    % Get the next line
+    l = fgets(fh);
+    if isequal(l, -1)
+        break; % Quit, no rectangle found
+    end
+    % Check if the line contains the background rectangle
+    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1)
+        % Set the line to whitespace and quit
+        l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
+        fseek(fh, -numel(l), 0);
+        fprintf(fh, l);
+        break;
+    end
+end
+% Close the file
+fclose(fh);
+return
+
+function b = isvector(options)
+b = options.pdf || options.eps;
+return
+
+function b = isbitmap(options)
+b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
+return
+
+% Helper function
+function A = make_cell(A)
+if ~iscell(A)
+    A = {A};
+end
+return
+
+function add_bookmark(fname, bookmark_text)
+% Adds a bookmark to the temporary EPS file after %%EndPageSetup
+% Read in the file
+fh = fopen(fname, 'r');
+if fh == -1
+    error('File %s not found.', fname);
+end
+try
+    fstrm = fread(fh, '*char')';
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+
+% Include standard pdfmark prolog to maximize compatibility
+fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
+% Add page bookmark
+fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
+
+% Write out the updated file
+fh = fopen(fname, 'w');
+if fh == -1
+    error('Unable to open %s for writing.', fname);
+end
+try
+    fwrite(fh, fstrm, 'char*1');
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/fix_lines.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/fix_lines.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/fix_lines.m	(revision 18231)
@@ -0,0 +1,154 @@
+function fix_lines(fname, fname2)
+%FIX_LINES  Improves the line style of eps files generated by print
+%
+% Examples:
+%   fix_lines fname
+%   fix_lines fname fname2
+%
+% This function improves the style of lines in eps files generated by
+% MATLAB's print function, making them more similar to those seen on
+% screen. Grid lines are also changed from a dashed style to a dotted
+% style, for greater differentiation from dashed lines.
+% 
+% The function also places embedded fonts after the postscript header, in
+% versions of MATLAB which place the fonts first (R2006b and earlier), in
+% order to allow programs such as Ghostscript to find the bounding box
+% information.
+%
+% IN:
+%   fname - Name or path of source eps file.
+%   fname2 - Name or path of destination eps file. Default: same as fname.
+
+% Copyright: (C) Oliver Woodford, 2008-2010
+
+% The idea of editing the EPS file to change line styles comes from Jiro
+% Doke's FIXPSLINESTYLE (fex id: 17928)
+% The idea of changing dash length with line width came from comments on
+% fex id: 5743, but the implementation is mine :)
+
+% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
+% interaction in older versions of MATLAB to my attention.
+% Thank you to D Ko for bringing an error with eps files with tiff previews
+% to my attention.
+% Thank you to Laurence K for suggesting the check to see if the file was
+% opened.
+
+% Read in the file
+fh = fopen(fname, 'r');
+if fh == -1
+    error('File %s not found.', fname);
+end
+try
+    fstrm = fread(fh, '*char')';
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+
+% Move any embedded fonts after the postscript header
+if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
+    % Find the start and end of the header
+    ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
+    [ind2 ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
+    % Put the header first
+    if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
+        fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
+    end
+end
+
+% Make sure all line width commands come before the line style definitions,
+% so that dash lengths can be based on the correct widths
+% Find all line style sections
+ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
+       regexp(fstrm, '[\n\r]DO[\n\r]'),...
+       regexp(fstrm, '[\n\r]DA[\n\r]'),...
+       regexp(fstrm, '[\n\r]DD[\n\r]')];
+ind = sort(ind);
+% Find line width commands
+[ind2 ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
+% Go through each line style section and swap with any line width commands
+% near by
+b = 1;
+m = numel(ind);
+n = numel(ind2);
+for a = 1:m
+    % Go forwards width commands until we pass the current line style
+    while b <= n && ind2(b) < ind(a)
+        b = b + 1;
+    end
+    if b > n
+        % No more width commands
+        break;
+    end
+    % Check we haven't gone past another line style (including SO!)
+    if a < m && ind2(b) > ind(a+1)
+        continue;
+    end
+    % Are the commands close enough to be confident we can swap them?
+    if (ind2(b) - ind(a)) > 8
+        continue;
+    end
+    % Move the line style command below the line width command
+    fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
+    b = b + 1;
+end
+
+% Find any grid line definitions and change to GR format
+% Find the DO sections again as they may have moved
+ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
+if ~isempty(ind)
+    % Find all occurrences of what are believed to be axes and grid lines
+    ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
+    if ~isempty(ind2)
+        % Now see which DO sections come just before axes and grid lines
+        ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
+        ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
+        ind = ind(ind2);
+        % Change any regions we believe to be grid lines to GR
+        fstrm(ind+1) = 'G';
+        fstrm(ind+2) = 'R';
+    end
+end
+
+% Isolate line style definition section
+first_sec = strfind(fstrm, '% line types:');
+[second_sec remaining] = strtok(fstrm(first_sec+1:end), '/');
+[remaining remaining] = strtok(remaining, '%');
+
+% Define the new styles, including the new GR format
+% Dot and dash lengths have two parts: a constant amount plus a line width
+% variable amount. The constant amount comes after dpi2point, and the
+% variable amount comes after currentlinewidth. If you want to change
+% dot/dash lengths for a one particular line style only, edit the numbers
+% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
+% /GR (grid lines) lines for the style you want to change.
+new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
+             '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
+             '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
+             '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
+             '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
+             '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
+             '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
+
+if nargin < 2
+    % Overwrite the input file
+    fname2 = fname;
+end
+
+% Save the file with the section replaced
+fh = fopen(fname2, 'w');
+if fh == -1
+    error('Unable to open %s for writing.', fname2);
+end
+try
+    fwrite(fh, fstrm(1:first_sec), 'char*1');
+    fwrite(fh, second_sec, 'char*1');
+    fprintf(fh, '%s\r', new_style{:});
+    fwrite(fh, remaining, 'char*1');
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/ghostscript.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/ghostscript.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/ghostscript.m	(revision 18231)
@@ -0,0 +1,139 @@
+%GHOSTSCRIPT  Calls a local GhostScript executable with the input command
+%
+% Example:
+%   [status result] = ghostscript(cmd)
+%
+% Attempts to locate a ghostscript executable, finally asking the user to
+% specify the directory ghostcript was installed into. The resulting path
+% is stored for future reference.
+% 
+% Once found, the executable is called with the input command string.
+%
+% This function requires that you have Ghostscript installed on your
+% system. You can download this from: http://www.ghostscript.com
+%
+% IN:
+%   cmd - Command string to be passed into ghostscript.
+%
+% OUT:
+%   status - 0 iff command ran without problem.
+%   result - Output from ghostscript.
+
+% Copyright: Oliver Woodford, 2009-2010
+
+% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
+% Mac OS.
+% Thanks to Nathan Childress for the fix to the default location on 64-bit
+% Windows systems.
+% 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
+% Shaun Kline for pointing out the issue
+% 4/5/11 - Thanks to David Chorlian for pointing out an alternative
+% location for gs on linux.
+% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
+% Punnoose for highlighting the issue.
+
+function varargout = ghostscript(cmd)
+% Call ghostscript
+[varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd));
+return
+
+function path_ = gs_path
+% Return a valid path
+% Start with the currently set path
+path_ = user_string('ghostscript');
+% Check the path works
+if check_gs_path(path_)
+    return
+end
+% Check whether the binary is on the path
+if ispc
+    bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
+else
+    bin = {'gs'};
+end
+for a = 1:numel(bin)
+    path_ = bin{a};
+    if check_store_gs_path(path_)
+        return
+    end
+end
+% Search the obvious places
+if ispc
+    default_location = 'C:\Program Files\gs\';
+    dir_list = dir(default_location);
+    if isempty(dir_list)
+        default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems 
+        dir_list = dir(default_location);
+    end
+    executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
+    ver_num = 0;
+    % If there are multiple versions, use the newest
+    for a = 1:numel(dir_list)
+        ver_num2 = sscanf(dir_list(a).name, 'gs%g');
+        if ~isempty(ver_num2) && ver_num2 > ver_num
+            for b = 1:numel(executable)
+                path2 = [default_location dir_list(a).name executable{b}];
+                if exist(path2, 'file') == 2
+                    path_ = path2;
+                    ver_num = ver_num2;
+                end
+            end
+        end
+    end
+    if check_store_gs_path(path_)
+        return
+    end
+else
+    bin = {'/usr/bin/gs', '/usr/local/bin/gs'};
+    for a = 1:numel(bin)
+        path_ = bin{a};
+        if check_store_gs_path(path_)
+            return
+        end
+    end
+end
+% Ask the user to enter the path
+while 1
+    if strncmp(computer, 'MAC', 3) % Is a Mac
+        % Give separate warning as the uigetdir dialogue box doesn't have a
+        % title
+        uiwait(warndlg('Ghostscript not found. Please locate the program.'))
+    end
+    base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
+    if isequal(base, 0)
+        % User hit cancel or closed window
+        break;
+    end
+    base = [base filesep];
+    bin_dir = {'', ['bin' filesep], ['lib' filesep]};
+    for a = 1:numel(bin_dir)
+        for b = 1:numel(bin)
+            path_ = [base bin_dir{a} bin{b}];
+            if exist(path_, 'file') == 2
+                if check_store_gs_path(path_)
+                    return
+                end
+            end
+        end
+    end
+end
+error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
+
+function good = check_store_gs_path(path_)
+% Check the path is valid
+good = check_gs_path(path_);
+if ~good
+    return
+end
+% Update the current default path to the path found
+if ~user_string('ghostscript', path_)
+    warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.');
+    return
+end
+return
+
+function good = check_gs_path(path_)
+% Check the path is valid
+[good, message] = system(sprintf('"%s" -h', path_));
+good = good == 0;
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/isolate_axes.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/isolate_axes.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/isolate_axes.m	(revision 18231)
@@ -0,0 +1,113 @@
+%ISOLATE_AXES Isolate the specified axes in a figure on their own
+%
+% Examples:
+%   fh = isolate_axes(ah)
+%   fh = isolate_axes(ah, vis)
+%
+% This function will create a new figure containing the axes/uipanels
+% specified, and also their associated legends and colorbars. The objects
+% specified must all be in the same figure, but they will generally only be
+% a subset of the objects in the figure.
+%
+% IN:
+%    ah - An array of axes and uipanel handles, which must come from the
+%         same figure.
+%    vis - A boolean indicating whether the new figure should be visible.
+%          Default: false.
+%
+% OUT:
+%    fh - The handle of the created figure.
+
+% Copyright (C) Oliver Woodford 2011-2012
+
+% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
+% 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio
+% for pointing out that the function is also used in export_fig.m.
+% 12/12/12 - Add support for isolating uipanels. Thanks to michael for
+% suggesting it.
+
+function fh = isolate_axes(ah, vis)
+% Make sure we have an array of handles
+if ~all(ishandle(ah))
+    error('ah must be an array of handles');
+end
+% Check that the handles are all for axes or uipanels, and are all in the same figure
+fh = ancestor(ah(1), 'figure');
+nAx = numel(ah);
+for a = 1:nAx
+    if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
+        error('All handles must be axes or uipanel handles.');
+    end
+    if ~isequal(ancestor(ah(a), 'figure'), fh)
+        error('Axes must all come from the same figure.');
+    end
+end
+% Tag the objects so we can find them in the copy
+old_tag = get(ah, 'Tag');
+if nAx == 1
+    old_tag = {old_tag};
+end
+set(ah, 'Tag', 'ObjectToCopy');
+% Create a new figure exactly the same as the old one
+fh = copyfig(fh); %copyobj(fh, 0);
+if nargin < 2 || ~vis
+    set(fh, 'Visible', 'off');
+end
+% Reset the object tags
+for a = 1:nAx
+    set(ah(a), 'Tag', old_tag{a});
+end
+% Find the objects to save
+ah = findall(fh, 'Tag', 'ObjectToCopy');
+if numel(ah) ~= nAx
+    close(fh);
+    error('Incorrect number of objects found.');
+end
+% Set the axes tags to what they should be
+for a = 1:nAx
+    set(ah(a), 'Tag', old_tag{a});
+end
+% Keep any legends and colorbars which overlap the subplots
+lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'});
+nLeg = numel(lh);
+if nLeg > 0
+    ax_pos = get(ah, 'OuterPosition');
+    if nAx > 1
+        ax_pos = cell2mat(ax_pos(:));
+    end
+    ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
+    leg_pos = get(lh, 'OuterPosition');
+    if nLeg > 1;
+        leg_pos = cell2mat(leg_pos);
+    end
+    leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
+    for a = 1:nAx
+            % Overlap test
+            ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &...
+                         leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))];
+    end
+end
+% Get all the objects in the figure
+axs = findall(fh);
+% Delete everything except for the input objects and associated items
+delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
+return
+
+function ah = allchildren(ah)
+ah = allchild(ah);
+if iscell(ah)
+    ah = cell2mat(ah);
+end
+ah = ah(:);
+return
+
+function ph = allancestors(ah)
+ph = [];
+for a = 1:numel(ah)
+    h = get(ah(a), 'parent');
+    while h ~= 0
+        ph = [ph; h];
+        h = get(h, 'parent');
+    end
+end
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/license.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/license.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/license.txt	(revision 18231)
@@ -0,0 +1,24 @@
+Copyright (c) 2012, Oliver Woodford
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in
+      the documentation and/or other materials provided with the distribution
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdf2eps.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdf2eps.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdf2eps.m	(revision 18231)
@@ -0,0 +1,51 @@
+%PDF2EPS  Convert a pdf file to eps format using pdftops
+%
+% Examples:
+%   pdf2eps source dest
+%
+% This function converts a pdf file to eps format.
+%
+% This function requires that you have pdftops, from the Xpdf suite of
+% functions, installed on your system. This can be downloaded from:
+% http://www.foolabs.com/xpdf  
+%
+%IN:
+%   source - filename of the source pdf file to convert. The filename is
+%            assumed to already have the extension ".pdf".
+%   dest - filename of the destination eps file. The filename is assumed to
+%          already have the extension ".eps".
+
+% Copyright (C) Oliver Woodford 2009-2010
+
+% Thanks to Aldebaro Klautau for reporting a bug when saving to
+% non-existant directories.
+
+function pdf2eps(source, dest)
+% Construct the options string for pdftops
+options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
+% Convert to eps using pdftops
+[status message] = pdftops(options);
+% Check for error
+if status
+    % Report error
+    if isempty(message)
+        error('Unable to generate eps. Check destination directory is writable.');
+    else
+        error(message);
+    end
+end
+% Fix the DSC error created by pdftops
+fid = fopen(dest, 'r+');
+if fid == -1
+    % Cannot open the file
+    return
+end
+fgetl(fid); % Get the first line
+str = fgetl(fid); % Get the second line
+if strcmp(str(1:min(13, end)), '% Produced by')
+    fseek(fid, -numel(str)-1, 'cof');
+    fwrite(fid, '%'); % Turn ' ' into '%'
+end
+fclose(fid);
+return
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdftops.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdftops.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/pdftops.m	(revision 18231)
@@ -0,0 +1,107 @@
+function varargout = pdftops(cmd)
+%PDFTOPS  Calls a local pdftops executable with the input command
+%
+% Example:
+%   [status result] = pdftops(cmd)
+%
+% Attempts to locate a pdftops executable, finally asking the user to
+% specify the directory pdftops was installed into. The resulting path is
+% stored for future reference.
+% 
+% Once found, the executable is called with the input command string.
+%
+% This function requires that you have pdftops (from the Xpdf package)
+% installed on your system. You can download this from:
+% http://www.foolabs.com/xpdf
+%
+% IN:
+%   cmd - Command string to be passed into pdftops.
+%
+% OUT:
+%   status - 0 iff command ran without problem.
+%   result - Output from pdftops.
+
+% Copyright: Oliver Woodford, 2009-2010
+
+% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
+% Mac OS.
+% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
+% under linux.
+
+% Call pdftops
+[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
+return
+
+function path_ = xpdf_path
+% Return a valid path
+% Start with the currently set path
+path_ = user_string('pdftops');
+% Check the path works
+if check_xpdf_path(path_)
+    return
+end
+% Check whether the binary is on the path
+if ispc
+    bin = 'pdftops.exe';
+else
+    bin = 'pdftops';
+end
+if check_store_xpdf_path(bin)
+    path_ = bin;
+    return
+end
+% Search the obvious places
+if ispc
+    path_ = 'C:\Program Files\xpdf\pdftops.exe';
+else
+    path_ = '/usr/local/bin/pdftops';
+end
+if check_store_xpdf_path(path_)
+    return
+end
+% Ask the user to enter the path
+while 1
+    if strncmp(computer,'MAC',3) % Is a Mac
+        % Give separate warning as the uigetdir dialogue box doesn't have a
+        % title
+        uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.'))
+    end
+    base = uigetdir('/', 'Pdftops not found. Please locate the program.');
+    if isequal(base, 0)
+        % User hit cancel or closed window
+        break;
+    end
+    base = [base filesep];
+    bin_dir = {'', ['bin' filesep], ['lib' filesep]};
+    for a = 1:numel(bin_dir)
+        path_ = [base bin_dir{a} bin];
+        if exist(path_, 'file') == 2
+            break;
+        end
+    end
+    if check_store_xpdf_path(path_)
+        return
+    end
+end
+error('pdftops executable not found.');
+
+function good = check_store_xpdf_path(path_)
+% Check the path is valid
+good = check_xpdf_path(path_);
+if ~good
+    return
+end
+% Update the current default path to the path found
+if ~user_string('pdftops', path_)
+    warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.');
+    return
+end
+return
+
+function good = check_xpdf_path(path_)
+% Check the path is valid
+[good message] = system(sprintf('"%s" -h', path_));
+% system returns good = 1 even when the command runs
+% Look for something distinct in the help text
+good = ~isempty(strfind(message, 'PostScript'));
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2array.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2array.m	(revision 18231)
@@ -0,0 +1,198 @@
+%PRINT2ARRAY  Exports a figure to an image array
+%
+% Examples:
+%   A = print2array
+%   A = print2array(figure_handle)
+%   A = print2array(figure_handle, resolution)
+%   A = print2array(figure_handle, resolution, renderer)
+%   [A bcol] = print2array(...)
+%
+% This function outputs a bitmap image of the given figure, at the desired
+% resolution.
+%
+% If renderer is '-painters' then ghostcript needs to be installed. This
+% can be downloaded from: http://www.ghostscript.com
+%
+% IN:
+%   figure_handle - The handle of the figure to be exported. Default: gcf.
+%   resolution - Resolution of the output, as a factor of screen
+%                resolution. Default: 1.
+%   renderer - string containing the renderer paramater to be passed to
+%              print. Default: '-opengl'.
+%
+% OUT:
+%   A - MxNx3 uint8 image of the figure.
+%   bcol - 1x3 uint8 vector of the background color
+
+% Copyright (C) Oliver Woodford 2008-2012
+
+% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
+%           renderers. Thanks to Pawel Kocieniewski for reporting the
+%           issue.
+% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting
+%           the issue.
+% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure
+%           size and erasemode settings. Makes it a bit slower, but more
+%           reliable. Thanks to Phil Trinh and Meelis Lootus for reporting
+%           the issues.
+% 09/12/11: Pass font path to ghostscript.
+% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
+%           Ken Campbell for reporting it.
+% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting
+%           it.
+% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
+%           reporting the issue.
+
+function [A, bcol] = print2array(fig, res, renderer)
+% Generate default input arguments, if needed
+if nargin < 2
+    res = 1;
+    if nargin < 1
+        fig = gcf;
+    end
+end
+% Warn if output is large
+old_mode = get(fig, 'Units');
+set(fig, 'Units', 'pixels');
+px = get(fig, 'Position');
+set(fig, 'Units', old_mode);
+npx = prod(px(3:4)*res)/1e6;
+if npx > 30
+    % 30M pixels or larger!
+    warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
+end
+% Retrieve the background colour
+bcol = get(fig, 'Color');
+% Set the resolution parameter
+res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
+% Generate temporary file name
+tmp_nam = [tempname '.tif'];
+if nargin > 2 && strcmp(renderer, '-painters')
+    % Print to eps file
+    tmp_eps = [tempname '.eps'];
+    print2eps(tmp_eps, fig, renderer, '-loose');
+    try
+        % Initialize the command to export to tiff using ghostscript
+        cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
+        % Set the font path
+        fp = font_path();
+        if ~isempty(fp)
+            cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
+        end
+        % Add the filenames
+        cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"'];
+        % Execute the ghostscript command
+        ghostscript(cmd_str);
+    catch me
+        % Delete the intermediate file
+        delete(tmp_eps);
+        rethrow(me);
+    end
+    % Delete the intermediate file
+    delete(tmp_eps);
+    % Read in the generated bitmap
+    A = imread(tmp_nam);
+    % Delete the temporary bitmap file
+    delete(tmp_nam);
+    % Set border pixels to the correct colour
+    if isequal(bcol, 'none')
+        bcol = [];
+    elseif isequal(bcol, [1 1 1])
+        bcol = uint8([255 255 255]);
+    else
+        for l = 1:size(A, 2)
+            if ~all(reshape(A(:,l,:) == 255, [], 1))
+                break;
+            end
+        end
+        for r = size(A, 2):-1:l
+            if ~all(reshape(A(:,r,:) == 255, [], 1))
+                break;
+            end
+        end
+        for t = 1:size(A, 1)
+            if ~all(reshape(A(t,:,:) == 255, [], 1))
+                break;
+            end
+        end
+        for b = size(A, 1):-1:t
+            if ~all(reshape(A(b,:,:) == 255, [], 1))
+                break;
+            end
+        end
+        bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
+        for c = 1:size(A, 3)
+            A(:,[1:l-1, r+1:end],c) = bcol(c);
+            A([1:t-1, b+1:end],:,c) = bcol(c);
+        end
+    end
+else
+    if nargin < 3
+        renderer = '-opengl';
+    end
+    err = false;
+    % Set paper size
+    old_pos_mode = get(fig, 'PaperPositionMode');
+    old_orientation = get(fig, 'PaperOrientation');
+    set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
+    try
+        % Print to tiff file
+        print(fig, renderer, res_str, '-dtiff', tmp_nam);
+        % Read in the printed file
+        A = imread(tmp_nam);
+        % Delete the temporary file
+        delete(tmp_nam);
+    catch ex
+        err = true;
+    end
+    % Reset paper size
+    set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
+    % Throw any error that occurred
+    if err
+        rethrow(ex);
+    end
+    % Set the background color
+    if isequal(bcol, 'none')
+        bcol = [];
+    else
+        bcol = bcol * 255;
+        if isequal(bcol, round(bcol))
+            bcol = uint8(bcol);
+        else
+            bcol = squeeze(A(1,1,:));
+        end
+    end
+end
+% Check the output size is correct
+if isequal(res, round(res))
+    px = [px([4 3])*res 3];
+    if ~isequal(size(A), px)
+        % Correct the output size
+        A = A(1:min(end,px(1)),1:min(end,px(2)),:);
+    end
+end
+return
+
+% Function to return (and create, where necessary) the font path
+function fp = font_path()
+fp = user_string('gs_font_path');
+if ~isempty(fp)
+    return
+end
+% Create the path
+% Start with the default path
+fp = getenv('GS_FONTPATH');
+% Add on the typical directories for a given OS
+if ispc
+    if ~isempty(fp)
+        fp = [fp ';'];
+    end
+    fp = [fp getenv('WINDIR') filesep 'Fonts'];
+else
+    if ~isempty(fp)
+        fp = [fp ':'];
+    end
+    fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
+end
+user_string('gs_font_path', fp);
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2eps.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/print2eps.m	(revision 18231)
@@ -0,0 +1,206 @@
+%PRINT2EPS  Prints figures to eps with improved line styles
+%
+% Examples:
+%   print2eps filename
+%   print2eps(filename, fig_handle)
+%   print2eps(filename, fig_handle, options)
+%
+% This function saves a figure as an eps file, with two improvements over
+% MATLAB's print command. First, it improves the line style, making dashed
+% lines more like those on screen and giving grid lines their own dotted
+% style. Secondly, it substitutes original font names back into the eps
+% file, where these have been changed by MATLAB, for up to 11 different
+% fonts.
+%
+%IN:
+%   filename - string containing the name (optionally including full or
+%              relative path) of the file the figure is to be saved as. A
+%              ".eps" extension is added if not there already. If a path is
+%              not specified, the figure is saved in the current directory.
+%   fig_handle - The handle of the figure to be saved. Default: gcf.
+%   options - Additional parameter strings to be passed to print.
+
+% Copyright (C) Oliver Woodford 2008-2013
+
+% The idea of editing the EPS file to change line styles comes from Jiro
+% Doke's FIXPSLINESTYLE (fex id: 17928)
+% The idea of changing dash length with line width came from comments on
+% fex id: 5743, but the implementation is mine :)
+
+% 14/11/2011: Fix a MATLAB bug rendering black or white text incorrectly.
+%             Thanks to Mathieu Morlighem for reporting the issue and
+%             obtaining a fix from TMW.
+% 08/12/11: Added ability to correct fonts. Several people have requested
+%           this at one time or another, and also pointed me to printeps
+%           (fex id: 7501), so thank you to them. My implementation (which
+%           was not inspired by printeps - I'd already had the idea for my
+%           approach) goes slightly further in that it allows multiple
+%           fonts to be swapped.
+% 14/12/11: Fix bug affecting font names containing spaces. Thanks to David
+%           Szwer for reporting the issue.
+% 25/01/12: Add a font not to be swapped. Thanks to Anna Rafferty and Adam
+%           Jackson for reporting the issue. Also fix a bug whereby using a
+%           font alias can lead to another font being swapped in.
+% 10/04/12: Make the font swapping case insensitive.
+% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
+%           reporting the issue.
+% 26/10/12: Fix issue to do with swapping fonts changing other fonts and
+%           sizes we don't want, due to listeners. Thanks to Malcolm Hudson
+%           for reporting the issue.
+% 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
+%           for reporting the issue.
+
+function print2eps(name, fig, varargin)
+options = {'-depsc2'};
+if nargin < 2
+    fig = gcf;
+elseif nargin > 2
+    options = [options varargin];
+end
+% Construct the filename
+if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps')
+    name = [name '.eps']; % Add the missing extension
+end
+% Find all the used fonts in the figure
+font_handles = findall(fig, '-property', 'FontName');
+fonts = get(font_handles, 'FontName');
+if ~iscell(fonts)
+    fonts = {fonts};
+end
+% Map supported font aliases onto the correct name
+fontsl = lower(fonts);
+for a = 1:numel(fonts)
+    f = fontsl{a};
+    f(f==' ') = [];
+    switch f
+        case {'times', 'timesnewroman', 'times-roman'}
+            fontsl{a} = 'times-roman';
+        case {'arial', 'helvetica'}
+            fontsl{a} = 'helvetica';
+        case {'newcenturyschoolbook', 'newcenturyschlbk'}
+            fontsl{a} = 'newcenturyschlbk';
+        otherwise
+    end
+end
+fontslu = unique(fontsl);
+% Determine the font swap table
+matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
+                'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
+matlab_fontsl = lower(matlab_fonts);
+require_swap = find(~ismember(fontslu, matlab_fontsl));
+unused_fonts = find(~ismember(matlab_fontsl, fontslu));
+font_swap = cell(3, min(numel(require_swap), numel(unused_fonts)));
+fonts_new = fonts;
+for a = 1:size(font_swap, 2)
+    font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
+    font_swap{2,a} = matlab_fonts{unused_fonts(a)};
+    font_swap{3,a} = fonts{font_swap{1,end}(1)};
+    fonts_new(font_swap{1,a}) = {font_swap{2,a}};
+end
+% Swap the fonts
+if ~isempty(font_swap)
+    fonts_size = get(font_handles, 'FontSize');
+    if iscell(fonts_size)
+        fonts_size = cell2mat(fonts_size);
+    end
+    M = false(size(font_handles));
+    % Loop because some changes may not stick first time, due to listeners
+    c = 0;
+    update = zeros(1000, 1);
+    for b = 1:10 % Limit number of loops to avoid infinite loop case
+        for a = 1:numel(M)
+            M(a) = ~isequal(get(font_handles(a), 'FontName'), fonts_new{a}) || ~isequal(get(font_handles(a), 'FontSize'), fonts_size(a));
+            if M(a)
+                set(font_handles(a), 'FontName', fonts_new{a}, 'FontSize', fonts_size(a));
+                c = c + 1;
+                update(c) = a;
+            end
+        end
+        if ~any(M)
+            break;
+        end
+    end
+    % Compute the order to revert fonts later, without the need of a loop
+    [update, M] = unique(update(1:c));
+    [M, M] = sort(M);
+    update = reshape(update(M), 1, []);
+end
+% Set paper size
+old_pos_mode = get(fig, 'PaperPositionMode');
+old_orientation = get(fig, 'PaperOrientation');
+set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
+% MATLAB bug fix - black and white text can come out inverted sometimes
+% Find the white and black text
+white_text_handles = findobj(fig, 'Type', 'text');
+M = get(white_text_handles, 'Color');
+if iscell(M)
+    M = cell2mat(M);
+end
+M = sum(M, 2);
+black_text_handles = white_text_handles(M == 0);
+white_text_handles = white_text_handles(M == 3);
+% Set the font colors slightly off their correct values
+set(black_text_handles, 'Color', [0 0 0] + eps);
+set(white_text_handles, 'Color', [1 1 1] - eps);
+% Print to eps file
+print(fig, options{:}, name);
+% Reset the font colors
+set(black_text_handles, 'Color', [0 0 0]);
+set(white_text_handles, 'Color', [1 1 1]);
+% Reset paper size
+set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
+% Correct the fonts
+if ~isempty(font_swap)
+    % Reset the font names in the figure
+    for a = update
+        set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
+    end
+    % Replace the font names in the eps file
+    font_swap = font_swap(2:3,:);
+    try
+        swap_fonts(name, font_swap{:});
+    catch
+        warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
+        return
+    end
+end
+% Fix the line styles
+try
+    fix_lines(name);
+catch
+    warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
+end
+return
+
+function swap_fonts(fname, varargin)
+% Read in the file
+fh = fopen(fname, 'r');
+if fh == -1
+    error('File %s not found.', fname);
+end
+try
+    fstrm = fread(fh, '*char')';
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+
+% Replace the font names
+for a = 1:2:numel(varargin)
+    fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1})));
+end
+
+% Write out the updated file
+fh = fopen(fname, 'w');
+if fh == -1
+    error('Unable to open %s for writing.', fname2);
+end
+try
+    fwrite(fh, fstrm, 'char*1');
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/user_string.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/export_fig/user_string.m	(revision 18231)
@@ -0,0 +1,87 @@
+%USER_STRING  Get/set a user specific string
+%
+% Examples:
+%   string = user_string(string_name)
+%   saved = user_string(string_name, new_string)
+%
+% Function to get and set a string in a system or user specific file. This
+% enables, for example, system specific paths to binaries to be saved.
+%
+% IN:
+%   string_name - String containing the name of the string required. The
+%                 string is extracted from a file called (string_name).txt,
+%                 stored in the same directory as user_string.m.
+%   new_string - The new string to be saved under the name given by
+%                string_name.
+%
+% OUT:
+%   string - The currently saved string. Default: ''.
+%   saved - Boolean indicating whether the save was succesful
+
+% Copyright (C) Oliver Woodford 2011-2013
+
+% This method of saving paths avoids changing .m files which might be in a
+% version control system. Instead it saves the user dependent paths in
+% separate files with a .txt extension, which need not be checked in to
+% the version control system. Thank you to Jonas Dorn for suggesting this
+% approach.
+
+% 10/01/2013 - Access files in text, not binary mode, as latter can cause
+% errors. Thanks to Christian for pointing this out.
+
+function string = user_string(string_name, string)
+if ~ischar(string_name)
+    error('string_name must be a string.');
+end
+% Create the full filename
+string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']);
+if nargin > 1
+    % Set string
+    if ~ischar(string)
+        error('new_string must be a string.');
+    end
+    % Make sure the save directory exists
+    dname = fileparts(string_name);
+    if ~exist(dname, 'dir')
+        % Create the directory
+        try
+            if ~mkdir(dname)                
+                string = false;
+                return
+            end
+        catch
+            string = false;
+            return
+        end
+        % Make it hidden
+        try
+            fileattrib(dname, '+h');
+        catch
+        end
+    end
+    % Write the file
+    fid = fopen(string_name, 'wt');
+    if fid == -1
+        string = false;
+        return
+    end
+    try
+        fprintf(fid, '%s', string);
+    catch
+        fclose(fid);
+        string = false;
+        return
+    end
+    fclose(fid);
+    string = true;
+else
+    % Get string
+    fid = fopen(string_name, 'rt');
+    if fid == -1
+        string = '';
+        return
+    end
+    string = fgetl(fid);
+    fclose(fid);
+end
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ffmpeg/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ffmpeg/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ffmpeg/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install ffmpeg-1.1.2
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ffmpeg-1.1.2.tar.gz' 'ffmpeg-1.1.2.tar.gz'
+
+#Untar 
+tar -zxvf  ffmpeg-1.1.2.tar.gz
+
+#Move ffmpeg into src directory
+mv ffmpeg-1.1.2/* src
+rm -rf ffmpeg-1.1.2
+
+#Configure ffmpeg
+cd src
+
+export CFLAGS=" -arch x86_64"
+
+./configure --prefix="$ISSM_DIR/externalpackages/ffmpeg/install" --disable-yasm
+
+#Compile ffmpeg
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/README	(revision 18231)
@@ -0,0 +1,2 @@
+Fingbugs for Java programs. 
+Downloaded from http://findbugs.sourceforge.net/downloads.html
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/findbugs/install.sh	(revision 18231)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  findbugs-1.3.9
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/findbugs-1.3.9.tar.gz' 'findbugs-1.3.9.tar.gz'
+tar -zxvf findbugs-1.3.9.tar.gz 
+
+mv findbugs-1.3.9/* install
+rm -rf findbugs-1.3.9
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/flaim/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/flaim/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/flaim/install.sh	(revision 18231)
@@ -0,0 +1,8 @@
+#!/bin/bash
+set -eu
+
+#Erase symlink
+rm -rf install
+
+#symlink to flaim directory
+ln -s /home/jschierm/flaim/svn/trunk ./install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/freetype/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/freetype/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/freetype/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf freetype-2.5.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/freetype-2.5.0.tar.gz' 'freetype-2.5.0.tar.gz'
+
+#Untar 
+tar -zxvf  freetype-2.5.0.tar.gz
+
+#Move freetype into src directory
+mv freetype-2.5.0/* src
+rm -rf freetype-2.5.0
+
+#Configure freetype
+cd src
+sudo ./configure 
+
+#Compile and install freetype
+if [ $# -eq 0 ]; then
+	sudo make
+else
+	sudo make -j $1
+fi
+sudo make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/Makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/Makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/Makefile	(revision 18231)
@@ -0,0 +1,90 @@
+## * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+##* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+##=======================================================================
+##Copyright (C) 2010-2013 Leonardo A. BAUTISTA GOMEZ
+##This program is free software; you can redistribute it and/or modify
+##it under the terms of the GNU General Public License (GPL) as published
+##of the License, or (at your option) any later version.
+##
+##This program is distributed in the hope that it will be useful,
+##but WITHOUT ANY WARRANTY; without even the implied warranty of
+##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##GNU General Public License for more details.
+##
+##To read the license please visit http://www.gnu.org/copyleft/gpl.html
+##=======================================================================
+
+##=======================================================================
+##   PLEASE SET THESE VARIABLES BEFORE COMPILING
+##=======================================================================
+
+FTIPATH		= $(ISSM_DIR)/externalpackages/fti/install
+MPIPATH		= $(ISSM_DIR)/externalpackages/mpich/install
+
+##=======================================================================
+##   DIRECTORY TREE
+##=======================================================================
+
+LIB 		= lib
+OBJ		= obj
+SRC		= src
+DOC		= doc
+INC		= include
+
+##=======================================================================
+##   COMPILERS
+##=======================================================================
+
+CC 		= gcc
+MPICC 		= mpicc
+
+##=======================================================================
+##   FLAGS
+##=======================================================================
+
+FTIFLAGS	= -fPIC -g -Iinclude/ -c
+MPIFLAGS	= -I$(MPIPATH)/include -L$(MPIPATH)/lib -lmpich -lpmpich
+
+##=======================================================================
+##   TARGETS
+##=======================================================================
+
+
+OBJS		= $(OBJ)/galois.o $(OBJ)/jerasure.o $(OBJ)/dictionary.o $(OBJ)/iniparser.o \
+		$(OBJ)/recover.o $(OBJ)/tools.o $(OBJ)/checkpoint.o $(OBJ)/topo.o \
+		$(OBJ)/api.o
+
+SHARED		= libfti.so
+STATIC		= libfti.a
+
+all: 		$(SHARED) $(STATIC)
+
+doc:
+		doxygen $(DOC)/Doxyfile
+
+$(OBJ)/%.o:	$(SRC)/%.c
+		$(MPICC) $(FTIFLAGS) $< -o $@
+
+$(SHARED):	$(OBJS)
+		$(CC) $(MPIFLAGS) -shared -o $(LIB)/$(SHARED) $(OBJS) -lc
+
+$(STATIC):	$(OBJS)
+		$(AR) -cvq $(LIB)/$(STATIC) $(OBJS)
+install:
+		if [ ! -d "$(FTIPATH)/FTI" ]; then mkdir $(FTIPATH)/FTI; fi
+		if [ ! -d "$(FTIPATH)/FTI/$(LIB)" ]; then mkdir $(FTIPATH)/FTI/$(LIB); fi
+		if [ ! -d "$(FTIPATH)/FTI/$(INC)" ]; then mkdir $(FTIPATH)/FTI/$(INC); fi
+		rm -f $(FTIPATH)/FTI/$(LIB)/* $(FTIPATH)/FTI/$(INC)/*
+		cp $(INC)/* $(FTIPATH)/FTI/$(INC)/
+		cp $(LIB)/* $(FTIPATH)/FTI/$(LIB)/
+
+uninstall:
+		rm -f $(FTIPATH)/FTI/$(LIB)/* $(FTIPATH)/FTI/$(INC)/*
+		if [ -d "$(FTIPATH)/FTI/$(LIB)" ]; then rmdir $(FTIPATH)/FTI/$(LIB); fi
+		if [ -d "$(FTIPATH)/FTI/$(INC)" ]; then rmdir $(FTIPATH)/FTI/$(INC); fi
+		if [ -d "$(FTIPATH)/FTI" ]; then rmdir $(FTIPATH)/FTI; fi
+
+clean:
+		rm -f $(OBJ)/* $(LIB)/*
+
+.PHONY:		$(SHARED) $(STATIC) doc install uninstall clean
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/fti/install.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install fti-0.9.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/fti-0.9.2.tgz' 'fti-0.9.2.tgz'
+
+#Untar 
+tar -zxvf  fti-0.9.2.tgz
+
+#Move mpich into src directory
+mv fti/* install
+rm -rf fti
+
+#Configure mpich
+cd install
+cp ../Makefile .
+
+#Compile mpich (this new version supports parallel make)
+make
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/configs/GDALmake.opt.patch.murdo
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/configs/GDALmake.opt.patch.murdo	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/configs/GDALmake.opt.patch.murdo	(revision 18231)
@@ -0,0 +1,8 @@
+31c31
+< LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib -lexpat -ljpeg -lpng -lz  -lm -lrt -ldl  $(KAK_LIBS) $(DWG_LIBS) $(CURL_LIB) \
+---
+> LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib64 -lexpat -ljpeg -lpng -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/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-linux64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#WARNING: you need to have python installed in externalpackages
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.10.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.10.0.tar.gz' 'gdal-1.10.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.10.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.10.0/* src
+rm -rf gdal-1.10.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--with-python \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-hdf5
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.10-macosx64.sh	(revision 18231)
@@ -0,0 +1,38 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.10.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.10.0.tar.gz' 'gdal-1.10.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.10.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.10.0/* src
+rm -rf gdal-1.10.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--with-python \
+	--with-netcdf=no \
+	--with-libiconv-prefix="/usr/lib/" \
+	--without-hdf5 \
+	--with-expat=$ISSM_DIR/externalpackages/expat/install
+#Note:
+# look for libiconv in /usr/lib/ because there seemed to be a conflict with port's library
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-linux64-murdo.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-linux64-murdo.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-linux64-murdo.sh	(revision 18231)
@@ -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 ../configs/GDALmake.opt.patch
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gdal/install-1.6-macosx64.sh	(revision 18231)
@@ -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 \
+	--without-hdf5 \
+	--with-unix-stdio-64=no \
+	--with-expat=$ISSM_DIR/externalpackages/expat/install
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/geos5/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/geos5/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/geos5/install.sh	(revision 18231)
@@ -0,0 +1,7 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf  GEOSagcm
+#svn download
+svn --username eric.larour@jpl.nasa.gov checkout http://geos5.org/svn/branches/Fortuna-2_5_p1 GEOSagcm
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gfortran/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gfortran/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gfortran/README	(revision 18231)
@@ -0,0 +1,7 @@
+For Mac users, you can download a fortran compiler on:
+http://gcc.gnu.org/wiki/GFortranBinaries
+
+Other websites:
+http://www.macresearch.org/gfortran-leopard
+http://hpc.sourceforge.net/
+http://r.research.att.com/tools/ or http://cran.r-project.org/bin/macosx/tools/
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/git/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/git/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/git/install.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/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" 
+#--with-python="$ISSM_DIR/externalpackages/python/install/bin/python" #Do we really need this line?
+	
+#Compile
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmake/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmake/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmake/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src make-3.82
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/make-3.82.tar.gz' 'make-3.82.tar.gz'
+
+#Untar 
+tar -zxvf  make-3.82.tar.gz
+
+#Move make into install directory
+mv make-3.82/* src
+rm -rf make-3.82
+
+#Apply patches
+cd src 
+
+#Configure and compile: 
+./configure --prefix=$ISSM_DIR/externalpackages/gmake/install
+
+if [ $# -eq 0 ]; then
+	make
+	make install
+else 
+	make -j $1; 
+	make -j $1 install;
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmp/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmp/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmp/install-linux64.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/gmsh/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmsh/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gmsh/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+mkdir install
+
+#Download latest version
+svn --username gmsh --password gmsh co https://geuz.org/svn/gmsh/trunk src
+
+#Configure
+cd install
+cmake ../src -DCMAKE_INSTALL_PREFIX="$ISSM_DIR/externalpackages/gmsh/install"
+
+#Compile and install
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/googleearthtoolbox/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/googleearthtoolbox/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/googleearthtoolbox/install.sh	(revision 18231)
@@ -0,0 +1,8 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install  
+
+#Download code: 
+svn checkout http://googleearthtoolbox.googlecode.com/svn/trunk/ install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/graphviz/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/graphviz/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/graphviz/install.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/graphviz-2.24.0.tar.gz' 'graphviz-2.24.0.tar.gz'
+
+#Untar 
+tar -zxvf  graphviz-2.24.0.tar.gz
+
+#Move Dakota to src directory
+mv graphviz-2.24.0/* src/
+rm -rf graphviz-2.24.0
+
+#Configure dakota
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/graphviz/install"
+cd ..
+
+#Compile and install
+cd src
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/Makefile.am.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/Makefile.am.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/Makefile.am.patch	(revision 18231)
@@ -0,0 +1,27 @@
+--- Makefile.am	2011-04-14 08:13:48.000000000 -0700
++++ Makefile.am_tmp	2012-11-12 14:54:02.000000000 -0800
+@@ -24,10 +24,22 @@
+ noinst_HEADERS = templates_on.h templates_off.h build.h
+ 
+ MINGW32_HOST = @MINGW32_HOST@
+-if MINGW32_HOST
++
++# Origional 'Makefile.am' sets 'libgslcblas.la' as a requirement for
++#'libgsl.ls' only if the host system is detected to be MingW32. This
++# is unfortunate as 'libgsl.la' has undefined 'cblas' symbols the
++# result is linking errors at run time. This patch sets the 'cblas'
++# library as a requirement for linking 'libgsl'.
++#
++# Origional script:
++#
++# if MINGW32_HOST
++# libgsl_la_LIBADD += cblas/libgslcblas.la
++# libgsl_la_LDFLAGS += -no-undefined
++# endif
++
+ libgsl_la_LIBADD += cblas/libgslcblas.la
+ libgsl_la_LDFLAGS += -no-undefined
+-endif
+ 
+ m4datadir = $(datadir)/aclocal
+ m4data_DATA = gsl.m4
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/README	(revision 18231)
@@ -0,0 +1,1 @@
+GNU Scientfic Library, obtained from: http://www.gnu.org/software/gsl/
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-android.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-android.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-android.sh	(revision 18231)
@@ -0,0 +1,49 @@
+#!/bin/bash
+set -eu
+
+source $ANDROID_DIR/android_aux.sh
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+    #Some cleanup
+    rm -rf src install gsl-1.15
+    mkdir src install
+
+    #Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'
+
+    #Untar 
+    tar -zxvf  gsl-1.15.tar.gz
+
+    #Move gsl into src directory
+    mv gsl-1.15/* src
+    rm -rf gsl-1.15
+fi
+
+#Configure gsl
+if [[ $step == "2" || $step == "0" ]]; then
+    cd src
+
+    patch Makefile.am < ./../Makefile.am.patch
+
+    autoreconf -if
+
+    ./configure \
+        --build="i386-apple-darwin10.8.0" \
+        --host=$host_triplet \
+	    --prefix="$ISSM_DIR/externalpackages/gsl/install"
+fi
+
+#Compile gsl
+if [[ $step == "3" || $step == "0" ]]; then
+	cd $ISSM_DIR/externalpackages/gsl/src
+
+    if [ $# -eq 0 ]; then
+	    make 
+    else
+	    make -j $j 
+    fi
+
+    make install
+fi
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-greenplanet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-greenplanet.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-ios.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-ios.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-ios.sh	(revision 18231)
@@ -0,0 +1,63 @@
+#!/bin/bash
+set -eu
+
+source $ANDROID_DIR/android_aux.sh
+export DEVROOT="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/"
+export SDKROOT="$DEVROOT/SDKs/iPhoneOS6.0.sdk/"
+export CC="$DEVROOT/usr/bin/gcc -arch armv7"
+export CFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export CXXFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export CPP=$DEVROOT/usr/bin/cpp
+export CXX=$DEVROOT/usr/bin/g++
+export AR=$DEVROOT/usr/bin/ar
+export AS=$DEVROOT/usr/bin/as
+export LIBTOOL=$DEVROOT/usr/bin/libtool
+export LDFLAGS="-lstdc++ -arch armv7 -isysroot $SDKROOT"
+export STRIP=$DEVROOT/usr/bin/strip
+export RANLIB=$DEVROOT/usr/bin/ranlib
+
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+    #Some cleanup
+    rm -rf src install gsl-1.15
+    mkdir src install
+
+    #Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'
+
+    #Untar 
+    tar -zxvf  gsl-1.15.tar.gz
+
+    #Move gsl into src directory
+    mv gsl-1.15/* src
+    rm -rf gsl-1.15
+fi
+
+#Configure gsl
+if [[ $step == "2" || $step == "0" ]]; then
+    cd src
+
+    patch Makefile.am < ./../Makefile.am.patch
+
+    autoreconf -if
+
+    ./configure \
+		--build="i386-apple-darwin10.8.0" \
+		--host="arm-apple-darwin10" \
+	    --prefix="$ISSM_DIR/externalpackages/gsl/install"
+fi
+
+#Compile gsl
+if [[ $step == "3" || $step == "0" ]]; then
+	cd $ISSM_DIR/externalpackages/gsl/src
+
+    if [ $# -eq 0 ]; then
+	    make 
+    else
+	    make -j $j 
+    fi
+
+    make install
+fi
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-linux64.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+export CFLAGS=" -arch x86_64"
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-pleiades.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-walgreen.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-walgreen.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gsl/install-walgreen.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+export CC=icc
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gslib/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gslib/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/gslib/install.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gslib90_ls.tar.gz' 'gslib90_ls.tar.gz'
+
+#Untar 
+tar -zxvf  gslib90_ls.tar.gz
+
+#Move gslib into install directory
+mv gslib90/* install
+rm -rf gslib90
+
+#Change compiler to gfortran
+cd install
+cat Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+mv Makefile.bak Makefile
+cat gslib/Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+mv Makefile.bak gslib/Makefile
+make 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/h5py/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/h5py/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/h5py/install.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/bash
+set -eu
+
+#needed further along
+export HDF5_DIR=$ISSM_DIR/externalpackages/hdf5/install
+
+#Some cleanup
+rm -rf install h5py-2.0.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/h5py-2.0.1.tar.gz' 'h5py-2.0.1.tar.gz'
+
+#Untar 
+tar -zxvf  h5py-2.0.1.tar.gz
+
+#Move h5py to install directory
+rm -rf install/*
+mv h5py-2.0.1/* install/
+rm -rf h5py-2.0.1
+
+#Configure and compile
+cd install
+python setup.py build –hdf5=$ISSM_DIR/externalpackages/hdf5/install
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/hdf5/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/hdf5/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/hdf5/install.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install hdf5-1.8.9
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/hdf5-1.8.9.tar.gz' 'hdf5-1.8.9.tar.gz'
+
+#Untar 
+tar -zxvf  hdf5-1.8.9.tar.gz
+
+#Move hdf5 to src directory
+rm -rf src/*
+mv hdf5-1.8.9/* src/
+rm -rf hdf5-1.8.9
+
+#Configure and compile
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/hdf5/install" 
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/enviread.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/enviread.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/enviread.m	(revision 18231)
@@ -0,0 +1,323 @@
+function I=enviread(varargin)
+%enviread: Read binary image files using ENVI header information
+%
+%I=enviread('filename') where the header file is named filename.hdr
+%and exists in the same directory. Otherwise use 
+%
+%I=enviread('filename','hdrfilename')
+%
+%The output structure I contains fields I.x, I.y, I.z and I.info
+%containing the x-coordinate vector, y-coordinate vector,
+%images data and header info, respectively. I.z will be in whatever
+%number format (double, int, etc.) as in the envi file.
+%
+%Original version by Ian Howat, Ohio State Universtiy, ihowat@gmail.com
+%Thanks to Yushin Ahn and Ray Jung
+%
+%% Current version 3 - adding subsetting feature to read only parts of
+%% files.
+
+file=varargin{1};
+hdrfile=[deblank(file),'.hdr'];
+info=read_envihdr(hdrfile);
+sub = [1, info.samples, 1, info.lines];
+if nargin==2
+    if varargin{2}=='date'
+        [pathstr, name, ext, versn] = fileparts(file);
+        info.hdrname=hdrfile;
+        info.ipath=pathstr;
+        info.iname=name;
+        info.ipname=file;
+        info.year =name(1:4);
+        info.month=name(5:6);
+        info.day  =name(7:8);
+        info.date =name(1:8);
+        info.sfname=name(1:14);
+        info.datenum=datenum(str2double(info.year),...
+            str2double(info.month),str2double(info.day));
+    end
+end
+
+% subset
+if nargin == 3;
+    if strcmp(varargin{2},'pixel_subset');
+        sub = varargin{3};
+    elseif strcmp(varargin{2},'map_subset');
+        sub = varargin{3};
+        subx = (sub(1:2)-info.map_info.mapx)./info.map_info.dx;
+        suby = (info.map_info.mapy - sub(3:4))./info.map_info.dy;
+        subx = round(subx);
+        suby = round(suby);
+        
+        subx(subx < 1) = 1;
+        suby(suby < 1) = 1;
+        subx(subx > info.samples) = info.samples;
+        suby(suby > info.lines)   = info.lines;
+      
+        sub  = [subx,suby];
+    end
+end
+
+sub(1:2) = sort(sub(1:2));
+sub(3:4) = sort(sub(3:4));
+
+
+%% Make geo-location vectors
+if isfield(info.map_info,'mapx') && isfield(info.map_info,'mapy')
+    xi = info.map_info.image_coords(1);
+    yi = info.map_info.image_coords(2);
+    xm = info.map_info.mapx;
+    ym = info.map_info.mapy;
+    %adjust points to corner (1.5,1.5)
+    if yi > 1.5
+        ym =  ym + ((yi*info.map_info.dy)-info.map_info.dy);
+    end
+    if xi > 1.5
+        xm = xm - ((xi*info.map_info.dy)-info.map_info.dx);
+    end
+
+    I.x = xm + ((0:info.samples-1).*info.map_info.dx);
+    I.y = ym - ((0:info.lines-1).*  info.map_info.dy);
+    %I.x = xm + (subE(1):subE(2)-1).*info.map_info.dx;
+    %I.y = ym - (subE(3):subE(4)-1).*info.map_info.dy;
+end
+
+
+I.x = I.x(sub(1):sub(2));
+I.y = I.y(sub(3):sub(4));
+
+
+%% Set binary format parameters
+switch info.byte_order
+    case {0}
+        machine = 'ieee-le';
+    case {1}
+        machine = 'ieee-be';
+    otherwise
+        machine = 'n';
+end
+switch info.data_type
+    case {1}
+        format = 'uint8';
+    case {2}
+        format= 'int16';
+    case{3}
+        format= 'int32';
+    case {4}
+        format= 'single';
+    case {5}
+        format= 'double';
+    case {6}
+        disp('>> Sorry, Complex (2x32 bits)data currently not supported');
+        disp('>> Importing as double-precision instead');
+        format= 'double';
+    case {9}
+        error('Sorry, double-precision complex (2x64 bits) data currently not supported');
+    case {12}
+        format= 'uint16';
+    case {13}
+        format= 'uint32';
+    case {14}
+        format= 'int64';
+    case {15}
+        format= 'uint64';
+    otherwise
+        error(['File type number: ',num2str(dtype),' not supported']);
+end
+
+%% file read
+% Version 2 code by Yushin Ahn - replaces resize calls with loops (except
+% for BIP formats) to work on big arrays.
+
+        %tmp=zeros(info.lines, info.samples,info.bands,format);
+        tmp=zeros(sub(4)-sub(3)+1,sub(2)-sub(1)+1,info.bands,format);
+        fid=fopen(file,'r');
+
+switch lower(info.interleave)
+
+    case {'bsq'}
+        % Format:
+        % [Band 1]       
+        % R1: C1, C2, C3, ...
+        % R2: C1, C2, C3, ...
+        %  ...
+        % RN: C1, C2, C3, ...
+        %
+        % [Band 2]
+        %  ...
+        % [Band N]
+
+%% Old Script w/out subsetting
+%         for b=1:info.bands
+%             for i=1:info.lines
+%                 t=fread(fid,info.samples,format);
+%                 tmp(i,:,b)=t;    
+%             end
+%         end
+        
+%% New Subsetting script - IMH
+        offset1=(sub(3)-1)*info.samples;
+        fseek(fid,offset1,'bof');
+        for b=1:info.bands
+            for i=sub(3):sub(4)
+                t=fread(fid,info.samples,format);
+                %if i >=  sub(3) && i <= sub(4)
+                    tmp(i-sub(3)+1,:,b)=t(sub(1):sub(2));
+                %end
+            end
+            offset2 = info.samples*info.lines*b+offset1;
+            fseek(fid,offset2,'bof');
+        end
+
+    case {'bil'}
+        % Format:        
+        % [Row 1]      
+        % B1: C1, C2, C3, ...
+        % B2: C1, C2, C3, ...
+        %
+        %  ...
+        % [Row N]
+
+%         for i=1:info.lines
+%             for b=1:info.bands
+%                  t=fread(fid,info.samples,format);
+%                 tmp(i,:,b)=t;       
+%             end
+%         end
+      
+%% New Subsetting script - IMH
+        for i=1:sub(4) 
+            for b=1:info.bands
+                t=fread(fid,info.samples,format);
+                if i >=  sub(3) && i <= sub(4) 
+                    tmp(i-sub(3)+1,:,b)=t(sub(1):sub(2));    
+                end
+            end
+        end
+
+
+
+    case {'bip'}
+    
+        % Row 1
+        % C1: B1 B2 B3, ...
+        % C2: B1 B2 B3, ...
+        % ...
+        % Row N
+        %This section authored by Ray Jung, APL-Johns Hopkins
+        Z = fread(fid,info.samples*info.lines*info.bands,format,0,machine);  
+        Z = reshape(Z, [info.bands, info.samples, info.lines]);
+
+        for k=1:info.bands
+            tmp(:,:,k) = squeeze(Z(k,:,:))';
+        end     
+end
+fclose(fid);
+
+% tmp2=zeros(subE(4)-subE(3)+1,subE(2)-subE(1)+1,info.bands,format);
+% [a,b]=size(tmp);
+% for i=1:info.bands
+%     tmp2(xoff+1:a,yoff+1:b,1)=tmp(1:a,1:b,1);
+% end
+I.z=tmp;
+I.info =info;
+
+
+
+%% sub function
+function info = read_envihdr(hdrfile)
+% READ_ENVIHDR read and return ENVI image file header information.
+%   INFO = READ_ENVIHDR('HDR_FILE') reads the ASCII ENVI-generated image
+%   header file and returns all the information in a structure of
+%   parameters.
+%
+%   Example:
+%   >> info = read_envihdr('my_envi_image.hdr')
+%   info =
+%          description: [1x101 char]
+%              samples: 658
+%                lines: 749
+%                bands: 3
+%        header_offset: 0
+%            file_type: 'ENVI Standard'
+%            data_type: 4
+%           interleave: 'bsq'
+%          sensor_type: 'Unknown'
+%           byte_order: 0
+%             map_info: [1x1 struct]
+%      projection_info: [1x102 char]
+%     wavelength_units: 'Unknown'
+%           pixel_size: [1x1 struct]
+%           band_names: [1x154 char]
+%
+%   NOTE: This function is used by ENVIREAD to import data.
+% Ian M. Howat, Applied Physics Lab, University of Washington
+% ihowat@apl.washington.edu
+% Version 1: 19-Jul-2007 00:50:57
+fid = fopen(hdrfile);
+while fid;
+    line = fgetl(fid);
+    if line == -1
+        break
+    else
+        eqsn = findstr(line,'=');
+        if ~isempty(eqsn)
+            param = strtrim(line(1:eqsn-1));
+            param(findstr(param,' ')) = '_';
+            value = strtrim(line(eqsn+1:end));
+            if isempty(str2num(value))
+                if ~isempty(findstr(value,'{')) && isempty(findstr(value,'}'))
+                    while isempty(findstr(value,'}'))
+                        line = fgetl(fid);
+                        value = [value,strtrim(line)];
+                    end
+                end
+                eval(['info.',param,' = ''',value,''';'])
+            else
+                eval(['info.',param,' = ',value,';'])
+            end
+        end
+    end
+end
+fclose(fid);
+
+if isfield(info,'map_info')
+    line = info.map_info;
+    line(line == '{' | line == '}') = [];
+    line = strtrim(split(line,','));
+    info.map_info = [];
+    info.map_info.projection = line{1};
+    info.map_info.image_coords = [str2num(line{2}),str2num(line{3})];
+    info.map_info.mapx = str2num(line{4});
+    info.map_info.mapy = str2num(line{5});
+    info.map_info.dx  = str2num(line{6});
+    info.map_info.dy  = str2num(line{7});
+    if length(line) == 9
+        info.map_info.datum  = line{8};
+        info.map_info.units  = line{9}(7:end);
+    elseif length(line) == 11
+        info.map_info.zone  = str2num(line{8});
+        info.map_info.hemi  = line{9};
+        info.map_info.datum  = line{10};
+        info.map_info.units  = line{11}(7:end);
+    end
+end
+
+if isfield(info,'pixel_size')
+    line = info.pixel_size;
+    line(line == '{' | line == '}') = [];
+    line = strtrim(split(line,','));
+    info.pixel_size = [];
+    info.pixel_size.x = str2num(line{1});
+    info.pixel_size.y = str2num(line{2});
+    info.pixel_size.units = line{3}(7:end);
+end
+
+%%
+function A = split(s,d)
+%This function by Gerald Dalley (dalleyg@mit.edu), 2004
+A = {};
+while (length(s) > 0)
+    [t,s] = strtok(s,d);
+    A = {A{:}, t};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/subsetGimpIceMask.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/subsetGimpIceMask.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/howatmask/subsetGimpIceMask.m	(revision 18231)
@@ -0,0 +1,282 @@
+function [M,Mx,My] = subsetGimpIceMask(x0,x1,y0,y1)
+% subsetGimpIceMask samples mask tiles for a given coordinate range
+%
+%   [M,Mx,My] = subsetGimpIceMask(x0,x1,y0,y1) returns the mask in array M
+%   with map vectors Mx and My within the bounding box specified by
+%   coordinate ranges x0 < x1 and y0 < y1. The function finds tiles
+%   overlappimg the box, samples the tiles and mosaics the samples into one
+%   array.
+%
+% 	Example: Specify the following coordinate range and map the result.
+%   >> x0 = 260000; x1 = 377900;  y0 = -2609400; y1 = -2543000;
+%   >> [M,Mx,My] = subsetGimpIceMask(x0,x1,y0,y1);
+%   >> imagesc(Mx,My,M); axis equal xy; colormap gray;
+%
+%   Ian Howat, Ohio State University, ihowat@gmail.com
+%   The Greenland Ice Mapping Project is funded by NASA.
+%   $Revision: 0 $  $Date: 09-Nov-2011 14:48:24$
+%
+
+%make coordinate index
+nt = 6;
+ps = 15;
+xn0 = -640000 ; %xn1 = 857550;
+yn0 =  -3313350; %yn1 = -665450;
+
+c = 16640;
+r = 29420;
+
+x = xn0:ps:xn0 + c.*ps.*nt;
+y = yn0:ps:yn0 + r.*ps.*nt;
+
+X = cell(1,nt);
+Y = cell(nt,1);
+i=1;
+for i=1:nt;
+    
+    X{i} = [x((i-1)*c+1),x(i*c)];
+    Y{i} = [y((i-1)*r+1),y(i*r)];
+    
+end
+
+X = repmat(X,[nt,1]);
+Y = repmat(Y,[1,nt]);
+N = cell(size(X));
+
+
+i=1;
+for i=1:numel(X)
+    N{i} = [[X{i}(1),Y{i}(2)];...
+        [X{i}(2),Y{i}(2)];...
+        [X{i}(2),Y{i}(1)];...
+        [X{i}(1),Y{i}(1)]];
+end
+
+
+%% find overlapping tiles
+p = [[x0,y1];[x1,y1];[x1,y0];[x0,y0]];
+
+n = zeros(size(N));
+
+i=1;
+for i=1:numel(N)
+    n(i) = any(inpolygon(p(:,1),p(:,2),N{i}(:,1),N{i}(:,2)));
+end
+i=1;
+for i=1:size(n,1)
+    n(i,find(n(i,:),1,'first'):find(n(i,:),1,'last')) = 1;
+end
+i=1;
+for i=1:size(n,2)
+    n(find(n(:,i),1,'first'):find(n(:,i),1,'last'),i) = 1;
+end
+
+[i,j] = find(n);
+row = (min(i):max(i))';
+col = min(j):max(j);
+col = repmat(col,[length(row),1])-1;
+row = repmat(row,[1,size(col,2)])-1;
+
+% make output cells
+M = cell(size(row));
+Mx = M;
+My = M;
+
+% read each overlapping file and populate output cell
+j=1;
+for j=1:size(col,2)
+    i=1;
+    for i=1:size(row,1);
+        m = enviread(['GimpIceMask_15m_tile',num2str(col(i,j)),'_',...
+            num2str(row(i,j))],'map_subset',[x0 x1 y0 y1]);
+        M{end-i+1,j} = m.z;
+        Mx{end-i+1,j} = m.x;
+        My{end-i+1,j} = m.y';
+        
+        
+    end
+end
+
+% put together cells
+M = cell2mat(M);
+Mx =cell2mat(Mx(1,:));
+My =cell2mat(My(:,1));
+
+
+function I=enviread(varargin)
+
+file=varargin{1};
+hdrfile=[deblank(file),'.hdr'];
+info=read_envihdr(hdrfile);
+sub = [1, info.samples, 1, info.lines];
+
+sub = varargin{3};
+subx = (sub(1:2)-info.map_info.mapx)./info.map_info.dx;
+suby = (info.map_info.mapy - sub(3:4))./info.map_info.dy;
+subx = round(subx);
+suby = round(suby);
+
+subx(subx < 1) = 1;
+suby(suby < 1) = 1;
+subx(subx > info.samples) = info.samples;
+suby(suby > info.lines)   = info.lines;
+
+sub  = [subx,suby];
+
+sub(1:2) = sort(sub(1:2));
+sub(3:4) = sort(sub(3:4));
+
+%% Make geo-location vectors
+if isfield(info.map_info,'mapx') && isfield(info.map_info,'mapy')
+    xi = info.map_info.image_coords(1);
+    yi = info.map_info.image_coords(2);
+    xm = info.map_info.mapx;
+    ym = info.map_info.mapy;
+    %adjust points to corner (1.5,1.5)
+    if yi > 1.5
+        ym =  ym + ((yi*info.map_info.dy)-info.map_info.dy);
+    end
+    if xi > 1.5
+        xm = xm - ((xi*info.map_info.dy)-info.map_info.dx);
+    end
+    
+    I.x = xm + ((0:info.samples-1).*info.map_info.dx);
+    I.y = ym - ((0:info.lines-1).*  info.map_info.dy);
+    
+end
+
+I.x = I.x(sub(1):sub(2));
+I.y = I.y(sub(3):sub(4));
+
+%% Set binary format parameters
+switch info.byte_order
+    case {0}
+        machine = 'ieee-le';
+    case {1}
+        machine = 'ieee-be';
+    otherwise
+        machine = 'n';
+end
+
+format = 'uint8';
+
+tmp=zeros(sub(4)-sub(3)+1,sub(2)-sub(1)+1,info.bands,format);
+fid=fopen(file,'r');
+
+offset1=(sub(3)-1)*info.samples;
+fseek(fid,offset1,'bof');
+for b=1:info.bands
+    for i=sub(3):sub(4)
+        t=fread(fid,info.samples,format);
+        tmp(i-sub(3)+1,:,b)=t(sub(1):sub(2));
+    end
+    offset2 = info.samples*info.lines*b+offset1;
+    fseek(fid,offset2,'bof');
+end
+
+fclose(fid);
+
+I.z=tmp;
+I.info =info;
+
+%% sub function
+function info = read_envihdr(hdrfile)
+% READ_ENVIHDR read and return ENVI image file header information.
+%   INFO = READ_ENVIHDR('HDR_FILE') reads the ASCII ENVI-generated image
+%   header file and returns all the information in a structure of
+%   parameters.
+%
+%   Example:
+%   >> info = read_envihdr('my_envi_image.hdr')
+%   info =
+%          description: [1x101 char]
+%              samples: 658
+%                lines: 749
+%                bands: 3
+%        header_offset: 0
+%            file_type: 'ENVI Standard'
+%            data_type: 4
+%           interleave: 'bsq'
+%          sensor_type: 'Unknown'
+%           byte_order: 0
+%             map_info: [1x1 struct]
+%      projection_info: [1x102 char]
+%     wavelength_units: 'Unknown'
+%           pixel_size: [1x1 struct]
+%           band_names: [1x154 char]
+%
+%   NOTE: This function is used by ENVIREAD to import data.
+% Ian M. Howat, Applied Physics Lab, University of Washington
+% ihowat@apl.washington.edu
+% Version 1: 19-Jul-2007 00:50:57
+fid = fopen(hdrfile);
+while fid;
+    line = fgetl(fid);
+    if line == -1
+        break
+    else
+        eqsn = findstr(line,'=');
+        if ~isempty(eqsn)
+            param = strtrim(line(1:eqsn-1));
+            param(findstr(param,' ')) = '_';
+            value = strtrim(line(eqsn+1:end));
+            if isempty(str2num(value))
+                if ~isempty(findstr(value,'{')) && isempty(findstr(value,'}'))
+                    while isempty(findstr(value,'}'))
+                        line = fgetl(fid);
+                        value = [value,strtrim(line)];
+                    end
+                end
+                eval(['info.',param,' = ''',value,''';'])
+            else
+                eval(['info.',param,' = ',value,';'])
+            end
+        end
+    end
+end
+fclose(fid);
+
+if isfield(info,'map_info')
+    line = info.map_info;
+    line(line == '{' | line == '}') = [];
+    line = strtrim(split(line,','));
+    info.map_info = [];
+    info.map_info.projection = line{1};
+    info.map_info.image_coords = [str2num(line{2}),str2num(line{3})];
+    info.map_info.mapx = str2num(line{4});
+    info.map_info.mapy = str2num(line{5});
+    info.map_info.dx  = str2num(line{6});
+    info.map_info.dy  = str2num(line{7});
+    if length(line) == 9
+        info.map_info.datum  = line{8};
+        info.map_info.units  = line{9}(7:end);
+    elseif length(line) == 11
+        info.map_info.zone  = str2num(line{8});
+        info.map_info.hemi  = line{9};
+        info.map_info.datum  = line{10};
+        info.map_info.units  = line{11}(7:end);
+    end
+end
+
+if isfield(info,'pixel_size')
+    line = info.pixel_size;
+    line(line == '{' | line == '}') = [];
+    line = strtrim(split(line,','));
+    info.pixel_size = [];
+    info.pixel_size.x = str2num(line{1});
+    info.pixel_size.y = str2num(line{2});
+    info.pixel_size.units = line{3}(7:end);
+end
+
+%%
+function A = split(s,d)
+%This function by Gerald Dalley (dalleyg@mit.edu), 2004
+A = {};
+while (length(s) > 0)
+    [t,s] = strtok(s,d);
+    A = {A{:}, t};
+end
+
+
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/install.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+#inishell install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a inishell-src-*.tgz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls inishell-src-*.tgz`
+source_version=`echo $source_tar | sed 's/inishell-src-//g' | sed 's/.tgz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be inishell-src-*.tgz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+
+#Some cleanup
+rm -rf src install inishell-$source_version
+mkdir install
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv inishell-$source_version src
+rm -rf inishell-$source_version
+
+#Build inishell
+cd src && ant snowpack
+
+#Put the .jar in the install directory
+cp dist/inishell.jar ../install
+
+#Install script to launch inishell jar file directly
+cd ..
+cp scripts/inishell install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/scripts/inishell
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/scripts/inishell	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/inishell/scripts/inishell	(revision 18231)
@@ -0,0 +1,3 @@
+#/bin/bash
+
+java -jar $ISSM_DIR/externalpackages/inishell/install/inishell.jar
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ipython/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ipython/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ipython/install.sh	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/bash
+set -eu 
+
+#Some cleanup
+rm -rf src
+rm -rf ipython-1.0.0
+mkdir src 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ipython-1.0.0.tar.gz' 'ipython-1.0.0.tar.gz'
+
+#Untar 
+tar -zxvf  ipython-1.0.0.tar.gz
+
+#Move ipython into src directory
+mv ipython-1.0.0/* src
+rm -rf ipython-1.0.0
+
+#install  ipython
+cd src
+python setup.py build
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/kml/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/kml/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/kml/install.sh	(revision 18231)
@@ -0,0 +1,5 @@
+#!/bin/bash
+set -eu
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/kml_shapefile.zip' 'kml_shapefile.zip'
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/linux64/make.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/linux64/make.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/linux64/make.inc	(revision 18231)
@@ -0,0 +1,71 @@
+####################################################################
+#  LAPACK make include file.                                       #
+#  LAPACK, Version 3.4.0                                           #
+#  April 2012                                                   #
+####################################################################
+#
+SHELL = /bin/sh
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran 
+OPTS     = -fPIC -O2
+DRVOPTS  = $(OPTS)
+NOOPT    = -fPIC -O0
+LOADER   = gfortran
+LOADOPTS =
+#
+# Timer for the SECOND and DSECND routines
+#
+# Default : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME
+#TIMER    = EXT_ETIME
+# For RS6K : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME_
+# TIMER    = EXT_ETIME_
+# For gfortran compiler: SECOND and DSECND will use a call to the INTERNAL FUNCTION ETIME
+TIMER    = INT_ETIME
+# If your Fortran compiler does not provide etime (like Nag Fortran Compiler, etc...)
+# SECOND and DSECND will use a call to the INTERNAL FUNCTION CPU_TIME
+# TIMER    = INT_CPU_TIME
+# If neither of this works...you can use the NONE value... In that case, SECOND and DSECND will always return 0
+# TIMER     = NONE
+#
+#  Configuration LAPACKE: Native C interface to LAPACK
+#  To generate LAPACKE library: type 'make lapackelib'
+#  Configuration file: turned off (default)
+#  Complex types: C99 (default)
+#  Name pattern: mixed case (default)
+#  (64-bit) Data model: LP64 (default)
+#
+# CC is the C compiler, normally invoked with options CFLAGS.
+#
+CC = gcc
+CFLAGS = -O3
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  Location of the extended-precision BLAS (XBLAS) Fortran library
+#  used for building and testing extended-precision routines.  The
+#  relevant routines will be compiled and XBLAS will be linked only if
+#  USEXBLAS is defined.
+#
+# USEXBLAS    = Yes
+XBLASLIB     =
+# XBLASLIB    = -lxblas
+#
+#  The location of the libraries to which you will link.  (The 
+#  machine-specific, optimized BLAS library should be used whenever
+#  possible.)
+#
+BLASLIB      = ../../librefblas.a
+LAPACKLIB    = liblapack.a
+TMGLIB       = libtmglib.a
+LAPACKELIB   = liblapacke.a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/macosx64/make.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/macosx64/make.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/configs/macosx64/make.inc	(revision 18231)
@@ -0,0 +1,71 @@
+####################################################################
+#  LAPACK make include file.                                       #
+#  LAPACK, Version 3.4.0                                           #
+#  April 2012                                                   #
+####################################################################
+#
+SHELL = /bin/sh
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran 
+OPTS     = -fPIC -O2
+DRVOPTS  = $(OPTS)
+NOOPT    = -fPIC -O0
+LOADER   = gfortran
+LOADOPTS =
+#
+# Timer for the SECOND and DSECND routines
+#
+# Default : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME
+#TIMER    = EXT_ETIME
+# For RS6K : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME_
+# TIMER    = EXT_ETIME_
+# For gfortran compiler: SECOND and DSECND will use a call to the INTERNAL FUNCTION ETIME
+TIMER    = INT_ETIME
+# If your Fortran compiler does not provide etime (like Nag Fortran Compiler, etc...)
+# SECOND and DSECND will use a call to the INTERNAL FUNCTION CPU_TIME
+# TIMER    = INT_CPU_TIME
+# If neither of this works...you can use the NONE value... In that case, SECOND and DSECND will always return 0
+# TIMER     = NONE
+#
+#  Configuration LAPACKE: Native C interface to LAPACK
+#  To generate LAPACKE library: type 'make lapackelib'
+#  Configuration file: turned off (default)
+#  Complex types: C99 (default)
+#  Name pattern: mixed case (default)
+#  (64-bit) Data model: LP64 (default)
+#
+# CC is the C compiler, normally invoked with options CFLAGS.
+#
+CC = gcc
+CFLAGS = -O3
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  Location of the extended-precision BLAS (XBLAS) Fortran library
+#  used for building and testing extended-precision routines.  The
+#  relevant routines will be compiled and XBLAS will be linked only if
+#  USEXBLAS is defined.
+#
+# USEXBLAS    = Yes
+XBLASLIB     =
+# XBLASLIB    = -lxblas
+#
+#  The location of the libraries to which you will link.  (The 
+#  machine-specific, optimized BLAS library should be used whenever
+#  possible.)
+#
+BLASLIB      = ../../librefblas.a
+LAPACKLIB    = liblapack.a
+TMGLIB       = libtmglib.a
+LAPACKELIB   = liblapacke.a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-linux64.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install lapack-3.4.1 lapack-3.4.1.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/lapack-3.4.1.tgz' 'lapack-3.4.1.tgz'
+
+#Untar 
+tar -zxvf  lapack-3.4.1.tgz
+
+#Move lapack into install directory
+mv lapack-3.4.1/* src
+rm -rf lapack-3.4.1
+
+#install
+cd src 
+cp ../configs/linux64/make.inc ./
+
+#Compile and install lapack
+if [ $# -eq 0 ]; then
+	make lib
+else
+	make -j $1 lib
+fi
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/liblapack.a .
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/lapack/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install lapack-3.4.1 lapack-3.4.1.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/lapack-3.4.1.tgz' 'lapack-3.4.1.tgz'
+
+#Untar 
+tar -zxvf  lapack-3.4.1.tgz
+
+#Move lapack into install directory
+mv lapack-3.4.1/* src
+rm -rf lapack-3.4.1
+
+#install
+cd src 
+cp ../configs/macosx64/make.inc ./
+
+#Compile and install lapack
+if [ $# -eq 0 ]; then
+	make lib
+else
+	make -j $1 lib
+fi
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/liblapack.a .
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/latex2rtf/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/latex2rtf/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/latex2rtf/install.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf latex2rtf-2.0.0 cfg install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/latex2rtf-2.0.0.tar.gz' 'latex2rtf-2.0.0.tar.gz'
+
+#untar 
+tar -zxvf  latex2rtf-2.0.0.tar.gz
+mv latex2rtf-2.0.0 install
+
+#Compile
+cd install
+export PREFIX="$ISSM_DIR/externalpackages/latex2rtf/install/"
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libermate/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libermate/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libermate/install.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+rm -rf libermate-0.4
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libermate-0.4.tgz' 'libermate-0.4.tgz'
+
+#Untar 
+tar -zxvf  libermate-0.4.tgz
+
+#Move libermate into install directory
+mv libermate-0.4/* install
+rm -rf libermate-0.4
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libpng/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libpng/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/libpng/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf libpng-1.5.10
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libpng-1.5.10.tar.gz' 'libpng-1.5.10.tar.gz'
+
+#Untar 
+tar -zxvf  libpng-1.5.10.tar.gz
+
+#Move libpng into src directory
+mv libpng-1.5.10/* src
+rm -rf libpng-1.5.10
+
+#Configure libpng
+cd src
+sudo ./configure 
+
+#Compile and install libpng
+if [ $# -eq 0 ]; then
+	sudo make
+else
+	sudo make -j $1
+fi
+sudo make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m1qn3/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m1qn3/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m1qn3/install.sh	(revision 18231)
@@ -0,0 +1,59 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install src m1qn3-3.3-distrib
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/m1qn3-3.3-distrib.tgz' 'm1qn3-3.3-distrib.tgz'
+
+#Untar 
+tar -xzf m1qn3-3.3-distrib.tgz
+mv m1qn3-3.3-distrib src
+
+if which ifort >/dev/null; then
+	FC="ifort"
+else
+	FC="gfortran"
+fi
+
+#Compile m1qn3
+cd src/src/
+(
+cat << EOF
+LIB_EXT=a
+FC=$FC
+install: libm1qn3.\$(LIB_EXT)
+	cp libm1qn3.\$(LIB_EXT) ../../install/
+OBJECTS= m1qn3.o
+libm1qn3.\$(LIB_EXT): \$(OBJECTS)
+	ar -r libm1qn3.\$(LIB_EXT) \$(OBJECTS) 
+	ranlib libm1qn3.\$(LIB_EXT) 
+%.o: %.f
+	\$(FC) \$(FFLAGS) -c $< -o \$@
+clean: 
+	rm -rf *.o *.\$(LIB_EXT)
+EOF
+) > Makefile
+make
+
+#compile ddot
+cd ../blas
+(
+cat << EOF
+LIB_EXT=a
+FC=$FC
+install: libddot.\$(LIB_EXT)
+	cp libddot.\$(LIB_EXT) ../../install/
+OBJECTS= ddot.o
+libddot.\$(LIB_EXT): \$(OBJECTS)
+	ar -r libddot.\$(LIB_EXT) \$(OBJECTS) 
+	ranlib libddot.\$(LIB_EXT) 
+%.o: %.f
+	\$(FC) \$(FFLAGS) -c $< -o \$@
+clean: 
+	rm -rf *.o *.\$(LIB_EXT)
+EOF
+) > Makefile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install m2html
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/m2html.zip' 'm2html.zip'
+
+#uncompress
+unzip m2html.zip
+
+#move to install directory
+mv m2html/* install
+rm -rf m2html
+
+#patch m2html
+cd install
+patch m2html.m ../m2html.m.patch
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/m2html.m.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/m2html.m.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/m2html/m2html.m.patch	(revision 18231)
@@ -0,0 +1,114 @@
+*** m2html.m	2011-08-12 10:57:45.000000000 -0700
+--- install/m2html.m	2011-08-12 10:58:26.000000000 -0700
+***************
+*** 306,311 ****
+--- 306,325 ----
+  	end
+  
+  	mdir = unique(mdirs);
++ 
++ 	%add root directories
++ 	for i=1:length(mdir)
++ 		path=strsplit(mdir{i},'/');
++ 		string=path{1};
++ 		mdir{end+1}=string;
++ 		for j=2:length(path),
++ 			string=[string '/' path{j}];
++ 			mdir{end+1}=string;
++ 		end
++ 	end
++ 
++ 	mdir=unique(mdir);
++ 
+  	if options.verbose,
+  		fprintf('Found %d unique Matlab directories.\n',length(mdir));
+  	end
+***************
+*** 423,429 ****
+  %- Set some template variables
+  tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
+  							datestr(now,13)]);
+! tpl = set(tpl,'var','MASTERPATH',       './');
+  tpl = set(tpl,'var','DIRS',    sprintf('%s ',mdir{:}));
+  
+  %- Print list of unique directories
+--- 437,443 ----
+  %- Set some template variables
+  tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
+  							datestr(now,13)]);
+! tpl = set(tpl,'var','MASTERPATH',       '');
+  tpl = set(tpl,'var','DIRS',    sprintf('%s ',mdir{:}));
+  
+  %- Print list of unique directories
+***************
+*** 555,561 ****
+  	tpl = set(tpl,'var','subfold','');
+  	d = dir(mdir{i});
+  	d = {d([d.isdir]).name};
+! 	d = {d{~ismember(d,{'.' '..'})}};
+  	for j=1:length(d)
+  		if ismember(fullfile(mdir{i},d{j}),mdir)
+  			tpl = set(tpl,'var','SUBDIRECTORY',...
+--- 569,575 ----
+  	tpl = set(tpl,'var','subfold','');
+  	d = dir(mdir{i});
+  	d = {d([d.isdir]).name};
+! 	d = {d{~ismember(d,{'.' '..' 'CVS' '.svn'})}};
+  	for j=1:length(d)
+  		if ismember(fullfile(mdir{i},d{j}),mdir)
+  			tpl = set(tpl,'var','SUBDIRECTORY',...
+***************
+*** 687,695 ****
+  % Path should look like:  ...;C:\WINNT\System32;...;C:\GraphViz\bin
+  % (Note that this should have been done automatically during GraphViz installation)
+  
+! 			eval(['!' dot_exec ' -Tcmap -Tpng ' mdotfile ...
+  				' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.map']) ... 
+! 				' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.png'])])
+  			% use '!' rather than 'system' for backward compability
+  		catch
+  			fprintf('failed.');
+--- 701,709 ----
+  % Path should look like:  ...;C:\WINNT\System32;...;C:\GraphViz\bin
+  % (Note that this should have been done automatically during GraphViz installation)
+  
+! 			eval(['!' dot_exec ' -Tcmap -Tgif ' mdotfile ...
+  				' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.map']) ... 
+! 				' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.gif'])])
+  			% use '!' rather than 'system' for backward compability
+  		catch
+  			fprintf('failed.');
+***************
+*** 700,706 ****
+  		tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
+  		tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
+  		tpl = set(tpl,'var','MDIR',       mdir{i});
+! 		tpl = set(tpl,'var','GRAPH_IMG',  [dotbase '.png']);
+  		fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r');
+  		tpl = set(tpl,'var','GRAPH_MAP',  fscanf(fmap,'%c'));
+  		fclose(fmap);
+--- 714,720 ----
+  		tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
+  		tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
+  		tpl = set(tpl,'var','MDIR',       mdir{i});
+! 		tpl = set(tpl,'var','GRAPH_IMG',  [dotbase '.gif']);
+  		fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r');
+  		tpl = set(tpl,'var','GRAPH_MAP',  fscanf(fmap,'%c'));
+  		fclose(fmap);
+***************
+*** 1032,1038 ****
+  			if recursive
+  				d = dir(mdirs{i});
+  				d = {d([d.isdir]).name};
+! 				d = {d{~ismember(d,{'.' '..'})}};
+  				for j=1:length(d)
+  					mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})),...
+  									   mfiles,recursive);
+--- 1046,1052 ----
+  			if recursive
+  				d = dir(mdirs{i});
+  				d = {d([d.isdir]).name};
+! 				d = {d{~ismember(d,{'.' '..' 'CVS' '.svn'})}};
+  				for j=1:length(d)
+  					mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})),...
+  									   mfiles,recursive);
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/math77/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/math77/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/math77/install.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install math77
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/math77.tar.gz' 'math77.tar.gz'
+
+#Untar 
+tar -zxvf  math77.tar.gz
+
+#Move math77 into src directory
+mv math77/* src
+rm -rf math77
+
+#Configure math77
+cd src
+
+#Compile math77
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matlab/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matlab/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matlab/install.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+if [ ! -h install ];
+then
+	echo "  ****************************************************************"
+	echo "  *                                                              *"
+	echo "  * you need create a symbolic link from matlab's root directory *"
+	echo "  *                                                              *"
+	echo "  * First, you need to locate matlab's root directory            *"
+	echo "  * The easiest way to find it is to launch matlab and run the   *"
+	echo "  * following command: matlabroot                                *"
+	echo "  * Then, create a symbolic link using the command 'ln -s ' the  *"
+	echo "  * target directory should be named 'install'                   *"
+	echo "  *                                                              *"
+	echo "  * Examples:                                                    *"
+	echo "  *    ln -s /usr/local/matlab712/ install                       *"
+	echo "  *    ln -s /Applications/MATLAB_R2012a.app/ install            *"
+	echo "  *                                                              *"
+	echo "  * run ./install.sh again to check that the link is correct     *"
+	echo "  *                                                              *"
+	echo "  ****************************************************************"
+else
+
+	#Read link
+	DIR=$(readlink install)
+	if [ -d $DIR ]
+	then
+		echo "Symbolic link correctly set"
+	else
+		rm -rf install
+		echo "Incorrect symbolic link:"
+		echo "provided target ($DIR) does not exist or is not a directory"
+	fi
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-linux64.sh	(revision 18231)
@@ -0,0 +1,14 @@
+#/bin/bash
+set -eu
+export GIT_SSL_NO_VERIFY=true 
+export CC="gcc -fPIC "
+export CXX="g++ -fPIC -L$ISSM_DIR/externalpackages/tcl/install/lib"
+export F77="gfortran -fPIC"
+export FC="gfortran -fPIC"
+export FFLAGS=-ff2c
+
+git clone https://github.com/matplotlib/matplotlib
+mv matplotlib src
+cd src
+python setup.py build 
+python setup.py install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/matplotlib/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#/bin/bash
+set -eu
+
+rm -rf src deps 
+
+export C_INCLUDE_PATH="$C_INCLUDE_PATH:/usr/include/c++/4.2.1"
+export GIT_SSL_NO_VERIFY=true 
+export CC="gcc -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export CXX="g++ -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export F77="gfortran -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export FC="gfortran -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export FFLAGS="-ff2c -arch x86_64 -I/usr/include/c++/4.2.1"
+export ARCHFLAGS="-arch x86_64 -I/usr/include/c++/4.2.1"
+
+git clone https://github.com/matplotlib/matplotlib
+mv matplotlib src
+mkdir deps
+cd src
+
+#only try this if the classic python setup.py build approach does not work. The approach in the next 3 lines can 
+#trigger issues of permissions with freetype. Sometimes it is better to independently install freetype2 (from the 
+#issm externalpackages) as sudo (or root), so that the python script can detect its existence automatically.
+#sudo make -f make.osx PREFIX=$ISSM_DIR/externalpackages/matplotlib/deps PYVERSION=$pythonversion fetch deps mpl_install_std
+#sudo make -f make.osx PREFIX=$ISSM_DIR/externalpackages/matplotlib/deps PYVERSION=$pythonversion mpl_install_std
+#python -c "import matplotlib; print 'Installed matplotlib', matplotlib.__version__, matplotlib.__file__"
+
+#comments: try exporting this first before calling python setup.py build
+CFLAGS=-mmacosx-version-min=10.7 
+
+#to be tried:  first get freetype and zlib and libpng installed in sudo mode
+python setup.py build
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mercurial/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mercurial/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mercurial/install.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install mercurial-1.7.3
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mercurial-1.7.3.tar.gz' 'mercurial-1.7.3.tar.gz'
+
+#Untar 
+tar -zxvf  mercurial-1.7.3.tar.gz
+
+#Move mercurial into install directory
+mv mercurial-1.7.3/* install
+rm -rf mercurial-1.7.3
+
+#Apply patches
+cd install 
+#patch Lib/Makefile ../lib_Makefile.patch
+exit
+
+#Compile mercurial
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/meteoio/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/meteoio/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/meteoio/install.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+#METEOIO install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a MeteoIO-*-tar.gz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls MeteoIO-*.tar.gz`
+source_version=`echo $source_tar | sed 's/MeteoIO-//g' | sed 's/.tar.gz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be MeteoIO-*-tar.gz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+#Some cleanup
+rm -rf src install MeteoIO-$source_version
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv MeteoIO-$source_version/usr src
+rm -rf MeteoIO-$source_version
+
+#Reset makefile: 
+cd src && rm -rf CMakeCache.txt 
+cmake -DCMAKE_INSTALL_PREFIX:PATH=$ISSM_DIR/externalpackages/meteoio/install .
+
+#Compile 
+if [ $# -eq 0 ]; then
+	make all install
+else
+	make -j $1 all install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = gcc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/discover/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/discover/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/discover/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/greenplanet/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/greenplanet/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/greenplanet/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = gcc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = gcc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -O2  -m32
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = gcc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -O2  -m64
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win32/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win32/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win32/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icl
+> OBJ_EXT=obj
+> LIB_EXT=lib
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DWIN32 -D__VC__
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.in.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.in.patch	(revision 18231)
@@ -0,0 +1,21 @@
+3c3,5
+< CC = cc
+---
+> CC = cl
+> OBJ_EXT=obj
+> LIB_EXT=lib
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DWIN32 -D__VC__
+14,20c16,17
+< # What archiving to use
+< AR = ar rv
+< 
+< # What to use for indexing the archive
+< RANLIB = ranlib
+< #RANLIB = ar -ts
+< #RANLIB = 
+---
+> # What tool to use to create library
+> LIB=lib.exe
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/configs/4.0/win7/Makefile.patch	(revision 18231)
@@ -0,0 +1,5 @@
+24c24,25
+< 	$(LIB) -out:$@ $(OBJS)
+---
+> 	$(AR) $@ $(OBJS)
+> 	$(RANLIB) $@
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-altix64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-altix64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-altix64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/altix64/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-cosmos.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-cosmos.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-cosmos.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/cosmos/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-discover.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/discover/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-greenplanet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-greenplanet.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/greenplanet/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-hoffman2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-hoffman2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-hoffman2.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/pleiades/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-linux64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/linux64/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx32.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/macosx32/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-macosx64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/macosx64/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-pleiades.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/pleiades/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win32.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/win32/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-4.0-win7.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch -R Lib/Makefile ../configs/4.0/win7/Makefile.patch
+patch Makefile.in ../configs/4.0/win7/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-5.0.1-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-5.0.1-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/install-5.0.1-linux64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#metis 5.0 should be used: srand48 and drand48 are being redefined in conflict to the stdlib equivalent functions.
+
+#Some cleanup
+rm -rf install metis-5.0.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-5.0.1.tar.gz' 'metis-5.0.1.tar.gz'
+
+#Untar 
+tar -zxvf  metis-5.0.1.tar.gz
+
+#Move metis into install directory
+mv metis-5.0.1/* install
+rm -rf metis-5.0.1
+
+#Apply patches
+cd install 
+
+#Compile metis
+make config prefix="$ISSM_DIR/externalpackages/metis/install"
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/metis-4.0.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/metis-4.0.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/metis/metis-4.0.patch	(revision 18231)
@@ -0,0 +1,237 @@
+diff -crB install/Lib/kmetis.c install2/Lib/kmetis.c
+*** install/Lib/kmetis.c	1998-11-30 08:26:47.000000000 -0800
+--- install2/Lib/kmetis.c	2011-06-08 15:47:33.911358942 -0700
+***************
+*** 66,72 ****
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(40*log2(*nparts)), 20*(*nparts));
+    ctrl.maxvwgt = 1.5*((graph.vwgt ? idxsum(*nvtxs, graph.vwgt) : (*nvtxs))/ctrl.CoarsenTo);
+  
+    InitRandom(-1);
+--- 66,72 ----
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(40*log2_function(*nparts)), 20*(*nparts));
+    ctrl.maxvwgt = 1.5*((graph.vwgt ? idxsum(*nvtxs, graph.vwgt) : (*nvtxs))/ctrl.CoarsenTo);
+  
+    InitRandom(-1);
+diff -crB install/Lib/kvmetis.c install2/Lib/kvmetis.c
+*** install/Lib/kvmetis.c	1998-11-30 08:26:47.000000000 -0800
+--- install2/Lib/kvmetis.c	2011-06-08 15:47:33.916358976 -0700
+***************
+*** 66,72 ****
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KVMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(40*log2(*nparts)), 20*(*nparts));
+    ctrl.maxvwgt = 1.5*((graph.vwgt ? idxsum(*nvtxs, graph.vwgt) : (*nvtxs))/ctrl.CoarsenTo);
+  
+    InitRandom(-1);
+--- 66,72 ----
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KVMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(40*log2_function(*nparts)), 20*(*nparts));
+    ctrl.maxvwgt = 1.5*((graph.vwgt ? idxsum(*nvtxs, graph.vwgt) : (*nvtxs))/ctrl.CoarsenTo);
+  
+    InitRandom(-1);
+diff -crB install/Lib/Makefile install2/Lib/Makefile
+*** install/Lib/Makefile	1998-09-22 05:08:29.000000000 -0700
+--- install2/Lib/Makefile	2011-06-08 15:19:00.551540482 -0700
+***************
+*** 6,31 ****
+  LD = $(CC) -L. 
+  
+  
+! OBJS = coarsen.o fm.o initpart.o match.o ccgraph.o memory.o \
+!        pmetis.o pqueue.o refine.o util.o timing.o debug.o \
+!        bucketsort.o graph.o stat.o kmetis.o kwayrefine.o \
+!        kwayfm.o balance.o ometis.o srefine.o sfm.o separator.o \
+!        mincover.o mmd.o mesh.o meshpart.o frename.o fortran.o \
+!        myqsort.o compress.o parmetis.o estmem.o \
+!        mpmetis.o mcoarsen.o mmatch.o minitpart.o mbalance.o \
+!        mrefine.o mutil.o mfm.o mkmetis.o mkwayrefine.o mkwayfmh.o \
+!        mrefine2.o minitpart2.o mbalance2.o mfm2.o \
+!        kvmetis.o kwayvolrefine.o kwayvolfm.o subdomains.o
+  
+! .c.o:
+! 	$(CC) $(CFLAGS) -c $*.c
+  
+! ../libmetis.a: $(OBJS)
+  	$(AR) $@ $(OBJS)
+  	$(RANLIB) $@
+  
+  clean:
+! 	rm -f *.o
+  
+  realclean:
+! 	rm -f *.o ; rm -f ../libmetis.a
+--- 6,31 ----
+  LD = $(CC) -L. 
+  
+  
+! OBJS = coarsen.$(OBJ_EXT) fm.$(OBJ_EXT) initpart.$(OBJ_EXT) match.$(OBJ_EXT) ccgraph.$(OBJ_EXT) memory.$(OBJ_EXT) \
+!        pmetis.$(OBJ_EXT) pqueue.$(OBJ_EXT) refine.$(OBJ_EXT) util.$(OBJ_EXT) timing.$(OBJ_EXT) debug.$(OBJ_EXT) \
+!        bucketsort.$(OBJ_EXT) graph.$(OBJ_EXT) stat.$(OBJ_EXT) kmetis.$(OBJ_EXT) kwayrefine.$(OBJ_EXT) \
+!        kwayfm.$(OBJ_EXT) balance.$(OBJ_EXT) ometis.$(OBJ_EXT) srefine.$(OBJ_EXT) sfm.$(OBJ_EXT) separator.$(OBJ_EXT) \
+!        mincover.$(OBJ_EXT) mmd.$(OBJ_EXT) mesh.$(OBJ_EXT) meshpart.$(OBJ_EXT) frename.$(OBJ_EXT) fortran.$(OBJ_EXT) \
+!        myqsort.$(OBJ_EXT) compress.$(OBJ_EXT) parmetis.$(OBJ_EXT) estmem.$(OBJ_EXT) \
+!        mpmetis.$(OBJ_EXT) mcoarsen.$(OBJ_EXT) mmatch.$(OBJ_EXT) minitpart.$(OBJ_EXT) mbalance.$(OBJ_EXT) \
+!        mrefine.$(OBJ_EXT) mutil.$(OBJ_EXT) mfm.$(OBJ_EXT) mkmetis.$(OBJ_EXT) mkwayrefine.$(OBJ_EXT) mkwayfmh.$(OBJ_EXT) \
+!        mrefine2.$(OBJ_EXT) minitpart2.$(OBJ_EXT) mbalance2.$(OBJ_EXT) mfm2.$(OBJ_EXT) \
+!        kvmetis.$(OBJ_EXT) kwayvolrefine.$(OBJ_EXT) kwayvolfm.$(OBJ_EXT) subdomains.$(OBJ_EXT)
+  
+! %.$(OBJ_EXT) : %.c
+! 	$(CC) -c $(CFLAGS) -o $@ $<
+  
+! ../libmetis.$(LIB_EXT): $(OBJS)
+  	$(AR) $@ $(OBJS)
+  	$(RANLIB) $@
+  
+  clean:
+! 	rm -f *.$(OBJ_EXT)
+  
+  realclean:
+! 	rm -f *.$(OBJ_EXT) ; rm -f ../libmetis.$(LIB_EXT)
+diff -crB install/Lib/metis.h install2/Lib/metis.h
+*** install/Lib/metis.h	1998-11-30 08:26:50.000000000 -0800
+--- install2/Lib/metis.h	2011-06-08 15:19:00.544540433 -0700
+***************
+*** 18,24 ****
+--- 18,26 ----
+  #else
+  #include <malloc.h>
+  #endif
++ #ifndef WIN32
+  #include <strings.h>
++ #endif
+  #include <string.h>
+  #include <ctype.h>
+  #include <math.h>
+diff -crB install/Lib/mkmetis.c install2/Lib/mkmetis.c
+*** install/Lib/mkmetis.c	1998-11-30 08:26:48.000000000 -0800
+--- install2/Lib/mkmetis.c	2011-06-08 15:47:33.921359010 -0700
+***************
+*** 47,53 ****
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(20*log2(*nparts)), 30*(*nparts));
+  
+    ctrl.nmaxvwgt = 1.5/(1.0*ctrl.CoarsenTo);
+  
+--- 47,53 ----
+      ctrl.dbglvl = options[OPTION_DBGLVL];
+    }
+    ctrl.optype = OP_KMETIS;
+!   ctrl.CoarsenTo = amax((*nvtxs)/(20*log2_function(*nparts)), 30*(*nparts));
+  
+    ctrl.nmaxvwgt = 1.5/(1.0*ctrl.CoarsenTo);
+  
+diff -crB install/Lib/proto.h install2/Lib/proto.h
+*** install/Lib/proto.h	1998-11-30 08:26:50.000000000 -0800
+--- install2/Lib/proto.h	2011-06-08 15:47:34.009359613 -0700
+***************
+*** 230,237 ****
+--- 230,243 ----
+  void QUADNODALMETIS(int, int, idxtype *, idxtype *, idxtype *adjncy);
+  
+  /* meshpart.c */
++ #ifdef __cplusplus
++ extern "C" {
++ #endif
+  void METIS_PartMeshNodal(int *, int *, idxtype *, int *, int *, int *, int *, idxtype *, idxtype *);
+  void METIS_PartMeshDual(int *, int *, idxtype *, int *, int *, int *, int *, idxtype *, idxtype *);
++ #ifdef __cplusplus
++ }
++ #endif
+  
+  /* mfm.c */
+  void MocFM_2WayEdgeRefine(CtrlType *, GraphType *, float *, int);
+***************
+*** 459,465 ****
+  void srand48(long);
+  int ispow2(int);
+  void InitRandom(int);
+! int log2(int);
+  
+  
+  
+--- 465,471 ----
+  void srand48(long);
+  int ispow2(int);
+  void InitRandom(int);
+! int log2_function(int);
+  
+  
+  
+diff -crB install/Lib/rename.h install2/Lib/rename.h
+*** install/Lib/rename.h	1998-11-30 08:26:50.000000000 -0800
+--- install2/Lib/rename.h	2011-06-08 15:47:34.014359647 -0700
+***************
+*** 410,416 ****
+  #define RandomPermute			__RandomPermute
+  #define ispow2				__ispow2
+  #define InitRandom			__InitRandom
+! #define log2				__log2
+  
+  
+  
+--- 410,417 ----
+  #define RandomPermute			__RandomPermute
+  #define ispow2				__ispow2
+  #define InitRandom			__InitRandom
+! /* Correction bug Nadir SOUALEM*/
+! #define log2_function				__log2_function
+  
+  
+  
+diff -crB install/Lib/util.c install2/Lib/util.c
+*** install/Lib/util.c	1998-11-30 08:26:50.000000000 -0800
+--- install2/Lib/util.c	2011-06-08 15:47:34.018359675 -0700
+***************
+*** 507,515 ****
+  }
+  
+  /*************************************************************************
+! * This function returns the log2(x)
+  **************************************************************************/
+! int log2(int a)
+  {
+    int i;
+  
+--- 507,515 ----
+  }
+  
+  /*************************************************************************
+! * This function returns the log2_function(x)
+  **************************************************************************/
+! int log2_function(int a)
+  {
+    int i;
+  
+diff -crB install/Makefile install2/Makefile
+*** install/Makefile	1998-09-20 11:15:31.000000000 -0700
+--- install2/Makefile	2011-06-08 15:19:00.511540204 -0700
+***************
+*** 2,9 ****
+  
+  default:
+  	(cd Lib ; make ) 
+! 	(cd Programs ; make ) 
+! 	(cd Test ; make ) 
+  
+  clean:
+  	(cd Lib ; make clean )
+--- 2,9 ----
+  
+  default:
+  	(cd Lib ; make ) 
+! #	(cd Programs ; make ) 
+! #	(cd Test ; make ) 
+  
+  clean:
+  	(cd Lib ; make clean )
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/install.sh	(revision 18231)
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -eu
+
+#Do these commands once:
+# cvs -d:pserver:cvsanon@mitgcm.org:/u/gcmpack login
+# ( enter the CVS password: "cvsanon" )
+
+#Some cleanup
+rm -rf install   bin exe
+
+#add cvs repository
+export CVSROOT=':pserver:cvsanon@mitgcm.org:/u/gcmpack'
+
+echo loging into MITgcm cvs: provide password, which is cvsanon
+cvs login
+
+#Download code from server
+cvs login
+cvs co -P MITgcm
+
+#move
+mv MITgcm install
+
+
+#compile code
+cd install
+mkdir bin exe
+cd bin
+../tools/genmake2 -mods=../../code
+make depend
+make -j 8
+
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/notes
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/notes	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/notes	(revision 18231)
@@ -0,0 +1,112 @@
+Explanations of the code:  {{{1
+doc:  call Dimitris.
+
+Main code of MITgcm in 3 dir: 
+
+eesupp:  running the code on parallel  clusters. infrastructure for running MPI, shared memory, non-physics part of the code.
+	src: main.F: eeboo  (wrapper initialization)
+			     check_threads
+			     the_model_main
+			     eedie (wrapper termination)
+	inc
+
+
+model:  here is the model main.
+	src: the_model_main.F includes the base MITgcm code.
+	inc:
+
+pkg: do various physics. packages will not be compiled.
+   kpp: vertical mixing  parametization
+   gmred: isopicnel mixing parameterization. 
+  
+   thice: 
+   seaice: sea ice models
+   
+   shelfice: interacting with ice sheets
+   icefront 
+
+   cal: calendar correspondance between model time step and calendar time.
+
+   diagnostics: any physical variable that you want to look at. get output variables into output of the model.
+
+   debug: other kind of diagnostics, various levels of debug.
+
+   frazil: frazil ice.
+
+   atmospherics packages: fizhi, cheapaml
+
+   exch2: fancier way of exchanging data and tiling.
+
+
+jobs: forget about it.
+
+
+lsopt: forget it.
+
+optim: forget it.
+
+
+utils: 
+   matlab: bunch of matlab scripts.
+
+tools: build_options: platform dependent run files to be run with gene_make to generate the correct Makefile. 
+}}}
+How to run : {{{1
+All the verification tests are downloaded if you checkout the MITgcm repository instead of the 
+MITgcm_code: 
+cvs co -P MITgcm
+
+The verification tests are downloaded in MITgcm/verification. They can be run using 
+the testreport utility. Only a subset of the tests can be run if needed, by supplying 
+an option flag to tesstreport. 
+
+
+For our work, the relevant tests are: 
+labsea: sea ice
+ismip: shelf ice
+
+If you run a test like lab_sea: 
+
+./code/packages.conf: list of packages that we want to compile for this specific run.
+For each package, you at least need to modify code/size.h
+
+You can find the runtime parameters in: 
+input/data: runtime parameters  for model source
+input/eedata:runtime parameters  for eesupp source
+input/data.: runtime parameters for all packages
+intput/data.pkg: runtime parameters for packages that need to be run. subset of packages.conf
+
+The build directory holds the source and objects for the current test, with symlinks 
+
+If errors appear during the run, go into: 
+./run and find the STDERR file.
+
+To supply different Makefile templates for testreport:
+testreport -ef -opt Makefile_amd64_gfortran
+
+You can use matlab to plot the results: 
+use readbin from the labsea experiment or MITgcm/tools/matlab/rdmds
+
+There is an MITgcm_contrib repository for code that is not in the main trunk yet: 
+MITgcm_contrib/MPMice/beaufort presents a scenario for a quick coupler.
+
+}}}
+Extra nodes{{{
+cd install/verification/ 
+./testreport -of ../tools/build_options/linux_amd64_gfortran
+
+( results for baseline lab_sea verification
+  experiment are in verification/lab_sea/run )
+
+cd lab_sea/run
+there is routines in lab_sea/matlab
+
+ma
+addpath('../matlab')
+eta=readbin('Eta.0000000001.data',[20 16],1);
+pcolor(eta')
+colorbar
+
+addpath('../../../utils/matlab')
+eta=rdmds('Eta.0000000001');
+}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/readme_mitgcm.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/readme_mitgcm.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mitgcm/readme_mitgcm.txt	(revision 18231)
@@ -0,0 +1,84 @@
+Instructions for getting MITgcm:   http://mitgcm.org/ 
+
+
+(1)
+add to your .bashrc file
+# CVS 
+export CVSROOT=':pserver:cvsanon@mitgcm.org:/u/gcmpack'
+
+source .bashrc
+
+cvs login 
+ ( enter the CVS password: "cvsanon" )
+
+cvs co -P MITgcm
+
+(
+or if you don't want the verification packages
+cvs co -P MITgcm_code
+)
+
+
+(2)
+and if you don't like CVS  go to :
+
+http://mitgcm.org/download/
+
+and download the most recent checkpoint:
+e.g.
+     MITgcm_c62w.tar.gz
+
+
+
+
+
+==========================================================
+Instructions for generating and running a 1-CPU experiment
+==========================================================
+
+  cd MITgcm/verification/lab_sea
+  cd build
+  cp ../code/*.h ../code/packages.conf .
+  ../../../tools/genmake2
+  make depend
+  make
+  cd ../input
+  ../build/mitgcmuv > output.txt
+
+Use matlab script to look at the output
+  cd ../../../verification/lab_sea/matlab
+  matlab
+  lookat_ice  (you might have to modify the script)
+
+
+
+================================================================
+Instructions for running the "weddell" 200x160x50 configuration
+================================================================
+face=6; ix=101:300; jx=290:449; kx=1:50;
+
+1. Obtain copies of following directories:
+ ftp://ecco2.jpl.nasa.gov/data1/weddell/code
+ ftp://ecco2.jpl.nasa.gov/data1/weddell/run_template
+ ftp://ecco2.jpl.nasa.gov/data1/data/era40/era40_ecmwf_blend
+ ftp://ecco2.jpl.nasa.gov/data1/data/blend_forcing/cube59_GPCP
+
+2. Get and compile code:
+ cvs co MITgcm_code
+ cd MITgcm
+ mkdir bin exe
+ cd bin
+ ../tools/genmake2 -mods=../../code
+ make depend
+ make -j
+
+3. Model execution:
+ cd ../exe
+ cp ../../run_template/* .
+ cp ../bin/mitgcmuv .
+ ./mitgcmuv >& output.txt &
+
+
+
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modelE/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modelE/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modelE/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+#modelE  downloaded from the gis repository of the GISS (Goddard Institute for Space Studies)
+#at  http://www.giss.nasa.gov/tools/modelE/
+
+#Some cleanup
+rm -rf src install  modelE_AR5_branch
+mkdir src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/modelE_AR5_branch.2012.03.13_10.12.21.tgz' 'modelE_AR5_branch.2012.03.13_10.12.21.tgz'
+
+#Untar 
+tar -zxvf  modelE_AR5_branch.2012.03.13_10.12.21.tgz
+
+#Move modelE into install directory
+mv modelE_AR5_branch/* src
+rm -rf modelE_AR5_branch
+
+#Apply patches
+cd src 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+rm -rf modules-3.2.10
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/modules-3.2.10.tar.gz' 'modules-3.2.10.tar.gz'
+
+#Untar 
+tar -zxvf  modules-3.2.10.tar.gz
+
+#Move modules into src directory
+
+#Configure modules
+cd modules-3.2.10
+sudo ./configure \
+	--prefix=/usr/local/modules \
+	--with-tcl-lib=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework/Versions/8.5\
+	--with-tcl-inc=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework/Versions/8.5/Headers\
+	--with-tcl-ver=8.5 \
+	--with-tclx-lib=$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4\
+    --with-tclx-inc=$ISSM_DIR/externalpackages/tclx/install/include\
+	--with-tclx-ver=8.4 \
+	--with-version-path=/usr/local/modules/versions \
+	--with-skel-path=/usr/local/modules/etc/skel \
+	--with-etc-path=/usr/local/modules/etc \
+	--with-module-path=/usr/local/modules/files \
+	--disable-dependency-tracking
+
+#Compile and install modules
+if [ $# -eq 0 ]; then
+	sudo make
+else
+	sudo make -j $1
+fi
+sudo make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/modules/install.sh	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/modules-3.2.9c.tar.gz modules-3.2.9c.tar.gz
+
+#Untar and move python into install directory
+tar -zxvf  modules-3.2.9c.tar.gz
+mv modules-3.2.9 install
+
+#Configure doxygen
+cd install
+./configure \
+  --prefix "$ISSM_DIR/externalpackages/modules/install" \
+  --without-x
+
+#compile and install
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-linux64.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export -n F90 
+export CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx32.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export FFLAGS=" -m32"
+export CFLAGS=" -m32"
+export CXXFLAGS=" -arch i386"
+export CPPFLAGS=" -arch i386"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-f91=gfortran \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4-macosx64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export FCFLAGS=" -m64"
+export FFLAGS=" -m64"
+export CFLAGS=" -arch x86_64"
+export CXXFLAGS=" -arch x86_64"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-f91 \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4.1-p1-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4.1-p1-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.4.1-p1-win7.sh	(revision 18231)
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#In order to install MPICH2 on your platform, go to www.mpich.org/downloads 
+#and download the following file (Windows x86_64 for the Windows distribution): 
+#mpich2-1.4.1p1-win-x86-64.msi. This file is also hosted on the ISSM website.
+
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.1p1-win-x86-64.msi' 'mpich2-1.4.1p1-win-x86-64.msi'
+
+#once installed, create a symbolic link between the MPICH2 directory 
+#and the install directory. For example: 
+#ln -s /cygdrive/c/Program\ Files/MPICH2 install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-linux64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran  CC=gcc FC=gfortran
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-macosx64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-walgreen.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-walgreen.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-2_1.5-walgreen.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--with-device=ch3:sock
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-linux64.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mpich/install-3.0-macosx64.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared
+
+	#CC=llvm-gcc \
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/README	(revision 18231)
@@ -0,0 +1,1 @@
+MUMPS install package. Better rely on Petsc to install this, but feel free to try.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/configs/Makefile-macosx64.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/configs/Makefile-macosx64.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/configs/Makefile-macosx64.inc	(revision 18231)
@@ -0,0 +1,32 @@
+LPORDDIR   = $(topdir)/PORD/lib/
+IPORD      = -I$(topdir)/PORD/include/
+LPORD      = -L$(LPORDDIR) -lpord
+IMETIS = -I$(ISSM_DIR)/externalpackages/petsc/install/include/
+LMETIS = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lparmetis
+ORDERINGSC = -Dpord -Dmetis -Dparmetis
+ORDERINGSF = -Dprod -Dmetis -Dparmetis
+LORDERINGS  = $(LMETIS) $(LPORD) $(LSCOTCH)
+IORDERINGSC = $(IMETIS) $(IPORD) $(ISCOTCH)
+IORDERINGSF = $(ISCOTCH)
+RM = /bin/rm -f
+CC = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpicc
+OPTC    =  -PIC  -Wwrite-strings -Wno-strict-aliasing -Wno-unknown-pragmas -O 
+OUTC = -o 
+FC = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpif90
+FL = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpif90
+OPTF    =  -fPIC  -Wno-unused-variable -Wno-unused-dummy-argument -O  
+OUTF = -o 
+CDEFS   = -DAdd_
+AR      = /usr/bin/ar cr 
+LIBEXT  = .a
+RANLIB  = /usr/bin/ranlib -c
+SCALAP  = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lscalapack -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lblacs
+INCPAR  = -I$(ISSM_DIR)/externalpackages/mpich2/install/include -I$(ISSM_DIR)/externalpackages/mpich2/install/include
+LIBPAR  = $(SCALAP) 
+INCSEQ  = -I$(topdir)/libseq
+LIBSEQ  =  $(LAPACK) -L$(topdir)/libseq -lmpiseq
+LIBBLAS = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lflapack -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lfblas -L$(ISSM_DIR)/externalpackages/mpich2/install/lib -L/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/x86_64 -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/x86_64 -L/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/lib/gcc -L$(ISSM_DIR)/externalpackages/petsc/src -L$(ISSM_DIR)/externalpackages/hdf5/install/lib -L$(ISSM_DIR)/externalpackages/netcdf/install/lib -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/lib -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib -lmpichf90 -lgfortran -L/usr/local/gfortran/lib/gcc/x86_64-apple-darwin11/4.6.2 -L/usr/local/gfortran/lib -lgfortran -lgcc_ext.10.5 -lquadmath -lm -lm
+OPTL    = -O -I.
+INCS = $(INCPAR)
+LIBS = $(LIBPAR)
+LIBSEQNEEDED =
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/mumps/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mumps-4.10.0-p3
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mumps-4.10.0-p3.tar.gz' 'mumps-4.10.0-p3.tar.gz'
+
+#Untar 
+tar -zxvf  mumps-4.10.0-p3.tar.gz
+
+#Move mumps into src directory
+mv mumps-4.10.0-p3/* src
+rm -rf mumps-4.10.0-p3
+
+#configuration: 
+cp configs/Makefile-macosx64.inc src/Makefile.inc
+
+#Configure mumps
+cd src
+
+#Compile mumps
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ncview/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ncview/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/ncview/install.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ncview-1.93g.tar.gz' 'ncview-1.93g.tar.gz'
+
+#Untar 
+tar -zxvf  ncview-1.93g.tar.gz
+
+#Move doxygen into src directory
+mv ncview-1.93g/* install
+rmdir ncview-1.93g
+
+#Configure doxygen
+cd install
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/ncview/install" \
+	--x-libraries=/usr/X11/lib/ \
+	--x-includes=/usr/X11/include/ \
+	--with-netcdf_incdir="$ISSM_DIR/externalpackages/netcdf/install/include/" \
+	--with-netcdf_libdir="$ISSM_DIR/externalpackages/netcdf/install/lib/"
+
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-cxx/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-cxx/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-cxx/install.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install netcdf-cxx-4.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/netcdf-cxx-4.2.tar.gz' 'netcdf-cxx-4.2.tar.gz'
+
+#Untar 
+tar -zxvf netcdf-cxx-4.2.tar.gz
+
+#Move metis into install directory
+mv netcdf-cxx-4.2/* install
+rm -rf netcdf-cxx-4.2
+
+#Compile
+export CXXFLAGS="-I$ISSM_DIR/externalpackages/netcdf/install/include "
+cd install 
+./configure --prefix="$ISSM_DIR/externalpackages/netcdf-cxx/install" 
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-python/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-python/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf-python/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install netCDF4-1.0
+mkdir install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netCDF4-1.0.tar.gz" "netCDF4-1.0.tar.gz"
+
+#Untar 
+tar -zxvf  netCDF4-1.0.tar.gz
+
+#for later: 
+rm -rf ISSMDIR
+echo $ISSM_DIR | sed 's/\//\\\//g' > ISSMDIR
+ISSMDIR=`cat ISSMDIR` && rm -rf ISSMDIR
+
+#Move netCDF4 to install directory
+rm -rf install/*
+mv netCDF4-1.0/* install/
+rm -rf netCDF4-1.0
+
+#Configur and compile
+cd install
+#edit setup.cfg to point to hdf5 and netcdf
+cat setup.cfg.template  | sed "s/\#netCDF4_dir = \/usr\/local/netCDF4_dir = $ISSMDIR\/externalpackages\/netcdf\/install/g"  | sed "s/\#HDF5_dir = \/usr\/local/HDF5_DIR = $ISSMDIR\/externalpackages\/hdf5\/install/g" > setup.cfg
+
+python setup.py build 
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/netcdf/install.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python2.sh	(revision 18231)
@@ -0,0 +1,20 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src  install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/nose-1.1.2.tar.gz' 'nose-1.1.2.tar.gz'
+tar -zxvf  nose-1.1.2.tar.gz
+mv nose-1.1.2 src
+rm -rf nose-1.1.2
+
+cd src
+python ./setup.py build
+python ./setup.py install
+
+#to be flagged by jenkins, we create an empty install dir: 
+cd ../
+mkdir install
+touch install/emptyfile
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python3.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python3.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-linux64-python3.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src  install
+
+svn checkout http://python-nose.googlecode.com/svn/branches/py3k
+mv py3k src
+
+cd src
+python ./setup.py build
+python ./setup.py install
+
+#to be flagged by jenkins, we create an empty install dir: 
+cd ../
+mkdir install
+touch install/emptyfile
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python2.sh	(revision 18231)
@@ -0,0 +1,19 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src  install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/nose-1.1.2.tar.gz' 'nose-1.1.2.tar.gz'
+tar -zxvf  nose-1.1.2.tar.gz
+mv nose-1.1.2 src
+rm -rf nose-1.1.2
+
+cd src
+python ./setup.py build
+python ./setup.py install
+
+#to be flagged by jenkins, we create an empty install dir: 
+cd ../
+mkdir install
+touch install/emptyfile
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python3.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python3.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/nose/install-macosx64-python3.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src  install
+
+svn checkout http://python-nose.googlecode.com/svn/branches/py3k
+mv py3k src
+
+cd src
+python ./setup.py build
+python ./setup.py install
+
+#to be flagged by jenkins, we create an empty install dir: 
+cd ../
+mkdir install
+touch install/emptyfile
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/README	(revision 18231)
@@ -0,0 +1,9 @@
+For OSX 10.7 (Lion), the instructions here can be followed:  
+http://www.scipy.org/Installing_SciPy/Mac_OS_X
+
+For OSX 10.6 (Snow Leopard), the scipy folks recommend gcc and g++ version 4.0.
+However, ISSM needs the gfortran version recommended in $ISSM_DIR/externalpackages/gfortran.
+On the webpage listed above, make sure the "export CC" and "export CXX" commands point to the 
+binaries associated with this gfortran version (likely in /usr/local/gfortran/bin by default).
+Once this gfortran is installed, the install script in this directory for Snow Leopard should
+work.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-linux64.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+
+export CC="gcc -fPIC"
+export CXX="g++ -fPIC"
+export F77="gfortran -fPIC"
+export FC="gfortran -fPIC"
+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()"
+
+#to be flagged by jenkins, we create an empty install dir: 
+mkdir install
+touch install/emptyfile
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-lion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-lion.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+
+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()"
+
+#to be flagged by jenkins, we create an empty install dir: 
+mkdir install
+touch install/emptyfile
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-mlion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-mlion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-mlion.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+
+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()"
+
+#to be flagged by jenkins, we create an empty install dir: 
+mkdir install
+touch install/emptyfile
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-snowleopard.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/numpy/install-macosx-snowleopard.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+
+# On OSX 10.6, gfortran gets installed in /usr/local/gfortran 
+export CC="/usr/local/gfortran/bin/gcc"
+export CXX="/usr/local/gfortran/bin/g++"
+
+#download numpy first
+git clone https://github.com/numpy/numpy.git
+
+#install numpy
+cd numpy
+python setup.py build
+python setup.py install
+cd ..
+python -c "import numpy; print 'Installed NumPy', numpy.__version__"
+python -c "import numpy; numpy.test()"
+
+#to be flagged by jenkins, we create an empty install dir: 
+mkdir install
+touch install/emptyfile
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/octave/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/octave/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/octave/install.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install octave-3.6.2 
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/octave-3.6.2.tar.gz" "octave-3.6.2.tar.gz"
+
+#Untar 
+tar -zxvf  octave-3.6.2.tar.gz
+
+#Move octave into install directory
+mv octave-3.6.2/* src
+rm -rf octave-3.6.2
+
+#install
+cd src 
+./configure \
+ --prefix=$ISSM_DIR/externalpackages/octave/install \
+ --disable-readline
+
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/oofem/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/oofem/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/oofem/install.sh	(revision 18231)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf oofem-2.0
+mkdir src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/oofem-2.0.tar.gz' 'oofem-2.0.tar.gz'
+
+#Untar 
+tar -zxvf  oofem-2.0.tar.gz
+
+#Move oofem into src directory
+mv oofem-2.0/* src
+rm -rf oofem-2.0
+
+# currently a basic serial configuration, see http://www.oofem.org/wiki/doku.php?id=installation 
+# for details on enabling the IML++ and PETSc libraries, and for configuring the parallel version
+cd src
+./configure OOFEM_TARGET=oofem-2.0 --enable-dss
+
+#Compile oofem 
+cd targets/oofem-2.0
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+
+# build verification tools
+cd ../../tools && make all
+
+# testing solver
+cd ../targets/oofem-2.0 && make tests && less ./test_results
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openanalysis/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openanalysis/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openanalysis/install.sh	(revision 18231)
@@ -0,0 +1,14 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf openanalysis
+
+#download openanalysis
+svn co http://svn.berlios.de/svnroot/repos/openanalysis/OpenAnalysis/trunk openanalysis
+
+#Configure
+cd openanalysis
+
+make -f Makefile.quick all
+make -f Makefile.quick install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openssl/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openssl/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/openssl/install.sh	(revision 18231)
@@ -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" shared
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/packagemaker/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/packagemaker/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/packagemaker/install.sh	(revision 18231)
@@ -0,0 +1,8 @@
+#!/bin/bash
+set -eu
+
+#Erase symlink
+rm -rf install
+
+#Select or create a new simlink
+ln -s /Developer/Applications/Utilities/PackageMaker.app/Contents/MacOS/ install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pcre/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pcre/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pcre/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Cleaning
+rm -rf install
+rm -rf pcre-8.21
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/pcre-8.21.tar.gz' 'pcre-8.21.tar.gz'
+
+#Untar and move python into install directory
+tar -zxvf  pcre-8.21.tar.gz
+mv pcre-8.21/* install
+rm -rf pcre-8.21
+
+#Configure doxygen
+cd install 
+./configure --prefix "$ISSM_DIR/externalpackages/python/install"
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/README	(revision 18231)
@@ -0,0 +1,27 @@
+petsc carries a version of Blas that uses int arguments (int32) type, while 
+Matlab carries a version of Blas that uses int64_t arguments (hidden behing 
+a ptrdiff_t type (check MATLAB_DIR/extern/include/blas.h). 
+In serial mode, Matlab discards the Petsc Blas library (even when it was statically 
+linked against the mex files!) symbols, and replaces them with its version. 
+Because the prototypes conflict (32 vs 64), crashes ensue whenever using a Blas 
+routine (for ex: VecAXPY calls BLASaxpy_, which calls daxpy). 
+
+To avoid that, we have to recompile Petsc with a 64 bit prototype. Luckily, 
+Petsc did a good job, and hid the Blas int type into the typedef BLASint (check
+in include/petsc.h). Just typedef it back from int to int64_t, and recompile, 
+and that does the trick. Don't forget the #include "inttypes.h" at the top of petsc.h,
+otherwise, crashes during the compile.
+
+Same problem may arise for using the lapack library.
+
+Now, Petsc pretends it can compile in --with-64-bit-pointers. That sets PetscInt to long long 
+The only problem, it says MUMPS, Scalapack, blacs, Plapack don't support 64 bit indexing. 
+Mumps looks like it might. 
+
+If compiling --with-64-bit-pointers,  all prototypes in Petsc ask for PetscInt = long long 
+which Issm does not know. Can't compile with this option. Unless we switch to 64 bit integers 
+in ISSM. Started to put this framework into place: we now have IssmInt, IssmDouble, IssmChar 
+in types.h. They rely on ISSM_USE_64_BIT_INDEXING symbol, define in config.h, instantiated by 
+autotools with --with-64bit-pointers=1 in configure.sh
+
+Recomendation: wait until MUMPS implements 64 bit indexing. 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/configs/3.1/win7/petscfix.h.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/configs/3.1/win7/petscfix.h.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/configs/3.1/win7/petscfix.h.patch	(revision 18231)
@@ -0,0 +1,8 @@
+10c10
+< extern "C" {
+---
+> //extern "C" {
+14c14
+< }
+---
+> //}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-altix64-castor.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 18231)
@@ -0,0 +1,66 @@
+#!/bin/bash
+set -eu
+#Step 1: unzip and install
+#Step 2: After Plapack implodes
+STEP=0
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-3.1-p7 src
+	mkdir install src
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-3.1-p7.tar.gz
+	mv petsc-3.1-p7/* install/
+	rm -rf petsc-3.1-p7
+
+	#configure
+	cd src
+	./config/configure.py \
+	  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	  --ISSM_ARCH=$ISSM_ARCH \
+	  --with-debugging=no \
+	  --with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+	  --with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
+	  --with-mpi-lib=/usr/lib/libmpi.so \
+	  --with-mpi-include=/usr/include  \
+	  --with-mpi-shared=0 \
+	  --download-mumps=yes \
+	  --download-scalapack=yes \
+	  --download-blacs=yes  \
+	  --download-plapack=yes \
+	  --FFLAGS=-I/usr/include \
+	  --with-cc=icc \
+	  --with-fc=ifort  \
+	  --download-parmetis=yes
+
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc31/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd src
+	./config/configure.py \
+		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+		--with-batch=1  \
+		--ISSM_ARCH=$ISSM_ARCH \
+		--with-debugging=no \
+		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
+		--with-mpi-lib=/usr/lib/libmpi.so \
+		--with-mpi-include=/usr/include  \
+		--with-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort  \
+		--download-parmetis=yes
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-cosmos.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-cosmos.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-cosmos.sh	(revision 18231)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-batch=1  \
+	--ISSM_ARCH=$ISSM_ARCH \
+	--with-debugging=no COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+	--with-blas-lapack-dir=/opt/intel/mkl/10.0.5.025/ \
+	--with-mpi-dir=/opt/mpich/gm/intel10.1/  \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes  \
+	--download-plapack=yes \
+	--FFLAGS=-I/usr/include  \
+	--with-mpi-shared=0  \
+	--download-parmetis=yes
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-linux64-berg.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-linux64-berg.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-linux64-berg.sh	(revision 18231)
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+#Get number of cpus on current platform
+NUMCPUS=$1;
+
+#version of petsc?
+#version='2.3.2-p3';
+version='3.1-p7'
+#version='3.2-p3'
+
+#Some cleanup
+rm -rf install petsc-$version src
+
+#Create src and install directories
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar 
+tar -zxvf  petsc-$version.tar.gz
+
+#Move petsc to install directory or src depending on the version
+if [[ $version != "2.3.2-p3" ]]
+then	
+	mv petsc-$version/* src/
+	rm -rf petsc-$version
+	cd src
+else
+	mv petsc-$version/* install/
+	rm -rf petsc-$version
+	cd install
+fi
+
+#configure
+../configure.sh
+
+#Compile petsc and install it
+if [ -z $NUMCPUS ];
+then
+	make
+else
+	make -j $NUMCPUS
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-mathieu.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+#configure
+cd src
+./config/configure.py  \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --PETSC_ARCH=macosx-gnu \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+ --with-debugging=0 \
+ --with-shared=0 \
+ --download-mumps=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-plapack=yes \
+ --FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -arch i386" \
+ --COPTFLAGS="-march=opteron -O2 -arch i386" \
+ --FOPTFLAGS="-march=opteron -O2 -arch i386" \
+ --CXXOPTFLAGS="-march=opteron -O2 -arch i386" \
+ --download-parmetis=yes
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-ogive.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+	--PETSC_ARCH=macosx-gnu \
+	--with-fc=/usr/local/bin/gfortran \
+	--with-debugging=0 \
+	--with-shared=0 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-plapack=yes  \
+	--download-parmetis=yes \
+	--download-f-blas-lapack=yes \
+	--COPTFLAGS="-march=opteron -O2 " \
+	--FOPTFLAGS="-march=opteron -O2 " \
+	--CXXOPTFLAGS="-march=opteron -O2 " \
+	--FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -L$ISSM_DIR/externalpackages/mpich/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran " 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-pleiades.sh	(revision 18231)
@@ -0,0 +1,73 @@
+#!/bin/bash
+set -eu
+#Step 1: unzip and install
+#Step 2: After Plapack implodes
+STEP=0
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-3.1-p7 src
+	mkdir install src
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-3.1-p7.tar.gz
+	mv petsc-3.1-p7/* install/
+	rm -rf petsc-3.1-p7
+
+	#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=no \
+		--with-shared=0 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--with-mpi-lib=/nasa/sgi/mpt/1.25/lib/libmpi.so \
+		--with-mpi-include=/nasa/sgi/mpt/1.25/include  \
+		--known-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-plapack=yes \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort \
+		--COPTFLAGS=" -O3 -xS" \
+		--FOPTFLAGS=" -O3 -xS" \
+		--CXXOPTFLAGS=" -O3 -xS" \
+		--with-pic=1
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc31/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd src
+	./config/configure.py \
+	 --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	 --with-batch=1  \
+	 --PETSC_ARCH="$ISSM_ARCH" \
+	 --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	 --with-debugging=no \
+	 --with-shared=0 \
+	 --with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+	 --with-mpi-lib=/nasa/sgi/mpt/1.25/lib/libmpi.so \
+	 --with-mpi-include=/nasa/sgi/mpt/1.25/include  \
+	 --known-mpi-shared=0 \
+	 --download-mumps=yes \
+	 --download-scalapack=yes \
+	 --download-blacs=yes  \
+	 --with-plapack-dir=$ISSM_DIR/externalpackages/petsc/src/$ISSM_ARCH \
+	 --download-parmetis=yes \
+	 --FFLAGS=-I/usr/include \
+	 --with-cc=icc \
+	 --with-fc=ifort \
+	 --COPTFLAGS=" -O3 -xS" \
+	 --FOPTFLAGS=" -O3 -xS" \
+	 --CXXOPTFLAGS=" -O3 -xS" \
+	 --with-pic=1
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-ubuntu64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+ --PETSC_ARCH=linux-gnu\
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-debugging=0 \
+ --with-shared=0 \
+ --download-mumps=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-parmetis=yes \
+ --FFLAGS=-I$ISSM_DIR/externalpackages/mpich/install/include \
+ --download-plapack=yes \
+ --COPTFLAGS="-O2" \
+ --FOPTFLAGS="-O2" \
+ --CXXOPTFLAGS="-O2" \
+ --with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7-parallel.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7-parallel.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7-parallel.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+cd src
+./config/configure.py  \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_ARCH=cygwin-intel \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--download-c-blas-lapack=yes \
+	--with-cc='win32fe cl' \
+	--with-fc=0 \
+	--with-cxx='win32fe cl' \
+	--with-clanguage=cxx  \
+	--with-mpi-include="/cygdrive/c/MPICH2/include" \
+	--with-mpi-lib="/cygdrive/c/MPICH2/lib/mpi.lib"
+
+
+#Compile petsc and install it
+make
+make install
+
+patch ../install/include/petscfix.h ../configs/3.1/win7/petscfix.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.1-win7.sh	(revision 18231)
@@ -0,0 +1,57 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+export PETSC_DIR=`cygpath -u "$ISSM_DIR/externalpackages/petsc/src"`
+export PREFIX_DIR=`cygpath -u "$ISSM_DIR/externalpackages/petsc/install"`
+
+#configure
+cd src
+./config/configure.py  \
+	--with-parallel-no \
+	--prefix=$PREFIX_DIR \
+	--PETSC_ARCH=cygwin-intel \
+	--PETSC_DIR=$PETSC_DIR \
+	--with-debugging=0 \
+	--with-mpi=0 \
+	--download-c-blas-lapack=yes \
+	--with-cc='win32fe cl' \
+	--with-fc=0 \
+	--with-cxx='win32fe cl' \
+	--with-clanguage=cxx 
+
+#./config/configure.py  \
+# --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+# --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+# --PETSC_ARCH=macosx-gnu \
+# --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+# --with-debugging=0 \
+# --with-shared=0 \
+# --download-mumps=yes \
+# --download-scalapack=yes \
+# --download-blacs=yes \
+# --download-blas=yes \
+# --download-f-blas-lapack=yes \
+# --download-plapack=yes \
+# --FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -arch i386" \
+# --COPTFLAGS="-march=opteron -O2 -arch i386" \
+# --FOPTFLAGS="-march=opteron -O2 -arch i386" \
+# --CXXOPTFLAGS="-march=opteron -O2 -arch i386" \
+# --download-parmetis=yes
+
+#Compile petsc and install it
+make
+make install
+
+patch ../install/include/petscfix.h ../configs/3.1/win7/petscfix.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover-intel13.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover-intel13.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover-intel13.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--PETSC_ARCH="$ISSM_ARCH" \
+	--with-batch=1 \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--known-mpi-shared-libraries=1 \
+	--with-mpi-dir=/usr/local/intel/mpi/4.0.3.008/lib64/ \
+	--with-blas-lapack-dir=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/ \
+	--with-scalapack-lib=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/lib/intel64/libmkl_scalapack_lp64.a \
+	--with-scalapack-include=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/include/ \
+	--with-blacs-lib=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a \
+	--with-blacs-include=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/include/ \
+	--download-mumps=yes \
+	--download-scalapack=no \
+	--download-blacs=no \
+	--download-plapack=no \
+	--download-parmetis=yes \
+	--with-pic=1
+
+echo "== Follow PETSc's instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-discover.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--PETSC_ARCH="$ISSM_ARCH" \
+	--with-batch=1 \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--known-mpi-shared-libraries=1 \
+	--with-mpi-dir=/usr/local/intel/mpi/4.0.3.008/lib64/ \
+	--with-blas-lapack-dir=/usr/local/intel/mkl/10.1.2.024/lib/64/ \
+	--with-scalapack-lib=/usr/local/intel/mkl/10.1.2.024/lib/64/libmkl_scalapack_lp64.a \
+	--with-scalapack-include=/usr/local/intel/mkl/10.1.2.024/include/ \
+	--with-blacs-lib=/usr/local/intel/mkl/10.1.2.024/lib/64/libmkl_blacs_intelmpi_lp64.a \
+	--with-blacs-include=/usr/local/intel/mkl/10.1.2.024/include/ \
+	--download-mumps=yes \
+	--download-scalapack=no \
+	--download-blacs=no \
+	--download-plapack=no \
+	--download-parmetis=yes \
+	--with-pic=1
+
+echo "== Follow PETSc's instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--PETSC_ARCH="$ISSM_ARCH" \
+	--with-batch=1 \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--known-mpi-shared-libraries=1 \
+	--with-mpi-dir=/sopt/mpi/openmpi-1.5.4_psm/intel/ \
+	--with-blas-lapack-dir=/opt/intel/mkl/10.2.4.032/ \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+echo "== Follow PETSc's instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-hoffman2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-hoffman2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-hoffman2.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi=1 \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-linux64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-macosx64.sh	(revision 18231)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+  --PETSC_ARCH="macosx-gnu" \
+  --with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+  --with-debugging=0 \
+  --with-shared-libraries=1 \
+  --download-mumps=yes \
+  --download-scalapack=yes \
+  --download-blacs=yes \
+  --download-blas=yes \
+  --download-plapack=no  \
+  --download-parmetis=yes \
+  --download-f-blas-lapack=yes 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-pleiades.sh	(revision 18231)
@@ -0,0 +1,88 @@
+#!/bin/bash
+set -eu
+#Step 1: unzip and install
+#Step 2: After Plapack implodes
+STEP=2
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-3.2-p3 src
+	mkdir install src
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-3.2-p3.tar.gz
+	mv petsc-3.2-p3/* src/
+	rm -rf petsc-3.2-p3
+
+	#configure
+	cd src
+	./config/configure.py \
+		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH="$ISSM_ARCH" \
+		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+		--with-debugging=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/1.25/lib/libmpi.so \
+		--with-mpi-include=/nasa/sgi/mpt/1.25/include  \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-plapack=yes \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort \
+		--COPTFLAGS=" -O3 -xS" \
+		--FOPTFLAGS=" -O3 -xS" \
+		--CXXOPTFLAGS=" -O3 -xS" \
+		--with-pic=1
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/documentation/faq/petsc32/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd src
+	./config/configure.py \
+	 --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	 --with-batch=1  \
+	 --PETSC_ARCH="$ISSM_ARCH" \
+	 --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	 --with-debugging=0 \
+	 --with-shared-libraries=1 \
+	 --with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+	 --with-mpi-lib=/nasa/sgi/mpt/1.25/lib/libmpi.so \
+	 --with-mpi-include=/nasa/sgi/mpt/1.25/include  \
+	 --known-mpi-shared-libraries=1 \
+	 --download-mumps=yes \
+	 --download-scalapack=yes \
+	 --download-blacs=yes  \
+	 --with-plapack-dir=$ISSM_DIR/externalpackages/petsc/src/$ISSM_ARCH \
+	 --download-parmetis=yes \
+	 --FFLAGS=-I/usr/include \
+	 --with-cc=icc \
+	 --with-fc=ifort \
+	 --COPTFLAGS=" -O3 -xS" \
+	 --FOPTFLAGS=" -O3 -xS" \
+	 --CXXOPTFLAGS=" -O3 -xS" \
+	 --with-pic=1
+	 cat > src/script.queue << EOF
+#PBS -S /bin/bash
+#PBS -q debug 
+#PBS -l select=1:ncpus=1:model=har 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010 
+#PBS -m e 
+. /usr/share/modules/init/bash 
+module load comp-intel/11.1.046 
+module load mpi/mpt.1.25 
+module load math/intel_mkl_64_10.0.011 
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-ubuntu64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-ubuntu64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.2-ubuntu64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir=/usr/lib/mpich \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-linux64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.3-p6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--download-metis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-macosx64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.3-p6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+	--PETSC_ARCH="macosx-gnu" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--download-metis=yes \
+	--with-debugging=yes
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-pleiades.sh	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.3-p6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2013.1.117
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-walgreen.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-walgreen.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.3-walgreen.sh	(revision 18231)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.3-p6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --with-blas-lapack-dir=/opt/intel/mkl/10.0.1.014/ \
+ --download-mumps=yes \
+ --download-blacs=yes  \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-parmetis=yes \
+ --download-metis=yes \
+ --download-superlu=yes \
+ #--download-hypre=yes 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-acenet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-acenet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-acenet.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="linux-gnu-amd64" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi-dir=$OPENMPI \
+ --with-blas-lapack-dir=/usr/local/intel/composer_xe_2011_sp1.13.367/mkl/ \
+ --download-scalapack=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes 
+
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-greenplanet.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-greenplanet.sh	(revision 18231)
@@ -0,0 +1,55 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-dir=/sopt/mpi/openmpi-1.5.4_psm/intel/ \
+ --with-blas-lapack-dir=/opt/intel/mkl/10.2.4.032/ \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l nodes=1:ppn=1
+#PBS -q c6145
+#PBS -l walltime=10
+
+cd $(echo $ISSM_DIR)/externalpackages/petsc/src/
+mpiexec -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-hpc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-hpc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-hpc.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#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 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-dir=/data/apps/mpi/openmpi-1.6.0/gcc-4.7.2// \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --COPTFLAGS="-O3" \
+ --FOPTFLAGS="-O3" \
+ --CXXOPTFLAGS="-O3"
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-linux64.sh	(revision 18231)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-parmetis=yes \
+	--download-metis=yes \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-macosx64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_ARCH="macosx-gnu" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-metis=yes \
+	--download-parmetis=yes \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--with-debugging=yes
+
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-intel2012.0.032-mpt.2.06rp16
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-intel2012.0.032-mpt.2.06rp16	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-intel2012.0.032-mpt.2.06rp16	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.2 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.2.tar.gz
+mv petsc-3.4.2/* src/
+rm -rf petsc-3.4.2
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2012.0.032/composer_xe_2011_sp1/mkl/lib/intel64" \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2012.0.032
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc444.sh	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/mvapich2/1.4.1/gcc.sles11/lib/libmpich.a"\
+ --with-mpi-include="/nasa/mvapich2/1.4.1/gcc.sles11/include"\
+ --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpich" \
+ --FOPTFLAGS="-lmpich" \
+ --CXXOPTFLAGS="-lmpich"
+
+#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 mpi-mvapich2/1.4.1/gcc
+module load gcc/4.4.4
+
+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/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2-gcc470.sh	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/mvapich2/1.6.sles11/gcc/lib/libmpich.a"\
+ --with-mpi-include="/nasa/mvapich2/1.6.sles11/gcc/include" \
+ --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpich" \
+ --FOPTFLAGS="-lmpich" \
+ --CXXOPTFLAGS="-lmpich"
+
+#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 mpi-mvapich2/1.6/gcc
+module load gcc/4.7.0
+
+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/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades-mpich2.sh	(revision 18231)
@@ -0,0 +1,68 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.2 src
+mkdir install src
+
+export cc=gcc
+alias cc='gcc'
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.2.tar.gz
+mv petsc-3.4.2/* src/
+rm -rf petsc-3.4.2
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="$ISSM_DIR/externalpackages/mpich/install/lib/libmpich.so"\
+ --with-mpi-include="$ISSM_DIR/externalpackages/mpich/install/include" \
+  --known-mpi-shared-libraries=1 \
+  --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+  --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes  \
+ --COPTFLAGS=" -O3 -march=corei7-avx" \
+ --FOPTFLAGS=" -O3 -march=corei7-avx" \
+ --CXXOPTFLAGS=" -O3 -march=corei7-avx" 
+
+#--with-mpi-lib="/nasa/mvapich2/1.4.1/gcc.sles11/lib/libmpich.a" \
+# --with-mpi-include="/nasa/mvapich2/1.4.1/gcc.sles11/include" \
+
+
+#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 mpi-mvapich2/1.6/gcc
+module load gcc/4.7.0
+
+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/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades.sh	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2013.1.117
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-3.4-pleiades2.sh	(revision 18231)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.3.tar.gz' 'petsc-3.4.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.4.3.tar.gz
+mv petsc-3.4.3/* src/
+rm -rf petsc-3.4.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2013.1.117
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-linux64.sh	(revision 18231)
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+STEP=2
+
+if [ $STEP -eq 1 ]; then
+	# Used Mercurial to get code
+	rm -rf src
+	hg clone http://petsc.cs.iit.edu/petsc/petsc-dev src
+	cd src
+	hg clone http://petsc.cs.iit.edu/petsc/BuildSystem config/BuildSystem
+fi
+
+# To update (via Mercurial):
+#      cd petsc-dev
+#      hg pull -u
+#      cd config/BuildSystem
+#      hg pull -u
+
+# configure script
+# Note: 
+#  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 \
+
+
+if [ $STEP -eq 2 ]; then
+	rm -rf install
+	cd src
+	./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes  \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-parmetis=yes \
+	--download-metis=yes \
+	--download-trilinos=yes \
+	--download-euclid=yes \
+	--download-spooles=yes \
+	--download-spai=yes \
+	--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+	--download-hypre=yes \
+	--download-c2html=yes
+#	--with-pic=1
+
+	#Compile petsc and install it
+	make
+	make install
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/petsc/install-dev-pleiades.sh	(revision 18231)
@@ -0,0 +1,78 @@
+#!/bin/bash
+#Step 0: download
+#Step 1: install and write script
+STEP=1
+
+if [ $STEP -eq 0 ]; then
+	# Adapted from petsc 3.2. 
+	# Used Mercurial to get code
+	rm -rf src
+	hg clone http://petsc.cs.iit.edu/petsc/petsc-dev src
+	cd src
+	hg clone http://petsc.cs.iit.edu/petsc/BuildSystem config/BuildSystem
+fi
+
+# To update (via Mercurial):
+#      cd petsc-dev
+#      hg pull -u
+#      cd config/BuildSystem
+#      hg pull -u
+
+# configure script
+# Note: using metis from externalpackages did not work...
+# for now downloading new metis
+#   -then rename metis in externalpackages to metis2
+#
+#		--download-prometheus=yes \
+#--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+#		--download-plapack=yes \
+
+if [ $STEP -eq 1 ]; then
+
+	#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 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--known-mpi-shared-libraries=1 \
+		--with-mpi=1 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-blas=yes \
+		--download-f-blas-lapack=yes \
+		--download-parmetis=yes \
+		--download-metis=yes \
+		--download-trilinos=yes \
+		--download-euclid=yes \
+		--download-spai=yes \
+		--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+		--download-hypre=yes \
+		--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 -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
+	echo "== Now: cd src/ "
+	echo "== qsub -q devel script.queue "
+	echo "== Then run reconfigure script generated by PETSc and follow instructions"
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/polygonclipper/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/polygonclipper/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/polygonclipper/install.sh	(revision 18231)
@@ -0,0 +1,19 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/PolygonClipper.zip' 'PolygonClipper.zip'
+
+#install
+mkdir install
+cd install
+cp ../PolygonClipper.zip .
+
+#uncompress
+unzip PolygonClipper.zip
+
+#Make
+mex gpc.c gpc_mexfile.c -O -output PolygonClip
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/proj.4/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/proj.4/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/proj.4/install.sh	(revision 18231)
@@ -0,0 +1,15 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+
+#Download trunk
+svn checkout http://svn.osgeo.org/metacrs/proj/trunk/proj install
+
+#compile
+cd install
+./configure --prefix="$ISSM_DIR/externalpackages/proj.4/install"
+make 
+make install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pyclips/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pyclips/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pyclips/install.sh	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+rm -rf pyclips-1.0.7.348
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/pyclips-1.0.7.348.tar.gz' 'pyclips-1.0.7.348.tar.gz'
+
+#Untar 
+tar -zxvf  pyclips-1.0.7.348.tar.gz
+
+#Move pyclips into install directory
+mv pyclips/* install
+rm -rf pyclips
+
+#install
+cd install
+python setup.py build
+sudo python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pysvn/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pysvn/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/pysvn/install.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf pysvn-1.7.6
+mkdir src 
+
+export CC=/usr/local/gfortran/bin/gcc
+export CXX=/usr/local/gfortran/bin/g++
+export FFLAGS=-ff2c
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/pysvn-1.7.6.tar.gz' 'pysvn-1.7.6.tar.gz'
+
+#Untar 
+tar -zxvf  pysvn-1.7.6.tar.gz
+
+#Move pysvn into src directory
+mv pysvn-1.7.6/* src
+rm -rf pysvn-1.7.6
+
+$install
+cd src
+python setup.py build
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-linux64.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#Configure python
+cd src 
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --enable-shared
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install/include
+cp python2.7/* ./
+cd ../lib
+ln -s  libpython2.7.so.1.0 libpython.so
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-lion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-lion.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-mlion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-mlion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-mlion.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-snowleopard.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-2.7.3-macosx-snowleopard.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#exports
+export MACOSX_DEPLOYMENT_TARGET=10.6
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#Configure doxygen
+cd src 
+# --enable-framework needs to have the form "$SOME_PATH/Library/Frameworks" to avoid installing components in /Applications directory
+# --prefix is recognized as $SOME_PATH as long as this form is taken, so it's not necessary to include
+./configure --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#make
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install
+ln -s Library/Frameworks/Python.framework/Headers include
+ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
+
+#Patch pyport.h:
+cd include
+patch pyport.h $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-linux64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure python
+cd src 
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --enable-shared
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 18231)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#obsolete? 
+#./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install"
+
+#make
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 18231)
@@ -0,0 +1,41 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+export MACOSX_DEPLOYMENT_TARGET=10.6
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd src 
+# --enable-framework needs to have the form "$SOME_PATH/Library/Frameworks" to avoid installing components in /Applications directory
+# --prefix is recognized as $SOME_PATH as long as this form is taken, so it's not necessary to include
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#make
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+cd ..
+
+cd install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch	(revision 18231)
@@ -0,0 +1,22 @@
+680a681
+> #ifdef isalnum
+682a684,685
+> #endif
+> #ifdef isalpha
+684a688,689
+> #endif
+> #ifdef islower
+686a692,693
+> #endif
+> #ifdef isspace
+688a696,697
+> #endif
+> #ifdef isupper
+690a700,701
+> #endif
+> #ifdef tolower
+692a704,705
+> #endif
+> #ifdef toupper
+695a709
+> #endif
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch.bugreport
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 18231)
@@ -0,0 +1,1 @@
+http://bugs.python.org/issue10910
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/qhull/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/qhull/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/qhull/install.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install qhull-2003.1
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/qhull-2003.1.tar.gz' 'qhull-2003.1.tar.gz'
+
+#Untar 
+tar -zxvf  qhull-2003.1.tar.gz
+
+#Move qhull to src directory
+rm -rf src/*
+mv qhull-2003.1/* src/
+rm -rf qhull-2003.1
+
+#Configure qhull
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/qhull/install"
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/README	(revision 18231)
@@ -0,0 +1,3 @@
+Rought Auditing Tools for Software
+Obtained code from https://www.fortify.com/ssa-elements/threat-intelligence/rats.html
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rats/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src rats-2.3
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/rats-2.3.tar.gz' 'rats-2.3.tar.gz'
+
+#install directory
+mkdir src
+tar -zxvf rats-2.3.tar.gz 
+mv rats-2.3/* src
+rm -rf rats-2.3
+
+#compile
+cd src
+./configure --prefix=$ISSM_DIR/externalpackages/rats/install
+make
+make install
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/readline/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/readline/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/readline/install.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf readline-6.2.2
+mkdir src 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/readline-6.2.2.tar.gz' 'readline-6.2.2.tar.gz'
+
+#Untar 
+tar -zxvf  readline-6.2.2.tar.gz
+
+#Move readline into src directory
+mv readline-6.2.2/* src
+rm -rf readline-6.2.2
+
+#install
+cd src
+python setup.py install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rose/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rose/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/rose/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf source build install
+mkdir install source build
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/rose-0.9.5a-13219.tar.gz' 'rose-0.9.5a-13219.tar.gz'
+
+#Untar 
+tar -zxvf  rose-0.9.5a-13219.tar.gz
+
+#Move rose into install directory
+mv rose-0.9.5a-13219/* source
+rm -rf rose-0.9.5a-13219
+
+#Configure
+cd build
+../source/configure \
+	--prefix=$ISSM_DIR/externalpackages/rose/install \
+	--with-boost=$ISSM_DIR/externalpackages/boost/install\
+	--srcdir=$ISSM_DIR/externalpackages/rose/source
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/satstress/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/satstress/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/satstress/install.sh	(revision 18231)
@@ -0,0 +1,20 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install SatStress-0.1.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/SatStress-0.1.2.tar.gz' 'SatStress-0.1.2.tar.gz'
+
+#Untar 
+tar -zxvf  SatStress-0.1.2.tar.gz
+
+#Move SatStress into install directory
+mv SatStress-0.1.2/* install
+rm -rf SatStress-0.1.2
+
+#Compile SatStress
+cd install 
+make test
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/README	(revision 18231)
@@ -0,0 +1,9 @@
+For OSX 10.7 (Lion), the instructions here can be followed:  
+http://www.scipy.org/Installing_SciPy/Mac_OS_X
+
+For OSX 10.6 (Snow Leopard), the scipy folks recommend gcc and g++ version 4.0.
+However, ISSM needs the gfortran version recommended in $ISSM_DIR/externalpackages/gfortran.
+On the webpage listed above, make sure the "export CC" and "export CXX" commands point to the 
+binaries associated with this gfortran version (likely in /usr/local/gfortran/bin by default).
+Once this gfortran is installed, the install script in this directory for Snow Leopard should
+work.
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-linux64.sh	(revision 18231)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+export CC="gcc -fPIC"
+export CXX="g++ -fPIC"
+export F77="gfortran -fPIC"
+export FC="gfortran -fPIC"
+export FFLAGS=-ff2c
+
+#clean up
+rm -rf scipy
+#download scipy
+export GIT_SSL_NO_VERIFY=true 
+git clone https://github.com/scipy/scipy.git
+
+#install scipy
+cd scipy
+export  BLAS_SRC=$ISSM_DIR/externalpackages/blas/install/lib
+export  BLAS=$ISSM_DIR/externalpackages/blas/install/lib
+export  LAPACK_SRC=$ISSM_DIR/externalpackages/lapack/install/lib
+export  LAPACK=$ISSM_DIR/externalpackages/lapack/install/lib
+
+python setup.py build
+python setup.py install
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+#python -c "import scipy; scipy.test()"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-lion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-lion.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/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
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+#python -c "import scipy; scipy.test()"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-mlion.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-mlion.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-mlion.sh	(revision 18231)
@@ -0,0 +1,23 @@
+#!/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
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+#python -c "import scipy; scipy.test()"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 18231)
@@ -0,0 +1,17 @@
+#!/bin/bash
+set -eu
+
+# On OSX 10.6, fgortran gets installed in /usr/local/gfortran 
+export CC="/usr/local/gfortran/bin/gcc"
+export CXX="/usr/local/gfortran/bin/g++"
+
+#download scipy
+git clone https://github.com/scipy/scipy.git
+
+#install scipy
+cd scipy
+python setup.py build
+python setup.py install
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+#python -c "import scipy; scipy.test()"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/Makefile.inc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/Makefile.inc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/Makefile.inc	(revision 18231)
@@ -0,0 +1,26 @@
+EXE	=
+LIB	= .a
+OBJ	= .o
+MEX	= .mexa64
+
+MAKE	= make
+AR	= ar
+ARFLAGS	= -ruv
+CAT	= cat
+CCS	= gcc
+CCP     = mpicc
+CCD     = mpicc
+CCM	= ${MATLAB_DIR}/bin/mex
+#CFLAGS	= -m64 -O3 -std=c99 -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DMATLAB -fPIC -I${MATLAB_DIR}/extern/include
+CFLAGS	= -m64 -O3 -std=c99 -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -fPIC
+#LDFLAGS	= -lz -lm -lrt -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat
+#LDFLAGS	= -lz -lm -lrt -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat
+LDFLAGS	= -lz -lm -lrt
+MFLAGS	= -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include -largeArrayDims
+CP	= cp
+LEX	= flex
+LN	= ln
+MKDIR	= mkdir
+MV	= mv
+RANLIB	= ranlib
+YACC	= yacc
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap.m	(revision 18231)
@@ -0,0 +1,66 @@
+%
+%  function to call the gmap module of the scotch partitioner.
+%
+%  [maptab]=gmap(adj_mat,vlist,vwgt,ewgt,atype,apar,...
+%                options)
+%
+%  where the required input is:
+%    adj_mat    (double [sparse nv x nv], vertex adjacency matrix)
+%    vlist      (double [nv], vertex labels or [])
+%    vwgt       (double [nv], vertex weights (integers) or [])
+%    ewgt       (double [sparse nv x nv], edge weights (integers) or [])
+%    atype      (character, architecture type)
+%                 'cmplt'      complete graph
+%                 'cmpltw'     weighted complete graph
+%                 'hcub'       binary hypercube
+%                 'leaf'       tree-leaf architecture
+%                 'mesh2d'     bidimensional array
+%                 'mesh3d'     tridimensional array
+%                 'torus2d'    bidimensional array with wraparound edges
+%                 'torus3d'    tridimensional array with wraparound edges
+%    apars      (double, architecture params (corresponding to atype))
+%                 [size]                     cmplt
+%                 [size load0 load1 ...]     cmpltw
+%                 [dim]                      hcub
+%                 [height cluster weight]    leaf
+%                 [dimX dimY]                mesh2d
+%                 [dimX dimY dimZ]           mesh3d
+%                 [dimX dimY]                torus2d
+%                 [dimX dimY dimZ]           torus3d
+%
+%  the required output is:
+%    maptab     (double [nv x 2], vertex labels and partitions)
+%
+%  the optional input is:
+%    options    (character, options to gmap)
+%               "  -h         : Display this help"
+%               "  -m<strat>  : Set mapping strategy (see user's manual)"
+%               "  -s<obj>    : Force unity weights on <obj>:"
+%               "                 e  : edges"
+%               "                 v  : vertices"
+%               "  -V         : Print program version and copyright"
+%               "  -v<verb>   : Set verbose mode to <verb>:"
+%               "                 m  : mapping information"
+%               "                 s  : strategy information"
+%               "                 t  : timing information"
+%               ""
+%               "See default strategy with option '-vs'"
+%
+function [maptab]=gmap(adj_mat,vlist,vwgt,ewgt,atype,apars,...
+                       varargin)
+
+if ~nargin
+    help gmap
+    return
+end
+
+%  gmap_mex uses static variables, so clear those out before every run
+clear gmap_mex
+
+[maptab]=gmap_mex(adj_mat,vlist,vwgt,ewgt,atype,apars,...
+                  varargin{:});
+
+%  doesn't hurt to clear out after every run, too
+clear gmap_mex
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap_mex.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap_mex.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmap_mex.c	(revision 18231)
@@ -0,0 +1,286 @@
+
+#define THISFUNCTION "Gmap"
+
+/*  Gmap 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
+
+void GmapUsage( void );
+
+
+int
+gmapx (
+	int                 (**pmaptabi)[2],
+	int                 argcm,
+	char                *argvm[],
+	int                 nvi,
+	int                 ne2i,
+	int                 *ir,
+	int                 *jc,
+	int                 *vli,
+	int                 *vwi,
+	int                 *ewi,
+	char                archtyp[],
+	int                 nai,
+	int                 *api);
+
+/******************************/
+/*                            */
+/* This is the main function. */
+/*                            */
+/******************************/
+
+void mexFunction( int nlhs,
+				  mxArray *plhs[],
+				  int nrhs,
+				  const mxArray *prhs[] )
+{
+	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",
+				  THISFUNCTION,argvm[isi]);
+		isi++;
+	}
+	else {
+		argvm[isi] = (char *) calloc(5+1,sizeof(char));
+		strcpy(argvm[isi],"gpart");
+		mexPrintf("%s -- Using \"%s\" entry point.\n",
+				  THISFUNCTION,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",
+				  THISFUNCTION,argvm[isi]);
+		isi++;
+		imi++;
+	}
+
+	if (!mxIsNumeric(prhs[imi]) || (!mxIsEmpty(prhs[imi]) && !mxIsSparse(prhs[imi]))) {
+		mexPrintf("%s -- Adjacency matrix must be numeric and sparse.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]),mxGetNzmax(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex label vector must be numeric.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex weight vector must be numeric.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,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",THISFUNCTION);
+		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",
+				  THISFUNCTION,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",THISFUNCTION);
+			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",
+					  THISFUNCTION,archtyp);
+		}
+		imi++;
+
+		if (!mxIsNumeric(prhs[imi])) {
+			mexPrintf("%s -- Architecture parameter vector must be numeric.\n",THISFUNCTION);
+			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",
+					  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+		}
+		imi++;
+	}
+
+	while (imi < nrhs) {
+		if (!mxIsChar(prhs[imi])) {
+			mexPrintf("%s -- prhs[%d] must be character.\n",THISFUNCTION,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",THISFUNCTION,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;
+}
+
+void GmapUsage( void )
+{
+
+    mexPrintf("\n");
+    mexPrintf("Usage: [maptab]=Gmap_mex(adjmat,vertlb,vertwt,edgewt,archtyp,archpar,\n");
+    mexPrintf("                         Scotch-specific parameters);\n");
+    mexPrintf("\n");
+
+    return;
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmapx.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmapx.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gmapx.c	(revision 18231)
@@ -0,0 +1,385 @@
+/* Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS
+**
+** This file is part of the Scotch software package for static mapping,
+** graph partitioning and sparse matrix ordering.
+**
+** This software is governed by the CeCILL-C license under French law
+** and abiding by the rules of distribution of free software. You can
+** use, modify and/or redistribute the software under the terms of the
+** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
+** URL: "http://www.cecill.info".
+** 
+** As a counterpart to the access to the source code and rights to copy,
+** modify and redistribute granted by the license, users are provided
+** only with a limited warranty and the software's author, the holder of
+** the economic rights, and the successive licensors have only limited
+** liability.
+** 
+** In this respect, the user's attention is drawn to the risks associated
+** with loading, using, modifying and/or developing or reproducing the
+** software by the user in light of its specific status of free software,
+** that may mean that it is complicated to manipulate, and that also
+** therefore means that it is reserved for developers and experienced
+** professionals having in-depth computer knowledge. Users are therefore
+** encouraged to load and test the software's suitability as regards
+** their requirements in conditions enabling the security of their
+** systems and/or data to be ensured and, more generally, to use and
+** operate it in the same conditions as regards security.
+** 
+** The fact that you are presently reading this means that you have had
+** knowledge of the CeCILL-C license and that you accept its terms.
+*/
+/************************************************************/
+/**                                                        **/
+/**   NAME       : gmap.c                                  **/
+/**                                                        **/
+/**   AUTHOR     : Francois PELLEGRINI                     **/
+/**                                                        **/
+/**   FUNCTION   : Part of a graph mapping software.       **/
+/**                This module contains the main function. **/
+/**                                                        **/
+/**   DATES      : # Version 0.0  : from : 05 jan 1993     **/
+/**                                 to     12 may 1993     **/
+/**                # Version 1.1  : from : 15 oct 1993     **/
+/**                                 to     15 oct 1993     **/
+/**                # Version 1.3  : from : 06 apr 1994     **/
+/**                                 to     18 may 1994     **/
+/**                # Version 2.0  : from : 06 jun 1994     **/
+/**                                 to     17 nov 1994     **/
+/**                # Version 2.1  : from : 07 apr 1995     **/
+/**                                 to     18 jun 1995     **/
+/**                # Version 3.0  : from : 01 jul 1995     **/
+/**                                 to     02 oct 1995     **/
+/**                # Version 3.1  : from : 07 nov 1995     **/
+/**                                 to     25 apr 1996     **/
+/**                # Version 3.2  : from : 24 sep 1996     **/
+/**                                 to     26 may 1998     **/
+/**                # Version 3.3  : from : 19 oct 1998     **/
+/**                                 to   : 30 mar 1999     **/
+/**                # Version 3.4  : from : 03 feb 2000     **/
+/**                                 to   : 03 feb 2000     **/
+/**                # Version 4.0  : from : 16 jan 2004     **/
+/**                                 to   : 27 dec 2004     **/
+/**                # Version 5.0  : from : 23 dec 2007     **/
+/**                                 to   : 18 jun 2008     **/
+/**                                                        **/
+/************************************************************/
+
+/*
+**  The defines and includes.
+*/
+
+#define GMAP
+
+#include "module.h"
+#include "common.h"
+#include "scotch.h"
+#include "gmap.h"
+
+/*
+**  The static variables.
+*/
+
+static int                  C_partNbr = 2;        /* Default number of parts     */
+static int                  C_paraNum = 0;        /* Number of parameters        */
+static int                  C_paraNbr = 0;        /* No parameters for mapping   */
+static int                  C_fileNum = 0;        /* Number of file in arg list  */
+static int                  C_fileNbr = 4;        /* Number of files for mapping */
+static File                 C_fileTab[C_FILENBR] = { /* File array               */
+                              { "-", NULL, "r" },
+                              { "-", NULL, "r" },
+                              { "-", NULL, "w" },
+                              { "-", NULL, "w" } };
+
+static const char *         C_usageList[] = {     /* Usage */
+  "gmap [<input source file> [<input target file> [<output mapping file> [<output log file>]]]] <options>",
+  "gpart [<nparts>] [<input source file> [<output mapping file> [<output log file>]]] <options>",
+  "  -h         : Display this help",
+  "  -m<strat>  : Set mapping strategy (see user's manual)",
+  "  -s<obj>    : Force unity weights on <obj>:",
+  "                 e  : edges",
+  "                 v  : vertices",
+  "  -V         : Print program version and copyright",
+  "  -v<verb>   : Set verbose mode to <verb>:",
+  "                 m  : mapping information",
+  "                 s  : strategy information",
+  "                 t  : timing information",
+  "",
+  "See default strategy with option '-vs'",
+  NULL };
+
+/******************************/
+/*                            */
+/* This is the main function. */
+/*                            */
+/******************************/
+
+int
+gmapx (
+  int                 (**pmaptabi)[2],
+  int                 argcm,
+  char                *argvm[],
+  int                 nvi,
+  int                 ne2i,
+  int                 *ir,
+  int                 *jc,
+  int                 *vli,
+  int                 *vwi,
+  int                 *ewi,
+  char                archtyp[],
+  int                 nai,
+  int                 *api)
+{
+  SCOTCH_Graph        grafdat;                    /* Source graph            */
+  SCOTCH_Num          grafflag;                   /* Source graph properties */
+  SCOTCH_Arch         archdat;                    /* Target architecture     */
+  SCOTCH_Strat        stradat;                    /* Mapping strategy        */
+  SCOTCH_Mapping      mapdat;                     /* Mapping data            */
+  Clock               runtime[2];                 /* Timing variables        */
+  SCOTCH_Num          nvert =0;
+  SCOTCH_Num          nedge2=0;
+  SCOTCH_Num*         adjir  =NULL;
+  SCOTCH_Num*         adjjc  =NULL;
+  SCOTCH_Num*         vertlab=NULL;
+  SCOTCH_Num*         vertwgt=NULL;
+  SCOTCH_Num*         edgewgt=NULL;
+  SCOTCH_Num          napar =0;
+  SCOTCH_Num*         archpar=NULL;
+  SCOTCH_Num          (*maptab)[2]=NULL;
+  int                 (*maptabi)[2]=NULL;
+  int                 flagval;
+  int                 i,j,k;
+
+/*  reset static variables from previous runs (jes, 4/27/10)  */
+
+  C_partNbr = 2;        /* Default number of parts     */
+  C_paraNum = 0;        /* Number of parameters        */
+  C_paraNbr = 0;        /* No parameters for mapping   */
+  C_fileNum = 0;        /* Number of file in arg list  */
+  C_fileNbr = 4;        /* Number of files for mapping */
+  for (i=0; i<C_FILENBR; i++) {
+    C_fileTab[i].name = "-";
+    C_fileTab[i].pntr = NULL;
+    if (i < 2)
+      C_fileTab[i].mode = "r";
+    else
+      C_fileTab[i].mode = "w";
+  }
+
+/*  convert input arguments to scotch data types  */
+
+  nvert =(SCOTCH_Num)nvi;
+  nedge2=(SCOTCH_Num)ne2i;
+
+  if (ir && jc) {
+    adjir = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      adjir[i]=(SCOTCH_Num)ir[i];
+    adjjc = (SCOTCH_Num *) malloc((nvert+1)*sizeof(SCOTCH_Num));
+    for (i=0; i<(nvert+1); i++)
+      adjjc[i]=(SCOTCH_Num)jc[i];
+  }
+
+  if (vli) {
+    vertlab = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertlab[i]=(SCOTCH_Num)vli[i];
+  }
+
+  if (vwi) {
+    vertwgt = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertwgt[i]=(SCOTCH_Num)vwi[i];
+  }
+
+  if (ewi) {
+    edgewgt = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      edgewgt[i]=(SCOTCH_Num)ewi[i];
+  }
+
+  napar =(SCOTCH_Num)nai;
+
+  if (api) {
+    archpar = (SCOTCH_Num *) malloc(nai*sizeof(SCOTCH_Num));
+    for (i=0; i<nai; i++)
+      archpar[i]=(SCOTCH_Num)api[i];
+  }
+
+/*  start scotch processing  */
+
+  flagval = C_FLAGNONE;                           /* Default behavior */
+  i = strlen (argvm[0]);
+  if ((i >= 5) && (strncmp (argvm[0] + i - 5, "gpart", 5) == 0)) {
+    flagval |= C_FLAGPART;
+    C_paraNbr = 1;                                /* One more parameter       */
+    C_fileNbr = 3;                                /* One less file to provide */
+    errorProg ("gpart");
+  }
+  else
+    errorProg ("gmap");
+
+  intRandResetStatic ();
+  intRandInit ();
+
+  if ((argcm >= 2) && (argvm[1][0] == '?')) {       /* If need for help */
+    usagePrint (stdout, C_usageList);
+    return     (0);
+  }
+
+  grafflag = 0;                                   /* Use vertex and edge weights  */
+  SCOTCH_stratInit (&stradat);                    /* Set default mapping strategy */
+
+  for (i = 0; i < C_FILENBR; i ++)                /* Set default stream pointers */
+    C_fileTab[i].pntr = (C_fileTab[i].mode[0] == 'r') ? stdin : stdout;
+  for (i = 1; i < argcm; i ++) {                   /* Loop for all option codes                        */
+    if ((argvm[i][0] != '-') || (argvm[i][1] == '\0') || (argvm[i][1] == '.')) { /* If found a file name */
+      if (C_paraNum < C_paraNbr) {                /* If number of parameters not reached              */
+        if ((C_partNbr = atoi (argvm[i])) < 1)     /* Get the number of parts                          */
+          errorPrint ("main: invalid number of parts (\"%s\")", argvm[i]);
+        C_paraNum ++;
+        continue;                                 /* Process the other parameters */
+      }
+      if (C_fileNum < C_fileNbr)                  /* A file name has been given */
+        C_fileTab[C_fileNum ++].name = argvm[i];
+      else
+        errorPrint ("main: too many file names given");
+    }
+    else {                                        /* If found an option name */
+      switch (argvm[i][1]) {
+        case 'H' :                                /* Give the usage message */
+        case 'h' :
+          usagePrint (stdout, C_usageList);
+          return     (0);
+        case 'M' :
+        case 'm' :
+          SCOTCH_stratExit (&stradat);
+          SCOTCH_stratInit (&stradat);
+          SCOTCH_stratGraphMap (&stradat, &argvm[i][2]);
+          break;
+        case 'S' :
+        case 's' :                                /* Source graph parameters */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'E' :
+              case 'e' :
+                grafflag |= 2;                    /* Do not load edge weights */
+                break;
+              case 'V' :
+              case 'v' :
+                grafflag |= 1;                    /* Do not load vertex weights */
+                break;
+              default :
+                errorPrint ("main: invalid source graph option (\"%c\")", argvm[i][j]);
+            }
+          }
+          break;
+        case 'V' :
+          fprintf (stderr, "gmap/gpart, version %s - F. Pellegrini\n", SCOTCH_VERSION);
+          fprintf (stderr, "Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS, France\n");
+          fprintf (stderr, "This software is libre/free software under CeCILL-C -- see the user's manual for more information\n");
+          return  (0);
+        case 'v' :                                /* Output control info */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'M' :
+              case 'm' :
+                flagval |= C_FLAGVERBMAP;
+                break;
+              case 'S' :
+              case 's' :
+                flagval |= C_FLAGVERBSTR;
+                break;
+              case 'T' :
+              case 't' :
+                flagval |= C_FLAGVERBTIM;
+                break;
+              default :
+                errorPrint ("main: unprocessed parameter \"%c\" in \"%s\"", argvm[i][j], argvm[i]);
+            }
+          }
+          break;
+        default :
+          errorPrint ("main: unprocessed option (\"%s\")", argvm[i]);
+      }
+    }
+  }
+  if ((flagval & C_FLAGPART) != 0) {              /* If program run as the partitioner            */
+    C_fileTab[3].name = C_fileTab[2].name;        /* Put provided file names at their right place */
+    C_fileTab[2].name = C_fileTab[1].name;
+    C_fileTab[1].name = "-";
+  }
+
+  fileBlockOpen (C_fileTab, C_FILENBR);           /* Open all files */
+
+  clockInit  (&runtime[0]);
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphInit (&grafdat);                    /* Create graph structure         */
+  SCOTCH_graphLoad (&grafdat, C_filepntrsrcinp, -1, grafflag, nvert, nedge2, adjir, adjjc, vertlab, vertwgt, edgewgt); /* Read source graph */
+
+  SCOTCH_archInit (&archdat);                     /* Create architecture structure          */
+  if ((flagval & C_FLAGPART) != 0)                /* If program run as the partitioner      */
+    SCOTCH_archCmplt (&archdat, C_partNbr);       /* Create a complete graph of proper size */
+  else
+    SCOTCH_archLoad (&archdat, C_filepntrtgtinp, archtyp, napar, archpar); /* Read target architecture */
+
+  clockStop  (&runtime[0]);                       /* Get input time */
+  clockInit  (&runtime[1]);
+  clockStart (&runtime[1]);
+
+  SCOTCH_graphMapInit    (&grafdat, &mapdat, &archdat, NULL);
+  SCOTCH_graphMapCompute (&grafdat, &mapdat, &stradat); /* Perform mapping */
+
+  clockStop  (&runtime[1]);                       /* Get computation time */
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphMapSave (&nvert, &maptab, &grafdat, &mapdat, C_filepntrmapout); /* Write mapping */
+
+/*  convert output arguments from scotch data types  */
+
+  if (maptab) {
+    *pmaptabi = (int (*)[2]) malloc(nvert*2*sizeof(int));
+    maptabi  = *pmaptabi;
+    for (j=0; j<2; j++)
+      for (i=0; i<nvert; i++)
+          maptabi[i][j]=(int)maptab[i][j];
+    free(maptab);
+  }
+
+  clockStop (&runtime[0]);                        /* Get output time */
+
+  if (flagval & C_FLAGVERBSTR) {
+    fprintf (C_filepntrlogout, "S\tStrat=");
+    SCOTCH_stratSave (&stradat, C_filepntrlogout);
+    putc ('\n', C_filepntrlogout);
+  }
+  if (flagval & C_FLAGVERBTIM) {
+    fprintf (C_filepntrlogout, "T\tMapping\t\t%g\nT\tI/O\t\t%g\nT\tTotal\t\t%g\n",
+             (double) clockVal (&runtime[1]),
+             (double) clockVal (&runtime[0]),
+             (double) clockVal (&runtime[0]) +
+             (double) clockVal (&runtime[1]));
+  }
+  if (flagval & C_FLAGVERBMAP)
+    SCOTCH_graphMapView (&grafdat, &mapdat, C_filepntrlogout);
+
+  fileBlockClose (C_fileTab, C_FILENBR);          /* Always close explicitely to end eventual (un)compression tasks */
+
+  SCOTCH_graphMapExit (&grafdat, &mapdat);
+  SCOTCH_graphExit    (&grafdat);
+  SCOTCH_stratExit    (&stradat);
+  SCOTCH_archExit     (&archdat);
+
+  if (archpar) free(archpar);
+  if (edgewgt) free(edgewgt);
+  if (vertwgt) free(vertwgt);
+  if (vertlab) free(vertlab);
+  if (adjjc) free(adjjc);
+  if (adjir) free(adjir);
+
+#ifdef COMMON_PTHREAD
+  pthread_exit ((void *) 0);                      /* Allow potential (un)compression tasks to complete */
+#endif /* COMMON_PTHREAD */
+  return (0);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gpart.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gpart.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/gpart.m	(revision 18231)
@@ -0,0 +1,50 @@
+%
+%  function to call the gpart module of the scotch partitioner.
+%  (note that gpart is just a simplied entry into gmap.)
+%
+%  [maptab]=gpart(npart,adj_mat,vlist,vwgt,ewgt,...
+%                 options)
+%
+%  where the required input is:
+%    npart      (double, number of parts for 'cmplt' architecture)
+%    adj_mat    (double [sparse nv x nv], vertex adjacency matrix)
+%    vlist      (double [nv], vertex labels or [])
+%    vwgt       (double [nv], vertex weights (integers) or [])
+%    ewgt       (double [sparse nv x nv], edge weights (integers) or [])
+%
+%  the required output is:
+%    maptab     (double [nv x 2], vertex labels and partitions)
+%
+%  the optional input is:
+%    options    (character, options to gpart)
+%               "  -h         : Display this help"
+%               "  -m<strat>  : Set mapping strategy (see user's manual)"
+%               "  -s<obj>    : Force unity weights on <obj>:"
+%               "                 e  : edges"
+%               "                 v  : vertices"
+%               "  -V         : Print program version and copyright"
+%               "  -v<verb>   : Set verbose mode to <verb>:"
+%               "                 m  : mapping information"
+%               "                 s  : strategy information"
+%               "                 t  : timing information"
+%               ""
+%               "See default strategy with option '-vs'"
+%
+function [maptab]=gpart(npart,adj_mat,vlist,vwgt,ewgt,...
+                        varargin)
+
+if ~nargin
+    help gpart
+    return
+end
+
+%  gmap_mex uses static variables, so clear those out before every run
+clear gmap_mex
+
+[maptab]=gmap_mex(npart,adj_mat,vlist,vwgt,ewgt,...
+                  varargin{:});
+
+%  doesn't hurt to clear out after every run, too
+clear gmap_mex
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/install.sh	(revision 18231)
@@ -0,0 +1,57 @@
+#!/bin/bash
+set -eu
+
+# Some cleanup
+rm -rf scotch_5.1
+rm -rf src 
+rm -rf install 
+
+# Create src and install directories
+mkdir src install 
+
+#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 
+tar -xvzf scotch_5.1.6.tar.gz
+
+# Apply patches (all at once, since many)
+# (written by diff -rc old_src new_src > scotch.patch)
+patch -p0 < scotch.patch
+
+# Move scotch to src directory
+mv scotch_5.1/* src
+rm -rf scotch_5.1
+
+# Build scotch
+cp -p Makefile.inc src/src
+cp -p gmap_mex.c src/src/scotch
+cp -p gmapx.c src/src/scotch
+cd src/src
+# For stand-alone scotch modules:
+make scotch
+make clean
+# For no-file-io scotch modules:
+make nfioscotch
+# Clean up
+make clean
+cd ../..
+
+# Populate install directory
+cp -pr src/grf install
+cp -pr src/tgt install
+cp -pr src/doc install
+cp -pr src/man install
+mkdir install/include
+cp -p src/src/libscotch/module.h install/include/scotch_module.h
+cp -p src/src/libscotch/common.h install/include/scotch_common.h
+cp -p src/include/scotch.h install/include/
+cp -p src/src/scotch/gmap.h install/include/scotch_gmap.h
+mkdir install/lib
+mv src/lib/* install/lib
+mkdir install/bin
+mv src/bin/* install/bin
+#cp -p gmap.m install/bin
+#cp -p gpart.m install/bin
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmap.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmap.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmap.c	(revision 18231)
@@ -0,0 +1,278 @@
+
+#define THISFUNCTION "Gmap"
+
+/*  Gmap structures and prototypes  */
+
+#include "mat.h"
+#include "mex.h"
+#include "matrix.h"
+
+void GmapUsage( void );
+
+
+int
+Gmapx (
+	int                 (**pmaptabi)[2],
+	int                 argcm,
+	char                *argvm[],
+	int                 nvi,
+	int                 ne2i,
+	int                 *ir,
+	int                 *jc,
+	int                 *vli,
+	int                 *vwi,
+	int                 *ewi,
+	char                archtyp[],
+	int                 nai,
+	int                 *api);
+
+/******************************/
+/*                            */
+/* This is the main function. */
+/*                            */
+/******************************/
+
+void mexFunction( int nlhs,
+				  mxArray *plhs[],
+				  int nrhs,
+				  const mxArray *prhs[] )
+{
+	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",
+				  THISFUNCTION,argvm[isi]);
+		isi++;
+	}
+	else {
+		argvm[isi] = (char *) calloc(5+1,sizeof(char));
+		strcpy(argvm[isi],"Gpart");
+		mexPrintf("%s -- Using \"%s\" entry point.\n",
+				  THISFUNCTION,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",
+				  THISFUNCTION,argvm[isi]);
+		isi++;
+		imi++;
+	}
+
+	if (!mxIsNumeric(prhs[imi]) || (!mxIsEmpty(prhs[imi]) && !mxIsSparse(prhs[imi]))) {
+		mexPrintf("%s -- Adjacency matrix must be numeric and sparse.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]),mxGetNzmax(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex label vector must be numeric.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex weight vector must be numeric.\n",THISFUNCTION);
+		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",
+				  THISFUNCTION,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",THISFUNCTION);
+		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",
+				  THISFUNCTION,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",THISFUNCTION);
+			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",
+					  THISFUNCTION,archtyp);
+		}
+		imi++;
+
+		if (!mxIsNumeric(prhs[imi])) {
+			mexPrintf("%s -- Architecture parameter vector must be numeric.\n",THISFUNCTION);
+			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",
+					  THISFUNCTION,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+		}
+		imi++;
+	}
+
+	while (imi < nrhs) {
+		if (!mxIsChar(prhs[imi])) {
+			mexPrintf("%s -- prhs[%d] must be character.\n",THISFUNCTION,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",THISFUNCTION,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 (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);
+	if (argvm) {
+		for (i=argcm-1; i>=0; i--)
+			free(argvm[i]);
+		free(argvm);
+	}
+
+	return;
+}
+
+void GmapUsage( void )
+{
+
+    mexPrintf("\n");
+    mexPrintf("Usage: [maptab]=Gmap(adjmat,vertlb,vertwt,edgewt,archtyp,archpar,\n");
+    mexPrintf("                         Scotch-specific parameters);\n");
+    mexPrintf("\n");
+
+    return;
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmapx.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmapx.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Gmapx.c	(revision 18231)
@@ -0,0 +1,385 @@
+/* Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS
+**
+** This file is part of the Scotch software package for static mapping,
+** graph partitioning and sparse matrix ordering.
+**
+** This software is governed by the CeCILL-C license under French law
+** and abiding by the rules of distribution of free software. You can
+** use, modify and/or redistribute the software under the terms of the
+** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
+** URL: "http://www.cecill.info".
+** 
+** As a counterpart to the access to the source code and rights to copy,
+** modify and redistribute granted by the license, users are provided
+** only with a limited warranty and the software's author, the holder of
+** the economic rights, and the successive licensors have only limited
+** liability.
+** 
+** In this respect, the user's attention is drawn to the risks associated
+** with loading, using, modifying and/or developing or reproducing the
+** software by the user in light of its specific status of free software,
+** that may mean that it is complicated to manipulate, and that also
+** therefore means that it is reserved for developers and experienced
+** professionals having in-depth computer knowledge. Users are therefore
+** encouraged to load and test the software's suitability as regards
+** their requirements in conditions enabling the security of their
+** systems and/or data to be ensured and, more generally, to use and
+** operate it in the same conditions as regards security.
+** 
+** The fact that you are presently reading this means that you have had
+** knowledge of the CeCILL-C license and that you accept its terms.
+*/
+/************************************************************/
+/**                                                        **/
+/**   NAME       : gmap.c                                  **/
+/**                                                        **/
+/**   AUTHOR     : Francois PELLEGRINI                     **/
+/**                                                        **/
+/**   FUNCTION   : Part of a graph mapping software.       **/
+/**                This module contains the main function. **/
+/**                                                        **/
+/**   DATES      : # Version 0.0  : from : 05 jan 1993     **/
+/**                                 to     12 may 1993     **/
+/**                # Version 1.1  : from : 15 oct 1993     **/
+/**                                 to     15 oct 1993     **/
+/**                # Version 1.3  : from : 06 apr 1994     **/
+/**                                 to     18 may 1994     **/
+/**                # Version 2.0  : from : 06 jun 1994     **/
+/**                                 to     17 nov 1994     **/
+/**                # Version 2.1  : from : 07 apr 1995     **/
+/**                                 to     18 jun 1995     **/
+/**                # Version 3.0  : from : 01 jul 1995     **/
+/**                                 to     02 oct 1995     **/
+/**                # Version 3.1  : from : 07 nov 1995     **/
+/**                                 to     25 apr 1996     **/
+/**                # Version 3.2  : from : 24 sep 1996     **/
+/**                                 to     26 may 1998     **/
+/**                # Version 3.3  : from : 19 oct 1998     **/
+/**                                 to   : 30 mar 1999     **/
+/**                # Version 3.4  : from : 03 feb 2000     **/
+/**                                 to   : 03 feb 2000     **/
+/**                # Version 4.0  : from : 16 jan 2004     **/
+/**                                 to   : 27 dec 2004     **/
+/**                # Version 5.0  : from : 23 dec 2007     **/
+/**                                 to   : 18 jun 2008     **/
+/**                                                        **/
+/************************************************************/
+
+/*
+**  The defines and includes.
+*/
+
+#define GMAP
+
+#include "module.h"
+#include "common.h"
+#include "scotch.h"
+#include "gmap.h"
+
+/*
+**  The static variables.
+*/
+
+static int                  C_partNbr = 2;        /* Default number of parts     */
+static int                  C_paraNum = 0;        /* Number of parameters        */
+static int                  C_paraNbr = 0;        /* No parameters for mapping   */
+static int                  C_fileNum = 0;        /* Number of file in arg list  */
+static int                  C_fileNbr = 4;        /* Number of files for mapping */
+static File                 C_fileTab[C_FILENBR] = { /* File array               */
+                              { "-", NULL, "r" },
+                              { "-", NULL, "r" },
+                              { "-", NULL, "w" },
+                              { "-", NULL, "w" } };
+
+static const char *         C_usageList[] = {     /* Usage */
+  "gmap [<input source file> [<input target file> [<output mapping file> [<output log file>]]]] <options>",
+  "gpart [<nparts>] [<input source file> [<output mapping file> [<output log file>]]] <options>",
+  "  -h         : Display this help",
+  "  -m<strat>  : Set mapping strategy (see user's manual)",
+  "  -s<obj>    : Force unity weights on <obj>:",
+  "                 e  : edges",
+  "                 v  : vertices",
+  "  -V         : Print program version and copyright",
+  "  -v<verb>   : Set verbose mode to <verb>:",
+  "                 m  : mapping information",
+  "                 s  : strategy information",
+  "                 t  : timing information",
+  "",
+  "See default strategy with option '-vs'",
+  NULL };
+
+/******************************/
+/*                            */
+/* This is the main function. */
+/*                            */
+/******************************/
+
+int
+Gmapx (
+  int                 (**pmaptabi)[2],
+  int                 argcm,
+  char                *argvm[],
+  int                 nvi,
+  int                 ne2i,
+  int                 *ir,
+  int                 *jc,
+  int                 *vli,
+  int                 *vwi,
+  int                 *ewi,
+  char                archtyp[],
+  int                 nai,
+  int                 *api)
+{
+  SCOTCH_Graph        grafdat;                    /* Source graph            */
+  SCOTCH_Num          grafflag;                   /* Source graph properties */
+  SCOTCH_Arch         archdat;                    /* Target architecture     */
+  SCOTCH_Strat        stradat;                    /* Mapping strategy        */
+  SCOTCH_Mapping      mapdat;                     /* Mapping data            */
+  Clock               runtime[2];                 /* Timing variables        */
+  SCOTCH_Num          nvert =0;
+  SCOTCH_Num          nedge2=0;
+  SCOTCH_Num*         adjir  =NULL;
+  SCOTCH_Num*         adjjc  =NULL;
+  SCOTCH_Num*         vertlab=NULL;
+  SCOTCH_Num*         vertwgt=NULL;
+  SCOTCH_Num*         edgewgt=NULL;
+  SCOTCH_Num          napar =0;
+  SCOTCH_Num*         archpar=NULL;
+  SCOTCH_Num          (*maptab)[2]=NULL;
+  int                 (*maptabi)[2]=NULL;
+  int                 flagval;
+  int                 i,j,k;
+
+/*  reset static variables from previous runs (jes, 4/27/10)  */
+
+  C_partNbr = 2;        /* Default number of parts     */
+  C_paraNum = 0;        /* Number of parameters        */
+  C_paraNbr = 0;        /* No parameters for mapping   */
+  C_fileNum = 0;        /* Number of file in arg list  */
+  C_fileNbr = 4;        /* Number of files for mapping */
+  for (i=0; i<C_FILENBR; i++) {
+    C_fileTab[i].name = "-";
+    C_fileTab[i].pntr = NULL;
+    if (i < 2)
+      C_fileTab[i].mode = "r";
+    else
+      C_fileTab[i].mode = "w";
+  }
+
+/*  convert input arguments to scotch data types  */
+
+  nvert =(SCOTCH_Num)nvi;
+  nedge2=(SCOTCH_Num)ne2i;
+
+  if (ir && jc) {
+    adjir = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      adjir[i]=(SCOTCH_Num)ir[i];
+    adjjc = (SCOTCH_Num *) malloc((nvert+1)*sizeof(SCOTCH_Num));
+    for (i=0; i<(nvert+1); i++)
+      adjjc[i]=(SCOTCH_Num)jc[i];
+  }
+
+  if (vli) {
+    vertlab = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertlab[i]=(SCOTCH_Num)vli[i];
+  }
+
+  if (vwi) {
+    vertwgt = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertwgt[i]=(SCOTCH_Num)vwi[i];
+  }
+
+  if (ewi) {
+    edgewgt = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      edgewgt[i]=(SCOTCH_Num)ewi[i];
+  }
+
+  napar =(SCOTCH_Num)nai;
+
+  if (api) {
+    archpar = (SCOTCH_Num *) malloc(nai*sizeof(SCOTCH_Num));
+    for (i=0; i<nai; i++)
+      archpar[i]=(SCOTCH_Num)api[i];
+  }
+
+/*  start scotch processing  */
+
+  flagval = C_FLAGNONE;                           /* Default behavior */
+  i = strlen (argvm[0]);
+  if ((i >= 5) && (strncmp (argvm[0] + i - 5, "Gpart", 5) == 0)) {
+    flagval |= C_FLAGPART;
+    C_paraNbr = 1;                                /* One more parameter       */
+    C_fileNbr = 3;                                /* One less file to provide */
+    errorProg ("Gpart");
+  }
+  else
+    errorProg ("Gmap");
+
+  intRandResetStatic ();
+  intRandInit ();
+
+  if ((argcm >= 2) && (argvm[1][0] == '?')) {       /* If need for help */
+    usagePrint (stdout, C_usageList);
+    return     (0);
+  }
+
+  grafflag = 0;                                   /* Use vertex and edge weights  */
+  SCOTCH_stratInit (&stradat);                    /* Set default mapping strategy */
+
+  for (i = 0; i < C_FILENBR; i ++)                /* Set default stream pointers */
+    C_fileTab[i].pntr = (C_fileTab[i].mode[0] == 'r') ? stdin : stdout;
+  for (i = 1; i < argcm; i ++) {                   /* Loop for all option codes                        */
+    if ((argvm[i][0] != '-') || (argvm[i][1] == '\0') || (argvm[i][1] == '.')) { /* If found a file name */
+      if (C_paraNum < C_paraNbr) {                /* If number of parameters not reached              */
+        if ((C_partNbr = atoi (argvm[i])) < 1)     /* Get the number of parts                          */
+          errorPrint ("main: invalid number of parts (\"%s\")", argvm[i]);
+        C_paraNum ++;
+        continue;                                 /* Process the other parameters */
+      }
+      if (C_fileNum < C_fileNbr)                  /* A file name has been given */
+        C_fileTab[C_fileNum ++].name = argvm[i];
+      else
+        errorPrint ("main: too many file names given");
+    }
+    else {                                        /* If found an option name */
+      switch (argvm[i][1]) {
+        case 'H' :                                /* Give the usage message */
+        case 'h' :
+          usagePrint (stdout, C_usageList);
+          return     (0);
+        case 'M' :
+        case 'm' :
+          SCOTCH_stratExit (&stradat);
+          SCOTCH_stratInit (&stradat);
+          SCOTCH_stratGraphMap (&stradat, &argvm[i][2]);
+          break;
+        case 'S' :
+        case 's' :                                /* Source graph parameters */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'E' :
+              case 'e' :
+                grafflag |= 2;                    /* Do not load edge weights */
+                break;
+              case 'V' :
+              case 'v' :
+                grafflag |= 1;                    /* Do not load vertex weights */
+                break;
+              default :
+                errorPrint ("main: invalid source graph option (\"%c\")", argvm[i][j]);
+            }
+          }
+          break;
+        case 'V' :
+          fprintf (stderr, "Gmap/Gpart, version %s - F. Pellegrini\n", SCOTCH_VERSION);
+          fprintf (stderr, "Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS, France\n");
+          fprintf (stderr, "This software is libre/free software under CeCILL-C -- see the user's manual for more information\n");
+          return  (0);
+        case 'v' :                                /* Output control info */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'M' :
+              case 'm' :
+                flagval |= C_FLAGVERBMAP;
+                break;
+              case 'S' :
+              case 's' :
+                flagval |= C_FLAGVERBSTR;
+                break;
+              case 'T' :
+              case 't' :
+                flagval |= C_FLAGVERBTIM;
+                break;
+              default :
+                errorPrint ("main: unprocessed parameter \"%c\" in \"%s\"", argvm[i][j], argvm[i]);
+            }
+          }
+          break;
+        default :
+          errorPrint ("main: unprocessed option (\"%s\")", argvm[i]);
+      }
+    }
+  }
+  if ((flagval & C_FLAGPART) != 0) {              /* If program run as the partitioner            */
+    C_fileTab[3].name = C_fileTab[2].name;        /* Put provided file names at their right place */
+    C_fileTab[2].name = C_fileTab[1].name;
+    C_fileTab[1].name = "-";
+  }
+
+  fileBlockOpen (C_fileTab, C_FILENBR);           /* Open all files */
+
+  clockInit  (&runtime[0]);
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphInit (&grafdat);                    /* Create graph structure         */
+  SCOTCH_graphLoad (&grafdat, C_filepntrsrcinp, -1, grafflag, nvert, nedge2, adjir, adjjc, vertlab, vertwgt, edgewgt); /* Read source graph */
+
+  SCOTCH_archInit (&archdat);                     /* Create architecture structure          */
+  if ((flagval & C_FLAGPART) != 0)                /* If program run as the partitioner      */
+    SCOTCH_archCmplt (&archdat, C_partNbr);       /* Create a complete graph of proper size */
+  else
+    SCOTCH_archLoad (&archdat, C_filepntrtgtinp, archtyp, napar, archpar); /* Read target architecture */
+
+  clockStop  (&runtime[0]);                       /* Get input time */
+  clockInit  (&runtime[1]);
+  clockStart (&runtime[1]);
+
+  SCOTCH_graphMapInit    (&grafdat, &mapdat, &archdat, NULL);
+  SCOTCH_graphMapCompute (&grafdat, &mapdat, &stradat); /* Perform mapping */
+
+  clockStop  (&runtime[1]);                       /* Get computation time */
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphMapSave (&nvert, &maptab, &grafdat, &mapdat, C_filepntrmapout); /* Write mapping */
+
+/*  convert output arguments from scotch data types  */
+
+  if (maptab) {
+    *pmaptabi = (int (*)[2]) malloc(nvert*2*sizeof(int));
+    maptabi  = *pmaptabi;
+    for (j=0; j<2; j++)
+      for (i=0; i<nvert; i++)
+          maptabi[i][j]=(int)maptab[i][j];
+    free(maptab);
+  }
+
+  clockStop (&runtime[0]);                        /* Get output time */
+
+  if (flagval & C_FLAGVERBSTR) {
+    fprintf (C_filepntrlogout, "S\tStrat=");
+    SCOTCH_stratSave (&stradat, C_filepntrlogout);
+    putc ('\n', C_filepntrlogout);
+  }
+  if (flagval & C_FLAGVERBTIM) {
+    fprintf (C_filepntrlogout, "T\tMapping\t\t%g\nT\tI/O\t\t%g\nT\tTotal\t\t%g\n",
+             (double) clockVal (&runtime[1]),
+             (double) clockVal (&runtime[0]),
+             (double) clockVal (&runtime[0]) +
+             (double) clockVal (&runtime[1]));
+  }
+  if (flagval & C_FLAGVERBMAP)
+    SCOTCH_graphMapView (&grafdat, &mapdat, C_filepntrlogout);
+
+  fileBlockClose (C_fileTab, C_FILENBR);          /* Always close explicitely to end eventual (un)compression tasks */
+
+  SCOTCH_graphMapExit (&grafdat, &mapdat);
+  SCOTCH_graphExit    (&grafdat);
+  SCOTCH_stratExit    (&stradat);
+  SCOTCH_archExit     (&archdat);
+
+  if (archpar) free(archpar);
+  if (edgewgt) free(edgewgt);
+  if (vertwgt) free(vertwgt);
+  if (vertlab) free(vertlab);
+  if (adjjc) free(adjjc);
+  if (adjir) free(adjir);
+
+#ifdef COMMON_PTHREAD
+  pthread_exit ((void *) 0);                      /* Allow potential (un)compression tasks to complete */
+#endif /* COMMON_PTHREAD */
+  return (0);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/Makefile	(revision 18231)
@@ -0,0 +1,102 @@
+## Copyright 2004,2007-2009 ENSEIRB, INRIA & CNRS
+##
+## This file is part of the Scotch software package for static mapping,
+## graph partitioning and sparse matrix ordering.
+##
+## This software is governed by the CeCILL-C license under French law
+## and abiding by the rules of distribution of free software. You can
+## use, modify and/or redistribute the software under the terms of the
+## CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
+## URL: "http://www.cecill.info".
+## 
+## As a counterpart to the access to the source code and rights to copy,
+## modify and redistribute granted by the license, users are provided
+## only with a limited warranty and the software's author, the holder of
+## the economic rights, and the successive licensors have only limited
+## liability.
+## 
+## In this respect, the user's attention is drawn to the risks associated
+## with loading, using, modifying and/or developing or reproducing the
+## software by the user in light of its specific status of free software,
+## that may mean that it is complicated to manipulate, and that also
+## therefore means that it is reserved for developers and experienced
+## professionals having in-depth computer knowledge. Users are therefore
+## encouraged to load and test the software's suitability as regards
+## their requirements in conditions enabling the security of their
+## systems and/or data to be ensured and, more generally, to use and
+## operate it in the same conditions as regards security.
+## 
+## The fact that you are presently reading this means that you have had
+## knowledge of the CeCILL-C license and that you accept its terms.
+##
+
+#bindir		= ../../bin
+#includedir	= ../../include
+#libdir		= ../../lib
+#bindir		= ${SCOTCH_DIR}/../src/bin
+#includedir	= ${SCOTCH_DIR}/../src/include
+#libdir		= ${SCOTCH_DIR}/../src/lib
+bindir		= ${SCOTCH_DIR}/bin
+includedir	= ${SCOTCH_DIR}/include
+libdir		= ${SCOTCH_DIR}/lib
+
+##
+##  General inference rules.
+##
+
+#include ../Makefile.inc
+include ${SCOTCH_DIR}/../src/src/Makefile.inc
+
+%$(OBJ)	:	%.c
+				$(CC) $(CFLAGS) -I${SCOTCH_DIR}/../src/src/scotch -I$(includedir) -I${SCOTCH_DIR}/../src/src/libscotch -DSCOTCH_VERSION=\"$(VERSION)\" -c $(<) -o $(@)
+
+%$(MEX)	:	%.c
+		 		$(CCM) $(MFLAGS) -I${SCOTCH_DIR}/../src/src/scotch -I$(includedir) -I${SCOTCH_DIR}/../src/src/libscotch -DSCOTCH_VERSION=\"$(VERSION)\" $(<) -o $(@) -L$(libdir) -l$(SCOTCHLIB) -l$(SCOTCHLIB)errexit $(LDFLAGS)
+
+##
+##  Project rules.
+##
+
+.PHONY				:	mexscotch	mexinstall	clean	realclean
+
+mexscotch			:	clean
+					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO" CC="$(CCS)" CCD="$(CCS)" SCOTCHLIB=nfioscotch \
+                    Gmapx$(OBJ)
+					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include" CC="$(CCS)" LDFLAGS="$(LDFLAGS) -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat Gmapx$(OBJ)" SCOTCHLIB=nfioscotch	\
+					Gmap$(MEX)
+
+mexinstall			:
+					-$(CP) Gmap$(MEX) $(bindir)
+					-$(RM) $(bindir)/Gpart$(MEX)
+					-$(LN) $(bindir)/Gmap$(MEX) $(bindir)/Gpart$(MEX)
+
+clean				:
+					-$(RM) *~ *$(OBJ)
+					-$(RM) Gmap$(MEX)
+
+realclean			:	clean
+
+##
+##  Todo list.
+##
+
+Gmapx$(OBJ)			:	Gmapx.c					\
+					${SCOTCH_DIR}/../src/src/libscotch/module.h			\
+					${SCOTCH_DIR}/../src/src/libscotch/common.h			\
+					$(includedir)/scotch.h			\
+					$(libdir)/libnfioscotch$(LIB)		\
+					$(libdir)/libnfioscotcherrexit$(LIB)	\
+					${SCOTCH_DIR}/../src/src/scotch/gmap.h
+
+Gmap$(MEX)		:	Gmap.c					\
+					${SCOTCH_DIR}/../src/src/libscotch/module.h			\
+					${SCOTCH_DIR}/../src/src/libscotch/common.h			\
+					$(includedir)/scotch.h			\
+					$(libdir)/libnfioscotch$(LIB)		\
+					$(libdir)/libnfioscotcherrexit$(LIB)	\
+					${SCOTCH_DIR}/../src/src/scotch/gmap.h
+
+Gpart$(MEX)		:	Gmap$(MEX)
+					-$(RM) Gpart$(MEX)
+					-$(LN) Gmap$(MEX) Gpart$(MEX)
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/VectorToSparse.c
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/VectorToSparse.c	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/mex/VectorToSparse.c	(revision 18231)
@@ -0,0 +1,138 @@
+
+#define THISFUNCTION "VectorToSparse"
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "mex.h"
+
+
+/* Input Arguments */
+
+#define    IR_IN        prhs[0]
+#define    JC_IN        prhs[1]
+#define    PR_IN        prhs[2]
+#define    M_IN         prhs[3]
+#define    N_IN         prhs[4]
+
+/* Output Arguments */
+
+#define    A_OUT        plhs[0]
+
+
+void VectorToSparseUsage( void );
+
+
+void mexFunction( int nlhs,
+				  mxArray *plhs[],
+				  int nrhs,
+				  const mxArray *prhs[] )
+{
+	int     min,nin;
+	mwIndex *ir =NULL,*jc =NULL;
+	double  *ird=NULL,*jcd=NULL,*pr=NULL,*prd=NULL;
+	int     i,mrow;
+
+	/* Check for proper number of arguments */
+   
+	if      (nrhs == 0 && nlhs == 0) {
+		VectorToSparseUsage();
+		return;
+	}
+	else if (nrhs <  2 || nlhs != 1) {
+		VectorToSparseUsage();
+		mexErrMsgTxt(" ");
+	}
+
+	/* Create matrices for the return arguments */
+
+	if (!mxIsNumeric(IR_IN) || !mxIsNumeric(JC_IN)) {
+		mexPrintf("%s -- Input matrices IR and JC must be numeric.\n",THISFUNCTION);
+		mexErrMsgTxt(" ");
+	}
+
+	mrow = 0;
+	ird = mxGetPr(IR_IN);
+	for (i=0; i<mxGetM(IR_IN)*mxGetN(IR_IN); i++)
+		if ((int)ird[i]+1 > mrow)
+			mrow=(int)ird[i]+1;
+
+	if (nrhs >= 4 && mxIsNumeric(M_IN) && !mxIsEmpty(M_IN))
+		min = mxGetScalar(M_IN);
+	else {
+		min = mrow;
+	}
+
+	if (mrow > min) {
+		mexPrintf("%s -- Number of rows specified by M (%d) and IR (%d) is inconsistent.\n",
+				  THISFUNCTION,min,mrow);
+		mexErrMsgTxt(" ");
+	}
+
+	if (nrhs >= 5 && mxIsNumeric(N_IN) && !mxIsEmpty(N_IN))
+		nin = mxGetScalar(N_IN);
+	else
+		nin = mxGetM(JC_IN)*mxGetN(JC_IN)-1;
+
+	if (mxGetM(JC_IN)*mxGetN(JC_IN)-1 != nin) {
+		mexPrintf("%s -- Number of columns specified by N (%d) and JC (%d) is inconsistent.\n",
+				  THISFUNCTION,nin,mxGetM(JC_IN)*mxGetN(JC_IN)-1);
+		mexErrMsgTxt(" ");
+	}
+
+	A_OUT = mxCreateSparse(min, nin, mxGetM(IR_IN)*mxGetN(IR_IN), mxREAL);
+	if (mxGetM(IR_IN)*mxGetN(IR_IN)) {
+		ird = mxGetPr(IR_IN);
+		ir  = mxGetIr(A_OUT);
+		for (i=0; i<mxGetM(IR_IN)*mxGetN(IR_IN); i++)
+			ir[i]=(mwIndex)ird[i];
+	}
+	if (mxGetM(JC_IN)*mxGetN(JC_IN)) {
+		jcd = mxGetPr(JC_IN);
+		jc  = mxGetJc(A_OUT);
+		for (i=0; i<mxGetM(JC_IN)*mxGetN(JC_IN); i++)
+			jc[i]=(mwIndex)jcd[i];
+	}
+
+	if (nrhs >= 3 && mxIsNumeric(PR_IN) && !mxIsEmpty(PR_IN)) {
+		if (mxGetM(PR_IN)*mxGetN(PR_IN) != mxGetM(IR_IN)*mxGetN(IR_IN)) {
+			mexPrintf("%s -- Number of terms specified by IR (%d) and PR (%d) is inconsistent.\n",
+					  THISFUNCTION,mxGetM(IR_IN)*mxGetN(IR_IN),mxGetM(PR_IN)*mxGetN(PR_IN));
+			mexErrMsgTxt(" ");
+		}
+
+		if (mxGetM(PR_IN)*mxGetN(PR_IN)) {
+			prd = mxGetPr(PR_IN);
+			pr  = mxGetPr(A_OUT);
+			for (i=0; i<mxGetM(PR_IN)*mxGetN(PR_IN); i++)
+				pr[i]=prd[i];
+		}
+	}
+
+	else {
+		mexPrintf("%s -- Populating sparse matrix terms with ones.\n",THISFUNCTION);
+		mexWarnMsgTxt(" ");
+
+		if (mxGetM(IR_IN)*mxGetN(IR_IN)) {
+			pr  = mxGetPr(A_OUT);
+			for (i=0; i<mxGetM(IR_IN)*mxGetN(IR_IN); i++)
+				pr[i]=1.;
+		}
+	}
+
+	mexPrintf("%s -- Output matrix is of size %d by %d with %d non-zeroes.\n",
+			  THISFUNCTION,min,nin,mxGetM(IR_IN)*mxGetN(IR_IN));
+
+	return;
+}
+
+void VectorToSparseUsage( void )
+{
+
+    mexPrintf("\n");
+    mexPrintf("Usage: [a]=VectorToSparse(ir,jc,pr,m,n);\n");
+    mexPrintf("\n");
+
+    return;
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch.patch	(revision 18231)
@@ -0,0 +1,2418 @@
+Only in src: bin
+Only in src: include
+Only in src: lib
+diff -crB scotch_5.1/src/libscotch/arch.c src/src/libscotch/arch.c
+*** scotch_5.1/src/libscotch/arch.c	2008-09-27 07:48:01.000000000 -0700
+--- src/src/libscotch/arch.c	2013-05-06 14:14:11.000000000 -0700
+***************
+*** 173,187 ****
+  int
+  archLoad (
+  Arch * restrict const       archptr,
+! FILE * const                stream)
+  {
+    const ArchClass * restrict  class;              /* Pointer to architecture class */
+    char                        name[256];          /* Architecture name string      */
+  
+    if (fscanf (stream, "%255s", name) != 1) {      /* Read architecture name */
+      errorPrint ("archLoad: cannot load architecture type");
+      return     (1);
+    }
+    name[255] = '\0';                               /* Set end of string */
+  
+    if ((class = archClass (name)) == NULL) {       /* Get class from its name */
+--- 173,203 ----
+  int
+  archLoad (
+  Arch * restrict const       archptr,
+! FILE * const                stream
+! #ifdef NOFILEIO
+!                                   ,
+! const char *                archtyp,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    const ArchClass * restrict  class;              /* Pointer to architecture class */
+    char                        name[256];          /* Architecture name string      */
+  
++ #ifdef NOFILEIO
++ //  printf("archLoad - stream=%p; archtyp=\"%s\"\n",stream,archtyp);
++ //  printf("archLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
++ #ifndef NOFILEIO
+    if (fscanf (stream, "%255s", name) != 1) {      /* Read architecture name */
+      errorPrint ("archLoad: cannot load architecture type");
+      return     (1);
+    }
++ #else /* NOFILEIO */
++   strcpy(name,archtyp);
++ #endif /* NOFILEIO */
+    name[255] = '\0';                               /* Set end of string */
+  
+    if ((class = archClass (name)) == NULL) {       /* Get class from its name */
+***************
+*** 190,196 ****
+--- 206,216 ----
+    }
+  
+    if (class->archLoad != NULL) {                  /* If class has loading function */
++ #ifndef NOFILEIO
+      if (class->archLoad (&archptr->data, stream) != 0) { /* Load class data        */
++ #else /* NOFILEIO */
++     if (class->archLoad (&archptr->data, stream, napar, archpar) != 0) { /* Load class data        */
++ #endif /* NOFILEIO */
+        errorPrint ("archLoad: cannot load architecture data");
+        memset     (archptr, 0, sizeof (Arch));     /* Initialize architecture body */
+        return     (1);
+diff -crB scotch_5.1/src/libscotch/arch_cmplt.c src/src/libscotch/arch_cmplt.c
+*** scotch_5.1/src/libscotch/arch_cmplt.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmplt.c	2013-05-06 14:14:11.000000000 -0700
+***************
+*** 90,99 ****
+  int
+  archCmpltArchLoad (
+  ArchCmplt * restrict const  archptr,
+! FILE * restrict const       stream)
+  {
+    long                numnbr;
+  
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchCmplt)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchCmpltDom) > sizeof (ArchDomDummy))) {
+--- 90,109 ----
+  int
+  archCmpltArchLoad (
+  ArchCmplt * restrict const  archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    long                numnbr;
+  
++ #ifdef NOFILEIO
++ //  printf("archCmpltArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchCmplt)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchCmpltDom) > sizeof (ArchDomDummy))) {
+***************
+*** 102,109 ****
+--- 112,124 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((fscanf (stream, "%ld", &numnbr) != 1) ||
+        (numnbr < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 1) ||
++       ((numnbr=(long)archpar[0]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archCmpltArchLoad: bad input");
+      return     (1);
+    }
+diff -crB scotch_5.1/src/libscotch/arch_cmplt.h src/src/libscotch/arch_cmplt.h
+*** scotch_5.1/src/libscotch/arch_cmplt.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmplt.h	2013-05-06 14:14:11.000000000 -0700
+***************
+*** 87,93 ****
+--- 87,97 ----
+  #define static
+  #endif
+  
++ #ifndef NOFILEIO
+  int                         archCmpltArchLoad   (ArchCmplt * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archCmpltArchLoad   (ArchCmplt * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archCmpltArchSave   (const ArchCmplt * const, FILE * restrict const);
+  #define archCmpltArchFree           NULL
+  ArchDomNum                  archCmpltDomNum     (const ArchCmplt * const, const ArchCmpltDom * const);
+diff -crB scotch_5.1/src/libscotch/arch_cmpltw.c src/src/libscotch/arch_cmpltw.c
+*** scotch_5.1/src/libscotch/arch_cmpltw.c	2008-08-27 14:22:22.000000000 -0700
+--- src/src/libscotch/arch_cmpltw.c	2013-05-06 14:14:12.000000000 -0700
+***************
+*** 200,211 ****
+  int
+  archCmpltwArchLoad (
+  ArchCmpltw * restrict const  archptr,
+! FILE * restrict const       stream)
+  {
+    long                vertnbr;
+    Gnum                velosum;
+    Anum                vertnum;
+  
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchCmpltw)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchCmpltwDom) > sizeof (ArchDomDummy))) {
+--- 200,221 ----
+  int
+  archCmpltwArchLoad (
+  ArchCmpltw * restrict const  archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    long                vertnbr;
+    Gnum                velosum;
+    Anum                vertnum;
+  
++ #ifdef NOFILEIO
++ //  printf("archCmpltwArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchCmpltw)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchCmpltwDom) > sizeof (ArchDomDummy))) {
+***************
+*** 214,221 ****
+--- 224,236 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((fscanf (stream, "%ld", &vertnbr) != 1) ||
+        (vertnbr < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 1) ||
++       ((vertnbr=(long)archpar[0]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archCmpltwArchLoad: bad input (1)");
+      return     (1);
+    }
+***************
+*** 230,237 ****
+--- 245,257 ----
+      long                veloval;
+      Gnum                velotmp;
+  
++ #ifndef NOFILEIO
+      if ((fscanf (stream, "%ld", &veloval) != 1) ||
+          (veloval < 1)) {
++ #else /* NOFILEIO */
++     if ((napar < 1+(vertnum+1)) ||
++         ((veloval=(long)archpar[1+(vertnum+1)]) < 1)) {
++ #endif /* NOFILEIO */
+        errorPrint ("archCmpltwArchLoad: bad input (2)");
+        return     (1);
+      }
+diff -crB scotch_5.1/src/libscotch/arch_cmpltw.h src/src/libscotch/arch_cmpltw.h
+*** scotch_5.1/src/libscotch/arch_cmpltw.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmpltw.h	2013-05-06 14:14:12.000000000 -0700
+***************
+*** 86,92 ****
+--- 86,96 ----
+  #endif
+  
+  int                         archCmpltwArchBuild (ArchCmpltw * restrict const archptr, const Gnum, const Gnum * restrict const);
++ #ifndef NOFILEIO
+  int                         archCmpltwArchLoad  (ArchCmpltw * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archCmpltwArchLoad  (ArchCmpltw * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archCmpltwArchSave  (const ArchCmpltw * const, FILE * restrict const);
+  int                         archCmpltwArchFree  (ArchCmpltw * restrict const);
+  ArchDomNum                  archCmpltwDomNum    (const ArchCmpltw * const, const ArchCmpltwDom * const);
+diff -crB scotch_5.1/src/libscotch/arch_deco.c src/src/libscotch/arch_deco.c
+*** scotch_5.1/src/libscotch/arch_deco.c	2008-09-28 06:35:27.000000000 -0700
+--- src/src/libscotch/arch_deco.c	2013-05-06 14:14:12.000000000 -0700
+***************
+*** 211,217 ****
+  int
+  archDecoArchLoad (
+  ArchDeco * restrict const   archptr,
+! FILE * restrict const       stream)
+  {
+    INT                         decotype;           /* Type of decomposition                            */
+    INT                         termdomnbr;         /* Number of terminal domains (ie processors)       */
+--- 211,223 ----
+  int
+  archDecoArchLoad (
+  ArchDeco * restrict const   archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    INT                         decotype;           /* Type of decomposition                            */
+    INT                         termdomnbr;         /* Number of terminal domains (ie processors)       */
+***************
+*** 220,225 ****
+--- 226,237 ----
+    Anum * restrict             termdisttab;        /* Table of terminal-to-terminal distances          */
+    INT                         i, j;
+  
++ #ifdef NOFILEIO
++ //  printf("archDecoArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++   errorPrint ("archDecoArchLoad - not yet converted to matlab matrices");
++   return     (1);
++ #endif /* NOFILEIO */
++ 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchDeco)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchDecoDom) > sizeof (ArchDomDummy))) {
+diff -crB scotch_5.1/src/libscotch/arch_deco.h src/src/libscotch/arch_deco.h
+*** scotch_5.1/src/libscotch/arch_deco.h	2008-09-27 07:49:46.000000000 -0700
+--- src/src/libscotch/arch_deco.h	2013-05-06 14:14:13.000000000 -0700
+***************
+*** 113,119 ****
+--- 113,123 ----
+  #endif
+  
+  int                         archDecoArchBuild   (ArchDeco * const, const Anum, const Anum, const ArchDecoTermVert * const, const Anum  * const);
++ #ifndef NOFILEIO
+  int                         archDecoArchLoad    (ArchDeco * const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archDecoArchLoad    (ArchDeco * const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archDecoArchSave    (const ArchDeco * const, FILE * restrict const);
+  int                         archDecoArchFree    (ArchDeco * const);
+  Anum                        archDecoArchSize    (ArchDeco * const, const Anum);
+diff -crB scotch_5.1/src/libscotch/arch.h src/src/libscotch/arch.h
+*** scotch_5.1/src/libscotch/arch.h	2009-04-28 08:11:27.000000000 -0700
+--- src/src/libscotch/arch.h	2013-05-06 14:14:13.000000000 -0700
+***************
+*** 175,181 ****
+--- 175,185 ----
+  int                         archInit            (Arch * restrict const);
+  int                         archExit            (Arch * restrict const);
+  int                         archFree            (Arch * restrict const);
++ #ifndef NOFILEIO
+  int                         archLoad            (Arch * restrict const, FILE * const);
++ #else /* NOFILEIO */
++ int                         archLoad            (Arch * restrict const, FILE * const, const char *, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archSave            (const Arch * const, FILE * const);
+  char *                      archName            (const Arch * const);
+  const ArchClass *           archClass           (const char * const);
+diff -crB scotch_5.1/src/libscotch/arch_hcub.c src/src/libscotch/arch_hcub.c
+*** scotch_5.1/src/libscotch/arch_hcub.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_hcub.c	2013-05-06 14:14:13.000000000 -0700
+***************
+*** 88,95 ****
+  int
+  archHcubArchLoad (
+  ArchHcub * restrict const   archptr,
+! FILE * restrict const       stream)
+  {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchHcub)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchHcubDom) > sizeof (ArchDomDummy))) {
+--- 88,105 ----
+  int
+  archHcubArchLoad (
+  ArchHcub * restrict const   archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
++ #ifdef NOFILEIO
++ //  printf("archHcubArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchHcub)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchHcubDom) > sizeof (ArchDomDummy))) {
+***************
+*** 98,105 ****
+--- 108,120 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->dimmax) != 1) ||
+        (archptr->dimmax < 1)                     ||
++ #else /* NOFILEIO */
++   if ((napar < 1)                        ||
++       ((archptr->dimmax=archpar[0]) < 1) ||
++ #endif /* NOFILEIO */
+        (archptr->dimmax > (sizeof (archptr->dimmax) << 3))) {
+      errorPrint ("archHcubArchLoad: bad input");
+      return     (1);
+diff -crB scotch_5.1/src/libscotch/arch_hcub.h src/src/libscotch/arch_hcub.h
+*** scotch_5.1/src/libscotch/arch_hcub.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_hcub.h	2013-05-06 14:14:14.000000000 -0700
+***************
+*** 85,91 ****
+--- 85,95 ----
+  #define static
+  #endif
+  
++ #ifndef NOFILEIO
+  int                         archHcubArchLoad    (ArchHcub * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archHcubArchLoad    (ArchHcub * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archHcubArchSave    (const ArchHcub * const, FILE * restrict const);
+  #define archHcubArchFree            NULL
+  ArchDomNum                  archHcubDomNum      (const ArchHcub * const, const ArchHcubDom * const);
+diff -crB scotch_5.1/src/libscotch/arch_mesh.c src/src/libscotch/arch_mesh.c
+*** scotch_5.1/src/libscotch/arch_mesh.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_mesh.c	2013-05-06 14:14:14.000000000 -0700
+***************
+*** 96,103 ****
+  int
+  archMesh2ArchLoad (
+  ArchMesh2 * restrict const  archptr,
+! FILE * restrict const       stream)
+! {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchMesh2)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchMesh2Dom) > sizeof (ArchDomDummy))) {
+--- 96,113 ----
+  int
+  archMesh2ArchLoad (
+  ArchMesh2 * restrict const  archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+! {
+! #ifdef NOFILEIO
+! //  printf("archMesh2ArchLoad - napar=%d,archpar=%p\n",napar,archpar);
+! #endif /* NOFILEIO */
+! 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchMesh2)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchMesh2Dom) > sizeof (ArchDomDummy))) {
+***************
+*** 106,114 ****
+--- 116,130 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->c[0]) != 1) ||
+        (intLoad (stream, &archptr->c[1]) != 1) ||
+        (archptr->c[0] < 1) || (archptr->c[1] < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 2)                      ||
++       ((archptr->c[0]=archpar[0]) < 1) ||
++       ((archptr->c[1]=archpar[1]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archMesh2ArchLoad: bad input");
+      return     (1);
+    }
+***************
+*** 421,428 ****
+  int
+  archMesh3ArchLoad (
+  ArchMesh3 * restrict const  archptr,
+! FILE * restrict const       stream)
+! {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchMesh3)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchMesh3Dom) > sizeof (ArchDomDummy))) {
+--- 437,454 ----
+  int
+  archMesh3ArchLoad (
+  ArchMesh3 * restrict const  archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+! {
+! #ifdef NOFILEIO
+! //  printf("archMesh3ArchLoad - napar=%d,archpar=%p\n",napar,archpar);
+! #endif /* NOFILEIO */
+! 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchMesh3)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchMesh3Dom) > sizeof (ArchDomDummy))) {
+***************
+*** 431,440 ****
+--- 457,473 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->c[0]) != 1) ||
+        (intLoad (stream, &archptr->c[1]) != 1) ||
+        (intLoad (stream, &archptr->c[2]) != 1) ||
+        (archptr->c[0] < 1) || (archptr->c[1] < 1) || (archptr->c[2] < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 3)                      ||
++       ((archptr->c[0]=archpar[0]) < 1) ||
++       ((archptr->c[1]=archpar[1]) < 1) ||
++       ((archptr->c[2]=archpar[2]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archMesh3ArchLoad: bad input");
+      return     (1);
+    }
+diff -crB scotch_5.1/src/libscotch/arch_mesh.h src/src/libscotch/arch_mesh.h
+*** scotch_5.1/src/libscotch/arch_mesh.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_mesh.h	2013-05-06 14:14:14.000000000 -0700
+***************
+*** 96,102 ****
+--- 96,106 ----
+  #define static
+  #endif
+  
++ #ifndef NOFILEIO
+  int                         archMesh2ArchLoad   (ArchMesh2 * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archMesh2ArchLoad   (ArchMesh2 * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archMesh2ArchSave   (const ArchMesh2 * const, FILE * restrict const);
+  #define archMesh2ArchFree           NULL
+  ArchDomNum                  archMesh2DomNum     (const ArchMesh2 * const, const ArchMesh2Dom * const);
+***************
+*** 114,120 ****
+--- 118,128 ----
+  int                         archMesh2DomMpiType (const ArchMesh2 * const, MPI_Datatype * const);
+  #endif /* SCOTCH_PTSCOTCH */
+  
++ #ifndef NOFILEIO
+  int                         archMesh3ArchLoad   (ArchMesh3 * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archMesh3ArchLoad   (ArchMesh3 * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archMesh3ArchSave   (const ArchMesh3 * const, FILE * restrict const);
+  #define archMesh3ArchFree           NULL
+  ArchDomNum                  archMesh3DomNum     (const ArchMesh3 * const, const ArchMesh3Dom * const);
+diff -crB scotch_5.1/src/libscotch/arch_tleaf.c src/src/libscotch/arch_tleaf.c
+*** scotch_5.1/src/libscotch/arch_tleaf.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_tleaf.c	2013-05-06 14:14:14.000000000 -0700
+***************
+*** 92,99 ****
+  int
+  archTleafArchLoad (
+  ArchTleaf * restrict const  archptr,
+! FILE * restrict const       stream)
+  {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTleaf)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTleafDom) > sizeof (ArchDomDummy))) {
+--- 92,109 ----
+  int
+  archTleafArchLoad (
+  ArchTleaf * restrict const  archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
++ #ifdef NOFILEIO
++ //  printf("archTleafArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTleaf)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTleafDom) > sizeof (ArchDomDummy))) {
+***************
+*** 102,107 ****
+--- 112,118 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->leafdep) != 1) ||
+        (intLoad (stream, &archptr->clusdep) != 1) ||
+        (intLoad (stream, &archptr->linkval) != 1) ||
+***************
+*** 109,114 ****
+--- 120,132 ----
+        (archptr->clusdep < 0)                     ||
+        (archptr->clusdep > archptr->leafdep)      ||
+        (archptr->linkval < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 3)                            ||
++       ((archptr->leafdep=archpar[0]) < 1)    ||
++       ((archptr->clusdep=archpar[1]) < 0)    ||
++       ( archptr->clusdep > archptr->leafdep) ||
++       ((archptr->linkval=archpar[2]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archTleafArchLoad: bad input");
+      return     (1);
+    }
+diff -crB scotch_5.1/src/libscotch/arch_tleaf.h src/src/libscotch/arch_tleaf.h
+*** scotch_5.1/src/libscotch/arch_tleaf.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_tleaf.h	2013-05-06 14:14:15.000000000 -0700
+***************
+*** 89,95 ****
+--- 89,99 ----
+  #define static
+  #endif
+  
++ #ifndef NOFILEIO
+  int                         archTleafArchLoad   (ArchTleaf * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archTleafArchLoad   (ArchTleaf * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archTleafArchSave   (const ArchTleaf * const, FILE * restrict const);
+  #define archTleafArchFree           NULL
+  ArchDomNum                  archTleafDomNum     (const ArchTleaf * const, const ArchTleafDom * const);
+diff -crB scotch_5.1/src/libscotch/arch_torus.c src/src/libscotch/arch_torus.c
+*** scotch_5.1/src/libscotch/arch_torus.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_torus.c	2013-05-06 14:14:15.000000000 -0700
+***************
+*** 90,97 ****
+  int
+  archTorus2ArchLoad (
+  ArchTorus2 * restrict const archptr,
+! FILE * restrict const       stream)
+! {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTorus2)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTorus2Dom) > sizeof (ArchDomDummy))) {
+--- 90,107 ----
+  int
+  archTorus2ArchLoad (
+  ArchTorus2 * restrict const archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+! {
+! #ifdef NOFILEIO
+! //  printf("archTorus2ArchLoad - napar=%d,archpar=%p\n",napar,archpar);
+! #endif /* NOFILEIO */
+! 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTorus2)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTorus2Dom) > sizeof (ArchDomDummy))) {
+***************
+*** 100,108 ****
+--- 110,124 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->c[0]) != 1) ||
+        (intLoad (stream, &archptr->c[1]) != 1) ||
+        (archptr->c[0] < 1) || (archptr->c[1] < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 2)                      ||
++       ((archptr->c[0]=archpar[0]) < 1) ||
++       ((archptr->c[1]=archpar[1]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archTorus2ArchLoad: bad input");
+      return     (1);
+    }
+***************
+*** 363,370 ****
+  int
+  archTorus3ArchLoad (
+  ArchTorus3 * restrict const archptr,
+! FILE * restrict const       stream)
+! {
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTorus3)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTorus3Dom) > sizeof (ArchDomDummy))) {
+--- 379,396 ----
+  int
+  archTorus3ArchLoad (
+  ArchTorus3 * restrict const archptr,
+! FILE * restrict const       stream
+! #ifdef NOFILEIO
+!                                   ,
+! const Anum                  napar,
+! const Anum *                archpar
+! #endif /* NOFILEIO */
+!                                    )
+! {
+! #ifdef NOFILEIO
+! //  printf("archTorus3ArchLoad - napar=%d,archpar=%p\n",napar,archpar);
+! #endif /* NOFILEIO */
+! 
+  #ifdef SCOTCH_DEBUG_ARCH1
+    if ((sizeof (ArchTorus3)    > sizeof (ArchDummy)) ||
+        (sizeof (ArchTorus3Dom) > sizeof (ArchDomDummy))) {
+***************
+*** 373,382 ****
+--- 399,415 ----
+    }
+  #endif /* SCOTCH_DEBUG_ARCH1 */
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &archptr->c[0]) != 1) ||
+        (intLoad (stream, &archptr->c[1]) != 1) ||
+        (intLoad (stream, &archptr->c[2]) != 1) ||
+        (archptr->c[0] < 1) || (archptr->c[1] < 1) || (archptr->c[2] < 1)) {
++ #else /* NOFILEIO */
++   if ((napar < 3)                      ||
++       ((archptr->c[0]=archpar[0]) < 1) ||
++       ((archptr->c[1]=archpar[1]) < 1) ||
++       ((archptr->c[2]=archpar[2]) < 1)) {
++ #endif /* NOFILEIO */
+      errorPrint ("archTorus3ArchLoad: bad input");
+      return     (1);
+    }
+diff -crB scotch_5.1/src/libscotch/arch_torus.h src/src/libscotch/arch_torus.h
+*** scotch_5.1/src/libscotch/arch_torus.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_torus.h	2013-05-06 14:14:15.000000000 -0700
+***************
+*** 96,102 ****
+--- 96,106 ----
+  #define static
+  #endif
+  
++ #ifndef NOFILEIO
+  int                         archTorus2ArchLoad  (ArchTorus2 * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archTorus2ArchLoad  (ArchTorus2 * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archTorus2ArchSave  (const ArchTorus2 * const, FILE * restrict const);
+  #define archTorus2ArchFree          NULL
+  ArchDomNum                  archTorus2DomNum    (const ArchTorus2 * const, const ArchTorus2Dom * const);
+***************
+*** 114,120 ****
+--- 118,128 ----
+  int                         archTorus2DomMpiType (const ArchTorus2 * const, MPI_Datatype * const);
+  #endif /* SCOTCH_PTSCOTCH */
+  
++ #ifndef NOFILEIO
+  int                         archTorus3ArchLoad  (ArchTorus3 * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         archTorus3ArchLoad  (ArchTorus3 * restrict const, FILE * restrict const, const Anum, const Anum *);
++ #endif /* NOFILEIO */
+  int                         archTorus3ArchSave  (const ArchTorus3 * const, FILE * restrict const);
+  #define archTorus3ArchFree          NULL
+  ArchDomNum                  archTorus3DomNum    (const ArchTorus3 * const, const ArchTorus3Dom * const);
+diff -crB scotch_5.1/src/libscotch/common.c src/src/libscotch/common.c
+*** scotch_5.1/src/libscotch/common.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/common.c	2013-05-06 14:14:15.000000000 -0700
+***************
+*** 100,106 ****
+--- 100,112 ----
+  {
+    const char **       cptr;
+  
++ #ifndef MATLAB
+    fprintf (stream, "Usage is:\n");
+    for (cptr = data; *cptr != NULL; cptr ++)
+      fprintf (stream, "  %s\n", *cptr);
++ #else /* MATLAB */
++   mexPrintf ("Usage is:\n");
++   for (cptr = data; *cptr != NULL; cptr ++)
++     mexPrintf ("  %s\n", *cptr);
++ #endif /* MATLAB */
+  }
+diff -crB scotch_5.1/src/libscotch/common.h src/src/libscotch/common.h
+*** scotch_5.1/src/libscotch/common.h	2009-02-06 14:20:55.000000000 -0800
+--- src/src/libscotch/common.h	2013-05-09 11:49:35.317220518 -0700
+***************
+*** 1,3 ****
+--- 1,5 ----
++ #ifndef _SCOTCH_COMMON_H_
++ #define _SCOTCH_COMMON_H_
+  /* Copyright 2004,2007-2009 ENSEIRB, INRIA & CNRS
+  **
+  ** This file is part of the Scotch software package for static mapping,
+***************
+*** 79,84 ****
+--- 81,87 ----
+  #include            <sys/resource.h>
+  #endif /* COMMON_TIMING_OLD */
+  #include            <unistd.h>
++ #include            <sys/param.h>
+  
+  #ifdef SCOTCH_PTSCOTCH
+  #include            <mpi.h>
+***************
+*** 106,113 ****
+  #define memCpy(dst,src,siz)         memcpy((dst),(src),(siz))
+  #define memMov(dst,src,siz)         memmove((dst),(src),(siz))
+  
+- #define MIN(x,y)                    (((x) < (y)) ? (x) : (y))
+- #define MAX(x,y)                    (((x) < (y)) ? (y) : (x))
+  #define ABS(x)                      MAX ((x), -(x))
+  #define SIGN(x)                     (((x) < 0) ? -1 : 1)
+  
+--- 109,114 ----
+***************
+*** 171,179 ****
+  /** The file structure. **/
+  
+  typedef struct File_ {
+!   char *                    name;                 /*+ File name    +*/
+    FILE *                    pntr;                 /*+ File pointer +*/
+!   char *                    mode;                 /*+ Opening mode +*/
+  } File;
+  
+  /*
+--- 172,180 ----
+  /** The file structure. **/
+  
+  typedef struct File_ {
+!   const char *              name;                 /*+ File name    +*/
+    FILE *                    pntr;                 /*+ File pointer +*/
+!   const char *              mode;                 /*+ Opening mode +*/
+  } File;
+  
+  /*
+***************
+*** 190,216 ****
+  size_t                      memMax              ();
+  #endif /* COMMON_MEMORY_TRACE */
+  
+- void                        usagePrint          (FILE * const, const char (* []));
+  
+- int                         fileBlockOpen       (File * const, const int);
+  int                         fileBlockOpenDist   (File * const, const int, const int, const int, const int);
+- void                        fileBlockClose      (File * const, const int);
+  FILE *                      fileCompress        (FILE * const, const int);
+  int                         fileCompressType    (const char * const);
+  FILE *                      fileUncompress      (FILE * const, const int);
+  int                         fileUncompressType  (const char * const);
+  int                         fileNameDistExpand  (char ** const, const int, const int, const int);
+  
+  void                        errorProg           (const char * const);
+  void                        errorPrint          (const char * const, ...);
+  void                        errorPrintW         (const char * const, ...);
+  
+  int                         intLoad             (FILE * const, INT * const);
+  int                         intSave             (FILE * const, const INT);
+  void                        intAscn             (INT * const, const INT, const INT);
+  void                        intPerm             (INT * const, const INT);
+  void                        intRandReset        (void);
+- void                        intRandInit         (void);
+  INT                         intRandVal          (INT);
+  void                        intSort1asc1        (void * const, const INT);
+  void                        intSort2asc1        (void * const, const INT);
+--- 191,227 ----
+  size_t                      memMax              ();
+  #endif /* COMMON_MEMORY_TRACE */
+  
+  
+  int                         fileBlockOpenDist   (File * const, const int, const int, const int, const int);
+  FILE *                      fileCompress        (FILE * const, const int);
+  int                         fileCompressType    (const char * const);
+  FILE *                      fileUncompress      (FILE * const, const int);
+  int                         fileUncompressType  (const char * const);
+  int                         fileNameDistExpand  (char ** const, const int, const int, const int);
+  
++ #ifdef __cplusplus
++ extern "C" {
++ #endif /* __cplusplus */
++ 
+  void                        errorProg           (const char * const);
+  void                        errorPrint          (const char * const, ...);
+  void                        errorPrintW         (const char * const, ...);
++ double                      clockGet            (void);
++ void                        usagePrint          (FILE * const, const char (* []));
++ void                        intRandInit         (void);
++ int                         fileBlockOpen       (File * const, const int);
++ void                        fileBlockClose      (File * const, const int);
++ void                        intRandResetStatic  (void);
++ 
++ #ifdef __cplusplus
++ }
++ #endif /* __cplusplus */
+  
+  int                         intLoad             (FILE * const, INT * const);
+  int                         intSave             (FILE * const, const INT);
+  void                        intAscn             (INT * const, const INT, const INT);
+  void                        intPerm             (INT * const, const INT);
+  void                        intRandReset        (void);
+  INT                         intRandVal          (INT);
+  void                        intSort1asc1        (void * const, const INT);
+  void                        intSort2asc1        (void * const, const INT);
+***************
+*** 221,227 ****
+  void                        clockStart          (Clock * const);
+  void                        clockStop           (Clock * const);
+  double                      clockVal            (Clock * const);
+- double                      clockGet            (void);
+  
+  /*
+  **  Macro definitions.
+--- 232,237 ----
+***************
+*** 249,251 ****
+--- 259,263 ----
+  void nl##__ pl                                   \
+  { nu pc; }                                       \
+  void nu pl
++ 
++ #endif //#ifndef _SCOTCH_COMMON_H_
+diff -crB scotch_5.1/src/libscotch/common_integer.c src/src/libscotch/common_integer.c
+*** scotch_5.1/src/libscotch/common_integer.c	2009-01-21 01:32:32.000000000 -0800
+--- src/src/libscotch/common_integer.c	2013-05-06 14:14:16.000000000 -0700
+***************
+*** 191,196 ****
+--- 191,209 ----
+  static volatile int intrandflag = 0;              /*+ Flag set if generator already initialized +*/
+  static unsigned int intrandseed = 1;              /*+ Random seed                               +*/
+  
++ void
++ intRandResetStatic (void)
++ {
++ #ifdef MATLAB
++ //  printf("intRandResetStatic begin - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
++   intrandflag = 0;              /*+ Flag set if generator already initialized +*/
++   intrandseed = 1;              /*+ Random seed                               +*/
++ #ifdef MATLAB
++ //  printf("intRandResetStatic end   - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
++ }
++ 
+  /* This routine initializes the pseudo-random
+  ** generator if necessary. In order for multi-sequential
+  ** programs to have exactly the same behavior on any
+***************
+*** 205,210 ****
+--- 218,226 ----
+  void
+  intRandInit (void)
+  {
++ #ifdef MATLAB
++ //  printf("intRandInit begin - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
+    if (intrandflag == 0) {                         /* If generator not yet initialized */
+  #if ! ((defined COMMON_DEBUG) || (defined COMMON_RANDOM_FIXED_SEED) || (defined SCOTCH_DETERMINISTIC))
+      intrandseed = time (NULL);                    /* Set random seed if needed */
+***************
+*** 216,221 ****
+--- 232,240 ----
+  #endif /* COMMON_RANDOM_RAND */
+      intrandflag = 1;                              /* Generator has been initialized */
+    }
++ #ifdef MATLAB
++ //  printf("intRandInit end   - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
+  }
+  
+  /* This routine reinitializes the pseudo-random
+***************
+*** 228,233 ****
+--- 247,255 ----
+  void
+  intRandReset (void)
+  {
++ #ifdef MATLAB
++ //  printf("intRandReset begin - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
+    if (intrandflag != 0) {                         /* Keep seed computed during first initialization */
+  #ifdef COMMON_RANDOM_RAND
+      srand (intrandseed);
+***************
+*** 237,242 ****
+--- 259,267 ----
+    }
+    else
+      intRandInit ();
++ #ifdef MATLAB
++ //  printf("intRandReset end   - intrandflag=%d,intrandseed=%d\n",intrandflag,intrandseed);
++ #endif /* MATLAB */
+  }
+  
+  /*********************/
+diff -crB scotch_5.1/src/libscotch/common_memory.c src/src/libscotch/common_memory.c
+*** scotch_5.1/src/libscotch/common_memory.c	2009-01-03 02:16:11.000000000 -0800
+--- src/src/libscotch/common_memory.c	2013-05-06 14:14:16.000000000 -0700
+***************
+*** 87,93 ****
+--- 87,95 ----
+    size_t              newadd;
+    byte *              newptr;
+  
++   printf("memAllocRecord begin -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
++   printf("memAllocRecord begin -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+    if (muteflag != 0) {                            /* Unsafe code with respect to race conditions but should work as first allocs are sequential */
+      muteflag = 0;
+      pthread_mutex_init (&mutelocdat, NULL);       /* Initialize local mutex */
+***************
+*** 109,116 ****
+--- 111,120 ----
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
+    pthread_mutex_unlock (&mutelocdat);             /* Unlock local mutex */
++   printf("memAllocRecord end   -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
++   printf("memAllocRecord end   -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+    return ((void *) newptr);                       /* Return skewed pointer or NULL */
+  }
+  
+***************
+*** 124,133 ****
+--- 128,139 ----
+    size_t              oldsiz;
+    size_t              newadd;
+  
++   printf("memReallocRecord begin -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+    tmpptr = ((byte *) oldptr) - COMMON_MEMORY_SKEW;
+    oldsiz = *((size_t *) tmpptr);
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
++   printf("memReallocRecord begin -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+    pthread_mutex_lock (&mutelocdat);               /* Lock local mutex */
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
+***************
+*** 145,152 ****
+--- 151,160 ----
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
+    pthread_mutex_unlock (&mutelocdat);             /* Unlock local mutex */
++   printf("memReallocRecord end   -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
++   printf("memReallocRecord end   -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+    return ((void *) newptr);                       /* Return skewed pointer or NULL */
+  }
+  
+***************
+*** 157,166 ****
+--- 165,176 ----
+    byte *              tmpptr;
+    size_t              oldsiz;
+  
++   printf("memFreeRecord begin -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+    tmpptr = ((byte *) oldptr) - COMMON_MEMORY_SKEW;
+    oldsiz = *((size_t *) tmpptr);
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
++   printf("memFreeRecord begin -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+    pthread_mutex_lock (&mutelocdat);               /* Lock local mutex */
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
+***************
+*** 169,175 ****
+--- 179,187 ----
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
+    pthread_mutex_unlock (&mutelocdat);             /* Unlock local mutex */
++   printf("memFreeRecord end   -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
++   printf("memFreeRecord end   -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+  }
+  
+  size_t
+***************
+*** 177,183 ****
+--- 189,197 ----
+  {
+    size_t              curmax;
+  
++   printf("memMax begin -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
++   printf("memMax begin -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+    pthread_mutex_lock (&mutelocdat);               /* Lock local mutex */
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
+***************
+*** 185,192 ****
+--- 199,208 ----
+  
+  #if (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD))
+    pthread_mutex_unlock (&mutelocdat);             /* Unlock local mutex */
++   printf("memMax end   -- muteflag=%d,mutelocdat=%p\n",muteflag,mutelocdat);
+  #endif /* (defined (COMMON_PTHREAD) || defined (SCOTCH_PTHREAD)) */
+  
++   printf("memMax end   -- memorysiz=%d,memorymax=%d\n",memorysiz,memorymax);
+    return (curmax);
+  }
+  #endif /* COMMON_MEMORY_TRACE */
+diff -crB scotch_5.1/src/libscotch/dummysizes.c src/src/libscotch/dummysizes.c
+*** scotch_5.1/src/libscotch/dummysizes.c	2009-05-09 16:08:02.000000000 -0700
+--- src/src/libscotch/dummysizes.c	2013-05-06 14:14:16.000000000 -0700
+***************
+*** 267,271 ****
+--- 267,273 ----
+    }
+  #endif /* SCOTCH_DEBUG_MAIN1 */
+  
++ #ifndef MATLAB
+    exit (0);
++ #endif /* MATLAB */
+  }
+diff -crB scotch_5.1/src/libscotch/graph.c src/src/libscotch/graph.c
+*** scotch_5.1/src/libscotch/graph.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph.c	2013-05-06 14:14:17.000000000 -0700
+***************
+*** 135,141 ****
+      if ((grafptr->velotax != NULL) &&             /* Free graph tables             */
+          ((grafptr->flagval & GRAPHVERTGROUP) == 0))
+        memFree (grafptr->velotax + grafptr->baseval);
+!     if (grafptr->vlbltax != NULL)
+        memFree (grafptr->vlbltax + grafptr->baseval);
+      if ((grafptr->edlotax != NULL) &&
+          ((grafptr->flagval & GRAPHEDGEGROUP) == 0))
+--- 135,144 ----
+      if ((grafptr->velotax != NULL) &&             /* Free graph tables             */
+          ((grafptr->flagval & GRAPHVERTGROUP) == 0))
+        memFree (grafptr->velotax + grafptr->baseval);
+! /*  vlbltax must also check GRAPHVERTGROUP (jes, 12/11/09)  */
+! //    if (grafptr->vlbltax != NULL)
+!     if ((grafptr->vlbltax != NULL) &&
+!         ((grafptr->flagval & GRAPHVERTGROUP) == 0))
+        memFree (grafptr->vlbltax + grafptr->baseval);
+      if ((grafptr->edlotax != NULL) &&
+          ((grafptr->flagval & GRAPHEDGEGROUP) == 0))
+diff -crB scotch_5.1/src/libscotch/graph.h src/src/libscotch/graph.h
+*** scotch_5.1/src/libscotch/graph.h	2008-06-01 02:49:11.000000000 -0700
+--- src/src/libscotch/graph.h	2013-05-06 14:14:17.000000000 -0700
+***************
+*** 159,165 ****
+--- 159,169 ----
+  int                         graphInit           (Graph * const);
+  void                        graphExit           (Graph * const);
+  void                        graphFree           (Graph * const);
++ #ifndef NOFILEIO
+  int                         graphLoad           (Graph * const, FILE * const, const Gnum, const GraphFlag);
++ #else /* NOFILEIO */
++ int                         graphLoad           (Graph * const, FILE * const, const Gnum, const GraphFlag, const Gnum, const Gnum, const Gnum*, const Gnum*, const Gnum*, const Gnum*, const Gnum*);
++ #endif /* NOFILEIO */
+  int                         graphLoad2          (const Gnum, const Gnum, const Gnum * const, const Gnum * const, Gnum * restrict const, const Gnum, const Gnum * const);
+  int                         graphSave           (const Graph * const, FILE * const);
+  Gnum                        graphBase           (Graph * const, const Gnum);
+diff -crB scotch_5.1/src/libscotch/graph_io.c src/src/libscotch/graph_io.c
+*** scotch_5.1/src/libscotch/graph_io.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph_io.c	2013-05-06 14:14:17.000000000 -0700
+***************
+*** 86,92 ****
+  Graph * restrict const      grafptr,              /* Graph structure to fill              */
+  FILE * const                stream,               /* Stream from which to read graph data */
+  const Gnum                  baseval,              /* Base value (-1 means keep file base) */
+! const GraphFlag             flagval)              /* Graph loading flags                  */
+  {
+    Gnum                edgenum;                    /* Number of edges really allocated */
+    Gnum                edgennd;
+--- 86,103 ----
+  Graph * restrict const      grafptr,              /* Graph structure to fill              */
+  FILE * const                stream,               /* Stream from which to read graph data */
+  const Gnum                  baseval,              /* Base value (-1 means keep file base) */
+! const GraphFlag             flagval               /* Graph loading flags                  */
+! #ifdef NOFILEIO
+!                                    ,
+! const Gnum                  nvert,
+! const Gnum                  nedge2,
+! const Gnum*                 adjir,
+! const Gnum*                 adjjc,
+! const Gnum*                 vertlab,
+! const Gnum*                 vertwgt,
+! const Gnum*                 edgewgt
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    Gnum                edgenum;                    /* Number of edges really allocated */
+    Gnum                edgennd;
+***************
+*** 104,120 ****
+--- 115,141 ----
+    char                proptab[4];
+    Gnum                vertnum;
+  
++ #ifdef NOFILEIO
++ //  printf("graphLoad - stream=%p; nvert=%d,nedge2=%d\n",stream,nvert,nedge2);
++ //  printf("graphLoad - adjir=%p,adjjc=%p,vertlab=%p,vertwgt=%p,edgewgt=%p\n",
++ //         adjir,adjjc,vertlab,vertwgt,edgewgt);
++ #endif /* NOFILEIO */
+    memSet (grafptr, 0, sizeof (Graph));
+  
++ #ifndef NOFILEIO
+    if (intLoad (stream, &versval) != 1) {          /* Read version number */
+      errorPrint ("graphLoad: bad input (1)");
+      return     (1);
+    }
++ #else /* NOFILEIO */
++   versval=0;
++ #endif /* NOFILEIO */
+    if (versval != 0) {                             /* If version not zero */
+      errorPrint ("graphLoad: old-style graph format no longer supported");
+      return     (1);
+    }
+  
++ #ifndef NOFILEIO
+    if ((intLoad (stream, &grafptr->vertnbr) != 1) || /* Read rest of header */
+        (intLoad (stream, &grafptr->edgenbr) != 1) ||
+        (intLoad (stream, &baseadj)          != 1) ||
+***************
+*** 124,129 ****
+--- 145,159 ----
+      errorPrint ("graphLoad: bad input (2)");
+      return     (1);
+    }
++ #else /* NOFILEIO */
++   grafptr->vertnbr=nvert;
++   grafptr->edgenbr=nedge2;
++   baseadj=1;
++   propval=0;
++   if (vertlab) propval+=100;
++   if (edgewgt) propval+= 10;
++   if (vertwgt) propval+=  1;
++ #endif /* NOFILEIO */
+    sprintf (proptab, "%3.3d", (int) propval);      /* Compute file properties */
+    proptab[0] -= '0';                              /* Vertex labels flag      */
+    proptab[1] -= '0';                              /* Edge weights flag       */
+***************
+*** 140,145 ****
+--- 170,179 ----
+    }
+    if (proptab[0] != 0)                            /* If vertex labels, no base adjust */
+      baseadj = 0;
++ #ifdef NOFILEIO
++ //  printf("graphLoad - baseadj=%d,baseval=%d,grafptr->baseval=%d\n",
++ //         baseadj,baseval,grafptr->baseval);
++ #endif /* NOFILEIO */
+  
+    velonbr = ((proptab[2] != 0) && ((flagval & GRAPHIONOLOADVERT) == 0)) ? grafptr->vertnbr : 0;
+    vlblnbr = (proptab[0] != 0) ? grafptr->vertnbr : 0;
+***************
+*** 178,188 ****
+--- 212,226 ----
+      if (grafptr->vlbltax != NULL) {               /* If must read label               */
+        Gnum                vlblval;                /* Value where to read vertex label */
+  
++ #ifndef NOFILEIO
+        if (intLoad (stream, &vlblval) != 1) {      /* Read label data */
+          errorPrint ("graphLoad: bad input (3)");
+          graphFree  (grafptr);
+          return     (1);
+        }
++ #else /* NOFILEIO */
++       vlblval=vertlab[vertnum-grafptr->baseval];
++ #endif /* NOFILEIO */
+        grafptr->vlbltax[vertnum] = vlblval;
+        if (grafptr->vlbltax[vertnum] > vlblmax)    /* Get maximum vertex label */
+          vlblmax = grafptr->vlbltax[vertnum];
+***************
+*** 190,209 ****
+--- 228,257 ----
+      if (proptab[2] != 0) {                        /* If must read vertex load        */
+        Gnum                veloval;                /* Value where to read vertex load */
+  
++ #ifndef NOFILEIO
+        if (intLoad (stream, &veloval) != 1) {      /* Read vertex load data    */
+          errorPrint ("graphLoad: bad input (4)");
+          graphFree  (grafptr);
+          return     (1);
+        }
++ #else /* NOFILEIO */
++       veloval=vertwgt[vertnum-grafptr->baseval];
++ #endif /* NOFILEIO */
+        if (grafptr->velotax != NULL)
+          velosum                  +=
+          grafptr->velotax[vertnum] = veloval;
+      }
++ #ifndef NOFILEIO
+      if (intLoad (stream, &degrval) != 1) {        /* Read vertex degree */
+        errorPrint ("graphLoad: bad input (5)");
+        graphFree  (grafptr);
+        return     (1);
+      }
++ #else /* NOFILEIO */
++ //    printf("old degrval=%d; new degrval=%d\n",
++ //           degrval,adjjc[vertnum-grafptr->baseval+1]-adjjc[vertnum-grafptr->baseval]);
++     degrval=adjjc[vertnum-grafptr->baseval+1]-adjjc[vertnum-grafptr->baseval];
++ #endif /* NOFILEIO */
+      if (degrmax < degrval)                        /* Set maximum degree */
+        degrmax = degrval;
+  
+***************
+*** 219,238 ****
+--- 267,301 ----
+        if (proptab[1] != 0) {                      /* If must read edge load        */
+          Gnum                edloval;              /* Value where to read edge load */
+  
++ #ifndef NOFILEIO
+          if (intLoad (stream, &edloval) != 1) {    /* Read edge load data    */
+            errorPrint ("graphLoad: bad input (6)");
+            graphFree  (grafptr);
+            return     (1);
+          }
++ #else /* NOFILEIO */
++         edloval=edgewgt[edgenum-grafptr->baseval];
++ #endif /* NOFILEIO */
+          if (grafptr->edlotax != NULL)
+            edlosum                  +=
+            grafptr->edlotax[edgenum] = (Gnum) edloval;
+        }
++ #ifndef NOFILEIO
+        if (intLoad (stream, &edgeval) != 1) {      /* Read edge data */
+          errorPrint ("graphLoad: bad input (7)");
+          graphFree  (grafptr);
+          return     (1);
+        }
++ #else /* NOFILEIO */
++ //      printf("edgenum=%d: old edgeval=%d; new edgeval[%d]=%d\n",
++ //            edgenum,edgeval,edgenum-grafptr->baseval,adjir[edgenum-grafptr->baseval]+1);
++ /*  if vertex labels are supplied, they must be referenced  (jes, 1/05/10)  */
++ //      edgeval=adjir[edgenum-grafptr->baseval]+1;
++       if (vertlab)
++         edgeval=vertlab[adjir[edgenum-grafptr->baseval]  ];
++       else
++         edgeval=        adjir[edgenum-grafptr->baseval]+1;
++ #endif /* NOFILEIO */
+        grafptr->edgetax[edgenum] = edgeval + baseadj;
+      }
+    }
+***************
+*** 279,284 ****
+--- 342,351 ----
+    Gnum                vertnum;                    /* Number of current vertex        */
+    Gnum * restrict     indxtab;                    /* Vertex label/number index table */
+  
++ #ifdef NOFILEIO
++   printf("graphLoad2 - baseval=%d,vertnnd=%d,vlblmax=%d\n",
++          baseval,vertnnd,vlblmax);
++ #endif /* NOFILEIO */
+    if ((indxtab = (Gnum *) memAlloc ((vlblmax + 1) * sizeof (Gnum))) == NULL) {
+      errorPrint  ("graphLoad2: out of memory");
+      return      (1);
+***************
+*** 286,291 ****
+--- 353,362 ----
+  
+    memSet (indxtab, ~0, (vlblmax + 1) * sizeof (Gnum)); /* Assume labels not used */
+    for (vertnum = baseval; vertnum < vertnnd; vertnum ++) {
++ #ifdef NOFILEIO
++ //    printf("graphLoad2 - vertnum=%d; vlbltax=%d,indxtab=%d\n",
++ //           vertnum,vlbltax[vertnum],indxtab[vlbltax[vertnum]]);
++ #endif /* NOFILEIO */
+      if (indxtab[vlbltax[vertnum]] != ~0) {        /* If vertex label already used */
+        errorPrint  ("graphLoad2: duplicate vertex label");
+        memFree     (indxtab);
+***************
+*** 294,299 ****
+--- 365,374 ----
+      indxtab[vlbltax[vertnum]] = vertnum;          /* Set vertex number index */
+    }
+    for (vertnum = baseval; vertnum < vertnnd; vertnum ++) {
++ #ifdef NOFILEIO
++ //    printf("graphLoad2 - vertnum=%d; vlbltax=%d,indxtab=%d\n",
++ //           vertnum,vlbltax[vertnum],indxtab[vlbltax[vertnum]]);
++ #endif /* NOFILEIO */
+      Gnum                edgenum;                  /* Number of current edge */
+  
+      for (edgenum = verttax[vertnum]; edgenum < vendtax[vertnum]; edgenum ++) {
+***************
+*** 307,313 ****
+--- 382,396 ----
+          memFree    (indxtab);
+          return     (1);
+        }
++ #ifdef NOFILEIO
++ //      printf("graphLoad2 - edgenum=%d; old edgetax=%d,",
++ //             edgenum,edgetax[edgenum]);
++ #endif /* NOFILEIO */
+        edgetax[edgenum] = indxtab[edgetax[edgenum]]; /* Replace label by number */
++ #ifdef NOFILEIO
++ //      printf("new edgetax=%d\n",
++ //             edgetax[edgenum]);
++ #endif /* NOFILEIO */
+      }
+    }
+  
+diff -crB scotch_5.1/src/libscotch/graph_io_scot.c src/src/libscotch/graph_io_scot.c
+*** scotch_5.1/src/libscotch/graph_io_scot.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph_io_scot.c	2013-05-06 14:14:17.000000000 -0700
+***************
+*** 89,95 ****
+--- 89,99 ----
+    int                           o;
+  
+    if (filesrcptr != NULL) {
++ #ifndef NOFILEIO
+      if (graphLoad (grafptr, filesrcptr, -1, 0) != 0)
++ #else /* NOFILEIO */
++     if (graphLoad (grafptr, filesrcptr, -1, 0, 0, 0, NULL, NULL, NULL, NULL, NULL) != 0)
++ #endif /* NOFILEIO */
+        return (1);
+    }
+  
+diff -crB scotch_5.1/src/libscotch/library_arch.c src/src/libscotch/library_arch.c
+*** scotch_5.1/src/libscotch/library_arch.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/library_arch.c	2013-05-06 14:14:17.000000000 -0700
+***************
+*** 120,128 ****
+  int
+  SCOTCH_archLoad (
+  SCOTCH_Arch * const         archptr,
+! FILE * const                stream)
+  {
+    return (archLoad ((Arch *) archptr, stream));
+  }
+  
+  /*+ This routine saves the given opaque
+--- 120,139 ----
+  int
+  SCOTCH_archLoad (
+  SCOTCH_Arch * const         archptr,
+! FILE * const                stream
+! #ifdef NOFILEIO
+!                                   ,
+! const char *                archtyp,
+! const SCOTCH_Num            napar,
+! const SCOTCH_Num *          archpar
+! #endif /* NOFILEIO */
+!                                    )
+  {
++ #ifndef NOFILEIO
+    return (archLoad ((Arch *) archptr, stream));
++ #else /* NOFILEIO */
++   return (archLoad ((Arch *) archptr, stream, archtyp, napar, archpar));
++ #endif /* NOFILEIO */
+  }
+  
+  /*+ This routine saves the given opaque
+diff -crB scotch_5.1/src/libscotch/library_arch_f.c src/src/libscotch/library_arch_f.c
+*** scotch_5.1/src/libscotch/library_arch_f.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/library_arch_f.c	2013-05-06 14:14:18.000000000 -0700
+***************
+*** 121,127 ****
+--- 121,131 ----
+    }
+    setbuf (stream, NULL);                          /* Do not buffer on input */
+  
++ #ifndef NOFILEIO
+    o = SCOTCH_archLoad (archptr, stream);
++ #else /* NOFILEIO */
++   o = SCOTCH_archLoad (archptr, stream, "", 0, NULL);
++ #endif /* NOFILEIO */
+  
+    fclose (stream);                                /* This closes filenum too */
+  
+diff -crB scotch_5.1/src/libscotch/library_error_exit.c src/src/libscotch/library_error_exit.c
+*** scotch_5.1/src/libscotch/library_error_exit.c	2009-01-20 00:36:33.000000000 -0800
+--- src/src/libscotch/library_error_exit.c	2013-05-06 14:14:18.000000000 -0700
+***************
+*** 114,119 ****
+--- 114,120 ----
+    int                 proclocnum;
+  #endif /* SCOTCH_PTSCOTCH */
+  
++ #ifndef MATLAB
+    fprintf  (stderr, "%s", _SCOTCHerrorProgName);
+  #ifdef SCOTCH_PTSCOTCH
+    if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+***************
+*** 131,136 ****
+--- 132,155 ----
+    fprintf  (stderr, "\n");
+    fflush   (stderr);                              /* In case it has been set to buffered mode */
+  
++ #else /* MATLAB */
++   mexPrintf  ("%s", _SCOTCHerrorProgName);
++ #ifdef SCOTCH_PTSCOTCH
++   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
++       (proclocnum != 0)                              &&
++       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
++     mexPrintf ("(%d): ", proclocnum);
++ #else /* SCOTCH_PTSCOTCH */
++   if (_SCOTCHerrorProgName[0] != '\0')
++     mexPrintf  (": ");
++ #endif /* SCOTCH_PTSCOTCH */
++   mexPrintf  ("ERROR: ");
++   va_start (errlist, errstr);
++   mexPrintf (errstr, errlist);             /* Print arguments */
++   va_end   (errlist);
++   mexPrintf  ("\n");
++ #endif /* MATLAB */
++ 
+  #ifdef SCOTCH_ERROR_SLEEP
+    sleep (SCOTCH_ERROR_SLEEP);                     /* Wait for messages to be propagated */
+  #endif /* SCOTCH_ERROR_SLEEP */
+***************
+*** 155,160 ****
+--- 174,180 ----
+    int                 proclocnum;
+  #endif /* SCOTCH_PTSCOTCH */
+  
++ #ifndef MATLAB
+    fprintf  (stderr, "%s", _SCOTCHerrorProgName);
+  #ifdef SCOTCH_PTSCOTCH
+    if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+***************
+*** 171,174 ****
+--- 191,212 ----
+    va_end   (errlist);
+    fprintf  (stderr, "\n");
+    fflush   (stderr);                              /* In case it has been set to buffered mode */
++ 
++ #else /* MATLAB */
++   mexPrintf  ("%s", _SCOTCHerrorProgName);
++ #ifdef SCOTCH_PTSCOTCH
++   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
++       (proclocnum != 0)                              &&
++       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
++     mexPrintf ("(%d): ", proclocnum);
++ #else /* SCOTCH_PTSCOTCH */
++   if (_SCOTCHerrorProgName[0] != '\0')
++     mexPrintf  (": ");
++ #endif /* SCOTCH_PTSCOTCH */
++   mexPrintf  ("WARNING: ");
++   va_start (errlist, errstr);
++   mexPrintf (errstr, errlist);             /* Print arguments */
++   va_end   (errlist);
++   mexPrintf  ("\n");
++ #endif /* MATLAB */
+  }
+diff -crB scotch_5.1/src/libscotch/library_graph.c src/src/libscotch/library_graph.c
+*** scotch_5.1/src/libscotch/library_graph.c	2008-05-22 07:28:12.000000000 -0700
+--- src/src/libscotch/library_graph.c	2013-05-06 14:14:18.000000000 -0700
+***************
+*** 137,143 ****
+  SCOTCH_Graph * const        grafptr,
+  FILE * const                stream,
+  const SCOTCH_Num            baseval,
+! const SCOTCH_Num            flagval)
+  {
+    GraphFlag           srcgrafflag;                /* Graph flags */
+  
+--- 137,154 ----
+  SCOTCH_Graph * const        grafptr,
+  FILE * const                stream,
+  const SCOTCH_Num            baseval,
+! const SCOTCH_Num            flagval
+! #ifdef NOFILEIO
+!                                    ,
+! const SCOTCH_Num            nvert,
+! const SCOTCH_Num            nedge2,
+! const SCOTCH_Num*           adjir,
+! const SCOTCH_Num*           adjjc,
+! const SCOTCH_Num*           vertlab,
+! const SCOTCH_Num*           vertwgt,
+! const SCOTCH_Num*           edgewgt
+! #endif /* NOFILEIO */
+!                                    )
+  {
+    GraphFlag           srcgrafflag;                /* Graph flags */
+  
+***************
+*** 153,159 ****
+--- 164,174 ----
+    srcgrafflag = (((flagval & 1) != 0) ? GRAPHIONOLOADVERT : 0) +
+                  (((flagval & 2) != 0) ? GRAPHIONOLOADEDGE : 0);
+  
++ #ifndef NOFILEIO
+    return (graphLoad ((Graph * const) grafptr, stream, (Gnum) baseval, srcgrafflag));
++ #else /* NOFILEIO */
++   return (graphLoad ((Graph * const) grafptr, stream, (Gnum) baseval, srcgrafflag, (const Gnum) nvert, (const Gnum) nedge2, (const Gnum *) adjir, (const Gnum *) adjjc, (const Gnum *) vertlab, (const Gnum *) vertwgt, (const Gnum *) edgewgt));
++ #endif /* NOFILEIO */
+  }
+  
+  /*+ This routine saves the contents of the given
+diff -crB scotch_5.1/src/libscotch/library_graph_f.c src/src/libscotch/library_graph_f.c
+*** scotch_5.1/src/libscotch/library_graph_f.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/library_graph_f.c	2013-05-06 14:14:18.000000000 -0700
+***************
+*** 136,142 ****
+--- 136,146 ----
+    }
+    setbuf (stream, NULL);                          /* Do not buffer on input */
+  
++ #ifndef NOFILEIO
+    o = SCOTCH_graphLoad (grafptr, stream, *baseptr, *flagptr);
++ #else /* NOFILEIO */
++   o = SCOTCH_graphLoad (grafptr, stream, *baseptr, *flagptr, 0, 0, NULL, NULL, NULL, NULL, NULL);
++ #endif /* NOFILEIO */
+  
+    fclose (stream);                                /* This closes filenum too */
+  
+diff -crB scotch_5.1/src/libscotch/library_graph_map.c src/src/libscotch/library_graph_map.c
+*** scotch_5.1/src/libscotch/library_graph_map.c	2008-09-28 04:04:05.000000000 -0700
+--- src/src/libscotch/library_graph_map.c	2013-05-06 14:14:19.000000000 -0700
+***************
+*** 182,192 ****
+--- 182,200 ----
+  
+  int
+  SCOTCH_graphMapSave (
++ #ifdef NOFILEIO
++ Gnum *pnvert,
++ Gnum (**pmaptab)[2],
++ #endif /* NOFILEIO */
+  const SCOTCH_Graph * const    grafptr,            /*+ Graph to order  +*/
+  const SCOTCH_Mapping * const  mappptr,            /*+ Mapping to save +*/
+  FILE * const                  stream)             /*+ Output stream   +*/
+  {
++ #ifndef NOFILEIO
+    return (mapSave (&((LibMapping *) mappptr)->m, ((Graph *) grafptr)->vlbltax, stream));
++ #else /* NOFILEIO */
++   return (mapSave (pnvert, pmaptab, &((LibMapping *) mappptr)->m, ((Graph *) grafptr)->vlbltax, stream));
++ #endif /* NOFILEIO */
+  }
+  
+  /*+ This routine computes a mapping
+diff -crB scotch_5.1/src/libscotch/library_graph_map_f.c src/src/libscotch/library_graph_map_f.c
+*** scotch_5.1/src/libscotch/library_graph_map_f.c	2008-06-28 03:44:26.000000000 -0700
+--- src/src/libscotch/library_graph_map_f.c	2013-05-06 14:14:19.000000000 -0700
+***************
+*** 183,189 ****
+--- 183,193 ----
+      return;
+    }
+  
++ #ifndef NOFILEIO
+    o = SCOTCH_graphMapSave (grafptr, mapptr, stream);
++ #else /* NOFILEIO */
++   o = SCOTCH_graphMapSave (NULL, NULL, grafptr, mapptr, stream);
++ #endif /* NOFILEIO */
+  
+    fclose (stream);                                /* This closes filenum too */
+  
+diff -crB scotch_5.1/src/libscotch/library.h src/src/libscotch/library.h
+*** scotch_5.1/src/libscotch/library.h	2009-05-09 16:08:03.000000000 -0700
+--- src/src/libscotch/library.h	2013-05-06 14:14:19.000000000 -0700
+***************
+*** 1,3 ****
+--- 1,5 ----
++ #ifndef _SCOTCH_H_
++ #define _SCOTCH_H_
+  /* Copyright 2004,2007-2009 ENSEIRB, INRIA & CNRS
+  **
+  ** This file is part of the Scotch software package for static mapping,
+***************
+*** 134,140 ****
+--- 136,146 ----
+  
+  int                         SCOTCH_archInit     (SCOTCH_Arch * const);
+  void                        SCOTCH_archExit     (SCOTCH_Arch * const);
++ #ifndef NOFILEIO
+  int                         SCOTCH_archLoad     (SCOTCH_Arch * const, FILE * const);
++ #else /* NOFILEIO */
++ int                         SCOTCH_archLoad     (SCOTCH_Arch * const, FILE * const, const char *, const SCOTCH_Num, const SCOTCH_Num *);
++ #endif /* NOFILEIO */
+  int                         SCOTCH_archSave     (const SCOTCH_Arch * const, FILE * const);
+  int                         SCOTCH_archBuild    (SCOTCH_Arch * const, const SCOTCH_Graph * const, const SCOTCH_Num, const SCOTCH_Num * const, const SCOTCH_Strat * const);
+  int                         SCOTCH_archCmplt    (SCOTCH_Arch * const, const SCOTCH_Num);
+***************
+*** 191,197 ****
+--- 197,207 ----
+  int                         SCOTCH_graphInit    (SCOTCH_Graph * const);
+  void                        SCOTCH_graphExit    (SCOTCH_Graph * const);
+  void                        SCOTCH_graphFree    (SCOTCH_Graph * const);
++ #ifndef NOFILEIO
+  int                         SCOTCH_graphLoad    (SCOTCH_Graph * const, FILE * const, const SCOTCH_Num, const SCOTCH_Num);
++ #else /* NOFILEIO */
++ int                         SCOTCH_graphLoad    (SCOTCH_Graph * const, FILE * const, const SCOTCH_Num, const SCOTCH_Num, const SCOTCH_Num, const SCOTCH_Num, const SCOTCH_Num *, const SCOTCH_Num *, const SCOTCH_Num *, const SCOTCH_Num *, const SCOTCH_Num *);
++ #endif /* NOFILEIO */
+  int                         SCOTCH_graphSave    (const SCOTCH_Graph * const, FILE * const);
+  int                         SCOTCH_graphBuild   (SCOTCH_Graph * const, const SCOTCH_Num, const SCOTCH_Num, const SCOTCH_Num * const, const SCOTCH_Num * const, const SCOTCH_Num * const, const SCOTCH_Num * const, const SCOTCH_Num, const SCOTCH_Num * const, const SCOTCH_Num * const);
+  SCOTCH_Num                  SCOTCH_graphBase    (SCOTCH_Graph * const, const SCOTCH_Num baseval);
+***************
+*** 210,216 ****
+--- 220,230 ----
+  int                         SCOTCH_graphMapInit (const SCOTCH_Graph * const, SCOTCH_Mapping * const, const SCOTCH_Arch * const, SCOTCH_Num * const);
+  void                        SCOTCH_graphMapExit (const SCOTCH_Graph * const, SCOTCH_Mapping * const);
+  int                         SCOTCH_graphMapLoad (const SCOTCH_Graph * const, const SCOTCH_Mapping * const, FILE * const);
++ #ifndef NOFILEIO
+  int                         SCOTCH_graphMapSave (const SCOTCH_Graph * const, const SCOTCH_Mapping * const, FILE * const);
++ #else /* NOFILEIO */
++ int                         SCOTCH_graphMapSave (SCOTCH_Num *, SCOTCH_Num (**)[2], const SCOTCH_Graph * const, const SCOTCH_Mapping * const, FILE * const);
++ #endif /* NOFILEIO */
+  int                         SCOTCH_graphMapView (const SCOTCH_Graph * const, const SCOTCH_Mapping * const, FILE * const);
+  int                         SCOTCH_graphMapCompute (const SCOTCH_Graph * const, SCOTCH_Mapping * const, const SCOTCH_Strat * const);
+  int                         SCOTCH_graphMap     (const SCOTCH_Graph * const, const SCOTCH_Arch * const, const SCOTCH_Strat * const, SCOTCH_Num * const);
+***************
+*** 278,280 ****
+--- 292,296 ----
+  #ifdef __cplusplus
+  }
+  #endif /* __cplusplus */
++ 
++ #endif //#ifndef _SCOTCH_H_
+diff -crB scotch_5.1/src/libscotch/Makefile src/src/libscotch/Makefile
+*** scotch_5.1/src/libscotch/Makefile	2009-05-09 16:08:04.000000000 -0700
+--- src/src/libscotch/Makefile	2013-05-06 14:14:19.000000000 -0700
+***************
+*** 49,55 ****
+  ##  Project rules.
+  ##
+  
+! .PHONY				:	ptscotch	scotch	ptinstall	install	clean	realclean
+  
+  scotch				:	clean
+  					$(MAKE) CC="$(CCS)" CCD="$(CCS)" SCOTCHLIB=scotch	\
+--- 49,55 ----
+  ##  Project rules.
+  ##
+  
+! .PHONY				:	ptscotch	scotch	nfioscotch	mexscotch	ptinstall	install	nfioinstall	mexinstall	clean	realclean
+  
+  scotch				:	clean
+  					$(MAKE) CC="$(CCS)" CCD="$(CCS)" SCOTCHLIB=scotch	\
+***************
+*** 68,73 ****
+--- 68,93 ----
+  					libptscotcherr$(LIB)								\
+  					libptscotcherrexit$(LIB)
+  
++ nfioscotch				:	clean
++ 					$(MAKE) CFLAGS="$(CFLAGS)" CC="$(CCS)" CCD="$(CCS)" LDFLAGS="$(LDFLAGS)" SCOTCHLIB=scotch	\
++ 					dummysizes$(EXE)
++ 					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO" CC="$(CCS)" CCD="$(CCS)" SCOTCHLIB=nfioscotch	\
++ 					scotch.h						\
++ 					scotchf.h						\
++ 					libnfioscotch$(LIB)						\
++ 					libnfioscotcherr$(LIB)					\
++ 					libnfioscotcherrexit$(LIB)
++ 
++ mexscotch			:	clean
++ 					$(MAKE) CFLAGS="$(CFLAGS)" CC="$(CCS)" CCD="$(CCS)" LDFLAGS="$(LDFLAGS)" SCOTCHLIB=scotch	\
++ 					dummysizes$(EXE)
++ 					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include" CC="$(CCS)" CCD="$(CCS)" LDFLAGS="$(LDFLAGS) -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat" SCOTCHLIB=mexscotch	\
++ 					scotch.h						\
++ 					scotchf.h						\
++ 					libmexscotch$(LIB)						\
++ 					libmexscotcherr$(LIB)					\
++ 					libmexscotcherrexit$(LIB)
++ 
+  install				:
+  					-$(CP) scotch.h scotchf.h $(includedir)
+  					-$(CP) libscotch$(LIB) libscotcherr*$(LIB) $(libdir)
+***************
+*** 77,82 ****
+--- 97,110 ----
+  					-$(CP) scotchf.h $(includedir)/ptscotchf.h
+  					-$(CP) libptscotch*$(LIB) $(libdir)
+  
++ nfioinstall				:
++ 					-$(CP) scotch.h scotchf.h $(includedir)
++ 					-$(CP) libnfioscotch$(LIB) libnfioscotcherr*$(LIB) $(libdir)
++ 
++ mexinstall				:
++ 					-$(CP) scotch.h scotchf.h $(includedir)
++ 					-$(CP) libmexscotch$(LIB) libmexscotcherr*$(LIB) $(libdir)
++ 
+  clean				:
+  					-$(RM) *~ *$(OBJ) lib*$(LIB) common2* parser_yy.c parser_ly.h parser_ll.c *scotch.h *scotchf.h y.output dummysizes$(EXE)
+  
+***************
+*** 2452,2457 ****
+--- 2480,2807 ----
+  					$(AR) $(ARFLAGS) lib$(SCOTCHLIB)$(LIB) $(?)
+  					-$(RANLIB) lib$(SCOTCHLIB)$(LIB)
+  
++ libnfioscotch$(LIB)			:	arch$(OBJ)				\
++ 					arch_build$(OBJ)			\
++ 					arch_cmplt$(OBJ)			\
++ 					arch_cmpltw$(OBJ)			\
++ 					arch_deco$(OBJ)				\
++ 					arch_hcub$(OBJ)				\
++ 					arch_mesh$(OBJ)				\
++ 					arch_tleaf$(OBJ)			\
++ 					arch_torus$(OBJ)			\
++ 					arch_vcmplt$(OBJ)			\
++ 					arch_vhcub$(OBJ)			\
++ 					bgraph$(OBJ)				\
++ 					bgraph_bipart_bd$(OBJ)			\
++ 					bgraph_bipart_df$(OBJ)			\
++ 					bgraph_bipart_ex$(OBJ)			\
++ 					bgraph_bipart_fm$(OBJ)			\
++ 					bgraph_bipart_gg$(OBJ)			\
++ 					bgraph_bipart_gp$(OBJ)			\
++ 					bgraph_bipart_ml$(OBJ)			\
++ 					bgraph_bipart_st$(OBJ)			\
++ 					bgraph_bipart_zr$(OBJ)			\
++ 					bgraph_check$(OBJ)			\
++ 					bgraph_store$(OBJ)			\
++ 					common$(OBJ)				\
++ 					common_file$(OBJ)			\
++ 					common_file_compress$(OBJ)		\
++ 					common_file_uncompress$(OBJ)		\
++ 					common_integer$(OBJ)			\
++ 					common_memory$(OBJ)			\
++ 					common_stub$(OBJ)			\
++ 					gain$(OBJ)				\
++ 					geom$(OBJ)				\
++ 					graph$(OBJ)				\
++ 					graph_base$(OBJ)			\
++ 					graph_check$(OBJ)			\
++ 					graph_coarsen$(OBJ)			\
++ 					graph_induce$(OBJ)			\
++ 					graph_io$(OBJ)				\
++ 					graph_io_chac$(OBJ)			\
++ 					graph_io_habo$(OBJ)			\
++ 					graph_io_mmkt$(OBJ)			\
++ 					graph_io_scot$(OBJ)			\
++ 					graph_list$(OBJ)			\
++ 					hall_order_hd$(OBJ)			\
++ 					hall_order_hf$(OBJ)			\
++ 					hall_order_hx$(OBJ)			\
++ 					hgraph$(OBJ)				\
++ 					hgraph_check$(OBJ)			\
++ 					hgraph_induce$(OBJ)			\
++ 					hgraph_order_bl$(OBJ)			\
++ 					hgraph_order_cp$(OBJ)			\
++ 					hgraph_order_gp$(OBJ)			\
++ 					hgraph_order_hd$(OBJ)			\
++ 					hgraph_order_hf$(OBJ)			\
++ 					hgraph_order_hx$(OBJ)			\
++ 					hgraph_order_nd$(OBJ)			\
++ 					hgraph_order_si$(OBJ)			\
++ 					hgraph_order_st$(OBJ)			\
++ 					hmesh$(OBJ)				\
++ 					hmesh_check$(OBJ)			\
++ 					hmesh_hgraph$(OBJ)			\
++ 					hmesh_induce$(OBJ)			\
++ 					hmesh_mesh$(OBJ)			\
++ 					hmesh_order_bl$(OBJ)			\
++ 					hmesh_order_cp$(OBJ)			\
++ 					hmesh_order_gr$(OBJ)			\
++ 					hmesh_order_gp$(OBJ)			\
++ 					hmesh_order_hd$(OBJ)			\
++ 					hmesh_order_hf$(OBJ)			\
++ 					hmesh_order_hx$(OBJ)			\
++ 					hmesh_order_nd$(OBJ)			\
++ 					hmesh_order_si$(OBJ)			\
++ 					hmesh_order_st$(OBJ)			\
++ 					kgraph$(OBJ)				\
++ 					kgraph_map_rb$(OBJ)			\
++ 					kgraph_map_rb_map$(OBJ)			\
++ 					kgraph_map_rb_part$(OBJ)		\
++ 					kgraph_map_st$(OBJ)			\
++ 					library_arch$(OBJ)			\
++ 					library_arch_f$(OBJ)			\
++ 					library_arch_build$(OBJ)		\
++ 					library_arch_build_f$(OBJ)		\
++ 					library_arch_cmpltw$(OBJ)		\
++ 					library_arch_cmpltw_f$(OBJ)		\
++ 					library_geom$(OBJ)			\
++ 					library_geom_f$(OBJ)			\
++ 					library_graph$(OBJ)			\
++ 					library_graph_f$(OBJ)			\
++ 					library_graph_base$(OBJ)		\
++ 					library_graph_base_f$(OBJ)		\
++ 					library_graph_check$(OBJ)		\
++ 					library_graph_check_f$(OBJ)		\
++ 					library_graph_io_chac$(OBJ)		\
++ 					library_graph_io_chac_f$(OBJ)		\
++ 					library_graph_io_habo$(OBJ)		\
++ 					library_graph_io_habo_f$(OBJ)		\
++ 					library_graph_io_mmkt$(OBJ)		\
++ 					library_graph_io_mmkt_f$(OBJ)		\
++ 					library_graph_io_scot$(OBJ)		\
++ 					library_graph_io_scot_f$(OBJ)		\
++ 					library_graph_map$(OBJ)			\
++ 					library_graph_map_f$(OBJ)		\
++ 					library_graph_map_view$(OBJ)		\
++ 					library_graph_map_view_f$(OBJ)		\
++ 					library_graph_order$(OBJ)		\
++ 					library_graph_order_f$(OBJ)		\
++ 					library_mesh$(OBJ)			\
++ 					library_mesh_f$(OBJ)			\
++ 					library_mesh_graph$(OBJ)		\
++ 					library_mesh_graph_f$(OBJ)		\
++ 					library_mesh_io_habo$(OBJ)		\
++ 					library_mesh_io_habo_f$(OBJ)		\
++ 					library_mesh_io_scot$(OBJ)		\
++ 					library_mesh_io_scot_f$(OBJ)		\
++ 					library_mesh_order$(OBJ)		\
++ 					library_mesh_order_f$(OBJ)		\
++ 					library_parser$(OBJ)			\
++ 					library_parser_f$(OBJ)			\
++ 					library_random$(OBJ)			\
++ 					library_random_f$(OBJ)			\
++ 					mapping$(OBJ)				\
++ 					mapping_io$(OBJ)			\
++ 					mesh$(OBJ)				\
++ 					mesh_check$(OBJ)			\
++ 					mesh_coarsen$(OBJ)			\
++ 					mesh_graph$(OBJ)			\
++ 					mesh_induce_sepa$(OBJ)			\
++ 					mesh_io$(OBJ)				\
++ 					mesh_io_habo$(OBJ)			\
++ 					mesh_io_scot$(OBJ)			\
++ 					order$(OBJ)				\
++ 					order_check$(OBJ)			\
++ 					order_io$(OBJ)				\
++ 					parser$(OBJ)				\
++ 					parser_ll$(OBJ)				\
++ 					parser_yy$(OBJ)				\
++ 					vgraph$(OBJ)				\
++ 					vgraph_check$(OBJ)			\
++ 					vgraph_separate_bd$(OBJ)		\
++ 					vgraph_separate_es$(OBJ)		\
++ 					vgraph_separate_fm$(OBJ)		\
++ 					vgraph_separate_gg$(OBJ)		\
++ 					vgraph_separate_gp$(OBJ)		\
++ 					vgraph_separate_ml$(OBJ)		\
++ 					vgraph_separate_st$(OBJ)		\
++ 					vgraph_separate_th$(OBJ)		\
++ 					vgraph_separate_vw$(OBJ)		\
++ 					vgraph_separate_zr$(OBJ)		\
++ 					vgraph_store$(OBJ)			\
++ 					vmesh$(OBJ)				\
++ 					vmesh_check$(OBJ)			\
++ 					vmesh_separate_fm$(OBJ)			\
++ 					vmesh_separate_gg$(OBJ)			\
++ 					vmesh_separate_gr$(OBJ)			\
++ 					vmesh_separate_ml$(OBJ)			\
++ 					vmesh_separate_zr$(OBJ)			\
++ 					vmesh_separate_st$(OBJ)			\
++ 					vmesh_store$(OBJ)
++ 					$(AR) $(ARFLAGS) lib$(SCOTCHLIB)$(LIB) $(?)
++ 					-$(RANLIB) lib$(SCOTCHLIB)$(LIB)
++ 
++ libmexscotch$(LIB)			:	arch$(OBJ)				\
++ 					arch_build$(OBJ)			\
++ 					arch_cmplt$(OBJ)			\
++ 					arch_cmpltw$(OBJ)			\
++ 					arch_deco$(OBJ)				\
++ 					arch_hcub$(OBJ)				\
++ 					arch_mesh$(OBJ)				\
++ 					arch_tleaf$(OBJ)			\
++ 					arch_torus$(OBJ)			\
++ 					arch_vcmplt$(OBJ)			\
++ 					arch_vhcub$(OBJ)			\
++ 					bgraph$(OBJ)				\
++ 					bgraph_bipart_bd$(OBJ)			\
++ 					bgraph_bipart_df$(OBJ)			\
++ 					bgraph_bipart_ex$(OBJ)			\
++ 					bgraph_bipart_fm$(OBJ)			\
++ 					bgraph_bipart_gg$(OBJ)			\
++ 					bgraph_bipart_gp$(OBJ)			\
++ 					bgraph_bipart_ml$(OBJ)			\
++ 					bgraph_bipart_st$(OBJ)			\
++ 					bgraph_bipart_zr$(OBJ)			\
++ 					bgraph_check$(OBJ)			\
++ 					bgraph_store$(OBJ)			\
++ 					common$(OBJ)				\
++ 					common_file$(OBJ)			\
++ 					common_file_compress$(OBJ)		\
++ 					common_file_uncompress$(OBJ)		\
++ 					common_integer$(OBJ)			\
++ 					common_memory$(OBJ)			\
++ 					common_stub$(OBJ)			\
++ 					gain$(OBJ)				\
++ 					geom$(OBJ)				\
++ 					graph$(OBJ)				\
++ 					graph_base$(OBJ)			\
++ 					graph_check$(OBJ)			\
++ 					graph_coarsen$(OBJ)			\
++ 					graph_induce$(OBJ)			\
++ 					graph_io$(OBJ)				\
++ 					graph_io_chac$(OBJ)			\
++ 					graph_io_habo$(OBJ)			\
++ 					graph_io_mmkt$(OBJ)			\
++ 					graph_io_scot$(OBJ)			\
++ 					graph_list$(OBJ)			\
++ 					hall_order_hd$(OBJ)			\
++ 					hall_order_hf$(OBJ)			\
++ 					hall_order_hx$(OBJ)			\
++ 					hgraph$(OBJ)				\
++ 					hgraph_check$(OBJ)			\
++ 					hgraph_induce$(OBJ)			\
++ 					hgraph_order_bl$(OBJ)			\
++ 					hgraph_order_cp$(OBJ)			\
++ 					hgraph_order_gp$(OBJ)			\
++ 					hgraph_order_hd$(OBJ)			\
++ 					hgraph_order_hf$(OBJ)			\
++ 					hgraph_order_hx$(OBJ)			\
++ 					hgraph_order_nd$(OBJ)			\
++ 					hgraph_order_si$(OBJ)			\
++ 					hgraph_order_st$(OBJ)			\
++ 					hmesh$(OBJ)				\
++ 					hmesh_check$(OBJ)			\
++ 					hmesh_hgraph$(OBJ)			\
++ 					hmesh_induce$(OBJ)			\
++ 					hmesh_mesh$(OBJ)			\
++ 					hmesh_order_bl$(OBJ)			\
++ 					hmesh_order_cp$(OBJ)			\
++ 					hmesh_order_gr$(OBJ)			\
++ 					hmesh_order_gp$(OBJ)			\
++ 					hmesh_order_hd$(OBJ)			\
++ 					hmesh_order_hf$(OBJ)			\
++ 					hmesh_order_hx$(OBJ)			\
++ 					hmesh_order_nd$(OBJ)			\
++ 					hmesh_order_si$(OBJ)			\
++ 					hmesh_order_st$(OBJ)			\
++ 					kgraph$(OBJ)				\
++ 					kgraph_map_rb$(OBJ)			\
++ 					kgraph_map_rb_map$(OBJ)			\
++ 					kgraph_map_rb_part$(OBJ)		\
++ 					kgraph_map_st$(OBJ)			\
++ 					library_arch$(OBJ)			\
++ 					library_arch_f$(OBJ)			\
++ 					library_arch_build$(OBJ)		\
++ 					library_arch_build_f$(OBJ)		\
++ 					library_arch_cmpltw$(OBJ)		\
++ 					library_arch_cmpltw_f$(OBJ)		\
++ 					library_geom$(OBJ)			\
++ 					library_geom_f$(OBJ)			\
++ 					library_graph$(OBJ)			\
++ 					library_graph_f$(OBJ)			\
++ 					library_graph_base$(OBJ)		\
++ 					library_graph_base_f$(OBJ)		\
++ 					library_graph_check$(OBJ)		\
++ 					library_graph_check_f$(OBJ)		\
++ 					library_graph_io_chac$(OBJ)		\
++ 					library_graph_io_chac_f$(OBJ)		\
++ 					library_graph_io_habo$(OBJ)		\
++ 					library_graph_io_habo_f$(OBJ)		\
++ 					library_graph_io_mmkt$(OBJ)		\
++ 					library_graph_io_mmkt_f$(OBJ)		\
++ 					library_graph_io_scot$(OBJ)		\
++ 					library_graph_io_scot_f$(OBJ)		\
++ 					library_graph_map$(OBJ)			\
++ 					library_graph_map_f$(OBJ)		\
++ 					library_graph_map_view$(OBJ)		\
++ 					library_graph_map_view_f$(OBJ)		\
++ 					library_graph_order$(OBJ)		\
++ 					library_graph_order_f$(OBJ)		\
++ 					library_mesh$(OBJ)			\
++ 					library_mesh_f$(OBJ)			\
++ 					library_mesh_graph$(OBJ)		\
++ 					library_mesh_graph_f$(OBJ)		\
++ 					library_mesh_io_habo$(OBJ)		\
++ 					library_mesh_io_habo_f$(OBJ)		\
++ 					library_mesh_io_scot$(OBJ)		\
++ 					library_mesh_io_scot_f$(OBJ)		\
++ 					library_mesh_order$(OBJ)		\
++ 					library_mesh_order_f$(OBJ)		\
++ 					library_parser$(OBJ)			\
++ 					library_parser_f$(OBJ)			\
++ 					library_random$(OBJ)			\
++ 					library_random_f$(OBJ)			\
++ 					mapping$(OBJ)				\
++ 					mapping_io$(OBJ)			\
++ 					mesh$(OBJ)				\
++ 					mesh_check$(OBJ)			\
++ 					mesh_coarsen$(OBJ)			\
++ 					mesh_graph$(OBJ)			\
++ 					mesh_induce_sepa$(OBJ)			\
++ 					mesh_io$(OBJ)				\
++ 					mesh_io_habo$(OBJ)			\
++ 					mesh_io_scot$(OBJ)			\
++ 					order$(OBJ)				\
++ 					order_check$(OBJ)			\
++ 					order_io$(OBJ)				\
++ 					parser$(OBJ)				\
++ 					parser_ll$(OBJ)				\
++ 					parser_yy$(OBJ)				\
++ 					vgraph$(OBJ)				\
++ 					vgraph_check$(OBJ)			\
++ 					vgraph_separate_bd$(OBJ)		\
++ 					vgraph_separate_es$(OBJ)		\
++ 					vgraph_separate_fm$(OBJ)		\
++ 					vgraph_separate_gg$(OBJ)		\
++ 					vgraph_separate_gp$(OBJ)		\
++ 					vgraph_separate_ml$(OBJ)		\
++ 					vgraph_separate_st$(OBJ)		\
++ 					vgraph_separate_th$(OBJ)		\
++ 					vgraph_separate_vw$(OBJ)		\
++ 					vgraph_separate_zr$(OBJ)		\
++ 					vgraph_store$(OBJ)			\
++ 					vmesh$(OBJ)				\
++ 					vmesh_check$(OBJ)			\
++ 					vmesh_separate_fm$(OBJ)			\
++ 					vmesh_separate_gg$(OBJ)			\
++ 					vmesh_separate_gr$(OBJ)			\
++ 					vmesh_separate_ml$(OBJ)			\
++ 					vmesh_separate_zr$(OBJ)			\
++ 					vmesh_separate_st$(OBJ)			\
++ 					vmesh_store$(OBJ)
++ 					$(AR) $(ARFLAGS) lib$(SCOTCHLIB)$(LIB) $(?)
++ 					-$(RANLIB) lib$(SCOTCHLIB)$(LIB)
++ 
+  libptscotcherr$(LIB)		:	library_error$(OBJ)
+  					$(AR) $(ARFLAGS) $(@) $(?)
+  					-$(RANLIB) $(@)
+***************
+*** 2467,2469 ****
+--- 2817,2835 ----
+  libscotcherrexit$(LIB)		:	library_error_exit$(OBJ)
+  					$(AR) $(ARFLAGS) $(@) $(?)
+  					-$(RANLIB) $(@)
++ 
++ libnfioscotcherr$(LIB)		:	library_error$(OBJ)
++ 					$(AR) $(ARFLAGS) $(@) $(?)
++ 					-$(RANLIB) $(@)
++ 
++ libnfioscotcherrexit$(LIB)		:	library_error_exit$(OBJ)
++ 					$(AR) $(ARFLAGS) $(@) $(?)
++ 					-$(RANLIB) $(@)
++ 
++ libmexscotcherr$(LIB)		:	library_error$(OBJ)
++ 					$(AR) $(ARFLAGS) $(@) $(?)
++ 					-$(RANLIB) $(@)
++ 
++ libmexscotcherrexit$(LIB)		:	library_error_exit$(OBJ)
++ 					$(AR) $(ARFLAGS) $(@) $(?)
++ 					-$(RANLIB) $(@)
+diff -crB scotch_5.1/src/libscotch/mapping.h src/src/libscotch/mapping.h
+*** scotch_5.1/src/libscotch/mapping.h	2008-10-27 08:27:47.000000000 -0700
+--- src/src/libscotch/mapping.h	2013-05-06 14:14:20.000000000 -0700
+***************
+*** 106,112 ****
+--- 106,116 ----
+  int                         mapInit2            (Mapping * restrict const, const Gnum, const Gnum, const Arch * restrict const, const ArchDom * restrict const);
+  void                        mapExit             (Mapping * const);
+  int                         mapLoad             (Mapping * restrict const, const Gnum * restrict const, FILE * restrict const);
++ #ifndef NOFILEIO
+  int                         mapSave             (const Mapping * restrict const, const Gnum * restrict const, FILE * restrict const);
++ #else /* NOFILEIO */
++ int                         mapSave             (Gnum *, Gnum (**)[2], const Mapping * restrict const, const Gnum * restrict const, FILE * restrict const);
++ #endif /* NOFILEIO */
+  int                         mapView             (const Mapping * restrict const, const Graph * restrict const, FILE * const);
+  
+  #undef static
+diff -crB scotch_5.1/src/libscotch/mapping_io.c src/src/libscotch/mapping_io.c
+*** scotch_5.1/src/libscotch/mapping_io.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/mapping_io.c	2013-05-06 14:14:20.000000000 -0700
+***************
+*** 199,204 ****
+--- 199,208 ----
+  
+  int
+  mapSave (
++ #ifdef NOFILEIO
++ Gnum *pnvert,
++ Gnum (**pmaptab)[2],
++ #endif /* NOFILEIO */
+  const Mapping * restrict const  mappptr,
+  const Gnum * restrict const     vlbltab,
+  FILE * restrict const           stream)
+***************
+*** 206,226 ****
+    const Gnum * restrict vlbltax;
+    Gnum                  vertnum;
+  
+    vlbltax = (vlbltab != NULL) ? (vlbltab - mappptr->baseval) : NULL;
+  
+    if (fprintf (stream, "%ld\n", (long) mappptr->vertnbr) == EOF) {
+      errorPrint ("mapSave: bad output (1)");
+      return     (1);
+    }
+  
+    for (vertnum = mappptr->baseval; vertnum < (mappptr->vertnbr + mappptr->baseval); vertnum ++) {
+      if (fprintf (stream, "%ld\t%ld\n",
+!                  (long) ((vlbltax != NULL) ? vlbltax[vertnum] : vertnum),
+                   (long) archDomNum (&mappptr->archdat, &mappptr->domntab[mappptr->parttax[vertnum]])) == EOF) {
+        errorPrint ("mapSave: bad output (2)");
+        return     (1);
+      }
+    }
+  
+    return (0);
+  }
+--- 210,258 ----
+    const Gnum * restrict vlbltax;
+    Gnum                  vertnum;
+  
++ #ifdef NOFILEIO
++ //  printf("mapSave - stream=%p\n",stream);
++ #endif /* NOFILEIO */
+    vlbltax = (vlbltab != NULL) ? (vlbltab - mappptr->baseval) : NULL;
+  
++ #ifndef NOFILEIO
+    if (fprintf (stream, "%ld\n", (long) mappptr->vertnbr) == EOF) {
+      errorPrint ("mapSave: bad output (1)");
+      return     (1);
+    }
++ #else /* NOFILEIO */
++   if (pnvert) {
++     *pnvert=mappptr->vertnbr;
++ //    printf("mapSave - nvert=%d\n",*pnvert);
++   }
++   if (pmaptab) {
++     *pmaptab = (Gnum (*)[2]) malloc(mappptr->vertnbr*2*sizeof(Gnum));
++ //    printf("mapSave - maptab=%p\n",*pmaptab);
++   }
++ #endif /* NOFILEIO */
+  
++ #ifndef NOFILEIO
+    for (vertnum = mappptr->baseval; vertnum < (mappptr->vertnbr + mappptr->baseval); vertnum ++) {
+      if (fprintf (stream, "%ld\t%ld\n",
+! /*  not sure why, but need to offset vlbltax in other direction (jes, 12/11/09)  */
+! //                 (long) ((vlbltax != NULL) ? vlbltax[vertnum] : vertnum),
+!                  (long) ((vlbltax != NULL) ? vlbltax[vertnum+mappptr->baseval] : vertnum),
+                   (long) archDomNum (&mappptr->archdat, &mappptr->domntab[mappptr->parttax[vertnum]])) == EOF) {
+        errorPrint ("mapSave: bad output (2)");
+        return     (1);
+      }
+    }
++ #else /* NOFILEIO */
++   if (pmaptab && *pmaptab)
++     for (vertnum = mappptr->baseval; vertnum < (mappptr->vertnbr + mappptr->baseval); vertnum ++) {
++ /*  not sure why, but need to offset vlbltax in other direction (jes, 12/11/09)  */
++ //      (*pmaptab)[vertnum-mappptr->baseval][0]=((vlbltax != NULL) ? vlbltax[vertnum] : vertnum);
++       (*pmaptab)[vertnum-mappptr->baseval][0]=((vlbltax != NULL) ? vlbltax[vertnum+mappptr->baseval] : vertnum);
++       (*pmaptab)[vertnum-mappptr->baseval][1]=archDomNum (&mappptr->archdat, &mappptr->domntab[mappptr->parttax[vertnum]]);
++ //    printf("mapSave - vertnum=%d; vlbltax=%d,archDomNum=%d\n",
++ //           vertnum,((vlbltax != NULL) ? vlbltax[vertnum+mappptr->baseval] : -1),archDomNum (&mappptr->archdat, &mappptr->domntab[mappptr->parttax[vertnum]]));
++     }
++ #endif /* NOFILEIO */
+  
+    return (0);
+  }
+diff -crB scotch_5.1/src/libscotch/mesh_io_scot.c src/src/libscotch/mesh_io_scot.c
+*** scotch_5.1/src/libscotch/mesh_io_scot.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/mesh_io_scot.c	2013-05-06 14:14:20.000000000 -0700
+***************
+*** 85,91 ****
+--- 85,95 ----
+    int                           o;
+  
+    if (filesrcptr != NULL) {
++ #ifndef NOFILEIO
+      if (graphLoad (meshptr, filesrcptr, -1, 0) != 0)
++ #else /* NOFILEIO */
++     if (graphLoad (meshptr, filesrcptr, -1, 0, 0, 0, NULL, NULL, NULL, NULL, NULL) != 0)
++ #endif /* NOFILEIO */
+        return (1);
+    }
+  
+diff -crB scotch_5.1/src/libscotch/module.h src/src/libscotch/module.h
+*** scotch_5.1/src/libscotch/module.h	2009-04-26 23:07:14.000000000 -0700
+--- src/src/libscotch/module.h	2013-05-06 14:14:20.000000000 -0700
+***************
+*** 1,3 ****
+--- 1,5 ----
++ #ifndef _SCOTCH_MODULE_H_
++ #define _SCOTCH_MODULE_H_
+  /* Copyright 2004,2007-2009 ENSEIRB, INRIA & CNRS
+  **
+  ** This file is part of the Scotch software package for static mapping,
+***************
+*** 55,60 ****
+--- 57,65 ----
+  
+  #define MODULE_H
+  
++ /*Don't forget stdint.h:*/
++ #include "stdint.h"
++ 
+  /*
+  ** Collective communication handling.
+  */
+***************
+*** 156,161 ****
+--- 161,167 ----
+  #define intSave                     _SCOTCHintSave
+  #define intAscn                     _SCOTCHintAscn
+  #define intPerm                     _SCOTCHintPerm
++ #define intRandResetStatic          _SCOTCHintRandResetStatic
+  #define intRandReset                _SCOTCHintRandReset
+  #define intRandInit                 _SCOTCHintRandInit
+  /* #define intRandVal               _SCOTCHintRandVal Already a macro */
+***************
+*** 681,683 ****
+--- 687,691 ----
+  #define vmeshStoreSave              _SCOTCHvmeshStoreSave
+  #define vmeshStoreUpdt              _SCOTCHvmeshStoreUpdt
+  #endif /* SCOTCH_RENAME */
++ 
++ #endif //#ifndef _SCOTCH_MODULE_H_
+diff -crB scotch_5.1/src/libscotch/parser_ll.l src/src/libscotch/parser_ll.l
+*** scotch_5.1/src/libscotch/parser_ll.l	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/parser_ll.l	2013-05-06 14:14:21.000000000 -0700
+***************
+*** 192,197 ****
+--- 192,214 ----
+  stratParserInit (
+  const char * const          string)               /*+ Strategy string to parse +*/
+  {
++ /*  reset static variables from previous runs (jes, 4/29/10)  */
++   yy_current_buffer = 0;
++   yy_hold_char = (char) 0;
++   yy_n_chars=0;          /* number of characters read into yy_ch_buf */
++   yy_c_buf_p = (char *) 0;
++   yy_init = 1;         /* whether we need to initialize */
++   yy_start = 0;        /* start state number */
++   yy_did_buffer_switch_on_eof=0;
++   yy_last_accepting_state=0;
++   yy_last_accepting_cpos = (char *) 0;
++   stratparserstringptr = (char *) 0; /* Pointer to the string to parse */
++ #if YY_STACK_USED
++   yy_start_stack_ptr = 0;
++   yy_start_stack_depth = 0;
++   yy_start_stack = 0;
++ #endif
++ 
+  #ifdef FLEX_SCANNER
+    yyrestart (yyin);                               /* (Re-)initialize the parser */
+  #endif /* FLEX_SCANNER */
+diff -crB scotch_5.1/src/libscotch/parser_yy.y src/src/libscotch/parser_yy.y
+*** scotch_5.1/src/libscotch/parser_yy.y	2008-10-22 15:12:48.000000000 -0700
+--- src/src/libscotch/parser_yy.y	2013-05-06 14:14:21.000000000 -0700
+***************
+*** 774,779 ****
+--- 774,780 ----
+    stratParserInit (string);                       /* Initialize the lexical parser           */
+    parserstrattab  = strattab;                     /* Point to the parsing tables             */
+    parserstratcurr = NULL;                         /* Clear up the temporary strategy pointer */
++   parserparamcurr = NULL;                         /* reset the last static (jes, 4/29/10)    */
+  
+    if (stratParserParse2 () != 0) {                /* Parse the strategy string */
+      if (parserstratcurr != NULL)
+diff -crB scotch_5.1/src/libscotch/vgraph_separate_vw.c src/src/libscotch/vgraph_separate_vw.c
+*** scotch_5.1/src/libscotch/vgraph_separate_vw.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/vgraph_separate_vw.c	2013-05-06 14:14:21.000000000 -0700
+***************
+*** 83,88 ****
+--- 83,89 ----
+    FILE * restrict     fileptr;
+    Gnum                vertnum;                    /* Vertex number */
+  
++   printf("vgraphSeparateVw begin -- vgraphseparatevwfilenum=%d\n",vgraphseparatevwfilenum);
+    sprintf (nametab, "vgraphseparatevw_output_%08d.map", vgraphseparatevwfilenum ++);
+    if ((fileptr = fopen (nametab, "w+")) == NULL) {
+      errorPrint ("vgraphSeparateVw: cannot open partition file");
+***************
+*** 102,106 ****
+--- 103,108 ----
+      }
+    }
+  
++   printf("vgraphSeparateVw end   -- vgraphseparatevwfilenum=%d\n",vgraphseparatevwfilenum);
+    return (0);
+  }
+diff -crB scotch_5.1/src/Makefile src/src/Makefile
+*** scotch_5.1/src/Makefile	2008-09-15 05:50:51.000000000 -0700
+--- src/src/Makefile	2013-05-06 14:14:21.000000000 -0700
+***************
+*** 97,102 ****
+--- 97,109 ----
+  					(cd scotch ;         $(MAKE) VERSION=\"$(VERSION)\" ptscotch && $(MAKE) ptinstall)
+  					(cd libscotchmetis ; $(MAKE)                        ptscotch && $(MAKE) ptinstall)
+  
++ nfioscotch			:	required
++ 					(cd libscotch ;      $(MAKE) VERSION=\"$(VERSION)\" nfioscotch && $(MAKE) nfioinstall)
++ 
++ mexscotch			:	required
++ 					(cd libscotch ;      $(MAKE) VERSION=\"$(VERSION)\" mexscotch && $(MAKE) mexinstall)
++ 					(cd scotch ;         $(MAKE) VERSION=\"$(VERSION)\" mexscotch && $(MAKE) mexinstall)
++ 
+  install				:	required	$(bindir)	$(includedir)	$(libdir)	$(mandir)/man1
+  					-$(CP) -f ../bin/[agm]*$(EXE) $(bindir)
+  					-$(CP) -f ../include/*scotch*.h $(includedir)
+Only in src/src: Makefile.inc
+diff -crB scotch_5.1/src/scotch/gmap.h src/src/scotch/gmap.h
+*** scotch_5.1/src/scotch/gmap.h	2008-06-18 11:05:17.000000000 -0700
+--- src/src/scotch/gmap.h	2013-05-06 14:14:22.000000000 -0700
+***************
+*** 1,3 ****
+--- 1,5 ----
++ #ifndef _SCOTCH_GMAP_H_
++ #define _SCOTCH_GMAP_H_
+  /* Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS
+  **
+  ** This file is part of the Scotch software package for static mapping,
+***************
+*** 87,89 ****
+--- 89,93 ----
+  #define C_FLAGVERBSTR               0x0002        /* Verbose flags */
+  #define C_FLAGVERBTIM               0x0004
+  #define C_FLAGVERBMAP               0x0008
++ 
++ #endif //#ifndef _SCOTCH_GMAP_H_
+Only in src/src/scotch: gmap_mex.c
+Only in src/src/scotch: gmapx.c
+diff -crB scotch_5.1/src/scotch/Makefile src/src/scotch/Makefile
+*** scotch_5.1/src/scotch/Makefile	2009-04-27 02:19:43.000000000 -0700
+--- src/src/scotch/Makefile	2013-05-06 14:14:22.000000000 -0700
+***************
+*** 49,59 ****
+  %$(EXE)	:	%.c
+  		 		$(CC) $(CFLAGS) -I$(includedir) -I../libscotch -DSCOTCH_VERSION=\"$(VERSION)\" $(<) -o $(@) -L$(libdir) -l$(SCOTCHLIB) -l$(SCOTCHLIB)errexit $(LDFLAGS)
+  
+  ##
+  ##  Project rules.
+  ##
+  
+! .PHONY				:	ptscotch	scotch	ptinstall	install	clean	realclean
+  
+  scotch				:	clean
+  					$(MAKE) CC="$(CCS)" SCOTCHLIB=scotch	\
+--- 49,62 ----
+  %$(EXE)	:	%.c
+  		 		$(CC) $(CFLAGS) -I$(includedir) -I../libscotch -DSCOTCH_VERSION=\"$(VERSION)\" $(<) -o $(@) -L$(libdir) -l$(SCOTCHLIB) -l$(SCOTCHLIB)errexit $(LDFLAGS)
+  
++ %$(MEX)	:	%.c
++ 		 		$(CCM) $(MFLAGS) -I$(includedir) -I../libscotch -DSCOTCH_VERSION=\"$(VERSION)\" $(<) -o $(@) -L$(libdir) -l$(SCOTCHLIB) -l$(SCOTCHLIB)errexit $(LDFLAGS)
++ 
+  ##
+  ##  Project rules.
+  ##
+  
+! .PHONY				:	ptscotch	scotch	mexscotch	ptinstall	install	mexinstall	clean	realclean
+  
+  scotch				:	clean
+  					$(MAKE) CC="$(CCS)" SCOTCHLIB=scotch	\
+***************
+*** 94,99 ****
+--- 97,108 ----
+  					dgscat$(EXE)				\
+  					dgtst$(EXE)
+  
++ mexscotch			:	clean
++ 					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include" CC="$(CCS)" CCD="$(CCS)" LDFLAGS="$(LDFLAGS) -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat" SCOTCHLIB=mexscotch \
++                     gmapx$(OBJ)
++ 					$(MAKE) CFLAGS="$(CFLAGS) -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include" CC="$(CCS)" LDFLAGS="$(LDFLAGS) -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat gmapx$(OBJ)" SCOTCHLIB=mexscotch	\
++ 					gmap_mex$(MEX)
++ 
+  install				:
+  					-$(CP) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) gmap$(EXE) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) gord$(EXE) gotst$(EXE) gout$(EXE) *gtst$(EXE) gscat$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE) $(bindir)
+  					-$(RM) $(bindir)/gpart$(EXE)
+***************
+*** 104,111 ****
+--- 113,126 ----
+  					-$(RM) $(bindir)/dgpart$(EXE)
+  					-$(LN) $(bindir)/dgmap$(EXE) $(bindir)/dgpart$(EXE)
+  
++ mexinstall			:
++ 					-$(CP) gmap_mex$(MEX) $(bindir)
++ 					-$(RM) $(bindir)/gpart_mex$(MEX)
++ 					-$(LN) $(bindir)/gmap_mex$(MEX) $(bindir)/gpart_mex$(MEX)
++ 
+  clean				:
+  					-$(RM) *~ *$(OBJ) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) *gmap$(EXE) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) *gord$(EXE) gotst$(EXE) gout$(EXE) *gpart$(EXE) *gscat$(EXE) *gtst$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE)
++ 					-$(RM) gmap_mex$(MEX)
+  
+  realclean			:	clean
+  
+***************
+*** 365,367 ****
+--- 380,403 ----
+  					$(libdir)/libscotch$(LIB)		\
+  					$(libdir)/libscotcherrexit$(LIB)	\
+  					mtst.h
++ 
++ gmapx$(OBJ)			:	gmapx.c					\
++ 					../libscotch/module.h			\
++ 					../libscotch/common.h			\
++ 					$(includedir)/scotch.h			\
++ 					$(libdir)/libmexscotch$(LIB)		\
++ 					$(libdir)/libmexscotcherrexit$(LIB)	\
++ 					gmap.h
++ 
++ gmap_mex$(MEX)		:	gmap_mex.c					\
++ 					../libscotch/module.h			\
++ 					../libscotch/common.h			\
++ 					$(includedir)/scotch.h			\
++ 					$(libdir)/libmexscotch$(LIB)		\
++ 					$(libdir)/libmexscotcherrexit$(LIB)	\
++ 					gmap.h
++ 
++ gpart_mex$(MEX)			:	gmap_mex$(MEX)
++ 					-$(RM) gpart_mex$(MEX)
++ 					-$(LN) gmap_mex$(MEX) gpart_mex$(MEX)
++ 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_README.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_README.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_README.txt	(revision 18231)
@@ -0,0 +1,296 @@
+8/06/09:
+
+following INSTALL.txt:
+- GNU Make 3.81, lex, yacc all present
+
+
+[jschierm@astrid src]$ diff Makefile_old.inc Makefile.inc
+
+- started with Makefile.inc.i686_sun_solaris5
+- changed CCS from cc to gcc
+- removed SCOTCH_PTHREAD, since MPICH2 1.0.2p1 is prior to 1.0.7
+- added -std=c99 to CFLAGS for "restrict" attribute (based on various internet pages)
+- added -DCOMMON_TIMING_OLD to CFLAGS for undeclared CLOCK_REALTIME (based on common2.c)
+- added MEX, CCM, and MFLAGS for Matlab mex modules (as well as Matlab libraries and -largeArrayDims)
+- removed -DCOMMON_PTHREAD from CFLAGS and MFLAGS to eliminate fatal exception at pthread_exit in gmap_mex.c
+- removed -DCOMMON_FILE_COMPRESS_GZ from CFLAGS and MFLAGS since gzip not used
+- added -Wl,-rpath-link,/usr/local/pkgs/matlab-7.6/bin/glnxa64 to LDFLAGS to eliminate missing libhdf5.so.0 in Matlab directories (based on Cielo make)
+
+3a4
+> MEX   = .mexa64
+12,13c13,16
+< CFLAGS        = -m64 -O3 -std=c99 -DCOMMON_FILE_COMPRESS_GZ -DCOMMON_PTHREAD -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DINTSIZE64 -Dintptr_t="long int" -DCOMMON_TIMING_OLD
+< LDFLAGS       = -lz -lm -lrt
+---
+> CCM   = mex
+> CFLAGS        = -m64 -O3 -std=c99 -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DMATLAB -fPIC -I/usr/local/pkgs/matlab-7.6/extern/include
+> LDFLAGS       = -lz -lm -lrt -Wl,-rpath-link,/usr/local/pkgs/matlab-7.6/bin/glnxa64 -L/usr/local/pkgs/matlab-7.6/bin/glnxa64 -lmex -lmat
+> MFLAGS        = -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DMATLAB -I/usr/local/pkgs/matlab-7.6/extern/include -largeArrayDims
+
+
+[jschierm@astrid libscotch]$ diff common_old.c common.c
+
+- redirect usagePrint to within Matlab
+102a103
+> #ifndef MATLAB
+105a107,111
+> #else /* MATLAB */
+>   mexPrintf ("Usage is:\n");
+>   for (cptr = data; *cptr != NULL; cptr ++)
+>     mexPrintf ("  %s\n", *cptr);
+> #endif /* MATLAB */
+
+
+[jschierm@astrid libscotch]$ diff common_old.h common.h
+
+- fix undeclared type intptr_t
+68a69
+> #include            <stdint.h>                    /* added for intptr_t */
+
+- for running as a matlab mex function
+- add macro for fprintf to capture missing output
+- fix exits to exit within Matlab
+90a92,105
+> #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
+> 
+
+
+[jschierm@astrid libscotch]$ diff dummysizes_old.c dummysizes.c
+
+- dummysizes must run by itself during compilation and exit cleanly
+269a270
+> #ifndef MATLAB
+270a272
+> #endif /* MATLAB */
+
+
+[jschierm@astrid libscotch]$ diff library_error_exit_old.c library_error_exit.c
+
+- redirect errorPrint and errorPrintW to within Matlab
+116a117
+> #ifndef MATLAB
+133a135,152
+> #else /* MATLAB */
+>   mexPrintf  ("%s", _SCOTCHerrorProgName);
+> #ifdef SCOTCH_PTSCOTCH
+>   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+>       (proclocnum != 0)                              &&
+>       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
+>     mexPrintf ("(%d): ", proclocnum);
+> #else /* SCOTCH_PTSCOTCH */
+>   if (_SCOTCHerrorProgName[0] != '\0')
+>     mexPrintf  (": ");
+> #endif /* SCOTCH_PTSCOTCH */
+>   mexPrintf  ("ERROR: ");
+>   va_start (errlist, errstr);
+>   mexPrintf (errstr, errlist);             /* Print arguments */
+>   va_end   (errlist);
+>   mexPrintf  ("\n");
+> #endif /* MATLAB */
+> 
+157a177
+> #ifndef MATLAB
+173a194,211
+> 
+> #else /* MATLAB */
+>   mexPrintf  ("%s", _SCOTCHerrorProgName);
+> #ifdef SCOTCH_PTSCOTCH
+>   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+>       (proclocnum != 0)                              &&
+>       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
+>     mexPrintf ("(%d): ", proclocnum);
+> #else /* SCOTCH_PTSCOTCH */
+>   if (_SCOTCHerrorProgName[0] != '\0')
+>     mexPrintf  (": ");
+> #endif /* SCOTCH_PTSCOTCH */
+>   mexPrintf  ("WARNING: ");
+>   va_start (errlist, errstr);
+>   mexPrintf (errstr, errlist);             /* Print arguments */
+>   va_end   (errlist);
+>   mexPrintf  ("\n");
+> #endif /* MATLAB */
+
+
+[jschierm@astrid scotch]$ diff Makefile_old Makefile
+- add MEX rule
+- add gmap_mex into scotch, clean, and install rules
+- add gmap_mex object
+51a52,54
+> %$(MEX)       :       %.c
+>                               $(CCM) $(MFLAGS) -I$(includedir) -I../libscotch -DSCOTCH_VERSION=\"$(VERSION)\" $(<) -o $(@) -L$(libdir) -l$(SCOTCHLIB) -l$(SCOTCHLIB)errexit $(LDFLAGS)
+> 
+70a74
+>                                       gmap_mex$(MEX) \
+98c102
+<                                       -$(CP) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) gmap$(EXE) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) gord$(EXE) gotst$(EXE) gout$(EXE) *gtst$(EXE) gscat$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE) $(bindir)
+---
+>                                       -$(CP) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) gmap$(EXE) gmap_mex$(MEX) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) gord$(EXE) gotst$(EXE) gout$(EXE) *gtst$(EXE) gscat$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE) $(bindir)
+108c112
+<                                       -$(RM) *~ *$(OBJ) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) *gmap$(EXE) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) *gord$(EXE) gotst$(EXE) gout$(EXE) *gpart$(EXE) *gscat$(EXE) *gtst$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE)
+---
+>                                       -$(RM) *~ *$(OBJ) acpl$(EXE) amk_ccc$(EXE) amk_fft2$(EXE) amk_grf$(EXE) amk_hy$(EXE) amk_m2$(EXE) amk_p2$(EXE) atst$(EXE) gbase$(EXE) gcv$(EXE) *gmap$(EXE) gmap_mex$(MEX) gmk_hy$(EXE) gmk_m2$(EXE) gmk_m3$(EXE) gmk_msh$(EXE) gmk_ub2$(EXE) gmtst$(EXE) *gord$(EXE) gotst$(EXE) gout$(EXE) *gpart$(EXE) *gscat$(EXE) *gtst$(EXE) mcv$(EXE) mmk_m2$(EXE) mmk_m3$(EXE) mord$(EXE) mtst$(EXE)
+239a244,251
+> gmap_mex$(MEX)                :       gmap_mex.c \
+>                                       ../libscotch/module.h \
+>                                       ../libscotch/common.h \
+>                                       $(includedir)/scotch.h \
+>                                       $(libdir)/libscotch$(LIB) \
+>                                       $(libdir)/libscotcherrexit$(LIB) \
+>                                       gmap.h
+> 
+
+
+[jschierm@astrid scotch]$ diff gmap.c gmap_mex.c
+- convert gmap to gmap_mex mex function with variable argument list
+117,120c117,120
+< int
+< main (
+< int                         argc,
+< char *                      argv[])
+---
+> void mexFunction( int nlhs,
+>                   mxArray *plhs[],
+>                   int nrhs,
+>                   const mxArray *prhs[] )
+121a122,123
+>   int                         argcm;
+>   char                        argvm[21][257];
+130a133,152
+> /*  check static variables from previous runs  */
+> 
+>   if (C_paraNum > 0 || C_fileNum > 0)
+>     mexErrMsgTxt("gmap_mex still in memory -- clear gmap_mex and try again.\n");
+> 
+> /*  load matlab argument list  */
+> 
+>   argcm=nrhs+1;
+>   mexPrintf("argcm=%d\n",argcm);
+>   strcpy(argvm[0],"gmap");
+>   for (i=0; i<nrhs; i++)
+>     if (!mxIsChar(prhs[i])) {
+>       mexPrintf("%s -- prhs[%d] must be character.\n","gmap",i);
+>       mexErrMsgTxt(" ");
+>     }
+>     else
+>       mxGetString(prhs[i],argvm[i+1],256);
+>   for (i=0; i<nrhs+1; i++)
+>     mexPrintf("argvm[%d]=%s\n",i,argvm[i]);
+> 
+132,133c154,155
+<   i = strlen (argv[0]);
+<   if ((i >= 5) && (strncmp (argv[0] + i - 5, "gpart", 5) == 0)) {
+---
+>   i = strlen (argvm[0]);
+>   if ((i >= 5) && (strncmp (argvm[0] + i - 5, "gpart", 5) == 0)) {
+144c166
+<   if ((argc >= 2) && (argv[1][0] == '?')) {       /* If need for help */
+---
+>   if ((argcm >= 2) && (argvm[1][0] == '?')) {       /* If need for help */
+151a174,175
+>   printf("point 0: C_FILENBR=%d, C_fileNbr=%d, C_paraNbr=%d\n",
+>          C_FILENBR,C_fileNbr,C_paraNbr);
+154,155c178,183
+<   for (i = 1; i < argc; i ++) {                   /* Loop for all option codes                        */
+<     if ((argv[i][0] != '-') || (argv[i][1] == '\0') || (argv[i][1] == '.')) { /* If found a file name */
+---
+>   for (i = 1; i < argcm; i ++) {                   /* Loop for all option codes                        */
+>   printf("point 1: i=%d; C_fileNbr=%d, C_fileNum=%d, C_paraNbr=%d, C_paraNum=%d\n",
+>          i,C_fileNbr,C_fileNum,C_paraNbr,C_paraNum);
+>     if ((argvm[i][0] != '-') || (argvm[i][1] == '\0') || (argvm[i][1] == '.')) { /* If found a file name */
+>   printf("point 2: i=%d; C_fileNbr=%d, C_fileNum=%d, C_paraNbr=%d, C_paraNum=%d\n",
+>          i,C_fileNbr,C_fileNum,C_paraNbr,C_paraNum);
+157,158c185,186
+<         if ((C_partNbr = atoi (argv[i])) < 1)     /* Get the number of parts */
+<           errorPrint ("main: invalid number of parts (\"%s\")", argv[i]);
+---
+>         if ((C_partNbr = atoi (argvm[i])) < 1)     /* Get the number of parts                          */
+>           errorPrint ("main: invalid number of parts (\"%s\")", argvm[i]);
+161a190,191
+>   printf("point 3: i=%d; C_fileNbr=%d, C_fileNum=%d, C_paraNbr=%d, C_paraNum=%d\n",
+>          i,C_fileNbr,C_fileNum,C_paraNbr,C_paraNum);
+163c193
+<         C_fileTab[C_fileNum ++].name = argv[i];
+---
+>         C_fileTab[C_fileNum ++].name = argvm[i];
+165a196,197
+>   printf("point 4: i=%d; C_fileNbr=%d, C_fileNum=%d, C_paraNbr=%d, C_paraNum=%d\n",
+>          i,C_fileNbr,C_fileNum,C_paraNbr,C_paraNum);
+168c200
+<       switch (argv[i][1]) {
+---
+>       switch (argvm[i][1]) {
+177c209
+<           SCOTCH_stratGraphMap (&stradat, &argv[i][2]);
+---
+>           SCOTCH_stratGraphMap (&stradat, &argvm[i][2]);
+181,182c213,214
+<           for (j = 2; argv[i][j] != '\0'; j ++) {
+<             switch (argv[i][j]) {
+---
+>           for (j = 2; argvm[i][j] != '\0'; j ++) {
+>             switch (argvm[i][j]) {
+192c224
+<                 errorPrint ("main: invalid source graph option (\"%c\")", argv[i][j]);
+---
+>                 errorPrint ("main: invalid source graph option (\"%c\")", argvm[i][j]);
+202,203c234,235
+<           for (j = 2; argv[i][j] != '\0'; j ++) {
+<             switch (argv[i][j]) {
+---
+>           for (j = 2; argvm[i][j] != '\0'; j ++) {
+>             switch (argvm[i][j]) {
+217c249
+<                 errorPrint ("main: unprocessed parameter \"%c\" in \"%s\"", argv[i][j], argv[i]);
+---
+>                 errorPrint ("main: unprocessed parameter \"%c\" in \"%s\"", argvm[i][j], argvm[i]);
+222c254
+<           errorPrint ("main: unprocessed option (\"%s\")", argv[i]);
+---
+>           errorPrint ("main: unprocessed option (\"%s\")", argvm[i]);
+225a258
+>   printf("point 5\n");
+230a264
+>   printf("point 6\n");
+232a267
+>   printf("point 7\n");
+235a271
+>   printf("point 8\n");
+239a276
+>   printf("point 9\n");
+244a282
+>   printf("point 10\n");
+251a290
+>   printf("point 11\n");
+256a296
+>   printf("point 12\n");
+264a305
+>   printf("point 13\n");
+271a313
+>   printf("point 14\n");
+273a316
+>   printf("point 15\n");
+276a320
+>   printf("point 16\n");
+277a322
+>   printf("point 16a\n");
+278a324
+>   printf("point 16b\n");
+279a326
+>   printf("point 16c\n");
+280a328
+>   printf("point 17\n");
+284a333
+>   printf("point 18\n");
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_jes_notes.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_jes_notes.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/scotch/scotch_jes_notes.txt	(revision 18231)
@@ -0,0 +1,308 @@
+8/06/09:
+
+following INSTALL.txt:
+- GNU Make 3.81, lex, yacc all present
+- started with Makefile.inc.i686_sun_solaris5
+- changed CCS from cc to gcc
+- removed SCOTCH_PTHREAD, since MPICH2 1.0.2p1 is prior to 1.0.7
+
+graph.h:110: error: expected :, ,, ;, ) or __attribute__ before vnumtab
+(and so on for "restrict" attribute in graph.h,geom.h,mesh.h,arch.h,mapping.h,order.h)
+- added -std=c99 to CFLAGS (based on various internet pages)
+
+bgraph_bipart_gg.c:267: error: intptr_t undeclared
+- according to various internet pages, should be included in c99 standard
+- defined in /usr/include/stdint.h (also referenced in inttypes.h), so why not included?
+- added -DINTSIZE64 to CFLAGS, still didn't work (based on INSTALL.txt)
+- added -Dintptr_t="long int" (based on /usr/include/stdint.h)
+
+common2.c:764: error: storage size of tp isn't known
+common2.c:766: error: CLOCK_REALTIME undeclared
+- added -DCOMMON_TIMING_OLD to CFLAGS (based on source code)
+
+8/13/09:
+
+for running as a matlab mex function:
+[jschierm@astrid libscotch]$ diff common_old.h common.h
+90a91,102
+> #ifdef MATLAB
+>     #include "mat.h"
+>     #include "mex.h"
+>     #include "matrix.h"
+> 
+>     #define printf mexPrintf
+>     #define malloc mxMalloc
+>     #define calloc mxCalloc
+>     #define realloc mxRealloc
+>     #define free mxFree
+> #endif
+> 
+
+[jschierm@astrid src]$ diff Makefile_old.inc Makefile.inc
+12,13c12,13
+< CFLAGS        = -m64 -O3 -std=c99 -DCOMMON_FILE_COMPRESS_GZ -DCOMMON_PTHREAD -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DINTSIZE64 -Dintptr_t="long int" -DCOMMON_TIMING_OLD
+< LDFLAGS       = -lz -lm -lrt
+---
+> CFLAGS        = -m64 -O3 -std=c99 -DCOMMON_FILE_COMPRESS_GZ -DCOMMON_PTHREAD -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DINTSIZE64 -Dintptr_t="long int" -DCOMMON_TIMING_OLD -DMATLAB -fPIC -I/usr/local/pkgs/matlab-7.6/extern/include
+> LDFLAGS       = -lz -lm -lrt -L/usr/local/pkgs/matlab-7.6/bin/glnxa64 -lmat -lmex
+
+8/19/09:
+
+- still having problems with intptr_t:
+gcc: int: No such file or directory
+In file included from ../libscotch/common.h:81,
+                 from gmap_mex.c:75:
+/usr/include/unistd.h:238: error: two or more data types in declaration specifiers
+- removed -DINTSIZE64 and -Dintptr_t="long int" from CFLAGS above
+[jschierm@astrid libscotch]$ diff common_old.h common.h
+68a69
+> #include            <stdint.h>                    /* added for intptr_t */
+
+8/20/09:
+
+- must fix exits to exit within Matlab:
+[jschierm@astrid libscotch]$ diff common_old.h common.h
+68a69
+> #include            <stdint.h>                    /* added for intptr_t */
+90a92,104
+> #ifdef MATLAB
+>     #include "mat.h"
+>     #include "mex.h"
+>     #include "matrix.h"
+> 
+>     #define printf mexPrintf
+>     #define malloc mxMalloc
+>     #define calloc mxCalloc
+>     #define realloc mxRealloc
+>     #define free mxFree
+>     #define exit(status) mexErrMsgTxt("exit=" #status)
+> #endif
+> 
+
+- however, dummysizes must run by itself during compilation and exit cleanly:
+[jschierm@astrid libscotch]$ diff dummysizes_old.c dummysizes.c
+269a270
+> #ifndef MATLAB
+270a272
+> #endif /* MATLAB */
+
+- redirect errorPrint and errorPrintW to within Matlab:
+[jschierm@astrid libscotch]$ diff library_error_exit_old.c
+library_error_exit.c
+116a117
+> #ifndef MATLAB
+133a135,152
+> #else /* MATLAB */
+>   mexPrintf  ("%s", _SCOTCHerrorProgName);
+> #ifdef SCOTCH_PTSCOTCH
+>   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+>       (proclocnum != 0)                              &&
+>       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
+>     mexPrintf ("(%d): ", proclocnum);
+> #else /* SCOTCH_PTSCOTCH */
+>   if (_SCOTCHerrorProgName[0] != '\0')
+>     mexPrintf  (": ");
+> #endif /* SCOTCH_PTSCOTCH */
+>   mexPrintf  ("ERROR: ");
+>   va_start (errlist, errstr);
+>   mexPrintf (errstr, errlist);             /* Print arguments */
+>   va_end   (errlist);
+>   mexPrintf  ("\n");
+> #endif /* MATLAB */
+> 
+157a177
+> #ifndef MATLAB
+173a194,211
+> 
+> #else /* MATLAB */
+>   mexPrintf  ("%s", _SCOTCHerrorProgName);
+> #ifdef SCOTCH_PTSCOTCH
+>   if ((MPI_Initialized (&proclocnum) == MPI_SUCCESS) &&
+>       (proclocnum != 0)                              &&
+>       (MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum) == MPI_SUCCESS))
+>     mexPrintf ("(%d): ", proclocnum);
+> #else /* SCOTCH_PTSCOTCH */
+>   if (_SCOTCHerrorProgName[0] != '\0')
+>     mexPrintf  (": ");
+> #endif /* SCOTCH_PTSCOTCH */
+>   mexPrintf  ("WARNING: ");
+>   va_start (errlist, errstr);
+>   mexPrintf (errstr, errlist);             /* Print arguments */
+>   va_end   (errlist);
+>   mexPrintf  ("\n");
+> #endif /* MATLAB */
+
+- redirect usagePrint to within Matlab:
+[jschierm@astrid libscotch]$ diff common_old.c common.c  
+102a103
+> #ifndef MATLAB
+105a107,111
+> #else /* MATLAB */
+>   mexPrintf ("Usage is:\n");
+>   for (cptr = data; *cptr != NULL; cptr ++)
+>     mexPrintf ("  %s\n", *cptr);
+> #endif /* MATLAB */
+
+8/21/09:
+
+- removed -DCOMMON_PTHREAD from CFLAGS and MFLAGS to eliminate fatal exception at pthread_exit in gmap_mex.c
+- removed -DCOMMON_FILE_COMPRESS_GZ from CFLAGS and MFLAGS because unused
+
+8/25/09:
+
+added macro for fprintf to capture missing output:
+[jschierm@astrid libscotch]$ diff common_old.h common.h
+68a69
+> #include            <stdint.h>                    /* added for intptr_t */
+90a92,105
+> #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
+> 
+
+11/12/09:
+
+- added -Wl,-rpath-link,/usr/local/pkgs/matlab-7.6/bin/glnxa64 to LDFLAGS to eliminate missing libhdf5.so.0 in Matlab directories (based on Cielo make, but why did this not occur before?)
+
+11/18/09:
+
+- changed the following files to allow adjir,adjjc,vertlab,vertwgt,edgewgt rather than graph file
+
+libscotch/library.h
+- argument list for SCOTCH_graphLoad
+libscotch/library_graph.c
+- SCOTCH_graphLoad changes and call to graphLoad
+libscotch/graph.h
+- argument list for graphLoad
+libscotch/graph_io.c
+- graphLoad changes
+libscotch/graph_io_scot.c
+- miscellaneous call to graphLoad
+libscotch/mesh_io_scot.c
+- miscellaneous call to graphLoad
+libscotch/library_graph_f.c
+- miscellaneous call to SCOTCH_graphLoad
+scotch/gmap_mex.c
+- input/processing of Matlab arguments and call to SCOTCH_graphLoad
+
+11/30/09:
+
+- changed the following files to allow nvert,maptab rather than map file
+
+libscotch/library.h
+- argument list for SCOTCH_graphMapSave
+libscotch/library_graph_map.c
+- SCOTCH_graphMapSave changes and call to mapSave
+libscotch/mapping.h
+- argument list for mapSave
+libscotch/mapping_io.c
+- mapSave changes
+libscotch/library_graph_map_f.c
+- miscellaneous call to SCOTCH_graphMapSave
+scotch/gmap_mex.c
+- call to SCOTCH_graphMapSave and processing/output of Matlab arguments
+
+12/08/09:
+
+- changed the following files to allow archtyp,napar,archpar rather than target file
+
+libscotch/library.h
+- argument list for SCOTCH_archLoad
+libscotch/library_arch.c
+- SCOTCH_archLoad changes and call to archLoad
+libscotch/arch.h
+- argument list for archLoad
+libscotch/arch.c
+- archLoad changes and call to class->archLoad
+libscotch/arch_cmplt.h
+libscotch/arch_cmpltw.h
+libscotch/arch_deco.h
+libscotch/arch_hcub.h
+libscotch/arch_mesh.h
+libscotch/arch_tleaf.h
+libscotch/arch_torus.h
+- argument lists for arch*ArchLoad
+libscotch/arch_cmplt.c
+libscotch/arch_cmpltw.c
+libscotch/arch_deco.c
+libscotch/arch_hcub.c
+libscotch/arch_mesh.c
+libscotch/arch_tleaf.c
+libscotch/arch_torus.c
+- arch*ArchLoad changes
+libscotch/library_arch_f.c
+- miscellaneous call to SCOTCH_archLoad
+scotch/gmap_mex.c
+- input/processing of Matlab arguments and call to SCOTCH_archLoad
+
+12/11/09:
+
+- fixed a couple bugs
+
+libscotch/graph.c -- caused crash when trying to free vertex labels
+138c138,141
+<     if (grafptr->vlbltax != NULL)
+---
+> /*  vlbltax must also check GRAPHVERTGROUP (jes, 12/11/09)  */
+> //    if (grafptr->vlbltax != NULL)
+>     if ((grafptr->vlbltax != NULL) &&
+>         ((grafptr->flagval & GRAPHVERTGROUP) == 0))
+
+libscotch/mapping_io.c -- caused first vertex label to be uninitialized
+> /*  not sure why, but need to offset vlbltax in other direction (jes, 12/11/09
+> //                 (long) ((vlbltax != NULL) ? vlbltax[vertnum] : vertnum),
+>                  (long) ((vlbltax != NULL) ? vlbltax[vertnum+mappptr->baseva
+
+1/05/10:
+
+libscotch/graph_io.c -- if vertex labels are supplied, they must be referenced
+263c265,268
+<       edgeval=adjir[edgenum-grafptr->baseval]+1;
+---
+>       if (vertlab)
+>         edgeval=vertlab[adjir[edgenum-grafptr->baseval]  ];
+>       else
+>         edgeval=        adjir[edgenum-grafptr->baseval]+1;
+
+2/08/10:
+
+- modified all source code changes to use the MATLAB compiler conditional, so that both mex and stand-alone modules could be built simultaneously
+
+2/10/10:
+
+- added mexscotch target to makefiles to separate mex from stand-alone modules
+- removed Matlab-specific switches from CFLAGS and LDFLAGS and added them to mexscotch target
+
+3/03/10:
+
+- separated dummysizes within mexscotch target in libscotch/Makefile so that it is built without the matlab flag, includes, and libraries (matlab 7.8 would fail even though matlab 7.6 was okay).
+
+4/26/10:
+
+- separated gmap_mex.c driver into gmap_mex.c matlab-layer (independent of scotch) and gmapx.c x-layer (independent of matlab).
+
+4/29/10:
+
+- made changes to gmapx.c, parser_yy.y/stratParserParse, and parser_ll.l/stratParserInit to reset static variables from previous runs.
+- inserted print statements into common_integer.c/intRand*, common_memory.c/mem*, and vgraph_separate_vw.c/vgraphSeparateVw to monitor static variables in case those have to be reset.
+
+5/03/10:
+
+- implemented gpart functionality in gmap_mex.c, gmapx.c, and new gpart.m.
+- implemented common_integer.c/intRandResetStatic to reset static variables from previous runs.
+
+6/16/10:
+
+- renamed scotch x-layer and separated it from rest of build.
+- set up scotch to build both stand-alone and mex libraries.
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/install.sh	(revision 18231)
@@ -0,0 +1,56 @@
+#!/bin/bash
+set -eu
+
+# Some cleanup
+rm -rf shapelib-1.2.10
+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/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/docs/shapefile.pdf' 'shapefile.pdf'
+
+# Untar 
+tar -xvzf shapelib-1.2.10.tar.gz
+unzip shape_eg_data.zip -d shapelib-1.2.10/eg_data
+
+# Move shapelib to src directory
+mv shapelib-1.2.10/* src
+rm -rf shapelib-1.2.10
+
+# Apply patches (all at once)
+# (written by diff -rc old_src new_src > shapelib.patch)
+patch -p0 < shapelib.patch
+
+# Build shapelib and run self-tests
+cd src
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make test
+
+# Clean up objects (but not library or executable)
+#make clean
+cd ..
+
+# Populate install directory
+cp -p src/README install
+cp -p src/*.html install
+mkdir install/include
+cp -p src/shapefil.h install/include
+mkdir install/lib
+mv src/libshape.a install/lib/libshape.a
+mkdir install/exec
+mv src/shpcreate install/exec
+mv src/shpadd install/exec
+mv src/shpdump install/exec
+mv src/shprewind install/exec
+mv src/dbfcreate install/exec
+mv src/dbfadd install/exec
+mv src/dbfdump install/exec
+mv src/shputils install/exec
+mv src/shptest install/exec
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/shapelib.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/shapelib.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shapelib/shapelib.patch	(revision 18231)
@@ -0,0 +1,139 @@
+diff -rc src/Makefile src_new/Makefile
+*** src/Makefile	2003-04-07 06:03:22.000000000 -0700
+--- src_new/Makefile	2011-10-19 11:58:13.993411828 -0700
+***************
+*** 1,20 ****
+  
+  #LINKOPT	=	/usr/local/lib/libdbmalloc.a
+! CFLAGS	=	-g
+  
+  default:	all
+  
+! all:	shpcreate shpadd shpdump shprewind dbfcreate dbfadd dbfdump shptest
+  
+  shpopen.o:	shpopen.c shapefil.h
+  	$(CC) $(CFLAGS) -c shpopen.c
+  
+- shptree.o:	shptree.c shapefil.h
+- 	$(CC) $(CFLAGS) -c shptree.c
+- 
+  dbfopen.o:	dbfopen.c shapefil.h
+  	$(CC) $(CFLAGS) -c dbfopen.c
+  
+  shpcreate:	shpcreate.c shpopen.o
+  	$(CC) $(CFLAGS) shpcreate.c shpopen.o $(LINKOPT) -o shpcreate
+  
+--- 1,24 ----
+  
+  #LINKOPT	=	/usr/local/lib/libdbmalloc.a
+! CC =		gcc
+! #CFLAGS	=	-g
+! CFLAGS	=	-fPIC -fno-omit-frame-pointer -pthread -fexceptions -g
+! AR =		/usr/bin/ar rcv
+! RANLIB =	/usr/bin/ranlib
+  
+  default:	all
+  
+! all:	libshape.a shpcreate shpadd shpdump shprewind dbfcreate dbfadd dbfdump shputils shptest
+  
+  shpopen.o:	shpopen.c shapefil.h
+  	$(CC) $(CFLAGS) -c shpopen.c
+  
+  dbfopen.o:	dbfopen.c shapefil.h
+  	$(CC) $(CFLAGS) -c dbfopen.c
+  
++ libshape.a:    shpopen.o dbfopen.o
++ 	${AR} libshape.a shpopen.o dbfopen.o ; ${RANLIB} libshape.a
++ 
+  shpcreate:	shpcreate.c shpopen.o
+  	$(CC) $(CFLAGS) shpcreate.c shpopen.o $(LINKOPT) -o shpcreate
+  
+***************
+*** 36,58 ****
+  dbfdump:	dbfdump.c dbfopen.o
+  	$(CC) $(CFLAGS) dbfdump.c dbfopen.o $(LINKOPT) -o dbfdump
+  
+  shptest:	shptest.c shpopen.o
+  	$(CC) $(CFLAGS) shptest.c shpopen.o $(LINKOPT) -o shptest
+  
+! shputils:	shputils.c shpopen.o dbfopen.o
+! 	$(CC) $(CFLAGS) shputils.c shpopen.o dbfopen.o $(LINKOPT) -o shputils
+  
+  shptreedump:	shptreedump.c shptree.o shpopen.o
+  	$(CC) $(CFLAGS) shptreedump.c shptree.o shpopen.o $(LINKOPT) \
+  		-o shptreedump
+  
+  clean:
+! 	rm -f *.o dbfdump dbfcreate dbfadd shpdump shpcreate shpadd shputils
+  	rm -f shptreedump
+  	rm -rf *.lo *.la .libs
+- 	rm -f shptest
+  
+! test:	test2 test3
+  
+  #
+  #	Note this stream only works if example data is accessable.
+--- 40,64 ----
+  dbfdump:	dbfdump.c dbfopen.o
+  	$(CC) $(CFLAGS) dbfdump.c dbfopen.o $(LINKOPT) -o dbfdump
+  
++ shputils:	shputils.c shpopen.o dbfopen.o
++ 	$(CC) $(CFLAGS) shputils.c shpopen.o dbfopen.o $(LINKOPT) -o shputils
++ 
+  shptest:	shptest.c shpopen.o
+  	$(CC) $(CFLAGS) shptest.c shpopen.o $(LINKOPT) -o shptest
+  
+! shptree.o:	shptree.c shapefil.h
+! 	$(CC) $(CFLAGS) -c shptree.c
+  
+  shptreedump:	shptreedump.c shptree.o shpopen.o
+  	$(CC) $(CFLAGS) shptreedump.c shptree.o shpopen.o $(LINKOPT) \
+  		-o shptreedump
+  
+  clean:
+! 	rm -f *.o *.a shpcreate shpadd shpdump shprewind dbfcreate dbfadd dbfdump shputils shptest
+  	rm -f shptreedump
+  	rm -rf *.lo *.la .libs
+  
+! test:	test1 test2 test3
+  
+  #
+  #	Note this stream only works if example data is accessable.
+diff -rc src/shputils.c src_new/shputils.c
+*** src/shputils.c	2003-04-07 06:03:22.000000000 -0700
+--- src_new/shputils.c	2011-10-14 14:52:32.179022813 -0700
+***************
+*** 274,280 ****
+                  if (factor == 0)
+                  {
+                    if (infactor ==0)
+!                   { puts("ERROR: Input unit must be defined before output unit"); exit(); }
+                    factor=infactor/outfactor;
+                  }
+                  printf("Output file coordinate values will be factored by %lg\n",factor);
+--- 274,280 ----
+                  if (factor == 0)
+                  {
+                    if (infactor ==0)
+!                   { puts("ERROR: Input unit must be defined before output unit"); exit( 1 ); }
+                    factor=infactor/outfactor;
+                  }
+                  printf("Output file coordinate values will be factored by %lg\n",factor);
+diff -rc src/stream1.sh src_new/stream1.sh
+*** src/stream1.sh	2003-04-07 06:03:22.000000000 -0700
+--- src_new/stream1.sh	2011-10-19 11:45:08.192964291 -0700
+***************
+*** 1,6 ****
+  #!/bin/sh
+  	
+! EG_DATA=/u/www/projects/shapelib/eg_data
+  
+  echo -------------------------------------------------------------------------
+  echo Test 1: dump anno.shp
+--- 1,6 ----
+  #!/bin/sh
+  	
+! EG_DATA=./eg_data
+  
+  echo -------------------------------------------------------------------------
+  echo Test 1: dump anno.shp
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/README	(revision 18231)
@@ -0,0 +1,9 @@
+http://code.google.com/p/shell2junit/
+
+Shell2junit
+
+Shell2junit is a simple utility which facilitates to generate junit reports for batch processes executed in shell scripts. 
+
+The reports can be easily parsed in Hudson and other CI software in order to monitor and generate trends and alerts. 
+
+This page teaches how to do it in Hudson. 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh	(revision 18231)
@@ -0,0 +1,9 @@
+#!/bin/bash
+set -eu
+
+
+#Some cleanup
+rm -rf install 
+mkdir install 
+
+cp patch/sh2ju.sh install/
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh.old
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh.old	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/install.sh.old	(revision 18231)
@@ -0,0 +1,20 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf shell2junit
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/shell2junit-1.0.0.zip' 'shell2junit-1.0.0.zip'
+
+#Untar 
+unzip shell2junit-1.0.0.zip
+
+#Move shell2junit into install directory
+mv shell2junit/* src
+rm -rf shell2junit
+
+#Copy executable: 
+cp src/sh2ju.sh install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/patch/sh2ju.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/patch/sh2ju.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/shell2junit/patch/sh2ju.sh	(revision 18231)
@@ -0,0 +1,131 @@
+#!/bin/sh
+### Copyright 2010 Manuel Carrasco Moñino. (manolo at apache.org) 
+###
+### Licensed under the Apache License, Version 2.0.
+### You may obtain a copy of it at
+### http://www.apache.org/licenses/LICENSE-2.0
+
+###
+### A library for shell scripts which creates reports in jUnit format.
+### These reports can be used in Hudson, or any other CI.
+###
+### Usage: 
+###     - Include this file in your shell script
+###     - Use juLog to call your command any time you want to produce a new report
+###        Usage:   juLog <options> command arguments
+###           options:
+###             -name="TestName" : the test name which will be shown in the junit report
+###             -error="RegExp"  : a regexp which sets the test as failure when the output matches it
+###             -ierror="RegExp" : same as -error but case insensitive
+###     - Junit reports are left in the folder 'result' under the directory where the script is executed.
+###     - Configure hudson to parse junit files from the generated folder
+###
+
+asserts=00; errors=0; total=0; content=""
+
+# create output folder
+juDIR=`pwd`/results
+mkdir -p $juDIR || exit
+
+# The name of the suite is calculated based in your script name
+suite=`basename $0 | sed -e 's/.sh$//' | tr "." "_"`
+
+# A wrapper for the eval method witch allows catching seg-faults and use tee
+errfile=/tmp/evErr.$$.log
+eVal() {
+  eval "$1"
+  echo $? | tr -d "\n" >$errfile
+}
+
+# Method to clean old tests
+juLogClean() {
+  echo "+++ Removing old junit reports from: $juDIR "
+  rm -f $juDIR/TEST-*	
+}
+
+# Execute a command and record its results 
+juLog() {
+  
+  # parse arguments
+  ya=""; icase=""; testname="";
+  while [ -z "$ya" ]; do  
+    case "$1" in
+  	  -name=*)   name=$asserts-`echo "$1" | sed -e 's/-name=//'`;   shift;;
+      -ierror=*) ereg=`echo "$1" | sed -e 's/-ierror=//'`; icase="-i"; shift;;
+      -error=*)  ereg=`echo "$1" | sed -e 's/-error=//'`;  shift;;
+      -test=*)  testname=`echo "$1" | sed -e 's/-test=//'`;  shift;;
+      *)         ya=1;;
+    esac
+  done  
+
+  # use first arg as name if it was not given 
+  if [ -z "$name" ]; then
+    name="$asserts-$1" 
+    shift
+  fi
+
+  # calculate command to eval
+  [ -z "$1" ] && return
+  cmd="$1"; shift
+  while [ -n "$1" ]
+  do
+     cmd="$cmd \"$1\""
+     shift
+  done
+
+  # eval the command sending output to a file
+  outf=/var/tmp/ju$$.txt
+  >$outf
+  echo ""                         | tee -a $outf
+  echo "+++ Running case: $testname " | tee -a $outf
+  echo "+++ working dir: "`pwd`           | tee -a $outf
+  #echo "+++ command: $cmd"            | tee -a $outf
+  ini=`date +%s`
+  eVal "$cmd" 2>&1                | tee -a $outf
+  evErr=`cat $errfile`
+  rm -f $errfile
+  end=`date +%s`
+  echo "+++ exit code: $evErr"        | tee -a $outf
+  
+  # set the appropriate error, based in the exit code and the regex  
+  [ $evErr != 0 ] && err=1 || err=0
+  out=`cat $outf | sed -e 's/^\([^+]\)/| \1/g'`
+  if [ $err = 0 -a -n "$ereg" ]; then
+      H=`echo "$out" | egrep $icase "$ereg"`
+      [ -n "$H" ] && err=1
+  fi
+  echo "+++ error: $err"         | tee -a $outf
+  rm -f $outf
+
+  # calculate vars
+  asserts=`expr $asserts + 1`
+  asserts=`printf "%.2d" $asserts`
+  errors=`expr $errors + $err`
+  time=`expr $end - $ini`
+  total=`expr $total + $time`
+
+  # write the junit xml report
+  ## failure tag
+  [ $err = 0 ] && failure="" || failure="
+      <failure type=\"ScriptError\" message=\"Script Error\"></failure>
+  "
+  ## testcase tag
+  content="$content
+    <testcase assertions=\"1\" name=\"$testname $ereg\" time=\"$time\">
+    $failure
+    <system-out>
+<![CDATA[
+$out
+]]>
+    </system-out>
+    </testcase>
+  "
+  ## testsuite block
+  cat <<EOF >$juDIR/TEST-$suite.xml
+  <testsuite failures="0" assertions="$assertions" name="ISSM Test Suite" tests="1" errors="$errors" time="$total">
+    $content
+  </testsuite>
+EOF
+
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/slepc/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/slepc/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/slepc/install.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install slepc-2.3.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/slepc-2.3.2.tgz' 'slepc-2.3.2.tgz'
+
+#Untar 
+tar -zxvf  slepc-2.3.2.tgz
+
+#Move slepc to install directory
+mv slepc-2.3.2/* install/
+rm -rf slepc-2.3.2
+
+#Make slepc
+cd install
+./config/configure.py
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/snowpack/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/snowpack/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/snowpack/install.sh	(revision 18231)
@@ -0,0 +1,56 @@
+#!/bin/bash
+#SNOWPACK install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a Snowpack-*-src.tar.gz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls Snowpack-*-src.tar.gz`
+source_version=`echo $source_tar | sed 's/Snowpack-//g' | sed 's/-src.tar.gz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be Snowpack-*-src.tar.gz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+#Some cleanup
+rm -rf src install Snowpack-$source_version
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv Snowpack-$source_version/usr src
+rm -rf Snowpack-$source_version
+
+#Build library
+cd src && rm -rf CMakeCache.txt 
+cmake -DCMAKE_INSTALL_PREFIX:PATH=$ISSM_DIR/externalpackages/snowpack/install \
+	-DMETEOIO_INCLUDE_DIR:PATH=$ISSM_DIR/externalpackages/meteoio/install/include \
+	-DMETEOIO_LIBRARY:PATH=$ISSM_DIR/externalpackages/meteoio/install/lib/libmeteoio.dylib\
+	.
+	#-DCMAKE_VERBOSE_MAKEFILE=true \
+
+#Compile
+if [ $# -eq 0 ]; then
+	make  all install
+else
+	make -j $1  all install
+fi
+
+#Build binary: 
+cd applications/snowpack
+cmake -DCMAKE_MODULE_PATH:PATH=/Users/larour/issm-uci/trunk-jpl/externalpackages/snowpack/src/tools/cmake/      -DMETEOIO_INCLUDE_DIR:PATH=$ISSM_DIR/externalpackages/meteoio/install/include  .
+
+#Compile
+if [ $# -eq 0 ]; then
+	make  all install
+else
+	make -j $1  all install
+fi
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/sqlite/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/sqlite/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/sqlite/install.sh	(revision 18231)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf sqlite-autoconf-3071300
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/sqlite-autoconf-3071300.tar.gz' 'sqlite-autoconf-3071300.tar.gz'
+
+#Untar 
+tar -zxvf  sqlite-autoconf-3071300.tar.gz
+
+#Move sqlite-autoconf into src directory
+mv sqlite-autoconf-3071300/* src
+rm -rf sqlite-autoconf-3071300
+
+#Configure sqlite-autoconf
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/sqlite/install" 
+
+#Compile and install sqlite-autoconf
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/starcluster/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/starcluster/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/starcluster/install.sh	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/externalpackages/svn/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/svn/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/svn/install.sh	(revision 18231)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf subversion-1.6.18
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/subversion-1.6.18.tar.gz' 'subversion-1.6.18.tar.gz'
+
+#Untar 
+tar -zxvf  subversion-1.6.18.tar.gz
+
+#Move subversion into src directory
+mv subversion-1.6.18/* src
+rm -rf subversion-1.6.18
+
+#Configure subversion
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/svn/install" \
+	--with-swig="$ISSM_DIR/externalpackages/swig/install"  \
+	PYTHON2="$ISSM_DIR/externalpackages/python/install/bin/python" \
+	--with-sqlite="$ISSM_DIR/externalpackages/sqlite/install"
+
+#Compile and install subversion
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/swig/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/swig/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/swig/install.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+rm -rf swig-2.0.4
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/swig-2.0.4.tar.gz' 'swig-2.0.4.tar.gz'
+
+#Untar and move python into install directory
+tar -zxvf  swig-2.0.4.tar.gz
+mv swig-2.0.4/* install
+rm -rf swig-2.0.4
+
+#Copy pcre prototype in include directory
+cd install 
+#cp $ISSM_DIR/externalpackages/pcre/install/pcre.h  ./Source/Include/
+#cp $ISSM_DIR/externalpackages/pcre/install/.libs/*  ./Source/Include/
+export CFLAGS="-I$ISSM_DIR/externalpackages/pcre/install"
+export LDFLAGS="-L$ISSM_DIR/externalpackages/pcre/install/.libs/"
+export LIBS="-lpcre"
+#Configure swig
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/swig/install" \
+ --with-pcre-prefix="$ISSM_DIR/externalpackages/pcre/install" \
+ --with-pcre-exec-prefix="$ISSM_DIR/externalpackages/pcre/install" \
+ --with-python="$ISSM_DIR/externalpackages/python/install/bin/python"
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.0.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.0.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.0.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#http://www.mcs.anl.gov/research/projects/tao/download/index.html
+
+#Compatible with PETSc 3.2
+
+#Some cleanup
+rm -rf install tao-2.0-p3
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.0-p3.tar.gz' 'tao-2.0-p3.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.0-p3.tar.gz
+
+#move into place
+mv tao-2.0-p3/* install/
+rm -rf tao-2.0-p3
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+
+#petsc needs to be compiled with --with-clanguage=C++
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.1.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.1.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.1.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#http://www.mcs.anl.gov/research/projects/tao/download/index.html
+
+#compatible with PETSc 3.3
+
+#Some cleanup
+rm -rf install tao-2.1-p0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.1-p0.tar.gz' 'tao-2.1-p0.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.1-p0.tar.gz
+
+#move into place
+mv tao-2.1-p0/* install/
+rm -rf tao-2.1-p0
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+
+#petsc needs to be compiled with --with-clanguage=C++
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.2.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.2.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tao/install-2.2.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#http://www.mcs.anl.gov/research/projects/tao/download/tao-2.2.2.tar.gz
+
+#compatible with PETSc 3.4
+
+#Some cleanup
+rm -rf install tao-2.2.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.2.2.tar.gz' 'tao-2.2.2.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.2.2.tar.gz
+
+#move into place
+mv tao-2.2.2/* install/
+rm -rf tao-2.2.2
+
+#compile
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tcl/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tcl/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tcl/install.sh	(revision 18231)
@@ -0,0 +1,49 @@
+#!/bin/bash
+set -eu
+
+sudochoice=0;
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tcl8.5.11
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tcl8.5.11.tar.gz' 'tcl8.5.11.tar.gz'
+
+#Untar 
+tar -zxvf  tcl8.5.11.tar.gz
+
+#Move tcl into src directory
+mv tcl8.5.11/* src
+rm -rf tcl8.5.11
+
+#Configure tcl
+ver="8.4.12"
+
+cd src/unix
+
+#User mode: 
+if [[ $sudochoice == "0" ]]; 
+then 
+	./configure --prefix=$ISSM_DIR/externalpackages/tcl/install
+	if [ $# -eq 0 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install 
+fi
+
+#sudo mode: 
+if [[ $sudochoice == "1" ]]; 
+then
+	sudo ./configure 
+	if [ $# -eq 0 ]; then
+		sudo make
+	else
+		sudo make -j $1
+	fi
+	sudo make install 
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tclx/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tclx/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tclx/install.sh	(revision 18231)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tclx8.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tclx8.4.tar.gz' 'tclx8.4.tar.gz'
+
+#Untar 
+tar -zxvf  tclx8.4.tar.gz
+
+#Move tclx into src directory
+mv tclx8.4/* src
+rm -rf tclx8.4
+
+#Configure tclx
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/tclx/install"  \
+			--exec-prefix="$ISSM_DIR/externalpackages/tclx/install"  \
+	        --with-tcl=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework
+
+#Compile and install tclx
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tex2im/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tex2im/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tex2im/install.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tex2im-1.8.tar.gz' 'tex2im-1.8.tar.gz'
+
+#Untar 
+tar -zxvf  tex2im-1.8.tar.gz
+
+#Move tex2im into src directory
+mv tex2im-1.8/tex2im install/
+rm -rf tex2im-1.8
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tk/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tk/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/tk/install.sh	(revision 18231)
@@ -0,0 +1,46 @@
+#!/bin/bash
+set -eu
+
+sudochoice=0;
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tk8.5.12
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tk8.5.12-src.tar.gz' 'tk8.5.12.tar.gz'
+
+#Untar 
+tar -zxvf  tk8.5.12.tar.gz
+
+#Move tk into src directory
+mv tk8.5.12/* src
+rm -rf tk8.5.12
+
+cd src/unix
+
+#User mode: 
+if [[ $sudochoice == "0" ]]; 
+then 
+	./configure --prefix=$ISSM_DIR/externalpackages/tk/install
+	if [ $# -eq 0 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install 
+fi
+
+#sudo mode: 
+if [[ $sudochoice == "1" ]]; 
+then
+	sudo ./configure 
+	if [ $# -eq 0 ]; then
+		sudo make
+	else
+		sudo make -j $1
+	fi
+	sudo make install 
+fi
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/altix64/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/altix64/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/altix64/configure.make	(revision 18231)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/android/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/android/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/android/configure.make	(revision 18231)
@@ -0,0 +1,18 @@
+# This makefile configures build process to cross-compile to the android platform.
+# The binary tools referenced below are specifically configured to target armeabi-v7a.
+# Furthermore, the compilers (which are simply wrappers around GNU GCC) are set to
+# produce binaries that are EABI compliant.
+#
+# Note that the AAPCS standard defines 'EABI' as a moniker used to specify
+# a _family_ of similar but distinct ABIs. Android follows the little-endian
+# ARM GNU/Linux ABI as documented in the following document:
+#
+# http://www.codesourcery.com/gnu_toolchains/arm/arm_gnu_linux_abi.pdf
+
+CC=${host_triplet}-gcc
+AR=${host_triplet}-ar
+RANLIB=${host_triplet}-ranlib
+CSWITCHES = $(CFLAGS) -DNO_TIMER 
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/linux64/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/linux64/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/linux64/configure.make	(revision 18231)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx32/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx32/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx32/configure.make	(revision 18231)
@@ -0,0 +1,5 @@
+CC=gcc -arch i386
+CSWITCHES = $(CFLAGS) -DNO_TIMER -fPIC 
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx64/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx64/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/macosx64/configure.make	(revision 18231)
@@ -0,0 +1,5 @@
+CC=gcc -arch x86_64
+CSWITCHES = $(CFLAGS) -DNO_TIMER -fPIC
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/pleiades/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/pleiades/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/pleiades/configure.make	(revision 18231)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win32/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win32/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win32/configure.make	(revision 18231)
@@ -0,0 +1,4 @@
+CC=icl
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DWIN32
+OBJ_EXT=obj
+LIB_EXT=a
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/configure.make
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/configure.make	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/configure.make	(revision 18231)
@@ -0,0 +1,4 @@
+CC=cl
+CSWITCHES = $(CFLAGS) -DNO_TIMER 
+OBJ_EXT=obj
+LIB_EXT=lib
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/configs/win7/makefile	(revision 18231)
@@ -0,0 +1,21 @@
+#Adaptation of Triangle makefile to compile only the triangle.c file, 
+#into a standalone library that can then be used to compile mex modules
+
+include ./configure.make
+
+AR = ar
+
+TRILIBDEFS = -DTRILIBRARY
+
+all: triangle.$(LIB_EXT)
+
+OBJECTS=triangle.$(OBJ_EXT)
+
+triangle.$(LIB_EXT): $(OBJECTS)
+	lib -out:triangle.$(LIB_EXT) $(OBJECTS)
+
+triangle.$(OBJ_EXT): triangle.c triangle.h
+	$(CC) $(CSWITCHES) $(TRILIBDEFS) -c triangle.c
+
+clean: 
+	rm -rf *.$(LIB_EXT) *.$(OBJ_EXT) *.LIB *.LST *.$(OBJ_EXT)bj *.BAK
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-altix64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-altix64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-altix64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/altix64/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-android.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-android.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-android.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu
+
+source $ANDROID_DIR/android_aux.sh
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/android/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-discover.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-discover.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/pleiades/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-linux64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/linux64/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx32.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/macosx32/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/macosx64/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-pleiades.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-pleiades.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/pleiades/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win32.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/win32/configure.make ./
+cp ../makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win7.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win7.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/install-win7.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/win7/configure.make ./
+cp ../configs/win7/makefile ./
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/makefile	(revision 18231)
@@ -0,0 +1,32 @@
+#Adaptation of Triangle makefile to compile only the triangle.c file, 
+#into a standalone library that can then be used to compile mex modules
+
+include ./configure.make
+
+ifeq "$(origin CC)" "undefined"
+	CC = cc
+endif
+
+ifeq "$(origin AR)" "undefined"
+	AR = ar
+endif
+
+ifeq "$(origin RANLIB)" "undefined"
+	RANLIB = ranlib
+endif
+
+TRILIBDEFS = -DTRILIBRARY
+
+all: triangle.$(LIB_EXT)
+
+OBJECTS=triangle.$(OBJ_EXT)
+
+triangle.$(LIB_EXT): $(OBJECTS)
+	$(AR) cr  triangle.$(LIB_EXT) $(OBJECTS)
+	$(RANLIB) triangle.$(LIB_EXT)
+
+triangle.$(OBJ_EXT): triangle.c triangle.h
+	$(CC) $(CSWITCHES) $(TRILIBDEFS) -c triangle.c
+
+clean: 
+	rm -rf *.$(LIB_EXT) *.$(OBJ_EXT) *.LIB *.LST *.$(OBJ_EXT)bj *.BAK
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/triangle.h.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/triangle.h.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/triangle/triangle.h.patch	(revision 18231)
@@ -0,0 +1,12 @@
+250a251,257
+> /*Patch for ISSM*/
+> #ifndef REAL
+> typedef double REAL;
+> typedef void VOID;
+> #endif
+> /*End patch*/
+> 
+283c290
+< void triangulate(char *, struct triangulateio *, struct triangulateio *,
+---
+> extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-altix64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-altix64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-altix64.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install valgrind-3.8.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+
+#Untar 
+tar -jxvf  valgrind-3.8.1.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
+
+#configure
+cd install
+./configure --prefix="$ISSM_DIR/externalpackages/valgrind/install"
+
+#Compile valgrind
+make  -j 4
+make install
+
+#final thing: if mpi is compiled in, soft link its target to a simpler name
+cd lib
+ln -s valgrind/libmpi*  ./libmpidebug.so
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-linux64.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install valgrind-3.8.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+
+#Untar 
+tar -jxvf  valgrind-3.8.1.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
+
+#configure
+cd install
+./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install"
+
+#Compile valgrind
+make  -j 4
+make install
+
+#final thing: if mpi is compiled in, soft link its target to a simpler name
+cd lib
+ln -s valgrind/libmpiwrap-*  ./libmpidebug.so
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx32.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install valgrind-3.8.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+
+#Untar 
+tar -jxvf  valgrind-3.8.1.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
+
+#configure
+cd install
+./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install" --enable-only32bit
+
+#Compile valgrind
+make  -j 4
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-macosx64.sh	(revision 18231)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install valgrind-3.8.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+
+#Untar 
+tar -jxvf  valgrind-3.8.1.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
+
+#configure
+cd install
+./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install" --enable-only64bit
+
+#Compile valgrind
+make  -j 8
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-win32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-win32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/install-win32.sh	(revision 18231)
@@ -0,0 +1,28 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install valgrind-3.8.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+
+#Untar 
+tar -jxvf  valgrind-3.8.1.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
+
+#configure
+cd install
+./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install"
+
+#Compile valgrind
+make  -j 4
+make install
+
+#final thing: if mpi is compiled in, soft link its target to a simpler name
+cd lib
+ln -s valgrind/libmpi*  ./libmpidebug.so
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/issm.supp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/issm.supp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/valgrind/issm.supp	(revision 18231)
@@ -0,0 +1,213 @@
+# This holds the errors to be suppressed from valgrind report for ISSM.
+# See: http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress
+#
+# to add errors:
+#   1. in m/classes/clusters/generic.m,
+#      add: --gen-suppressions=all
+#   2. in the errlog, copy and paste the suppression log
+#      in this file.
+
+#OS specific errors{{{
+#http://stackoverflow.com/questions/14474691/wifstream-with-imbue-locale-produces-valgrind-errors (larsen)
+{
+   <OS1>
+   Memcheck:Addr8
+   fun:wcscmp
+   fun:_ZNSt10moneypunctIwLb1EED1Ev
+   fun:_ZNSt10moneypunctIwLb1EED0Ev
+}
+{
+   <OS0>
+   Memcheck:Addr8
+   fun:wcscmp
+   fun:_ZNSt10moneypunctIwLb0EED1Ev
+   fun:_ZNSt10moneypunctIwLb0EED0Ev
+   fun:_ZNSt6locale5_ImplD1Ev
+   fun:_ZNSt6localeD1Ev
+   fun:__cxa_finalize
+   obj:/u/astrid-r1b/morlighe/issmjpl/cron/trunk-jpl/externalpackages/boost/install/lib/libboost_filesystem.so.1.49.0
+   obj:/u/astrid-r1b/morlighe/issmjpl/cron/trunk-jpl/externalpackages/boost/install/lib/libboost_filesystem.so.1.49.0
+   fun:__run_exit_handlers
+   fun:exit
+   fun:(below main)
+}
+{
+   <OS2>
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
+   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
+   fun:_ZNSsC1EPKcRKSaIcE
+}
+#}}}
+#PETSc {{{
+{
+   <petsc0>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:MatStashScatterGetMesg_Private
+   fun:MatAssemblyEnd_MPIAIJ
+   fun:MatAssemblyEnd
+}
+{
+   <petsc1>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:VecStashScatterGetMesg_Private
+   fun:VecAssemblyEnd_MPI
+   fun:VecAssemblyEnd
+   fun:_ZN8PetscVec8AssembleEv
+}
+{
+   <petsc2>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:_Z14VecToMPISerialPPdP6_p_Veci
+   fun:_ZN8PetscVec11ToMPISerialEv
+}
+{
+   <petsc3>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:VecScatterCreate_PtoS
+   fun:VecScatterCreate
+   fun:MatSetUpMultiply_MPIAIJ
+   fun:MatAssemblyEnd_MPIAIJ
+   fun:MatAssemblyEnd
+}
+{
+   <mumps0>
+   Memcheck:Leak
+   fun:malloc
+   fun:mumps_397.3148
+   fun:__mumps_static_mapping_MOD_mumps_369
+   fun:dmumps_537_
+   fun:dmumps_26_
+   fun:dmumps_
+   fun:dmumps_f77_
+   fun:dmumps_c
+   fun:MatLUFactorSymbolic_AIJMUMPS
+   fun:MatLUFactorSymbolic
+   fun:PCSetUp_LU
+   fun:PCSetUp
+}
+{
+   <mumps1>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_664_
+}
+{
+   <mumps2>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:mpi_waitany
+   fun:dmumps_664_
+}
+{
+   <mumps3>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_282_
+}
+{
+   <mumps4>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_255_
+}
+{
+   <mumps5>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Wait
+   fun:PMPI_WAIT
+   fun:dmumps_255_
+}
+{
+   <mump6>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_638_
+}
+{
+   <mumps7>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_640.3488
+}
+{
+   <mumps8>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:MPI_GET_COUNT
+   fun:dmumps_638_
+}
+{
+   <mumps9>
+   Memcheck:User
+   fun:check_mem_is_defined_untyped
+   fun:PMPI_Pack
+   fun:PMPI_PACK
+   fun:__dmumps_comm_buffer_MOD_dmumps_62
+}
+{
+   <mumps10>
+   Memcheck:User
+   fun:check_mem_is_defined_untyped
+   fun:PMPI_Pack
+   fun:PMPI_PACK
+   fun:__dmumps_comm_buffer_MOD_dmumps_62
+}
+{
+	<mumps11>
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:PMPI_Isend
+	  fun:libparmetis__gkMPI_Isend
+	  fun:libparmetis__CommInterfaceData
+	  fun:libparmetis__CompactGraph
+	  fun:libparmetis__MultilevelOrder
+	  fun:ParMETIS_V32_NodeND
+	  fun:ParMETIS_V3_NodeND
+	  fun:mumps_parmetis_
+}
+{
+	<mumps12>
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:PMPI_Bcast
+	  fun:MPI_BCAST
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_718
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_717
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_715
+}
+{
+	<mumps13>
+	  Memcheck:Leak
+	  fun:malloc
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_775
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_720
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_715
+}
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/README	(revision 18231)
@@ -0,0 +1,5 @@
+To use ISSM's settings for vim:
+
+1. Add the settings from vimrc to your .vimrc file
+
+2. Add softlinks from vim to your .vim directory
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/Align.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/Align.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/Align.vim	(revision 18231)
@@ -0,0 +1,1029 @@
+" Align: tool to align multiple fields based on one or more separators
+"   Author:		Charles E. Campbell, Jr.
+"   Date:		Mar 03, 2009
+"   Version:	35
+" GetLatestVimScripts: 294 1 :AutoInstall: Align.vim
+" GetLatestVimScripts: 1066 1 :AutoInstall: cecutil.vim
+" Copyright:    Copyright (C) 1999-2007 Charles E. Campbell, Jr. {{{1
+"               Permission is hereby granted to use and distribute this code,
+"               with or without modifications, provided that this copyright
+"               notice is copied with it. Like anything else that's free,
+"               Align.vim is provided *as is* and comes with no warranty
+"               of any kind, either expressed or implied. By using this
+"               plugin, you agree that in no event will the copyright
+"               holder be liable for any damages resulting from the use
+"               of this software.
+"
+" Romans 1:16,17a : For I am not ashamed of the gospel of Christ, for it is {{{1
+" the power of God for salvation for everyone who believes; for the Jew first,
+" and also for the Greek.  For in it is revealed God's righteousness from
+" faith to faith.
+
+" ---------------------------------------------------------------------
+" Load Once: {{{1
+if exists("g:loaded_Align") || &cp
+ finish
+endif
+let g:loaded_Align = "v35"
+if v:version < 700
+ echohl WarningMsg
+ echo "***warning*** this version of Align needs vim 7.0"
+ echohl Normal
+ finish
+endif
+let s:keepcpo= &cpo
+set cpo&vim
+"DechoTabOn
+
+" ---------------------------------------------------------------------
+" Debugging Support: {{{1
+"if !exists("g:loaded_Decho") | runtime plugin/Decho.vim | endif
+
+" ---------------------------------------------------------------------
+" Options: {{{1
+if !exists("g:Align_xstrlen")
+ if &enc == "latin1" || $LANG == "en_US.UTF-8" || !has("multi_byte")
+  let g:Align_xstrlen= 0
+ else
+  let g:Align_xstrlen= 1
+ endif
+endif
+
+" ---------------------------------------------------------------------
+" Align#AlignCtrl: enter alignment patterns here {{{1
+"
+"   Styles   =  all alignment-break patterns are equivalent
+"            C  cycle through alignment-break pattern(s)
+"            l  left-justified alignment
+"            r  right-justified alignment
+"            c  center alignment
+"            -  skip separator, treat as part of field
+"            :  treat rest of line as field
+"            +  repeat previous [lrc] style
+"            <  left justify separators
+"            >  right justify separators
+"            |  center separators
+"
+"   Builds   =  s:AlignPat  s:AlignCtrl  s:AlignPatQty
+"            C  s:AlignPat  s:AlignCtrl  s:AlignPatQty
+"            p  s:AlignPrePad
+"            P  s:AlignPostPad
+"            w  s:AlignLeadKeep
+"            W  s:AlignLeadKeep
+"            I  s:AlignLeadKeep
+"            l  s:AlignStyle
+"            r  s:AlignStyle
+"            -  s:AlignStyle
+"            +  s:AlignStyle
+"            :  s:AlignStyle
+"            c  s:AlignStyle
+"            g  s:AlignGPat
+"            v  s:AlignVPat
+"            <  s:AlignSep
+"            >  s:AlignSep
+"            |  s:AlignSep
+fun! Align#AlignCtrl(...)
+
+"  call Dfunc("AlignCtrl(...) a:0=".a:0)
+
+  " save options that will be changed
+  let keep_search = @/
+  let keep_ic     = &ic
+
+  " turn ignorecase off
+  set noic
+
+  " clear visual mode so that old visual-mode selections don't
+  " get applied to new invocations of Align().
+  if v:version < 602
+   if !exists("s:Align_gavemsg")
+	let s:Align_gavemsg= 1
+    echomsg "Align needs at least Vim version 6.2 to clear visual-mode selection"
+   endif
+  elseif exists("s:dovisclear")
+"   call Decho("clearing visual mode a:0=".a:0." a:1<".a:1.">")
+   let clearvmode= visualmode(1)
+  endif
+
+  " set up a list akin to an argument list
+  if a:0 > 0
+   let A= s:QArgSplitter(a:1)
+  else
+   let A=[0]
+  endif
+
+  if A[0] > 0
+   let style = A[1]
+
+   " Check for bad separator patterns (zero-length matches)
+   " (but zero-length patterns for g/v is ok)
+   if style !~# '[gv]'
+    let ipat= 2
+    while ipat <= A[0]
+     if "" =~ A[ipat]
+      echoerr "AlignCtrl: separator<".A[ipat]."> matches zero-length string"
+	  let &ic= keep_ic
+"      call Dret("AlignCtrl")
+      return
+     endif
+     let ipat= ipat + 1
+    endwhile
+   endif
+  endif
+
+"  call Decho("AlignCtrl() A[0]=".A[0])
+  if !exists("s:AlignStyle")
+   let s:AlignStyle= "l"
+  endif
+  if !exists("s:AlignPrePad")
+   let s:AlignPrePad= 0
+  endif
+  if !exists("s:AlignPostPad")
+   let s:AlignPostPad= 0
+  endif
+  if !exists("s:AlignLeadKeep")
+   let s:AlignLeadKeep= 'w'
+  endif
+
+  if A[0] == 0
+   " ----------------------
+   " List current selection
+   " ----------------------
+   if !exists("s:AlignPatQty")
+	let s:AlignPatQty= 0
+   endif
+   echo "AlignCtrl<".s:AlignCtrl."> qty=".s:AlignPatQty." AlignStyle<".s:AlignStyle."> Padding<".s:AlignPrePad."|".s:AlignPostPad."> LeadingWS=".s:AlignLeadKeep." AlignSep=".s:AlignSep
+"   call Decho("AlignCtrl<".s:AlignCtrl."> qty=".s:AlignPatQty." AlignStyle<".s:AlignStyle."> Padding<".s:AlignPrePad."|".s:AlignPostPad."> LeadingWS=".s:AlignLeadKeep." AlignSep=".s:AlignSep)
+   if      exists("s:AlignGPat") && !exists("s:AlignVPat")
+	echo "AlignGPat<".s:AlignGPat.">"
+   elseif !exists("s:AlignGPat") &&  exists("s:AlignVPat")
+	echo "AlignVPat<".s:AlignVPat.">"
+   elseif exists("s:AlignGPat") &&  exists("s:AlignVPat")
+	echo "AlignGPat<".s:AlignGPat."> AlignVPat<".s:AlignVPat.">"
+   endif
+   let ipat= 1
+   while ipat <= s:AlignPatQty
+	echo "Pat".ipat."<".s:AlignPat_{ipat}.">"
+"	call Decho("Pat".ipat."<".s:AlignPat_{ipat}.">")
+	let ipat= ipat + 1
+   endwhile
+
+  else
+   " ----------------------------------
+   " Process alignment control settings
+   " ----------------------------------
+"   call Decho("process the alignctrl settings")
+"   call Decho("style<".style.">")
+
+   if style ==? "default"
+     " Default:  preserve initial leading whitespace, left-justified,
+     "           alignment on '=', one space padding on both sides
+	 if exists("s:AlignCtrlStackQty")
+	  " clear AlignCtrl stack
+      while s:AlignCtrlStackQty > 0
+	   call Align#AlignPop()
+	  endwhile
+	  unlet s:AlignCtrlStackQty
+	 endif
+	 " Set AlignCtrl to its default value
+     call Align#AlignCtrl("Ilp1P1=<",'=')
+	 call Align#AlignCtrl("g")
+	 call Align#AlignCtrl("v")
+	 let s:dovisclear = 1
+	 let &ic          = keep_ic
+	 let @/           = keep_search
+"     call Dret("AlignCtrl")
+	 return
+   endif
+
+   if style =~# 'm'
+	" map support: Do an AlignPush now and the next call to Align()
+	"              will do an AlignPop at exit
+"	call Decho("style case m: do AlignPush")
+	call Align#AlignPush()
+	let s:DoAlignPop= 1
+   endif
+
+   " = : record a list of alignment patterns that are equivalent
+   if style =~# "="
+"	call Decho("style case =: record list of equiv alignment patterns")
+    let s:AlignCtrl  = '='
+	if A[0] >= 2
+     let s:AlignPatQty= 1
+     let s:AlignPat_1 = A[2]
+     let ipat         = 3
+     while ipat <= A[0]
+      let s:AlignPat_1 = s:AlignPat_1.'\|'.A[ipat]
+      let ipat         = ipat + 1
+     endwhile
+     let s:AlignPat_1= '\('.s:AlignPat_1.'\)'
+"     call Decho("AlignCtrl<".s:AlignCtrl."> AlignPat<".s:AlignPat_1.">")
+	endif
+
+    "c : cycle through alignment pattern(s)
+   elseif style =~# 'C'
+"	call Decho("style case C: cycle through alignment pattern(s)")
+    let s:AlignCtrl  = 'C'
+	if A[0] >= 2
+     let s:AlignPatQty= A[0] - 1
+     let ipat         = 1
+     while ipat < A[0]
+      let s:AlignPat_{ipat}= A[ipat+1]
+"     call Decho("AlignCtrl<".s:AlignCtrl."> AlignQty=".s:AlignPatQty." AlignPat_".ipat."<".s:AlignPat_{ipat}.">")
+      let ipat= ipat + 1
+     endwhile
+	endif
+   endif
+
+   if style =~# 'p'
+    let s:AlignPrePad= substitute(style,'^.*p\(\d\+\).*$','\1','')
+"	call Decho("style case p".s:AlignPrePad.": pre-separator padding")
+    if s:AlignPrePad == ""
+     echoerr "AlignCtrl: 'p' needs to be followed by a numeric argument'
+     let @/ = keep_search
+	 let &ic= keep_ic
+"     call Dret("AlignCtrl")
+     return
+	endif
+   endif
+
+   if style =~# 'P'
+    let s:AlignPostPad= substitute(style,'^.*P\(\d\+\).*$','\1','')
+"	call Decho("style case P".s:AlignPostPad.": post-separator padding")
+    if s:AlignPostPad == ""
+     echoerr "AlignCtrl: 'P' needs to be followed by a numeric argument'
+     let @/ = keep_search
+	 let &ic= keep_ic
+"     call Dret("AlignCtrl")
+     return
+	endif
+   endif
+
+   if     style =~# 'w'
+"	call Decho("style case w: ignore leading whitespace")
+	let s:AlignLeadKeep= 'w'
+   elseif style =~# 'W'
+"	call Decho("style case w: keep leading whitespace")
+	let s:AlignLeadKeep= 'W'
+   elseif style =~# 'I'
+"	call Decho("style case w: retain initial leading whitespace")
+	let s:AlignLeadKeep= 'I'
+   endif
+
+   if style =~# 'g'
+	" first list item is a "g" selector pattern
+"	call Decho("style case g: global selector pattern")
+	if A[0] < 2
+	 if exists("s:AlignGPat")
+	  unlet s:AlignGPat
+"	  call Decho("unlet s:AlignGPat")
+	 endif
+	else
+	 let s:AlignGPat= A[2]
+"	 call Decho("s:AlignGPat<".s:AlignGPat.">")
+	endif
+   elseif style =~# 'v'
+	" first list item is a "v" selector pattern
+"	call Decho("style case v: global selector anti-pattern")
+	if A[0] < 2
+	 if exists("s:AlignVPat")
+	  unlet s:AlignVPat
+"	  call Decho("unlet s:AlignVPat")
+	 endif
+	else
+	 let s:AlignVPat= A[2]
+"	 call Decho("s:AlignVPat<".s:AlignVPat.">")
+	endif
+   endif
+
+    "[-lrc+:] : set up s:AlignStyle
+   if style =~# '[-lrc+:]'
+"	call Decho("style case [-lrc+:]: field justification")
+    let s:AlignStyle= substitute(style,'[^-lrc:+]','','g')
+"    call Decho("AlignStyle<".s:AlignStyle.">")
+   endif
+
+   "[<>|] : set up s:AlignSep
+   if style =~# '[<>|]'
+"	call Decho("style case [-lrc+:]: separator justification")
+	let s:AlignSep= substitute(style,'[^<>|]','','g')
+"	call Decho("AlignSep ".s:AlignSep)
+   endif
+  endif
+
+  " sanity
+  if !exists("s:AlignCtrl")
+   let s:AlignCtrl= '='
+  endif
+
+  " restore search and options
+  let @/ = keep_search
+  let &ic= keep_ic
+
+"  call Dret("AlignCtrl ".s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle)
+  return s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle
+endfun
+
+" ---------------------------------------------------------------------
+" s:MakeSpace: returns a string with spacecnt blanks {{{1
+fun! s:MakeSpace(spacecnt)
+"  call Dfunc("MakeSpace(spacecnt=".a:spacecnt.")")
+  let str      = ""
+  let spacecnt = a:spacecnt
+  while spacecnt > 0
+   let str      = str . " "
+   let spacecnt = spacecnt - 1
+  endwhile
+"  call Dret("MakeSpace <".str.">")
+  return str
+endfun
+
+" ---------------------------------------------------------------------
+" Align#Align: align selected text based on alignment pattern(s) {{{1
+fun! Align#Align(hasctrl,...) range
+"  call Dfunc("Align#Align(hasctrl=".a:hasctrl.",...) a:0=".a:0)
+
+  " sanity checks
+  if string(a:hasctrl) != "0" && string(a:hasctrl) != "1"
+   echohl Error|echo 'usage: Align#Align(hasctrl<'.a:hasctrl.'> (should be 0 or 1),"separator(s)"  (you have '.a:0.') )'|echohl None
+"   call Dret("Align#Align")
+   return
+  endif
+  if exists("s:AlignStyle") && s:AlignStyle == ":"
+   echohl Error |echo '(Align#Align) your AlignStyle is ":", which implies "do-no-alignment"!'|echohl None
+"   call Dret("Align#Align")
+   return
+  endif
+
+  " set up a list akin to an argument list
+  if a:0 > 0
+   let A= s:QArgSplitter(a:1)
+  else
+   let A=[0]
+  endif
+
+  " if :Align! was used, then the first argument is (should be!) an AlignCtrl string
+  " Note that any alignment control set this way will be temporary.
+  let hasctrl= a:hasctrl
+"  call Decho("hasctrl=".hasctrl)
+  if a:hasctrl && A[0] >= 1
+"   call Decho("Align! : using A[1]<".A[1]."> for AlignCtrl")
+   if A[1] =~ '[gv]'
+   	let hasctrl= hasctrl + 1
+	call Align#AlignCtrl('m')
+    call Align#AlignCtrl(A[1],A[2])
+"    call Decho("Align! : also using A[2]<".A[2]."> for AlignCtrl")
+   elseif A[1] !~ 'm'
+    call Align#AlignCtrl(A[1]."m")
+   else
+    call Align#AlignCtrl(A[1])
+   endif
+  endif
+
+  " Check for bad separator patterns (zero-length matches)
+  let ipat= 1 + hasctrl
+  while ipat <= A[0]
+   if "" =~ A[ipat]
+	echoerr "Align: separator<".A[ipat]."> matches zero-length string"
+"    call Dret("Align#Align")
+	return
+   endif
+   let ipat= ipat + 1
+  endwhile
+
+  " record current search pattern for subsequent restoration
+  let keep_search= @/
+  let keep_ic    = &ic
+  let keep_report= &report
+  set noic report=10000
+
+  if A[0] > hasctrl
+  " Align will accept a list of separator regexps
+"   call Decho("A[0]=".A[0].": accepting list of separator regexp")
+
+   if s:AlignCtrl =~# "="
+   	"= : consider all separators to be equivalent
+"    call Decho("AlignCtrl: record list of equivalent alignment patterns")
+    let s:AlignCtrl  = '='
+    let s:AlignPat_1 = A[1 + hasctrl]
+    let s:AlignPatQty= 1
+    let ipat         = 2 + hasctrl
+    while ipat <= A[0]
+     let s:AlignPat_1 = s:AlignPat_1.'\|'.A[ipat]
+     let ipat         = ipat + 1
+    endwhile
+    let s:AlignPat_1= '\('.s:AlignPat_1.'\)'
+"    call Decho("AlignCtrl<".s:AlignCtrl."> AlignPat<".s:AlignPat_1.">")
+
+   elseif s:AlignCtrl =~# 'C'
+    "c : cycle through alignment pattern(s)
+"    call Decho("AlignCtrl: cycle through alignment pattern(s)")
+    let s:AlignCtrl  = 'C'
+    let s:AlignPatQty= A[0] - hasctrl
+    let ipat         = 1
+    while ipat <= s:AlignPatQty
+     let s:AlignPat_{ipat}= A[(ipat + hasctrl)]
+"     call Decho("AlignCtrl<".s:AlignCtrl."> AlignQty=".s:AlignPatQty." AlignPat_".ipat."<".s:AlignPat_{ipat}.">")
+     let ipat= ipat + 1
+    endwhile
+   endif
+  endif
+
+  " Initialize so that begline<endline and begcol<endcol.
+  " Ragged right: check if the column associated with '< or '>
+  "               is greater than the line's string length -> ragged right.
+  " Have to be careful about visualmode() -- it returns the last visual
+  " mode used whether or not it was used currently.
+  let begcol   = virtcol("'<")-1
+  let endcol   = virtcol("'>")-1
+  if begcol > endcol
+   let begcol  = virtcol("'>")-1
+   let endcol  = virtcol("'<")-1
+  endif
+"  call Decho("begcol=".begcol." endcol=".endcol)
+  let begline  = a:firstline
+  let endline  = a:lastline
+  if begline > endline
+   let begline = a:lastline
+   let endline = a:firstline
+  endif
+"  call Decho("begline=".begline." endline=".endline)
+  let fieldcnt = 0
+  if (begline == line("'>") && endline == line("'<")) || (begline == line("'<") && endline == line("'>"))
+   let vmode= visualmode()
+"   call Decho("vmode=".vmode)
+   if vmode == "\<c-v>"
+	if exists("g:Align_xstrlen") && g:Align_xstrlen
+     let ragged   = ( col("'>") > s:Strlen(getline("'>")) || col("'<") > s:Strlen(getline("'<")) )
+	else
+     let ragged   = ( col("'>") > strlen(getline("'>")) || col("'<") > strlen(getline("'<")) )
+	endif
+   else
+	let ragged= 1
+   endif
+  else
+   let ragged= 1
+  endif
+  if ragged
+   let begcol= 0
+  endif
+"  call Decho("lines[".begline.",".endline."] col[".begcol.",".endcol."] ragged=".ragged." AlignCtrl<".s:AlignCtrl.">")
+
+  " Keep user options
+  let etkeep   = &l:et
+  let pastekeep= &l:paste
+  setlocal et paste
+
+  " convert selected range of lines to use spaces instead of tabs
+  " but if first line's initial white spaces are to be retained
+  " then use 'em
+  if begcol <= 0 && s:AlignLeadKeep == 'I'
+   " retain first leading whitespace for all subsequent lines
+   let bgntxt= substitute(getline(begline),'^\(\s*\).\{-}$','\1','')
+"   call Decho("retaining 1st leading whitespace: bgntxt<".bgntxt.">")
+   set noet
+  endif
+  exe begline.",".endline."ret"
+
+  " Execute two passes
+  " First  pass: collect alignment data (max field sizes)
+  " Second pass: perform alignment
+  let pass= 1
+  while pass <= 2
+"   call Decho(" ")
+"   call Decho("---- Pass ".pass.": ----")
+
+   let line= begline
+   while line <= endline
+    " Process each line
+    let txt = getline(line)
+"    call Decho(" ")
+"    call Decho("Pass".pass.": Line ".line." <".txt.">")
+
+    " AlignGPat support: allows a selector pattern (akin to g/selector/cmd )
+    if exists("s:AlignGPat")
+"	 call Decho("Pass".pass.": AlignGPat<".s:AlignGPat.">")
+	 if match(txt,s:AlignGPat) == -1
+"	  call Decho("Pass".pass.": skipping")
+	  let line= line + 1
+	  continue
+	 endif
+    endif
+
+    " AlignVPat support: allows a selector pattern (akin to v/selector/cmd )
+    if exists("s:AlignVPat")
+"	 call Decho("Pass".pass.": AlignVPat<".s:AlignVPat.">")
+	 if match(txt,s:AlignVPat) != -1
+"	  call Decho("Pass".pass.": skipping")
+	  let line= line + 1
+	  continue
+	 endif
+    endif
+
+	" Always skip blank lines
+	if match(txt,'^\s*$') != -1
+"	  call Decho("Pass".pass.": skipping")
+	 let line= line + 1
+	 continue
+	endif
+
+    " Extract visual-block selected text (init bgntxt, endtxt)
+	if exists("g:Align_xstrlen") && g:Align_xstrlen
+     let txtlen= s:Strlen(txt)
+	else
+     let txtlen= strlen(txt)
+	endif
+    if begcol > 0
+	 " Record text to left of selected area
+     let bgntxt= strpart(txt,0,begcol)
+"	  call Decho("Pass".pass.": record text to left: bgntxt<".bgntxt.">")
+    elseif s:AlignLeadKeep == 'W'
+	 let bgntxt= substitute(txt,'^\(\s*\).\{-}$','\1','')
+"	  call Decho("Pass".pass.": retaining all leading ws: bgntxt<".bgntxt.">")
+    elseif s:AlignLeadKeep == 'w' || !exists("bgntxt")
+	 " No beginning text
+	 let bgntxt= ""
+"	  call Decho("Pass".pass.": no beginning text")
+    endif
+    if ragged
+	 let endtxt= ""
+    else
+     " Elide any text lying outside selected columnar region
+     let endtxt= strpart(txt,endcol+1,txtlen-endcol)
+     let txt   = strpart(txt,begcol,endcol-begcol+1)
+    endif
+"    call Decho(" ")
+"    call Decho("Pass".pass.": bgntxt<".bgntxt.">")
+"    call Decho("Pass".pass.":    txt<". txt  .">")
+"    call Decho("Pass".pass.": endtxt<".endtxt.">")
+	if !exists("s:AlignPat_{1}")
+	 echohl Error|echo "no separators specified!"|echohl None
+"     call Dret("Align#Align")
+	 return
+	endif
+
+    " Initialize for both passes
+    let seppat      = s:AlignPat_{1}
+    let ifield      = 1
+    let ipat        = 1
+    let bgnfield    = 0
+    let endfield    = 0
+    let alignstyle  = s:AlignStyle
+    let doend       = 1
+	let newtxt      = ""
+    let alignprepad = s:AlignPrePad
+    let alignpostpad= s:AlignPostPad
+	let alignsep    = s:AlignSep
+	let alignophold = " "
+	let alignop     = "l"
+"	call Decho("Pass".pass.": initial alignstyle<".alignstyle."> seppat<".seppat.">")
+
+    " Process each field on the line
+    while doend > 0
+
+	  " C-style: cycle through pattern(s)
+     if s:AlignCtrl == 'C' && doend == 1
+	  let seppat   = s:AlignPat_{ipat}
+"	  call Decho("Pass".pass.": processing field: AlignCtrl=".s:AlignCtrl." ipat=".ipat." seppat<".seppat.">")
+	  let ipat     = ipat + 1
+	  if ipat > s:AlignPatQty
+	   let ipat = 1
+	  endif
+     endif
+
+	 " cyclic alignment/justification operator handling
+	 let alignophold  = alignop
+	 let alignop      = strpart(alignstyle,0,1)
+	 if alignop == '+' || doend == 2
+	  let alignop= alignophold
+	 else
+	  let alignstyle   = strpart(alignstyle,1).strpart(alignstyle,0,1)
+	  let alignopnxt   = strpart(alignstyle,0,1)
+	  if alignop == ':'
+	   let seppat  = '$'
+	   let doend   = 2
+"	   call Decho("Pass".pass.": alignop<:> case: setting seppat<$> doend==2")
+	  endif
+	 endif
+
+	 " cylic separator alignment specification handling
+	 let alignsepop= strpart(alignsep,0,1)
+	 let alignsep  = strpart(alignsep,1).alignsepop
+
+	 " mark end-of-field and the subsequent end-of-separator.
+	 " Extend field if alignop is '-'
+     let endfield = match(txt,seppat,bgnfield)
+	 let sepfield = matchend(txt,seppat,bgnfield)
+     let skipfield= sepfield
+"	 call Decho("Pass".pass.": endfield=match(txt<".txt.">,seppat<".seppat.">,bgnfield=".bgnfield.")=".endfield)
+	 while alignop == '-' && endfield != -1
+	  let endfield  = match(txt,seppat,skipfield)
+	  let sepfield  = matchend(txt,seppat,skipfield)
+	  let skipfield = sepfield
+	  let alignop   = strpart(alignstyle,0,1)
+	  let alignstyle= strpart(alignstyle,1).strpart(alignstyle,0,1)
+"	  call Decho("Pass".pass.": extend field: endfield<".strpart(txt,bgnfield,endfield-bgnfield)."> alignop<".alignop."> alignstyle<".alignstyle.">")
+	 endwhile
+	 let seplen= sepfield - endfield
+"	 call Decho("Pass".pass.": seplen=[sepfield=".sepfield."] - [endfield=".endfield."]=".seplen)
+
+	 if endfield != -1
+	  if pass == 1
+	   " ---------------------------------------------------------------------
+	   " Pass 1: Update FieldSize to max
+"	   call Decho("Pass".pass.": before lead/trail remove: field<".strpart(txt,bgnfield,endfield-bgnfield).">")
+	   let field      = substitute(strpart(txt,bgnfield,endfield-bgnfield),'^\s*\(.\{-}\)\s*$','\1','')
+       if s:AlignLeadKeep == 'W'
+	    let field = bgntxt.field
+	    let bgntxt= ""
+	   endif
+	   if exists("g:Align_xstrlen") && g:Align_xstrlen
+	    let fieldlen   = s:Strlen(field)
+	   else
+	    let fieldlen   = strlen(field)
+	   endif
+	   let sFieldSize = "FieldSize_".ifield
+	   if !exists(sFieldSize)
+	    let FieldSize_{ifield}= fieldlen
+"	    call Decho("Pass".pass.":  set FieldSize_{".ifield."}=".FieldSize_{ifield}." <".field.">")
+	   elseif fieldlen > FieldSize_{ifield}
+	    let FieldSize_{ifield}= fieldlen
+"	    call Decho("Pass".pass.": oset FieldSize_{".ifield."}=".FieldSize_{ifield}." <".field.">")
+	   endif
+	   let sSepSize= "SepSize_".ifield
+	   if !exists(sSepSize)
+		let SepSize_{ifield}= seplen
+"	    call Decho(" set SepSize_{".ifield."}=".SepSize_{ifield}." <".field.">")
+	   elseif seplen > SepSize_{ifield}
+		let SepSize_{ifield}= seplen
+"	    call Decho("Pass".pass.": oset SepSize_{".ifield."}=".SepSize_{ifield}." <".field.">")
+	   endif
+
+	  else
+	   " ---------------------------------------------------------------------
+	   " Pass 2: Perform Alignment
+	   let prepad       = strpart(alignprepad,0,1)
+	   let postpad      = strpart(alignpostpad,0,1)
+	   let alignprepad  = strpart(alignprepad,1).strpart(alignprepad,0,1)
+	   let alignpostpad = strpart(alignpostpad,1).strpart(alignpostpad,0,1)
+	   let field        = substitute(strpart(txt,bgnfield,endfield-bgnfield),'^\s*\(.\{-}\)\s*$','\1','')
+       if s:AlignLeadKeep == 'W'
+	    let field = bgntxt.field
+	    let bgntxt= ""
+	   endif
+	   if doend == 2
+		let prepad = 0
+		let postpad= 0
+	   endif
+	   if exists("g:Align_xstrlen") && g:Align_xstrlen
+	    let fieldlen   = s:Strlen(field)
+	   else
+	    let fieldlen   = strlen(field)
+	   endif
+	   let sep        = s:MakeSpace(prepad).strpart(txt,endfield,sepfield-endfield).s:MakeSpace(postpad)
+	   if seplen < SepSize_{ifield}
+		if alignsepop == "<"
+		 " left-justify separators
+		 let sep       = sep.s:MakeSpace(SepSize_{ifield}-seplen)
+		elseif alignsepop == ">"
+		 " right-justify separators
+		 let sep       = s:MakeSpace(SepSize_{ifield}-seplen).sep
+		else
+		 " center-justify separators
+		 let sepleft   = (SepSize_{ifield} - seplen)/2
+		 let sepright  = SepSize_{ifield} - seplen - sepleft
+		 let sep       = s:MakeSpace(sepleft).sep.s:MakeSpace(sepright)
+		endif
+	   endif
+	   let spaces     = FieldSize_{ifield} - fieldlen
+"	   call Decho("Pass".pass.": Field #".ifield."<".field."> spaces=".spaces." be[".bgnfield.",".endfield."] pad=".prepad.','.postpad." FS_".ifield."<".FieldSize_{ifield}."> sep<".sep."> ragged=".ragged." doend=".doend." alignop<".alignop.">")
+
+	    " Perform alignment according to alignment style justification
+	   if spaces > 0
+	    if     alignop == 'c'
+		 " center the field
+	     let spaceleft = spaces/2
+	     let spaceright= FieldSize_{ifield} - spaceleft - fieldlen
+	     let newtxt    = newtxt.s:MakeSpace(spaceleft).field.s:MakeSpace(spaceright).sep
+	    elseif alignop == 'r'
+		 " right justify the field
+	     let newtxt= newtxt.s:MakeSpace(spaces).field.sep
+	    elseif ragged && doend == 2
+		 " left justify rightmost field (no trailing blanks needed)
+	     let newtxt= newtxt.field
+		else
+		 " left justfiy the field
+	     let newtxt= newtxt.field.s:MakeSpace(spaces).sep
+	    endif
+	   elseif ragged && doend == 2
+		" field at maximum field size and no trailing blanks needed
+	    let newtxt= newtxt.field
+	   else
+		" field is at maximum field size already
+	    let newtxt= newtxt.field.sep
+	   endif
+"	   call Decho("Pass".pass.": newtxt<".newtxt.">")
+	  endif	" pass 1/2
+
+	  " bgnfield indexes to end of separator at right of current field
+	  " Update field counter
+	  let bgnfield= sepfield
+      let ifield  = ifield + 1
+	  if doend == 2
+	   let doend= 0
+	  endif
+	   " handle end-of-text as end-of-field
+	 elseif doend == 1
+	  let seppat  = '$'
+	  let doend   = 2
+	 else
+	  let doend   = 0
+	 endif		" endfield != -1
+    endwhile	" doend loop (as well as regularly separated fields)
+
+	if pass == 2
+	 " Write altered line to buffer
+"     call Decho("Pass".pass.": bgntxt<".bgntxt."> line=".line)
+"     call Decho("Pass".pass.": newtxt<".newtxt.">")
+"     call Decho("Pass".pass.": endtxt<".endtxt.">")
+	 call setline(line,bgntxt.newtxt.endtxt)
+	endif
+
+    let line = line + 1
+   endwhile	" line loop
+
+   let pass= pass + 1
+  endwhile	" pass loop
+"  call Decho("end of two pass loop")
+
+  " Restore user options
+  let &l:et    = etkeep
+  let &l:paste = pastekeep
+
+  if exists("s:DoAlignPop")
+   " AlignCtrl Map support
+   call Align#AlignPop()
+   unlet s:DoAlignPop
+  endif
+
+  " restore current search pattern
+  let @/      = keep_search
+  let &ic     = keep_ic
+  let &report = keep_report
+
+"  call Dret("Align#Align")
+  return
+endfun
+
+" ---------------------------------------------------------------------
+" Align#AlignPush: this command/function pushes an alignment control string onto a stack {{{1
+fun! Align#AlignPush()
+"  call Dfunc("AlignPush()")
+
+  " initialize the stack
+  if !exists("s:AlignCtrlStackQty")
+   let s:AlignCtrlStackQty= 1
+  else
+   let s:AlignCtrlStackQty= s:AlignCtrlStackQty + 1
+  endif
+
+  " construct an AlignCtrlStack entry
+  if !exists("s:AlignSep")
+   let s:AlignSep= ''
+  endif
+  let s:AlignCtrlStack_{s:AlignCtrlStackQty}= s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle.s:AlignSep
+"  call Decho("AlignPush: AlignCtrlStack_".s:AlignCtrlStackQty."<".s:AlignCtrlStack_{s:AlignCtrlStackQty}.">")
+
+  " push [GV] patterns onto their own stack
+  if exists("s:AlignGPat")
+   let s:AlignGPat_{s:AlignCtrlStackQty}= s:AlignGPat
+  else
+   let s:AlignGPat_{s:AlignCtrlStackQty}=  ""
+  endif
+  if exists("s:AlignVPat")
+   let s:AlignVPat_{s:AlignCtrlStackQty}= s:AlignVPat
+  else
+   let s:AlignVPat_{s:AlignCtrlStackQty}=  ""
+  endif
+
+"  call Dret("AlignPush")
+endfun
+
+" ---------------------------------------------------------------------
+" Align#AlignPop: this command/function pops an alignment pattern from a stack {{{1
+"           and into the AlignCtrl variables.
+fun! Align#AlignPop()
+"  call Dfunc("Align#AlignPop()")
+
+  " sanity checks
+  if !exists("s:AlignCtrlStackQty")
+   echoerr "AlignPush needs to be used prior to AlignPop"
+"   call Dret("Align#AlignPop <> : AlignPush needs to have been called first")
+   return ""
+  endif
+  if s:AlignCtrlStackQty <= 0
+   unlet s:AlignCtrlStackQty
+   echoerr "AlignPush needs to be used prior to AlignPop"
+"   call Dret("Align#AlignPop <> : AlignPop needs to have been called first")
+   return ""
+  endif
+
+  " pop top of AlignCtrlStack and pass value to AlignCtrl
+  let retval=s:AlignCtrlStack_{s:AlignCtrlStackQty}
+  unlet s:AlignCtrlStack_{s:AlignCtrlStackQty}
+  call Align#AlignCtrl(retval)
+
+  " pop G pattern stack
+  if s:AlignGPat_{s:AlignCtrlStackQty} != ""
+   call Align#AlignCtrl('g',s:AlignGPat_{s:AlignCtrlStackQty})
+  else
+   call Align#AlignCtrl('g')
+  endif
+  unlet s:AlignGPat_{s:AlignCtrlStackQty}
+
+  " pop V pattern stack
+  if s:AlignVPat_{s:AlignCtrlStackQty} != ""
+   call Align#AlignCtrl('v',s:AlignVPat_{s:AlignCtrlStackQty})
+  else
+   call Align#AlignCtrl('v')
+  endif
+
+  unlet s:AlignVPat_{s:AlignCtrlStackQty}
+  let s:AlignCtrlStackQty= s:AlignCtrlStackQty - 1
+
+"  call Dret("Align#AlignPop <".retval."> : AlignCtrlStackQty=".s:AlignCtrlStackQty)
+  return retval
+endfun
+
+" ---------------------------------------------------------------------
+" Align#AlignReplaceQuotedSpaces: {{{1
+fun! Align#AlignReplaceQuotedSpaces() 
+"  call Dfunc("AlignReplaceQuotedSpaces()")
+
+  let l:line          = getline(line("."))
+  if exists("g:Align_xstrlen") && g:Align_xstrlen
+   let l:linelen      = s:Strlen(l:line)
+  else
+   let l:linelen      = strlen(l:line)
+  endif
+  let l:startingPos   = 0
+  let l:startQuotePos = 0
+  let l:endQuotePos   = 0
+  let l:spacePos      = 0
+  let l:quoteRe       = '\\\@<!"'
+
+"  "call Decho("in replace spaces.  line=" . line('.'))
+  while (1)
+    let l:startQuotePos = match(l:line, l:quoteRe, l:startingPos)
+    if (l:startQuotePos < 0) 
+"      "call Decho("No more quotes to the end of line")
+      break
+    endif
+    let l:endQuotePos = match(l:line, l:quoteRe, l:startQuotePos + 1)
+    if (l:endQuotePos < 0)
+"      "call Decho("Mismatched quotes")
+      break
+    endif
+    let l:spaceReplaceRe = '^.\{' . (l:startQuotePos + 1) . '}.\{-}\zs\s\ze.*.\{' . (linelen - l:endQuotePos) . '}$'
+"    "call Decho('spaceReplaceRe="' . l:spaceReplaceRe . '"')
+    let l:newStr = substitute(l:line, l:spaceReplaceRe, '%', '')
+    while (l:newStr != l:line)
+"      "call Decho('newstr="' . l:newStr . '"')
+      let l:line = l:newStr
+      let l:newStr = substitute(l:line, l:spaceReplaceRe, '%', '')
+    endwhile
+    let l:startingPos = l:endQuotePos + 1
+  endwhile
+  call setline(line('.'), l:line)
+
+"  call Dret("AlignReplaceQuotedSpaces")
+endfun
+
+" ---------------------------------------------------------------------
+" s:QArgSplitter: to avoid \ processing by <f-args>, <q-args> is needed. {{{1
+" However, <q-args> doesn't split at all, so this function returns a list
+" of arguments which has been:
+"   * split at whitespace
+"   * unless inside "..."s.  One may escape characters with a backslash inside double quotes.
+" along with a leading length-of-list.
+"
+"   Examples:   %Align "\""   will align on "s
+"               %Align " "    will align on spaces
+"
+" The resulting list:  qarglist[0] corresponds to a:0
+"                      qarglist[i] corresponds to a:{i}
+fun! s:QArgSplitter(qarg)
+"  call Dfunc("s:QArgSplitter(qarg<".a:qarg.">)")
+
+  if a:qarg =~ '".*"'
+   " handle "..." args, which may include whitespace
+   let qarglist = []
+   let args     = a:qarg
+"   call Decho("handle quoted arguments: args<".args.">")
+   while args != ""
+	let iarg   = 0
+	let arglen = strlen(args)
+"	call Decho("args[".iarg."]<".args[iarg]."> arglen=".arglen)
+	" find index to first not-escaped '"'
+	while args[iarg] != '"' && iarg < arglen
+	 if args[iarg] == '\'
+	  let args= strpart(args,1)
+	 endif
+	 let iarg= iarg + 1
+	endwhile
+"	call Decho("args<".args."> iarg=".iarg." arglen=".arglen)
+
+	if iarg > 0
+	 " handle left of quote or remaining section
+"	 call Decho("handle left of quote or remaining section")
+	 if args[iarg] == '"'
+	  let qarglist= qarglist + split(strpart(args,0,iarg-1))
+	 else
+	  let qarglist= qarglist + split(strpart(args,0,iarg))
+	 endif
+	 let args    = strpart(args,iarg)
+	 let arglen  = strlen(args)
+
+	elseif iarg < arglen && args[0] == '"'
+	 " handle "quoted" section
+"	 call Decho("handle quoted section")
+	 let iarg= 1
+	 while args[iarg] != '"' && iarg < arglen
+	  if args[iarg] == '\'
+	   let args= strpart(args,1)
+	  endif
+	  let iarg= iarg + 1
+	 endwhile
+"	 call Decho("args<".args."> iarg=".iarg." arglen=".arglen)
+	 if args[iarg] == '"'
+	  call add(qarglist,strpart(args,1,iarg-1))
+	  let args= strpart(args,iarg+1)
+	 else
+	  let qarglist = qarglist + split(args)
+	  let args     = ""
+	 endif
+	endif
+"	call Decho("qarglist".string(qarglist)." iarg=".iarg." args<".args.">")
+   endwhile
+
+  else
+   " split at all whitespace
+   let qarglist= split(a:qarg)
+  endif
+
+  let qarglistlen= len(qarglist)
+  let qarglist   = insert(qarglist,qarglistlen)
+"  call Dret("s:QArgSplitter ".string(qarglist))
+  return qarglist
+endfun
+
+" ---------------------------------------------------------------------
+" s:Strlen: this function returns the length of a string, even if its {{{1
+"           using two-byte etc characters.
+"           Currently, its only used if g:Align_xstrlen is set to a
+"           nonzero value.  Solution from Nicolai Weibull, vim docs
+"           (:help strlen()), Tony Mechelynck, and my own invention.
+fun! s:Strlen(x)
+"  call Dfunc("s:Strlen(x<".a:x.">")
+  if g:Align_xstrlen == 1
+   " number of codepoints (Latin a + combining circumflex is two codepoints)
+   " (comment from TM, solution from NW)
+   let ret= strlen(substitute(a:x,'.','c','g'))
+
+  elseif g:Align_xstrlen == 2
+   " number of spacing codepoints (Latin a + combining circumflex is one spacing 
+   " codepoint; a hard tab is one; wide and narrow CJK are one each; etc.)
+   " (comment from TM, solution from TM)
+   let ret=strlen(substitute(a:x, '.\Z', 'x', 'g')) 
+
+  elseif g:Align_xstrlen == 3
+   " virtual length (counting, for instance, tabs as anything between 1 and 
+   " 'tabstop', wide CJK as 2 rather than 1, Arabic alif as zero when immediately 
+   " preceded by lam, one otherwise, etc.)
+   " (comment from TM, solution from me)
+   let modkeep= &l:mod
+   exe "norm! o\<esc>"
+   call setline(line("."),a:x)
+   let ret= virtcol("$") - 1
+   d
+   let &l:mod= modkeep
+
+  else
+   " at least give a decent default
+   ret= strlen(a:x)
+  endif
+"  call Dret("s:Strlen ".ret)
+  return ret
+endfun
+
+" ---------------------------------------------------------------------
+" Set up default values: {{{1
+"call Decho("-- Begin AlignCtrl Initialization --")
+call Align#AlignCtrl("default")
+"call Decho("-- End AlignCtrl Initialization --")
+
+" ---------------------------------------------------------------------
+"  Restore: {{{1
+let &cpo= s:keepcpo
+unlet s:keepcpo
+" vim: ts=4 fdm=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/AlignMaps.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/AlignMaps.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/autoload/AlignMaps.vim	(revision 18231)
@@ -0,0 +1,330 @@
+" AlignMaps.vim : support functions for AlignMaps
+"   Author: Charles E. Campbell, Jr.
+"   Date:   Mar 03, 2009
+" Version:           41
+" ---------------------------------------------------------------------
+"  Load Once: {{{1
+if &cp || exists("g:loaded_AlignMaps")
+ finish
+endif
+let g:loaded_AlignMaps= "v41"
+let s:keepcpo         = &cpo
+set cpo&vim
+
+" =====================================================================
+" Functions: {{{1
+
+" ---------------------------------------------------------------------
+" AlignMaps#WrapperStart: {{{2
+fun! AlignMaps#WrapperStart(vis) range
+"  call Dfunc("AlignMaps#WrapperStart(vis=".a:vis.")")
+
+  if a:vis
+   norm! '<ma'>
+  endif
+
+  if line("'y") == 0 || line("'z") == 0 || !exists("s:alignmaps_wrapcnt") || s:alignmaps_wrapcnt <= 0
+"   call Decho("wrapper initialization")
+   let s:alignmaps_wrapcnt    = 1
+   let s:alignmaps_keepgd     = &gdefault
+   let s:alignmaps_keepsearch = @/
+   let s:alignmaps_keepch     = &ch
+   let s:alignmaps_keepmy     = SaveMark("'y")
+   let s:alignmaps_keepmz     = SaveMark("'z")
+   let s:alignmaps_posn       = SaveWinPosn(0)
+   " set up fencepost blank lines
+   put =''
+   norm! mz'a
+   put! =''
+   ky
+   let s:alignmaps_zline      = line("'z")
+   exe "'y,'zs/@/\177/ge"
+  else
+"   call Decho("embedded wrapper")
+   let s:alignmaps_wrapcnt    = s:alignmaps_wrapcnt + 1
+   norm! 'yjma'zk
+  endif
+
+  " change some settings to align-standard values
+  set nogd
+  set ch=2
+  AlignPush
+  norm! 'zk
+"  call Dret("AlignMaps#WrapperStart : alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z"))
+endfun
+
+" ---------------------------------------------------------------------
+" AlignMaps#WrapperEnd:	{{{2
+fun! AlignMaps#WrapperEnd() range
+"  call Dfunc("AlignMaps#WrapperEnd() alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z"))
+
+  " remove trailing white space introduced by whatever in the modification zone
+  'y,'zs/ \+$//e
+
+  " restore AlignCtrl settings
+  AlignPop
+
+  let s:alignmaps_wrapcnt= s:alignmaps_wrapcnt - 1
+  if s:alignmaps_wrapcnt <= 0
+   " initial wrapper ending
+   exe "'y,'zs/\177/@/ge"
+
+   " if the 'z line hasn't moved, then go ahead and restore window position
+   let zstationary= s:alignmaps_zline == line("'z")
+
+   " remove fencepost blank lines.
+   " restore 'a
+   norm! 'yjmakdd'zdd
+
+   " restore original 'y, 'z, and window positioning
+   call RestoreMark(s:alignmaps_keepmy)
+   call RestoreMark(s:alignmaps_keepmz)
+   if zstationary > 0
+    call RestoreWinPosn(s:alignmaps_posn)
+"    call Decho("restored window positioning")
+   endif
+
+   " restoration of options
+   let &gd= s:alignmaps_keepgd
+   let &ch= s:alignmaps_keepch
+   let @/ = s:alignmaps_keepsearch
+
+   " remove script variables
+   unlet s:alignmaps_keepch
+   unlet s:alignmaps_keepsearch
+   unlet s:alignmaps_keepmy
+   unlet s:alignmaps_keepmz
+   unlet s:alignmaps_keepgd
+   unlet s:alignmaps_posn
+  endif
+
+"  call Dret("AlignMaps#WrapperEnd : alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z"))
+endfun
+
+" ---------------------------------------------------------------------
+" AlignMaps#StdAlign: some semi-standard align calls {{{2
+fun! AlignMaps#StdAlign(mode) range
+"  call Dfunc("AlignMaps#StdAlign(mode=".a:mode.")")
+  if     a:mode == 1
+   " align on @
+"   call Decho("align on @")
+   AlignCtrl mIp1P1=l @
+   'a,.Align
+  elseif a:mode == 2
+   " align on @, retaining all initial white space on each line
+"   call Decho("align on @, retaining all initial white space on each line")
+   AlignCtrl mWp1P1=l @
+   'a,.Align
+  elseif a:mode == 3
+   " like mode 2, but ignore /* */-style comments
+"   call Decho("like mode 2, but ignore /* */-style comments")
+   AlignCtrl v ^\s*/[/*]
+   AlignCtrl mWp1P1=l @
+   'a,.Align
+  else
+   echoerr "(AlignMaps) AlignMaps#StdAlign doesn't support mode#".a:mode
+  endif
+"  call Dret("AlignMaps#StdAlign")
+endfun
+
+" ---------------------------------------------------------------------
+" AlignMaps#CharJoiner: joins lines which end in the given character (spaces {{{2
+"             at end are ignored)
+fun! AlignMaps#CharJoiner(chr)
+"  call Dfunc("AlignMaps#CharJoiner(chr=".a:chr.")")
+  let aline = line("'a")
+  let rep   = line(".") - aline
+  while rep > 0
+  	norm! 'a
+  	while match(getline(aline),a:chr . "\s*$") != -1 && rep >= 0
+  	  " while = at end-of-line, delete it and join with next
+  	  norm! 'a$
+  	  j!
+  	  let rep = rep - 1
+  	endwhile
+  	" update rep(eat) count
+  	let rep = rep - 1
+  	if rep <= 0
+  	  " terminate loop if at end-of-block
+  	  break
+  	endif
+  	" prepare for next line
+  	norm! jma
+  	let aline = line("'a")
+  endwhile
+"  call Dret("AlignMaps#CharJoiner")
+endfun
+
+" ---------------------------------------------------------------------
+" AlignMaps#Equals: supports \t= and \T= {{{2
+fun! AlignMaps#Equals() range
+"  call Dfunc("AlignMaps#Equals()")
+  'a,'zs/\s\+\([*/+\-%|&\~^]\==\)/ \1/e
+  'a,'zs@ \+\([*/+\-%|&\~^]\)=@\1=@ge
+  'a,'zs/==/\="\<Char-0x0f>\<Char-0x0f>"/ge
+  'a,'zs/\([!<>:]\)=/\=submatch(1)."\<Char-0x0f>"/ge
+  norm g'zk
+  AlignCtrl mIp1P1=l =
+  AlignCtrl g =
+  'a,'z-1Align
+  'a,'z-1s@\([*/+\-%|&\~^!=]\)\( \+\)=@\2\1=@ge
+  'a,'z-1s/\( \+\);/;\1/ge
+  if &ft == "c" || &ft == "cpp"
+"   call Decho("exception for ".&ft)
+   'a,'z-1v/^\s*\/[*/]/s/\/[*/]/@&@/e
+   'a,'z-1v/^\s*\/[*/]/s/\*\//@&/e
+   if exists("g:mapleader")
+    exe "norm 'zk"
+    call AlignMaps#StdAlign(1)
+   else
+    exe "norm 'zk"
+    call AlignMaps#StdAlign(1)
+   endif
+   'y,'zs/^\(\s*\) @/\1/e
+  endif
+  'a,'z-1s/\%x0f/=/ge
+  'y,'zs/ @//eg
+"  call Dret("AlignMaps#Equals")
+endfun
+
+" ---------------------------------------------------------------------
+" AlignMaps#Afnc: useful for splitting one-line function beginnings {{{2
+"            into one line per argument format
+fun! AlignMaps#Afnc()
+"  call Dfunc("AlignMaps#Afnc()")
+
+  " keep display quiet
+  let chkeep = &ch
+  let gdkeep = &gd
+  let vekeep = &ve
+  set ch=2 nogd ve=
+
+  " will use marks y,z ; save current values
+  let mykeep = SaveMark("'y")
+  let mzkeep = SaveMark("'z")
+
+  " Find beginning of function -- be careful to skip over comments
+  let cmmntid  = synIDtrans(hlID("Comment"))
+  let stringid = synIDtrans(hlID("String"))
+  exe "norm! ]]"
+  while search(")","bW") != 0
+"   call Decho("line=".line(".")." col=".col("."))
+   let parenid= synIDtrans(synID(line("."),col("."),1))
+   if parenid != cmmntid && parenid != stringid
+   	break
+   endif
+  endwhile
+  norm! %my
+  s/(\s*\(\S\)/(\r  \1/e
+  exe "norm! `y%"
+  s/)\s*\(\/[*/]\)/)\r\1/e
+  exe "norm! `y%mz"
+  'y,'zs/\s\+$//e
+  'y,'zs/^\s\+//e
+  'y+1,'zs/^/  /
+
+  " insert newline after every comma only one parenthesis deep
+  sil! exe "norm! `y\<right>h"
+  let parens   = 1
+  let cmmnt    = 0
+  let cmmntline= -1
+  while parens >= 1
+"   call Decho("parens=".parens." @a=".@a)
+   exe 'norm! ma "ay`a '
+   if @a == "("
+    let parens= parens + 1
+   elseif @a == ")"
+    let parens= parens - 1
+
+   " comment bypass:  /* ... */  or //...
+   elseif cmmnt == 0 && @a == '/'
+    let cmmnt= 1
+   elseif cmmnt == 1
+	if @a == '/'
+	 let cmmnt    = 2   " //...
+	 let cmmntline= line(".")
+	elseif @a == '*'
+	 let cmmnt= 3   " /*...
+	else
+	 let cmmnt= 0
+	endif
+   elseif cmmnt == 2 && line(".") != cmmntline
+	let cmmnt    = 0
+	let cmmntline= -1
+   elseif cmmnt == 3 && @a == '*'
+	let cmmnt= 4
+   elseif cmmnt == 4
+	if @a == '/'
+	 let cmmnt= 0   " ...*/
+	elseif @a != '*'
+	 let cmmnt= 3
+	endif
+
+   elseif @a == "," && parens == 1 && cmmnt == 0
+	exe "norm! i\<CR>\<Esc>"
+   endif
+  endwhile
+  norm! `y%mz%
+  sil! 'y,'zg/^\s*$/d
+
+  " perform substitutes to mark fields for Align
+  sil! 'y+1,'zv/^\//s/^\s\+\(\S\)/  \1/e
+  sil! 'y+1,'zv/^\//s/\(\S\)\s\+/\1 /eg
+  sil! 'y+1,'zv/^\//s/\* \+/*/ge
+  sil! 'y+1,'zv/^\//s/\w\zs\s*\*/ */ge
+  "                                                 func
+  "                    ws  <- declaration   ->    <-ptr  ->   <-var->    <-[array][]    ->   <-glop->      <-end->
+  sil! 'y+1,'zv/^\//s/^\s*\(\(\K\k*\s*\)\+\)\s\+\([(*]*\)\s*\(\K\k*\)\s*\(\(\[.\{-}]\)*\)\s*\(.\{-}\)\=\s*\([,)]\)\s*$/  \1@#\3@\4\5@\7\8/e
+  sil! 'y+1,'z+1g/^\s*\/[*/]/norm! kJ
+  sil! 'y+1,'z+1s%/[*/]%@&@%ge
+  sil! 'y+1,'z+1s%*/%@&%ge
+  AlignCtrl mIp0P0=l @
+  sil! 'y+1,'zAlign
+  sil! 'y,'zs%@\(/[*/]\)@%\t\1 %e
+  sil! 'y,'zs%@\*/% */%e
+  sil! 'y,'zs/@\([,)]\)/\1/
+  sil! 'y,'zs/@/ /
+  AlignCtrl mIlrp0P0= # @
+  sil! 'y+1,'zAlign
+  sil! 'y+1,'zs/#/ /
+  sil! 'y+1,'zs/@//
+  sil! 'y+1,'zs/\(\s\+\)\([,)]\)/\2\1/e
+
+  " Restore
+  call RestoreMark(mykeep)
+  call RestoreMark(mzkeep)
+  let &ch= chkeep
+  let &gd= gdkeep
+  let &ve= vekeep
+
+"  call Dret("AlignMaps#Afnc")
+endfun
+
+" ---------------------------------------------------------------------
+"  AlignMaps#FixMultiDec: converts a   type arg,arg,arg;   line to multiple lines {{{2
+fun! AlignMaps#FixMultiDec()
+"  call Dfunc("AlignMaps#FixMultiDec()")
+
+  " save register x
+  let xkeep   = @x
+  let curline = getline(".")
+"  call Decho("curline<".curline.">")
+
+  " Get the type.  I'm assuming one type per line (ie.  int x; double y;   on one line will not be handled properly)
+  let @x=substitute(curline,'^\(\s*[a-zA-Z_ \t][a-zA-Z0-9_ \t]*\)\s\+[(*]*\h.*$','\1','')
+"  call Decho("@x<".@x.">")
+
+  " transform line
+  exe 's/,/;\r'.@x.' /ge'
+
+  "restore register x
+  let @x= xkeep
+
+"  call Dret("AlignMaps#FixMultiDec : my=".line("'y")." mz=".line("'z"))
+endfun
+
+" ---------------------------------------------------------------------
+"  Restore: {{{1
+let &cpo= s:keepcpo
+unlet s:keepcpo
+" vim: ts=4 fdm=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_black.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 18231)
@@ -0,0 +1,86 @@
+" issm_black color scheme
+" table http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
+
+"Set up coloring
+hi clear
+if exists("syntax_on")
+  syntax reset
+endif
+syntax on
+let colors_name = "issm_black"
+
+"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        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       ctermfg=0  ctermbg=87   cterm=BOLD
+if version >= 700 " Vim 7.x specific colors
+  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      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 " == & 
+
+"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/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_white.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 18231)
@@ -0,0 +1,86 @@
+" issm_white scheme
+" table http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
+
+"Set up coloring
+hi clear
+if exists("syntax_on")
+  syntax reset
+endif
+syntax on
+let colors_name = "issm_black"
+
+"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
+
+"                forground    background   style (reverse,bold,..)
+" General colors
+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       ctermfg=0  ctermbg=33   cterm=BOLD
+if version >= 700 " Vim 7.x specific colors
+  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      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 " == & 
+
+"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/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/Align.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/Align.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/Align.txt	(revision 18231)
@@ -0,0 +1,1469 @@
+*align.txt*	The Alignment Tool			Mar 04, 2009
+
+Author:    Charles E. Campbell, Jr.  <NdrOchip@ScampbellPfamily.AbizM>
+           (remove NOSPAM from Campbell's email first)
+Copyright: (c) 2004-2008 by Charles E. Campbell, Jr.	*Align-copyright*
+           The VIM LICENSE applies to Align.vim, AlignMaps.vim, and Align.txt
+           (see |copyright|) except use "Align and AlignMaps" instead of "Vim"
+           NO WARRANTY, EXPRESS OR IMPLIED.  USE AT-YOUR-OWN-RISK.
+
+==============================================================================
+1. Contents					*align* *align-contents* {{{1
+
+	1. Contents.................: |align-contents|
+	2. Alignment Manual.........: |align-manual|
+	3. Alignment Usage..........: |align-usage|
+	   Alignment Concepts.......: |align-concepts|
+	   Alignment Commands.......: |align-commands|
+	   Alignment Control........: |align-control|
+	     Separators.............: |alignctrl-separators|
+	     Initial Whitespace.....: |alignctrl-w| |alignctrl-W| |alignctrl-I|
+	     Justification..........: |alignctrl-l| |alignctrl-r| |alignctrl-c|
+	     Justification Control..: |alignctrl--| |alignctrl-+| |alignctrl-:|
+	     Cyclic/Sequential......: |alignctrl-=| |alignctrl-C|
+	     Separator Justification: |alignctrl-<| |alignctrl->| |alignctrl-||
+	     Line (de)Selection.....: |alignctrl-g| |alignctrl-v|
+	     Temporary Settings.....: |alignctrl-m|
+	     Padding................: |alignctrl-p| |alignctrl-P|
+	     Current Options........: |alignctrl-settings| |alignctrl-|
+	   Alignment................: |align-align|
+	4. Alignment Maps...........: |align-maps|
+	     \a,....................: |alignmap-a,|
+	     \a?....................: |alignmap-a?|
+	     \a<....................: |alignmap-a<|
+	     \abox..................: |alignmap-abox|
+	     \acom..................: |alignmap-acom|
+	     \anum..................: |alignmap-anum|
+	     \ascom.................: |alignmap-ascom|
+	     \adec..................: |alignmap-adec|
+	     \adef..................: |alignmap-adef|
+	     \afnc..................: |alignmap-afnc|
+	     \adcom.................: |alignmap-adcom|
+	     \aocom.................: |alignmap-aocom|
+	     \tsp...................: |alignmap-tsp|
+	     \tsq...................: |alignmap-tsq|
+	     \tt....................: |alignmap-tt|
+	     \t=....................: |alignmap-t=|
+	     \T=....................: |alignmap-T=|
+	     \Htd...................: |alignmap-Htd|
+	5. Alignment Tool History...: |align-history|
+
+==============================================================================
+2. Align Manual			*alignman* *alignmanual* *align-manual* {{{1
+
+	Align comes as a vimball; simply typing >
+		vim Align.vba.gz
+		:so %
+<	should put its components where they belong.  The components are: >
+		.vim/plugin/AlignPlugin.vim
+		.vim/plugin/AlignMapsPlugin.vim
+		.vim/plugin/cecutil.vim
+		.vim/autoload/Align.vim
+		.vim/autoload/AlignMaps.vim
+		.vim/doc/Align.txt
+<	To see a user's guide, see |align-userguide|
+	To see examples, see |alignctrl| and |alignmaps|
+>
+/=============+=========+=====================================================\
+||            \ Default/                                                     ||
+||  Commands   \ Value/                Explanation                           ||
+||              |    |                                                       ||
+++==============+====+=======================================================++
+||  AlignCtrl   |    |  =Clrc-+:pPIWw [..list-of-separator-patterns..]       ||
+||              |    +-------------------------------------------------------+|
+||              |    |  may be called as a command or as a function:         ||
+||              |    |  :AlignCtrl =lp0P0W & \\                              ||
+||              |    |  :call Align#AlignCtrl('=lp0P0W','&','\\')            ||
+||              |    |                                                       ||
+||              |    +-------------------------------------------------------++
+||   1st arg    |  = | =  all separator patterns are equivalent and are      ||
+||              |    |    simultaneously active. Patterns are |regexp|.      ||
+||              |    | C  cycle through separator patterns.  Patterns are    ||
+||              |    |    |regexp| and are active sequentially.              ||
+||              |    |                                                       ||
+||              |  < | <  left justify separator   Separators are justified, ||
+||              |    | >  right justify separator  too.  Separator styles    ||
+||              |    | |  center separator         are cyclic.               ||
+||              |    |                                                       ||
+||              |  l | l  left justify   Justification styles are always     ||
+||              |    | r  right justify  cyclic (ie. lrc would mean left j., ||
+||              |    | c  center         then right j., then center, repeat. ||
+||              |    | -  skip this separator                                ||
+||              |    | +  re-use last justification method                   ||
+||              |    | :  treat rest of text as a field                      ||
+||              |    |                                                       ||
+||              | p1 | p### pad separator on left  by # blanks               ||
+||              | P1 | P### pad separator on right by # blanks               ||
+||              |    |                                                       ||
+||              |  I | I  preserve and apply first line's leading white      ||
+||              |    |    space to all lines                                 ||
+||              |    | W  preserve leading white space on every line, even   ||
+||              |    |    if it varies from line to line                     ||
+||              |    | w  don't preserve leading white space                 ||
+||              |    |                                                       ||
+||              |    | g  second argument is a selection pattern -- only     ||
+||              |    |    align on lines that have a match  (inspired by     ||
+||              |    |    :g/selection pattern/command)                      ||
+||              |    | v  second argument is a selection pattern -- only     ||
+||              |    |    align on lines that _don't_ have a match (inspired ||
+||              |    |    by :v/selection pattern/command)                   ||
+||              |    |                                                       ||
+||              |    | m  Map support: AlignCtrl will immediately do an      ||
+||              |    |    AlignPush() and the next call to Align() will do   ||
+||              |    |    an AlignPop at the end.  This feature allows maps  ||
+||              |    |    to preserve user settings.                         ||
+||              |    |                                                       ||
+||              |    | default                                               ||
+||              |    |    AlignCtrl default                                  ||
+||              |    |    will clear the AlignCtrl                           ||
+||              |    |    stack & set the default:  AlignCtrl "Ilp1P1=" '='  ||
+||              |    |                                                       ||
+||              +----+-------------------------------------------------------+|
+||  More args   |  More arguments are interpreted as describing separators   ||
+||              +------------------------------------------------------------+|
+||   No args    |  AlignCtrl will display its current settings               ||
+||==============+============================================================+|
+||[range]Align  |   [..list-of-separators..]                                 ||
+||[range]Align! |   [AlignCtrl settings] [..list-of-separators..]            ||
+||              +------------------------------------------------------------+|
+||              |  Aligns text over the given range.  The range may be       ||
+||              |  selected via visual mode (v, V, or ctrl-v) or via         ||
+||              |  the command line.  The Align operation may be invoked     ||
+||              |  as a command or as a function; as a function, the first   ||
+||              |  argument is 0=separators only, 1=AlignCtrl option string  ||
+||              |  followed by a list of separators.                         ||
+||              |   :[range]Align                                            ||
+||              |   :[range]Align [list of separators]                       ||
+||              |   :[range]call Align#Align(0)                              ||
+||              |   :[range]call Align#Align(0,"list","of","separators",...) ||
+\=============================================================================/
+
+==============================================================================
+3. Alignment Usage	*alignusage* *align-usage* *align-userguide* {{{1
+
+
+ALIGNMENT CONCEPTS			*align-concept* *align-concepts* {{{2
+
+	The typical text to be aligned is considered to be:
+
+		* composed of two or more fields
+		* separated by one or more separator pattern(s):
+		* two or more lines
+>
+		ws field ws separator ws field ws separator ...
+		ws field ws separator ws field ws separator ...
+<
+	where "ws" stands for "white space" such as blanks and/or tabs,
+	and "fields" are arbitrary text.  For example, consider >
+
+		x= y= z= 3;
+		xx= yy= zz= 4;
+		zzz= yyy= zzz= 5;
+		a= b= c= 3;
+<
+	Assume that it is desired to line up all the "=" signs; these,
+	then, are the separators.  The fields are composed of all the
+	alphameric text.  Assuming they lie on lines 1-4, one may align
+	those "=" signs with: >
+		:AlignCtrl l
+		:1,4Align =
+<	The result is: >
+		x   = y   = z   = 3;
+		xx  = yy  = zz  = 4;
+		zzz = yyy = zzz = 5;
+		a   = b   = c   = 3;
+
+<	Note how each "=" sign is surrounded by a single space; the
+	default padding is p1P1 (p1 means one space before the separator,
+	and P1 means one space after it).  If you wish to change the
+	padding, say to no padding, use  (see |alignctrl-p|) >
+		:AlignCtrl lp0P0
+
+<	Next, note how each field is left justified; that's what the "l"
+	(a small letter "ell") does.  If right-justification of the fields
+	had been desired, an "r" could've been used: >
+		:AlignCtrl r
+<	yielding >
+		  x =   y =   z = 3;
+		 xx =  yy =  zz = 4;
+		zzz = yyy = zzz = 5;
+		  a =   b =   c = 3;
+<	There are many more options available for field justification: see
+	|alignctrl-c| and |alignctrl--|.
+
+	Separators, although commonly only one character long, are actually
+	specified by regular expressions (see |regexp|), and one may left
+	justify, right justify, or center them, too (see |alignctrl-<|).
+
+	Assume that for some reason a left-right-left-right-... justification
+	sequence was wished.  This wish is simply achieved with >
+		:AlignCtrl lr
+		:1,4Align =
+<	because the justification commands are considered to be "cylic"; ie.
+	lr is the same as lrlrlrlrlrlrlr...
+
+	There's a lot more discussed under |alignctrl|; hopefully the examples
+	there will help, too.
+
+
+ALIGNMENT COMMANDS			*align-command* *align-commands* {{{2
+
+        The <Align.vim> script includes two primary commands and two
+	minor commands:
+
+	  AlignCtrl : this command/function sets up alignment options
+	              which persist until changed for later Align calls.
+		      It controls such things as: how to specify field
+		      separators, initial white space, padding about
+		      separators, left/right/center justification, etc. >
+			ex.  AlignCtrl wp0P1
+                             Interpretation: during subsequent alignment
+			     operations, preserve each line's initial
+			     whitespace.  Use no padding before separators
+			     but provide one padding space after separators.
+<
+	  Align     : this command/function operates on the range given it to
+		      align text based on one or more separator patterns.  The
+		      patterns may be provided via AlignCtrl or via Align
+		      itself. >
+
+			ex. :%Align ,
+			    Interpretation: align all commas over the entire
+			    file.
+<		      The :Align! format permits alignment control commands
+		      to precede the alignment patterns. >
+			ex. :%Align! p2P2 =
+<		      This will align all "=" in the file with two padding
+		      spaces on both sides of each "=" sign.
+
+		      NOTE ON USING PATTERNS WITH ALIGN:~
+		      Align and AlignCtrl use |<q-args>| to obtain their
+		      input patterns and they use an internal function to
+		      split arguments at whitespace unless inside "..."s.
+		      One may escape characters inside a double-quote string
+		      by preceding such characters with a backslash.
+
+	  AlignPush : this command/function pushes the current AlignCtrl
+	              state onto an internal stack. >
+			ex. :AlignPush
+			    Interpretation: save the current AlignCtrl
+			    settings, whatever they may be.  They'll
+			    also remain as the current settings until
+			    AlignCtrl is used to change them.
+<
+	  AlignPop  : this command/function pops the current AlignCtrl
+	              state from an internal stack. >
+			ex. :AlignPop
+			    Interpretation: presumably AlignPush was
+			    used (at least once) previously; this command
+			    restores the AlignCtrl settings when AlignPush
+			    was last used.
+<	              Also see |alignctrl-m| for a way to automatically do
+	              an AlignPop after an Align (primarily this is for maps).
+
+ALIGNMENT OPTIONS			*align-option* *align-options* {{{2
+    *align-utf8* *align-utf* *align-codepoint* *align-strlen* *align-multibyte*
+
+	For those of you who are using 2-byte (or more) characters such as are
+	available with utf-8, Align now provides a special option which you
+	may choose based upon your needs:
+
+	Use Built-in strlen() ~
+>
+			let g:Align_xstrlen= 0
+
+<       This is the fastest method, but it doesn't handle multibyte characters
+	well.  It is the default for:
+
+	  enc=latin1
+	  vim compiled without multi-byte support
+	  $LANG is en_US.UTF-8 (assuming USA english)
+
+	Number of codepoints (Latin a + combining circumflex is two codepoints)~
+>
+			let g:Align_xstrlen= 1              (default)
+<
+	Number of spacing codepoints (Latin a + combining circumflex is one~
+	spacing codepoint; a hard tab is one; wide and narrow CJK are one~
+	each; etc.)~
+>
+			let g:Align_xstrlen= 2
+<
+	Virtual length (counting, for instance, tabs as anything between 1 and~
+	'tabstop', wide CJK as 2 rather than 1, Arabic alif as zero when~
+	immediately preceded by lam, one otherwise, etc.)~
+>
+			let g:Align_xstrlen= 3
+<
+	By putting one of these settings into your <.vimrc>, Align will use an
+	internal (interpreted) function to determine a string's length instead
+	of the Vim's built-in |strlen()| function.  Since the function is
+	interpreted, Align will run a bit slower but will handle such strings
+	correctly.  The last setting (g:Align_xstrlen= 3) probably will run
+	the slowest but be the most accurate.  (thanks to Tony Mechelynck for
+	these)
+
+
+ALIGNMENT CONTROL				*alignctrl* *align-control* {{{2
+
+	This command doesn't do the alignment operation itself; instead, it
+	controls subsequent alignment operation(s).
+
+	The first argument to AlignCtrl is a string which may contain one or
+	more alignment control settings.  Most of the settings are specified
+	by single letters; the exceptions are the p# and P# commands which
+	interpret a digit following the p or P as specifying padding about the
+	separator.
+
+	The typical text line is considered to be composed of two or more
+	fields separated by one or more separator pattern(s): >
+
+		ws field ws separator ws field ws separator ...
+<
+	where "ws" stands for "white space" such as blanks and/or tabs.
+
+	
+	SEPARATORS				*alignctrl-separators* {{{3
+
+	As a result, separators may not have white space (tabs or blanks) on
+	their outsides (ie.  ":  :" is fine as a separator, but " :: " is
+	not).  Usually such separators are not needed, although a map has been
+	provided which works around this limitation and aligns on whitespace
+	(see |alignmap-tsp|).
+
+	However, if you really need to have separators with leading or
+	trailing whitespace, consider handling them by performing a substitute
+	first (ie. s/  ::  /@/g), do the alignment on the temporary pattern
+	(ie. @), and then perform a substitute to revert the separators back
+	to their desired condition (ie. s/@/  ::  /g).
+
+	The Align#Align() function will first convert tabs over the region into
+	spaces and then apply alignment control.  Except for initial white
+	space, white space surrounding the fields is ignored.  One has three
+	options just for handling initial white space:
+
+
+	--- 						*alignctrl-w*
+	wWI 	INITIAL WHITE SPACE			*alignctrl-W* {{{3
+	--- 						*alignctrl-I*
+		w : ignore all selected lines' initial white space
+		W : retain all selected lines' initial white space
+		I : retain only the first line's initial white space and
+		    re-use it for subsequent lines
+
+	Example: Leading white space options: >
+                         +---------------+-------------------+-----------------+
+	                 |AlignCtrl w= :=|  AlignCtrl W= :=  | AlignCtrl I= := |
+      +------------------+---------------+-------------------+-----------------+
+      |     Original     |   w option    |     W option      |     I option    |
+      +------------------+---------------+-------------------+-----------------+
+      |   a := baaa      |a     := baaa  |   a      : = baaa |   a     := baaa |
+      | caaaa := deeee   |caaaa := deeee | caaaa    : = deeee|   caaaa := deeee|
+      |       ee := f    |ee    := f     |       ee : = f    |   ee    := f    |
+      +------------------+---------------+-------------------+-----------------+
+<
+	The original has at least one leading white space on every line.
+	Using Align with w eliminated each line's leading white space.
+	Using Align with W preserved  each line's leading white space.
+	Using Align with I applied the first line's leading white space
+	                   (three spaces) to each line.
+
+
+	------						*alignctrl-l*
+	lrc-+:	FIELD JUSTIFICATION			*alignctrl-r* {{{3
+	------						*alignctrl-c*
+
+	With "lrc", the fields will be left-justified, right-justified, or
+	centered as indicated by the justification specifiers (lrc).  The
+	"lrc" options are re-used by cycling through them as needed:
+
+		l   means llllll....
+		r   means rrrrrr....
+		lr  means lrlrlr....
+		llr means llrllr....
+
+     Example: Justification options: Align = >
+     +------------+-------------------+-------------------+-------------------+
+     |  Original  |  AlignCtrl l      | AlignCtrl r       | AlignCtrl lr      |
+     +------------+-------------------+-------------------+-------------------+
+     | a=bb=ccc=1 |a   = bb  = ccc = 1|  a =  bb = ccc = 1|a   =  bb = ccc = 1|
+     | ccc=a=bb=2 |ccc = a   = bb  = 2|ccc =   a =  bb = 2|ccc =   a = bb  = 2|
+     | dd=eee=f=3 |dd  = eee = f   = 3| dd = eee =   f = 3|dd  = eee = f   = 3|
+     +------------+-------------------+-------------------+-------------------+
+     | Alignment  |l     l     l     l|  r     r     r   r|l       r   l     r|
+     +------------+-------------------+-------------------+-------------------+
+<
+		AlignCtrl l : The = separator is repeatedly re-used, as the
+			      cycle only consists of one character (the "l").
+			      Every time left-justification is used for fields.
+		AlignCtrl r : The = separator is repeatedly re-used, as the
+			      cycle only consists of one character (the "l").
+			      Every time right-justification is used for fields
+		AlignCtrl lr: Again, the "=" separator is repeatedly re-used,
+			      but the fields are justified alternately between
+			      left and right.
+
+	Even more separator control is available.  With "-+:":
+
+	    - : skip treating the separator as a separator.   *alignctrl--*
+	    + : repeat use of the last "lrc" justification    *alignctrl-+*
+	    : : treat the rest of the line as a single field  *alignctrl-:*
+
+     Example: More justification options:  Align = >
+     +------------+---------------+--------------------+---------------+
+     |  Original  |  AlignCtrl -l | AlignCtrl rl+      | AlignCtrl l:  |
+     +------------+---------------+--------------------+---------------+
+     | a=bb=ccc=1 |a=bb   = ccc=1 |  a = bb  = ccc = 1 |a   = bb=ccc=1 |
+     | ccc=a=bb=2 |ccc=a  = bb=2  |ccc = a   = bb  = 2 |ccc = a=bb=2   |
+     | dd=eee=f=3 |dd=eee = f=3   | dd = eee = f   = 3 |dd  = eee=f=3  |
+     +------------+---------------+--------------------+---------------+
+     | Alignment  |l        l     |  r   l     l     l |l     l        |
+     +------------+---------------+--------------------+---------------+
+<
+	In the first example in "More justification options":
+
+	  The first "=" separator is skipped by the "-" specification,
+	  and so "a=bb", "ccc=a", and "dd=eee" are considered as single fields.
+
+	  The next "=" separator has its (left side) field left-justified.
+	  Due to the cyclic nature of separator patterns, the "-l"
+	  specification is equivalent to "-l-l-l ...".
+
+	  Hence the next specification is a "skip", so "ccc=1", etc are fields.
+
+	In the second example in "More justification options":
+
+	  The first field is right-justified, the second field is left
+	  justified, and all remaining fields repeat the last justification
+	  command (ie. they are left justified, too).
+
+	  Hence rl+ is equivalent to         rlllllllll ...
+	  (whereas plain rl is equivalent to rlrlrlrlrl ... ).
+
+	In the third example in "More justification options":
+
+	  The text following the first separator is treated as a single field.
+
+	Thus using the - and : operators one can apply justification to a
+	single separator.
+
+	ex. 1st separator only:    AlignCtrl l:
+	    2nd separator only:    AlignCtrl -l:
+	    3rd separator only:    AlignCtrl --l:
+	    etc.
+
+
+	---						     *alignctrl-=*
+	=C	CYCLIC VS ALL-ACTIVE SEPARATORS		     *alignctrl-C* {{{3
+	---
+
+	The separators themselves may be considered as equivalent and
+	simultaneously active ("=") or sequentially cycled through ("C").
+	Separators are regular expressions (|regexp|) and are specified as the
+	second, third, etc arguments.  When the separator patterns are
+	equivalent and simultaneously active, there will be one pattern
+	constructed: >
+
+		AlignCtrl ... pat1 pat2 pat3
+		\(pat1\|pat2\|pat3\)
+<
+	Each separator pattern is thus equivalent and simultaneously active.
+	The cyclic separator AlignCtrl option stores a list of patterns, only
+	one of which is active for each field at a time.
+
+	Example: Equivalent/Simultaneously-Active vs Cyclic Separators >
+ +-------------+------------------+---------------------+----------------------+
+ |   Original  | AlignCtrl = = + -| AlignCtrl = =       | AlignCtrl C = + -    |
+ +-------------+------------------+---------------------+----------------------+
+ |a = b + c - d|a = b + c - d     |a = b + c - d        |a = b         + c - d |
+ |x = y = z + 2|x = y = z + 2     |x = y         = z + 2|x = y = z     + 2     |
+ |w = s - t = 0|w = s - t = 0     |w = s - t     = 0    |w = s - t = 0         |
+ +-------------+------------------+---------------------+----------------------+
+<
+	The original is initially aligned with all operators (=+-) being
+	considered as equivalent and simultaneously active field separators.
+	Thus the "AlignCtrl = = + -" example shows no change.
+
+	The second example only accepts the '=' as a field separator;
+	consequently "b + c - d" is now a single field.
+
+	The third example illustrates cyclic field separators and is analyzed
+	in the following illustration: >
+
+	field1 separator field2    separator field3 separator field4
+	   a      =      b             +       c        -       d
+	   x      =      y = z         +       2
+	   w      =      s - t = 0
+<
+	The word "cyclic" is used because the patterns form a cycle of use; in
+	the above case, its = + - = + - = + - = + -...
+
+	Example: Cyclic separators >
+		Label : this is some text discussing ":"s | ex. abc:def:ghi
+		Label : this is some text with a ":" in it | ex. abc:def
+<
+	  apply AlignCtrl lWC : | |
+	        (select lines)Align >
+                Label : this is some text discussing ":"s  | ex. abc:def:ghi
+                Label : this is some text with a ":" in it | ex. abcd:efg
+<
+	In the current example,
+	  : is the first separator        So the first ":"s are aligned
+	  | is the second separator       but subsequent ":"s are not.
+	  | is the third separator        The "|"s are aligned, too.
+	  : is the fourth separator       Since there aren't two bars,
+	  | is the fifth separator        the subsequent potential cycles
+	  | is the sixth separator        don't appear.
+	 ...
+
+	In this case it would probably have been a better idea to have used >
+		AlignCtrl WCl: : |
+<	as that alignment control would guarantee that no more cycling
+	would be used after the vertical bar.
+
+	Example: Cyclic separators
+
+	    Original: >
+		a| b&c | (d|e) & f-g-h
+		aa| bb&cc | (dd|ee) & ff-gg-hh
+		aaa| bbb&ccc | (ddd|eee) & fff-ggg-hhh
+<
+	    AlignCtrl C | | & - >
+		a   | b&c     | (d|e)     & f   - g-h
+		aa  | bb&cc   | (dd|ee)   & ff  - gg-hh
+		aaa | bbb&ccc | (ddd|eee) & fff - ggg-hhh
+<
+	In this example,
+	the first and second separators are "|",
+	the third            separator  is  "&", and
+	the fourth           separator  is  "-",
+
+	(cycling)
+	the fifth and sixth  separators are "|",
+	the seventh          separator  is  "&", and
+	the eighth           separator  is  "-", etc.
+
+	Thus the first "&"s are (not yet) separators, and hence are treated as
+	part of the field.  Ignoring white space for the moment, the AlignCtrl
+	shown here means that Align will work with >
+
+	field | field | field & field - field | field | field & field - ...
+<
+
+	---						*alignctrl-<*
+	<>|	SEPARATOR JUSTIFICATION			*alignctrl->* {{{3
+	---						*alignctrl-|*
+
+	Separators may be of differing lengths as shown in the example below.
+	Hence they too may be justified left, right, or centered.
+	Furthermore, separator justification specifications are cyclic:
+
+		<  means <<<<<...    justify separator(s) to the left
+		>  means >>>>>...    justify separator(s) to the right
+		|  means |||||...    center separator(s)
+
+	Example: Separator Justification: Align -\+ >
+				+-----------------+
+				|    Original     |
+				+-----------------+
+				| a - bbb - c     |
+				| aa -- bb -- ccc |
+				| aaa --- b --- cc|
+	+---------------------+-+-----------------+-+---------------------+
+	|     AlignCtrl <     |     AlignCtrl >     |     AlignCtrl |     |
+	+---------------------+---------------------+---------------------+
+	| a   -   bbb -   c   | a     - bbb   - c   | a    -  bbb  -  c   |
+	| aa  --  bb  --  ccc | aa   -- bb   -- ccc | aa  --  bb  --  ccc |
+	| aaa --- b   --- cc  | aaa --- b   --- cc  | aaa --- b   --- cc  |
+	+---------------------+---------------------+---------------------+
+<
+
+	---						*alignctrl-g*
+	gv	SELECTIVE APPLICATION			*alignctrl-v* {{{3
+	---
+
+
+	These two options provide a way to select (g) or to deselect (v) lines
+	based on a pattern.  Ideally :g/pat/Align  would work; unfortunately
+	it results in Align#Align() being called on each line satisfying the
+	pattern separately. >
+
+		AlignCtrl g pattern
+<
+	Align will only consider those lines which have the given pattern. >
+
+		AlignCtrl v pattern
+<
+	Align will only consider those lines without the given pattern.  As an
+	example of use, consider the following example: >
+
+				           :AlignCtrl v ^\s*/\*
+	  Original          :Align =       :Align =
+	+----------------+------------------+----------------+
+	|one= 2;         |one     = 2;      |one   = 2;      |
+	|three= 4;       |three   = 4;      |three = 4;      |
+	|/* skip=this */ |/* skip = this */ |/* skip=this */ |
+	|five= 6;        |five    = 6;      |five  = 6;      |
+	+----------------+------------------+----------------+
+<
+	The first "Align =" aligned with all "="s, including that one in the
+	"skip=this" comment.
+
+	The second "Align =" had a AlignCtrl v-pattern which caused it to skip
+	(ignore) the "skip=this" line when aligning.
+	
+	To remove AlignCtrl's g and v patterns, use (as appropriate) >
+
+		AlignCtrl g
+		AlignCtrl v
+<
+	To see what g/v patterns are currently active, just use the reporting
+	capability of an unadorned call to AlignCtrl: >
+
+		AlignCtrl
+<
+
+	---
+	 m	MAP SUPPORT				*alignctrl-m* {{{3
+	---
+
+	This option primarily supports the development of maps.  The
+	Align#AlignCtrl() call will first do an Align#AlignPush() (ie. retain
+	current alignment control settings).  The next Align#Align() will, in
+	addition to its alignment job, finish up with an Align#AlignPop().
+	Thus the Align#AlignCtrl settings that follow the "m" are only
+	temporarily in effect for just the next Align#Align().
+
+
+	---
+	p###						*alignctrl-p*
+	P###	PADDING					*alignctrl-P* {{{3
+	---
+
+	These two options control pre-padding and post-padding with blanks
+	about the separator.  One may pad separators with zero to nine spaces;
+	the padding number(s) is/are treated as a cyclic parameter.  Thus one
+	may specify padding separately for each field or re-use a padding
+	pattern. >
+
+	Example:          AlignCtrl p102P0
+	+---------+----------------------------------+
+	| Original| a=b=c=d=e=f=g=h=1                |
+        | Align = | a =b=c  =d =e=f  =g =h=1         |
+        +---------+----------------------------------+
+	| prepad  |   1 0   2  1 0   2  1 0          |
+        +---------+----------------------------------+
+<
+	This example will cause Align to:
+
+		pre-pad the first  "=" with a single blank,
+		pre-pad the second "=" with no blanks,
+		pre-pad the third  "=" with two blanks,
+		pre-pad the fourth "=" with a single blank,
+		pre-pad the fifth  "=" with no blanks,
+		pre-pad the sixth  "=" with two blanks,
+	        etc.
+
+	---------------				*alignctrl-settings*
+	No option given		DISPLAY STATUS	*alignctrl-*		{{{3
+	---------------				*alignctrl-no-option*
+
+	AlignCtrl, when called with no arguments, will display the current
+	alignment control settings.  A typical display is shown below: >
+
+		AlignCtrl<=> qty=1 AlignStyle<l> Padding<1|1>
+		Pat1<\(=\)>
+<
+	Interpreting, this means that the separator patterns are all
+	equivalent; in this case, there's only one (qty=1).  Fields will be
+	padded on the right with spaces (left justification), and separators
+	will be padded on each side with a single space.
+
+	To change one of these items, see:
+
+	  AlignCtrl......|alignctrl|
+	  qty............|align-concept|
+	  AlignStyle.....|alignctrl--| |alignctrl-+| |alignctrl-:||alignctrl-c|
+	  Padding........|alignctrl-p| |alignctrl-P|
+
+	One may get a string which can be fed back into AlignCtrl: >
+
+		:let alignctrl= Align#AlignCtrl()
+<
+	This form will put a string describing the current AlignCtrl options,
+	except for the "g" and "v" patterns, into a variable.  The
+	Align#AlignCtrl() function will still echo its settings, however.  One
+	can feed any non-supported "option" to AlignCtrl() to prevent this,
+	however: >
+
+		:let alignctrl= Align#AlignCtrl("d")
+<
+
+ALIGNMENT						*align-align* {{{2
+
+	Once the alignment control has been determined, the user specifies a
+	range of lines for the Align command/function to do its thing.
+	Alignment is often done on a line-range basis, but one may also
+	restrict alignment to a visual block using ctrl-v.  For any visual
+	mode, one types the colon (:) and then "Align".  One may, of course,
+	specify a range of lines: >
+
+		:[range]Align [list-of-separators]
+<
+	where the |:range| is the usual Vim-powered set of possibilities; the
+	list of separators is the same as the AlignCtrl capability.  There is
+	only one list of separators, but either AlignCtrl or Align can be used
+	to specify that list.
+
+	An alternative form of the Align command can handle both alignment
+	control and the separator list: >
+
+		:[range]Align! [alignment-control-string] [list-of-separators]
+<
+	The alignment control string will be applied only for this particular
+	application of Align (it uses |alignctrl-m|).  The "g pattern" and
+	"v pattern" alignment controls (see |alignctrl-g| and |alignctrl-v|)
+	are also available via this form of the Align command.
+
+	Align makes two passes over the text to be aligned.  The first pass
+	determines how many fields there are and determines the maximum sizes
+	of each field; these sizes are then stored in a vector.  The second
+	pass pads the field (left/right/centered as specified) to bring its
+	length up to the maximum size of the field.  Then the separator and
+	its AlignCtrl-specified padding is appended.
+
+		Pseudo-Code:~
+		 During pass 1
+		 | For all fields in the current line
+		 || Determine current separator
+		 || Examine field specified by current separator
+		 || Determine length of field and save if largest thus far
+		 Initialize newline based on initial whitespace option (wWI)
+		 During pass 2
+		 | For all fields in current line
+		 || Determine current separator
+		 || Extract field specified by current separator
+		 || Prepend/append padding as specified by AlignCtrl
+		 || (right/left/center)-justify to fit field into max-size field
+		 || Append separator with AlignCtrl-specified separator padding
+		 || Delete current line, install newly aligned line
+
+	The g and v AlignCtrl patterns cause the passes not to consider lines
+	for alignment, either by requiring that the g-pattern be present or
+	that the v-pattern not be present.
+
+	The whitespace on either side of a separator is ignored.
+
+
+==============================================================================
+4. Alignment Maps				*alignmaps* *align-maps* {{{1
+
+	There are a number of maps using Align#AlignCtrl() and Align#Align()
+	in the <AlignMapsPlugin.vim> file.  This file may also be put into the
+	plugins subdirectory.  Since AlignCtrl and Align supercede textab and
+	its <ttalign.vim> file, the maps either have a leading "t" (for
+	"textab") or the more complicated ones an "a" (for "alignment") for
+	backwards compatibility.
+
+	The maps are shown below with a leading backslash (\).  Actually, the
+	<Leader> construct is used (see |mapleader|), so the maps' leading
+	kick-off character is easily customized.
+
+	Furthermore, all AlignMapsPlugin.vim maps use the <Plug> construct (see
+	|<Plug>|and |usr_41.txt|).  Hence, if one wishes to override the
+	mapping entirely, one may do that, too.  As an example: >
+		map <Leader>ACOM	<Plug>AM_acom
+<	would have \ACOM do what \acom previously did (assuming that the
+	mapleader has been left at its default value of a backslash).
+
+	  \a,   : useful for breaking up comma-separated
+	          declarations prior to \adec			|alignmap-a,|
+	  \a(   : aligns ( and , (useful for prototypes)        *alignmap-a(*
+	  \a?   : aligns (...)? ...:... expressions on ? and :	|alignmap-a?|
+	  \a<   : aligns << and >> for c++			|alignmap-a<|
+	  \a=   : aligns := assignments   			|alignmap-a=|
+	  \abox : draw a C-style comment box around text lines	|alignmap-abox|
+	  \acom : useful for aligning comments			|alignmap-acom|
+	  \adcom: useful for aligning comments in declarations  |alignmap-adcom|
+	  \anum : useful for aligning numbers 			|alignmap-anum|
+	          NOTE: For the visual-mode use of \anum, <vis.vim> is needed!
+		    See http://mysite.verizon.net/astronaut/vim/index.html#VIS
+	  \aenum: align a European-style number			|alignmap-anum|
+	  \aunum: align a USA-style number			|alignmap-anum|
+	  \adec : useful for aligning declarations		|alignmap-adec|
+	  \adef : useful for aligning definitions		|alignmap-adef|
+	  \afnc : useful for aligning ansi-c style functions'
+	          argument lists				|alignmap-afnc|
+	  \adcom: a variant of \acom, restricted to comment     |alignmap-adcom|
+	          containing lines only, but also only for
+		  those which don't begin with a comment.
+		  Good for certain declaration styles.
+	  \aocom: a variant of \acom, restricted to comment     |alignmap-aocom|
+	          containing lines only
+	  \tab  : align a table based on tabs			*alignmap-tab*
+	          (converts to spaces)
+	  \tml  : useful for aligning the trailing backslashes	|alignmap-tml|
+	          used to continue lines (shell programming, etc)
+	  \tsp  : use Align to make a table separated by blanks	|alignmap-tsp|
+	          (left justified)
+	  \ts,  : like \t, but swaps whitespace on the right of *alignmap-ts,*
+	          the commas to their left
+	  \ts:  : like \t: but swaps whitespace on the right of *alignmap-ts:*
+	          the colons to their left
+	  \ts<  : like \t< but swaps whitespace on the right of *alignmap-ts<*
+	          the less-than signs to their left
+	  \ts=  : like \t= but swaps whitespace on the right of *alignmap-ts=*
+	          the equals signs to their left
+	  \Tsp  : use Align to make a table separated by blanks	|alignmap-Tsp|
+	          (right justified)
+	  \tsq  : use Align to make a table separated by blanks	|alignmap-tsq|
+	          (left justified) -- "strings" are not split up
+	  \tt   : useful for aligning LaTeX tabular tables	|alignmap-tt|
+	  \Htd  : tabularizes html tables:			|alignmap-Htd|
+	          <TR><TD> ...field... </TD><TD> ...field... </TD></TR>
+
+		  *alignmap-t|* *alignmap-t#* *alignmap-t,* *alignmap-t:*
+		  *alignmap-t;* *alignmap-t<* *alignmap-t?* *alignmap-t~*
+		  *alignmap-m=*
+	  \tx   : make a left-justified  alignment on
+	          character "x" where "x" is: ,:<=@|#		|alignmap-t=|
+	  \Tx   : make a right-justified alignment on
+	          character "x" where "x" is: ,:<=@#		|alignmap-T=|
+	  \m=   : like \t= but aligns with %... style comments
+
+	The leading backslash is actually <leader> (see |mapleader| for how to
+	customize the leader to be whatever you like).  These maps use the
+	<Align.vim> package and are defined in the <AlignMaps.vim> file.
+	Although the maps use AlignCtrl options, they typically use the "m"
+	option which pushes the options (AlignPush).  The associated Align
+	call which follows will then AlignPop the user's original options
+	back.
+
+	ALIGNMENT MAP USE WITH MARK AND MOVE~
+	In the examples below, one may select the text with a "ma" at the
+	first line, move to the last line, then execute the map.
+
+	ALIGNMENT MAP USE WITH VISUAL MODE~
+	Alternatively, one may select the text with the "V" visual mode
+	command.
+
+	ALIGNMENT MAP USE WITH MENUS~
+	One may use the mark-and-move style (ma, move, use the menu) or
+	the visual mode style (use the V visual mode, move, then select
+	the alignment map with menu selection).  The alignment map menu
+	items are under DrChip.AlignMaps .
+
+	One may even change the top level menu name to whatever is wished; by
+	default, its >
+		let g:DrChipTopLvlMenu= "DrChip."
+<	If you set the variable to the empty string (""), then no menu items
+	will be produced.  Of course, one must have a vim with +menu, the gui
+	must be running, and |'go'| must have the menu bar suboption (ie. m
+	must be included).
+
+	COMPLEX ALIGNMENT MAP METHOD~
+
+	For those complex alignment maps which do alignment on constructs
+	(e.g. \acom, \adec, etc), a series of substitutes is used to insert
+	"@" symbols in appropriate locations.  Align#Align() is then used to
+	do alignment directly on "@"s; then it is followed by further
+	substitutes to do clean-up.  However, the maps \WS and \WE, used by
+	every map supported by AlignMaps, protect any original embedded "@"
+	symbols by first converting them to <DEL> characters, doing the
+	requested job, and then converting them back. >
+
+	    \WS  calls AlignMaps#WrapperStart()
+	    \WE  calls AlignMaps#WrapperEnd()
+<
+
+	---------------------------
+	Alignment Map Examples: \a,			*alignmap-a,* {{{3
+	---------------------------
+
+	Original: illustrates comma-separated declaration splitting: >
+		int a,b,c;
+		struct ABC_str abc,def;
+<
+	Becomes: >
+		int a;
+		int b;
+		int c;
+		struct ABC_str abc;
+		struct ABC_str def;
+<
+
+	---------------------------
+	Alignment Map Examples: \a?			*alignmap-a?* {{{3
+	---------------------------
+
+	Original: illustrates ()?: aligning >
+		printf("<%s>\n",
+		  (x == ABC)? "abc" :
+		  (x == DEFG)? "defg" :
+		  (x == HIJKL)? "hijkl" : "???");
+<
+	Becomes:  select "(x == ..." lines, then \a? >
+		printf("<%s>\n",
+		  (x == ABC)?   "abc"   :
+		  (x == DEFG)?  "defg"  :
+		  (x == HIJKL)? "hijkl" : "???");
+<
+
+	---------------------------
+	Alignment Map Examples: \a<			*alignmap-a<* {{{3
+	---------------------------
+
+	Original: illustrating aligning of << and >> >
+		cin << x;
+		cin      << y;
+		cout << "this is x=" << x;
+		cout << "but y=" << y << "is not";
+<
+	Becomes:  select "(x == ..." lines, then \a< >
+		cin  << x;
+		cin  << y;
+		cout << "this is x=" << x;
+		cout << "but y="     << y  << "is not";
+<
+
+	---------------------------
+	Alignment Map Examples: \a=			*alignmap-a=* {{{3
+	---------------------------
+
+	Original: illustrates how to align := assignments >
+		aa:=bb:=cc:=1;
+		a:=b:=c:=1;
+		aaa:=bbb:=ccc:=1;
+<	
+	Bcomes: select the three assignment lines, then \a:= >
+		aa  := bb  := cc  := 1;
+		a   := b   := c   := 1;
+		aaa := bbb := ccc := 1;
+<
+
+	---------------------------
+	Alignment Map Examples: \abox			*alignmap-abox* {{{3
+	---------------------------
+
+	Original: illustrates how to comment-box some text >
+		This is some plain text
+		which will
+		soon be surrounded by a
+		comment box.
+<
+	Becomes:  Select "This..box." with ctrl-v, press \abox >
+		/***************************
+		 * This is some plain text *
+		 * which will              *
+		 * soon be surrounded by a *
+		 * comment box.            *
+		 ***************************/
+<
+
+	---------------------------
+	Alignment Map Examples: \acom			*alignmap-acom* {{{3
+	---------------------------
+
+	Original: illustrates aligning C-style comments (works for //, too) >
+		if(itworks) { /* this */
+			then= dothis; /* is a */
+			} /* set of three comments */
+<
+	Becomes: Select the three lines, press \acom >
+	        if(itworks) {         /* this                  */
+	                then= dothis; /* is a                  */
+	                }             /* set of three comments */
+<
+	Also see |alignmap-aocom|
+
+
+	---------------------------
+	Alignment Map Examples: \anum			*alignmap-anum* {{{3
+	---------------------------
+
+	Original: illustrates how to get numbers lined up >
+		 -1.234 .5678 -.901e-4
+		 1.234 5.678 9.01e-4
+		 12.34 56.78 90.1e-4
+		 123.4 567.8 901.e-4
+<
+	Becomes: Go to first line, ma.  Go to last line, press \anum >
+		  -1.234    .5678   -.901e-4
+		   1.234   5.678    9.01e-4
+		  12.34   56.78    90.1e-4
+		 123.4   567.8    901.e-4
+<
+	Original: >
+		 | -1.234 .5678 -.901e-4 |
+		 | 1.234 5.678 9.01e-4   |
+		 | 12.34 56.78 90.1e-4   |
+		 | 123.4 567.8 901.e-4   |
+<
+	Becomes: Select the numbers with ctrl-v (visual-block mode), >
+	         press \anum
+	         |  -1.234    .5678   -.901e-4 |
+	         |   1.234   5.678    9.01e-4  |
+	         |  12.34   56.78    90.1e-4   |
+	         | 123.4   567.8    901.e-4    |
+<
+	Original: >
+		 -1,234 ,5678 -,901e-4
+		 1,234 5,678 9,01e-4
+		 12,34 56,78 90,1e-4
+		 123,4 567,8 901,e-4
+<
+	Becomes: Go to first line, ma.  Go to last line, press \anum >
+		  -1,234    ,5678   -,901e-4
+		   1,234   5,678    9,01e-4
+		  12,34   56,78    90,1e-4
+		 123,4   567,8    901,e-4
+<
+	In addition:
+	  \aenum is provided to support European-style numbers
+	  \aunum is provided to support USA-style numbers
+
+	One may get \aenum behavior for \anum >
+	  let g:alignmaps_euronumber= 1
+<	or \aunum behavior for \anum if one puts >
+	  let g:alignmaps_usanumber= 1
+<	in one's <.vimrc>.
+
+
+	---------------------------
+	Alignment Map Examples: \ascom			*alignmap-ascom* {{{3
+	---------------------------
+
+	Original: >
+		/* A Title */
+		int x; /* this is a comment */
+		int yzw; /* this is another comment*/
+<
+	Becomes: Select the three lines, press \ascom >
+	        /* A Title */
+	        int x;   /* this is a comment       */
+	        int yzw; /* this is another comment */
+<
+
+	---------------------------
+	Alignment Map Examples: \adec			*alignmap-adec* {{{3
+	---------------------------
+
+	Original: illustrates how to clean up C/C++ declarations >
+		int     a;
+		float   b;
+		double *c=NULL;
+		char x[5];
+		struct  abc_str abc;
+		struct  abc_str *pabc;
+		int     a;              /* a   */
+		float   b;              /* b   */
+		double *c=NULL;              /* b   */
+		char x[5]; /* x[5] */
+		struct  abc_str abc;    /* abc */
+		struct  abc_str *pabc;    /* pabc */
+		static   int     a;              /* a   */
+		static   float   b;              /* b   */
+		static   double *c=NULL;              /* b   */
+		static   char x[5]; /* x[5] */
+		static   struct  abc_str abc;    /* abc */
+		static   struct  abc_str *pabc;    /* pabc */
+<
+	Becomes: Select the declarations text, then \adec >
+		int                    a;
+		float                  b;
+		double                *c    = NULL;
+		char                   x[5];
+		struct abc_str         abc;
+		struct abc_str        *pabc;
+		int                    a;           /* a    */
+		float                  b;           /* b    */
+		double                *c    = NULL; /* b    */
+		char                   x[5];        /* x[5] */
+		struct abc_str         abc;         /* abc  */
+		struct abc_str        *pabc;        /* pabc */
+		static int             a;           /* a    */
+		static float           b;           /* b    */
+		static double         *c    = NULL; /* b    */
+		static char            x[5];        /* x[5] */
+		static struct abc_str  abc;         /* abc  */
+		static struct abc_str *pabc;        /* pabc */
+<
+
+	---------------------------
+	Alignment Map Examples: \adef			*alignmap-adef* {{{3
+	---------------------------
+
+	Original: illustrates how to line up #def'initions >
+		#define ONE 1
+		#define TWO 22
+		#define THREE 333
+		#define FOUR 4444
+<
+	Becomes: Select four definition lines, apply \adef >
+	#	 define ONE   1
+	#	 define TWO   22
+	#	 define THREE 333
+	#	 define FOUR  4444
+<
+
+	---------------------------
+	Alignment Map Examples: \afnc			*alignmap-afnc* {{{3
+	---------------------------
+
+	This map is an exception to the usual selection rules.
+	It uses "]]" to find the function body's leading "{".
+	Just put the cursor anywhere in the function arguments and
+	the entire function declaration should be processed.
+
+	Because "]]" looks for that "{" in the first column, the
+	"original" and "becomes" examples are in the first column,
+	too.
+
+	Original: illustrates lining up ansi-c style function definitions >
+	int f(
+	  struct abc_str ***a, /* one */
+	  long *b, /* two */
+	  int c) /* three */
+	{
+	}
+<
+	Becomes: put cursor anywhere before the '{', press \afnc >
+	int f(
+	  struct abc_str ***a,	/* one   */
+	  long             *b,	/* two   */
+	  int               c)	/* three */
+	{
+	}
+<
+
+	---------------------------
+	Alignment Map Examples: \adcom			*alignmap-adcom* {{{3
+	---------------------------
+
+	Original: illustrates aligning comments that don't begin
+		lines (optionally after some whitespace). >
+		struct {
+			/* this is a test */
+			int x; /* of how */
+			double y; /* to use adcom */
+			};
+<
+	Becomes: Select the inside lines of the structure,
+		then press \adcom.  The comment-only
+		line is ignored but the other two comments
+		get aligned. >
+		struct {
+                        /* this is a test */
+                        int x;    /* of how       */
+                        double y; /* to use adcom */
+			};
+<
+
+	---------------------------
+	Alignment Map Examples: \aocom			*alignmap-aocom* {{{3
+	---------------------------
+
+	Original: illustrates how to align C-style comments (works for //, too)
+	          but restricted only to aligning with those lines containing
+		  comments.  See the difference from \acom (|alignmap-acom|). >
+		if(itworks) { /* this comment */
+			then= dothis;
+			} /* only appears on two lines */
+<
+	Becomes: Select the three lines, press \aocom >
+                if(itworks) { /* this comment              */
+                        then= dothis;
+                        }     /* only appears on two lines */
+<
+	Also see |alignmap-acom|
+
+
+	---------------------------			*alignmap-Tsp*
+	Alignment Map Examples: \tsp			*alignmap-tsp* {{{3
+	---------------------------
+
+	Normally Align can't use white spaces for field separators as such
+	characters are ignored surrounding field separators.  The \tsp and
+	\Tsp maps get around this limitation.
+
+	Original: >
+	 one two three four five
+	 six seven eight nine ten
+	 eleven twelve thirteen fourteen fifteen
+<
+	Becomes: Select the lines, \tsp >
+	 one    two    three    four     five
+	 six    seven  eight    nine     ten
+	 eleven twelve thirteen fourteen fifteen
+<
+	Becomes: Select the lines, \Tsp >
+	    one    two    three     four    five
+	    six  seven    eight     nine     ten
+	 eleven twelve thirteen fourteen fifteen
+<
+
+	---------------------------
+	Alignment Map Examples: \tsq			*alignmap-tsq* {{{3
+	---------------------------
+
+	The \tsp map is useful for aligning tables based on white space,
+	but sometimes one wants double-quoted strings to act as a single
+	object in spite of embedded spaces.  The \tsq map was invented
+	to support this. (thanks to Leif Wickland)
+
+	Original: >
+	 "one two" three
+	 four "five six"
+<
+	Becomes: Select the lines, \tsq >
+	 "one two" three
+	 four      "five six"
+<
+
+	---------------------------
+	Alignment Map Examples: \tt			*alignmap-tt* {{{3
+	---------------------------
+
+	Original: illustrates aligning a LaTex Table >
+	 \begin{tabular}{||c|l|r||}
+	 \hline\hline
+	   one&two&three\\ \hline
+	   four&five&six\\
+	   seven&eight&nine\\
+	 \hline\hline
+	 \end{tabular}
+<
+	Becomes: Select the three lines inside the table >
+	(ie. one..,four..,seven..) and press \tt
+	 \begin{tabular}{||c|l|r||}
+	 \hline\hline
+	   one   & two   & three \\ \hline
+	   four  & five  & six   \\
+	   seven & eight & nine  \\
+	 \hline\hline
+	 \end{tabular}
+<
+
+	----------------------------
+	Alignment Map Examples: \tml			*alignmap-tml* {{{3
+	----------------------------
+
+        Original:  illustrates aligning multi-line continuation marks >
+	one \
+	two three \
+	four five six \
+	seven \\ \
+	eight \nine \
+	ten \
+<
+        Becomes:  >
+        one           \
+        two three     \
+        four five six \
+        seven \\      \
+        eight \nine   \
+        ten           \
+<
+
+	---------------------------
+	Alignment Map Examples: \t=			*alignmap-t=* {{{3
+	---------------------------
+
+	Original: illustrates left-justified aligning of = >
+		aa=bb=cc=1;/*one*/
+		a=b=c=1;/*two*/
+		aaa=bbb=ccc=1;/*three*/
+<
+	Becomes: Select the three equations, press \t= >
+		aa  = bb  = cc  = 1; /* one   */
+		a   = b   = c   = 1; /* two   */
+		aaa = bbb = ccc = 1; /* three */
+<
+
+	---------------------------
+	Alignment Map Examples: \T=			*alignmap-T=* {{{3
+	---------------------------
+
+	Original: illustrates right-justified aligning of = >
+		aa=bb=cc=1; /* one */
+		a=b=c=1; /* two */
+		aaa=bbb=ccc=1; /* three */
+<
+	Becomes: Select the three equations, press \T= >
+                 aa =  bb =  cc = 1; /* one   */
+                  a =   b =   c = 1; /* two   */
+                aaa = bbb = ccc = 1; /* three */
+<
+
+	---------------------------
+	Alignment Map Examples: \Htd			*alignmap-Htd* {{{3
+	---------------------------
+
+	Original: for aligning tables with html >
+	  <TR><TD>...field one...</TD><TD>...field two...</TD></TR>
+	  <TR><TD>...field three...</TD><TD>...field four...</TD></TR>
+<
+	Becomes: Select <TR>... lines, press \Htd >
+	  <TR><TD> ...field one...   </TD><TD> ...field two...  </TD></TR>
+	  <TR><TD> ...field three... </TD><TD> ...field four... </TD></TR>
+<
+==============================================================================
+4. Alignment Tools' History				*align-history* {{{1
+
+ALIGN HISTORY								{{{2
+	35 : Nov 02, 2008 * g:loaded_AlignPlugin testing to prevent re-loading
+			    installed
+	     Nov 19, 2008 * new sanity check for an AlignStyle of just ":"
+	     Jan 08, 2009 * save&restore of |'mod'| now done with local
+			    variant
+	34 : Jul 08, 2008 * using :AlignCtrl before entering any alignment
+			    control commands was causing an error.
+	33 : Sep 20, 2007 * s:Strlen() introduced to support various ways
+			    used to represent characters and their effects
+			    on string lengths.  See |align-strlen|.
+			  * Align now accepts "..." -- so it can accept
+			    whitespace as separators.
+	32 : Aug 18, 2007 * uses |<q-args>| instead of |<f-args>| plus a
+	                    custom argument splitter to allow patterns with
+			    backslashes to slide in unaltered.
+	31 : Aug 06, 2007 * :[range]Align! [AlignCtrl settings] pattern(s)
+	                    implemented.
+	30 : Feb 12, 2007 * now uses |setline()|
+	29 : Jan 18, 2006 * cecutil updated to use keepjumps
+	     Feb 23, 2006 * Align now converted to vim 7.0 style using
+	                    auto-loading functions.
+	28 : Aug 17, 2005 * report option workaround
+	     Oct 24, 2005 * AlignCtrl l:  wasn't behaving as expected; fixed
+	27 : Apr 15, 2005 : cpo workaround
+	                    ignorecase workaround
+	26 : Aug 20, 2004 : loaded_align now also indicates version number
+	                    GetLatestVimScripts :AutoInstall: now supported
+	25 : Jul 27, 2004 : For debugging, uses Dfunc(), Dret(), and Decho()
+	24 : Mar 03, 2004 : (should've done this earlier!) visualmode(1)
+	                    not supported until v6.2, now Align will avoid
+			    calling it for earlier versions.  Visualmode
+			    clearing won't take place then, of course.
+	23 : Oct 07, 2003 : Included Leif Wickland's ReplaceQuotedSpaces()
+	                    function which supports \tsq
+	22 : Jan 29, 2003 : Now requires 6.1.308 or later to clear visualmode()
+	21 : Jan 10, 2003 : BugFix: similar problem to #19; new code
+	                    bypasses "norm! v\<Esc>" until initialization
+	                    is over.
+	20 : Dec 30, 2002 : BugFix: more on "unable to highlight" fixed
+	19 : Nov 21, 2002 : BugFix: some terminals gave an "unable to highlight"
+	                    message at startup; Hari Krishna Dara tracked it
+	                    down; a silent! now included to prevent noise.
+	18 : Nov 04, 2002 : BugFix: re-enabled anti-repeated-loading
+	17 : Nov 04, 2002 : BugFix: forgot to have AlignPush() push s:AlignSep
+	                    AlignCtrl now clears visual-block mode when used so
+	                    that Align won't try to use old visual-block
+	                    selection marks '< '>
+	16 : Sep 18, 2002 : AlignCtrl <>| options implemented (separator
+	                    justification)
+	15 : Aug 22, 2002 : bug fix: AlignCtrl's ":" now acts as a modifier of
+	                             the preceding alignment operator (lrc)
+	14 : Aug 20, 2002 : bug fix: AlignCtrl default now keeps &ic unchanged
+	                    bug fix: Align, on end-field, wasn't using correct
+	                    alignop bug fix: Align, on end-field, was appending
+			    padding
+	13 : Aug 19, 2002 : bug fix: zero-length g/v patterns are accepted
+	                    bug fix: always skip blank lines
+	                    bug fix: AlignCtrl default now also clears g and v
+	                             patterns
+	12 : Aug 16, 2002 : moved keep_ic above zero-length pattern checks
+	                    added "AlignCtrl default"
+	                    fixed bug with last field getting separator spaces
+	                    at end line
+	11 : Jul 08, 2002 : prevent separator patterns which match zero length
+	                    -+: included as additional alignment/justification
+	                    styles
+	10 : Jun 26, 2002 : =~# used instead of =~ (for matching case)
+	                    ignorecase option handled
+	 9 : Jun 25, 2002 : implemented cyclic padding
+
+ALIGNMENT MAP HISTORY					*alignmap-history* {{{2
+       v41    Nov 02, 2008   * g:loaded_AlignMapsPlugin testing to prevent
+			       re-loading installed
+			     * AlignMaps now use 0x0f (ctrl-p) for special
+			       character substitutions (instead of 0xff).
+			       Seems to avoid some problems with having to
+			       use Strlen().
+			     * bug fixed with \ts,
+			     * new maps: \ts; \ts, \ts: \ts< \ts= \a(
+       v40    Oct 21, 2008   * Modified AlignMaps so that its maps use <Plug>s
+			       and <script>s.  \t@ and related maps have been
+			       changed to call StdAlign() instead.  The
+			       WrapperStart function now takes an argument and
+			       handles being called via visual mode.  The
+			       former nmaps and vmaps have thus been replaced
+			       with a simple map.
+	      Oct 24, 2008   * broke AlignMaps into a plugin and autoload
+			       pair of scripts.
+	v39   Mar 06, 2008 : * \t= only does /* ... */ aligning when in *.c
+	                       *.cpp files.
+	v38   Aug 18, 2007 : * \tt altered so that it works with the new
+	                       use of |<q-args>| plus a custom argument
+			       splitter
+	v36   Sep 27, 2006 : * AlignWrapperStart() now has tests that marks
+	                       y and z are not set
+	      May 15, 2007   * \anum and variants improved
+	v35   Sep 01, 2006 : * \t= and cousins used "`"s.  They now use \xff
+	                       characters.
+	                     * \acom now works with doxygen style /// comments
+	                     * <char-0xff> used in \t= \T= \w= and \m= instead
+	                       of backquotes.
+	v34   Feb 23, 2006 : * AlignMaps now converted to vim 7.0 style using
+	                       auto-loading functions.
+	v33   Oct 12, 2005 : * \ts, now uses P1 in its AlignCtrl call
+	v32   Jun 28, 2005 : * s:WrapperStart() changed to AlignWrapperStart()
+	                       s:WrapperEnd() changed to AlignWrapperEnd()
+	                       These changes let the AlignWrapper...()s to be
+	                       used outside of AlignMaps.vim
+	v31   Feb 01, 2005 : * \adcom included, with help
+	                     * \a, now works across multiple lines with
+	                       different types
+	                     * AlignMaps now uses <cecutil.vim> for its mark and
+	                       window-position saving and restoration
+	      Mar 04, 2005   * improved \a,
+	      Apr 06, 2005   * included \aenum, \aunum, and provided
+	              g:alignmaps_{usa|euro]number} options
+	v30   Aug 20, 2004 : * \a, : handles embedded assignments and does \adec
+	                     * \acom  now can handle Doxygen-style comments
+	                     * g:loaded_alignmaps now also indicates version
+	                     * internal maps \WE and \WS are now re-entrant
+	v29   Jul 27, 2004 : * \tml aligns trailing multi-line single
+	                      backslashes (thanks to Raul Benavente!)
+	v28   May 13, 2004 : * \a, had problems with leading blanks; fixed!
+	v27   Mar 31, 2004 : * \T= was having problems with == and !=
+	                     * Fixed more problems with \adec
+	v26   Dec 09, 2003 : * \ascom now also ignores lines without comments
+	                     * \tt  \& now not matched
+	                     * \a< handles both << and >>
+	v25   Nov 14, 2003 : * included \anum (aligns numbers with periods and
+	                       commas).  \anum also supported with ctrl-v mode.
+	                     * \ts, \Ts, : (aligns on commas, then swaps leading
+	                       spaces with commas)
+	                     * \adec ignores preprocessor lines and lines with
+	                       with comments-only
+	v23   Sep 10, 2003 : * Bugfix for \afnc - no longer overwrites marks y,z
+	                     * fixed bug in \tsp, \tab, \Tsp, and \Tab - lines
+	                       containing backslashes were having their
+	                       backslashes removed.  Included Leif Wickland's
+	                       patch for \tsq.
+	                     * \adef now ignores lines holding comments only
+	v18   Aug 22, 2003 :   \a< lines up C++'s << operators
+	                       saves/restores gdefault option (sets to nogd)
+	                       all b:..varname.. are now b:alignmaps_..varname..
+	v17   Nov 04, 2002 :   \afnc now handles // comments correctly and
+	                       commas within comments
+	v16   Sep 10, 2002 :   changed : to :silent! for \adec
+	v15   Aug 27, 2002 :   removed some <c-v>s
+	v14   Aug 20, 2002 :   \WS, \WE mostly moved to functions, marks y and z
+	                       now restored
+	v11   Jul 08, 2002 :   \abox bug fix
+	 v9   Jun 25, 2002 :   \abox now handles leading initial whitespace
+	                   :   various bugfixes to \afnc, \T=, etc
+
+==============================================================================
+Modelines: {{{1
+vim:tw=78:ts=8:ft=help:fdm=marker:
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/skeleton.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/skeleton.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/skeleton.txt	(revision 18231)
@@ -0,0 +1,153 @@
+*skeleton.txt*	Skeleton for newly created buffers
+
+Version 0.0.2
+Script ID: 2291
+Copyright (C) 2008 kana <http://whileimautomaton.net/>
+License: MIT license  {{{
+    Permission is hereby granted, free of charge, to any person obtaining
+    a copy of this software and associated documentation files (the
+    "Software"), to deal in the Software without restriction, including
+    without limitation the rights to use, copy, modify, merge, publish,
+    distribute, sublicense, and/or sell copies of the Software, and to
+    permit persons to whom the Software is furnished to do so, subject to
+    the following conditions:
+
+    The above copyright notice and this permission notice shall be included
+    in all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+}}}
+
+CONTENTS					*skeleton-contents*
+
+Introduction		|skeleton-introduction|
+Interface		|skeleton-interface|
+  Commands		  |skeleton-commands|
+  Events		  |skeleton-events|
+Bugs			|skeleton-bugs|
+Changelog		|skeleton-changelog|
+
+
+
+
+==============================================================================
+INTRODUCTION					*skeleton-introduction*
+
+*skeleton* is a Vim plugin to set up a skeleton for a newly created buffer.
+Once you put skeleton files into specific directories, appropriate ones will
+be automatically expanded for newly created buffers.
+
+- Skeleton files must be put in a directory named "xtr/skeleton/" which is
+  under any directory listed in 'runtimepath'.
+
+  For example: ~/.vim/xtr/skeleton/
+
+- The name of a skeleton file should be "{filetype}" or "{filetype}-{suffix}",
+  where {filetype} is the 'filetype' for a newly created buffer and {suffix}
+  is an arbitrary string.
+
+  The former "{filetype}" is used as the default skeleton file for that
+  'filetype'.  The latter "{filetype}-{suffix}" is used to override the
+  default one for some cases which are speicifed by user.
+
+  For example: ~/.vim/xtr/skeleton/vim ~/.vim/xtr/skeleton/vim-plugin
+
+- Whenever user starts to edit a file that doesn't exists:
+
+  1) Skeleton publish a |User:plugin-skeleton-detect| event.  This event can
+     be used to |:SkeletonLoad| a special skeleton file other than the default
+     one.
+  
+  2) If |:SkeletonLoad| is not done for the previous step, Skeleton executes
+     the following command:
+>
+	execute 'SkeletonLoad' &l:filetype
+<
+     This means a skeleton file named "{filetype}" in a directory
+     "xtr/skeleton/" which is under any directory listed in 'runtimepath' is
+     loaded as a skeleton file.
+
+     If there is no such skeleton file, nothing will be happened.
+
+
+Requirements:
+- Vim 7.1 or later
+
+Latest version:
+http://github.com/kana/config/commits/vim-skeleton
+
+
+
+
+==============================================================================
+INTERFACE					*skeleton-interface*
+
+------------------------------------------------------------------------------
+COMMANDS					*skeleton-commands*
+
+						*:SkeletonLoad*
+:SkeletonLoad[!] {name}
+	Load the skeleton file with {name} for the current buffer.
+
+	- If the current buffer is not a normal buffer,
+	  nothing will be happened.
+	- If "!" is not given and the current buffer is not empty,
+	  nothing will be happened.
+	- If "!" is given, existing content of the current buffer will be
+	  deleted before loading the specified skeleton.
+
+
+------------------------------------------------------------------------------
+EVENTS						*skeleton-events*
+
+User plugin-skeleton-detect			*User:plugin-skeleton-detect*
+	Event to override the default skeleton file.  User can set up
+	|:autocmd| for this event to |:SkeletonLoad| a special skeleton file
+	other than the default one.
+
+	Example: >
+		autocmd User plugin-skeleton-detect
+		\   if expand('%') =~# '\<plugin/.*\.vim$'
+		\ |   SkeletonLoad vim-plugin
+		\ | endif
+<
+
+
+
+==============================================================================
+BUGS						*skeleton-bugs*
+
+- There are many bugs around the world.
+
+
+
+
+==============================================================================
+CHANGELOG					*skeleton-changelog*
+
+0.0.2	2009-03-17T01:16:29+09:00
+	- Refine the document.
+	- |:SkeletonLoad|:
+	  - Support completion.
+	  - Allow to override existing content of a buffer with "!".
+
+0.0.1	2008-07-13T00:20:09+09:00
+	- Fix to suppress extra message if there is no autocmd for
+	  |User:plugin-skeleton-detect|.
+	- Fix not to do the default |:SkeletonLoad| if 'filetype' of the
+	  current buffer is unknown.
+
+0.0.0	2008-07-11T12:23:55+09:00
+	- Initial version.
+
+
+
+
+==============================================================================
+vim:tw=78:ts=8:ft=help:norl:fen:fdl=0:fdm=marker:
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/tags
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/tags	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/doc/tags	(revision 18231)
@@ -0,0 +1,85 @@
+Align-copyright	Align.txt	/*Align-copyright*
+align	Align.txt	/*align*
+align-align	Align.txt	/*align-align*
+align-codepoint	Align.txt	/*align-codepoint*
+align-command	Align.txt	/*align-command*
+align-commands	Align.txt	/*align-commands*
+align-concept	Align.txt	/*align-concept*
+align-concepts	Align.txt	/*align-concepts*
+align-contents	Align.txt	/*align-contents*
+align-control	Align.txt	/*align-control*
+align-history	Align.txt	/*align-history*
+align-manual	Align.txt	/*align-manual*
+align-maps	Align.txt	/*align-maps*
+align-multibyte	Align.txt	/*align-multibyte*
+align-option	Align.txt	/*align-option*
+align-options	Align.txt	/*align-options*
+align-strlen	Align.txt	/*align-strlen*
+align-usage	Align.txt	/*align-usage*
+align-userguide	Align.txt	/*align-userguide*
+align-utf	Align.txt	/*align-utf*
+align-utf8	Align.txt	/*align-utf8*
+align.txt	Align.txt	/*align.txt*
+alignctrl	Align.txt	/*alignctrl*
+alignctrl-	Align.txt	/*alignctrl-*
+alignctrl-+	Align.txt	/*alignctrl-+*
+alignctrl--	Align.txt	/*alignctrl--*
+alignctrl-:	Align.txt	/*alignctrl-:*
+alignctrl-<	Align.txt	/*alignctrl-<*
+alignctrl-=	Align.txt	/*alignctrl-=*
+alignctrl->	Align.txt	/*alignctrl->*
+alignctrl-C	Align.txt	/*alignctrl-C*
+alignctrl-I	Align.txt	/*alignctrl-I*
+alignctrl-P	Align.txt	/*alignctrl-P*
+alignctrl-W	Align.txt	/*alignctrl-W*
+alignctrl-c	Align.txt	/*alignctrl-c*
+alignctrl-g	Align.txt	/*alignctrl-g*
+alignctrl-l	Align.txt	/*alignctrl-l*
+alignctrl-m	Align.txt	/*alignctrl-m*
+alignctrl-no-option	Align.txt	/*alignctrl-no-option*
+alignctrl-p	Align.txt	/*alignctrl-p*
+alignctrl-r	Align.txt	/*alignctrl-r*
+alignctrl-separators	Align.txt	/*alignctrl-separators*
+alignctrl-settings	Align.txt	/*alignctrl-settings*
+alignctrl-v	Align.txt	/*alignctrl-v*
+alignctrl-w	Align.txt	/*alignctrl-w*
+alignman	Align.txt	/*alignman*
+alignmanual	Align.txt	/*alignmanual*
+alignmap-Htd	Align.txt	/*alignmap-Htd*
+alignmap-T=	Align.txt	/*alignmap-T=*
+alignmap-Tsp	Align.txt	/*alignmap-Tsp*
+alignmap-a(	Align.txt	/*alignmap-a(*
+alignmap-a,	Align.txt	/*alignmap-a,*
+alignmap-a<	Align.txt	/*alignmap-a<*
+alignmap-a=	Align.txt	/*alignmap-a=*
+alignmap-a?	Align.txt	/*alignmap-a?*
+alignmap-abox	Align.txt	/*alignmap-abox*
+alignmap-acom	Align.txt	/*alignmap-acom*
+alignmap-adcom	Align.txt	/*alignmap-adcom*
+alignmap-adec	Align.txt	/*alignmap-adec*
+alignmap-adef	Align.txt	/*alignmap-adef*
+alignmap-afnc	Align.txt	/*alignmap-afnc*
+alignmap-anum	Align.txt	/*alignmap-anum*
+alignmap-aocom	Align.txt	/*alignmap-aocom*
+alignmap-ascom	Align.txt	/*alignmap-ascom*
+alignmap-history	Align.txt	/*alignmap-history*
+alignmap-m=	Align.txt	/*alignmap-m=*
+alignmap-t#	Align.txt	/*alignmap-t#*
+alignmap-t,	Align.txt	/*alignmap-t,*
+alignmap-t:	Align.txt	/*alignmap-t:*
+alignmap-t;	Align.txt	/*alignmap-t;*
+alignmap-t<	Align.txt	/*alignmap-t<*
+alignmap-t=	Align.txt	/*alignmap-t=*
+alignmap-t?	Align.txt	/*alignmap-t?*
+alignmap-tab	Align.txt	/*alignmap-tab*
+alignmap-tml	Align.txt	/*alignmap-tml*
+alignmap-ts,	Align.txt	/*alignmap-ts,*
+alignmap-ts:	Align.txt	/*alignmap-ts:*
+alignmap-ts<	Align.txt	/*alignmap-ts<*
+alignmap-ts=	Align.txt	/*alignmap-ts=*
+alignmap-tsp	Align.txt	/*alignmap-tsp*
+alignmap-tsq	Align.txt	/*alignmap-tsq*
+alignmap-tt	Align.txt	/*alignmap-tt*
+alignmap-t~	Align.txt	/*alignmap-t~*
+alignmaps	Align.txt	/*alignmaps*
+alignusage	Align.txt	/*alignusage*
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/matlab.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/matlab.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/matlab.vim	(revision 18231)
@@ -0,0 +1,146 @@
+" Matlab indent file
+" Language:	Matlab
+" Maintainer:	Fabrice Guy <fabrice.guy at gmail dot com>
+" Last Change:	2009 Nov 23 - Added support for if/end block on the same line
+
+" Only load this indent file when no other was loaded.
+if exists("b:did_indent")
+  finish
+endif
+let b:did_indent = 1
+let s:functionWithoutEndStatement = 0
+
+setlocal indentexpr=GetMatlabIndent()
+setlocal indentkeys=!,o,O=end,=case,=else,=elseif,=otherwise,=catch
+
+" Only define the function once.
+if exists("*GetMatlabIndent")
+  finish
+endif
+
+function! s:IsMatlabContinuationLine(lnum)
+  let continuationLine = 0
+  if a:lnum > 0
+    let pnbline = getline(prevnonblank(a:lnum))
+    " if we have the line continuation operator (... at the end of a line or
+    " ... followed by a comment) it may be a line continuation
+    if pnbline =~ '\.\.\.\s*$' || pnbline =~ '\.\.\.\s*%.*$'
+      let continuationLine = 1
+      " but if the ... are part of a string or a comment, it is not a
+      " continuation line
+      let col = match(pnbline, '\.\.\.\s*$')
+      if col == -1
+	let col = match(pnbline, '\.\.\.\s*%.*$')
+      endif
+      if has('syntax_items')
+	if synIDattr(synID(prevnonblank(a:lnum), col + 1, 1), "name") =~ "matlabString" ||
+	      \ synIDattr(synID(prevnonblank(a:lnum), col + 1, 1), "name") =~ "matlabComment" 
+	  let continuationLine = 0
+	endif
+      endif
+    endif
+  endif
+  return continuationLine
+endfunction
+
+function GetMatlabIndent()
+  " Find a non-blank line above the current line.
+  let plnum = prevnonblank(v:lnum - 1)
+
+  " If the previous line is a continuation line, get the beginning of the block to 
+  " use the indent of that line
+  if s:IsMatlabContinuationLine(plnum - 1)
+    while s:IsMatlabContinuationLine(plnum - 1)
+      let plnum = plnum - 1
+    endwhile
+  endif
+
+  " At the start of the file use zero indent.
+  if plnum == 0
+    return 0
+  endif
+
+  let curind = indent(plnum)
+  if s:IsMatlabContinuationLine(v:lnum - 1) 
+    let curind = curind + &sw
+  endif
+  " Add a 'shiftwidth' after classdef, properties, switch, methods, events,
+  " function, if, while, for, otherwise, case, try, catch, else, elseif
+  if getline(plnum) =~ '^\s*\(classdef\|properties\|switch\|methods\|events\|function\|if\|while\|for\|otherwise\|case\|try\|catch\|else\|elseif\)\>'
+    let curind = curind + &sw
+    " In Matlab we have different kind of functions
+    " - the main function (the function with the same name than the filename)
+    " - the nested functions
+    " - the functions defined in methods (for classes)
+    " - subfunctions
+    " Principles for the indentation :
+    " - all the function keywords are indented (corresponding to the
+    "   'indent all functions' in the Matlab Editor)
+    " - if we have only subfonctions (ie if the main function doesn't have
+    "   any mayching end), then each function is dedented
+    if getline(plnum)  =~ '^\s*\function\>'
+      let pplnum = plnum - 1
+      while pplnum > 1 && (getline(pplnum) =~ '^\s*%')
+	let pplnum = pplnum - 1
+      endwhile
+      " If it is the main function, determine if function has a matching end
+      " or not
+      if pplnum <= 1 
+	" look for a matching end : 
+	" - if we find a matching end everything is fine : end of functions
+	"   will be dedented when 'end' is reached
+	" - if not, then all other functions are subfunctions : 'function'
+	"   keyword has to be dedended
+	let old_lnum = v:lnum
+	let motion = plnum . "gg"
+	execute "normal" . motion
+	normal %
+	if getline(line('.')) =~ '^\s*end'
+	  let s:functionWithoutEndStatement = 0
+	else
+	  let s:functionWithoutEndStatement = 1
+	endif
+	normal %
+	let motion = old_lnum . "gg"
+	execute "normal" . motion
+      endif
+    endif
+    " if the for-end block (or while-end) is on the same line : dedent
+    if getline(plnum)  =~ '\<end[,;]*\s*\(%.*\)\?$'
+      let curind = curind - &sw 
+    endif
+  endif
+
+  " Subtract a 'shiftwidth' on a else, elseif, end, catch, otherwise, case
+  if getline(v:lnum) =~ '^\s*\(else\|elseif\|end\|catch\|otherwise\|case\)\>'
+    let curind = curind - &sw
+  endif
+  " No indentation in a subfunction
+  if getline(v:lnum)  =~ '^\s*\function\>' && s:functionWithoutEndStatement
+    let curind = curind - &sw
+  endif
+  " First case after a switch : indent
+  if getline(v:lnum) =~ '^\s*case'
+    while plnum > 0 && (getline(plnum) =~ '^\s*%' || getline(plnum) =~ '^\s*$')
+      let plnum = plnum - 1
+    endwhile
+    if getline(plnum) =~ '^\s*switch'
+      let curind = indent(plnum) + &sw
+    endif
+  endif
+
+  " end in a switch / end block : dedent twice
+  " we use the matchit script to know if this end is the end of a switch block
+  if exists("b:match_words")
+    if getline(v:lnum) =~ '^\s*end'
+      normal %
+      if getline(line('.')) =~ '^\s*switch'
+	let curind = curind - &sw
+      endif
+      normal %
+    end
+  end
+  return curind
+endfunction
+
+" vim:sw=2
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/tex.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/tex.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/indent/tex.vim	(revision 18231)
@@ -0,0 +1,139 @@
+" Vim indent file
+" Language:     LaTeX
+" Maintainer:   Johannes Tanzler <jtanzler@yline.com>
+" Created:      Sat, 16 Feb 2002 16:50:19 +0100
+" Last Change:	Sun, 17 Feb 2002 00:09:11 +0100
+" Last Update:  18th feb 2002, by LH :
+"               (*) better support for the option
+"               (*) use some regex instead of several '||'.
+" Version: 0.02
+" URL: comming soon: http://www.unet.univie.ac.at/~a9925098/vim/indent/tex.vim
+
+" --> If you're a Vim guru & and you find something that could be done in a
+"     better (perhaps in a more Vim-ish or Vi-ish) way, please let me know! 
+
+" Options: {{{
+"
+" To set the following options (ok, currently it's just one), add a line like
+"   let g:tex_indent_items = 1
+" to your ~/.vimrc.
+"
+" * g:tex_indent_items
+"
+"   If this variable is set, item-environments are indented like Emacs does
+"   it, i.e., continuation lines are indented with a shiftwidth.
+"   
+"   NOTE: I've already set the variable below; delete the corresponding line
+"   if you don't like this behaviour.
+"
+"   Per default, it is unset.
+"   
+"              set                                unset
+"   ----------------------------------------------------------------
+"       \begin{itemize}                      \begin{itemize}  
+"         \item blablabla                      \item blablabla
+"           bla bla bla                        bla bla bla  
+"         \item blablabla                      \item blablabla
+"           bla bla bla                        bla bla bla  
+"       \end{itemize}                        \end{itemize}    
+"
+"
+"   This option applies to itemize, description, enumerate, and
+"   thebibliography.
+"
+" }}} 
+
+" Delete the next line to avoid the special indention of items
+if !exists("g:tex_indent_items")
+  let g:tex_indent_items = 1
+endif
+
+if exists("b:did_indent") | finish
+endif
+let b:did_indent = 1
+
+
+setlocal indentexpr=GetTeXIndent()
+setlocal nolisp
+setlocal nosmartindent
+setlocal autoindent
+setlocal indentkeys+=},=\\item,=\\bibitem
+
+
+" Only define the function once
+if exists("*GetTeXIndent") | finish
+endif
+
+
+
+function GetTeXIndent()
+
+  " Find a non-blank line above the current line.
+  let lnum = prevnonblank(v:lnum - 1)
+
+  " At the start of the file use zero indent.
+  if lnum == 0 | return 0 
+  endif
+
+  let ind = indent(lnum)
+  let line = getline(lnum)             " last line
+  let cline = getline(v:lnum)          " current line
+
+  " Do not change indentation of commented lines.
+  if line =~ '^\s*%'
+    return ind
+  endif
+
+  " Add a 'shiftwidth' after beginning of environments.
+  " Don't add it for \begin{document} and \begin{verbatim}
+  ""if line =~ '^\s*\\begin{\(.*\)}'  && line !~ 'verbatim' 
+  " LH modification : \begin does not always start a line
+  if line =~ '\\begin{\(.*\)}'  && line !~ 'verbatim' 
+        \ && line !~ 'document'
+
+    let ind = ind + &sw
+
+    if g:tex_indent_items == 1
+      " Add another sw for item-environments
+      if line =~ 'itemize\|description\|enumerate\|thebibliography'
+        let ind = ind + &sw
+      endif
+    endif
+  endif
+
+  
+  " Subtract a 'shiftwidth' when an environment ends
+  if cline =~ '^\s*\\end' && cline !~ 'verbatim' 
+        \&& cline !~ 'document'
+
+    if g:tex_indent_items == 1
+      " Remove another sw for item-environments
+      if cline =~ 'itemize\|description\|enumerate\|thebibliography'
+        let ind = ind - &sw
+      endif
+    endif
+
+    let ind = ind - &sw
+  endif
+
+  
+  " Special treatment for 'item'
+  " ----------------------------
+  
+  if g:tex_indent_items == 1
+
+    " '\item' or '\bibitem' itself:
+    if cline =~ '^\s*\\\(bib\)\=item' 
+      let ind = ind - &sw
+    endif
+
+    " lines following to '\item' are intented once again:
+    if line =~ '^\s*\\\(bib\)\=item' 
+      let ind = ind + &sw
+    endif
+
+  endif
+
+  return ind
+endfunction
+
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim	(revision 18231)
@@ -0,0 +1,242 @@
+" AlignMapsPlugin:   Alignment maps based upon <Align.vim> and <AlignMaps.vim>
+" Maintainer:        Dr. Charles E. Campbell, Jr. <NdrOchipS@PcampbellAfamily.Mbiz>
+" Date:              Mar 03, 2009
+"
+" NOTE: the code herein needs vim 6.0 or later
+"                       needs <Align.vim> v6 or later
+"                       needs <cecutil.vim> v5 or later
+" Copyright:    Copyright (C) 1999-2008 Charles E. Campbell, Jr. {{{1
+"               Permission is hereby granted to use and distribute this code,
+"               with or without modifications, provided that this copyright
+"               notice is copied with it. Like anything else that's free,
+"               AlignMaps.vim is provided *as is* and comes with no warranty
+"               of any kind, either expressed or implied. By using this
+"               plugin, you agree that in no event will the copyright
+"               holder be liable for any damages resulting from the use
+"               of this software.
+"
+" Usage: {{{1
+" Use 'a to mark beginning of to-be-aligned region,   Alternative:  use V
+" move cursor to end of region, and execute map.      (linewise visual mode) to
+" The maps also set up marks 'y and 'z, and retain    mark region, execute same
+" 'a at the beginning of region.                      map.  Uses 'a, 'y, and 'z.
+"
+" The start/end wrappers save and restore marks 'y and 'z.
+"
+" Although the comments indicate the maps use a leading backslash,
+" actually they use <Leader> (:he mapleader), so the user can
+" specify that the maps start how he or she prefers.
+"
+" Note: these maps all use <Align.vim>.
+"
+" Romans 1:20 For the invisible things of Him since the creation of the {{{1
+" world are clearly seen, being perceived through the things that are
+" made, even His everlasting power and divinity; that they may be
+" without excuse.
+
+" ---------------------------------------------------------------------
+" Load Once: {{{1
+if &cp || exists("g:loaded_AlignMapsPlugin")
+ finish
+endif
+let s:keepcpo                = &cpo
+let g:loaded_AlignMapsPlugin = "v41"
+set cpo&vim
+
+" =====================================================================
+"  Maps: {{{1
+
+" ---------------------------------------------------------------------
+" WS: wrapper start map (internal)  {{{2
+" Produces a blank line above and below, marks with 'y and 'z
+if !hasmapto('<Plug>WrapperStart')
+ map <unique> <SID>WS	<Plug>AlignMapsWrapperStart
+endif
+nmap <silent> <script> <Plug>AlignMapsWrapperStart	:set lz<CR>:call AlignMaps#WrapperStart(0)<CR>
+vmap <silent> <script> <Plug>AlignMapsWrapperStart	:<c-u>set lz<CR>:call AlignMaps#WrapperStart(1)<CR>
+
+" ---------------------------------------------------------------------
+" WE: wrapper end (internal)   {{{2
+" Removes guard lines, restores marks y and z, and restores search pattern
+if !hasmapto('<Plug>WrapperEnd')
+ nmap <unique> <SID>WE	<Plug>AlignMapsWrapperEnd
+endif
+nmap <silent> <script> <Plug>AlignMapsWrapperEnd	:call AlignMaps#WrapperEnd()<CR>:set nolz<CR>
+
+" ---------------------------------------------------------------------
+" Complex C-code alignment maps: {{{2
+if !hasmapto('<Plug>AM_a?')   |map <unique> <Leader>a?		<Plug>AM_a?|endif
+if !hasmapto('<Plug>AM_a,')   |map <unique> <Leader>a,		<Plug>AM_a,|endif
+if !hasmapto('<Plug>AM_a<')   |map <unique> <Leader>a<		<Plug>AM_a<|endif
+if !hasmapto('<Plug>AM_a=')   |map <unique> <Leader>a=		<Plug>AM_a=|endif
+if !hasmapto('<Plug>AM_a(')   |map <unique> <Leader>a(		<Plug>AM_a(|endif
+if !hasmapto('<Plug>AM_abox') |map <unique> <Leader>abox	<Plug>AM_abox|endif
+if !hasmapto('<Plug>AM_acom') |map <unique> <Leader>acom	<Plug>AM_acom|endif
+if !hasmapto('<Plug>AM_adcom')|map <unique> <Leader>adcom	<Plug>AM_adcom|endif
+if !hasmapto('<Plug>AM_aocom')|map <unique> <Leader>aocom	<Plug>AM_aocom|endif
+if !hasmapto('<Plug>AM_ascom')|map <unique> <Leader>ascom	<Plug>AM_ascom|endif
+if !hasmapto('<Plug>AM_adec') |map <unique> <Leader>adec	<Plug>AM_adec|endif
+if !hasmapto('<Plug>AM_adef') |map <unique> <Leader>adef	<Plug>AM_adef|endif
+if !hasmapto('<Plug>AM_afnc') |map <unique> <Leader>afnc	<Plug>AM_afnc|endif
+if !hasmapto('<Plug>AM_afnc') |map <unique> <Leader>afnc	<Plug>AM_afnc|endif
+if !hasmapto('<Plug>AM_aunum')|map <unique> <Leader>aunum	<Plug>AM_aenum|endif
+if !hasmapto('<Plug>AM_aenum')|map <unique> <Leader>aenum	<Plug>AM_aunum|endif
+if exists("g:alignmaps_euronumber") && !exists("g:alignmaps_usanumber")
+ if !hasmapto('<Plug>AM_anum')|map <unique> <Leader>anum	<Plug>AM_aenum|endif
+else
+ if !hasmapto('<Plug>AM_anum')|map <unique> <Leader>anum	<Plug>AM_aunum|endif
+endif
+
+map <silent> <script> <Plug>AM_a?		<SID>WS:AlignCtrl mIp1P1lC ? : : : : <CR>:'a,.Align<CR>:'a,'z-1s/\(\s\+\)? /?\1/e<CR><SID>WE
+map <silent> <script> <Plug>AM_a,		<SID>WS:'y,'zs/\(\S\)\s\+/\1 /ge<CR>'yjma'zk:call AlignMaps#CharJoiner(",")<cr>:silent 'y,'zg/,/call AlignMaps#FixMultiDec()<CR>'z:exe "norm \<Plug>AM_adec"<cr><SID>WE
+map <silent> <script> <Plug>AM_a<		<SID>WS:AlignCtrl mIp1P1=l << >><CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_a(       <SID>WS:AlignCtrl mIp0P1=l<CR>:'a,.Align [(,]<CR>:sil 'y+1,'z-1s/\(\s\+\),/,\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_a=		<SID>WS:AlignCtrl mIp1P1=l<CR>:AlignCtrl g :=<CR>:'a,'zAlign :\==<CR><SID>WE
+map <silent> <script> <Plug>AM_abox		<SID>WS:let g:alignmaps_iws=substitute(getline("'a"),'^\(\s*\).*$','\1','e')<CR>:'a,'z-1s/^\s\+//e<CR>:'a,'z-1s/^.*$/@&@/<CR>:AlignCtrl m=p01P0w @<CR>:'a,.Align<CR>:'a,'z-1s/@/ * /<CR>:'a,'z-1s/@$/*/<CR>'aYP:s/./*/g<CR>0r/'zkYp:s/./*/g<CR>0r A/<Esc>:exe "'a-1,'z-1s/^/".g:alignmaps_iws."/e"<CR><SID>WE
+map <silent> <script> <Plug>AM_acom		<SID>WS:'a,.s/\/[*/]\/\=/@&@/e<CR>:'a,.s/\*\//@&/e<CR>:'y,'zs/^\( *\) @/\1@/e<CR>'zk:call AlignMaps#StdAlign(2)<CR>:'y,'zs/^\(\s*\) @/\1/e<CR>:'y,'zs/ @//eg<CR><SID>WE
+map <silent> <script> <Plug>AM_adcom	<SID>WS:'a,.v/^\s*\/[/*]/s/\/[*/]\*\=/@&@/e<CR>:'a,.v/^\s*\/[/*]/s/\*\//@&/e<CR>:'y,'zv/^\s*\/[/*]/s/^\( *\) @/\1@/e<CR>'zk:call AlignMaps#StdAlign(3)<cr>:'y,'zv/^\s*\/[/*]/s/^\(\s*\) @/\1/e<CR>:'y,'zs/ @//eg<CR><SID>WE
+map <silent> <script> <Plug>AM_aocom	<SID>WS:AlignPush<CR>:AlignCtrl g /[*/]<CR>:exe "norm \<Plug>AM_acom"<cr>:AlignPop<CR><SID>WE
+map <silent> <script> <Plug>AM_ascom	<SID>WS:'a,.s/\/[*/]/@&@/e<CR>:'a,.s/\*\//@&/e<CR>:silent! 'a,.g/^\s*@\/[*/]/s/@//ge<CR>:AlignCtrl v ^\s*\/[*/]<CR>:AlignCtrl g \/[*/]<CR>'zk:call AlignMaps#StdAlign(2)<cr>:'y,'zs/^\(\s*\) @/\1/e<CR>:'y,'zs/ @//eg<CR><SID>WE
+map <silent> <script> <Plug>AM_adec		<SID>WS:'a,'zs/\([^ \t/(]\)\([*&]\)/\1 \2/e<CR>:'y,'zv/^\//s/\([^ \t]\)\s\+/\1 /ge<CR>:'y,'zv/^\s*[*/]/s/\([^/][*&]\)\s\+/\1/ge<CR>:'y,'zv/^\s*[*/]/s/^\(\s*\%(\K\k*\s\+\%([a-zA-Z_*(&]\)\@=\)\+\)\([*(&]*\)\s*\([a-zA-Z0-9_()]\+\)\s*\(\(\[.\{-}]\)*\)\s*\(=\)\=\s*\(.\{-}\)\=\s*;/\1@\2#@\3\4@\6@\7;@/e<CR>:'y,'zv/^\s*[*/]/s/\*\/\s*$/@*\//e<CR>:'y,'zv/^\s*[*/]/s/^\s\+\*/@@@@@* /e<CR>:'y,'zv/^\s*[*/]/s/^@@@@@\*\(.*[^*/]\)$/&@*/e<CR>'yjma'zk:AlignCtrl v ^\s*[*/#]<CR>:call AlignMaps#StdAlign(1)<cr>:'y,'zv/^\s*[*/]/s/@ //ge<CR>:'y,'zv/^\s*[*/]/s/\(\s*\);/;\1/e<CR>:'y,'zv/^#/s/# //e<CR>:'y,'zv/^\s\+[*/#]/s/\([^/*]\)\(\*\+\)\( \+\)/\1\3\2/e<CR>:'y,'zv/^\s\+[*/#]/s/\((\+\)\( \+\)\*/\2\1*/e<CR>:'y,'zv/^\s\+[*/#]/s/^\(\s\+\) \*/\1*/e<CR>:'y,'zv/^\s\+[*/#]/s/[ \t@]*$//e<CR>:'y,'zs/^[*]/ */e<CR><SID>WE
+map <silent> <script> <Plug>AM_adef		<SID>WS:AlignPush<CR>:AlignCtrl v ^\s*\(\/\*\<bar>\/\/\)<CR>:'a,.v/^\s*\(\/\*\<bar>\/\/\)/s/^\(\s*\)#\(\s\)*define\s*\(\I[a-zA-Z_0-9(),]*\)\s*\(.\{-}\)\($\<Bar>\/\*\)/#\1\2define @\3@\4@\5/e<CR>:'a,.v/^\s*\(\/\*\<bar>\/\/\)/s/\($\<Bar>\*\/\)/@&/e<CR>'zk:call AlignMaps#StdAlign(1)<cr>'yjma'zk:'a,.v/^\s*\(\/\*\<bar>\/\/\)/s/ @//g<CR><SID>WE
+map <silent> <script> <Plug>AM_afnc		:<c-u>set lz<CR>:silent call AlignMaps#Afnc()<CR>:set nolz<CR>
+map <silent> <script> <Plug>AM_aunum	<SID>WS:'a,'zs/\%([0-9.]\)\s\+\zs\([-+.]\=\d\)/@\1/ge<CR>:'a,'zs/\(\(^\|\s\)\d\+\)\(\s\+\)@/\1@\3@/ge<CR>:'a,'zs/\.@/\.0@/ge<CR>:AlignCtrl wmp0P0r<CR>:'a,'zAlign [.@]<CR>:'a,'zs/@/ /ge<CR>:'a,'zs/\(\.\)\(\s\+\)\([0-9.,eE+]\+\)/\1\3\2/ge<CR>:'a,'zs/\([eE]\)\(\s\+\)\([0-9+\-+]\+\)/\1\3\2/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_aenum	<SID>WS:'a,'zs/\%([0-9.]\)\s\+\([-+]\=\d\)/\1@\2/ge<CR>:'a,'zs/\.@/\.0@/ge<CR>:AlignCtrl wmp0P0r<CR>:'a,'zAlign [,@]<CR>:'a,'zs/@/ /ge<CR>:'a,'zs/\(,\)\(\s\+\)\([-0-9.,eE+]\+\)/\1\3\2/ge<CR>:'a,'zs/\([eE]\)\(\s\+\)\([0-9+\-+]\+\)/\1\3\2/ge<CR><SID>WE
+
+" ---------------------------------------------------------------------
+" html table alignment	{{{2
+if !hasmapto('<Plug>AM_Htd')|map <unique> <Leader>Htd	<Plug>AM_Htd|endif
+map <silent> <script> <Plug>AM_Htd <SID>WS:'y,'zs%<[tT][rR]><[tT][dD][^>]\{-}>\<Bar></[tT][dD]><[tT][dD][^>]\{-}>\<Bar></[tT][dD]></[tT][rR]>%@&@%g<CR>'yjma'zk:AlignCtrl m=Ilp1P0 @<CR>:'a,.Align<CR>:'y,'zs/ @/@/<CR>:'y,'zs/@ <[tT][rR]>/<[tT][rR]>/ge<CR>:'y,'zs/@//ge<CR><SID>WE
+
+" ---------------------------------------------------------------------
+" character-based right-justified alignment maps {{{2
+if !hasmapto('<Plug>AM_T|')|map <unique> <Leader>T|		<Plug>AM_T||endif
+if !hasmapto('<Plug>AM_T#')	 |map <unique> <Leader>T#		<Plug>AM_T#|endif
+if !hasmapto('<Plug>AM_T,')	 |map <unique> <Leader>T,		<Plug>AM_T,o|endif
+if !hasmapto('<Plug>AM_Ts,') |map <unique> <Leader>Ts,		<Plug>AM_Ts,|endif
+if !hasmapto('<Plug>AM_T:')	 |map <unique> <Leader>T:		<Plug>AM_T:|endif
+if !hasmapto('<Plug>AM_T;')	 |map <unique> <Leader>T;		<Plug>AM_T;|endif
+if !hasmapto('<Plug>AM_T<')	 |map <unique> <Leader>T<		<Plug>AM_T<|endif
+if !hasmapto('<Plug>AM_T=')	 |map <unique> <Leader>T=		<Plug>AM_T=|endif
+if !hasmapto('<Plug>AM_T?')	 |map <unique> <Leader>T?		<Plug>AM_T?|endif
+if !hasmapto('<Plug>AM_T@')	 |map <unique> <Leader>T@		<Plug>AM_T@|endif
+if !hasmapto('<Plug>AM_Tab') |map <unique> <Leader>Tab		<Plug>AM_Tab|endif
+if !hasmapto('<Plug>AM_Tsp') |map <unique> <Leader>Tsp		<Plug>AM_Tsp|endif
+if !hasmapto('<Plug>AM_T~')	 |map <unique> <Leader>T~		<Plug>AM_T~|endif
+
+map <silent> <script> <Plug>AM_T| <SID>WS:AlignCtrl mIp0P0=r <Bar><CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_T#   <SID>WS:AlignCtrl mIp0P0=r #<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_T,   <SID>WS:AlignCtrl mIp0P1=r ,<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_Ts,  <SID>WS:AlignCtrl mIp0P1=r ,<CR>:'a,.Align<CR>:'a,.s/\(\s*\),/,\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_T:   <SID>WS:AlignCtrl mIp1P1=r :<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_T;   <SID>WS:AlignCtrl mIp0P0=r ;<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_T<   <SID>WS:AlignCtrl mIp0P0=r <<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_T=   <SID>WS:'a,'z-1s/\s\+\([*/+\-%<Bar>&\~^]\==\)/ \1/e<CR>:'a,'z-1s@ \+\([*/+\-%<Bar>&\~^]\)=@\1=@ge<CR>:'a,'z-1s/; */;@/e<CR>:'a,'z-1s/==/\="\<Char-0x0f>\<Char-0x0f>"/ge<CR>:'a,'z-1s/!=/\x="!\<Char-0x0f>"/ge<CR>:AlignCtrl mIp1P1=r = @<CR>:AlignCtrl g =<CR>:'a,'z-1Align<CR>:'a,'z-1s/; *@/;/e<CR>:'a,'z-1s/; *$/;/e<CR>:'a,'z-1s@\([*/+\-%<Bar>&\~^]\)\( \+\)=@\2\1=@ge<CR>:'a,'z-1s/\( \+\);/;\1/ge<CR>:'a,'z-1s/\xff/=/ge<CR><SID>WE:exe "norm <Plug>acom"
+map <silent> <script> <Plug>AM_T?   <SID>WS:AlignCtrl mIp0P0=r ?<CR>:'a,.Align<CR>:'y,'zs/ \( *\);/;\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_T@   <SID>WS:AlignCtrl mIp0P0=r @<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_Tab  <SID>WS:'a,.s/^\(\t*\)\(.*\)/\=submatch(1).escape(substitute(submatch(2),'\t','@','g'),'\')/<CR>:AlignCtrl mI=r @<CR>:'a,.Align<CR>:'y+1,'z-1s/@/ /g<CR><SID>WE
+map <silent> <script> <Plug>AM_Tsp  <SID>WS:'a,.s/^\(\s*\)\(.*\)/\=submatch(1).escape(substitute(submatch(2),'\s\+','@','g'),'\')/<CR>:AlignCtrl mI=r @<CR>:'a,.Align<CR>:'y+1,'z-1s/@/ /g<CR><SID>WE
+map <silent> <script> <Plug>AM_T~   <SID>WS:AlignCtrl mIp0P0=r ~<CR>:'a,.Align<CR>:'y,'zs/ \( *\);/;\1/ge<CR><SID>WE
+
+" ---------------------------------------------------------------------
+" character-based left-justified alignment maps {{{2
+if !hasmapto('<Plug>AM_t|')	|map <unique> <Leader>t|	<Plug>AM_t||endif
+if !hasmapto('<Plug>AM_t#')		|map <unique> <Leader>t#	<Plug>AM_t#|endif
+if !hasmapto('<Plug>AM_t,')		|map <unique> <Leader>t,	<Plug>AM_t,|endif
+if !hasmapto('<Plug>AM_t:')		|map <unique> <Leader>t:	<Plug>AM_t:|endif
+if !hasmapto('<Plug>AM_t;')		|map <unique> <Leader>t;	<Plug>AM_t;|endif
+if !hasmapto('<Plug>AM_t<')		|map <unique> <Leader>t<	<Plug>AM_t<|endif
+if !hasmapto('<Plug>AM_t=')		|map <unique> <Leader>t=	<Plug>AM_t=|endif
+if !hasmapto('<Plug>AM_ts,')	|map <unique> <Leader>ts,	<Plug>AM_ts,|endif
+if !hasmapto('<Plug>AM_ts:')	|map <unique> <Leader>ts:	<Plug>AM_ts:|endif
+if !hasmapto('<Plug>AM_ts;')	|map <unique> <Leader>ts;	<Plug>AM_ts;|endif
+if !hasmapto('<Plug>AM_ts<')	|map <unique> <Leader>ts<	<Plug>AM_ts<|endif
+if !hasmapto('<Plug>AM_ts=')	|map <unique> <Leader>ts=	<Plug>AM_ts=|endif
+if !hasmapto('<Plug>AM_w=')		|map <unique> <Leader>w=	<Plug>AM_w=|endif
+if !hasmapto('<Plug>AM_t?')		|map <unique> <Leader>t?	<Plug>AM_t?|endif
+if !hasmapto('<Plug>AM_t~')		|map <unique> <Leader>t~	<Plug>AM_t~|endif
+if !hasmapto('<Plug>AM_t@')		|map <unique> <Leader>t@	<Plug>AM_t@|endif
+if !hasmapto('<Plug>AM_m=')		|map <unique> <Leader>m=	<Plug>AM_m=|endif
+if !hasmapto('<Plug>AM_tab')	|map <unique> <Leader>tab	<Plug>AM_tab|endif
+if !hasmapto('<Plug>AM_tml')	|map <unique> <Leader>tml	<Plug>AM_tml|endif
+if !hasmapto('<Plug>AM_tsp')	|map <unique> <Leader>tsp	<Plug>AM_tsp|endif
+if !hasmapto('<Plug>AM_tsq')	|map <unique> <Leader>tsq	<Plug>AM_tsq|endif
+if !hasmapto('<Plug>AM_tt')		|map <unique> <Leader>tt	<Plug>AM_tt|endif
+
+map <silent> <script> <Plug>AM_t|		<SID>WS:AlignCtrl mIp0P0=l <Bar><CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_t#		<SID>WS:AlignCtrl mIp0P0=l #<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_t,		<SID>WS:AlignCtrl mIp0P1=l ,<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_t:		<SID>WS:AlignCtrl mIp1P1=l :<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_t;		<SID>WS:AlignCtrl mIp0P1=l ;<CR>:'a,.Align<CR>:sil 'y,'zs/\( *\);/;\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_t<		<SID>WS:AlignCtrl mIp0P0=l <<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_t=		<SID>WS:call AlignMaps#Equals()<CR><SID>WE
+map <silent> <script> <Plug>AM_ts,		<SID>WS:AlignCtrl mIp0P1=l #<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\)#/,\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_ts,		<SID>WS:AlignCtrl mIp0P1=l ,<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\),/,\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_ts:		<SID>WS:AlignCtrl mIp1P1=l :<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\):/:\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_ts;		<SID>WS:AlignCtrl mIp1P1=l ;<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\);/;\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_ts<		<SID>WS:AlignCtrl mIp1P1=l <<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\)</<\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_ts=		<SID>WS:AlignCtrl mIp1P1=l =<CR>:'a,.Align<CR>:sil 'y+1,'z-1s/\(\s*\)=/=\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_w=		<SID>WS:'a,'zg/=/s/\s\+\([*/+\-%<Bar>&\~^]\==\)/ \1/e<CR>:'a,'zg/=/s@ \+\([*/+\-%<Bar>&\~^]\)=@\1=@ge<CR>:'a,'zg/=/s/==/\="\<Char-0x0f>\<Char-0x0f>"/ge<CR>:'a,'zg/=/s/!=/\="!\<Char-0x0f>"/ge<CR>'zk:AlignCtrl mWp1P1=l =<CR>:AlignCtrl g =<CR>:'a,'z-1g/=/Align<CR>:'a,'z-1g/=/s@\([*/+\-%<Bar>&\~^!=]\)\( \+\)=@\2\1=@ge<CR>:'a,'z-1g/=/s/\( \+\);/;\1/ge<CR>:'a,'z-1v/^\s*\/[*/]/s/\/[*/]/@&@/e<CR>:'a,'z-1v/^\s*\/[*/]/s/\*\//@&/e<CR>'zk:call AlignMaps#StdAlign(1)<cr>:'y,'zs/^\(\s*\) @/\1/e<CR>:'a,'z-1g/=/s/\xff/=/ge<CR>:'y,'zg/=/s/ @//eg<CR><SID>WE
+map <silent> <script> <Plug>AM_t?		<SID>WS:AlignCtrl mIp0P0=l ?<CR>:'a,.Align<CR>:.,'zs/ \( *\);/;\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_t~		<SID>WS:AlignCtrl mIp0P0=l ~<CR>:'a,.Align<CR>:'y,'zs/ \( *\);/;\1/ge<CR><SID>WE
+map <silent> <script> <Plug>AM_t@		<SID>WS::call AlignMaps#StdAlign(1)<cr>:<SID>WE
+map <silent> <script> <Plug>AM_m=		<SID>WS:'a,'zs/\s\+\([*/+\-%<Bar>&\~^]\==\)/ \1/e<CR>:'a,'zs@ \+\([*/+\-%<Bar>&\~^]\)=@\1=@ge<CR>:'a,'zs/==/\="\<Char-0x0f>\<Char-0x0f>"/ge<CR>:'a,'zs/!=/\="!\<Char-0x0f>"/ge<CR>'zk:AlignCtrl mIp1P1=l =<CR>:AlignCtrl g =<CR>:'a,'z-1Align<CR>:'a,'z-1s@\([*/+\-%<Bar>&\~^!=]\)\( \+\)=@\2\1=@ge<CR>:'a,'z-1s/\( \+\);/;\1/ge<CR>:'a,'z-s/%\ze[^=]/ @%@ /e<CR>'zk:call AlignMaps#StdAlign(1)<cr>:'y,'zs/^\(\s*\) @/\1/e<CR>:'a,'z-1s/\xff/=/ge<CR>:'y,'zs/ @//eg<CR><SID>WE
+map <silent> <script> <Plug>AM_tab		<SID>WS:'a,.s/^\(\t*\)\(.*\)$/\=submatch(1).escape(substitute(submatch(2),'\t',"\<Char-0x0f>",'g'),'\')/<CR>:if &ts == 1<bar>exe "AlignCtrl mI=lp0P0 \<Char-0x0f>"<bar>else<bar>exe "AlignCtrl mI=l \<Char-0x0f>"<bar>endif<CR>:'a,.Align<CR>:exe "'y+1,'z-1s/\<Char-0x0f>/".((&ts == 1)? '\t' : ' ')."/g"<CR><SID>WE
+map <silent> <script> <Plug>AM_tml		<SID>WS:AlignCtrl mWp1P0=l \\\@<!\\\s*$<CR>:'a,.Align<CR><SID>WE
+map <silent> <script> <Plug>AM_tsp		<SID>WS:'a,.s/^\(\s*\)\(.*\)/\=submatch(1).escape(substitute(submatch(2),'\s\+','@','g'),'\')/<CR>:AlignCtrl mI=lp0P0 @<CR>:'a,.Align<CR>:'y+1,'z-1s/@/ /g<CR><SID>WE
+map <silent> <script> <Plug>AM_tsq		<SID>WS:'a,.AlignReplaceQuotedSpaces<CR>:'a,.s/^\(\s*\)\(.*\)/\=submatch(1).substitute(submatch(2),'\s\+','@','g')/<CR>:AlignCtrl mIp0P0=l @<CR>:'a,.Align<CR>:'y+1,'z-1s/[%@]/ /g<CR><SID>WE
+map <silent> <script> <Plug>AM_tt		<SID>WS:AlignCtrl mIp1P1=l \\\@<!& \\\\<CR>:'a,.Align<CR><SID>WE
+
+" =====================================================================
+" Menu Support: {{{1
+"   ma ..move.. use menu
+"   v V or ctrl-v ..move.. use menu
+if has("menu") && has("gui_running") && &go =~ 'm' && !exists("s:firstmenu")
+ let s:firstmenu= 1
+ if !exists("g:DrChipTopLvlMenu")
+  let g:DrChipTopLvlMenu= "DrChip."
+ endif
+ if g:DrChipTopLvlMenu != ""
+  let s:mapleader = exists("g:mapleader")? g:mapleader : '\'
+  let s:emapleader= escape(s:mapleader,'\ ')
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.<<\ and\ >><tab>'.s:emapleader.'a<	'.s:mapleader.'a<'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Assignment\ =<tab>'.s:emapleader.'t=	'.s:mapleader.'t='
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Assignment\ :=<tab>'.s:emapleader.'a=	'.s:mapleader.'a='
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Backslashes<tab>'.s:emapleader.'tml	'.s:mapleader.'tml'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Breakup\ Comma\ Declarations<tab>'.s:emapleader.'a,	'.s:mapleader.'a,'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.C\ Comment\ Box<tab>'.s:emapleader.'abox	'.s:mapleader.'abox'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Commas<tab>'.s:emapleader.'t,	'.s:mapleader.'t,'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Commas<tab>'.s:emapleader.'ts,	'.s:mapleader.'ts,'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Commas\ With\ Strings<tab>'.s:emapleader.'tsq	'.s:mapleader.'tsq'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Comments<tab>'.s:emapleader.'acom	'.s:mapleader.'acom'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Comments\ Only<tab>'.s:emapleader.'aocom	'.s:mapleader.'aocom'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Declaration\ Comments<tab>'.s:emapleader.'adcom	'.s:mapleader.'adcom'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Declarations<tab>'.s:emapleader.'adec	'.s:mapleader.'adec'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Definitions<tab>'.s:emapleader.'adef	'.s:mapleader.'adef'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Function\ Header<tab>'.s:emapleader.'afnc	'.s:mapleader.'afnc'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Html\ Tables<tab>'.s:emapleader.'Htd	'.s:mapleader.'Htd'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.(\.\.\.)?\.\.\.\ :\ \.\.\.<tab>'.s:emapleader.'a?	'.s:mapleader.'a?'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Numbers<tab>'.s:emapleader.'anum	'.s:mapleader.'anum'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Numbers\ (American-Style)<tab>'.s:emapleader.'aunum	<Leader>aunum	'.s:mapleader.'aunum	<Leader>aunum'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Numbers\ (Euro-Style)<tab>'.s:emapleader.'aenum	'.s:mapleader.'aenum'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Spaces\ (Left\ Justified)<tab>'.s:emapleader.'tsp	'.s:mapleader.'tsp'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Spaces\ (Right\ Justified)<tab>'.s:emapleader.'Tsp	'.s:mapleader.'Tsp'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Statements\ With\ Percent\ Style\ Comments<tab>'.s:emapleader.'m=	'.s:mapleader.'m='
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Symbol\ <<tab>'.s:emapleader.'t<	'.s:mapleader.'t<'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Symbol\ \|<tab>'.s:emapleader.'t\|	'.s:mapleader.'t|'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Symbol\ @<tab>'.s:emapleader.'t@	'.s:mapleader.'t@'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Symbol\ #<tab>'.s:emapleader.'t#	'.s:mapleader.'t#'
+  exe 'menu '.g:DrChipTopLvlMenu.'AlignMaps.Tabs<tab>'.s:emapleader.'tab	'.s:mapleader.'tab'
+  unlet s:mapleader
+  unlet s:emapleader
+ endif
+endif
+
+" =====================================================================
+"  Restore: {{{1
+let &cpo= s:keepcpo
+unlet s:keepcpo
+
+" ==============================================================================
+"  Modelines: {{{1
+" vim: ts=4 nowrap fdm=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim	(revision 18231)
@@ -0,0 +1,41 @@
+" AlignPlugin: tool to align multiple fields based on one or more separators
+"   Author:	 Charles E. Campbell, Jr.
+"   Date:    Nov 02, 2008
+" GetLatestVimScripts: 294 1 :AutoInstall: Align.vim
+" GetLatestVimScripts: 1066 1 :AutoInstall: cecutil.vim
+" Copyright:    Copyright (C) 1999-2007 Charles E. Campbell, Jr. {{{1
+"               Permission is hereby granted to use and distribute this code,
+"               with or without modifications, provided that this copyright
+"               notice is copied with it. Like anything else that's free,
+"               Align.vim is provided *as is* and comes with no warranty
+"               of any kind, either expressed or implied. By using this
+"               plugin, you agree that in no event will the copyright
+"               holder be liable for any damages resulting from the use
+"               of this software.
+"
+" Romans 1:16,17a : For I am not ashamed of the gospel of Christ, for it is {{{1
+" the power of God for salvation for everyone who believes; for the Jew first,
+" and also for the Greek.  For in it is revealed God's righteousness from
+" faith to faith.
+" ---------------------------------------------------------------------
+" Load Once: {{{1
+if &cp || exists("g:loaded_AlignPlugin")
+ finish
+endif
+let g:loaded_AlignPlugin = "v35"
+let s:keepcpo            = &cpo
+set cpo&vim
+
+" ---------------------------------------------------------------------
+" Public Interface: {{{1
+com! -bang -range -nargs=* Align <line1>,<line2>call Align#Align(<bang>0,<q-args>)
+com!       -range -nargs=0 AlignReplaceQuotedSpaces <line1>,<line2>call Align#AlignReplaceQuotedSpaces()
+com!              -nargs=* AlignCtrl call Align#AlignCtrl(<q-args>)
+com!              -nargs=0 AlignPush call Align#AlignPush()
+com!              -nargs=0 AlignPop  call Align#AlignPop()
+
+" ---------------------------------------------------------------------
+"  Restore: {{{1
+let &cpo= s:keepcpo
+unlet s:keepcpo
+" vim: ts=4 fdm=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/cecutil.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/cecutil.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/cecutil.vim	(revision 18231)
@@ -0,0 +1,510 @@
+" cecutil.vim : save/restore window position
+"               save/restore mark position
+"               save/restore selected user maps
+"  Author:	Charles E. Campbell, Jr.
+"  Version:	18b	ASTRO-ONLY
+"  Date:	Aug 27, 2008
+"
+"  Saving Restoring Destroying Marks: {{{1
+"       call SaveMark(markname)       let savemark= SaveMark(markname)
+"       call RestoreMark(markname)    call RestoreMark(savemark)
+"       call DestroyMark(markname)
+"       commands: SM RM DM
+"
+"  Saving Restoring Destroying Window Position: {{{1
+"       call SaveWinPosn()        let winposn= SaveWinPosn()
+"       call RestoreWinPosn()     call RestoreWinPosn(winposn)
+"		\swp : save current window/buffer's position
+"		\rwp : restore current window/buffer's previous position
+"       commands: SWP RWP
+"
+"  Saving And Restoring User Maps: {{{1
+"       call SaveUserMaps(mapmode,maplead,mapchx,suffix)
+"       call RestoreUserMaps(suffix)
+"
+" GetLatestVimScripts: 1066 1 :AutoInstall: cecutil.vim
+"
+" You believe that God is one. You do well. The demons also {{{1
+" believe, and shudder. But do you want to know, vain man, that
+" faith apart from works is dead?  (James 2:19,20 WEB)
+
+" ---------------------------------------------------------------------
+" Load Once: {{{1
+if &cp || exists("g:loaded_cecutil")
+ finish
+endif
+let g:loaded_cecutil = "v18b"
+let s:keepcpo        = &cpo
+set cpo&vim
+"DechoTabOn
+
+" =======================
+"  Public Interface: {{{1
+" =======================
+
+" ---------------------------------------------------------------------
+"  Map Interface: {{{2
+if !hasmapto('<Plug>SaveWinPosn')
+ map <unique> <Leader>swp <Plug>SaveWinPosn
+endif
+if !hasmapto('<Plug>RestoreWinPosn')
+ map <unique> <Leader>rwp <Plug>RestoreWinPosn
+endif
+nmap <silent> <Plug>SaveWinPosn		:call SaveWinPosn()<CR>
+nmap <silent> <Plug>RestoreWinPosn	:call RestoreWinPosn()<CR>
+
+" ---------------------------------------------------------------------
+" Command Interface: {{{2
+com! -bar -nargs=0 SWP	call SaveWinPosn()
+com! -bar -nargs=0 RWP	call RestoreWinPosn()
+com! -bar -nargs=1 SM	call SaveMark(<q-args>)
+com! -bar -nargs=1 RM	call RestoreMark(<q-args>)
+com! -bar -nargs=1 DM	call DestroyMark(<q-args>)
+
+if v:version < 630
+ let s:modifier= "sil "
+else
+ let s:modifier= "sil keepj "
+endif
+
+" ===============
+" Functions: {{{1
+" ===============
+
+" ---------------------------------------------------------------------
+" SaveWinPosn: {{{2
+"    let winposn= SaveWinPosn()  will save window position in winposn variable
+"    call SaveWinPosn()          will save window position in b:cecutil_winposn{b:cecutil_iwinposn}
+"    let winposn= SaveWinPosn(0) will *only* save window position in winposn variable (no stacking done)
+fun! SaveWinPosn(...)
+"  call Dfunc("SaveWinPosn() a:0=".a:0)
+  if line(".") == 1 && getline(1) == ""
+"   call Dfunc("SaveWinPosn : empty buffer")
+   return ""
+  endif
+  let so_keep   = &l:so
+  let siso_keep = &siso
+  let ss_keep   = &l:ss
+  setlocal so=0 siso=0 ss=0
+
+  let swline    = line(".")
+  let swcol     = col(".")
+  let swwline   = winline() - 1
+  let swwcol    = virtcol(".") - wincol()
+  let savedposn = "call GoWinbufnr(".winbufnr(0).")|silent ".swline
+  let savedposn = savedposn."|".s:modifier."norm! 0z\<cr>"
+  if swwline > 0
+   let savedposn= savedposn.":".s:modifier."norm! ".swwline."\<c-y>\<cr>"
+  endif
+  if swwcol > 0
+   let savedposn= savedposn.":".s:modifier."norm! 0".swwcol."zl\<cr>"
+  endif
+  let savedposn = savedposn.":".s:modifier."call cursor(".swline.",".swcol.")\<cr>"
+
+  " save window position in
+  " b:cecutil_winposn_{iwinposn} (stack)
+  " only when SaveWinPosn() is used
+  if a:0 == 0
+   if !exists("b:cecutil_iwinposn")
+   	let b:cecutil_iwinposn= 1
+   else
+   	let b:cecutil_iwinposn= b:cecutil_iwinposn + 1
+   endif
+"   call Decho("saving posn to SWP stack")
+   let b:cecutil_winposn{b:cecutil_iwinposn}= savedposn
+  endif
+
+  let &l:so = so_keep
+  let &siso = siso_keep
+  let &l:ss = ss_keep
+
+"  if exists("b:cecutil_iwinposn")	 " Decho
+"   call Decho("b:cecutil_winpos{".b:cecutil_iwinposn."}[".b:cecutil_winposn{b:cecutil_iwinposn}."]")
+"  else                      " Decho
+"   call Decho("b:cecutil_iwinposn doesn't exist")
+"  endif                     " Decho
+"  call Dret("SaveWinPosn [".savedposn."]")
+  return savedposn
+endfun
+
+" ---------------------------------------------------------------------
+" RestoreWinPosn: {{{2
+"      call RestoreWinPosn()
+"      call RestoreWinPosn(winposn)
+fun! RestoreWinPosn(...)
+"  call Dfunc("RestoreWinPosn() a:0=".a:0)
+"  call Decho("getline(1)<".getline(1).">")
+"  call Decho("line(.)=".line("."))
+  if line(".") == 1 && getline(1) == ""
+"   call Dfunc("RestoreWinPosn : empty buffer")
+   return ""
+  endif
+  let so_keep   = &l:so
+  let siso_keep = &l:siso
+  let ss_keep   = &l:ss
+  setlocal so=0 siso=0 ss=0
+
+  if a:0 == 0 || a:1 == ""
+   " use saved window position in b:cecutil_winposn{b:cecutil_iwinposn} if it exists
+   if exists("b:cecutil_iwinposn") && exists("b:cecutil_winposn{b:cecutil_iwinposn}")
+"   	call Decho("using stack b:cecutil_winposn{".b:cecutil_iwinposn."}<".b:cecutil_winposn{b:cecutil_iwinposn}.">")
+	try
+     exe "silent! ".b:cecutil_winposn{b:cecutil_iwinposn}
+	catch /^Vim\%((\a\+)\)\=:E749/
+	 " ignore empty buffer error messages
+	endtry
+    " normally drop top-of-stack by one
+    " but while new top-of-stack doesn't exist
+    " drop top-of-stack index by one again
+	if b:cecutil_iwinposn >= 1
+	 unlet b:cecutil_winposn{b:cecutil_iwinposn}
+	 let b:cecutil_iwinposn= b:cecutil_iwinposn - 1
+	 while b:cecutil_iwinposn >= 1 && !exists("b:cecutil_winposn{b:cecutil_iwinposn}")
+	  let b:cecutil_iwinposn= b:cecutil_iwinposn - 1
+	 endwhile
+	 if b:cecutil_iwinposn < 1
+	  unlet b:cecutil_iwinposn
+	 endif
+	endif
+   else
+   	echohl WarningMsg
+	echomsg "***warning*** need to SaveWinPosn first!"
+	echohl None
+   endif
+
+  else	 " handle input argument
+"   call Decho("using input a:1<".a:1.">")
+   " use window position passed to this function
+   exe "silent ".a:1
+   " remove a:1 pattern from b:cecutil_winposn{b:cecutil_iwinposn} stack
+   if exists("b:cecutil_iwinposn")
+    let jwinposn= b:cecutil_iwinposn
+    while jwinposn >= 1                     " search for a:1 in iwinposn..1
+        if exists("b:cecutil_winposn{jwinposn}")    " if it exists
+         if a:1 == b:cecutil_winposn{jwinposn}      " and the pattern matches
+       unlet b:cecutil_winposn{jwinposn}            " unlet it
+       if jwinposn == b:cecutil_iwinposn            " if at top-of-stack
+        let b:cecutil_iwinposn= b:cecutil_iwinposn - 1      " drop stacktop by one
+       endif
+      endif
+     endif
+     let jwinposn= jwinposn - 1
+    endwhile
+   endif
+  endif
+
+  " Seems to be something odd: vertical motions after RWP
+  " cause jump to first column.  The following fixes that.
+  " Note: was using wincol()>1, but with signs, a cursor
+  " at column 1 yields wincol()==3.  Beeping ensued.
+  if virtcol('.') > 1
+   silent norm! hl
+  elseif virtcol(".") < virtcol("$")
+   silent norm! lh
+  endif
+
+  let &l:so   = so_keep
+  let &l:siso = siso_keep
+  let &l:ss   = ss_keep
+
+"  call Dret("RestoreWinPosn")
+endfun
+
+" ---------------------------------------------------------------------
+" GoWinbufnr: go to window holding given buffer (by number) {{{2
+"   Prefers current window; if its buffer number doesn't match,
+"   then will try from topleft to bottom right
+fun! GoWinbufnr(bufnum)
+"  call Dfunc("GoWinbufnr(".a:bufnum.")")
+  if winbufnr(0) == a:bufnum
+"   call Dret("GoWinbufnr : winbufnr(0)==a:bufnum")
+   return
+  endif
+  winc t
+  let first=1
+  while winbufnr(0) != a:bufnum && (first || winnr() != 1)
+  	winc w
+	let first= 0
+   endwhile
+"  call Dret("GoWinbufnr")
+endfun
+
+" ---------------------------------------------------------------------
+" SaveMark: sets up a string saving a mark position. {{{2
+"           For example, SaveMark("a")
+"           Also sets up a global variable, g:savemark_{markname}
+fun! SaveMark(markname)
+"  call Dfunc("SaveMark(markname<".a:markname.">)")
+  let markname= a:markname
+  if strpart(markname,0,1) !~ '\a'
+   let markname= strpart(markname,1,1)
+  endif
+"  call Decho("markname=".markname)
+
+  let lzkeep  = &lz
+  set lz
+
+  if 1 <= line("'".markname) && line("'".markname) <= line("$")
+   let winposn               = SaveWinPosn(0)
+   exe s:modifier."norm! `".markname
+   let savemark              = SaveWinPosn(0)
+   let g:savemark_{markname} = savemark
+   let savemark              = markname.savemark
+   call RestoreWinPosn(winposn)
+  else
+   let g:savemark_{markname} = ""
+   let savemark              = ""
+  endif
+
+  let &lz= lzkeep
+
+"  call Dret("SaveMark : savemark<".savemark.">")
+  return savemark
+endfun
+
+" ---------------------------------------------------------------------
+" RestoreMark: {{{2
+"   call RestoreMark("a")  -or- call RestoreMark(savemark)
+fun! RestoreMark(markname)
+"  call Dfunc("RestoreMark(markname<".a:markname.">)")
+
+  if strlen(a:markname) <= 0
+"   call Dret("RestoreMark : no such mark")
+   return
+  endif
+  let markname= strpart(a:markname,0,1)
+  if markname !~ '\a'
+   " handles 'a -> a styles
+   let markname= strpart(a:markname,1,1)
+  endif
+"  call Decho("markname=".markname." strlen(a:markname)=".strlen(a:markname))
+
+  let lzkeep  = &lz
+  set lz
+  let winposn = SaveWinPosn(0)
+
+  if strlen(a:markname) <= 2
+   if exists("g:savemark_{markname}") && strlen(g:savemark_{markname}) != 0
+	" use global variable g:savemark_{markname}
+"	call Decho("use savemark list")
+	call RestoreWinPosn(g:savemark_{markname})
+	exe "norm! m".markname
+   endif
+  else
+   " markname is a savemark command (string)
+"	call Decho("use savemark command")
+   let markcmd= strpart(a:markname,1)
+   call RestoreWinPosn(markcmd)
+   exe "norm! m".markname
+  endif
+
+  call RestoreWinPosn(winposn)
+  let &lz       = lzkeep
+
+"  call Dret("RestoreMark")
+endfun
+
+" ---------------------------------------------------------------------
+" DestroyMark: {{{2
+"   call DestroyMark("a")  -- destroys mark
+fun! DestroyMark(markname)
+"  call Dfunc("DestroyMark(markname<".a:markname.">)")
+
+  " save options and set to standard values
+  let reportkeep= &report
+  let lzkeep    = &lz
+  set lz report=10000
+
+  let markname= strpart(a:markname,0,1)
+  if markname !~ '\a'
+   " handles 'a -> a styles
+   let markname= strpart(a:markname,1,1)
+  endif
+"  call Decho("markname=".markname)
+
+  let curmod  = &mod
+  let winposn = SaveWinPosn(0)
+  1
+  let lineone = getline(".")
+  exe "k".markname
+  d
+  put! =lineone
+  let &mod    = curmod
+  call RestoreWinPosn(winposn)
+
+  " restore options to user settings
+  let &report = reportkeep
+  let &lz     = lzkeep
+
+"  call Dret("DestroyMark")
+endfun
+
+" ---------------------------------------------------------------------
+" QArgSplitter: to avoid \ processing by <f-args>, <q-args> is needed. {{{2
+" However, <q-args> doesn't split at all, so this one returns a list
+" with splits at all whitespace (only!), plus a leading length-of-list.
+" The resulting list:  qarglist[0] corresponds to a:0
+"                      qarglist[i] corresponds to a:{i}
+fun! QArgSplitter(qarg)
+"  call Dfunc("QArgSplitter(qarg<".a:qarg.">)")
+  let qarglist    = split(a:qarg)
+  let qarglistlen = len(qarglist)
+  let qarglist    = insert(qarglist,qarglistlen)
+"  call Dret("QArgSplitter ".string(qarglist))
+  return qarglist
+endfun
+
+" ---------------------------------------------------------------------
+" ListWinPosn: {{{2
+"fun! ListWinPosn()                                                        " Decho 
+"  if !exists("b:cecutil_iwinposn") || b:cecutil_iwinposn == 0             " Decho 
+"   call Decho("nothing on SWP stack")                                     " Decho
+"  else                                                                    " Decho
+"   let jwinposn= b:cecutil_iwinposn                                       " Decho 
+"   while jwinposn >= 1                                                    " Decho 
+"    if exists("b:cecutil_winposn{jwinposn}")                              " Decho 
+"     call Decho("winposn{".jwinposn."}<".b:cecutil_winposn{jwinposn}.">") " Decho 
+"    else                                                                  " Decho 
+"     call Decho("winposn{".jwinposn."} -- doesn't exist")                 " Decho 
+"    endif                                                                 " Decho 
+"    let jwinposn= jwinposn - 1                                            " Decho 
+"   endwhile                                                               " Decho 
+"  endif                                                                   " Decho
+"endfun                                                                    " Decho 
+"com! -nargs=0 LWP	call ListWinPosn()                                    " Decho 
+
+" ---------------------------------------------------------------------
+" SaveUserMaps: this function sets up a script-variable (s:restoremap) {{{2
+"          which can be used to restore user maps later with
+"          call RestoreUserMaps()
+"
+"          mapmode - see :help maparg for details (n v o i c l "")
+"                    ex. "n" = Normal
+"                    The letters "b" and "u" are optional prefixes;
+"                    The "u" means that the map will also be unmapped
+"                    The "b" means that the map has a <buffer> qualifier
+"                    ex. "un"  = Normal + unmapping
+"                    ex. "bn"  = Normal + <buffer>
+"                    ex. "bun" = Normal + <buffer> + unmapping
+"                    ex. "ubn" = Normal + <buffer> + unmapping
+"          maplead - see mapchx
+"          mapchx  - "<something>" handled as a single map item.
+"                    ex. "<left>"
+"                  - "string" a string of single letters which are actually
+"                    multiple two-letter maps (using the maplead:
+"                    maplead . each_character_in_string)
+"                    ex. maplead="\" and mapchx="abc" saves user mappings for
+"                        \a, \b, and \c
+"                    Of course, if maplead is "", then for mapchx="abc",
+"                    mappings for a, b, and c are saved.
+"                  - :something  handled as a single map item, w/o the ":"
+"                    ex.  mapchx= ":abc" will save a mapping for "abc"
+"          suffix  - a string unique to your plugin
+"                    ex.  suffix= "DrawIt"
+fun! SaveUserMaps(mapmode,maplead,mapchx,suffix)
+"  call Dfunc("SaveUserMaps(mapmode<".a:mapmode."> maplead<".a:maplead."> mapchx<".a:mapchx."> suffix<".a:suffix.">)")
+
+  if !exists("s:restoremap_{a:suffix}")
+   " initialize restoremap_suffix to null string
+   let s:restoremap_{a:suffix}= ""
+  endif
+
+  " set up dounmap: if 1, then save and unmap  (a:mapmode leads with a "u")
+  "                 if 0, save only
+  let mapmode  = a:mapmode
+  let dounmap  = 0
+  let dobuffer = ""
+  while mapmode =~ '^[bu]'
+   if     mapmode =~ '^u'
+    let dounmap= 1
+    let mapmode= strpart(a:mapmode,1)
+   elseif mapmode =~ '^b'
+    let dobuffer= "<buffer> "
+    let mapmode= strpart(a:mapmode,1)
+   endif
+  endwhile
+"  call Decho("dounmap=".dounmap."  dobuffer<".dobuffer.">")
+ 
+  " save single map :...something...
+  if strpart(a:mapchx,0,1) == ':'
+"   call Decho("save single map :...something...")
+   let amap= strpart(a:mapchx,1)
+   if amap == "|" || amap == "\<c-v>"
+    let amap= "\<c-v>".amap
+   endif
+   let amap                    = a:maplead.amap
+   let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|:silent! ".mapmode."unmap ".dobuffer.amap
+   if maparg(amap,mapmode) != ""
+    let maprhs                  = substitute(maparg(amap,mapmode),'|','<bar>','ge')
+	let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|:".mapmode."map ".dobuffer.amap." ".maprhs
+   endif
+   if dounmap
+	exe "silent! ".mapmode."unmap ".dobuffer.amap
+   endif
+ 
+  " save single map <something>
+  elseif strpart(a:mapchx,0,1) == '<'
+"   call Decho("save single map <something>")
+   let amap       = a:mapchx
+   if amap == "|" || amap == "\<c-v>"
+    let amap= "\<c-v>".amap
+"	call Decho("amap[[".amap."]]")
+   endif
+   let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|silent! ".mapmode."unmap ".dobuffer.amap
+   if maparg(a:mapchx,mapmode) != ""
+    let maprhs                  = substitute(maparg(amap,mapmode),'|','<bar>','ge')
+	let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|".mapmode."map ".amap." ".dobuffer.maprhs
+   endif
+   if dounmap
+	exe "silent! ".mapmode."unmap ".dobuffer.amap
+   endif
+ 
+  " save multiple maps
+  else
+"   call Decho("save multiple maps")
+   let i= 1
+   while i <= strlen(a:mapchx)
+    let amap= a:maplead.strpart(a:mapchx,i-1,1)
+	if amap == "|" || amap == "\<c-v>"
+	 let amap= "\<c-v>".amap
+	endif
+	let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|silent! ".mapmode."unmap ".dobuffer.amap
+    if maparg(amap,mapmode) != ""
+     let maprhs                  = substitute(maparg(amap,mapmode),'|','<bar>','ge')
+	 let s:restoremap_{a:suffix} = s:restoremap_{a:suffix}."|".mapmode."map ".amap." ".dobuffer.maprhs
+    endif
+	if dounmap
+	 exe "silent! ".mapmode."unmap ".dobuffer.amap
+	endif
+    let i= i + 1
+   endwhile
+  endif
+"  call Dret("SaveUserMaps : restoremap_".a:suffix.": ".s:restoremap_{a:suffix})
+endfun
+
+" ---------------------------------------------------------------------
+" RestoreUserMaps: {{{2
+"   Used to restore user maps saved by SaveUserMaps()
+fun! RestoreUserMaps(suffix)
+"  call Dfunc("RestoreUserMaps(suffix<".a:suffix.">)")
+  if exists("s:restoremap_{a:suffix}")
+   let s:restoremap_{a:suffix}= substitute(s:restoremap_{a:suffix},'|\s*$','','e')
+   if s:restoremap_{a:suffix} != ""
+"   	call Decho("exe ".s:restoremap_{a:suffix})
+    exe "silent! ".s:restoremap_{a:suffix}
+   endif
+   unlet s:restoremap_{a:suffix}
+  endif
+"  call Dret("RestoreUserMaps")
+endfun
+
+" ==============
+"  Restore: {{{1
+" ==============
+let &cpo= s:keepcpo
+unlet s:keepcpo
+
+" ================
+"  Modelines: {{{1
+" ================
+" vim: ts=4 fdm=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/file_line.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 18231)
@@ -0,0 +1,51 @@
+" Avoid installing twice or when in unsupported Vim version.
+if exists('g:loaded_file_line') || (v:version < 700)
+	finish
+endif
+let g:loaded_file_line = 1
+
+function! s:gotoline()
+	let file = bufname("%")
+
+	" :e command calls BufRead even though the file is a new one.
+	" As a workarround Jonas Pfenniger<jonas@pfenniger.name> added an
+	" AutoCmd BufRead, this will test if this file actually exists before
+	" searching for a file and line to goto.
+	if (filereadable(file))
+		return
+	endif
+
+	" Accept file:line:column: or file:line:column and file:line also
+	let nocol = 0
+	let names =  matchlist( file, '\(.\{-1,}\):\%(\(\d\+\)\%(:\(\d*\):\?\)\?\)\?$')
+
+	if empty(names)
+		"no column provided maybe?
+		let names =  matchlist( file, '\(.*\):\(\d\+\)')
+		let nocol = 1
+		if empty(names)
+			return
+		endif
+	endif
+
+	let file_name =  names[1]
+	let line_num  =  names[2] == ''? '0' : names[2]
+	let  col_num  = (names[3] == '' && !nocol) ? '0' : names[3]
+
+	if filereadable(file_name)
+		let l:bufn = bufnr("%")
+		exec ":bwipeout " l:bufn
+
+		exec "keepalt edit " . file_name
+		exec ":" . line_num
+		exec "normal! " . col_num . '|'
+		if foldlevel(line_num) > 0
+			exec "normal! zv"
+		endif
+
+		exec "normal! zz"
+	endif
+endfunction
+
+autocmd! BufNewFile *:* nested call s:gotoline()
+autocmd! BufRead *:* nested call s:gotoline()
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/issmfolds.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/issmfolds.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/issmfolds.vim	(revision 18231)
@@ -0,0 +1,45 @@
+function! IssmFoldText()
+
+	" Get line {{{
+	let line = getline(v:foldstart)
+	"let line = line . '--'
+	"}}}
+	" remove the marker that caused this fold from the display {{{
+	let foldmarkers = split(&foldmarker,',')
+	let line = substitute(line, '\V' .  foldmarkers[0] . '\%(\d\+\)\?', ' ', '')
+	" }}}
+	" remove comments that vim knows about {{{
+	let comment = split(&commentstring, '%s')
+	if comment[0] != ''
+		let comment_begin = comment[0]
+		let comment_end = ''
+		if len(comment) > 1
+			let comment_end = comment[1]
+		end
+		let pattern = '\V' .  comment_begin .  '\s\*' .  comment_end .  '\s\*\$'
+		if line =~ pattern
+			let line = substitute(line, pattern, ' ', '')
+		else
+			let line = substitute(line, '.*\V' .  comment_begin, ' ', '')
+			if comment_end != ''
+				let line = substitute(line, '\V' .  comment_end, ' ', '')
+			endif
+		endif
+	endif
+	" }}}
+	" remove any remaining leading or trailing whitespace {{{
+	"let line = substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '')
+	let line = substitute(line, '^\s*%\(.\{-}\)\s*$', '\1', '') "Also remove % in matlab comments
+	" }}}
+	" align everything, and pad the end of the display with - {{{
+	let alignment = &columns - 18 - v:foldlevel
+	let line = strpart(printf('%-'.alignment.'s',line),0,alignment)
+	"let line = substitute(line, '\%( \)\@<= \%( *$\)\@=', '-', 'g') " ->dashes
+	let line = substitute(line, '\%( \)\@<= \%( *$\)\@=',' ', 'g')  " ->white spaces
+	" }}}
+	" format the line count {{{
+	let cnt = printf('%13s','('.(v:foldend - v:foldstart + 1) .' lines) ')
+	" }}}
+	return '+-'.v:folddashes.' '.line.cnt
+
+endfunction
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/matchit.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/matchit.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/matchit.vim	(revision 18231)
@@ -0,0 +1,812 @@
+"  matchit.vim: (global plugin) Extended "%" matching
+"  Last Change: Fri Jan 25 10:00 AM 2008 EST
+"  Maintainer:  Benji Fisher PhD   <benji@member.AMS.org>
+"  Version:     1.13.2, for Vim 6.3+
+"  URL:		http://www.vim.org/script.php?script_id=39
+
+" Documentation:
+"  The documentation is in a separate file, matchit.txt .
+
+" Credits:
+"  Vim editor by Bram Moolenaar (Thanks, Bram!)
+"  Original script and design by Raul Segura Acevedo
+"  Support for comments by Douglas Potts
+"  Support for back references and other improvements by Benji Fisher
+"  Support for many languages by Johannes Zellner
+"  Suggestions for improvement, bug reports, and support for additional
+"  languages by Jordi-Albert Batalla, Neil Bird, Servatius Brandt, Mark
+"  Collett, Stephen Wall, Dany St-Amant, Yuheng Xie, and Johannes Zellner.
+
+" Debugging:
+"  If you'd like to try the built-in debugging commands...
+"   :MatchDebug      to activate debugging for the current buffer
+"  This saves the values of several key script variables as buffer-local
+"  variables.  See the MatchDebug() function, below, for details.
+
+" TODO:  I should think about multi-line patterns for b:match_words.
+"   This would require an option:  how many lines to scan (default 1).
+"   This would be useful for Python, maybe also for *ML.
+" TODO:  Maybe I should add a menu so that people will actually use some of
+"   the features that I have implemented.
+" TODO:  Eliminate the MultiMatch function.  Add yet another argument to
+"   Match_wrapper() instead.
+" TODO:  Allow :let b:match_words = '\(\(foo\)\(bar\)\):\3\2:end\1'
+" TODO:  Make backrefs safer by using '\V' (very no-magic).
+" TODO:  Add a level of indirection, so that custom % scripts can use my
+"   work but extend it.
+
+" allow user to prevent loading
+" and prevent duplicate loading
+if exists("loaded_matchit") || &cp
+  finish
+endif
+let loaded_matchit = 1
+let s:last_mps = ""
+let s:last_words = ":"
+
+let s:save_cpo = &cpo
+set cpo&vim
+
+nnoremap <silent> %  :<C-U>call <SID>Match_wrapper('',1,'n') <CR>
+nnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'n') <CR>
+vnoremap <silent> %  :<C-U>call <SID>Match_wrapper('',1,'v') <CR>m'gv``
+vnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'v') <CR>m'gv``
+onoremap <silent> %  v:<C-U>call <SID>Match_wrapper('',1,'o') <CR>
+onoremap <silent> g% v:<C-U>call <SID>Match_wrapper('',0,'o') <CR>
+
+" Analogues of [{ and ]} using matching patterns:
+nnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "n") <CR>
+nnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W",  "n") <CR>
+vmap [% <Esc>[%m'gv``
+vmap ]% <Esc>]%m'gv``
+" vnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "v") <CR>m'gv``
+" vnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W",  "v") <CR>m'gv``
+onoremap <silent> [% v:<C-U>call <SID>MultiMatch("bW", "o") <CR>
+onoremap <silent> ]% v:<C-U>call <SID>MultiMatch("W",  "o") <CR>
+
+" text object:
+vmap a% <Esc>[%v]%
+
+" Auto-complete mappings:  (not yet "ready for prime time")
+" TODO Read :help write-plugin for the "right" way to let the user
+" specify a key binding.
+"   let g:match_auto = '<C-]>'
+"   let g:match_autoCR = '<C-CR>'
+" if exists("g:match_auto")
+"   execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls'
+" endif
+" if exists("g:match_autoCR")
+"   execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>'
+" endif
+" if exists("g:match_gthhoh")
+"   execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>'
+" endif " gthhoh = "Get the heck out of here!"
+
+let s:notslash = '\\\@<!\%(\\\\\)*'
+
+function! s:Match_wrapper(word, forward, mode) range
+  " In s:CleanUp(), :execute "set" restore_options .
+  let restore_options = (&ic ? " " : " no") . "ignorecase"
+  if exists("b:match_ignorecase")
+    let &ignorecase = b:match_ignorecase
+  endif
+  let restore_options = " ve=" . &ve . restore_options
+  set ve=
+  " If this function was called from Visual mode, make sure that the cursor
+  " is at the correct end of the Visual range:
+  if a:mode == "v"
+    execute "normal! gv\<Esc>"
+  endif
+  " In s:CleanUp(), we may need to check whether the cursor moved forward.
+  let startline = line(".")
+  let startcol = col(".")
+  " Use default behavior if called with a count.
+  if v:count
+    exe "normal! " . v:count . "%"
+    return s:CleanUp(restore_options, a:mode, startline, startcol)
+  end
+
+  " First step:  if not already done, set the script variables
+  "   s:do_BR	flag for whether there are backrefs
+  "   s:pat	parsed version of b:match_words
+  "   s:all	regexp based on s:pat and the default groups
+  "
+  if !exists("b:match_words") || b:match_words == ""
+    let match_words = ""
+    " Allow b:match_words = "GetVimMatchWords()" .
+  elseif b:match_words =~ ":"
+    let match_words = b:match_words
+  else
+    execute "let match_words =" b:match_words
+  endif
+" Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion!
+  if (match_words != s:last_words) || (&mps != s:last_mps) ||
+    \ exists("b:match_debug")
+    let s:last_words = match_words
+    let s:last_mps = &mps
+    " The next several lines were here before
+    " BF started messing with this script.
+    " quote the special chars in 'matchpairs', replace [,:] with \| and then
+    " append the builtin pairs (/*, */, #if, #ifdef, #else, #elif, #endif)
+    " let default = substitute(escape(&mps, '[$^.*~\\/?]'), '[,:]\+',
+    "  \ '\\|', 'g').'\|\/\*\|\*\/\|#if\>\|#ifdef\>\|#else\>\|#elif\>\|#endif\>'
+    let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+      \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>'
+    " s:all = pattern with all the keywords
+    let match_words = match_words . (strlen(match_words) ? "," : "") . default
+    if match_words !~ s:notslash . '\\\d'
+      let s:do_BR = 0
+      let s:pat = match_words
+    else
+      let s:do_BR = 1
+      let s:pat = s:ParseWords(match_words)
+    endif
+    let s:all = substitute(s:pat, s:notslash . '\zs[,:]\+', '\\|', 'g')
+    let s:all = '\%(' . s:all . '\)'
+    " let s:all = '\%(' . substitute(s:all, '\\\ze[,:]', '', 'g') . '\)'
+    if exists("b:match_debug")
+      let b:match_pat = s:pat
+    endif
+  endif
+
+  " Second step:  set the following local variables:
+  "     matchline = line on which the cursor started
+  "     curcol    = number of characters before match
+  "     prefix    = regexp for start of line to start of match
+  "     suffix    = regexp for end of match to end of line
+  " Require match to end on or after the cursor and prefer it to
+  " start on or before the cursor.
+  let matchline = getline(startline)
+  if a:word != ''
+    " word given
+    if a:word !~ s:all
+      echohl WarningMsg|echo 'Missing rule for word:"'.a:word.'"'|echohl NONE
+      return s:CleanUp(restore_options, a:mode, startline, startcol)
+    endif
+    let matchline = a:word
+    let curcol = 0
+    let prefix = '^\%('
+    let suffix = '\)$'
+  " Now the case when "word" is not given
+  else	" Find the match that ends on or after the cursor and set curcol.
+    let regexp = s:Wholematch(matchline, s:all, startcol-1)
+    let curcol = match(matchline, regexp)
+    " If there is no match, give up.
+    if curcol == -1
+      return s:CleanUp(restore_options, a:mode, startline, startcol)
+    endif
+    let endcol = matchend(matchline, regexp)
+    let suf = strlen(matchline) - endcol
+    let prefix = (curcol ? '^.*\%'  . (curcol + 1) . 'c\%(' : '^\%(')
+    let suffix = (suf ? '\)\%' . (endcol + 1) . 'c.*$'  : '\)$')
+  endif
+  if exists("b:match_debug")
+    let b:match_match = matchstr(matchline, regexp)
+    let b:match_col = curcol+1
+  endif
+
+  " Third step:  Find the group and single word that match, and the original
+  " (backref) versions of these.  Then, resolve the backrefs.
+  " Set the following local variable:
+  " group = colon-separated list of patterns, one of which matches
+  "       = ini:mid:fin or ini:fin
+  "
+  " Reconstruct the version with unresolved backrefs.
+  let patBR = substitute(match_words.',',
+    \ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
+  let patBR = substitute(patBR, s:notslash.'\zs:\{2,}', ':', 'g')
+  " Now, set group and groupBR to the matching group: 'if:endif' or
+  " 'while:endwhile' or whatever.  A bit of a kluge:  s:Choose() returns
+  " group . "," . groupBR, and we pick it apart.
+  let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
+  let i = matchend(group, s:notslash . ",")
+  let groupBR = strpart(group, i)
+  let group = strpart(group, 0, i-1)
+  " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
+  if s:do_BR " Do the hard part:  resolve those backrefs!
+    let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+  endif
+  if exists("b:match_debug")
+    let b:match_wholeBR = groupBR
+    let i = matchend(groupBR, s:notslash . ":")
+    let b:match_iniBR = strpart(groupBR, 0, i-1)
+  endif
+
+  " Fourth step:  Set the arguments for searchpair().
+  let i = matchend(group, s:notslash . ":")
+  let j = matchend(group, '.*' . s:notslash . ":")
+  let ini = strpart(group, 0, i-1)
+  let mid = substitute(strpart(group, i,j-i-1), s:notslash.'\zs:', '\\|', 'g')
+  let fin = strpart(group, j)
+  "Un-escape the remaining , and : characters.
+  let ini = substitute(ini, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  let mid = substitute(mid, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  let fin = substitute(fin, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  " searchpair() requires that these patterns avoid \(\) groups.
+  let ini = substitute(ini, s:notslash . '\zs\\(', '\\%(', 'g')
+  let mid = substitute(mid, s:notslash . '\zs\\(', '\\%(', 'g')
+  let fin = substitute(fin, s:notslash . '\zs\\(', '\\%(', 'g')
+  " Set mid.  This is optimized for readability, not micro-efficiency!
+  if a:forward && matchline =~ prefix . fin . suffix
+    \ || !a:forward && matchline =~ prefix . ini . suffix
+    let mid = ""
+  endif
+  " Set flag.  This is optimized for readability, not micro-efficiency!
+  if a:forward && matchline =~ prefix . fin . suffix
+    \ || !a:forward && matchline !~ prefix . ini . suffix
+    let flag = "bW"
+  else
+    let flag = "W"
+  endif
+  " Set skip.
+  if exists("b:match_skip")
+    let skip = b:match_skip
+  elseif exists("b:match_comment") " backwards compatibility and testing!
+    let skip = "r:" . b:match_comment
+  else
+    let skip = 's:comment\|string'
+  endif
+  let skip = s:ParseSkip(skip)
+  if exists("b:match_debug")
+    let b:match_ini = ini
+    let b:match_tail = (strlen(mid) ? mid.'\|' : '') . fin
+  endif
+
+  " Fifth step:  actually start moving the cursor and call searchpair().
+  " Later, :execute restore_cursor to get to the original screen.
+  let restore_cursor = virtcol(".") . "|"
+  normal! g0
+  let restore_cursor = line(".") . "G" .  virtcol(".") . "|zs" . restore_cursor
+  normal! H
+  let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  execute restore_cursor
+  call cursor(0, curcol + 1)
+  " normal! 0
+  " if curcol
+  "   execute "normal!" . curcol . "l"
+  " endif
+  if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
+    let skip = "0"
+  else
+    execute "if " . skip . "| let skip = '0' | endif"
+  endif
+  let sp_return = searchpair(ini, mid, fin, flag, skip)
+  let final_position = "call cursor(" . line(".") . "," . col(".") . ")"
+  " Restore cursor position and original screen.
+  execute restore_cursor
+  normal! m'
+  if sp_return > 0
+    execute final_position
+  endif
+  return s:CleanUp(restore_options, a:mode, startline, startcol, mid.'\|'.fin)
+endfun
+
+" Restore options and do some special handling for Operator-pending mode.
+" The optional argument is the tail of the matching group.
+fun! s:CleanUp(options, mode, startline, startcol, ...)
+  execute "set" a:options
+  " Open folds, if appropriate.
+  if a:mode != "o"
+    if &foldopen =~ "percent"
+      normal! zv
+    endif
+    " In Operator-pending mode, we want to include the whole match
+    " (for example, d%).
+    " This is only a problem if we end up moving in the forward direction.
+  elseif (a:startline < line(".")) ||
+	\ (a:startline == line(".") && a:startcol < col("."))
+    if a:0
+      " Check whether the match is a single character.  If not, move to the
+      " end of the match.
+      let matchline = getline(".")
+      let currcol = col(".")
+      let regexp = s:Wholematch(matchline, a:1, currcol-1)
+      let endcol = matchend(matchline, regexp)
+      if endcol > currcol  " This is NOT off by one!
+	execute "normal!" . (endcol - currcol) . "l"
+      endif
+    endif " a:0
+  endif " a:mode != "o" && etc.
+  return 0
+endfun
+
+" Example (simplified HTML patterns):  if
+"   a:groupBR	= '<\(\k\+\)>:</\1>'
+"   a:prefix	= '^.\{3}\('
+"   a:group	= '<\(\k\+\)>:</\(\k\+\)>'
+"   a:suffix	= '\).\{2}$'
+"   a:matchline	=  "123<tag>12" or "123</tag>12"
+" then extract "tag" from a:matchline and return "<tag>:</tag>" .
+fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+  if a:matchline !~ a:prefix .
+    \ substitute(a:group, s:notslash . '\zs:', '\\|', 'g') . a:suffix
+    return a:group
+  endif
+  let i = matchend(a:groupBR, s:notslash . ':')
+  let ini = strpart(a:groupBR, 0, i-1)
+  let tailBR = strpart(a:groupBR, i)
+  let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix,
+    \ a:groupBR)
+  let i = matchend(word, s:notslash . ":")
+  let wordBR = strpart(word, i)
+  let word = strpart(word, 0, i-1)
+  " Now, a:matchline =~ a:prefix . word . a:suffix
+  if wordBR != ini
+    let table = s:Resolve(ini, wordBR, "table")
+  else
+    " let table = "----------"
+    let table = ""
+    let d = 0
+    while d < 10
+      if tailBR =~ s:notslash . '\\' . d
+	" let table[d] = d
+	let table = table . d
+      else
+	let table = table . "-"
+      endif
+      let d = d + 1
+    endwhile
+  endif
+  let d = 9
+  while d
+    if table[d] != "-"
+      let backref = substitute(a:matchline, a:prefix.word.a:suffix,
+	\ '\'.table[d], "")
+	" Are there any other characters that should be escaped?
+      let backref = escape(backref, '*,:')
+      execute s:Ref(ini, d, "start", "len")
+      let ini = strpart(ini, 0, start) . backref . strpart(ini, start+len)
+      let tailBR = substitute(tailBR, s:notslash . '\zs\\' . d,
+	\ escape(backref, '\\'), 'g')
+    endif
+    let d = d-1
+  endwhile
+  if exists("b:match_debug")
+    if s:do_BR
+      let b:match_table = table
+      let b:match_word = word
+    else
+      let b:match_table = ""
+      let b:match_word = ""
+    endif
+  endif
+  return ini . ":" . tailBR
+endfun
+
+" Input a comma-separated list of groups with backrefs, such as
+"   a:groups = '\(foo\):end\1,\(bar\):end\1'
+" and return a comma-separated list of groups with backrefs replaced:
+"   return '\(foo\):end\(foo\),\(bar\):end\(bar\)'
+fun! s:ParseWords(groups)
+  let groups = substitute(a:groups.",", s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
+  let groups = substitute(groups, s:notslash . '\zs:\{2,}', ':', 'g')
+  let parsed = ""
+  while groups =~ '[^,:]'
+    let i = matchend(groups, s:notslash . ':')
+    let j = matchend(groups, s:notslash . ',')
+    let ini = strpart(groups, 0, i-1)
+    let tail = strpart(groups, i, j-i-1) . ":"
+    let groups = strpart(groups, j)
+    let parsed = parsed . ini
+    let i = matchend(tail, s:notslash . ':')
+    while i != -1
+      " In 'if:else:endif', ini='if' and word='else' and then word='endif'.
+      let word = strpart(tail, 0, i-1)
+      let tail = strpart(tail, i)
+      let i = matchend(tail, s:notslash . ':')
+      let parsed = parsed . ":" . s:Resolve(ini, word, "word")
+    endwhile " Now, tail has been used up.
+    let parsed = parsed . ","
+  endwhile " groups =~ '[^,:]'
+  let parsed = substitute(parsed, ',$', '', '')
+  return parsed
+endfun
+
+" TODO I think this can be simplified and/or made more efficient.
+" TODO What should I do if a:start is out of range?
+" Return a regexp that matches all of a:string, such that
+" matchstr(a:string, regexp) represents the match for a:pat that starts
+" as close to a:start as possible, before being preferred to after, and
+" ends after a:start .
+" Usage:
+" let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1)
+" let i      = match(getline("."), regexp)
+" let j      = matchend(getline("."), regexp)
+" let match  = matchstr(getline("."), regexp)
+fun! s:Wholematch(string, pat, start)
+  let group = '\%(' . a:pat . '\)'
+  let prefix = (a:start ? '\(^.*\%<' . (a:start + 2) . 'c\)\zs' : '^')
+  let len = strlen(a:string)
+  let suffix = (a:start+1 < len ? '\(\%>'.(a:start+1).'c.*$\)\@=' : '$')
+  if a:string !~ prefix . group . suffix
+    let prefix = ''
+  endif
+  return prefix . group . suffix
+endfun
+
+" No extra arguments:  s:Ref(string, d) will
+" find the d'th occurrence of '\(' and return it, along with everything up
+" to and including the matching '\)'.
+" One argument:  s:Ref(string, d, "start") returns the index of the start
+" of the d'th '\(' and any other argument returns the length of the group.
+" Two arguments:  s:Ref(string, d, "foo", "bar") returns a string to be
+" executed, having the effect of
+"   :let foo = s:Ref(string, d, "start")
+"   :let bar = s:Ref(string, d, "len")
+fun! s:Ref(string, d, ...)
+  let len = strlen(a:string)
+  if a:d == 0
+    let start = 0
+  else
+    let cnt = a:d
+    let match = a:string
+    while cnt
+      let cnt = cnt - 1
+      let index = matchend(match, s:notslash . '\\(')
+      if index == -1
+	return ""
+      endif
+      let match = strpart(match, index)
+    endwhile
+    let start = len - strlen(match)
+    if a:0 == 1 && a:1 == "start"
+      return start - 2
+    endif
+    let cnt = 1
+    while cnt
+      let index = matchend(match, s:notslash . '\\(\|\\)') - 1
+      if index == -2
+	return ""
+      endif
+      " Increment if an open, decrement if a ')':
+      let cnt = cnt + (match[index]=="(" ? 1 : -1)  " ')'
+      " let cnt = stridx('0(', match[index]) + cnt
+      let match = strpart(match, index+1)
+    endwhile
+    let start = start - 2
+    let len = len - start - strlen(match)
+  endif
+  if a:0 == 1
+    return len
+  elseif a:0 == 2
+    return "let " . a:1 . "=" . start . "| let " . a:2 . "=" . len
+  else
+    return strpart(a:string, start, len)
+  endif
+endfun
+
+" Count the number of disjoint copies of pattern in string.
+" If the pattern is a literal string and contains no '0' or '1' characters
+" then s:Count(string, pattern, '0', '1') should be faster than
+" s:Count(string, pattern).
+fun! s:Count(string, pattern, ...)
+  let pat = escape(a:pattern, '\\')
+  if a:0 > 1
+    let foo = substitute(a:string, '[^'.a:pattern.']', "a:1", "g")
+    let foo = substitute(a:string, pat, a:2, "g")
+    let foo = substitute(foo, '[^' . a:2 . ']', "", "g")
+    return strlen(foo)
+  endif
+  let result = 0
+  let foo = a:string
+  let index = matchend(foo, pat)
+  while index != -1
+    let result = result + 1
+    let foo = strpart(foo, index)
+    let index = matchend(foo, pat)
+  endwhile
+  return result
+endfun
+
+" s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where
+" word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'.  That is, the first
+" '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this
+" indicates that all other instances of '\1' in target are to be replaced
+" by '\3'.  The hard part is dealing with nesting...
+" Note that ":" is an illegal character for source and target,
+" unless it is preceded by "\".
+fun! s:Resolve(source, target, output)
+  let word = a:target
+  let i = matchend(word, s:notslash . '\\\d') - 1
+  let table = "----------"
+  while i != -2 " There are back references to be replaced.
+    let d = word[i]
+    let backref = s:Ref(a:source, d)
+    " The idea is to replace '\d' with backref.  Before we do this,
+    " replace any \(\) groups in backref with :1, :2, ... if they
+    " correspond to the first, second, ... group already inserted
+    " into backref.  Later, replace :1 with \1 and so on.  The group
+    " number w+b within backref corresponds to the group number
+    " s within a:source.
+    " w = number of '\(' in word before the current one
+    let w = s:Count(
+    \ substitute(strpart(word, 0, i-1), '\\\\', '', 'g'), '\(', '1')
+    let b = 1 " number of the current '\(' in backref
+    let s = d " number of the current '\(' in a:source
+    while b <= s:Count(substitute(backref, '\\\\', '', 'g'), '\(', '1')
+    \ && s < 10
+      if table[s] == "-"
+	if w + b < 10
+	  " let table[s] = w + b
+	  let table = strpart(table, 0, s) . (w+b) . strpart(table, s+1)
+	endif
+	let b = b + 1
+	let s = s + 1
+      else
+	execute s:Ref(backref, b, "start", "len")
+	let ref = strpart(backref, start, len)
+	let backref = strpart(backref, 0, start) . ":". table[s]
+	\ . strpart(backref, start+len)
+	let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1')
+      endif
+    endwhile
+    let word = strpart(word, 0, i-1) . backref . strpart(word, i+1)
+    let i = matchend(word, s:notslash . '\\\d') - 1
+  endwhile
+  let word = substitute(word, s:notslash . '\zs:', '\\', 'g')
+  if a:output == "table"
+    return table
+  elseif a:output == "word"
+    return word
+  else
+    return table . word
+  endif
+endfun
+
+" Assume a:comma = ",".  Then the format for a:patterns and a:1 is
+"   a:patterns = "<pat1>,<pat2>,..."
+"   a:1 = "<alt1>,<alt2>,..."
+" If <patn> is the first pattern that matches a:string then return <patn>
+" if no optional arguments are given; return <patn>,<altn> if a:1 is given.
+fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
+  let tail = (a:patterns =~ a:comma."$" ? a:patterns : a:patterns . a:comma)
+  let i = matchend(tail, s:notslash . a:comma)
+  if a:0
+    let alttail = (a:1 =~ a:comma."$" ? a:1 : a:1 . a:comma)
+    let j = matchend(alttail, s:notslash . a:comma)
+  endif
+  let current = strpart(tail, 0, i-1)
+  if a:branch == ""
+    let currpat = current
+  else
+    let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+  endif
+  while a:string !~ a:prefix . currpat . a:suffix
+    let tail = strpart(tail, i)
+    let i = matchend(tail, s:notslash . a:comma)
+    if i == -1
+      return -1
+    endif
+    let current = strpart(tail, 0, i-1)
+    if a:branch == ""
+      let currpat = current
+    else
+      let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+    endif
+    if a:0
+      let alttail = strpart(alttail, j)
+      let j = matchend(alttail, s:notslash . a:comma)
+    endif
+  endwhile
+  if a:0
+    let current = current . a:comma . strpart(alttail, 0, j-1)
+  endif
+  return current
+endfun
+
+" Call this function to turn on debugging information.  Every time the main
+" script is run, buffer variables will be saved.  These can be used directly
+" or viewed using the menu items below.
+if !exists(":MatchDebug")
+  command! -nargs=0 MatchDebug call s:Match_debug()
+endif
+
+fun! s:Match_debug()
+  let b:match_debug = 1	" Save debugging information.
+  " pat = all of b:match_words with backrefs parsed
+  amenu &Matchit.&pat	:echo b:match_pat<CR>
+  " match = bit of text that is recognized as a match
+  amenu &Matchit.&match	:echo b:match_match<CR>
+  " curcol = cursor column of the start of the matching text
+  amenu &Matchit.&curcol	:echo b:match_col<CR>
+  " wholeBR = matching group, original version
+  amenu &Matchit.wh&oleBR	:echo b:match_wholeBR<CR>
+  " iniBR = 'if' piece, original version
+  amenu &Matchit.ini&BR	:echo b:match_iniBR<CR>
+  " ini = 'if' piece, with all backrefs resolved from match
+  amenu &Matchit.&ini	:echo b:match_ini<CR>
+  " tail = 'else\|endif' piece, with all backrefs resolved from match
+  amenu &Matchit.&tail	:echo b:match_tail<CR>
+  " fin = 'endif' piece, with all backrefs resolved from match
+  amenu &Matchit.&word	:echo b:match_word<CR>
+  " '\'.d in ini refers to the same thing as '\'.table[d] in word.
+  amenu &Matchit.t&able	:echo '0:' . b:match_table . ':9'<CR>
+endfun
+
+" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW"
+" or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W".
+" Return a "mark" for the original position, so that
+"   let m = MultiMatch("bW", "n") ... execute m
+" will return to the original position.  If there is a problem, do not
+" move the cursor and return "", unless a count is given, in which case
+" go up or down as many levels as possible and again return "".
+" TODO This relies on the same patterns as % matching.  It might be a good
+" idea to give it its own matching patterns.
+fun! s:MultiMatch(spflag, mode)
+  if !exists("b:match_words") || b:match_words == ""
+    return ""
+  end
+  let restore_options = (&ic ? "" : "no") . "ignorecase"
+  if exists("b:match_ignorecase")
+    let &ignorecase = b:match_ignorecase
+  endif
+  let startline = line(".")
+  let startcol = col(".")
+
+  " First step:  if not already done, set the script variables
+  "   s:do_BR	flag for whether there are backrefs
+  "   s:pat	parsed version of b:match_words
+  "   s:all	regexp based on s:pat and the default groups
+  " This part is copied and slightly modified from s:Match_wrapper().
+  let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+    \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>'
+  " Allow b:match_words = "GetVimMatchWords()" .
+  if b:match_words =~ ":"
+    let match_words = b:match_words
+  else
+    execute "let match_words =" b:match_words
+  endif
+  if (match_words != s:last_words) || (&mps != s:last_mps) ||
+    \ exists("b:match_debug")
+    let s:last_words = match_words
+    let s:last_mps = &mps
+    if match_words !~ s:notslash . '\\\d'
+      let s:do_BR = 0
+      let s:pat = match_words
+    else
+      let s:do_BR = 1
+      let s:pat = s:ParseWords(match_words)
+    endif
+    let s:all = '\%(' . substitute(s:pat . (strlen(s:pat)?",":"") . default,
+      \	'[,:]\+','\\|','g') . '\)'
+    if exists("b:match_debug")
+      let b:match_pat = s:pat
+    endif
+  endif
+
+  " Second step:  figure out the patterns for searchpair()
+  " and save the screen, cursor position, and 'ignorecase'.
+  " - TODO:  A lot of this is copied from s:Match_wrapper().
+  " - maybe even more functionality should be split off
+  " - into separate functions!
+  let cdefault = (s:pat =~ '[^,]$' ? "," : "") . default
+  let open =  substitute(s:pat . cdefault,
+	\ s:notslash . '\zs:.\{-}' . s:notslash . ',', '\\),\\(', 'g')
+  let open =  '\(' . substitute(open, s:notslash . '\zs:.*$', '\\)', '')
+  let close = substitute(s:pat . cdefault,
+	\ s:notslash . '\zs,.\{-}' . s:notslash . ':', '\\),\\(', 'g')
+  let close = substitute(close, '^.\{-}' . s:notslash . ':', '\\(', '') . '\)'
+  if exists("b:match_skip")
+    let skip = b:match_skip
+  elseif exists("b:match_comment") " backwards compatibility and testing!
+    let skip = "r:" . b:match_comment
+  else
+    let skip = 's:comment\|string'
+  endif
+  let skip = s:ParseSkip(skip)
+  " let restore_cursor = line(".") . "G" . virtcol(".") . "|"
+  " normal! H
+  " let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  let restore_cursor = virtcol(".") . "|"
+  normal! g0
+  let restore_cursor = line(".") . "G" .  virtcol(".") . "|zs" . restore_cursor
+  normal! H
+  let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  execute restore_cursor
+
+  " Third step: call searchpair().
+  " Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
+  let openpat =  substitute(open, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g')
+  let openpat = substitute(openpat, ',', '\\|', 'g')
+  let closepat = substitute(close, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g')
+  let closepat = substitute(closepat, ',', '\\|', 'g')
+  if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
+    let skip = '0'
+  else
+    execute "if " . skip . "| let skip = '0' | endif"
+  endif
+  mark '
+  let level = v:count1
+  while level
+    if searchpair(openpat, '', closepat, a:spflag, skip) < 1
+      call s:CleanUp(restore_options, a:mode, startline, startcol)
+      return ""
+    endif
+    let level = level - 1
+  endwhile
+
+  " Restore options and return a string to restore the original position.
+  call s:CleanUp(restore_options, a:mode, startline, startcol)
+  return restore_cursor
+endfun
+
+" Search backwards for "if" or "while" or "<tag>" or ...
+" and return "endif" or "endwhile" or "</tag>" or ... .
+" For now, this uses b:match_words and the same script variables
+" as s:Match_wrapper() .  Later, it may get its own patterns,
+" either from a buffer variable or passed as arguments.
+" fun! s:Autocomplete()
+"   echo "autocomplete not yet implemented :-("
+"   if !exists("b:match_words") || b:match_words == ""
+"     return ""
+"   end
+"   let startpos = s:MultiMatch("bW")
+"
+"   if startpos == ""
+"     return ""
+"   endif
+"   " - TODO:  figure out whether 'if' or '<tag>' matched, and construct
+"   " - the appropriate closing.
+"   let matchline = getline(".")
+"   let curcol = col(".") - 1
+"   " - TODO:  Change the s:all argument if there is a new set of match pats.
+"   let regexp = s:Wholematch(matchline, s:all, curcol)
+"   let suf = strlen(matchline) - matchend(matchline, regexp)
+"   let prefix = (curcol ? '^.\{'  . curcol . '}\%(' : '^\%(')
+"   let suffix = (suf ? '\).\{' . suf . '}$'  : '\)$')
+"   " Reconstruct the version with unresolved backrefs.
+"   let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g')
+"   let patBR = substitute(patBR, ':\{2,}', ':', "g")
+"   " Now, set group and groupBR to the matching group: 'if:endif' or
+"   " 'while:endwhile' or whatever.
+"   let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
+"   let i = matchend(group, s:notslash . ",")
+"   let groupBR = strpart(group, i)
+"   let group = strpart(group, 0, i-1)
+"   " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
+"   if s:do_BR
+"     let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+"   endif
+" " let g:group = group
+"
+"   " - TODO:  Construct the closing from group.
+"   let fake = "end" . expand("<cword>")
+"   execute startpos
+"   return fake
+" endfun
+
+" Close all open structures.  "Get the heck out of here!"
+" fun! s:Gthhoh()
+"   let close = s:Autocomplete()
+"   while strlen(close)
+"     put=close
+"     let close = s:Autocomplete()
+"   endwhile
+" endfun
+
+" Parse special strings as typical skip arguments for searchpair():
+"   s:foo becomes (current syntax item) =~ foo
+"   S:foo becomes (current syntax item) !~ foo
+"   r:foo becomes (line before cursor) =~ foo
+"   R:foo becomes (line before cursor) !~ foo
+fun! s:ParseSkip(str)
+  let skip = a:str
+  if skip[1] == ":"
+    if skip[0] == "s"
+      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" .
+	\ strpart(skip,2) . "'"
+    elseif skip[0] == "S"
+      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" .
+	\ strpart(skip,2) . "'"
+    elseif skip[0] == "r"
+      let skip = "strpart(getline('.'),0,col('.'))=~'" . strpart(skip,2). "'"
+    elseif skip[0] == "R"
+      let skip = "strpart(getline('.'),0,col('.'))!~'" . strpart(skip,2). "'"
+    endif
+  endif
+  return skip
+endfun
+
+let &cpo = s:save_cpo
+
+" vim:sts=2:sw=2:
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/skeleton.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/skeleton.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/plugin/skeleton.vim	(revision 18231)
@@ -0,0 +1,97 @@
+" skeleton - Skeleton for newly created files
+" Version: 0.0.2
+" Copyright (C) 2008 kana <http://whileimautomaton.net/>
+" License: MIT license  {{{
+"     Permission is hereby granted, free of charge, to any person obtaining
+"     a copy of this software and associated documentation files (the
+"     "Software"), to deal in the Software without restriction, including
+"     without limitation the rights to use, copy, modify, merge, publish,
+"     distribute, sublicense, and/or sell copies of the Software, and to
+"     permit persons to whom the Software is furnished to do so, subject to
+"     the following conditions:
+"
+"     The above copyright notice and this permission notice shall be included
+"     in all copies or substantial portions of the Software.
+"
+"     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+"     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+"     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+"     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+"     CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+"     TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+"     SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+" }}}
+
+if exists('g:loaded_skeleton')
+  finish
+endif
+
+let s:SKELETON_DIR = 'xtr/skeleton/'
+
+
+
+
+command! -bang -bar -complete=customlist,s:cmd_SkeletonLoad_complete -nargs=1
+\ SkeletonLoad
+\ call s:cmd_SkeletonLoad(<q-args>, expand('<abuf>') == '', <bang>0)
+
+function! s:cmd_SkeletonLoad(name, interactive_use_p, banged_p)
+  if &l:buftype != ''
+    if a:interactive_use_p
+      echo 'This buffer is not a normal one.  Skeleton leaves it as is.'
+    endif
+    return
+  endif
+  if (!a:banged_p) && (line('$') != 1 || len(getline(1)) != 0)
+    if a:interactive_use_p
+      echo 'This buffer is not empty.  Skeleton leaves it as is.'
+    endif
+    return
+  endif
+
+  let candidates = split(globpath(&runtimepath, s:SKELETON_DIR.a:name), "\n")
+  if len(candidates) < 1
+    if a:interactive_use_p
+      echo 'Skeleton file is not found:' string(a:name)
+    endif
+    return
+  endif
+
+  " Load skeleton file.
+  if a:banged_p
+    % delete _
+  endif
+  silent keepalt 1 read `=candidates[0]`
+  0 delete _
+
+  return
+endfunction
+
+function! s:cmd_SkeletonLoad_complete(arglead, cmdline, cursorpos)
+  return map(split(globpath(&runtimepath, s:SKELETON_DIR.a:arglead.'*'), "\n"),
+  \          'fnamemodify(v:val, ":t")')
+endfunction
+
+
+
+
+augroup plugin-skeleton
+  autocmd!
+  autocmd BufNewFile *  call s:on_BufNewFile()
+augroup END
+
+function! s:on_BufNewFile()
+  silent doautocmd User plugin-skeleton-detect
+
+  if &l:filetype != ''
+    execute 'SkeletonLoad' &l:filetype
+  endif
+endfunction
+
+
+
+
+let g:loaded_skeleton = 1
+
+" __END__
+" vim: foldmethod=marker
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#Synchronize Enums
+
+#Get all lines of EnumDefinitions.h which hold Enum 
+cat c.vim | sed "/ISSM's Enums begin/,/vim: ts=8/d" > temp
+echo "\"ISSM's Enums begin" >> temp
+cat ../../../../../src/c/shared/Enum/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-z]Enum," -e "[A-Z]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
+echo "\"ISSM's Enums end" >> temp
+cat c.vim | sed "1,/ISSM's Enums end/d" >> temp
+mv temp c.vim
+
+#Synchronize objects
+cat c.vim | sed "/ISSM's objects begin/,/vim: ts=8/d" > temp
+echo "\"ISSM's objects begin" >> temp
+find ../../../../../src/c/classes -name "*.cpp" -o -name "*.h" | sed -e "s/\// /g" -e "s/\.cpp//" -e "s/\.h//" | awk '{print  $(NF)}' | sort | uniq | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
+find ../../../../../src/c/analyses -name "*Analysis.h" | sed -e "s/\// /g" -e "s/\.cpp//" -e "s/\.h//" | awk '{print  $(NF)}' | sort | uniq | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
+echo "\"ISSM's objects end" >> temp
+cat c.vim | sed "1,/ISSM's objects end/d" >> temp
+
+mv temp c.vim
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/c.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/c.vim	(revision 18231)
@@ -0,0 +1,1530 @@
+" Vim syntax file
+" Language:	C
+" Maintainer:	Bram Moolenaar <Bram@vim.org>
+" Last Change:	1999 Dec 02, 2004 Feb 04
+
+" For version 5.x: Clear all syntax items
+" For version 6.x: Quit when a syntax file was already loaded
+if version < 600
+  syntax clear
+elseif exists("b:current_syntax")
+  finish
+endif
+"hi clear
+
+syn match       cName		"\<[a-zA-Z_][a-zA-Z_0-9]*\>"
+"syn match       cConstant	"\<[A-Z_][A-Z_0-9]\{2,}[A-Za-z_0-9]*\>[^(:]"me=e-1
+"syn match       cConstant	"\<[A-Z_][A-Z_0-9]\{2,}[A-Za-z_0-9]*\>$"
+"syn match       cConstant	"\<_[_0-9]\{1,}\>[^(:]"
+syn match	cFunction	"\<[a-zA-Z_][a-zA-Z_0-9]*\>[^()]*)("me=e-2
+"syn match	cFunction	"\<[a-zA-Z_][a-zA-Z_0-9]*\>\s*)("me=e-2
+syn match	cFunction	"\<[a-zA-Z_][a-zA-Z_0-9]*\>\s*("me=e-1
+syn match	cBraces		"[{}]"
+
+syn keyword cMC			__DI __EI __asm __set_il
+syn keyword cMC			__wait_nop __mul __div __mod __mulu __divu __modu
+syn keyword cAnsiFunction	MULU_ DIVU_ MODU_ MUL_ DIV_ MOD_
+syn keyword cAnsiFunction	main typeof
+syn keyword cAnsiFunction	open close read write lseek dup dup2
+syn keyword cAnsiFunction	fcntl ioctl
+syn keyword cAnsiFunction	wctrans towctrans towupper
+syn keyword cAnsiFunction	towlower wctype iswctype
+syn keyword cAnsiFunction	iswxdigit iswupper iswspace
+syn keyword cAnsiFunction	iswpunct iswprint iswlower
+syn keyword cAnsiFunction	iswgraph iswdigit iswcntrl
+syn keyword cAnsiFunction	iswalpha iswalnum wcsrtombs
+syn keyword cAnsiFunction	mbsrtowcs wcrtomb mbrtowc
+syn keyword cAnsiFunction	mbrlen mbsinit wctob
+syn keyword cAnsiFunction	btowc wcsfxtime wcsftime
+syn keyword cAnsiFunction	wmemset wmemmove wmemcpy
+syn keyword cAnsiFunction	wmemcmp wmemchr wcstok
+syn keyword cAnsiFunction	wcsstr wcsspn wcsrchr
+syn keyword cAnsiFunction	wcspbrk wcslen wcscspn
+syn keyword cAnsiFunction	wcschr wcsxfrm wcsncmp
+syn keyword cAnsiFunction	wcscoll wcscmp wcsncat
+syn keyword cAnsiFunction	wcscat wcsncpy wcscpy
+syn keyword cAnsiFunction	wcstoull wcstoul wcstoll
+syn keyword cAnsiFunction	wcstol wcstold wcstof
+syn keyword cAnsiFunction	wcstod ungetwc putwchar
+syn keyword cAnsiFunction	putwc getwchar getwc
+syn keyword cAnsiFunction	fwide fputws fputwc
+syn keyword cAnsiFunction	fgetws fgetwc wscanf
+syn keyword cAnsiFunction	wprintf vwscanf vwprintf
+syn keyword cAnsiFunction	vswscanf vswprintf vfwscanf
+syn keyword cAnsiFunction	vfwprintf swscanf swprintf
+syn keyword cAnsiFunction	fwscanf fwprintf zonetime
+syn keyword cAnsiFunction	strfxtime strftime localtime
+syn keyword cAnsiFunction	gmtime ctime asctime
+syn keyword cAnsiFunction	time mkxtime mktime
+syn keyword cAnsiFunction	difftime clock strlen
+syn keyword cAnsiFunction	strerror memset strtok
+syn keyword cAnsiFunction	strstr strspn strrchr
+syn keyword cAnsiFunction	strpbrk strcspn strchr
+syn keyword cAnsiFunction	memchr strxfrm strncmp
+syn keyword cAnsiFunction	strcoll strcmp memcmp
+syn keyword cAnsiFunction	strncat strcat strncpy
+syn keyword cAnsiFunction	strcpy memmove memcpy
+syn keyword cAnsiFunction	wcstombs mbstowcs wctomb
+syn keyword cAnsiFunction	mbtowc mblen lldiv
+syn keyword cAnsiFunction	ldiv div llabs
+syn keyword cAnsiFunction	labs abs qsort
+syn keyword cAnsiFunction	bsearch system getenv
+syn keyword cAnsiFunction	exit atexit abort
+syn keyword cAnsiFunction	realloc malloc free
+syn keyword cAnsiFunction	calloc srand rand
+syn keyword cAnsiFunction	strtoull strtoul strtoll
+syn keyword cAnsiFunction	strtol strtold strtof
+syn keyword cAnsiFunction	strtod atoll atol
+syn keyword cAnsiFunction	atoi atof perror
+syn keyword cAnsiFunction	ferror feof clearerr
+syn keyword cAnsiFunction	rewind ftell fsetpos
+syn keyword cAnsiFunction	fseek fgetpos fwrite
+syn keyword cAnsiFunction	fread ungetc puts
+syn keyword cAnsiFunction	putchar putc gets
+syn keyword cAnsiFunction	getchar getc fputs
+syn keyword cAnsiFunction	fputc fgets fgetc
+syn keyword cAnsiFunction	vsscanf vsprintf vsnprintf
+syn keyword cAnsiFunction	vscanf vprintf vfscanf
+syn keyword cAnsiFunction	vfprintf sscanf sprintf
+syn keyword cAnsiFunction	snprintf scanf printf
+syn keyword cAnsiFunction	fscanf fprintf setvbuf
+syn keyword cAnsiFunction	setbuf freopen fopen
+syn keyword cAnsiFunction	fflush fclose tmpnam
+syn keyword cAnsiFunction	tmpfile rename remove
+syn keyword cAnsiFunction	offsetof va_start va_end
+syn keyword cAnsiFunction	va_copy va_arg raise signal
+syn keyword cAnsiFunction	longjmp setjmp isunordered
+syn keyword cAnsiFunction	islessgreater islessequal isless
+syn keyword cAnsiFunction	isgreaterequal isgreater fmal
+syn keyword cAnsiFunction	fmaf fma fminl
+syn keyword cAnsiFunction	fminf fmin fmaxl
+syn keyword cAnsiFunction	fmaxf fmax fdiml
+syn keyword cAnsiFunction	fdimf fdim nextafterxl
+syn keyword cAnsiFunction	nextafterxf nextafterx nextafterl
+syn keyword cAnsiFunction	nextafterf nextafter nanl
+syn keyword cAnsiFunction	nanf nan copysignl
+syn keyword cAnsiFunction	copysignf copysign remquol
+syn keyword cAnsiFunction	remquof remquo remainderl
+syn keyword cAnsiFunction	remainderf remainder fmodl
+syn keyword cAnsiFunction	fmodf fmod truncl
+syn keyword cAnsiFunction	truncf trunc llroundl
+syn keyword cAnsiFunction	llroundf llround lroundl
+syn keyword cAnsiFunction	lroundf lround roundl
+syn keyword cAnsiFunction	roundf round llrintl
+syn keyword cAnsiFunction	llrintf llrint lrintl
+syn keyword cAnsiFunction	lrintf lrint rintl
+syn keyword cAnsiFunction	rintf rint nearbyintl
+syn keyword cAnsiFunction	nearbyintf nearbyint floorl
+syn keyword cAnsiFunction	floorf floor ceill
+syn keyword cAnsiFunction	ceilf ceil tgammal
+syn keyword cAnsiFunction	tgammaf tgamma lgammal
+syn keyword cAnsiFunction	lgammaf lgamma erfcl
+syn keyword cAnsiFunction	erfcf erfc erfl
+syn keyword cAnsiFunction	erff erf sqrtl
+syn keyword cAnsiFunction	sqrtf sqrt powl
+syn keyword cAnsiFunction	powf pow hypotl
+syn keyword cAnsiFunction	hypotf hypot fabsl
+syn keyword cAnsiFunction	fabsf fabs cbrtl
+syn keyword cAnsiFunction	cbrtf cbrt scalblnl
+syn keyword cAnsiFunction	scalblnf scalbln scalbnl
+syn keyword cAnsiFunction	scalbnf scalbn modfl
+syn keyword cAnsiFunction	modff modf logbl
+syn keyword cAnsiFunction	logbf logb log2l
+syn keyword cAnsiFunction	log2f log2 log1pl
+syn keyword cAnsiFunction	log1pf log1p log10l
+syn keyword cAnsiFunction	log10f log10 logl
+syn keyword cAnsiFunction	logf log ldexpl
+syn keyword cAnsiFunction	ldexpf ldexp ilogbl
+syn keyword cAnsiFunction	ilogbf ilogb frexpl
+syn keyword cAnsiFunction	frexpf frexp expm1l
+syn keyword cAnsiFunction	expm1f expm1 exp2l
+syn keyword cAnsiFunction	exp2f exp2 expl
+syn keyword cAnsiFunction	expf exp tanhl
+syn keyword cAnsiFunction	tanhf tanh sinhl
+syn keyword cAnsiFunction	sinhf sinh coshl
+syn keyword cAnsiFunction	coshf cosh atanhl
+syn keyword cAnsiFunction	atanhf atanh asinhl
+syn keyword cAnsiFunction	asinhf asinh acoshl
+syn keyword cAnsiFunction	acoshf acosh tanl
+syn keyword cAnsiFunction	tanf tan sinl
+syn keyword cAnsiFunction	sinf sin cosl
+syn keyword cAnsiFunction	cosf cos atan2l
+syn keyword cAnsiFunction	atan2f atan2 atanl
+syn keyword cAnsiFunction	atanf atan asinl
+syn keyword cAnsiFunction	asinf asin acosl
+syn keyword cAnsiFunction	acosf acos signbit
+syn keyword cAnsiFunction	isnormal isnan isinf
+syn keyword cAnsiFunction	isfinite fpclassify localeconv
+syn keyword cAnsiFunction	setlocale wcstoumax wcstoimax
+syn keyword cAnsiFunction	strtoumax strtoimax feupdateenv
+syn keyword cAnsiFunction	fesetenv feholdexcept fegetenv
+syn keyword cAnsiFunction	fesetround fegetround fetestexcept
+syn keyword cAnsiFunction	fesetexceptflag feraiseexcept fegetexceptflag
+syn keyword cAnsiFunction	feclearexcept toupper tolower
+syn keyword cAnsiFunction	isxdigit isupper isspace
+syn keyword cAnsiFunction	ispunct isprint islower
+syn keyword cAnsiFunction	isgraph isdigit iscntrl
+syn keyword cAnsiFunction	isalpha isalnum creall
+syn keyword cAnsiFunction	crealf creal cprojl
+syn keyword cAnsiFunction	cprojf cproj conjl
+syn keyword cAnsiFunction	conjf conj cimagl
+syn keyword cAnsiFunction	cimagf cimag cargl
+syn keyword cAnsiFunction	cargf carg csqrtl
+syn keyword cAnsiFunction	csqrtf csqrt cpowl
+syn keyword cAnsiFunction	cpowf cpow cabsl
+syn keyword cAnsiFunction	cabsf cabs clogl
+syn keyword cAnsiFunction	clogf clog cexpl
+syn keyword cAnsiFunction	cexpf cexp ctanhl
+syn keyword cAnsiFunction	ctanhf ctanh csinhl
+syn keyword cAnsiFunction	csinhf csinh ccoshl
+syn keyword cAnsiFunction	ccoshf ccosh catanhl
+syn keyword cAnsiFunction	catanhf catanh casinhl
+syn keyword cAnsiFunction	casinhf casinh cacoshl
+syn keyword cAnsiFunction	cacoshf cacosh ctanl
+syn keyword cAnsiFunction	ctanf ctan csinl
+syn keyword cAnsiFunction	csinf csin ccosl
+syn keyword cAnsiFunction	ccosf ccos catanl
+syn keyword cAnsiFunction	catanf catan casinl
+syn keyword cAnsiFunction	casinf casin cacosl
+syn keyword cAnsiFunction	cacosf cacos assert
+syn keyword cAnsiFunction	UINTMAX_C INTMAX_C UINT64_C
+syn keyword cAnsiFunction	UINT32_C UINT16_C UINT8_C
+syn keyword cAnsiFunction	INT64_C INT32_C INT16_C INT8_C
+
+syn keyword	cMC		__interrupt __nosavereg
+syn keyword	cAnsiName	PRId8 PRIi16 PRIo32 PRIu64
+syn keyword	cAnsiName	PRId16 PRIi32 PRIo64 PRIuLEAST8
+syn keyword	cAnsiName	PRId32 PRIi64 PRIoLEAST8 PRIuLEAST16
+syn keyword	cAnsiName	PRId64 PRIiLEAST8 PRIoLEAST16 PRIuLEAST32
+syn keyword	cAnsiName	PRIdLEAST8 PRIiLEAST16 PRIoLEAST32 PRIuLEAST64
+syn keyword	cAnsiName	PRIdLEAST16 PRIiLEAST32 PRIoLEAST64 PRIuFAST8
+syn keyword	cAnsiName	PRIdLEAST32 PRIiLEAST64 PRIoFAST8 PRIuFAST16
+syn keyword	cAnsiName	PRIdLEAST64 PRIiFAST8 PRIoFAST16 PRIuFAST32
+syn keyword	cAnsiName	PRIdFAST8 PRIiFAST16 PRIoFAST32 PRIuFAST64
+syn keyword	cAnsiName	PRIdFAST16 PRIiFAST32 PRIoFAST64 PRIuMAX
+syn keyword	cAnsiName	PRIdFAST32 PRIiFAST64 PRIoMAX PRIuPTR
+syn keyword	cAnsiName	PRIdFAST64 PRIiMAX PRIoPTR PRIx8
+syn keyword	cAnsiName	PRIdMAX PRIiPTR PRIu8 PRIx16
+syn keyword	cAnsiName	PRIdPTR PRIo8 PRIu16 PRIx32
+syn keyword	cAnsiName	PRIi8 PRIo16 PRIu32 PRIx64
+
+syn keyword	cAnsiName	PRIxLEAST8 SCNd8 SCNiFAST32 SCNuLEAST32
+syn keyword	cAnsiName	PRIxLEAST16 SCNd16 SCNiFAST64 SCNuLEAST64
+syn keyword	cAnsiName	PRIxLEAST32 SCNd32 SCNiMAX SCNuFAST8
+syn keyword	cAnsiName	PRIxLEAST64 SCNd64 SCNiPTR SCNuFAST16
+syn keyword	cAnsiName	PRIxFAST8 SCNdLEAST8 SCNo8 SCNuFAST32
+syn keyword	cAnsiName	PRIxFAST16 SCNdLEAST16 SCNo16 SCNuFAST64
+syn keyword	cAnsiName	PRIxFAST32 SCNdLEAST32 SCNo32 SCNuMAX
+syn keyword	cAnsiName	PRIxFAST64 SCNdLEAST64 SCNo64 SCNuPTR
+syn keyword	cAnsiName	PRIxMAX SCNdFAST8 SCNoLEAST8 SCNx8
+syn keyword	cAnsiName	PRIxPTR SCNdFAST16 SCNoLEAST16 SCNx16
+syn keyword	cAnsiName	PRIX8 SCNdFAST32 SCNoLEAST32 SCNx32
+syn keyword	cAnsiName	PRIX16 SCNdFAST64 SCNoLEAST64 SCNx64
+syn keyword	cAnsiName	PRIX32 SCNdMAX SCNoFAST8 SCNxLEAST8
+syn keyword	cAnsiName	PRIX64 SCNdPTR SCNoFAST16 SCNxLEAST16
+syn keyword	cAnsiName	PRIXLEAST8 SCNi8 SCNoFAST32 SCNxLEAST32
+syn keyword	cAnsiName	PRIXLEAST16 SCNi16 SCNoFAST64 SCNxLEAST64
+syn keyword	cAnsiName	PRIXLEAST32 SCNi32 SCNoMAX SCNxFAST8
+syn keyword	cAnsiName	PRIXLEAST64 SCNi64 SCNoPTR SCNxFAST16
+syn keyword	cAnsiName	PRIXFAST8 SCNiLEAST8 SCNu8 SCNxFAST32
+syn keyword	cAnsiName	PRIXFAST16 SCNiLEAST16 SCNu16 SCNxFAST64
+syn keyword	cAnsiName	PRIXFAST32 SCNiLEAST32 SCNu32 SCNxMAX
+syn keyword	cAnsiName	PRIXFAST64 SCNiLEAST64 SCNu64 SCNxPTR
+syn keyword	cAnsiName	PRIXMAX SCNiFAST8 SCNuLEAST8
+syn keyword	cAnsiName	PRIXPTR SCNiFAST16 SCNuLEAST16
+
+syn keyword	cAnsiName	errno environ
+syn keyword	cAnsiName	stdout stdin stderr
+
+syn keyword	cAnsiName	STDC CX_LIMITED_RANGE
+syn keyword	cAnsiName	STDC FENV_ACCESS
+syn keyword	cAnsiName	STDC FP_CONTRACT
+
+"syn keyword	cAnsiName	acos sqrt fmod nearbyint
+"syn keyword	cAnsiName	asin fabs frexp nextafter
+"syn keyword	cAnsiName	atan atan2 tgamma nextafterx
+"syn keyword	cAnsiName	acosh cbrt hypot remainder
+"syn keyword	cAnsiName	asinh ceil ilogb remquo
+"syn keyword	cAnsiName	atanh copysign ldexp rint
+"syn keyword	cAnsiName	cos erf lgamma round
+"syn keyword	cAnsiName	sin erfc llrint scalbn
+"syn keyword	cAnsiName	tan exp2 llround scalbln
+"syn keyword	cAnsiName	cosh expm1 log10 trunc
+"syn keyword	cAnsiName	sinh fdim log1p carg
+"syn keyword	cAnsiName	tanh floor log2 cimag
+"syn keyword	cAnsiName	exp fma logb conj
+"syn keyword	cAnsiName	log fmax lrint cproj
+"syn keyword	cAnsiName	pow fmin lround creal
+
+syn keyword	cAnsiName	and bitor not_eq xor
+syn keyword	cAnsiName	and_eq compl or xor_eq
+syn keyword	cAnsiName	bitand not or_eq
+
+" A bunch of useful C keywords
+"syn keyword	cStatement	goto
+syn keyword	cStatement	break return continue asm
+syn keyword	cLabel		default
+syn keyword	cLabel		case
+syn keyword	cConditional	if else switch
+syn keyword	cRepeat		while for do
+
+syn keyword	cTodo		contained TODO FIXME XXX
+syn match	cTodo		contained "///[A-Z]!*"
+
+" cCommentGroup allows adding matches for special things in comments
+syn cluster	cCommentGroup	contains=cTodo
+
+" String and Character constants
+" Highlight special characters (those which have a backslash) differently
+syn match	cSpecial	display contained "\\\(x\x\+\|\o\{1,3}\|.\|$\)"
+if !exists("c_no_utf")
+  syn match	cSpecial	display contained "\\\(u\x\{4}\|U\x\{8}\)"
+endif
+if exists("c_no_cformat")
+  syn region	cString		start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial,@Spell
+  " cCppString: same as cString, but ends at end of line
+  syn region	cCppString	start=+L\="+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end='$' contains=cSpecial,@Spell
+else
+  syn match	cFormat		display "%\(\d\+\$\)\=[-+' #0*,]*\(\d*\|\*\|\*\d\+\$\)\(\.\(\d*\|\*\|\*\d\+\$\)\)\=\([hlLjztF]\|ll\|hh\)\=\([bdiuoxXDOUfeEgGcCsSpnAaK]\|\[\^\=.[^]]*\]\)" contained
+  syn match	cFormat		display "%%" contained
+  syn region	cString		start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial,cFormat,@Spell
+  " cCppString: same as cString, but ends at end of line
+  syn region	cCppString	start=+L\="+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end='$' contains=cSpecial,cFormat
+  hi link cFormat cSpecial
+endif
+hi link cCppString cString
+
+syn match	cCharacter	"L\='[^\\]'"
+syn match	cCharacter	"L'[^']*'" contains=cSpecial
+if exists("c_gnu")
+  syn match	cSpecialError	"L\='\\[^'\"?\\abefnrtv]'"
+  syn match	cSpecialCharacter "L\='\\['\"?\\abefnrtv]'"
+else
+  syn match	cSpecialError	"L\='\\[^'\"?\\abfnrtv]'"
+  syn match	cSpecialCharacter "L\='\\['\"?\\abfnrtv]'"
+endif
+syn match	cSpecialCharacter display "L\='\\\o\{1,3}'"
+syn match	cSpecialCharacter display "'\\x\x\{1,2}'"
+syn match	cSpecialCharacter display "L'\\x\x\+'"
+
+"when wanted, highlight trailing white space
+if exists("c_space_errors")
+  if !exists("c_no_trail_space_error")
+    syn match	cSpaceError	display excludenl "\s\+$"
+  endif
+  if !exists("c_no_tab_space_error")
+    syn match	cSpaceError	display " \+\t"me=e-1
+  endif
+endif
+
+"catch errors caused by wrong parenthesis and brackets
+" also accept <% for {, %> for }, <: for [ and :> for ] (C99)
+syn cluster	cParenGroup	contains=cParenError,cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cUserLabel2,cGotoLabel,cBitField,cCommentSkip,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom
+if exists("c_no_bracket_error")
+  syn region	cParen		transparent start='(' end=')' contains=ALLBUT,@cParenGroup,cCppParen,cCppString,@Spell
+  " cCppParen: same as cParen but ends at end-of-line; used in cDefine
+  syn region	cCppParen	transparent start='(' skip='\\$' excludenl end=')' end='$' contained contains=ALLBUT,@cParenGroup,cParen,cString,@Spell
+  syn match	cParenError	display ")"
+" syn match	cErrInParen	display contained "[{}]\|<%\|%>"
+  syn match	cErrInParen	display contained "[]\|<%\|%>"
+else
+  syn region	cParen		transparent start='(' end=')' contains=ALLBUT,@cParenGroup,cCppParen,cErrInBracket,cCppBracket,cCppString,@Spell
+  " cCppParen: same as cParen but ends at end-of-line; used in cDefine
+  syn region	cCppParen	transparent start='(' skip='\\$' excludenl end=')' end='$' contained contains=ALLBUT,@cParenGroup,cErrInBracket,cParen,cBracket,cString,@Spell
+  syn match	cParenError	display "[\])]"
+" syn match	cErrInParen	display contained "[\]{}]\|<%\|%>"
+  syn match	cErrInParen	display contained "[\]]\|<%\|%>"
+  syn region	cBracket	transparent start='\[\|<::\@!' end=']\|:>' contains=ALLBUT,@cParenGroup,cErrInParen,cCppParen,cCppBracket,cCppString,@Spell
+  " cCppBracket: same as cParen but ends at end-of-line; used in cDefine
+  syn region	cCppBracket	transparent start='\[\|<::\@!' skip='\\$' excludenl end=']\|:>' end='$' contained contains=ALLBUT,@cParenGroup,cErrInParen,cParen,cBracket,cString,@Spell
+  syn match	cErrInBracket	display contained "[);{}]\|<%\|%>"
+  "syn region	cBlock		transparent matchgroup=cBraces start='{' end='}' contains=ALLBUT,@cParenGroup,cCppParen,cCppBracket,cCppString,cBraceError,cErrInBracket
+  "syn match	cBraceError	"}"
+endif
+
+"integer number, or floating point number without a dot and with "f".
+syn case ignore
+syn match	cNumbers	display transparent "\<\d\|\.\d" contains=cNumber,cFloat,cOctalError,cOctal
+" Same, but without octal error (for comments)
+syn match	cNumbersCom	display contained transparent "\<\d\|\.\d" contains=cNumber,cFloat,cOctal
+syn match	cNumber		display contained "\d\+\(u\=l\{0,2}\|ll\=u\)\>"
+"hex number
+syn match	cNumber		display contained "0x\x\+\(u\=l\{0,2}\|ll\=u\)\>"
+" Flag the first zero of an octal number as something special
+syn match	cOctal		display contained "0\o\+\(u\=l\{0,2}\|ll\=u\)\>" contains=cOctalZero
+syn match	cOctalZero	display contained "\<0"
+syn match	cFloat		display contained "\d\+f"
+"floating point number, with dot, optional exponent
+syn match	cFloat		display contained "\d\+\.\d*\(e[-+]\=\d\+\)\=[fl]\="
+"floating point number, starting with a dot, optional exponent
+syn match	cFloat		display contained "\.\d\+\(e[-+]\=\d\+\)\=[fl]\=\>"
+"floating point number, without dot, with exponent
+syn match	cFloat		display contained "\d\+e[-+]\=\d\+[fl]\=\>"
+if !exists("c_no_c99")
+  "hexadecimal floating point number, optional leading digits, with dot, with exponent
+  syn match	cFloat		display contained "0x\x*\.\x\+p[-+]\=\d\+[fl]\=\>"
+  "hexadecimal floating point number, with leading digits, optional dot, with exponent
+  syn match	cFloat		display contained "0x\x\+\.\=p[-+]\=\d\+[fl]\=\>"
+endif
+
+" flag an octal number with wrong digits
+syn match	cOctalError	display contained "0\o*[89]\d*"
+syn case match
+
+if exists("xxxc_comment_strings")
+  " A comment can contain cString, cCharacter and cNumber.
+  " But a "*/" inside a cString in a cComment DOES end the comment!  So we
+  " need to use a special type of cString: cCommentString, which also ends on
+  " "*/", and sees a "*" at the start of the line as comment again.
+  " Unfortunately this doesn't very well work for // type of comments :-(
+  syntax match	cCommentSkip	contained "^\s*\*\($\|\s\+\)"
+  syntax region cCommentString	contained start=+L\=\\\@<!"+ skip=+\\\\\|\\"+ end=+"+ end=+\*/+me=s-1 contains=cSpecial,cCommentSkip
+  syntax region cComment2String	contained start=+L\=\\\@<!"+ skip=+\\\\\|\\"+ end=+"+ end="$" contains=cSpecial
+  syntax region  cCommentL	start="//" skip="\\$" end="$" keepend contains=@cCommentGroup,cComment2String,cCharacter,cNumbersCom,cSpaceError,@Spell
+  syntax region cComment	matchgroup=cCommentStart start="/\*" end="\*/" contains=@cCommentGroup,cCommentStartError,cCommentString,cCharacter,cNumbersCom,cSpaceError,@Spell
+else
+  syn region	cCommentL	start="//" skip="\\$" end="$" keepend contains=@cCommentGroup,cSpaceError,@Spell
+  syn region	cComment	matchgroup=cCommentStart start="/\*" end="\*/" contains=@cCommentGroup,cCommentStartError,cSpaceError,@Spell
+endif
+" keep a // comment separately, it terminates a preproc. conditional
+syntax match	cCommentError	display "\*/"
+syntax match	cCommentStartError display "/\*"me=e-1 contained
+
+syn keyword	cOperator	sizeof
+if exists("c_gnu")
+  syn keyword	cStatement	__asm__
+  syn keyword	cOperator	typeof __real__ __imag__
+endif
+syn keyword	cType		int long short char void
+syn keyword	cType		signed unsigned float double
+
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+"   ISSM special syntax                                                                                             "
+"   please try to keep the alphabetical ordering                                                                    "
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+"Petsc
+syn keyword	cType		Vec Mat SeqVec SeqMat
+"other ISSM's syntax
+syn keyword	cType		mxArray ErrorException QuadtreeBox
+syn keyword	cType		IssmDouble IssmPDouble
+
+"ISSM's objects begin
+syn keyword cType BoolInput
+syn keyword cType BoolParam
+syn keyword cType classes
+syn keyword cType Constraint
+syn keyword cType Constraints
+syn keyword cType Contour
+syn keyword cType Contours
+syn keyword cType ControlInput
+syn keyword cType DatasetInput
+syn keyword cType DataSetParam
+syn keyword cType Definition
+syn keyword cType DependentObject
+syn keyword cType DofIndexing
+syn keyword cType DoubleInput
+syn keyword cType DoubleMatArrayParam
+syn keyword cType DoubleMatParam
+syn keyword cType DoubleParam
+syn keyword cType DoubleTransientMatParam
+syn keyword cType DoubleVecParam
+syn keyword cType Element
+syn keyword cType ElementHook
+syn keyword cType ElementMatrix
+syn keyword cType Elements
+syn keyword cType ElementVector
+syn keyword cType ExponentialVariogram
+syn keyword cType ExternalResult
+syn keyword cType FemModel
+syn keyword cType FileParam
+syn keyword cType Friction
+syn keyword cType Gauss
+syn keyword cType GaussianVariogram
+syn keyword cType gaussobjects
+syn keyword cType GaussPenta
+syn keyword cType GaussSeg
+syn keyword cType GaussTetra
+syn keyword cType GaussTria
+syn keyword cType GenericExternalResult
+syn keyword cType GenericOption
+syn keyword cType GenericParam
+syn keyword cType GiaDeflectionCoreArgs
+syn keyword cType Hook
+syn keyword cType IndependentObject
+syn keyword cType Input
+syn keyword cType Inputs
+syn keyword cType IntInput
+syn keyword cType IntMatParam
+syn keyword cType IntParam
+syn keyword cType IntVecParam
+syn keyword cType IoModel
+syn keyword cType krigingobjects
+syn keyword cType Load
+syn keyword cType Loads
+syn keyword cType Massfluxatgate
+syn keyword cType Material
+syn keyword cType Materials
+syn keyword cType Matice
+syn keyword cType Matpar
+syn keyword cType matrixobjects
+syn keyword cType MatrixParam
+syn keyword cType Misfit
+syn keyword cType Node
+syn keyword cType Nodes
+syn keyword cType Numericalflux
+syn keyword cType Observation
+syn keyword cType Observations
+syn keyword cType Option
+syn keyword cType Options
+syn keyword cType OptionUtilities
+syn keyword cType Param
+syn keyword cType Parameters
+syn keyword cType Pengrid
+syn keyword cType Penpair
+syn keyword cType Penta
+syn keyword cType PentaInput
+syn keyword cType PentaRef
+syn keyword cType PowerVariogram
+syn keyword cType Profiler
+syn keyword cType Quadtree
+syn keyword cType Results
+syn keyword cType Riftfront
+syn keyword cType RiftStruct
+syn keyword cType Seg
+syn keyword cType SegInput
+syn keyword cType Segment
+syn keyword cType SegRef
+syn keyword cType SpcDynamic
+syn keyword cType SpcStatic
+syn keyword cType SpcTransient
+syn keyword cType SphericalVariogram
+syn keyword cType StringArrayParam
+syn keyword cType StringParam
+syn keyword cType Tetra
+syn keyword cType TetraInput
+syn keyword cType TetraRef
+syn keyword cType TransientInput
+syn keyword cType TransientParam
+syn keyword cType Tria
+syn keyword cType TriaInput
+syn keyword cType TriaRef
+syn keyword cType Update
+syn keyword cType Variogram
+syn keyword cType VectorParam
+syn keyword cType Vertex
+syn keyword cType Vertices
+syn keyword cType AdjointBalancethickness2Analysis
+syn keyword cType AdjointBalancethicknessAnalysis
+syn keyword cType AdjointHorizAnalysis
+syn keyword cType Analysis
+syn keyword cType Balancethickness2Analysis
+syn keyword cType BalancethicknessAnalysis
+syn keyword cType BalancethicknessSoftAnalysis
+syn keyword cType BalancevelocityAnalysis
+syn keyword cType DamageEvolutionAnalysis
+syn keyword cType DepthAverageAnalysis
+syn keyword cType EnthalpyAnalysis
+syn keyword cType EnumToAnalysis
+syn keyword cType ExtrapolationAnalysis
+syn keyword cType ExtrudeFromBaseAnalysis
+syn keyword cType ExtrudeFromTopAnalysis
+syn keyword cType FreeSurfaceBaseAnalysis
+syn keyword cType FreeSurfaceTopAnalysis
+syn keyword cType GiaAnalysis
+syn keyword cType HydrologyDCEfficientAnalysis
+syn keyword cType HydrologyDCInefficientAnalysis
+syn keyword cType HydrologyShreveAnalysis
+syn keyword cType L2ProjectionBaseAnalysis
+syn keyword cType L2ProjectionEPLAnalysis
+syn keyword cType LevelsetAnalysis
+syn keyword cType LsfReinitializationAnalysis
+syn keyword cType MasstransportAnalysis
+syn keyword cType MeltingAnalysis
+syn keyword cType MeshdeformationAnalysis
+syn keyword cType SmoothedSurfaceSlopeXAnalysis
+syn keyword cType SmoothedSurfaceSlopeYAnalysis
+syn keyword cType StressbalanceAnalysis
+syn keyword cType StressbalanceSIAAnalysis
+syn keyword cType StressbalanceVerticalAnalysis
+syn keyword cType ThermalAnalysis
+"ISSM's objects end
+"ISSM's Enums begin
+syn keyword cConstant AutodiffIsautodiffEnum
+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 AutodiffObufsizeEnum
+syn keyword cConstant AutodiffLbufsizeEnum
+syn keyword cConstant AutodiffCbufsizeEnum
+syn keyword cConstant AutodiffTbufsizeEnum
+syn keyword cConstant AutodiffGcTriggerRatioEnum
+syn keyword cConstant AutodiffGcTriggerMaxSizeEnum
+syn keyword cConstant BalancethicknessSpcthicknessEnum
+syn keyword cConstant BalancethicknessStabilizationEnum
+syn keyword cConstant BalancethicknessThickeningRateEnum
+syn keyword cConstant BasalforcingsEnum
+syn keyword cConstant BasalforcingsGeothermalfluxEnum
+syn keyword cConstant BasalforcingsGroundediceMeltingRateEnum
+syn keyword cConstant BasalforcingsFloatingiceMeltingRateEnum
+syn keyword cConstant BasalforcingsDeepwaterMeltingRateEnum
+syn keyword cConstant BasalforcingsDeepwaterElevationEnum
+syn keyword cConstant BasalforcingsUpperwaterElevationEnum
+syn keyword cConstant FloatingMeltRateEnum
+syn keyword cConstant LinearFloatingMeltRateEnum
+syn keyword cConstant BedEnum
+syn keyword cConstant BaseEnum
+syn keyword cConstant ConstantsGEnum
+syn keyword cConstant ConstantsReferencetemperatureEnum
+syn keyword cConstant ConstantsYtsEnum
+syn keyword cConstant DependentObjectEnum
+syn keyword cConstant StressbalanceAbstolEnum
+syn keyword cConstant StressbalanceIsnewtonEnum
+syn keyword cConstant StressbalanceMaxiterEnum
+syn keyword cConstant StressbalancePenaltyFactorEnum
+syn keyword cConstant StressbalanceReferentialEnum
+syn keyword cConstant StressbalanceReltolEnum
+syn keyword cConstant StressbalanceNumRequestedOutputsEnum
+syn keyword cConstant StressbalanceRequestedOutputsEnum
+syn keyword cConstant StressbalanceRestolEnum
+syn keyword cConstant StressbalanceRiftPenaltyLockEnum
+syn keyword cConstant StressbalanceRiftPenaltyThresholdEnum
+syn keyword cConstant StressbalanceShelfDampeningEnum
+syn keyword cConstant StressbalanceSpcvxEnum
+syn keyword cConstant StressbalanceSpcvyEnum
+syn keyword cConstant StressbalanceSpcvzEnum
+syn keyword cConstant StressbalanceFSreconditioningEnum
+syn keyword cConstant StressbalanceVertexPairingEnum
+syn keyword cConstant StressbalanceViscosityOvershootEnum
+syn keyword cConstant LoadingforceXEnum
+syn keyword cConstant LoadingforceYEnum
+syn keyword cConstant LoadingforceZEnum
+syn keyword cConstant FlowequationBorderSSAEnum
+syn keyword cConstant FlowequationBorderHOEnum
+syn keyword cConstant FlowequationBorderFSEnum
+syn keyword cConstant FlowequationElementEquationEnum
+syn keyword cConstant FlowequationIsSIAEnum
+syn keyword cConstant FlowequationIsSSAEnum
+syn keyword cConstant FlowequationIsL1L2Enum
+syn keyword cConstant FlowequationIsHOEnum
+syn keyword cConstant FlowequationIsFSEnum
+syn keyword cConstant FlowequationFeSSAEnum
+syn keyword cConstant FlowequationFeHOEnum
+syn keyword cConstant FlowequationFeFSEnum
+syn keyword cConstant FlowequationVertexEquationEnum
+syn keyword cConstant FrictionCoefficientEnum
+syn keyword cConstant FrictionPEnum
+syn keyword cConstant FrictionQEnum
+syn keyword cConstant FrictionMEnum
+syn keyword cConstant FrictionCEnum
+syn keyword cConstant FrictionLawEnum
+syn keyword cConstant GeometryHydrostaticRatioEnum
+syn keyword cConstant HydrologyModelEnum
+syn keyword cConstant HydrologyshreveEnum
+syn keyword cConstant HydrologyshreveSpcwatercolumnEnum
+syn keyword cConstant HydrologyshreveStabilizationEnum
+syn keyword cConstant HydrologydcEnum
+syn keyword cConstant SedimentHeadEnum
+syn keyword cConstant SedimentHeadOldEnum
+syn keyword cConstant SedimentHeadResidualEnum
+syn keyword cConstant EffectivePressureEnum
+syn keyword cConstant EplHeadEnum
+syn keyword cConstant EplHeadOldEnum
+syn keyword cConstant EplHeadSlopeXEnum
+syn keyword cConstant EplHeadSlopeYEnum
+syn keyword cConstant HydrologydcMaxIterEnum
+syn keyword cConstant HydrologydcRelTolEnum
+syn keyword cConstant HydrologydcSpcsedimentHeadEnum
+syn keyword cConstant HydrologydcSedimentCompressibilityEnum
+syn keyword cConstant HydrologydcSedimentPorosityEnum
+syn keyword cConstant HydrologydcSedimentThicknessEnum
+syn keyword cConstant HydrologydcSedimentTransmitivityEnum
+syn keyword cConstant HydrologydcWaterCompressibilityEnum
+syn keyword cConstant HydrologydcSpceplHeadEnum
+syn keyword cConstant HydrologydcMaskEplactiveNodeEnum
+syn keyword cConstant HydrologydcMaskEplactiveEltEnum
+syn keyword cConstant HydrologydcEplCompressibilityEnum
+syn keyword cConstant HydrologydcEplPorosityEnum
+syn keyword cConstant HydrologydcEplInitialThicknessEnum
+syn keyword cConstant HydrologydcEplMaxThicknessEnum
+syn keyword cConstant HydrologydcEplThicknessEnum
+syn keyword cConstant HydrologydcEplThicknessOldEnum
+syn keyword cConstant HydrologydcEplConductivityEnum
+syn keyword cConstant HydrologydcIsefficientlayerEnum
+syn keyword cConstant HydrologydcSedimentlimitFlagEnum
+syn keyword cConstant HydrologydcSedimentlimitEnum
+syn keyword cConstant HydrologydcTransferFlagEnum
+syn keyword cConstant HydrologydcLeakageFactorEnum
+syn keyword cConstant HydrologydcPenaltyFactorEnum
+syn keyword cConstant HydrologydcPenaltyLockEnum
+syn keyword cConstant HydrologydcBasalMoulinInputEnum
+syn keyword cConstant HydrologyLayerEnum
+syn keyword cConstant HydrologySedimentEnum
+syn keyword cConstant HydrologyEfficientEnum
+syn keyword cConstant HydrologySedimentKmaxEnum
+syn keyword cConstant IndependentObjectEnum
+syn keyword cConstant InversionControlParametersEnum
+syn keyword cConstant InversionCostFunctionThresholdEnum
+syn keyword cConstant InversionCostFunctionsCoefficientsEnum
+syn keyword cConstant InversionCostFunctionsEnum
+syn keyword cConstant InversionGradientScalingEnum
+syn keyword cConstant InversionIscontrolEnum
+syn keyword cConstant InversionTypeEnum
+syn keyword cConstant InversionIncompleteAdjointEnum
+syn keyword cConstant InversionMaxParametersEnum
+syn keyword cConstant InversionMaxiterPerStepEnum
+syn keyword cConstant InversionMaxiterEnum
+syn keyword cConstant InversionMaxstepsEnum
+syn keyword cConstant InversionFatolEnum
+syn keyword cConstant InversionFrtolEnum
+syn keyword cConstant InversionGatolEnum
+syn keyword cConstant InversionGrtolEnum
+syn keyword cConstant InversionGttolEnum
+syn keyword cConstant InversionAlgorithmEnum
+syn keyword cConstant InversionMinParametersEnum
+syn keyword cConstant InversionNstepsEnum
+syn keyword cConstant InversionDxminEnum
+syn keyword cConstant InversionNumControlParametersEnum
+syn keyword cConstant InversionNumCostFunctionsEnum
+syn keyword cConstant InversionStepThresholdEnum
+syn keyword cConstant InversionThicknessObsEnum
+syn keyword cConstant InversionVxObsEnum
+syn keyword cConstant InversionVyObsEnum
+syn keyword cConstant InversionVzObsEnum
+syn keyword cConstant MaskIceLevelsetEnum
+syn keyword cConstant QmuMaskIceLevelsetEnum
+syn keyword cConstant MaterialsBetaEnum
+syn keyword cConstant MaterialsHeatcapacityEnum
+syn keyword cConstant MaterialsLatentheatEnum
+syn keyword cConstant MaterialsMeltingpointEnum
+syn keyword cConstant MaterialsMixedLayerCapacityEnum
+syn keyword cConstant MaterialsRheologyBEnum
+syn keyword cConstant MaterialsRheologyBbarEnum
+syn keyword cConstant MaterialsRheologyLawEnum
+syn keyword cConstant MaterialsRheologyNEnum
+syn keyword cConstant DamageIsdamageEnum
+syn keyword cConstant DamageDEnum
+syn keyword cConstant DamageFEnum
+syn keyword cConstant QmuDamageDEnum
+syn keyword cConstant DamageDbarEnum
+syn keyword cConstant DamageLawEnum
+syn keyword cConstant DamageC1Enum
+syn keyword cConstant DamageC2Enum
+syn keyword cConstant DamageC3Enum
+syn keyword cConstant DamageC4Enum
+syn keyword cConstant DamageElementinterpEnum
+syn keyword cConstant DamageHealingEnum
+syn keyword cConstant DamageStressThresholdEnum
+syn keyword cConstant DamageStabilizationEnum
+syn keyword cConstant DamagePenaltyThresholdEnum
+syn keyword cConstant DamagePenaltyLockEnum
+syn keyword cConstant DamagePenaltyFactorEnum
+syn keyword cConstant DamageMaxiterEnum
+syn keyword cConstant DamageSpcdamageEnum
+syn keyword cConstant DamageMaxDamageEnum
+syn keyword cConstant DamageEquivStressEnum
+syn keyword cConstant DamageEvolutionNumRequestedOutputsEnum
+syn keyword cConstant DamageEvolutionRequestedOutputsEnum
+syn keyword cConstant MaterialsRhoIceEnum
+syn keyword cConstant MaterialsRhoSeawaterEnum
+syn keyword cConstant MaterialsRhoFreshwaterEnum
+syn keyword cConstant MaterialsMuWaterEnum
+syn keyword cConstant MaterialsThermalExchangeVelocityEnum
+syn keyword cConstant MaterialsThermalconductivityEnum
+syn keyword cConstant MaterialsTemperateiceconductivityEnum
+syn keyword cConstant MaterialsLithosphereShearModulusEnum
+syn keyword cConstant MaterialsLithosphereDensityEnum
+syn keyword cConstant MaterialsMantleShearModulusEnum
+syn keyword cConstant MaterialsMantleDensityEnum
+syn keyword cConstant MeshAverageVertexConnectivityEnum
+syn keyword cConstant MeshElements2dEnum
+syn keyword cConstant MeshElementsEnum
+syn keyword cConstant MeshLowerelementsEnum
+syn keyword cConstant MeshNumberofelements2dEnum
+syn keyword cConstant MeshNumberofelementsEnum
+syn keyword cConstant MeshNumberoflayersEnum
+syn keyword cConstant MeshNumberofvertices2dEnum
+syn keyword cConstant MeshNumberofverticesEnum
+syn keyword cConstant MeshUpperelementsEnum
+syn keyword cConstant MeshVertexonbaseEnum
+syn keyword cConstant MeshVertexonsurfaceEnum
+syn keyword cConstant MeshVertexonboundaryEnum
+syn keyword cConstant MeshXEnum
+syn keyword cConstant MeshYEnum
+syn keyword cConstant MeshZEnum
+syn keyword cConstant MeshElementtypeEnum
+syn keyword cConstant DomainTypeEnum
+syn keyword cConstant DomainDimensionEnum
+syn keyword cConstant Domain2DhorizontalEnum
+syn keyword cConstant Domain2DverticalEnum
+syn keyword cConstant Domain3DEnum
+syn keyword cConstant MiscellaneousNameEnum
+syn keyword cConstant MasstransportHydrostaticAdjustmentEnum
+syn keyword cConstant MasstransportIsfreesurfaceEnum
+syn keyword cConstant MasstransportMinThicknessEnum
+syn keyword cConstant MasstransportPenaltyFactorEnum
+syn keyword cConstant MasstransportSpcthicknessEnum
+syn keyword cConstant MasstransportCalvingrateEnum
+syn keyword cConstant MasstransportStabilizationEnum
+syn keyword cConstant MasstransportVertexPairingEnum
+syn keyword cConstant MasstransportNumRequestedOutputsEnum
+syn keyword cConstant MasstransportRequestedOutputsEnum
+syn keyword cConstant QmuIsdakotaEnum
+syn keyword cConstant MassFluxSegmentsEnum
+syn keyword cConstant MassFluxSegmentsPresentEnum
+syn keyword cConstant QmuMassFluxSegmentsPresentEnum
+syn keyword cConstant QmuNumberofpartitionsEnum
+syn keyword cConstant QmuNumberofresponsesEnum
+syn keyword cConstant QmuPartitionEnum
+syn keyword cConstant QmuResponsedescriptorsEnum
+syn keyword cConstant QmuVariabledescriptorsEnum
+syn keyword cConstant QmuMaterialsRheologyBEnum
+syn keyword cConstant RiftsNumriftsEnum
+syn keyword cConstant RiftsRiftstructEnum
+syn keyword cConstant SettingsResultsOnNodesEnum
+syn keyword cConstant SettingsIoGatherEnum
+syn keyword cConstant SettingsLowmemEnum
+syn keyword cConstant SettingsOutputFrequencyEnum
+syn keyword cConstant SettingsWaitonlockEnum
+syn keyword cConstant DebugProfilingEnum
+syn keyword cConstant ProfilingCurrentMemEnum
+syn keyword cConstant ProfilingCurrentFlopsEnum
+syn keyword cConstant ProfilingSolutionTimeEnum
+syn keyword cConstant MaxIterationConvergenceFlagEnum
+syn keyword cConstant SteadystateMaxiterEnum
+syn keyword cConstant SteadystateNumRequestedOutputsEnum
+syn keyword cConstant SteadystateReltolEnum
+syn keyword cConstant SteadystateRequestedOutputsEnum
+syn keyword cConstant SurfaceEnum
+syn keyword cConstant ThermalIsenthalpyEnum
+syn keyword cConstant ThermalIsdynamicbasalspcEnum
+syn keyword cConstant ThermalMaxiterEnum
+syn keyword cConstant ThermalPenaltyFactorEnum
+syn keyword cConstant ThermalPenaltyLockEnum
+syn keyword cConstant ThermalPenaltyThresholdEnum
+syn keyword cConstant ThermalSpctemperatureEnum
+syn keyword cConstant ThermalStabilizationEnum
+syn keyword cConstant ThermalNumRequestedOutputsEnum
+syn keyword cConstant ThermalRequestedOutputsEnum
+syn keyword cConstant GiaMantleViscosityEnum
+syn keyword cConstant GiaLithosphereThicknessEnum
+syn keyword cConstant ThicknessEnum
+syn keyword cConstant TimesteppingStartTimeEnum
+syn keyword cConstant TimesteppingFinalTimeEnum
+syn keyword cConstant TimesteppingCflCoefficientEnum
+syn keyword cConstant TimesteppingTimeAdaptEnum
+syn keyword cConstant TimesteppingTimeStepEnum
+syn keyword cConstant TimesteppingInterpForcingsEnum
+syn keyword cConstant TransientIsstressbalanceEnum
+syn keyword cConstant TransientIsgroundinglineEnum
+syn keyword cConstant TransientIsmasstransportEnum
+syn keyword cConstant TransientIsthermalEnum
+syn keyword cConstant TransientIsgiaEnum
+syn keyword cConstant TransientIsdamageevolutionEnum
+syn keyword cConstant TransientIshydrologyEnum
+syn keyword cConstant TransientNumRequestedOutputsEnum
+syn keyword cConstant TransientRequestedOutputsEnum
+syn keyword cConstant PotentialEnum
+syn keyword cConstant BalancethicknessSpcpotentialEnum
+syn keyword cConstant BalancethicknessApparentMassbalanceEnum
+syn keyword cConstant Balancethickness2MisfitEnum
+syn keyword cConstant BalancethicknessNuxEnum
+syn keyword cConstant BalancethicknessNuyEnum
+syn keyword cConstant BalancethicknessVxObsEnum
+syn keyword cConstant BalancethicknessVyObsEnum
+syn keyword cConstant BalancethicknessThicknessObsEnum
+syn keyword cConstant SurfaceforcingsEnum
+syn keyword cConstant SMBEnum
+syn keyword cConstant SurfaceforcingsMassBalanceEnum
+syn keyword cConstant SMBpddEnum
+syn keyword cConstant SurfaceforcingsDelta18oEnum
+syn keyword cConstant SurfaceforcingsDelta18oSurfaceEnum
+syn keyword cConstant SurfaceforcingsIsdelta18oEnum
+syn keyword cConstant SurfaceforcingsPrecipitationsPresentdayEnum
+syn keyword cConstant SurfaceforcingsTemperaturesPresentdayEnum
+syn keyword cConstant SurfaceforcingsTemperaturesLgmEnum
+syn keyword cConstant SurfaceforcingsPrecipitationEnum
+syn keyword cConstant SurfaceforcingsDesfacEnum
+syn keyword cConstant SurfaceforcingsS0pEnum
+syn keyword cConstant SMBgradientsEnum
+syn keyword cConstant SurfaceforcingsMonthlytemperaturesEnum
+syn keyword cConstant SurfaceforcingsHrefEnum
+syn keyword cConstant SurfaceforcingsSmbrefEnum
+syn keyword cConstant SurfaceforcingsBPosEnum
+syn keyword cConstant SurfaceforcingsBNegEnum
+syn keyword cConstant SMBhenningEnum
+syn keyword cConstant SMBcomponentsEnum
+syn keyword cConstant SurfaceforcingsAccumulationEnum
+syn keyword cConstant SurfaceforcingsEvaporationEnum
+syn keyword cConstant SurfaceforcingsRunoffEnum
+syn keyword cConstant SMBmeltcomponentsEnum
+syn keyword cConstant SurfaceforcingsMeltEnum
+syn keyword cConstant SurfaceforcingsRefreezeEnum
+syn keyword cConstant SurfaceforcingsIspddEnum
+syn keyword cConstant SurfaceforcingsIssmbgradientsEnum
+syn keyword cConstant SolutionTypeEnum
+syn keyword cConstant AnalysisTypeEnum
+syn keyword cConstant ConfigurationTypeEnum
+syn keyword cConstant AdjointBalancethicknessAnalysisEnum
+syn keyword cConstant AdjointBalancethickness2AnalysisEnum
+syn keyword cConstant AdjointHorizAnalysisEnum
+syn keyword cConstant AnalysisCounterEnum
+syn keyword cConstant DefaultAnalysisEnum
+syn keyword cConstant BalancethicknessAnalysisEnum
+syn keyword cConstant BalancethicknessSolutionEnum
+syn keyword cConstant Balancethickness2AnalysisEnum
+syn keyword cConstant Balancethickness2SolutionEnum
+syn keyword cConstant BalancethicknessSoftAnalysisEnum
+syn keyword cConstant BalancethicknessSoftSolutionEnum
+syn keyword cConstant BalancevelocityAnalysisEnum
+syn keyword cConstant BalancevelocitySolutionEnum
+syn keyword cConstant L2ProjectionEPLAnalysisEnum
+syn keyword cConstant L2ProjectionBaseAnalysisEnum
+syn keyword cConstant BedSlopeSolutionEnum
+syn keyword cConstant DamageEvolutionSolutionEnum
+syn keyword cConstant DamageEvolutionAnalysisEnum
+syn keyword cConstant StressbalanceAnalysisEnum
+syn keyword cConstant StressbalanceSIAAnalysisEnum
+syn keyword cConstant StressbalanceSolutionEnum
+syn keyword cConstant StressbalanceVerticalAnalysisEnum
+syn keyword cConstant EnthalpyAnalysisEnum
+syn keyword cConstant FlaimAnalysisEnum
+syn keyword cConstant FlaimSolutionEnum
+syn keyword cConstant HydrologyShreveAnalysisEnum
+syn keyword cConstant HydrologyDCInefficientAnalysisEnum
+syn keyword cConstant HydrologyDCEfficientAnalysisEnum
+syn keyword cConstant HydrologySolutionEnum
+syn keyword cConstant MeltingAnalysisEnum
+syn keyword cConstant MasstransportAnalysisEnum
+syn keyword cConstant MasstransportSolutionEnum
+syn keyword cConstant FreeSurfaceBaseAnalysisEnum
+syn keyword cConstant FreeSurfaceTopAnalysisEnum
+syn keyword cConstant SurfaceNormalVelocityEnum
+syn keyword cConstant ExtrudeFromBaseAnalysisEnum
+syn keyword cConstant ExtrudeFromTopAnalysisEnum
+syn keyword cConstant DepthAverageAnalysisEnum
+syn keyword cConstant SteadystateSolutionEnum
+syn keyword cConstant SurfaceSlopeSolutionEnum
+syn keyword cConstant SmoothedSurfaceSlopeXAnalysisEnum
+syn keyword cConstant SmoothedSurfaceSlopeYAnalysisEnum
+syn keyword cConstant ThermalAnalysisEnum
+syn keyword cConstant ThermalSolutionEnum
+syn keyword cConstant TransientSolutionEnum
+syn keyword cConstant GiaSolutionEnum
+syn keyword cConstant GiaAnalysisEnum
+syn keyword cConstant MeshdeformationSolutionEnum
+syn keyword cConstant MeshdeformationAnalysisEnum
+syn keyword cConstant LevelsetAnalysisEnum
+syn keyword cConstant ExtrapolationAnalysisEnum
+syn keyword cConstant LsfReinitializationAnalysisEnum
+syn keyword cConstant ApproximationEnum
+syn keyword cConstant NoneApproximationEnum
+syn keyword cConstant SIAApproximationEnum
+syn keyword cConstant SSAApproximationEnum
+syn keyword cConstant SSAHOApproximationEnum
+syn keyword cConstant SSAFSApproximationEnum
+syn keyword cConstant L1L2ApproximationEnum
+syn keyword cConstant HOApproximationEnum
+syn keyword cConstant HOFSApproximationEnum
+syn keyword cConstant FSApproximationEnum
+syn keyword cConstant FSvelocityEnum
+syn keyword cConstant FSpressureEnum
+syn keyword cConstant ConstraintsEnum
+syn keyword cConstant LoadsEnum
+syn keyword cConstant MaterialsEnum
+syn keyword cConstant NodesEnum
+syn keyword cConstant ContoursEnum
+syn keyword cConstant ParametersEnum
+syn keyword cConstant VerticesEnum
+syn keyword cConstant ResultsEnum
+syn keyword cConstant GenericParamEnum
+syn keyword cConstant AdolcParamEnum
+syn keyword cConstant BoolInputEnum
+syn keyword cConstant BoolParamEnum
+syn keyword cConstant ContourEnum
+syn keyword cConstant ControlInputEnum
+syn keyword cConstant DatasetInputEnum
+syn keyword cConstant DoubleInputEnum
+syn keyword cConstant DataSetParamEnum
+syn keyword cConstant DoubleMatArrayParamEnum
+syn keyword cConstant DoubleMatParamEnum
+syn keyword cConstant DoubleParamEnum
+syn keyword cConstant DoubleVecParamEnum
+syn keyword cConstant ElementEnum
+syn keyword cConstant ExternalResultEnum
+syn keyword cConstant FileParamEnum
+syn keyword cConstant InputEnum
+syn keyword cConstant IntInputEnum
+syn keyword cConstant InputToExtrudeEnum
+syn keyword cConstant InputToL2ProjectEnum
+syn keyword cConstant InputToDepthaverageEnum
+syn keyword cConstant IntParamEnum
+syn keyword cConstant IntVecParamEnum
+syn keyword cConstant TransientParamEnum
+syn keyword cConstant MaticeEnum
+syn keyword cConstant MatdamageiceEnum
+syn keyword cConstant MatparEnum
+syn keyword cConstant NodeEnum
+syn keyword cConstant NumericalfluxEnum
+syn keyword cConstant NumericalfluxTypeEnum
+syn keyword cConstant ParamEnum
+syn keyword cConstant PengridEnum
+syn keyword cConstant PenpairEnum
+syn keyword cConstant ProfilerEnum
+syn keyword cConstant MatrixParamEnum
+syn keyword cConstant NodeSIdEnum
+syn keyword cConstant VectorParamEnum
+syn keyword cConstant RiftfrontEnum
+syn keyword cConstant RiftfrontTypeEnum
+syn keyword cConstant SegmentEnum
+syn keyword cConstant SegmentRiftfrontEnum
+syn keyword cConstant SpcDynamicEnum
+syn keyword cConstant SpcStaticEnum
+syn keyword cConstant SpcTransientEnum
+syn keyword cConstant StringArrayParamEnum
+syn keyword cConstant StringParamEnum
+syn keyword cConstant SegEnum
+syn keyword cConstant SegInputEnum
+syn keyword cConstant TriaEnum
+syn keyword cConstant TriaInputEnum
+syn keyword cConstant TetraEnum
+syn keyword cConstant TetraInputEnum
+syn keyword cConstant PentaEnum
+syn keyword cConstant PentaInputEnum
+syn keyword cConstant VertexEnum
+syn keyword cConstant VertexPIdEnum
+syn keyword cConstant VertexSIdEnum
+syn keyword cConstant AirEnum
+syn keyword cConstant IceEnum
+syn keyword cConstant MelangeEnum
+syn keyword cConstant WaterEnum
+syn keyword cConstant ClosedEnum
+syn keyword cConstant FreeEnum
+syn keyword cConstant OpenEnum
+syn keyword cConstant AdjointpEnum
+syn keyword cConstant AdjointxEnum
+syn keyword cConstant AdjointyEnum
+syn keyword cConstant AdjointzEnum
+syn keyword cConstant BalancethicknessMisfitEnum
+syn keyword cConstant BedSlopeXEnum
+syn keyword cConstant BedSlopeYEnum
+syn keyword cConstant BoundaryEnum
+syn keyword cConstant ConvergedEnum
+syn keyword cConstant FillEnum
+syn keyword cConstant FractionIncrementEnum
+syn keyword cConstant FrictionEnum
+syn keyword cConstant InternalEnum
+syn keyword cConstant MassFluxEnum
+syn keyword cConstant MeltingOffsetEnum
+syn keyword cConstant MisfitEnum
+syn keyword cConstant PressureEnum
+syn keyword cConstant PressurePicardEnum
+syn keyword cConstant QmuPressureEnum
+syn keyword cConstant QmuVxEnum
+syn keyword cConstant QmuVyEnum
+syn keyword cConstant QmuVzEnum
+syn keyword cConstant QmuThicknessEnum
+syn keyword cConstant QmuBaseEnum
+syn keyword cConstant QmuSurfaceEnum
+syn keyword cConstant QmuMeltingEnum
+syn keyword cConstant QmuVxMeshEnum
+syn keyword cConstant QmuVyMeshEnum
+syn keyword cConstant QmuVzMeshEnum
+syn keyword cConstant AndroidFrictionCoefficientEnum
+syn keyword cConstant ResetPenaltiesEnum
+syn keyword cConstant SegmentOnIceShelfEnum
+syn keyword cConstant SurfaceAbsVelMisfitEnum
+syn keyword cConstant SurfaceAreaEnum
+syn keyword cConstant SurfaceAverageVelMisfitEnum
+syn keyword cConstant SurfaceLogVelMisfitEnum
+syn keyword cConstant SurfaceLogVxVyMisfitEnum
+syn keyword cConstant SurfaceRelVelMisfitEnum
+syn keyword cConstant SurfaceSlopeXEnum
+syn keyword cConstant SurfaceSlopeYEnum
+syn keyword cConstant TemperatureEnum
+syn keyword cConstant TemperaturePicardEnum
+syn keyword cConstant ThicknessAbsMisfitEnum
+syn keyword cConstant VelEnum
+syn keyword cConstant VelocityEnum
+syn keyword cConstant VxAverageEnum
+syn keyword cConstant VxEnum
+syn keyword cConstant VxPicardEnum
+syn keyword cConstant VyAverageEnum
+syn keyword cConstant VyEnum
+syn keyword cConstant VyPicardEnum
+syn keyword cConstant VzEnum
+syn keyword cConstant VzSSAEnum
+syn keyword cConstant VzHOEnum
+syn keyword cConstant VzPicardEnum
+syn keyword cConstant VzFSEnum
+syn keyword cConstant VxMeshEnum
+syn keyword cConstant VyMeshEnum
+syn keyword cConstant VzMeshEnum
+syn keyword cConstant EnthalpyEnum
+syn keyword cConstant EnthalpyPicardEnum
+syn keyword cConstant ThicknessAbsGradientEnum
+syn keyword cConstant ThicknessAlongGradientEnum
+syn keyword cConstant ThicknessAcrossGradientEnum
+syn keyword cConstant IntMatParamEnum
+syn keyword cConstant RheologyBbarAbsGradientEnum
+syn keyword cConstant DragCoefficientAbsGradientEnum
+syn keyword cConstant TransientInputEnum
+syn keyword cConstant WaterfractionEnum
+syn keyword cConstant WatercolumnEnum
+syn keyword cConstant BasalFrictionEnum
+syn keyword cConstant ViscousHeatingEnum
+syn keyword cConstant QmuTemperatureEnum
+syn keyword cConstant HydrologyWaterVxEnum
+syn keyword cConstant HydrologyWaterVyEnum
+syn keyword cConstant SigmaNNEnum
+syn keyword cConstant StressTensorEnum
+syn keyword cConstant StressTensorxxEnum
+syn keyword cConstant StressTensorxyEnum
+syn keyword cConstant StressTensorxzEnum
+syn keyword cConstant StressTensoryyEnum
+syn keyword cConstant StressTensoryzEnum
+syn keyword cConstant StressTensorzzEnum
+syn keyword cConstant DeviatoricStressEnum
+syn keyword cConstant DeviatoricStressxxEnum
+syn keyword cConstant DeviatoricStressxyEnum
+syn keyword cConstant DeviatoricStressxzEnum
+syn keyword cConstant DeviatoricStressyyEnum
+syn keyword cConstant DeviatoricStressyzEnum
+syn keyword cConstant DeviatoricStresszzEnum
+syn keyword cConstant StrainRateEnum
+syn keyword cConstant StrainRatexxEnum
+syn keyword cConstant StrainRatexyEnum
+syn keyword cConstant StrainRatexzEnum
+syn keyword cConstant StrainRateyyEnum
+syn keyword cConstant StrainRateyzEnum
+syn keyword cConstant StrainRatezzEnum
+syn keyword cConstant DivergenceEnum
+syn keyword cConstant GiaCrossSectionShapeEnum
+syn keyword cConstant GiadWdtEnum
+syn keyword cConstant GiaWEnum
+syn keyword cConstant P0Enum
+syn keyword cConstant P1Enum
+syn keyword cConstant P1DGEnum
+syn keyword cConstant P1bubbleEnum
+syn keyword cConstant P1bubblecondensedEnum
+syn keyword cConstant P2Enum
+syn keyword cConstant P2bubbleEnum
+syn keyword cConstant P2bubblecondensedEnum
+syn keyword cConstant P2xP1Enum
+syn keyword cConstant P1xP2Enum
+syn keyword cConstant P1xP3Enum
+syn keyword cConstant P2xP4Enum
+syn keyword cConstant P1P1Enum
+syn keyword cConstant P1P1GLSEnum
+syn keyword cConstant MINIEnum
+syn keyword cConstant MINIcondensedEnum
+syn keyword cConstant TaylorHoodEnum
+syn keyword cConstant XTaylorHoodEnum
+syn keyword cConstant OneLayerP4zEnum
+syn keyword cConstant CrouzeixRaviartEnum
+syn keyword cConstant SaveResultsEnum
+syn keyword cConstant BoolExternalResultEnum
+syn keyword cConstant DoubleExternalResultEnum
+syn keyword cConstant DoubleMatExternalResultEnum
+syn keyword cConstant IntExternalResultEnum
+syn keyword cConstant JEnum
+syn keyword cConstant StringExternalResultEnum
+syn keyword cConstant StepEnum
+syn keyword cConstant TimeEnum
+syn keyword cConstant WaterColumnOldEnum
+syn keyword cConstant OutputdefinitionEnum
+syn keyword cConstant OutputdefinitionListEnum
+syn keyword cConstant MassfluxatgateEnum
+syn keyword cConstant MassfluxatgateNameEnum
+syn keyword cConstant MassfluxatgateSegmentsEnum
+syn keyword cConstant MisfitNameEnum
+syn keyword cConstant MisfitModelEnumEnum
+syn keyword cConstant MisfitObservationEnum
+syn keyword cConstant MisfitObservationEnumEnum
+syn keyword cConstant MisfitTimeinterpolationEnum
+syn keyword cConstant MisfitWeightsEnum
+syn keyword cConstant MisfitWeightsEnumEnum
+syn keyword cConstant SurfaceObservationEnum
+syn keyword cConstant WeightsSurfaceObservationEnum
+syn keyword cConstant MinVelEnum
+syn keyword cConstant MaxVelEnum
+syn keyword cConstant MinVxEnum
+syn keyword cConstant MaxVxEnum
+syn keyword cConstant MaxAbsVxEnum
+syn keyword cConstant MinVyEnum
+syn keyword cConstant MaxVyEnum
+syn keyword cConstant MaxAbsVyEnum
+syn keyword cConstant MinVzEnum
+syn keyword cConstant MaxVzEnum
+syn keyword cConstant MaxAbsVzEnum
+syn keyword cConstant IceVolumeEnum
+syn keyword cConstant IceVolumeAboveFloatationEnum
+syn keyword cConstant TotalSmbEnum
+syn keyword cConstant AbsoluteEnum
+syn keyword cConstant IncrementalEnum
+syn keyword cConstant AugmentedLagrangianREnum
+syn keyword cConstant AugmentedLagrangianThetaEnum
+syn keyword cConstant NoneEnum
+syn keyword cConstant AggressiveMigrationEnum
+syn keyword cConstant SoftMigrationEnum
+syn keyword cConstant SubelementMigrationEnum
+syn keyword cConstant SubelementMigration2Enum
+syn keyword cConstant ContactEnum
+syn keyword cConstant MaskGroundediceLevelsetEnum
+syn keyword cConstant QmuMaskGroundediceLevelsetEnum
+syn keyword cConstant GaussSegEnum
+syn keyword cConstant GaussTriaEnum
+syn keyword cConstant GaussTetraEnum
+syn keyword cConstant GaussPentaEnum
+syn keyword cConstant FSSolverEnum
+syn keyword cConstant AdjointEnum
+syn keyword cConstant ColinearEnum
+syn keyword cConstant ControlSteadyEnum
+syn keyword cConstant FsetEnum
+syn keyword cConstant Gradient1Enum
+syn keyword cConstant Gradient2Enum
+syn keyword cConstant Gradient3Enum
+syn keyword cConstant GradientEnum
+syn keyword cConstant GroundinglineMigrationEnum
+syn keyword cConstant GsetEnum
+syn keyword cConstant IndexEnum
+syn keyword cConstant IndexedEnum
+syn keyword cConstant IntersectEnum
+syn keyword cConstant NodalEnum
+syn keyword cConstant OldGradientEnum
+syn keyword cConstant OutputFilePointerEnum
+syn keyword cConstant OutputFileNameEnum
+syn keyword cConstant LockFileNameEnum
+syn keyword cConstant ToolkitsOptionsAnalysesEnum
+syn keyword cConstant ToolkitsOptionsStringsEnum
+syn keyword cConstant QmuErrNameEnum
+syn keyword cConstant QmuInNameEnum
+syn keyword cConstant QmuOutNameEnum
+syn keyword cConstant RegularEnum
+syn keyword cConstant ScaledEnum
+syn keyword cConstant SeparateEnum
+syn keyword cConstant SsetEnum
+syn keyword cConstant VerboseEnum
+syn keyword cConstant TriangleInterpEnum
+syn keyword cConstant BilinearInterpEnum
+syn keyword cConstant NearestInterpEnum
+syn keyword cConstant XYEnum
+syn keyword cConstant XYZEnum
+syn keyword cConstant DenseEnum
+syn keyword cConstant MpiDenseEnum
+syn keyword cConstant MpiSparseEnum
+syn keyword cConstant SeqEnum
+syn keyword cConstant MpiEnum
+syn keyword cConstant MumpsEnum
+syn keyword cConstant GslEnum
+syn keyword cConstant OptionEnum
+syn keyword cConstant GenericOptionEnum
+syn keyword cConstant OptionCellEnum
+syn keyword cConstant OptionStructEnum
+syn keyword cConstant CuffeyEnum
+syn keyword cConstant PatersonEnum
+syn keyword cConstant ArrheniusEnum
+syn keyword cConstant LliboutryDuvalEnum
+syn keyword cConstant TransientIslevelsetEnum
+syn keyword cConstant ExtrapolationVariableEnum
+syn keyword cConstant IceMaskNodeActivationEnum
+syn keyword cConstant LevelsetfunctionSlopeXEnum
+syn keyword cConstant LevelsetfunctionSlopeYEnum
+syn keyword cConstant LevelsetfunctionPicardEnum
+"ISSM's Enums end
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+
+if !exists("c_no_ansi") || exists("c_ansi_typedefs")
+	syn keyword   cType		size_t ssize_t wchar_t ptrdiff_t sig_atomic_t fpos_t
+	syn keyword   cType		clock_t time_t va_list jmp_buf FILE DIR div_t ldiv_t
+	syn keyword   cType		mbstate_t wctrans_t wint_t wctype_t
+	syn keyword   cType		lldiv_t float_t double_t fenv_t fexcept_t
+endif
+if !exists("c_no_c99") " ISO C99
+	syn keyword	cType		bool complex imaginary
+	syn keyword	cType		int8_t int16_t int32_t int64_t
+	syn keyword	cType		uint8_t uint16_t uint32_t uint64_t
+	syn keyword	cType		int_least8_t int_least16_t int_least32_t int_least64_t
+	syn keyword	cType		uint_least8_t uint_least16_t uint_least32_t uint_least64_t
+	syn keyword	cType		int_fast8_t int_fast16_t int_fast32_t int_fast64_t
+	syn keyword	cType		uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t
+	syn keyword	cType		intptr_t uintptr_t
+	syn keyword	cType		intmax_t uintmax_t
+endif
+if exists("c_gnu")
+	syn keyword	cType		__label__ __complex__ __volatile__
+endif
+
+syn keyword	cStructure	struct union enum typedef
+syn keyword	cStorageClass	static register auto volatile extern const VOL
+if exists("c_gnu")
+	syn keyword	cStorageClass	inline __attribute__
+endif
+if !exists("c_no_c99")
+	syn keyword	cStorageClass	inline restrict
+endif
+
+if !exists("c_no_ansi") || exists("c_ansi_constants") || exists("c_gnu")
+	if exists("c_gnu")
+		syn keyword cConstant __GNUC__ __FUNCTION__ __PRETTY_FUNCTION__
+	endif
+	syn keyword cConstant __LINE__ __FILE__ __DATE__ __TIME__ __STDC__ __func__
+	syn keyword cConstant __STDC_VERSION__
+	syn keyword cConstant CHAR_BIT MB_LEN_MAX MB_CUR_MAX
+	syn keyword cConstant UCHAR_MAX UINT_MAX ULONG_MAX USHRT_MAX
+	syn keyword cConstant CHAR_MIN INT_MIN LONG_MIN SHRT_MIN
+	syn keyword cConstant CHAR_MAX INT_MAX LONG_MAX SHRT_MAX
+	syn keyword cConstant SCHAR_MIN SINT_MIN SLONG_MIN SSHRT_MIN
+	syn keyword cConstant SCHAR_MAX SINT_MAX SLONG_MAX SSHRT_MAX
+	if !exists("c_no_c99")
+		syn keyword cConstant LLONG_MIN LLONG_MAX ULLONG_MAX
+		syn keyword cConstant INT8_MIN INT16_MIN INT32_MIN INT64_MIN
+		syn keyword cConstant INT8_MAX INT16_MAX INT32_MAX INT64_MAX
+		syn keyword cConstant UINT8_MAX UINT16_MAX UINT32_MAX UINT64_MAX
+		syn keyword cConstant INT_LEAST8_MIN INT_LEAST16_MIN INT_LEAST32_MIN INT_LEAST64_MIN
+		syn keyword cConstant INT_LEAST8_MAX INT_LEAST16_MAX INT_LEAST32_MAX INT_LEAST64_MAX
+		syn keyword cConstant UINT_LEAST8_MAX UINT_LEAST16_MAX UINT_LEAST32_MAX UINT_LEAST64_MAX
+		syn keyword cConstant INT_FAST8_MIN INT_FAST16_MIN INT_FAST32_MIN INT_FAST64_MIN
+		syn keyword cConstant INT_FAST8_MAX INT_FAST16_MAX INT_FAST32_MAX INT_FAST64_MAX
+		syn keyword cConstant UINT_FAST8_MAX UINT_FAST16_MAX UINT_FAST32_MAX UINT_FAST64_MAX
+		syn keyword cConstant INTPTR_MIN INTPTR_MAX UINTPTR_MAX
+		syn keyword cConstant INTMAX_MIN INTMAX_MAX UINTMAX_MAX
+		syn keyword cConstant PTRDIFF_MIN PTRDIFF_MAX SIG_ATOMIC_MIN SIG_ATOMIC_MAX
+		syn keyword cConstant SIZE_MAX WCHAR_MIN WCHAR_MAX WINT_MIN WINT_MAX
+	endif
+	syn keyword cConstant FLT_RADIX FLT_ROUNDS
+	syn keyword cConstant FLT_DIG FLT_MANT_DIG FLT_EPSILON
+	syn keyword cConstant DBL_DIG DBL_MANT_DIG DBL_EPSILON
+	syn keyword cConstant LDBL_DIG LDBL_MANT_DIG LDBL_EPSILON
+	syn keyword cConstant FLT_MIN FLT_MAX FLT_MIN_EXP FLT_MAX_EXP
+	syn keyword cConstant FLT_MIN_10_EXP FLT_MAX_10_EXP
+	syn keyword cConstant DBL_MIN DBL_MAX DBL_MIN_EXP DBL_MAX_EXP
+	syn keyword cConstant DBL_MIN_10_EXP DBL_MAX_10_EXP
+	syn keyword cConstant LDBL_MIN LDBL_MAX LDBL_MIN_EXP LDBL_MAX_EXP
+	syn keyword cConstant LDBL_MIN_10_EXP LDBL_MAX_10_EXP
+	syn keyword cConstant HUGE_VAL CLOCKS_PER_SEC NULL _NO_LEAP_SECONDS _LOCALTIME
+	syn keyword cConstant LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY
+	syn keyword cConstant LC_NUMERIC LC_TIME
+	" syn keyword cConstant SIG_DFL SIG_ERR SIG_IGN
+	syn keyword cAnsiFuncPtr SIG_DFL SIG_ERR SIG_IGN
+	syn keyword cConstant SIGABRT SIGFPE SIGILL SIGHUP SIGINT SIGSEGV SIGTERM
+	syn keyword cConstant INFINITY     FP_SUBNORMAL FP_ILOGB0
+	syn keyword cConstant NAN          FP_ZERO      FP_ILOGBNAN
+	syn keyword cConstant FP_INFINITE  FP_FAST_FMA
+	syn keyword cConstant HUGE_VALF    FP_NAN       FP_FAST_FMAF
+	syn keyword cConstant HUGE_VALL    FP_NORMAL    FP_FAST_FMAL
+	syn keyword cConstant FE_OVERFLOW      FE_TOWARDZERO
+	syn keyword cConstant FE_UNDERFLOW     FE_UPWARD
+	syn keyword cConstant FE_DIVBYZERO     FE_ALL_EXCEPT    FE_DFL_ENV
+	syn keyword cConstant FE_INEXACT       FE_DOWNWARD
+	syn keyword cConstant FE_INVALID       FE_TONEAREST
+	syn keyword cConstant	_Complex_I _Imaginary_I 
+	" Add POSIX signals as well...
+	syn keyword cConstant SIGABRT SIGALRM SIGCHLD SIGCONT SIGFPE SIGHUP
+	syn keyword cConstant SIGILL SIGINT SIGKILL SIGPIPE SIGQUIT SIGSEGV
+	syn keyword cConstant SIGSTOP SIGTERM SIGTRAP SIGTSTP SIGTTIN SIGTTOU
+	syn keyword cConstant SIGUSR1 SIGUSR2
+	syn keyword cConstant _IOFBF _IOLBF _IONBF BUFSIZ EOF WEOF
+	syn keyword cConstant FOPEN_MAX FILENAME_MAX L_tmpnam
+	syn keyword cConstant SEEK_CUR SEEK_END SEEK_SET
+	syn keyword cConstant TMP_MAX stderr stdin stdout
+	syn keyword cConstant EXIT_FAILURE EXIT_SUCCESS RAND_MAX
+	" Add POSIX errors as well
+	syn keyword cConstant E2BIG EACCES EAGAIN EBADF EBADMSG EBUSY
+	syn keyword cConstant ECANCELED ECHILD EDEADLK EDOM EEXIST EFAULT
+	syn keyword cConstant EFBIG EILSEQ EINPROGRESS EINTR EINVAL EIO EISDIR
+	syn keyword cConstant EMFILE EMLINK EMSGSIZE ENAMETOOLONG ENFILE ENODEV
+	syn keyword cConstant ENOENT ENOEXEC ENOLCK ENOMEM ENOSPC ENOSYS
+	syn keyword cConstant ENOTDIR ENOTEMPTY ENOTSUP ENOTTY ENXIO EPERM
+	syn keyword cConstant EPIPE ERANGE EROFS ESPIPE ESRCH ETIMEDOUT EXDEV
+	" math.h
+	syn keyword cConstant M_E M_LOG2E M_LOG10E M_LN2 M_LN10 M_PI M_PI_2 M_PI_4
+	syn keyword cConstant M_1_PI M_2_PI M_2_SQRTPI M_SQRT2 M_SQRT1_2
+endif
+if !exists("c_no_c99") " ISO C99
+	syn keyword cConstant true false __bool_true_false_are_defined
+endif
+
+" Accept %: for # (C99)
+syn region	cPreCondit	start="^\s*\(%:\|#\)\s*\(ifdef\|ifndef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=cComment,cCppString,cCharacter,cCppParen,cParenError,cNumbers,cCommentError,cSpaceError
+syn keyword	cDefined	defined contained
+"syn match	cDefined	display contained "\<defined(\w\+)" contains=cName,cAnsiName
+syn region	cPreConditIf	start="^\s*\(%:\|#\)\s*\(if\|elif\)\>" skip="\\$" end="$" end="//"me=s-1 contains=cDefined,cComment,cCppString,cCharacter,cCppParen,cParenError,cNumbers,cCommentError,cSpaceError
+syn match	cPreCondit	display "^\s*\(%:\|#\)\s*\(else\|endif\)\>"
+if !exists("c_no_if0")
+	syn region	cCppOut		start="^\s*\(%:\|#\)\s*if\s\+0\+\>" end=".\@=\|$" contains=cCppOut2
+	syn region	cCppOut2	contained start="0" end="^\s*\(%:\|#\)\s*\(endif\>\|else\>\|elif\>\)" contains=cSpaceError,cCppSkip
+		syn region	cCppSkip	contained start="^\s*\(%:\|#\)\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*\(%:\|#\)\s*endif\>" contains=cSpaceError,cCppSkip
+	endif
+	syn region	cIncluded	display contained start=+"+ skip=+\\\\\|\\"+ end=+"+
+	syn match	cIncluded	display contained "<[^>]*>"
+	syn match	cInclude	display "^\s*\(%:\|#\)\s*include\>\s*["<]" contains=cIncluded
+	syn match cLineSkip	"\\$"
+	syn cluster	cPreProcGroup	contains=cPreConditIf,cPreCondit,cIncluded,cInclude,cDefined,cDefine,cErrInParen,cErrInBracket,cUserLabel,cUserLabel2,cGotoLabel,cSpecial,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cString,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cParen,cBracket,cMulti
+	"syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,@Spell
+	syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,cName,cFunction,cAnsiFunction,@Spell
+	syn region	cPreProc	start="^\s*\(%:\|#\)\s*\(pragma\>\|line\>\|warning\>\|warn\>\|error\>\)" skip="\\$" end="$" keepend contains=ALLBUT,@cPreProcGroup,@Spell
+
+	" Highlight User Labels
+	syn cluster	cMultiGroup	contains=cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cUserLabel2,cGotoLabel,cBitField,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cCppParen,cCppBracket,cCppString
+	syn region	cMulti		transparent start='?' skip='::' end=':' contains=ALLBUT,@cMultiGroup,@Spell
+	" Avoid matching foo::bar() in C++ by requiring that the next char is not ':'
+	syn cluster	cLabelGroup	contains=cUserLabel
+	syn match	cUserCont	display "^\s*\I\i*\s*:$" contains=@cLabelGroup
+	syn match	cUserCont	display ";\s*\I\i*\s*:$" contains=@cLabelGroup
+	syn match	cUserCont	display "^\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
+	syn match	cUserCont	display ";\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
+
+	syn match	cUserLabel	display "\I\i*" contained
+	syn match	cUserLabel2	display "\I\i*:;\+"me=e-2
+	syn match	cGotoLabel	display "\<goto\s\+\I\i*;"me=e-1,hs=s+5 contains=cGoto
+	syn keyword	cGoto		contained goto
+
+	" Avoid recognizing most bitfields as labels
+	syn match	cBitField	display "^\s*\I\i*\s*:\s*[1-9]"me=e-1
+	syn match	cBitField	display ";\s*\I\i*\s*:\s*[1-9]"me=e-1
+
+	syn match cOperator	"\(<<\|>>\|[-+*/%&^|<>!=]\)="
+	syn match cOperator	"<<\|>>\|&&\|||\|++\|--\|->"
+	syn match cOperator	"[.!~*&%<>^|=+-]"
+	syn match cOperator	"/[^/*=]"me=e-1
+	syn match cOperator	"/$"
+	syn match cOperator	"[\\]"
+	syn match cOperator	"&&\|||"
+	syn match cSpecialCharacter	"[,;]"
+	syn match cDelimiter    "[][(){}]"
+	syn keyword	cType		CHAR byte BYTE uchar ushort uint ulong
+	syn keyword	cType		WORD DWORD QWORD INT INT2 INT4 UNS UNS2 UNS4 INT8 UNS8
+	syn keyword	cType		CFG_t cfap_t cBYTE cvoid
+	syn keyword	cType		_Bool _Complex _Imaginary __int64
+	if !exists("c_no_ansi") || exists("c_ansi_typedefs")
+		syn keyword   cMC	__near __far FAR __io __direct DIR
+	endif
+
+	if exists("c_minlines")
+		let b:c_minlines = c_minlines
+	else
+		if !exists("c_no_if0")
+			let b:c_minlines = 50	" #if 0 constructs can be long
+		else
+			let b:c_minlines = 15	" mostly for () constructs
+		endif
+	endif
+	exec "syn sync ccomment cComment minlines=" . b:c_minlines
+
+	" Define the default highlighting.
+	" For version 5.7 and earlier: only when not done already
+	" For version 5.8 and later: only when an item doesn't have highlighting yet
+	if version >= 508 || !exists("did_c_syn_inits")
+		if version < 508
+			let did_c_syn_inits = 1
+			command -nargs=+ HiLink hi link <args>
+		else
+			command -nargs=+ HiLink hi def link <args>
+		endif
+
+		HiLink cFormat	cSpecial
+		HiLink cCppString	cString
+		HiLink cCommentL	cComment
+		HiLink cCommentStart	cComment
+		HiLink cLabel		Label
+		" HiLink cUserLabel	Label
+		HiLink cUserLabel	UserLabel2
+		HiLink cUserLabel2	UserLabel2
+		HiLink cGotoLabel	UserLabel2
+		HiLink cGoto		Statement
+		HiLink cConditional	Conditional
+		HiLink cRepeat	Repeat
+		HiLink cCharacter	Character
+		HiLink cSpecialCharacter cSpecial
+		HiLink cNumber	Number
+		HiLink cOctal		Number
+		HiLink cOctalZero	PreProc		" link this to Error if you want
+		HiLink cFloat		Float
+		HiLink cOctalError	cError
+		HiLink cParenError	cError
+		HiLink cErrInParen	cError
+		HiLink cErrInBracket	cError
+		HiLink cCommentError	cError
+		HiLink cCommentStartError	cError
+		HiLink cSpaceError	cError
+		HiLink cSpecialError	cError
+		HiLink cOperator	Operator
+		HiLink cOperatorBold	OperatorBold
+		HiLink cStructure	Structure
+		HiLink cStorageClass	StorageClass
+		HiLink cInclude	Include
+		HiLink cPreProc	PreProc
+		HiLink cDefine	Macro
+		HiLink cDefined	PreCondit
+		HiLink cIncluded	cString
+		HiLink cError		Error
+		HiLink cStatement	Statement
+		HiLink cPreCondit	PreCondit
+		HiLink cPreConditIf	PreCondit
+		HiLink cType		Type
+		HiLink cConstant	Constant
+		HiLink cCommentString cString
+		HiLink cComment2String cString
+		HiLink cCommentSkip	cComment
+		HiLink cString	String
+		HiLink cComment	Comment
+		HiLink cDelimiter     Delimiter
+		HiLink cSpecial	SpecialChar
+		HiLink cTodo		Todo
+		HiLink cCppSkip	cCppOut
+		HiLink cCppOut2	cCppOut
+		HiLink cCppOut	Comment
+		HiLink cMulti		Operator
+		HiLink cMultiMG	Operator
+		HiLink cFunction	Function
+		HiLink cAnsiFunction	StdFunction
+		HiLink cName		Name
+		HiLink cBitField	Name
+		HiLink cAnsiName	StdName
+		"HiLink cBlock	BlockBraces
+		HiLink cBraces	BlockBraces
+		"HiLink cBraceError	Error
+		HiLink cMC		MicroController
+		HiLink cAnsiFuncPtr	AnsiFuncPtr
+
+		hi Function		gui=NONE guifg=#e86f00
+		"hi StdFunction	gui=bold guifg=#ee0040
+		hi StdFunction	gui=bold guifg=#e86f00
+		hi Statement		gui=bold guifg=#a06129
+		hi UserLabel2		gui=bold guifg=#c96129
+		hi Operator		gui=NONE guifg=#000000
+		hi OperatorBold	gui=bold guifg=#000000
+		hi StdName		gui=bold guifg=#5276e6
+		hi Name		gui=NONE guifg=#5276e6
+		hi BlockBraces	gui=bold guifg=#000000
+		hi Special		gui=NONE guifg=#a000a0
+		hi Comment		gui=NONE guifg=grey62
+		hi MicroController	gui=bold guifg=#d00000
+		hi AnsiFuncPtr	gui=NONE guifg=#ff0000
+		" hi PreProc        	gui=NONE guifg=#6a5acd
+		hi PreCondit      	gui=NONE guifg=#6a5acd
+		" hi Macro          	gui=NONE guifg=#0000ff
+
+		delcommand HiLink
+	endif
+	hi Normal		gui=NONE guifg=#000000 guibg=Ivory1
+
+	let b:current_syntax = "c"
+
+	" vim: ts=8
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/matlab.vim
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/matlab.vim	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/syntax/matlab.vim	(revision 18231)
@@ -0,0 +1,357 @@
+" Vim syntax file
+" Language:	Matlab
+" Maintainer:	Fabrice Guy <fabrice.guy at gmail dot com>
+"		Original authors: Mario Eusebio and Preben Guldberg
+" Last Change:	2008 Oct 16 : added try/catch/rethrow and class statements
+" 		2008 Oct 28 : added highlighting for most of Matlab functions
+" 		2009 Nov 23 : added 'todo' keyword in the matlabTodo keywords 
+" 		(for doxygen support)
+
+" For version 5.x: Clear all syntax items
+" For version 6.x: Quit when a syntax file was already loaded
+if version < 600
+  syntax clear
+elseif exists("b:current_syntax")
+  finish
+endif
+
+syn keyword matlabStatement		return function
+syn keyword matlabConditional		switch case else elseif end if otherwise break continue
+syn keyword matlabRepeat		do for while
+syn keyword matlabStorageClass		classdef methods properties events persistent global
+syn keyword matlabExceptions		try catch rethrow throw
+
+syn keyword matlabTodo			contained  TODO NOTE FIXME XXX
+syn keyword matlabImport		import
+" If you do not want these operators lit, uncommment them and the "hi link" below
+syn match  matlabRelationalOperator	"\(==\|\~=\|>=\|<=\|=\~\|>\|<\|=\)"
+syn match matlabArithmeticOperator	"[-+]"
+syn match matlabArithmeticOperator	"\.\=[*/\\^]"
+syn match matlabLogicalOperator		"[&|~]"
+syn keyword matlabBoolean		true false
+
+syn match matlabLineContinuation	"\.\{3}"
+
+" String
+syn region matlabString			start=+'+ end=+'+	oneline
+
+" If you don't like tabs
+syn match matlabTab			"\t"
+
+" Standard numbers
+syn match matlabNumber		"\<\d\+[ij]\=\>"
+" floating point number, with dot, optional exponent
+syn match matlabFloat		"\<\d\+\(\.\d*\)\=\([edED][-+]\=\d\+\)\=[ij]\=\>"
+" floating point number, starting with a dot, optional exponent
+syn match matlabFloat		"\.\d\+\([edED][-+]\=\d\+\)\=[ij]\=\>"
+syn keyword matlabConstant	eps Inf NaN pi
+
+
+" Transpose character and delimiters: Either use just [...] or (...) aswell
+syn match matlabDelimiter		"[][]"
+"syn match matlabDelimiter		"[][()]"
+syn match matlabTransposeOperator	"[])a-zA-Z0-9.]'"lc=1
+
+syn match matlabSemicolon		";"
+
+syn match matlabComment			"%.*$"	contains=matlabTodo,matlabTab
+syn region matlabBlockComment        start=+%{+    end=+%}+ contains=matlabBlockComment
+
+
+" trigonometric
+syn keyword matlabFunc 			acos acosd acosh acot acotd acoth acsc acscd acsch asec asecd asech asin asind asinh
+syn keyword matlabFunc 			atan atan2 atand atanh cos cosd cosh cot cotd coth csc cscd csch hypot sec secd
+syn keyword matlabFunc 			sech sin sind sinh tan tand tanh
+" exponential
+syn keyword matlabFunc 			exp expm1 log log10 log1p log2 nextpow2 nthroot pow2 reallog realpow realsqrt sqrt
+" Complex
+syn keyword matlabFunc 			abs angle complex conj cplxpair  imag real sign unwrap
+" Rounding and Remainder
+syn keyword matlabFunc 			ceil fix floor idivide mod rem round
+"Discrete Math (e.g., Prime Factors)
+syn keyword matlabFunc 			factor factorial gcd isprime lcm nchoosek perms primes rat rats
+"Polynomials
+syn keyword matlabFunc 			conv deconv poly polyder polyeig polyfit polyint polyval polyvalm residue roots
+"Numeric Types
+syn keyword matlabFunc 			arrayfun cast cat class find intmax intmin intwarning ipermute isa isequal isequalwithequalnans isfinite isinf isnan isnumeric isreal isscalar isvector permute realmax realmin reshape squeeze zeros
+"Characters and Strings
+syn keyword matlabFunc 			cellstr char eval findstr isstr regexp sprintf sscanf strcat strcmp strcmpi strncmp strncmpi strings strjust strmatch strread strrep strtrim strvcat
+"Structures
+syn keyword matlabFunc 			cell2struct deal fieldnames getfield  isfield isstruct orderfields rmfield setfield struct struct2cell structfun
+"Cell Arrays
+syn keyword matlabFunc 			cell cell2mat celldisp cellfun cellplot iscell iscellstr mat2cell num2cell
+"Function Handles
+syn keyword matlabFunc 			feval func2str functions str2func
+"Java Classes and Objects
+syn keyword matlabFunc 			clear depfun exist im2java inmem javaaddpath javaArray javachk Generate javaclasspath javaMethod javaObject javarmpath methodsview usejava which
+"Data Type Identification
+syn keyword matlabFunc 			ischar isfloat isinteger isjava islogical isobject validateattributes who whos
+"Data type conversion
+"Numeric
+syn keyword matlabFunc 			double int8 int16 int32 int64 single typecast uint8 uint16 uint32 uint64
+"String to Numeric
+syn keyword matlabFunc 			base2dec bin2dec hex2dec hex2num str2double str2num unicode2native
+"Numeric to String
+syn keyword matlabFunc 			dec2base dec2bin dec2hex int2str mat2str native2unicode num2str
+"Other Conversions
+syn keyword matlabFunc 			datestr logical num2hex str2mat
+"String Creation
+syn keyword matlabFunc 			blanks
+"String Identification
+syn keyword matlabFunc 			isletter isspace isstrprop validatestring 
+"String Manipulation
+syn keyword matlabFunc 			deblank lower upper
+"String Parsing
+syn keyword matlabFunc 			regexpi regexprep regexptranslate strfind strtok 
+"String Evaluation
+syn keyword matlabFunc 			evalc evalin
+"String Comparison
+syn keyword matlabFunc 			strncmp strncmpi
+"Bit-wise Functions
+syn keyword matlabFunc			bitand bitcmp bitget bitmax bitor bitset bitshift bitxor swapbytes
+"Logical Functions
+syn keyword matlabFunc			all and any iskeyword isvarname not or xor
+"Predefined Dialog Boxes
+syn keyword matlabFunc dialog errordlg export2wsdlg helpdlg inputdlg listdlg msgbox printdlg printpreview questdlg uigetdir uigetfile uigetpref uiopen uiputfile uisave uisetcolor uisetfont waitbar warndlg
+"Deploying User Interfaces
+syn keyword matlabFunc guidata guihandles movegui openfig
+"Developing User Interfaces
+syn keyword matlabFunc addpref getappdata getpref ginput guide inspect isappdata ispref rmappdata rmpref setappdata setpref uisetpref waitfor waitforbuttonpress
+"User Interface Objects
+syn keyword matlabFunc uibuttongroup uicontextmenu uicontrol uimenu uipanel uipushtool uitoggletool uitoolbar menu
+"Finding Objects from Callbacks
+syn keyword matlabFunc findall findfigs findobj gcbf gcbo 
+"GUI Utility Functions
+syn keyword matlabFunc align getpixelposition listfonts selectmoveresize setpixelposition textwrap uistack
+"Controlling Program Execution
+syn keyword matlabFunc uiresume uiwait	
+"Basic Plots and Graphs
+syn keyword matlabFunc box errorbar hold  loglog  plot plot3 plotyy polar semilogx semilogy subplot
+"Plotting Tools
+syn keyword matlabFunc figurepalette pan plotbrowser plotedit plottools propertyeditor rotate3d  showplottool zoom 
+
+"Annotating Plots
+syn keyword matlabFunc annotation clabel datacursormode datetick gtext legend  line rectangle texlabel title xlabel ylabel zlabel
+"Area, Bar, and Pie Plots
+syn keyword matlabFunc area bar barh bar3 bar3h pareto pie pie3
+"Contour Plots
+syn keyword matlabFunc contour contour3  contourc contourf ezcontour ezcontourf
+"Direction and Velocity Plots
+syn keyword matlabFunc comet comet3 compass feather quiver quiver3 
+"Discrete Data Plots
+syn keyword matlabFunc stairs stem stem3
+"Function Plots
+syn keyword matlabFunc ezmesh ezmeshc ezplot ezplot3 ezpolar ezsurf ezsurfc fplot 
+"Histograms
+syn keyword matlabFunc hist histc rose
+"Polygons and Surfaces
+syn keyword matlabFunc convhull cylinder delaunay delaunay3 delaunayn dsearch dsearchn ellipsoid fill fill3 inpolygon pcolor  polyarea rectint ribbon slice sphere tsearch tsearchn voronoi waterfall
+"Scatter/Bubble Plots
+syn keyword matlabFunc plotmatrix scatter scatter3
+"Animation
+syn keyword matlabFunc getframe im2frame movie  noanimate
+"Bit-Mapped Images
+syn keyword matlabFunc frame2im image imagesc imfinfo imformats imread imwrite ind2rgb
+"Printing
+syn keyword matlabFunc frameedit hgexport orient print printopt saveas 
+"Handle Graphics
+syn keyword matlabFunc allchild ancestor copyobj delete gca gco get ishandle propedit set
+"Object 
+syn keyword matlabFunc axes figure hggroup hgtransform light patch colormap colorbar
+"root object	
+syn keyword matlabFunc surface text
+"Plot Objects
+syn keyword matlabFunc clf close closereq drawnow gcf hgload hgsave newplot opengl refresh
+"Axes Operations
+syn keyword matlabFunc axis cla grid ishold makehgtform
+"Operating on Object Properties
+syn keyword matlabFunc linkaxes linkprop refreshdata
+"Data analysis
+"Basic Operations
+syn keyword matlabFunc brush cumprod cumsum linkdata prod sort sortrows sum 
+"Descriptive Statistics
+syn keyword matlabFunc corrcoef cov max mean median min mode std var
+"Filtering and Convolution
+syn keyword matlabFunc conv2 convn detrend filter filter2 
+"Interpolation and Regression
+syn keyword matlabFunc interp1 interp2 interp3 interpn mldivide mrdivide
+"Fourier Transforms
+syn keyword matlabFunc fft fft2 fftn fftshift fftw ifft ifft2 ifftn ifftshift
+"Derivatives and Integrals
+syn keyword matlabFunc cumtrapz del2 diff gradient trapz 
+"File Operations
+syn keyword matlabFunc cd copyfile dir fileattrib filebrowser isdir lookfor ls matlabroot mkdir movefile pwd recycle rehash rmdir toolboxdir type what
+"Operating System Interface
+syn keyword matlabFunc clipboard computer dos getenv hostid maxNumCompThreads perl setenv system unix winqueryreg
+"MATLAB Version and License
+syn keyword matlabFunc ismac ispc isstudent isunix javachk license prefdir usejava ver verLessThan version 
+"Basic Information
+syn keyword matlabFunc disp display isempty issparse length ndims numel size 
+"Elementary Matrices and Arrays
+syn keyword matlabFunc blkdiag diag eye freqspace ind2sub linspace logspace meshgrid ndgrid ones rand randn sub2ind 
+"Array Operations
+syn keyword matlabFunc accumarray bsxfun cross dot kron tril triu 
+"Array Manipulation
+syn keyword matlabFunc circshift flipdim fliplr flipud horzcat inline repmat rot90 shiftdim vectorize vertcat transp
+"Specialized Matrices
+syn keyword matlabFunc compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson
+"Matrix Analysis
+syn keyword matlabFunc cond condeig det norm normest null orth rank rcond rref subspace trace
+"Linear Equations
+syn keyword matlabFunc chol cholinc condest funm ilu inv linsolve lscov lsqnonneg lu luinc pinv qr 
+"Eigenvalues and Singular Values
+syn keyword matlabFunc balance cdf2rdf eig eigs gsvd hess ordeig ordqz ordschur rsf2csf schur sqrtm ss2tf svd svds
+"Matrix Logarithms and Exponentials
+syn keyword matlabFunc expm logm 
+"Factorization
+syn keyword matlabFunc cholupdate planerot qrdelete qrinsert qrupdate qz 
+"Interpolation
+syn keyword matlabFunc griddata griddata3 griddatan interp1q interpft mkpp padecoef pchip ppval spline unmkpp 
+"Delaunay Triangulation and Tessellation
+syn keyword matlabFunc tetramesh trimesh triplot trisurf 
+"Convex Hull
+syn keyword matlabFunc convhulln	
+"Voronoi Diagrams
+syn keyword matlabFunc voronoin
+"Cartesian Coordinate System Conversion
+syn keyword matlabFunc cart2pol cart2sph pol2cart sph2cart 
+"Ordinary Differential Equations (IVP)
+syn keyword matlabFunc decic deval ode15i ode23 ode45 ode113 ode15s ode23s ode23t ode23tb odefile odeget odeset odextend
+"Delay Differential Equations
+syn keyword matlabFunc dde23 ddeget ddesd ddeset 
+"Boundary Value Problems
+syn keyword matlabFunc bvp4c bvp5c bvpget bvpinit bvpset bvpxtend
+"Partial Differential Equations
+syn keyword matlabFunc pdepe pdeval 
+"Optimization
+syn keyword matlabFunc fminbnd fminsearch fzero optimget optimset
+"Numerical Integration (Quadrature)
+syn keyword matlabFunc dblquad quad quadgk quadl quadv triplequad
+"Specialized Math
+syn keyword matlabFunc airy besselh besseli besselj besselk bessely beta betainc betaln ellipj ellipke erf erfc erfcx erfinv erfcinv expint gamma gammainc gammaln legendre psi
+"Elementary Sparse Matrices
+syn keyword matlabFunc spdiags speye sprand sprandn sprandsym
+"Full to Sparse Conversion
+syn keyword matlabFunc full sparse spconvert
+"Working with Sparse Matrices
+syn keyword matlabFunc nnz nonzeros nzmax spalloc spfun spones spparms spy 
+"Reordering Algorithms
+syn keyword matlabFunc amd colamd colperm dmperm ldl randperm symamd symrcm 
+"Linear Algebra
+syn keyword matlabFunc spaugment sprank 
+"Linear Equations (Iterative Methods)
+syn keyword matlabFunc bicg bicgstab cgs gmres lsqr minres pcg qmr symmlq 
+"Tree Operations
+syn keyword matlabFunc etree etreeplot gplot symbfact treelayout treeplot 
+"Timeseries
+"General Purpose
+syn keyword matlabFunc getdatasamplesize getqualitydesc timeseries tsprops tstool
+"Data Manipulation
+syn keyword matlabFunc addsample ctranspose delsample getabstime getinterpmethod getsampleusingtime idealfilter resample setabstime setinterpmethod synchronize transpose
+"Event Data
+syn keyword matlabFunc addevent delevent gettsafteratevent gettsafterevent gettsatevent gettsbeforeatevent gettsbeforeevent  gettsbetweenevents
+"Descriptive Statistics
+syn keyword matlabFunc iqr
+
+"Time Series Collections
+"General Purpose
+syn keyword matlabFunc tscollection
+"Data Manipulation
+syn keyword matlabFunc addsampletocollection addts delsamplefromcollection gettimeseriesnames removets settimeseriesnames
+"Set Functions
+syn keyword matlabFunc intersect ismember issorted setdiff setxor union unique 
+"Date and Time Functions
+syn keyword matlabFunc addtodate calendar clock cputime date datenum datevec eomday etime now weekday
+"M-File Functions and Scripts
+syn keyword matlabFunc addOptional addParamValue addRequired createCopy depdir echo input inputname inputParser mfilename namelengthmax nargchk nargin nargout nargoutchk parse pcode
+"script	Script M-file description
+syn keyword matlabFunc varargin varargout
+"Evaluation of Expressions and Functions
+syn keyword matlabFunc ans assert builtin pause run script symvar
+"Timer Functions
+syn keyword matlabFunc isvalid start startat stop timer timerfind timerfindall wait 
+"Variables and Functions in Memory
+syn keyword matlabFunc assignin datatipinfo genvarname isglobal memory mislocked mlock munlock pack
+"Control Flow
+syn keyword matlabFunc parfor
+"Error Handling
+syn keyword matlabFunc addCause error ferror getReport last lasterr lasterror lastwarn warning
+"Classes and Objects
+syn keyword matlabFunc addlistener addprop dynamicprops 
+"events 	Display class event names
+syn keyword matlabFunc findprop getdisp handle hgsetget inferiorto loadobj metaclass notify saveobj setdisp subsasgn subsindex subsref substruct superiorto 
+"File Name Construction
+syn keyword matlabFunc filemarker fileparts filesep fullfile tempdir tempname 
+"Opening, Loading, Saving Files
+syn keyword matlabFunc daqread filehandle importdata load open save uiimport winopen 
+"Memory Mapping
+syn keyword matlabFunc memmapfile
+"Low-Level File I/O
+syn keyword matlabFunc fclose feof fgetl fgets fopen fprintf fread frewind fscanf fseek ftell fwrite 
+
+"Text Files
+syn keyword matlabFunc csvread csvwrite dlmread dlmwrite textread textscan
+"XML Documents
+syn keyword matlabFunc xmlread xmlwrite xslt
+"Microsoft Excel Functions
+syn keyword matlabFunc xlsfinfo xlsread xlswrite
+"Lotus 1-2-3 Functions
+syn keyword matlabFunc wk1finfo wk1read wk1write
+"Common Data Format (CDF)
+syn keyword matlabFunc cdfepoch cdfinfo cdfread cdfwrite todatenum 
+"Flexible Image Transport System
+syn keyword matlabFunc fitsinfo fitsread 
+"Hierarchical Data Format (HDF)
+syn keyword matlabFunc hdf hdf5 hdf5info hdf5read hdf5write hdfinfo hdfread hdftool 
+"Band-Interleaved Data
+syn keyword matlabFunc multibandread multibandwrite 
+
+
+" Define the default highlighting.
+" For version 5.7 and earlier: only when not done already
+" For version 5.8 and later: only when an item doesn't have highlighting yet
+if version >= 508 || !exists("did_matlab_syntax_inits")
+  if version < 508
+    let did_matlab_syntax_inits = 1
+    command -nargs=+ HiLink hi link <args>
+  else
+    command -nargs=+ HiLink hi def link <args>
+  endif
+
+  HiLink matlabTransposeOperator	matlabOperator
+  HiLink matlabLineContinuation		Special
+  HiLink matlabLabel			Label
+  HiLink matlabConditional		Conditional
+  HiLink matlabRepeat			Repeat
+  HiLink matlabTodo			Todo
+  HiLink matlabString			String
+  HiLink matlabDelimiter		Identifier
+  HiLink matlabTransposeOther		Identifier
+  HiLink matlabNumber			Number
+  HiLink matlabFloat			Float
+  HiLink matlabConstant			Constant
+  HiLink matlabImplicit			matlabStatement
+  HiLink matlabStatement		Statement
+  HiLink matlabSemicolon		SpecialChar
+  HiLink matlabComment			Comment
+  HiLink matlabBlockComment		Comment
+  HiLink matlabImport			Include
+  HiLink matlabBoolean			Boolean
+  HiLink matlabStorageClass		StorageClass
+
+  HiLink matlabArithmeticOperator	matlabOperator
+  HiLink matlabRelationalOperator	matlabOperator
+  HiLink matlabLogicalOperator		matlabOperator
+  HiLink matlabOperator			Operator
+  HiLink matlabExceptions		Exception
+  HiLink matlabFunc			Function
+
+"optional highlighting
+  "HiLink matlabIdentifier		Identifier
+  "HiLink matlabTab			Error
+  delcommand HiLink
+endif
+
+let b:current_syntax = "matlab"
+
+"EOF	vim: ts=8 noet tw=100 sw=8 sts=0
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex	(revision 18231)
@@ -0,0 +1,15 @@
+\documentclass{letter}
+
+\signature{\'Eric Larour}
+\address{Jet Propulsion Laboratory\\4800 Oak Grove Drive\\CA 91109 Pasadena}
+\begin{document}
+
+\begin{letter}{RECIPIENT\\ADRESS}
+\opening{Dear RECIPIENT,}
+
+BLABLABLA BLABLABLA BLABLABLA BLABLABLA BLABLABLA
+
+\closing{regards,}
+\end{letter}
+
+\end{document}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vim/xtr/skeleton/sh	(revision 18231)
@@ -0,0 +1,1 @@
+#!/bin/bash
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vimrc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/addons/vimrc	(revision 18231)
@@ -0,0 +1,240 @@
+
+" General setup{{{
+" ----------------------------------------------------------------------
+" Use Vim settings, rather then Vi settings (much better!).
+" This must be first, because it changes other options as a side effect.
+set nocompatible
+" UNIX special
+set shell=/bin/bash  
+" jingle bells, jingle bells, hingle bells, ....
+set errorbells
+" keep 100 lines of command line history
+set history=100
+" show the cursor position all the time
+set ruler
+" display incomplete commands
+set showcmd	
+" display curent mode
+set showmode
+"----------------------------------------------------------------------}}}
+" Text-Formatting, Identing, Tabbing{{{
+" ----------------------------------------------------------------------
+" allow backspacing (to delete) over everything in insert mode
+set backspace=indent,eol,start
+" number of spaces the tab stands for
+set tabstop=3
+" number of spaces the softtab (>>) stands for
+set softtabstop=3 
+" number of spaces used for (auto)indenting
+set shiftwidth=3
+" a <tab> in an indent inserts 'shiftwidth' spaces (not tabstop)
+set smarttab
+" always set autoindenting on
+set autoindent
+"smartindenting useful (use '=')
+set smartindent
+
+"base folds on markers
+set foldmethod=marker
+set foldtext=IssmFoldText()
+" -----------------------------------------------------------}}}
+" Backups {{{
+" -----------------------------------------------------------
+" updatecount   number of characters typed to cause a swap file update (0->disable)
+set uc=0
+" make no backups
+set nobackup
+" -----------------------------------------------------------}}}
+" Searching, Substituting {{{
+" -----------------------------------------------------------
+" select case-insenitive search
+"set ignorecase 
+" No ignorecase if Uppercase chars in search
+"set scs
+" change the way backslashes are used in search patterns (. instead of \.)
+set magic
+" begin search at top when EOF reached
+set wrapscan
+" jump to matches during entering the pattern
+set sm
+" do incremental searching 
+set incsearch   
+"highlight all matches
+set hlsearch
+" Do not toggle 'g' and 'c' with :s///gc
+set noedcompatible
+
+" use 'g'-flag when substituting (subst. all matches in that line, not only
+" first) to turn off, use g
+set gdefault
+" how command line completion works (use tab to complete the file name)
+set wildmode=list:longest,list:full
+" ignore some files for filename completion
+set wildignore=*.o,*.r,*.so,*.sl,*.tar,*.tgz
+" some filetypes got lower priority
+set su=.h,.bak,~,.o,.info,.swp,.obj
+" ----------------------------------------------------------------------}}}
+" Colors and theme {{{
+" ----------------------------------------------------------------------
+" use 256 colors
+"set t_Co=8
+set t_Co=256
+" backgrounb color
+"set background=light
+"set background=dark
+" colorscheme
+"colorscheme issm_white
+colorscheme issm_black
+" ----------------------------------------------------------------------}}}
+
+" Mappings{{{
+" ----------------------------------------------------------------------
+"stop highlightings when spce is pressed
+nnoremap <silent> <Space> :silent noh<Bar>echo<CR> 
+
+"increment number
+nnoremap <C-i> <C-a>
+
+"line numbering in flip-flop
+map num :set number!<CR>
+
+" save & "make" the current file in all modes
+map <F8> :w <Enter> :make <Enter><Enter>
+map! <F8>  <ESC> :w <Enter> :make <Enter><Enter>
+" make update: nice for longer documents
+map <F7> :w <Enter> :make update <Enter><Enter>
+map! <F7> <ESC> :w <Enter> :make update <Enter><Enter>
+
+
+"use paste P: re-indent and re-format at the same time
+:nnoremap <Esc>P P'[v']=
+:nnoremap <Esc>p p'[v']=
+
+" Don't use Ex mode, use Q for formatting
+map Q gq
+" ----------------------------------------------------------------------}}}
+" Autocommands {{{
+" ----------------------------------------------------------------------
+" Only do this part when compiled with support for autocommands.
+if has("autocmd")
+
+  " Enable file type detection.
+  " Also load indent files, to automatically do language-dependent indenting.
+  filetype plugin indent on
+  "filetype plugin on
+
+  " For all text files set 'textwidth' to 78 characters.
+  autocmd FileType text setlocal textwidth=0
+
+  " When editing a file, always jump to the last known cursor position.
+  " Don't do it when the position is invalid or when inside an event handler
+  " (happens when dropping a file on gvim).
+  autocmd BufReadPost *
+    \ if line("'\"") > 0 && line("'\"") <= line("$") |
+    \   exe "normal g`\"" |
+    \ endif |
+	 \ for fnum in range(1,foldlevel('.')) |
+	 \   exe ":foldopen" |
+	 \ endfor
+
+  "scripts must be executable
+  autocmd BufWritePost   *.sh         !chmod +x %
+
+endif " has("autocmd")
+" ----------------------------------------------------------------------}}}
+" Matlab special {{{
+" ----------------------------------------------------------------------
+"" associate *.par with matlab filetype
+au BufRead,BufNewFile *.par setfiletype matlab
+au BufRead,BufNewFile *.tpl setfiletype html
+" ----------------------------------------------------------------------}}}
+" C special{{{
+" ----------------------------------------------------------------------
+"indenting for C-code
+set cindent
+" and here some nice options for cindenting
+set cinoptions={.5s,+.5s,t0,n-2,p2s,(03s,=.5s,>1s,=1s,:1s 
+" hash sign identation
+set cinkeys-=0#
+" ----------------------------------------------------------------------}}}
+" TEX special{{{
+" ----------------------------------------------------------------------
+au BufRead,BufNewFile *.tex,*.html set textwidth=100     "100 caracters max (See gq command)
+au BufRead,BufNewFile *.tex,*.html set formatoptions=cqt "automatic wraping
+au BufRead,BufNewFile *.tex,*.html set wrapmargin=0      "no margin
+au BufRead,BufNewFile *.cls setfiletype tex
+
+" OPTIONAL: Starting with Vim 7, the filetype of empty .tex files defaults to
+" 'plaintex' instead of 'tex', which results in vim-latex not being loaded.
+" The following changes the default filetype back to 'tex':
+let g:tex_flavor='latex'
+" ----------------------------------------------------------------------}}}
+" FORTRAN special{{{
+" ----------------------------------------------------------------------
+au BufRead,BufNewFile *.src setfiletype fortran
+" ----------------------------------------------------------------------}}}
+" InsertTabWrapper{{{
+" ----------------------------------------------------------------------
+function! InsertTabWrapper(direction) 
+let col = col('.') - 1 
+if !col || getline('.')[col - 1] !~ '\k' 
+   return "\<tab>" 
+elseif "backward" == a:direction 
+   return "\<c-p>" 
+else 
+   return "\<c-n>" 
+endif 
+endfunction 
+
+inoremap <tab> <c-r>=InsertTabWrapper ("forward")<cr>
+inoremap <s-tab> <c-r>=InsertTabWrapper ("backward")<cr>
+
+"source ~/.exrc 
+set wildmenu
+
+"Change to directory of current file automatically
+autocmd BufEnter * lcd %:p:h
+" ----------------------------------------------------------------------}}}
+
+" Abbreviations {{{
+" ----------------------------------------------------------------------
+func Eatchar(pat)
+	let c = nr2char(getchar())
+	return (c =~ a:pat) ? '' : c
+endfunc
+au BufRead,BufNewFile *.html   iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.m      iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m      iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
+au BufRead,BufNewFile *.c*,*.h iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*,*.h iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.py     iabbr <silent> ER  raise NameError('')<Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m      iabbr <silent> ER  error('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*     ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
+au BufRead,BufNewFile *.c*,*.h ab AS _assert_();
+au BufRead,BufNewFile *.c*,*.h iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
+au BufRead,BufNewFile *.c*,*.h iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
+"tex
+au BufRead,BufNewFile *.tex iab EQ 
+			\\begin{equation}
+			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab IT 
+			\\begin{itemize}
+			\<CR>\item 
+			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab EN 
+			\\begin{enumerate}
+			\<CR>\item 
+			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex ab (()) \left( \right)
+"}}}
+" Skeletons {{{
+au BufNewFile letter.tex   0r ~/.vim/xtr/skeleton/letter.tex
+"}}}
+" Copy and Paste{{{
+"vmap <C-c> y:call system("pbcopy", getreg("\""))<CR>
+"nmap <C-v> :call setreg("\"",system("pbpaste"))<CR>p
+"}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/vim/install.sh	(revision 18231)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf vim72
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/vim-7.2.tar.bz2' 'vim-7.2.tar.bz2'
+
+#Untar 
+bzip2 -d -k vim-7.2.tar.bz2
+tar -xvf vim-7.2.tar
+rm vim-7.2.tar
+
+#Move vim into install directory
+mv vim72/* src
+rm -rf vim72
+
+#Configure vim (icc seems to have issues with wctype.h)
+export CC=gcc
+cd src/src 
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/vim/install" \
+	--with-gcc="/usr/bin/gcc" \
+	--with-tlib="/lib/"
+
+#Compile vim
+make
+make  install
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/InstallInstructions.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/InstallInstructions.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/InstallInstructions.txt	(revision 18231)
@@ -0,0 +1,159 @@
+Win7: 
+-Be sure to use an account name that does not have spaces in it, as this could be an 
+issue with Cygwin. 
+
+
+Installing Matlab: 
+
+-Make sure that when you install Matlab, you choose C:\MATLAB\R2011b as directory 
+for the installation. Failing to do so could preclude the sdk compiler from 
+finding the Matlab header files.  Define environment variable:
+MATLAB_DIR="C:/MATLAB/R2011b" after you 'source $ISSM_TIER/etc/environment.sh'
+as described in the ISSM installation instructions below.
+
+-Also pay attention to what version of Matlab you are using, 32 or 64 bits, 
+as this will need to be reflected onto the sdk compiler settings. 
+
+
+
+Cygwin: 
+
+-You will need cygwin installed on your Windows platform to manage the compilation.  Cygwin emulates
+unix behaviour on windows machines.  The compilation will still be carried out by the windows sdk compiler, but the
+environment driving the compilation will be the unix-like cygwin. When you download
+cygwin, make sure that you install it in the C:\Cygwin directory. 
+
+-You will find the cygwin setup executable on the www.cygwin.com webpage. Here is a link
+to it: http://cygwin.com/setup.exe. Download this file to C:\Cygwin and be sure to reuse 
+it when you want to update your current cygwin installation. Do not download setup.exe 
+twice! 
+
+- You will need the following packages downloaded to carry out the compilation of ISSM
+ successfully, so be sure to include them in your cygwin install: 
+
+subversion
+autotools
+automake
+vim (or any other editor)
+patchutils
+make: The GNU version of the 'make' utility
+automake 1.11 and automake:Wrapper scripts
+autoconf
+python: Python language interpreter
+unzip
+cygrunsrv
+
+
+
+Compiler: 
+
+You need Visual Studio Express 2010 for C++, which you can find here: 
+http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express
+
+you will also need the Windows SDK 7.1 compiler, which you can find at the following link
+http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8279
+This compiler is compatible with Matlab, as detailed in the following webpage: 
+http://www.mathworks.com/support/compilers/R2011b/win64.html#n2
+
+Be careful not to download the sdk before Visual Studio Express, as this could lead to 
+environment setup issues. 
+
+
+Before you do anything related to ISSM! You have to capture the settings of your compiler.
+This is by far the most tricky part. 
+
+Follow Sdk1.png and Sdk2.png for more details. You have to launch sdk 7.1 command prompt, go to the 
+cygwin directory and fire up Cygwin by executing Cygwin.bat. Once this is done,dump the 
+results of the export command onto a file, called  sdk7.1.win7.64.sh 
+you will need this file later in the ISSM install. 
+
+
+
+Downloading issm: 
+
+Download issm into the C:\ directory. Do not download it in your Documents or Desktop
+folder. 
+
+In cygwin: 
+cd /cygdrive/c/
+svn co http://issm.ess.uci.edu/svn/issm/issm
+
+Once you download it, in your home directory, edit .bashrc: 
+and add the following lines:
+export ISSM_DIR=/cygdrive/c/issm
+export ISSM_TIER=$ISSM_DIR/trunk-jpl
+export ISSM_ARCH=cygwin-intel
+
+#source
+source $ISSM_TIER/etc/environment.sh
+
+
+Getting the cl.exe compiler to work: 
+before trying to compile the externalpackages, you need to be sure that your compiler cl.exe 
+(the sdk compiler)works. To make sure, create a simple hello world file: 
+
+hello.cpp
+
+#include <stdio.h>
+int main(){
+printf("%s\n","hello");
+return 1;
+}
+
+and try to compile it by doing: 
+cl hello.cpp
+
+If this does not work, do not go any further! The settings of your cl compiler are found
+in externalpackages/windows/configs/. If there is a significant different between your
+sdk7.1.win7.64.sh file (see above section Compiler) and the file that is being sourced in the windows/configs directory, place your new file in
+the configs directory. Relaunch bash, and try to run cl hello.cpp once more. Beware, you will likely
+have to erase some lines in your file, as cygwin might not like some of the stuff that your
+Windows platform is trying to define. To make sure that the correct bit compiler is
+being sourced in windows/configs (e.g. sdk7.1.win7-64.sh or sdk7.1.win7-32.sh) see
+section "One note about 32 vs 64 bit compile" below.
+
+Once the cl.exe compiler works, you can start installing the following packages: 
+petsc   metis triangle and cccl
+
+For petsc, use install-3.1-win7.sh 
+For metis, use install-4.0-win7.sh
+For cccl, use install-win7.sh
+For triangle, use install-win7.sh
+
+Once this is complete run the install.sh scripts in the autoconf and automake
+externalpackages directory
+
+Once these externalpackages have been compiled, you can compile issm: 
+
+./scripts/autoremakererun.sh
+./configs/config-win7-64.sh
+make install
+
+This should compile both parallel and serial versions of ISSM. Beware though, the parallel
+version cannot be run on multi-core platforms yet! We are actively working on it. 
+
+
+
+One note about 32 vs 64 bit compile: 
+Depending on your Matlab version, you will need to do a 32 or 64 bit compile. The only
+difference between both compiles is the setup of the cl.exe compiler. For ease of use,
+you will find in externalpackages/windows/windows_environment.sh a switch to go from 32
+to 64 bit compile. When you type cl.exe \help at the command prompt, cl.exe should report
+what system it is compiling for. Beware, switching 32 to 64 or vice-versa implies recompiling everything from scratch.
+
+
+
+How to setup a Cron job? 
+First, make sure you downloaded cygrunsrv, otherwise the cron setup will only work on a per-session 
+basis! Also, make sure that you have an email correctly setup.  In particular, cron relies on the
+/usr/sbin/sendmail script. If it does not exist, cron will not send emails. Most email management 
+systems will create this script, but you need to check on it. 
+Run cron-config  and fill up the questions. For daemon name, type ntsec. 
+Be careful, make sure that you are running your terminal as Administrator, 
+otherwise your settings will be only user-based. 
+How to setup email? 
+
+Preferred way is through ssmtp. Download it on cygwin, and type ssmtp-config.  If the ssmtp 
+daemon does not create /usr/sbin/sendmail, be sure to create a symlink from the email client 
+to the latter file. Be careful, make sure that you are running your terminal as Administrator, 
+otherwise your settings will be only user-based. 
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/README	(revision 18231)
@@ -0,0 +1,71 @@
+How to install intel compiler to work on cygwin at the command line: 
+
+This is what I got from the following post on google: 
+
+-----------------------------------------------------
+All necessary paths and environment variables are set if you put the Microsoft linker path in ICL.CFG, and open the Intel 
+compiler command line window on the Start menu. Then you can run cygwin.bat so that bash inherits the ICL paths, 
+without breaking ICL. You will sometimes get the bash warning about finding Windows style paths in the environment, 
+but those are necessary for ICL and Microsoft link. Needless to say, the Windows environment variable forgetfulness
+ point will be reached sooner with this setup.
+
+After I run cygwin.bat, and try to run icl, it says:
+
+link: invalid option -- o
+Try `ling --help' for more information.
+
+I verified that icl compiles without any problems before I run cygwin.bat
+
+What am I missing?
+
+
+
+This would indicate that you ignored my advice about icl.cfg, and so you are getting the wrong link.exe.  It should have said "link" not "ling."
+For a VC9 installation, /windows/C/Program Files/Intel/Compiler/11.1/026/bin/ia32/icl.cfg:
+-Qlocation,link,"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin"
+-Qprec-div -Qprec-sqrt -Qansi_alias
+----------------------------------------------------------
+
+
+
+
+
+So here is what you do: 
+edit /cygdrive/c/IntelInstall/Compiler/11.1/026/bin/ia32/icl.cfg
+
+add: 
+-Qlocation,link,"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin"
+-Qprec-div -Qprec-sqrt -Qansi_alias
+
+
+Then run the intel compiler command window. Go to C:\Cygwin and run Cygwin.bat. 
+you are now running cygwin with the correct paths.  Type "export" at the command line, and figure out which variables have been set that relate to the intel compiler and visual studio environment. Build a file containing specific export commands and source it from your .bashrc. intel.sh is an example of such file on a Windows XP 32 build. 
+
+
+
+Compiling ISSM using Matlab compatible  compilers. 
+
+At: http://www.mathworks.com/support/compilers/R2011b/win64.html#n2 
+you will find a list of Matlab supported compilers. 
+
+
+We'll try the compile with the Microsoft Windows SDK 7.1: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8279
+
+
+
+MPICH2: 
+to run in parallel.  First install MPICH2 from www.mpich.org/downloads. Make 
+sure the install directory in C:\Program Files\MPICH2, otherwise, ISSM will 
+not be able to figure out where the mpi libraries are installed on your windows platform.
+
+Then fire up smpd in a command line under Administrator privileges: 
+smpd -install
+
+Then: 
+mpiexe.exe -remove
+mpiexe.exe -register (type enter for username, for password, type your windows password, do not chose anything else!)
+mpiexe.exe -validate (should return SUCCESS)
+
+Then you are ready to run parallel.
+
+To do: how do we document this? Create webpage for all of this. + get a fortran compiler giong!
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/intel-winXP.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/intel-winXP.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/intel-winXP.sh	(revision 18231)
@@ -0,0 +1,16 @@
+ export CPATH="C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\include;C:\\IntelInstall\\Compiler\\11.1\\038\\mkl\\include;"
+ export DEVENVDIR="C:\\MicrosoftVisualStudio 9.0\\Common7\\IDE"
+ export FPATH="C:\\IntelInstall\\Compiler\\11.1\\038\\mkl\\include;"
+ export FRAMEWORK35VERSION="v3.5"
+ export FRAMEWORKDIR="C:\\WINDOWS\\Microsoft.NET\\Framework"
+ export FRAMEWORKVERSION="v2.0.50727"
+ export INCLUDE="C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\include;C:\\IntelInstall\\Compiler\\11.1\\038\\mkl\\include;C:\\IntelInstall\\Compiler\\11.1\\038\\tbb\\include;C:\\IntelInstall\\Compiler\\11.1\\038\\include;C:\\MicrosoftVisualStudio 9.0\\VC\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\include;"
+ export IPPROOT="C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32"
+ export LIB="C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\lib;C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\stublib;C:\\IntelInstall\\Compiler\\11.1\\038\\mkl\\ia32\\lib;C:\\IntelInstall\\Compiler\\11.1\\038\\tbb\\ia32\\vc9\\lib;C:\\IntelInstall\\Compiler\\11.1\\038\\Lib\\ia32;C:\\MicrosoftVisualStudio 9.0\\VC\\LIB;C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\lib;"
+ export LIBPATH="C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5;C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;C:\\MicrosoftVisualStudio 9.0\\VC\\LIB;"
+ export LIBRARY_PATH="C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\lib;C:\\IntelInstall\\Compiler\\11.1\\038\\ipp\\ia32\\stublib;C:\\IntelInstall\\Compiler\\11.1\\038\\mkl\\ia32\\lib;"
+ export PATH="$PATH:/cygdrive/c/IntelInstall/Compiler/11.1/038/Bin/ia32:/cygdrive/c/MicrosoftVisualStudio 9.0/Common7/IDE:/cygdrive/c/MicrosoftVisualStudio 9.0/VC/BIN:/cygdrive/c/MicrosoftVisualStudio 9.0/Common7/Tools:/cygdrive/c/WINDOWS/Microsoft.NET/Framework/v3.5:/cygdrive/c/WINDOWS/Microsoft.NET/Framework/v2.0.50727:/cygdrive/c/MicrosoftVisualStudio 9.0/VC/VCPackages:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v6.0A/bin:/cygdrive/c/WINDOWS"
+ export TBB_ARCH_PLATFORM="ia32\\vc9"
+ export VCINSTALLDIR="C:\\MicrosoftVisualStudio 9.0\\VC"
+ export VSINSTALLDIR="C:\\MicrosoftVisualStudio 9.0"
+ export WINDOWSSDKDIR="C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-32.sh	(revision 18231)
@@ -0,0 +1,39 @@
+declare -x ALLUSERSPROFILE="C:\\ProgramData"
+declare -x CL="/AI C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319"
+declare -x COMMONPROGRAMFILES="C:\\Program Files\\Common Files"
+declare -x COMSPEC="C:\\Windows\\system32\\cmd.exe"
+declare -x CommandPromptType="Native"
+declare -x Configuration="Debug"
+declare -x FP_NO_HOST_CHECK="NO"
+declare -x FrameworkVersion="v4.0.30319"
+declare -x HOMEDRIVE="C:"
+declare -x INCLUDE="C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\INCLUDE\\gl;"
+declare -x INFOPATH="/usr/local/info:/usr/share/info:/usr/info:"
+declare -x LANG="en_US.UTF-8"
+declare -x LIB="C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\Lib;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Lib;C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;C:\\Windows\\Microsoft.NET\\Framework\\v3.5;;"
+declare -x LIBPATH="C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;C:\\Windows\\Microsoft.NET\\Framework\\v3.5;;C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\Lib;"
+declare -x MANPATH="/usr/local/man:/usr/share/man:/usr/man:"
+declare -x PATH="/usr/local/bin:/usr/bin:/cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework/v3.5:/cygdrive/c/Program Files/Microsoft Visual Studio 10.0/Common7/IDE:/cygdrive/c/Program Files/Microsoft Visual Studio 10.0/Common7/Tools:/cygdrive/c/Program Files/Microsoft Visual Studio 10.0/VC/Bin:/cygdrive/c/Program Files/Microsoft Visual Studio 10.0/VC/Bin/VCPackages:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v7.1/Bin/NETFX 4.0 Tools:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v7.1/Bin:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/MATLAB/R2012a/runtime/win32:/cygdrive/c/MATLAB/R2012a/bin:/cygdrive/c/Program Files/Microsoft Windows Performance Toolkit"
+declare -x PATHEXT=".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
+declare -x PRINTER="137.78.140.129#:1"
+declare -x PROCESSOR_ARCHITECTURE="x86"
+declare -x PROCESSOR_IDENTIFIER="x86 Family 6 Model 42 Stepping 7, GenuineIntel"
+declare -x PROCESSOR_LEVEL="6"
+declare -x PROCESSOR_REVISION="2a07"
+declare -x PROGRAMFILES="C:\\Program Files"
+declare -x PSModulePath="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\"
+declare -x PUBLIC="C:\\Users\\Public"
+declare -x PlatformToolset="Windows7.1SDK"
+declare -x ProgramData="C:\\ProgramData"
+declare -x SHELL="/bin/bash"
+declare -x SYSTEMDRIVE="C:"
+declare -x SYSTEMROOT="C:\\Windows"
+declare -x TARGET_CPU="x86"
+declare -x TARGET_PLATFORM="WIN7"
+declare -x TERM="cygwin"
+declare -x ToolsVersion="4.0"
+declare -x VS100COMNTOOLS="C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\"
+declare -x WINDIR="C:\\Windows"
+declare -x WindowsSDKDir="C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\"
+declare -x WindowsSDKVersionOverride="v7.1"
+declare -x sdkdir="C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/configs/sdk7.1.win7-64.sh	(revision 18231)
@@ -0,0 +1,48 @@
+declare -x ALLUSERSPROFILE="C:\\ProgramData"
+declare -x CL="/AI C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319"
+declare -x COMMONPROGRAMFILES="C:\\Program Files (x86)\\Common Files"
+declare -x CURRENT_CPU="x64"
+declare -x CommandPromptType="Native"
+declare -x CommonProgramW6432="C:\\Program Files\\Common Files"
+declare -x Configuration="Debug"
+declare -x FP_NO_HOST_CHECK="NO"
+declare -x FrameworkVersion="v4.0.30319"
+declare -x INCLUDE="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\INCLUDE;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\INCLUDE\\gl;"
+declare -x INFOPATH="/usr/local/info:/usr/share/info:/usr/info:"
+declare -x LANG="C.UTF-8"
+declare -x LIB="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\Lib\\amd64;C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Lib\\X64;"
+declare -x LIBPATH="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319;C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;C:\\Windows\\Microsoft.NET\\Framework64\\v3.5;C:\\Windows\\Microsoft.NET\\Framework\\v3.5;;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\Lib\\amd64;"
+declare -x MANPATH="/usr/local/man:/usr/share/man:/usr/man:"
+declare -x PATH="/usr/local/bin:/usr/bin:/usr/include:/cygdrive/c/cygwin/usr/bin:/cygdrive/c/cygwin/usr/include:/cygdrive/c/Windows/Microsoft.NET/Framework64/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework64/v3.5:/cygdrive/c/Windows/Microsoft.NET/Framework/v3.5:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/Tools:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/Bin/amd64:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/Bin/VCPackages:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v7.1/Bin/NETFX 4.0 Tools/x64:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v7.1/Bin/x64:/cygdrive/c/Program Files/Microsoft SDKs/Windows/v7.1/Bin:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files/Microsoft Windows Performance Toolkit:/cygdrive/c/MATLAB/R2012a/runtime/win64:/cygdrive/c/MATLAB/R2012a/bin:/cygdrive/c/MATLAB/R2012a/extern/include:/cygdrive/c/MATLAB/R2011a/runtime/win64:/cygdrive/c/MATLAB/R2011a/bin:/cygdrive/c/MATLAB/R2011a/extern/include"
+declare -x PATHEXT=".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
+declare -x PROCESSOR_ARCHITECTURE="x86"
+declare -x PROCESSOR_ARCHITEW6432="AMD64"
+declare -x PROCESSOR_IDENTIFIER="Intel64 Family 6 Model 42 Stepping 7, GenuineIntel"
+declare -x PROCESSOR_LEVEL="6"
+declare -x PROCESSOR_REVISION="2a07"
+declare -x PROGRAMFILES="C:\\Program Files (x86)"
+declare -x PROMPT="\$P\$G"
+declare -x PSModulePath="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\"
+declare -x PUBLIC="C:\\Users\\Public"
+declare -x PlatformToolset="Windows7.1SDK"
+declare -x ProgramData="C:\\ProgramData"
+declare -x ProgramW6432="C:\\Program Files"
+declare -x REPO="jpl"
+declare -x SESSIONNAME="Console"
+declare -x SHLVL="1"
+declare -x HOMEDRIVE="C:"
+declare -x SYSTEMDRIVE="C:"
+declare -x SYSTEMROOT="C:\\Windows"
+declare -x TARGET_CPU="x64"
+declare -x TARGET_PLATFORM="WIN7"
+declare -x TEMP="/tmp"
+declare -x TERM="cygwin"
+declare -x TMP="/tmp"
+declare -x ToolsVersion="4.0"
+declare -x VS100COMNTOOLS="C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\Tools\\"
+declare -x WINDIR="C:\\Windows"
+declare -x WindowsSDKDir="C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\"
+declare -x WindowsSDKVersionOverride="v7.1"
+declare -x sdkdir="C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\"
+declare -x windows_tracing_flags="3"
+declare -x windows_tracing_logfile="C:\\BVTBin\\Tests\\installpackage\\csilogfile.log"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/fortran_environment.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/fortran_environment.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/fortran_environment.sh	(revision 18231)
@@ -0,0 +1,70 @@
+declare -x APPDATA="C:\Users\larour\AppData\Roaming"
+declare -x ARCH_PATH="ia32"
+declare -x ARCH_PATH_MPI="ia32"
+declare -x BIN_ROOT="C:\Program Files (x86)\Intel\Composer XE 2013\bin"
+declare -x BUNDLE_NAME="Intel(R) Parallel Studio XE 2013"
+declare -x COMMONPROGRAMFILES="C:\Program Files (x86)\Common Files"
+declare -x CommonProgramW6432="C:\Program Files\Common Files"
+declare -x COMPUTERNAME="WIN-BBO0CI1DTAL"
+declare -x COMSPEC="C:\Windows\system32\cmd.exe"
+declare -x C_TARGET_ARCH="ia32"
+declare -x DevEnvDir="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE"
+declare -x FP_NO_HOST_CHECK="NO"
+declare -x Framework35Version="v3.5"
+declare -x FrameworkDir="C:\Windows\Microsoft.NET\Framework"
+declare -x FrameworkDIR32="C:\Windows\Microsoft.NET\Framework"
+declare -x FrameworkVersion="v4.0.30319"
+declare -x FrameworkVersion32="v4.0.30319"
+declare -x HOMEDRIVE="C:"
+declare -x HOMEPATH="\Users\larour"
+declare -x IFORT_COMPILER13="C:\Program Files (x86)\Intel\Composer XE 2013"
+declare -x INCLUDE="C:\Program Files (x86)\Intel\Composer XE 2013\compiler\include;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\include\ia32;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\include;C:\Program Files (x86)\Intel\Composer XE 2013\mkl\include;"
+declare -x INTEL_DEV_REDIST="C:\Program Files (x86)\Common Files\Intel\Shared Libraries"
+declare -x INTEL_LICENSE_FILE="C:\Program Files (x86)\Common Files\Intel\Licenses"
+declare -x LIB="C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib\ia32;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\LIB;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib;C:\Program Files (x86)\Intel\Composer XE 2013\mkl\lib\ia32;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib\ia32;"
+declare -x LIBPATH="C:\Windows\Microsoft.NET\Framework\v4.0.30319;C:\Windows\Microsoft.NET\Framework\v3.5;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\LIB;"
+declare -x LOCALAPPDATA="C:\Users\larour\AppData\Local"
+declare -x LOGONSERVER="\\WIN-BBO0CI1DTAL"
+declare -x MKLROOT="C:\Program Files (x86)\Intel\Composer XE 2013\mkl"
+declare -x MSVS_VAR_SCRIPT="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\..\..\VC\vcvarsall.bat"
+declare -x NUMBER_OF_PROCESSORS="8"
+declare -x OS="Windows_NT"
+declare -x PATH="$PATH:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/bin/ia32:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/compiler:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/BIN:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/Tools:/cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework/v3.5:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/VCPackages:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin/NETFX 4.0 Tools:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/mkl:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/compiler:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64/mpirt:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64/compiler:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/ia32/mpirt:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/ia32/compiler:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files/Microsoft Windows Performance Toolkit:/cygdrive/c/MATLAB/R2012b/runtime/win64:/cygdrive/c/MATLAB/R2012b/bin:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/mpirt"
+declare -x PATHEXT=".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
+declare -x PROCESSOR_ARCHITECTURE="x86"
+declare -x PROCESSOR_ARCHITEW6432="AMD64"
+declare -x PROCESSOR_IDENTIFIER="Intel64 Family 6 Model 58 Stepping 9, GenuineIntel"
+declare -x PROCESSOR_LEVEL="6"
+declare -x PROCESSOR_REVISION="3a09"
+declare -x PRODUCT_NAME="Intel Composer XE 2013 "
+declare -x PRODUCT_NAME_FULL="Intel(R) Composer XE 2013 Update 3 (package 171)"
+declare -x ProgramData="C:\ProgramData"
+declare -x PROGRAMFILES="C:\Program Files (x86)"
+declare -x ProgramW6432="C:\Program Files"
+declare -x PROMPT="$P$G"
+declare -x protector_attach="true"
+declare -x PSModulePath="C:\Windows\system32\WindowsPowerShell\v1.0\Modules"
+declare -x PUBLIC="C:\Users\Public"
+declare -x ROOT="C:\Program Files (x86)\Intel\Composer XE 2013"
+declare -x SCRIPT_NAME="compilervars_arch.bat"
+declare -x SESSIONNAME="Console"
+declare -x SYSTEMDRIVE="C:"
+declare -x SYSTEMROOT="C:\Windows"
+declare -x TARGET_ARCH="ia32"
+declare -x TARGET_VS="vs2010"
+declare -x TARGET_VS_ARCH="x86"
+declare -x TEMP="/cygdrive/c/Users/larour/AppData/Local/Temp"
+declare -x TMP="/cygdrive/c/Users/larour/AppData/Local/Temp"
+declare -x USERDOMAIN="WIN-BBO0CI1DTAL"
+declare -x USERNAME="larour"
+declare -x USERPROFILE="C:\Users\larour"
+declare -x VCINSTALLDIR="C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC"
+declare -x VS100COMNTOOLS="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools"
+declare -x VSINSTALLDIR="C:\Program Files (x86)\Microsoft Visual Studio 10.0"
+declare -x WINDIR="C:\Windows"
+declare -x WindowsSdkDir="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A"
+declare -x windows_tracing_flags="3"
+declare -x windows_tracing_logfile="C:\BVTBin\Tests\installpackage\csilogfile.log"
+declare -x WIN_TITLE="Intel Composer XE 2013  IA-32 Visual Studio 2010"
+declare -x WIN_TITLE_ARCH="IA-32"
+declare -x WIN_TITLE_VS="Visual Studio 2010"
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/install.sh	(revision 18231)
@@ -0,0 +1,5 @@
+#!/bin/bash
+set -eu
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/win7.sdk7.1.exe' 'win7.sdk7.1.exe'
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/windows_environment.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/windows_environment.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/windows/windows_environment.sh	(revision 18231)
@@ -0,0 +1,41 @@
+#This file sources all relevant scripts to setup the paths to windows compilers.
+
+#Where are the configuration files for each compiler: 
+config_dir="$ISSM_DIR/externalpackages/windows/configs"
+
+#your choise of compiler: 
+# 1: sdk 7.1 32 bits on Win7
+# 2: sdk 7.1 64 bits on Win7
+# 3: intel compiler on Win7
+# 4: intel compiler on WinXP
+
+#Determine OS version using uname: 
+version=`uname -s | grep 64`
+if [[ $version == "" ]];then
+	compiler=1
+else
+	compiler=2
+fi
+
+#If you want to override and use intel compilers: 
+#compiler=3;
+
+
+#source corresponding environment variables: 
+
+if [[ "$compiler" == "1" ]]; then 
+	source $config_dir/sdk7.1.win7-32.sh
+elif [[ "$compiler" == "2" ]]; then 
+	source $config_dir/sdk7.1.win7-64.sh
+elif [[ "$compiler" == "3" ]]; then 
+	source $config_dir/intel-win7.sh
+else 
+	source $config_dir/intel-winXP.sh
+fi
+
+#finally, out of ISSM_DIR, we need to create an ISSM_DIR_WIN variable for Matlab to pick up on.
+ISSM_DIR_WIN=`cygpath -m $ISSM_DIR`
+export ISSM_DIR_WIN
+
+#Now source for fortran environment: 
+#source $ISSM_DIR/externalpackages/windows/fortran_environment.sh
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xaifbooster/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xaifbooster/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xaifbooster/install.sh	(revision 18231)
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf xaifBooster
+
+#download 
+svn co -r 125  http://hpc.svn.rice.edu/r/xaifBooster/trunk xaifBooster
+
+#Compile xaifBooster
+cd xaifBooster
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xerces/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xerces/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/xerces/install.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install xerces-c-src_2_8_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/xerces-c-src_2_8_0.tar.gz' 'xerces-c-src_2_8_0.tar.gz'
+
+#Untar 
+tar -zxvf  xerces-c-src_2_8_0.tar.gz
+
+#Move xerces-c-tools into install directory
+mv xerces-c-src_2_8_0/* src
+rm -rf xerces-c-src_2_8_0
+
+#Apply patches
+cd src/src/xercesc/
+
+#Configure
+./runConfigure -plinux -cgcc -xg++ -minmem -nsocket -tnative -rnone -s 
+
+#Compile xerces-c-tools
+make
Index: /issm/branches/trunk-jpl-ad2-integrated/externalpackages/yams/install.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/externalpackages/yams/install.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/externalpackages/yams/install.sh	(revision 18231)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/yams2-linux.gz' 'yams2-linux.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/yams2-osx.gz' 'yams2-osx.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/yams2-win.exe' 'yams2-win.exe'
+
+#loop over the binaries
+for i in yams*
+do
+	name=$i;
+	cp $i install/
+
+	#uncompress if necessary
+	if echo $i | grep -q ".gz"
+	then
+		gunzip install/$i
+	fi
+
+	#permissions
+	chmod 777 install/*
+done
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell	(revision 18231)
@@ -0,0 +1,22 @@
+#!/bin/bash
+
+#some exports required
+export ISSM_DIR="$WORKSPACE"
+
+#which configuration are we using?
+case $Platform in
+	master )
+		configfile=linux64_murdo ;;
+	imac-012301-gil )
+		configfile=imac-012301-gil ;;
+	larsen )
+		configfile=linux64_larsen ;;
+	windows )
+		configfile=windows
+		export PATH=/cygdrive/c/Cygwin/usr/bin:/cygdrive/c/Cygwin/bin:$PATH ;;
+
+esac
+
+#run
+cd "$WORKSPACE"
+source $ISSM_DIR/jenkins/jenkins.sh $ISSM_DIR/jenkins/$configfile
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell_ad
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell_ad	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/execute_shell_ad	(revision 18231)
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+#some exports required
+export ISSM_DIR="$WORKSPACE"
+
+#which configuration are we using? 
+case $AMPI in 
+	ampion ) 
+		configfile=linux64_murdo_ampi ;;
+	ampioff )
+		configfile=linux64_murdo_ad ;;
+esac 
+
+#run
+cd "$WORKSPACE"
+source $ISSM_DIR/jenkins/jenkins.sh $ISSM_DIR/jenkins/$configfile
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/imac-012301-gil
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/imac-012301-gil	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/imac-012301-gil	(revision 18231)
@@ -0,0 +1,110 @@
+#
+########### Configuration file for Eric Larour's Jenkins run on MaxOSX ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM matlab tests on MacOSX"
+
+#ISSM Architecture
+ISSM_ARCH="macosx-gnu"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--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/mpich/install/include  \
+	--with-mpi-libflags=" $ISSM_DIR/externalpackages/mpich/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpl.a " \
+	--with-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-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--enable-development'
+
+#MATLAB path
+MATLAB_PATH="/Applications/MATLAB_R2011b.app/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+						matlab    install.sh                
+						mpich     install-3.0-macosx64.sh    
+						cmake     install.sh                
+						petsc     install-3.4-macosx64.sh    
+						tao       install-2.2.sh
+						triangle  install-macosx64.sh 
+						shell2junit  install.sh "
+
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+##                                                                   bamg mesh   FS                     
+MATLAB_NROPTIONS="'exclude',[218 234 235 412 413 414 417 418 420 514 701 702 703 422 404 421 503 507 510]"
+PYTHON_NROPTIONS=""
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/jenkins.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/jenkins.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/jenkins.sh	(revision 18231)
@@ -0,0 +1,382 @@
+#!/bin/bash
+#This bash script calls the nightlyrun.m matlab file to run our nightly test decks. 
+#It then processes the results and sends an email to the Ice developpers.
+
+#some functions
+function timer() #{{{
+{
+	if [[ $# -eq 0 ]]; then
+		echo $(date '+%s')
+	else
+		local  stime=$1
+		etime=$(date '+%s')
+
+		if [[ -z "$stime" ]]; then stime=$etime; fi
+
+		dt=$((etime - stime))
+		ds=$((dt % 60))
+		dm=$(((dt / 60) % 60))
+		dh=$((dt / 3600))
+		printf '%d:%02d:%02d' $dh $dm $ds
+	fi
+} #}}}
+function todaydate() #{{{
+{
+	suffix=`date | awk '{printf("%s-%s-%s  %s",$2,$3,$6,$4);}'`			 
+	echo $suffix;			 
+} #}}}
+function host_name() #{{{
+{
+	#return host name depending on the OS
+	if [ "$1" = "win7" ] 
+	then
+		HOST_NAME=`hostname | sed 's/-//g'`;
+	else
+		HOST_NAME=`hostname -s | sed 's/-//g'`;
+	fi
+	echo $HOST_NAME;
+} #}}}
+function pause() #{{{
+{
+pid=`ps aux -W | grep $1 | awk '{printf("%s\n",$1);}'`
+
+while [ -n "$pid" ]
+do
+	pid=`ps aux -W | grep $1 | awk '{printf("%s\n",$1);}'`
+done
+}
+#}}}
+
+#Get configuration
+#Source config file{{{
+if [ $# -ne 1 ];
+then
+	#no config file specified: exit
+	echo "no config file specified. Exiting..." >&2 # Error message to stderr.
+	exit 1
+fi
+if [ ! -f "$1" ]
+then
+	echo "File $1 not found!" >&2   # Error message to stderr.
+	exit 1
+fi 
+source $1;
+#}}}
+#Initialize variables {{{
+TODAY=$(todaydate);
+OS=$(uname -s)
+if [[ $OS == "CYGWIN_NT-6.1-WOW64" ]]; then 
+	OS="win7";
+fi
+HOST_NAME=$(host_name $OS);
+START_TIME=$(timer);
+ISSM_RELEASE=$(basename $(echo $REPOSITORY));
+USER=$(whoami);
+INIT_PATH=$(pwd);
+#}}}
+
+#Installation ISSM
+#create matlab's installation sript {{{
+cat << END > $ISSM_DIR/externalpackages/matlab/install.sh
+#!/bin/bash
+rm -rf install
+ln -s $MATLAB_PATH install
+END
+#}}}
+#install/copy/none external packages    (ISSM_EXTERNALPACKAGES){{{
+if [ "$ISSM_EXTERNALPACKAGES" == "install" ]
+then
+	
+	cd $ISSM_DIR/externalpackages
+
+	#number of packages: 
+	NUMPACKAGES=$(($(echo $EXTERNALPACKAGES | wc -w )/2))
+
+	for ((i=1;i<=$NUMPACKAGES;i++))
+	do
+		NUM1=$((2*$i-1))
+		NUM2=$((2*$i))
+		PACKAGENAME=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM1-$NUM1)
+		PACKAGEINST=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM2-$NUM2)
+
+		cd $PACKAGENAME
+
+		#tricky part here. We do not want to reinstall this package if it's already installed
+		#and the svn file which does the install has not be modified! To keep track of 
+		#this, we check the current svn version against the "last changed" revision number.  If they 
+		#are the same, we reinstall the package. 
+		current_version=`svnversion`
+		last_changed_version=`svn info $PACKAGEINST | grep "Last Changed Rev" | awk '{printf("%s\n",$4);}'`
+
+		if [[ $current_version == $last_changed_version ]]; then 
+			#go ahead and reinstall. 
+			echo "For $PACKAGENAME: svn current_version  is $current_version and last changed version is $last_changed_version"
+			echo "Triggering new install of $PACKAGENAME"
+			install_test=1
+		else
+			#ok, we want to skip, unless the package is not installed: 
+			if [ -d install ]; then 
+				#could be empty, signaling a failed previous install: 
+				if [ "$(ls -A install)" ];then
+					echo "For $PACKAGENAME: svn current_version  is $current_version and last changed version is $last_changed_version"
+					echo "and install directory exists, so skipping install of $PACKAGENAME"
+					install_test=0;
+				else
+					echo "For $PACKAGENAME: svn current_version  is $current_version and last changed version is $last_changed_version"
+					echo "and install directory exists, however, it is empty, so triggering install of $PACKAGENAME"
+					install_test=1;
+				fi
+			else
+				echo "For $PACKAGENAME: svn current_version  is $current_version and last changed version is $last_changed_version"
+				echo "However, install directory does not exist, so triggering install of $PACKAGENAME"
+				install_test=1;
+			fi
+		fi
+
+		if [[ $install_test == 1 ]]; then 
+			echo "======================================================";
+			echo "       Installing $PACKAGENAME                        ";
+			echo "======================================================";
+			./$PACKAGEINST |  tee compil.log
+			if [ $? -ne 0 ]; then
+				echo "======================================================";
+				echo "    ERROR: installation of $PACKAGENAME failed        ";
+				echo "======================================================";
+				#erase install directory, so that next time, we still try and compile this!
+				rm -rf install
+			fi
+			source $ISSM_DIR/etc/environment.sh
+		else
+			echo "======================================================";
+			echo "       Skipping install of $PACKAGENAME                        ";
+			echo "======================================================";
+			source $ISSM_DIR/etc/environment.sh #for good measure :)
+		fi
+		cd ..
+	done
+
+elif [ "$ISSM_EXTERNALPACKAGES" == "copy" ]
+then
+	cd $ISSM_DIR
+	rm -rf externalpackages
+	cp -Rf $EXTERNALPACKAGESDIR ./
+elif [ "$ISSM_EXTERNALPACKAGES" == "link" ]
+then
+	cd $ISSM_DIR
+	rm -rf externalpackages
+	ln -s  $EXTERNALPACKAGESDIR  .
+elif [ "$ISSM_EXTERNALPACKAGES" == "none" ]
+then
+	echo "Skipping external packages installation"
+else
+	echo "ISSM_EXTERNALPACKAGES supported values are: install, copy and none. Exiting..." >&2 # Error message to stderr.
+	exit 1
+fi
+source $ISSM_DIR/etc/environment.sh
+#}}}
+#ISSM compilation yes/no                (ISSM_COMPILATION) {{{
+if [ "$ISSM_COMPILATION" == "yes" ]
+then
+	cd $ISSM_DIR
+	make uninstall
+	make clean
+	make distclean
+	./scripts/automakererun.sh
+	cat > configure.sh << EOF
+./configure $ISSM_CONFIG
+EOF
+	chmod 700 configure.sh
+	./configure.sh
+
+	#4: compile and install ISSM
+	if [ $NUMCPUS_INSTALL -gt 1 ]
+	then
+		echo "Making with " $NUMCPUS_INSTALL " cpus"
+		make -j $NUMCPUS_INSTALL install
+	else
+		make install
+	fi
+	if [ $? -ne 0 ]; then 
+		echo "ISSM_COMPILATION failed!"
+		exit 1
+	fi
+elif [ "$ISSM_COMPILATION" == "no" ]
+then
+	echo "Skipping ISSM compilation"
+else
+	echo "ISSM_COMPILATION supported values are: yes and no. Exiting..." >&2 # Error message to stderr.
+	exit 1
+fi
+#}}}
+echo "Cleaning up execution directory"
+rm -rf $ISSM_DIR/execution/*
+
+#Prepare info.log
+#{{{
+rm -rf $ISSM_DIR/nightlylog
+mkdir  $ISSM_DIR/nightlylog
+INSTALL_TIME=$(timer)
+ELAPSED=$(timer $START_TIME)
+VERSION=$(svnversion $ISSM_DIR)
+cat << END > $ISSM_DIR/nightlylog/info.log
+name:      $(echo $NAME)
+today:     $(echo $TODAY)
+user:      $(echo $USER)
+host:      $(echo $HOST_NAME)
+OS:        $(echo $OS)
+release:   $(echo $ISSM_RELEASE)
+init_path: $(echo $INIT_PATH)
+is_matlab: $(echo $MATLAB_TEST)
+is_python: $(echo $PYTHON_TEST)
+elapsed_install: $(echo $ELAPSED)
+version: $(echo $VERSION)
+END
+#}}}
+
+#matlab tests
+if [ $MATLAB_TEST -eq 1 ]; then
+#Launch all tests on different cpus {{{
+MATLAB_START_TIME=$(timer);
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	#Launch matlab and the nightly run script
+	cat > $ISSM_DIR/nightlylog/matlab_run$i.m << EOF
+	warning off %necessary to avoid a info.log of several Go for parallel runs
+	try,
+	$(if [ "$MATLAB_NROPTIONS" = ""  ]
+	then
+		echo "runme('output','nightly','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	else
+		echo "runme($MATLAB_NROPTIONS,'output','nightly','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	fi
+	)
+	catch me,
+		%An error occured, get report and exit
+		message=getReport(me)
+		directory=strsplit(pwd,'/');
+		fid=fopen([issmdir '/nightlylog/matlaberror.log'], 'at');
+		fprintf(fid,'\nMatlab error occured in: %s\n\n',directory{end});
+		fprintf(fid,'%s',message);
+		fclose(fid);
+	end
+	disp('MATLABEXITEDCORRECTLY');
+	exit
+EOF
+	cd $ISSM_DIR/test/NightlyRun
+	matlab -nojvm -nosplash -r "addpath $ISSM_DIR/src/m/dev; devpath; addpath $ISSM_DIR/nightlylog/; matlab_run$i" -logfile $ISSM_DIR/nightlylog/matlab_log$i.log &
+done
+
+#wait until matlab closes
+if [ "$OS" = "win7" ]; then
+	pause MATLAB
+else
+	wait
+fi
+
+#concatenate reports
+cd $ISSM_DIR/nightlylog/
+rm matlab_log.log
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	cat matlab_log$i.log >> matlab_log.log
+done
+
+#filter out windows characters: 
+cat matlab_log.log | tr -cd '\11\12\40-\176' > matlab_log.log2 && mv matlab_log.log2 matlab_log.log
+
+#}}}
+#Complete info.log {{{
+if [ $(cat matlab_log.log | grep "MATLABEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
+then
+	MATLABCRASH=0
+else
+	MATLABCRASH=1
+fi
+ELAPSED=$(timer $MATLAB_START_TIME)
+cat << END >>  $ISSM_DIR/nightlylog/info.log
+elapsed_matlab: $(echo $ELAPSED)
+matlab_crash:   $(echo $MATLABCRASH)
+END
+#}}}
+fi
+
+#python tests
+if [ $PYTHON_TEST -eq 1 ]; then
+#Launch all tests on different cpus {{{
+PYTHON_START_TIME=$(timer);
+export PYTHONSTARTUP=$ISSM_DIR/src/m/dev/devpath.py
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	cd $ISSM_DIR/test/NightlyRun
+	./runme.py --output=nightly --rank=$i --numprocs=$NUMCPUS_RUN $PYTHON_NROPTIONS 2>&1 > $ISSM_DIR/nightlylog/python_log$i.log &
+done
+
+#wait until python closes
+if [ "$OS" = "win7" ]; then
+	pause MATLAB
+else
+	wait
+fi
+
+#concatenate reports
+cd $ISSM_DIR/nightlylog/
+rm python_log.log
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	cat python_log$i.log >> python_log.log
+done
+#}}}
+#Complete info.log {{{
+if [ $(cat python_log.log | grep "PYTHONEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
+then
+	PYTHONCRASH=0
+else
+	PYTHONCRASH=1
+fi
+ELAPSED=$(timer $PYTHON_START_TIME)
+cat << END >>  $ISSM_DIR/nightlylog/info.log
+elapsed_python: $(echo $ELAPSED)
+python_crash:   $(echo $PYTHONCRASH)
+END
+#}}}
+fi
+
+#complete info.log
+#{{{
+ELAPSED=$(timer $START_TIME)
+cat << END >>  $ISSM_DIR/nightlylog/info.log
+elapsed_total:  $(echo $ELAPSED)
+END
+#}}}
+
+#process logs to be junit compatible
+#{{{
+cd $ISSM_DIR/nightlylog/
+source $ISSM_DIR/externalpackages/shell2junit/install/sh2ju.sh
+juLogClean
+
+if [ $MATLAB_TEST -eq 1 ]; then
+	#number tests:
+	numtests=`cat matlab_log.log  | grep "\-\-\-\-\-\-\-\-starting" | wc -l`
+	testlist=`cat matlab_log.log  | grep "\-\-\-\-\-\-\-\-starting" | sed 's/----------------starting://g'  | sed 's/-//g'`
+
+	#look through numtests:
+	for i in `echo $testlist`
+	do
+		juLog  -test=MATLAB-$i -name=Error -error=ERROR awk "/starting:$i/{flag=1;next}/finished/{flag=0} flag{print}" matlab_log.log
+		juLog  -test=MATLAB-$i -name=Failure -error=FAILURE awk "/starting:$i/{flag=1;next}/finished/{flag=0} flag{print}" matlab_log.log
+	done
+fi
+if [ $PYTHON_TEST -eq 1 ]; then
+	#number tests:
+	numtests=`cat python_log.log  | grep "\-\-\-\-\-\-\-\-starting" | wc -l`
+	testlist=`cat python_log.log  | grep "\-\-\-\-\-\-\-\-starting" | sed 's/----------------starting://g'  | sed 's/-//g'`
+
+	#look through numtests:
+	for i in `echo $testlist`
+	do
+		juLog  -test=PYTHON-$i -name=Error -error=ERROR awk "/starting:$i/{flag=1;next}/finished/{flag=0} flag{print}" python_log.log
+		juLog  -test=PYTHON-$i -name=Failure -error=FAILURE awk "/starting:$i/{flag=1;next}/finished/{flag=0} flag{print}" python_log.log
+	done
+fi
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_larsen
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_larsen	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_larsen	(revision 18231)
@@ -0,0 +1,112 @@
+#
+########### Configuration file for Eric Larour's Jenkins run on Murdo ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM matlab tests on Linux64 (murdo)"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--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/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-numthreads=18 \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--enable-development \
+	--enable-debugging '
+
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+						matlab    install.sh                
+						mpich     install-3.0-linux64.sh    
+						cmake     install.sh                
+						petsc     install-3.4-linux64.sh    
+						triangle  install-linux64.sh        
+						boost     install.sh                
+						dakota    install-5.3.1-linux64.sh  
+						tao       install-2.2.sh
+						chaco     install.sh 
+						shell2junit install.sh"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=8
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS=""
+PYTHON_NROPTIONS=""
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo	(revision 18231)
@@ -0,0 +1,125 @@
+#
+########### Configuration file for Eric Larour's Jenkins run on Murdo ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM matlab tests on Linux64 (murdo)"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--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/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-arch=$ISSM_ARCH \
+	--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-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-numthreads=18 \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
+	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--enable-development \
+	--enable-debugging '
+
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=1
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+						matlab    install.sh                
+						mpich     install-3.0-linux64.sh    
+						cmake     install.sh                
+						petsc     install-3.4-linux64.sh    
+						triangle  install-linux64.sh        
+						boost     install.sh                
+						dakota    install-5.3.1-linux64.sh  
+						tao       install-2.2.sh
+						chaco     install.sh 
+						python        install-2.7.3-linux64.sh    
+						nose          install-linux64-python2.sh  
+						blas          install-linux64.sh          
+						lapack        install-linux64.sh          
+						git           install.sh                  
+						numpy         install-linux64.sh          
+						scipy         install-linux64.sh          
+						hdf5          install.sh                  
+						netcdf        install.sh                  
+						netcdf-python install.sh
+						shell2junit install.sh"
+
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=8
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS="'exclude',[119,514,701,702,435]"
+PYTHON_NROPTIONS="--exclude 119 514 701 702 435"
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ad
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ad	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ad	(revision 18231)
@@ -0,0 +1,100 @@
+########### Configuration file for Eric Larour's Jenkins runs on Linux. Automatic differentiation ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM tests on Linux64 (murdo). Automatic differentiation validation tests"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--prefix=$ISSM_DIR\
+				--prefix=$ISSM_DIR \
+				--without-kriging \
+				--without-kml \
+				--without-Gia \
+				--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 '
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+					 git install.sh 
+					 cmake install.sh 
+					 matlab install.sh 
+					 mpich install-3.0-linux64.sh
+					 petsc install-3.4-linux64.sh
+					 metis install-5.0.1-linux64.sh
+					 triangle install-linux64.sh 
+					 gsl install-linux64.sh 
+					 adolc install.sh
+					 shell2junit install.sh"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=8
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS="'benchmark','adolc','id',[3001:3019]"
+PYTHON_NROPTIONS=""
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ampi
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ampi	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/linux64_murdo_ampi	(revision 18231)
@@ -0,0 +1,113 @@
+#
+########### Configuration file for Eric Larour's Jenkins run on Murdo ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM tests on Linux64 (murdo). Automatic differentiation validation tests with ampi"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--prefix=$ISSM_DIR\
+				  --without-kriging \
+				  --without-kml \
+				  --without-Gia \
+				  --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+				  --with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+				  --with-ampi-dir=$ISSM_DIR/externalpackages/adjoinablempi/install \
+				  --with-matlab-dir=$MATLAB_DIR \
+				  --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+				  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+				  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+				  --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+				  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+				  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+				  --with-numthreads=18  \
+				  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+				  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+				  --enable-development \
+				  --enable-debugging CXXFLAGS="-g -O0" '
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh 
+					 git install.sh 
+					 cmake install.sh 
+					 matlab install.sh 
+					 mpich install-3.0-linux64.sh
+					 petsc install-3.4-linux64.sh
+					 metis install-5.0.1-linux64.sh
+					 triangle install-linux64.sh 
+					 gsl install-linux64.sh 
+					 mercurial install.sh
+					 adjoinablempi install.sh
+					 adolc install-withampi.sh
+					 shell2junit install.sh"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=8
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS="'benchmark','adolc','id',[3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3108, 3109, 3119]"
+PYTHON_NROPTIONS=""
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/parsing_rules
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/parsing_rules	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/parsing_rules	(revision 18231)
@@ -0,0 +1,15 @@
+ok /not really/
+
+# match line starting with 'error ', case-insensitive
+error /.*\\berror:\\b.*/
+
+# list of warnings here...
+warning /[Ww]arning/
+warning /WARNING/
+
+# create a quick access link to lines in the report containing 'INFO'
+info /INFO/
+
+# each line containing 'BUILD' represents the start of a section for grouping errors and warnings found after the line.
+# also creates a quick access link.
+start /BUILD/
Index: /issm/branches/trunk-jpl-ad2-integrated/jenkins/windows
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/jenkins/windows	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/jenkins/windows	(revision 18231)
@@ -0,0 +1,106 @@
+#
+########### Configuration file for Eric Larour's Jenkins run on Windows ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#Nightly run name
+NAME="ISSM matlab tests on Windows"
+
+#ISSM Architecture
+ISSM_ARCH="cygwin-intel"
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--prefix=$ISSM_DIR \
+   --disable-static \
+	--without-Gia \
+	--with-vendor=intel-win7-64  \
+	--with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-petsc-arch=$ISSM_ARCH  \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
+	--with-mpi-libdir="$ISSM_DIR/externalpackages/petsc/install/lib" \
+	--with-mpi-libflags="-Wl,libpetsc.lib" \
+	--with-mpi-include="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" \
+	--enable-debugging '
+
+#MATLAB path
+MATLAB_PATH="C:/MATLAB/R2013a/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES=" cccl install-win7.sh
+						petsc     install-3.1-win7.sh
+						triangle  install-win7.sh        
+						matlab install.sh
+						metis install-4.0-win7.sh
+						shell2junit install.sh"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
+
+#Mailing list
+MAILINGLIST="eric.larour@jpl.nasa.gov"
+
+#------------------------#
+# 6: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+
+#In Windows, we don't yet have MUMPS, can't do full stokes, so exclude all FS runs. Also exclude all runs with Dakota. And exclude higher order runs that have penalties. And 800+ tests because we don't want to have --with-development since we do the binaries with this version
+MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280,801,802,803,804,805,291]"
+PYTHON_NROPTIONS=""
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/ltmain.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/ltmain.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/ltmain.sh	(revision 18231)
@@ -0,0 +1,9655 @@
+
+# libtool (GNU libtool) 2.4.2
+# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# GNU Libtool is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html,
+# or obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# Usage: $progname [OPTION]... [MODE-ARG]...
+#
+# Provide generalized library-building support services.
+#
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and exit
+#       --mode=MODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --no-warn            don't display warning messages
+#       --tag=TAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
+#
+# MODE must be one of the following:
+#
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a program
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
+#
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
+# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
+#
+# When reporting a bug, please describe a test case to reproduce it and
+# include the following information:
+#
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4.2
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
+#
+# Report bugs to <bug-libtool@gnu.org>.
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=libtool
+PACKAGE=libtool
+VERSION=2.4.2
+TIMESTAMP=""
+package_revision=1.3337
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
+# NLS nuisances: We save the old values to restore during execute mode.
+lt_user_locale=
+lt_safe_locale=
+for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+  eval "if test \"\${$lt_var+set}\" = set; then
+          save_$lt_var=\$$lt_var
+          $lt_var=C
+	  export $lt_var
+	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
+	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
+	fi"
+done
+LC_ALL=C
+LANGUAGE=C
+export LANGUAGE LC_ALL
+
+$lt_unset CDPATH
+
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+
+
+: ${CP="cp -f"}
+test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
+: ${MAKE="make"}
+: ${MKDIR="mkdir"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+: ${SHELL="${CONFIG_SHELL-/bin/sh}"}
+: ${Xsed="$SED -e 1s/^X//"}
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
+EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
+
+exit_status=$EXIT_SUCCESS
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" 	$lt_nl"
+
+dirname="s,/[^/]*$,,"
+basename="s,^.*/,,"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+    # Extract subdirectory from the argument.
+    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementation
+
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+    case ${2} in
+      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar='s,^/\([^/]*\).*$,\1,'
+pathcdr='s,^/[^/]*,,'
+removedotparts=':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes='s@/\{1,\}@/@g'
+finalslash='s,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=
+  func_normal_abspath_tpath=$1
+  func_normal_abspath_altnamespace=
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" = / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+        func_relative_path_tcancelled=$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" = x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=../$func_relative_path_result
+          func_relative_path_tcancelled=$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" != x ; then
+    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
+  fi
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=$func_stripname_result
+  fi
+}
+
+# The name of this program:
+func_dirname_and_basename "$progpath"
+progname=$func_basename_result
+
+# Make sure we have an absolute path for reexecution:
+case $progpath in
+  [\\/]*|[A-Za-z]:\\*) ;;
+  *[\\/]*)
+     progdir=$func_dirname_result
+     progdir=`cd "$progdir" && pwd`
+     progpath="$progdir/$progname"
+     ;;
+  *)
+     save_IFS="$IFS"
+     IFS=${PATH_SEPARATOR-:}
+     for progdir in $PATH; do
+       IFS="$save_IFS"
+       test -x "$progdir/$progname" && break
+     done
+     IFS="$save_IFS"
+     test -n "$progdir" || progdir=`pwd`
+     progpath="$progdir/$progname"
+     ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([`"$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+
+# Re-`\' parameter expansions in output of double_quote_subst that were
+# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
+# in input to double_quote_subst, that '$' was protected from expansion.
+# Since each input `\' is now two `\'s, look for any number of runs of
+# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
+bs='\\'
+bs2='\\\\'
+bs4='\\\\\\\\'
+dollar='\$'
+sed_double_backslash="\
+  s/$bs4/&\\
+/g
+  s/^$bs2$dollar/$bs&/
+  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
+  s/\n//g"
+
+# Standard options:
+opt_dry_run=false
+opt_help=false
+opt_quiet=false
+opt_verbose=false
+opt_warning=:
+
+# func_echo arg...
+# Echo program name prefixed message, along with the current mode
+# name if it has been set yet.
+func_echo ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
+}
+
+# func_verbose arg...
+# Echo program name prefixed message in verbose mode only.
+func_verbose ()
+{
+    $opt_verbose && func_echo ${1+"$@"}
+
+    # A bug in bash halts the script if the last line of a function
+    # fails when set -e is in force, so we need another command to
+    # work around that:
+    :
+}
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
+# func_error arg...
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
+}
+
+# func_warning arg...
+# Echo program name prefixed warning message to standard error.
+func_warning ()
+{
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
+
+    # bash bug again:
+    :
+}
+
+# func_fatal_error arg...
+# Echo program name prefixed message to standard error, and exit.
+func_fatal_error ()
+{
+    func_error ${1+"$@"}
+    exit $EXIT_FAILURE
+}
+
+# func_fatal_help arg...
+# Echo program name prefixed message to standard error, followed by
+# a help hint, and exit.
+func_fatal_help ()
+{
+    func_error ${1+"$@"}
+    func_fatal_error "$help"
+}
+help="Try \`$progname --help' for more information."  ## default
+
+
+# func_grep expression filename
+# Check whether EXPRESSION matches any line of FILENAME, without output.
+func_grep ()
+{
+    $GREP "$1" "$2" >/dev/null 2>&1
+}
+
+
+# func_mkdir_p directory-path
+# Make sure the entire path to DIRECTORY-PATH is available.
+func_mkdir_p ()
+{
+    my_directory_path="$1"
+    my_dir_list=
+
+    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then
+
+      # Protect directory names starting with `-'
+      case $my_directory_path in
+        -*) my_directory_path="./$my_directory_path" ;;
+      esac
+
+      # While some portion of DIR does not yet exist...
+      while test ! -d "$my_directory_path"; do
+        # ...make a list in topmost first order.  Use a colon delimited
+	# list incase some portion of path contains whitespace.
+        my_dir_list="$my_directory_path:$my_dir_list"
+
+        # If the last portion added has no slash in it, the list is done
+        case $my_directory_path in */*) ;; *) break ;; esac
+
+        # ...otherwise throw away the child directory and loop
+        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
+      done
+      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
+
+      save_mkdir_p_IFS="$IFS"; IFS=':'
+      for my_dir in $my_dir_list; do
+	IFS="$save_mkdir_p_IFS"
+        # mkdir can fail with a `File exist' error if two processes
+        # try to create one of the directories concurrently.  Don't
+        # stop in that case!
+        $MKDIR "$my_dir" 2>/dev/null || :
+      done
+      IFS="$save_mkdir_p_IFS"
+
+      # Bail out if we (or some other process) failed to create a directory.
+      test -d "$my_directory_path" || \
+        func_fatal_error "Failed to create \`$1'"
+    fi
+}
+
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible.  If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+    my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+    if test "$opt_dry_run" = ":"; then
+      # Return a directory name, but don't create it in dry-run mode
+      my_tmpdir="${my_template}-$$"
+    else
+
+      # If mktemp works, use that first and foremost
+      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+      if test ! -d "$my_tmpdir"; then
+        # Failing that, at least try and use $RANDOM to avoid a race
+        my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+        save_mktempdir_umask=`umask`
+        umask 0077
+        $MKDIR "$my_tmpdir"
+        umask $save_mktempdir_umask
+      fi
+
+      # If we're not in dry-run mode, bomb out on failure
+      test -d "$my_tmpdir" || \
+        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
+    fi
+
+    $ECHO "$my_tmpdir"
+}
+
+
+# func_quote_for_eval arg
+# Aesthetically quote ARG to be evaled later.
+# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
+# is double-quoted, suitable for a subsequent eval, whereas
+# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
+# which are still active within double quotes backslashified.
+func_quote_for_eval ()
+{
+    case $1 in
+      *[\\\`\"\$]*)
+	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
+      *)
+        func_quote_for_eval_unquoted_result="$1" ;;
+    esac
+
+    case $func_quote_for_eval_unquoted_result in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting, command substitution and and variable
+      # expansion for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
+        ;;
+      *)
+        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
+    esac
+}
+
+
+# func_quote_for_expand arg
+# Aesthetically quote ARG to be evaled later; same as above,
+# but do not quote variable references.
+func_quote_for_expand ()
+{
+    case $1 in
+      *[\\\`\"]*)
+	my_arg=`$ECHO "$1" | $SED \
+	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
+      *)
+        my_arg="$1" ;;
+    esac
+
+    case $my_arg in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting and command substitution for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        my_arg="\"$my_arg\""
+        ;;
+    esac
+
+    func_quote_for_expand_result="$my_arg"
+}
+
+
+# func_show_eval cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.
+func_show_eval ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$my_cmd"
+      my_status=$?
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+
+# func_show_eval_locale cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.  Use the saved locale for evaluation.
+func_show_eval_locale ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$lt_user_locale
+	    $my_cmd"
+      my_status=$?
+      eval "$lt_safe_locale"
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=$1
+    ;;
+  esac
+}
+
+
+# func_version
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
+        s/^# //
+	s/^# *$//
+        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
+        p
+     }' < "$progpath"
+     exit $?
+}
+
+# func_usage
+# Echo short help message to standard output and exit.
+func_usage ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
+        s/^# //
+	s/^# *$//
+	s/\$progname/'$progname'/
+	p
+    }' < "$progpath"
+    echo
+    $ECHO "run \`$progname --help | more' for full usage"
+    exit $?
+}
+
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
+func_help ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
+        s/^# //
+	s/^# *$//
+	s*\$progname*'$progname'*
+	s*\$host*'"$host"'*
+	s*\$SHELL*'"$SHELL"'*
+	s*\$LTCC*'"$LTCC"'*
+	s*\$LTCFLAGS*'"$LTCFLAGS"'*
+	s*\$LD*'"$LD"'*
+	s/\$with_gnu_ld/'"$with_gnu_ld"'/
+	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
+	p
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=$?
+    if test -z "$1"; then
+      exit $ret
+    fi
+}
+
+# func_missing_arg argname
+# Echo program name prefixed message to standard error and set global
+# exit_cmd.
+func_missing_arg ()
+{
+    $opt_debug
+
+    func_error "missing argument for $1."
+    exit_cmd=exit
+}
+
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
+    my_sed_long_arg='1s/^--[^=]*=//'
+
+    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
+exit_cmd=:
+
+
+
+
+
+magic="%%%MAGIC variable%%%"
+magic_exe="%%%MAGIC EXE variable%%%"
+
+# Global variables.
+nonopt=
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
+# func_fatal_configuration arg...
+# Echo program name prefixed message to standard error, followed by
+# a configuration failure hint, and exit.
+func_fatal_configuration ()
+{
+    func_error ${1+"$@"}
+    func_error "See the $PACKAGE documentation for more information."
+    func_fatal_error "Fatal configuration error."
+}
+
+
+# func_config
+# Display the configuration for all the tags in this script.
+func_config ()
+{
+    re_begincf='^# ### BEGIN LIBTOOL'
+    re_endcf='^# ### END LIBTOOL'
+
+    # Default configuration.
+    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"
+
+    # Now print the configurations for the tags.
+    for tagname in $taglist; do
+      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath"
+    done
+
+    exit $?
+}
+
+# func_features
+# Display the features supported by this script.
+func_features ()
+{
+    echo "host: $host"
+    if test "$build_libtool_libs" = yes; then
+      echo "enable shared libraries"
+    else
+      echo "disable shared libraries"
+    fi
+    if test "$build_old_libs" = yes; then
+      echo "enable static libraries"
+    else
+      echo "disable static libraries"
+    fi
+
+    exit $?
+}
+
+# func_enable_tag tagname
+# Verify that TAGNAME is valid, and either flag an error and exit, or
+# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
+# variable here.
+func_enable_tag ()
+{
+  # Global variable:
+  tagname="$1"
+
+  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
+  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
+  sed_extractcf="/$re_begincf/,/$re_endcf/p"
+
+  # Validate tagname.
+  case $tagname in
+    *[!-_A-Za-z0-9,/]*)
+      func_fatal_error "invalid tag name: $tagname"
+      ;;
+  esac
+
+  # Don't test for the "default" C tag, as we know it's
+  # there but not specially marked.
+  case $tagname in
+    CC) ;;
+    *)
+      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
+	taglist="$taglist $tagname"
+
+	# Evaluate the configuration.  Be careful to quote the path
+	# and the sed script, to avoid splitting on whitespace, but
+	# also don't use non-portable quotes within backquotes within
+	# quotes we have to do it in 2 steps:
+	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
+	eval "$extractedcf"
+      else
+	func_error "ignoring unknown tag $tagname"
+      fi
+      ;;
+  esac
+}
+
+# func_check_version_match
+# Ensure that we are using m4 macros, and libtool script from the same
+# release of libtool.
+func_check_version_match ()
+{
+  if test "$package_revision" != "$macro_revision"; then
+    if test "$VERSION" != "$macro_version"; then
+      if test -z "$macro_version"; then
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from an older release.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      else
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      fi
+    else
+      cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
+$progname: but the definition of this LT_INIT comes from revision $macro_revision.
+$progname: You should recreate aclocal.m4 with macros from revision $package_revision
+$progname: of $PACKAGE $VERSION and run autoconf again.
+_LT_EOF
+    fi
+
+    exit $EXIT_MISMATCH
+  fi
+}
+
+
+# Shorthand for --mode=foo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=:
+opt_dry_run=false
+opt_config=false
+opt_preserve_dup_deps=false
+opt_features=false
+opt_finish=false
+opt_help=false
+opt_help_all=false
+opt_silent=:
+opt_warning=:
+opt_verbose=:
+opt_silent=false
+opt_verbose=false
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt="$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug='set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=:
+			;;
+      --config)
+			opt_config=:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg="$1"
+			opt_dlopen="${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=:
+			;;
+      --features)
+			opt_features=:
+func_features
+			;;
+      --finish)
+			opt_finish=:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=:
+			;;
+      --help-all)
+			opt_help_all=:
+opt_help=': help-all'
+			;;
+      --mode)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_mode="$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=exit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=false
+func_append preserve_args " $opt"
+			;;
+      --no-warning|--no-warn)
+			opt_warning=false
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=false
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=:
+func_append preserve_args " $opt"
+        opt_verbose=false
+			;;
+      --verbose|-v)
+			opt_verbose=:
+func_append preserve_args " $opt"
+opt_silent=false
+			;;
+      --tag)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_tag="$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt="$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" = : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+      func_fatal_configuration "not configured to build any kind of library"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help="$help"
+    help="Try \`$progname --help --mode=$opt_mode' for more information."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
+## ----------- ##
+##    Main.    ##
+## ----------- ##
+
+# func_lalib_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_lalib_p ()
+{
+    test -f "$1" &&
+      $SED -e 4q "$1" 2>/dev/null \
+        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+}
+
+# func_lalib_unsafe_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function implements the same check as func_lalib_p without
+# resorting to external programs.  To this end, it redirects stdin and
+# closes it afterwards, without saving the original file descriptor.
+# As a safety measure, use it only where a negative result would be
+# fatal anyway.  Works if `file' does not exist.
+func_lalib_unsafe_p ()
+{
+    lalib_p=no
+    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
+	for lalib_p_l in 1 2 3 4
+	do
+	    read lalib_p_line
+	    case "$lalib_p_line" in
+		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
+	    esac
+	done
+	exec 0<&5 5<&-
+    fi
+    test "$lalib_p" = yes
+}
+
+# func_ltwrapper_script_p file
+# True iff FILE is a libtool wrapper script
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_script_p ()
+{
+    func_lalib_p "$1"
+}
+
+# func_ltwrapper_executable_p file
+# True iff FILE is a libtool wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_executable_p ()
+{
+    func_ltwrapper_exec_suffix=
+    case $1 in
+    *.exe) ;;
+    *) func_ltwrapper_exec_suffix=.exe ;;
+    esac
+    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
+}
+
+# func_ltwrapper_scriptname file
+# Assumes file is an ltwrapper_executable
+# uses $file to determine the appropriate filename for a
+# temporary ltwrapper_script.
+func_ltwrapper_scriptname ()
+{
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
+}
+
+# func_ltwrapper_p file
+# True iff FILE is a libtool wrapper script or wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_p ()
+{
+    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
+}
+
+
+# func_execute_cmds commands fail_cmd
+# Execute tilde-delimited COMMANDS.
+# If FAIL_CMD is given, eval that upon failure.
+# FAIL_CMD may read-access the current command in variable CMD!
+func_execute_cmds ()
+{
+    $opt_debug
+    save_ifs=$IFS; IFS='~'
+    for cmd in $1; do
+      IFS=$save_ifs
+      eval cmd=\"$cmd\"
+      func_show_eval "$cmd" "${2-:}"
+    done
+    IFS=$save_ifs
+}
+
+
+# func_source file
+# Source FILE, adding directory component if necessary.
+# Note that it is not necessary on cygwin/mingw to append a dot to
+# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
+# behavior happens only for exec(3), not for open(2)!  Also, sourcing
+# `FILE.' does not work on cygwin managed mounts.
+func_source ()
+{
+    $opt_debug
+    case $1 in
+    */* | *\\*)	. "$1" ;;
+    *)		. "./$1" ;;
+    esac
+}
+
+
+# func_resolve_sysroot PATH
+# Replace a leading = in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=$1
+  case $func_resolve_sysroot_result in
+  =*)
+    func_stripname '=' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with = and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result="=$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=$1
+    ;;
+  esac
+}
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+    $opt_debug
+    if test -n "$available_tags" && test -z "$tagname"; then
+      CC_quoted=
+      for arg in $CC; do
+	func_append_quoted CC_quoted "$arg"
+      done
+      CC_expanded=`func_echo_all $CC`
+      CC_quoted_expanded=`func_echo_all $CC_quoted`
+      case $@ in
+      # Blanks in the command may have been stripped by the calling shell,
+      # but not from the CC environment variable when configure was run.
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
+      # Blanks at the start of $base_compile will cause this to fail
+      # if we don't check for them as well.
+      *)
+	for z in $available_tags; do
+	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+	    # Evaluate the configuration.
+	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+	    CC_quoted=
+	    for arg in $CC; do
+	      # Double-quote args containing other shell metacharacters.
+	      func_append_quoted CC_quoted "$arg"
+	    done
+	    CC_expanded=`func_echo_all $CC`
+	    CC_quoted_expanded=`func_echo_all $CC_quoted`
+	    case "$@ " in
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
+	      # The compiler in the base compile command matches
+	      # the one in the tagged configuration.
+	      # Assume this is the tagged configuration we want.
+	      tagname=$z
+	      break
+	      ;;
+	    esac
+	  fi
+	done
+	# If $tagname still isn't set, then no tagged configuration
+	# was found and let the user know that the "--tag" command
+	# line option must be used.
+	if test -z "$tagname"; then
+	  func_echo "unable to infer tagged configuration"
+	  func_fatal_error "specify a tag with \`--tag'"
+#	else
+#	  func_verbose "using $tagname tagged configuration"
+	fi
+	;;
+      esac
+    fi
+}
+
+
+
+# func_write_libtool_object output_name pic_name nonpic_name
+# Create a libtool object file (analogous to a ".la" file),
+# but don't create it if we're doing a dry run.
+func_write_libtool_object ()
+{
+    write_libobj=${1}
+    if test "$build_libtool_libs" = yes; then
+      write_lobj=\'${2}\'
+    else
+      write_lobj=none
+    fi
+
+    if test "$build_old_libs" = yes; then
+      write_oldobj=\'${3}\'
+    else
+      write_oldobj=none
+    fi
+
+    $opt_dry_run || {
+      cat >${write_libobj}T <<EOF
+# $write_libobj - a libtool object file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+pic_object=$write_lobj
+
+# Name of the non-PIC object
+non_pic_object=$write_oldobj
+
+EOF
+      $MV "${write_libobj}T" "${write_libobj}"
+    }
+}
+
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *nix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath program
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and will
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result="$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and print
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, and
+# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
+# configured wine environment available, with the winepath program in $build's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=""
+  if test -n "$1"; then
+    oldIFS=$IFS
+    IFS=:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file name
+# or path in func_cygpath_result (input file name or path is assumed to be in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or path to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=
+    fi
+  else
+    func_cygpath_result=
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result="$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" != "x$2"; then
+      lt_replace_pathsep_chars="s|$1|$2|g"
+      func_to_host_path_result=`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result="$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return result
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result="$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environment
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinations,
+# the two new functions must follow this pattern, or func_init_to_host_path_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result="$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment and
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
+# func_mode_compile arg...
+func_mode_compile ()
+{
+    $opt_debug
+    # Get the compilation command and the source file.
+    base_compile=
+    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
+    suppress_opt=yes
+    suppress_output=
+    arg_mode=normal
+    libobj=
+    later=
+    pie_flag=
+
+    for arg
+    do
+      case $arg_mode in
+      arg  )
+	# do not "continue".  Instead, add this to base_compile
+	lastarg="$arg"
+	arg_mode=normal
+	;;
+
+      target )
+	libobj="$arg"
+	arg_mode=normal
+	continue
+	;;
+
+      normal )
+	# Accept any command-line options.
+	case $arg in
+	-o)
+	  test -n "$libobj" && \
+	    func_fatal_error "you cannot specify \`-o' more than once"
+	  arg_mode=target
+	  continue
+	  ;;
+
+	-pie | -fpie | -fPIE)
+          func_append pie_flag " $arg"
+	  continue
+	  ;;
+
+	-shared | -static | -prefer-pic | -prefer-non-pic)
+	  func_append later " $arg"
+	  continue
+	  ;;
+
+	-no-suppress)
+	  suppress_opt=no
+	  continue
+	  ;;
+
+	-Xcompiler)
+	  arg_mode=arg  #  the next one goes into the "base_compile" arg list
+	  continue      #  The current "srcfile" will either be retained or
+	  ;;            #  replaced later.  I would guess that would be a bug.
+
+	-Wc,*)
+	  func_stripname '-Wc,' '' "$arg"
+	  args=$func_stripname_result
+	  lastarg=
+	  save_ifs="$IFS"; IFS=','
+	  for arg in $args; do
+	    IFS="$save_ifs"
+	    func_append_quoted lastarg "$arg"
+	  done
+	  IFS="$save_ifs"
+	  func_stripname ' ' '' "$lastarg"
+	  lastarg=$func_stripname_result
+
+	  # Add the arguments to base_compile.
+	  func_append base_compile " $lastarg"
+	  continue
+	  ;;
+
+	*)
+	  # Accept the current argument as the source file.
+	  # The previous "srcfile" becomes the current argument.
+	  #
+	  lastarg="$srcfile"
+	  srcfile="$arg"
+	  ;;
+	esac  #  case $arg
+	;;
+      esac    #  case $arg_mode
+
+      # Aesthetically quote the previous argument.
+      func_append_quoted base_compile "$lastarg"
+    done # for arg
+
+    case $arg_mode in
+    arg)
+      func_fatal_error "you must specify an argument for -Xcompile"
+      ;;
+    target)
+      func_fatal_error "you must specify a target with \`-o'"
+      ;;
+    *)
+      # Get the name of the library object.
+      test -z "$libobj" && {
+	func_basename "$srcfile"
+	libobj="$func_basename_result"
+      }
+      ;;
+    esac
+
+    # Recognize several different file suffixes.
+    # If the user specifies -o file.o, it is replaced with file.lo
+    case $libobj in
+    *.[cCFSifmso] | \
+    *.ada | *.adb | *.ads | *.asm | \
+    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
+    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
+      func_xform "$libobj"
+      libobj=$func_xform_result
+      ;;
+    esac
+
+    case $libobj in
+    *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
+    *)
+      func_fatal_error "cannot determine name of library object from \`$libobj'"
+      ;;
+    esac
+
+    func_infer_tag $base_compile
+
+    for arg in $later; do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	continue
+	;;
+
+      -static)
+	build_libtool_libs=no
+	build_old_libs=yes
+	continue
+	;;
+
+      -prefer-pic)
+	pic_mode=yes
+	continue
+	;;
+
+      -prefer-non-pic)
+	pic_mode=no
+	continue
+	;;
+      esac
+    done
+
+    func_quote_for_eval "$libobj"
+    test "X$libobj" != "X$func_quote_for_eval_result" \
+      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
+      && func_warning "libobj name \`$libobj' may not contain shell special characters."
+    func_dirname_and_basename "$obj" "/" ""
+    objname="$func_basename_result"
+    xdir="$func_dirname_result"
+    lobj=${xdir}$objdir/$objname
+
+    test -z "$base_compile" && \
+      func_fatal_help "you must specify a compilation command"
+
+    # Delete any leftover library objects.
+    if test "$build_old_libs" = yes; then
+      removelist="$obj $lobj $libobj ${libobj}T"
+    else
+      removelist="$lobj $libobj ${libobj}T"
+    fi
+
+    # On Cygwin there's no "real" PIC flag so we must build both object types
+    case $host_os in
+    cygwin* | mingw* | pw32* | os2* | cegcc*)
+      pic_mode=default
+      ;;
+    esac
+    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+      # non-PIC code in shared libraries is not supported
+      pic_mode=default
+    fi
+
+    # Calculate the filename of the output object if compiler does
+    # not support -o with -c
+    if test "$compiler_c_o" = no; then
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
+      lockfile="$output_obj.lock"
+    else
+      output_obj=
+      need_locks=no
+      lockfile=
+    fi
+
+    # Lock this critical section if it is needed
+    # We use this script file to make the link, it avoids creating a new file
+    if test "$need_locks" = yes; then
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    elif test "$need_locks" = warn; then
+      if test -f "$lockfile"; then
+	$ECHO "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+      func_append removelist " $output_obj"
+      $ECHO "$srcfile" > "$lockfile"
+    fi
+
+    $opt_dry_run || $RM $removelist
+    func_append removelist " $lockfile"
+    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
+
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=$func_to_tool_file_result
+    func_quote_for_eval "$srcfile"
+    qsrcfile=$func_quote_for_eval_result
+
+    # Only build a PIC object if we are building libtool libraries.
+    if test "$build_libtool_libs" = yes; then
+      # Without this assignment, base_compile gets emptied.
+      fbsd_hideous_sh_bug=$base_compile
+
+      if test "$pic_mode" != no; then
+	command="$base_compile $qsrcfile $pic_flag"
+      else
+	# Don't build PIC code
+	command="$base_compile $qsrcfile"
+      fi
+
+      func_mkdir_p "$xdir$objdir"
+
+      if test -z "$output_obj"; then
+	# Place PIC objects in $objdir
+	func_append command " -o $lobj"
+      fi
+
+      func_show_eval_locale "$command"	\
+          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed, then go on to compile the next one
+      if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+	func_show_eval '$MV "$output_obj" "$lobj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+
+      # Allow error messages only from the first compilation.
+      if test "$suppress_opt" = yes; then
+	suppress_output=' >/dev/null 2>&1'
+      fi
+    fi
+
+    # Only build a position-dependent object if we build old libraries.
+    if test "$build_old_libs" = yes; then
+      if test "$pic_mode" != yes; then
+	# Don't build PIC code
+	command="$base_compile $qsrcfile$pie_flag"
+      else
+	command="$base_compile $qsrcfile $pic_flag"
+      fi
+      if test "$compiler_c_o" = yes; then
+	func_append command " -o $obj"
+      fi
+
+      # Suppress compiler output if we already did a PIC compilation.
+      func_append command "$suppress_output"
+      func_show_eval_locale "$command" \
+        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed
+      if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+	func_show_eval '$MV "$output_obj" "$obj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+    fi
+
+    $opt_dry_run || {
+      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
+
+      # Unlock the critical section if it was locked
+      if test "$need_locks" != no; then
+	removelist=$lockfile
+        $RM "$lockfile"
+      fi
+    }
+
+    exit $EXIT_SUCCESS
+}
+
+$opt_help || {
+  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
+}
+
+func_mode_help ()
+{
+    # We need to display help for each of the modes.
+    case $opt_mode in
+      "")
+        # Generic help is extracted from the usage comments
+        # at the start of this file.
+        func_help
+        ;;
+
+      clean)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      compile)
+      $ECHO \
+"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
+  -no-suppress      do not suppress compiler output for multiple passes
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
+  -shared           do not build a \`.o' file suitable for static linking
+  -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+        ;;
+
+      execute)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+  -dlopen FILE      add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+        ;;
+
+      finish)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges.  Use
+the \`--dry-run' option if you just want to see what would be executed."
+        ;;
+
+      install)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command.  The first component should be
+either the \`install' or \`cp' program.
+
+The following components of INSTALL-COMMAND are treated specially:
+
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+        ;;
+
+      link)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+  -all-static       do not do any dynamic linking at all
+  -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
+  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
+  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
+  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+  -export-symbols SYMFILE
+                    try to export only the symbols listed in SYMFILE
+  -export-symbols-regex REGEX
+                    try to export only the symbols matching REGEX
+  -LLIBDIR          search LIBDIR for required installed libraries
+  -lNAME            OUTPUT-FILE requires the installed library libNAME
+  -module           build a library that can dlopened
+  -no-fast-install  disable the fast-install mode
+  -no-install       link a not-installable executable
+  -no-undefined     declare that a library does not refer to external symbols
+  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
+  -objectlist FILE  Use a list of object files found in FILE to specify objects
+  -precious-files-regex REGEX
+                    don't remove output files matching REGEX
+  -release RELEASE  specify package release information
+  -rpath LIBDIR     the created library will eventually be installed in LIBDIR
+  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries
+  -shared           only do dynamic linking of libtool libraries
+  -shrext SUFFIX    override the standard shared library file extension
+  -static           do not do any dynamic linking of uninstalled libtool libraries
+  -static-libtool-libs
+                    do not do any dynamic linking of libtool libraries
+  -version-info CURRENT[:REVISION[:AGE]]
+                    specify library version info [each variable defaults to 0]
+  -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename.  Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+        ;;
+
+      uninstall)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      *)
+        func_fatal_help "invalid operation mode \`$opt_mode'"
+        ;;
+    esac
+
+    echo
+    $ECHO "Try \`$progname --help' for more information about other modes."
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" = :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
+      }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
+
+
+# func_mode_execute arg...
+func_mode_execute ()
+{
+    $opt_debug
+    # The first argument is the command name.
+    cmd="$nonopt"
+    test -z "$cmd" && \
+      func_fatal_help "you must specify a COMMAND"
+
+    # Handle -dlopen flags immediately.
+    for file in $opt_dlopen; do
+      test -f "$file" \
+	|| func_fatal_help "\`$file' is not a file"
+
+      dir=
+      case $file in
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$lib' is not a valid libtool archive"
+
+	# Read the libtool library.
+	dlname=
+	library_names=
+	func_source "$file"
+
+	# Skip this library if it cannot be dlopened.
+	if test -z "$dlname"; then
+	  # Warn if it was a shared library.
+	  test -n "$library_names" && \
+	    func_warning "\`$file' was not linked with \`-export-dynamic'"
+	  continue
+	fi
+
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+
+	if test -f "$dir/$objdir/$dlname"; then
+	  func_append dir "/$objdir"
+	else
+	  if test ! -f "$dir/$dlname"; then
+	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
+	  fi
+	fi
+	;;
+
+      *.lo)
+	# Just add the directory containing the .lo file.
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+	;;
+
+      *)
+	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
+	continue
+	;;
+      esac
+
+      # Get the absolute pathname.
+      absdir=`cd "$dir" && pwd`
+      test -n "$absdir" && dir="$absdir"
+
+      # Now add the directory to shlibpath_var.
+      if eval "test -z \"\$$shlibpath_var\""; then
+	eval "$shlibpath_var=\"\$dir\""
+      else
+	eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+      fi
+    done
+
+    # This variable tells wrapper scripts just to set shlibpath_var
+    # rather than running their programs.
+    libtool_execute_magic="$magic"
+
+    # Check if any of the arguments is a wrapper script.
+    args=
+    for file
+    do
+      case $file in
+      -* | *.la | *.lo ) ;;
+      *)
+	# Do a test to see if this is really a libtool program.
+	if func_ltwrapper_script_p "$file"; then
+	  func_source "$file"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	elif func_ltwrapper_executable_p "$file"; then
+	  func_ltwrapper_scriptname "$file"
+	  func_source "$func_ltwrapper_scriptname_result"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	fi
+	;;
+      esac
+      # Quote arguments (to preserve shell metacharacters).
+      func_append_quoted args "$file"
+    done
+
+    if test "X$opt_dry_run" = Xfalse; then
+      if test -n "$shlibpath_var"; then
+	# Export the shlibpath_var.
+	eval "export $shlibpath_var"
+      fi
+
+      # Restore saved environment variables
+      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+      do
+	eval "if test \"\${save_$lt_var+set}\" = set; then
+                $lt_var=\$save_$lt_var; export $lt_var
+	      else
+		$lt_unset $lt_var
+	      fi"
+      done
+
+      # Now prepare to actually exec the command.
+      exec_cmd="\$cmd$args"
+    else
+      # Display what would be done.
+      if test -n "$shlibpath_var"; then
+	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
+	echo "export $shlibpath_var"
+      fi
+      $ECHO "$cmd$args"
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
+
+
+# func_mode_finish arg...
+func_mode_finish ()
+{
+    $opt_debug
+    libs=
+    libdirs=
+    admincmds=
+
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
+        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+        done
+      else
+        tmpdir=`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      for libdir in $libdirs; do
+	if test -n "$finish_cmds"; then
+	  # Do each command in the finish commands.
+	  func_execute_cmds "$finish_cmds" 'admincmds="$admincmds
+'"$cmd"'"'
+	fi
+	if test -n "$finish_eval"; then
+	  # Do the single finish_eval.
+	  eval cmds=\"$finish_eval\"
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
+       $cmds"
+	fi
+      done
+    fi
+
+    # Exit here if they wanted silent mode.
+    $opt_silent && exit $EXIT_SUCCESS
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "----------------------------------------------------------------------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=LIBDIR
+	eval flag=\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "----------------------------------------------------------------------"
+    fi
+    exit $EXIT_SUCCESS
+}
+
+test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
+
+
+# func_mode_install arg...
+func_mode_install ()
+{
+    $opt_debug
+    # There may be an optional sh(1) argument at the beginning of
+    # install_prog (especially on Windows NT).
+    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+       # Allow the use of GNU shtool's install command.
+       case $nonopt in *shtool*) :;; *) false;; esac; then
+      # Aesthetically quote it.
+      func_quote_for_eval "$nonopt"
+      install_prog="$func_quote_for_eval_result "
+      arg=$1
+      shift
+    else
+      install_prog=
+      arg=$nonopt
+    fi
+
+    # The real first argument should be the name of the installation program.
+    # Aesthetically quote it.
+    func_quote_for_eval "$arg"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=: ;;
+      *) install_cp=false ;;
+    esac
+
+    # We need to accept at least all the BSD install flags.
+    dest=
+    files=
+    opts=
+    prev=
+    install_type=
+    isdir=no
+    stripme=
+    no_mode=:
+    for arg
+    do
+      arg2=
+      if test -n "$dest"; then
+	func_append files " $dest"
+	dest=$arg
+	continue
+      fi
+
+      case $arg in
+      -d) isdir=yes ;;
+      -f)
+	if $install_cp; then :; else
+	  prev=$arg
+	fi
+	;;
+      -g | -m | -o)
+	prev=$arg
+	;;
+      -s)
+	stripme=" -s"
+	continue
+	;;
+      -*)
+	;;
+      *)
+	# If the previous option needed an argument, then skip it.
+	if test -n "$prev"; then
+	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	    arg2=$install_override_mode
+	    no_mode=false
+	  fi
+	  prev=
+	else
+	  dest=$arg
+	  continue
+	fi
+	;;
+      esac
+
+      # Aesthetically quote the argument.
+      func_quote_for_eval "$arg"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
+    done
+
+    test -z "$install_prog" && \
+      func_fatal_help "you must specify an install program"
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
+
+    if test -z "$files"; then
+      if test -z "$dest"; then
+	func_fatal_help "no file or destination specified"
+      else
+	func_fatal_help "you must specify a destination"
+      fi
+    fi
+
+    # Strip any trailing slash from the destination.
+    func_stripname '' '/' "$dest"
+    dest=$func_stripname_result
+
+    # Check to see that the destination is a directory.
+    test -d "$dest" && isdir=yes
+    if test "$isdir" = yes; then
+      destdir="$dest"
+      destname=
+    else
+      func_dirname_and_basename "$dest" "" "."
+      destdir="$func_dirname_result"
+      destname="$func_basename_result"
+
+      # Not a directory, so check to see that there is only one file specified.
+      set dummy $files; shift
+      test "$#" -gt 1 && \
+	func_fatal_help "\`$dest' is not a directory"
+    fi
+    case $destdir in
+    [\\/]* | [A-Za-z]:[\\/]*) ;;
+    *)
+      for file in $files; do
+	case $file in
+	*.lo) ;;
+	*)
+	  func_fatal_help "\`$destdir' must be an absolute directory name"
+	  ;;
+	esac
+      done
+      ;;
+    esac
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    staticlibs=
+    future_libdirs=
+    current_libdirs=
+    for file in $files; do
+
+      # Do each installation.
+      case $file in
+      *.$libext)
+	# Do the static libraries later.
+	func_append staticlibs " $file"
+	;;
+
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$file' is not a valid libtool archive"
+
+	library_names=
+	old_library=
+	relink_command=
+	func_source "$file"
+
+	# Add the libdir to current_libdirs if it is the destination.
+	if test "X$destdir" = "X$libdir"; then
+	  case "$current_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append current_libdirs " $libdir" ;;
+	  esac
+	else
+	  # Note the libdir as a future libdir.
+	  case "$future_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append future_libdirs " $libdir" ;;
+	  esac
+	fi
+
+	func_dirname "$file" "/" ""
+	dir="$func_dirname_result"
+	func_append dir "$objdir"
+
+	if test -n "$relink_command"; then
+	  # Determine the prefix the user has applied to our future dir.
+	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
+
+	  # Don't allow the user to place us outside of our expected
+	  # location b/c this prevents finding dependent libraries that
+	  # are installed to the same prefix.
+	  # At present, this check doesn't affect windows .dll's that
+	  # are installed into $libdir/../bin (currently, that works fine)
+	  # but it's something to keep an eye on.
+	  test "$inst_prefix_dir" = "$destdir" && \
+	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+
+	  if test -n "$inst_prefix_dir"; then
+	    # Stick the inst_prefix_dir data into the link command.
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	  else
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+	  fi
+
+	  func_warning "relinking \`$file'"
+	  func_show_eval "$relink_command" \
+	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+	fi
+
+	# See the names of the shared library.
+	set dummy $library_names; shift
+	if test -n "$1"; then
+	  realname="$1"
+	  shift
+
+	  srcname="$realname"
+	  test -n "$relink_command" && srcname="$realname"T
+
+	  # Install the shared library and build the symlinks.
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
+	      'exit $?'
+	  tstripme="$stripme"
+	  case $host_os in
+	  cygwin* | mingw* | pw32* | cegcc*)
+	    case $realname in
+	    *.dll.a)
+	      tstripme=""
+	      ;;
+	    esac
+	    ;;
+	  esac
+	  if test -n "$tstripme" && test -n "$striplib"; then
+	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
+	  fi
+
+	  if test "$#" -gt 0; then
+	    # Delete the old symlinks, and create new ones.
+	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
+	    # so we also need to try rm && ln -s.
+	    for linkname
+	    do
+	      test "$linkname" != "$realname" \
+		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })"
+	    done
+	  fi
+
+	  # Do each command in the postinstall commands.
+	  lib="$destdir/$realname"
+	  func_execute_cmds "$postinstall_cmds" 'exit $?'
+	fi
+
+	# Install the pseudo-library for information purposes.
+	func_basename "$file"
+	name="$func_basename_result"
+	instname="$dir/$name"i
+	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
+
+	# Maybe install the static library, too.
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
+	;;
+
+      *.lo)
+	# Install (i.e. copy) a libtool object.
+
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# Deduce the name of the destination old-style object file.
+	case $destfile in
+	*.lo)
+	  func_lo2o "$destfile"
+	  staticdest=$func_lo2o_result
+	  ;;
+	*.$objext)
+	  staticdest="$destfile"
+	  destfile=
+	  ;;
+	*)
+	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
+	  ;;
+	esac
+
+	# Install the libtool object if requested.
+	test -n "$destfile" && \
+	  func_show_eval "$install_prog $file $destfile" 'exit $?'
+
+	# Install the old object if enabled.
+	if test "$build_old_libs" = yes; then
+	  # Deduce the name of the old-style object file.
+	  func_lo2o "$file"
+	  staticobj=$func_lo2o_result
+	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
+	fi
+	exit $EXIT_SUCCESS
+	;;
+
+      *)
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# If the file is missing, and there is a .exe on the end, strip it
+	# because it is most likely a libtool script we actually want to
+	# install
+	stripped_ext=""
+	case $file in
+	  *.exe)
+	    if test ! -f "$file"; then
+	      func_stripname '' '.exe' "$file"
+	      file=$func_stripname_result
+	      stripped_ext=".exe"
+	    fi
+	    ;;
+	esac
+
+	# Do a test to see if this is really a libtool program.
+	case $host in
+	*cygwin* | *mingw*)
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      wrapper=$func_ltwrapper_scriptname_result
+	    else
+	      func_stripname '' '.exe' "$file"
+	      wrapper=$func_stripname_result
+	    fi
+	    ;;
+	*)
+	    wrapper=$file
+	    ;;
+	esac
+	if func_ltwrapper_script_p "$wrapper"; then
+	  notinst_deplibs=
+	  relink_command=
+
+	  func_source "$wrapper"
+
+	  # Check the variables that should have been set.
+	  test -z "$generated_by_libtool_version" && \
+	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
+
+	  finalize=yes
+	  for lib in $notinst_deplibs; do
+	    # Check to see that each library is installed.
+	    libdir=
+	    if test -f "$lib"; then
+	      func_source "$lib"
+	    fi
+	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    if test -n "$libdir" && test ! -f "$libfile"; then
+	      func_warning "\`$lib' has not been installed in \`$libdir'"
+	      finalize=no
+	    fi
+	  done
+
+	  relink_command=
+	  func_source "$wrapper"
+
+	  outputname=
+	  if test "$fast_install" = no && test -n "$relink_command"; then
+	    $opt_dry_run || {
+	      if test "$finalize" = yes; then
+	        tmpdir=`func_mktempdir`
+		func_basename "$file$stripped_ext"
+		file="$func_basename_result"
+	        outputname="$tmpdir/$file"
+	        # Replace the output file specification.
+	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
+
+	        $opt_silent || {
+	          func_quote_for_expand "$relink_command"
+		  eval "func_echo $func_quote_for_expand_result"
+	        }
+	        if eval "$relink_command"; then :
+	          else
+		  func_error "error: relink \`$file' with the above command before installing it"
+		  $opt_dry_run || ${RM}r "$tmpdir"
+		  continue
+	        fi
+	        file="$outputname"
+	      else
+	        func_warning "cannot relink \`$file'"
+	      fi
+	    }
+	  else
+	    # Install the binary that we compiled earlier.
+	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
+	  fi
+	fi
+
+	# remove .exe since cygwin /usr/bin/install will append another
+	# one anyway
+	case $install_prog,$host in
+	*/usr/bin/install*,*cygwin*)
+	  case $file:$destfile in
+	  *.exe:*.exe)
+	    # this is ok
+	    ;;
+	  *.exe:*)
+	    destfile=$destfile.exe
+	    ;;
+	  *:*.exe)
+	    func_stripname '' '.exe' "$destfile"
+	    destfile=$func_stripname_result
+	    ;;
+	  esac
+	  ;;
+	esac
+	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
+	$opt_dry_run || if test -n "$outputname"; then
+	  ${RM}r "$tmpdir"
+	fi
+	;;
+      esac
+    done
+
+    for file in $staticlibs; do
+      func_basename "$file"
+      name="$func_basename_result"
+
+      # Set up the ranlib parameters.
+      oldlib="$destdir/$name"
+      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+      tool_oldlib=$func_to_tool_file_result
+
+      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
+
+      if test -n "$stripme" && test -n "$old_striplib"; then
+	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
+      fi
+
+      # Do each command in the postinstall commands.
+      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
+    done
+
+    test -n "$future_libdirs" && \
+      func_warning "remember to run \`$progname --finish$future_libdirs'"
+
+    if test -n "$current_libdirs"; then
+      # Maybe just do a dry run.
+      $opt_dry_run && current_libdirs=" -n$current_libdirs"
+      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+    else
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = install && func_mode_install ${1+"$@"}
+
+
+# func_generate_dlsyms outputname originator pic_p
+# Extract symbols from dlprefiles and create ${outputname}S.o with
+# a dlpreopen symbol table.
+func_generate_dlsyms ()
+{
+    $opt_debug
+    my_outputname="$1"
+    my_originator="$2"
+    my_pic_p="${3-no}"
+    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
+    my_dlsyms=
+
+    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+      if test -n "$NM" && test -n "$global_symbol_pipe"; then
+	my_dlsyms="${my_outputname}S.c"
+      else
+	func_error "not configured to extract global symbols from dlpreopened files"
+      fi
+    fi
+
+    if test -n "$my_dlsyms"; then
+      case $my_dlsyms in
+      "") ;;
+      *.c)
+	# Discover the nlist of each of the dlfiles.
+	nlist="$output_objdir/${my_outputname}.nm"
+
+	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
+
+	# Parse the name list into a source file.
+	func_verbose "creating $output_objdir/$my_dlsyms"
+
+	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
+/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
+/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
+/* External symbol declarations for the compiler. */\
+"
+
+	if test "$dlself" = yes; then
+	  func_verbose "generating symbol list for \`$output'"
+
+	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
+
+	  # Add our own program objects to the symbol list.
+	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	  for progfile in $progfiles; do
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
+	  done
+
+	  if test -n "$exclude_expsyms"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  if test -n "$export_symbols_regex"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  # Prepare the list of exported symbols
+	  if test -z "$export_symbols"; then
+	    export_symbols="$output_objdir/$outputname.exp"
+	    $opt_dry_run || {
+	      $RM $export_symbols
+	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+	      case $host in
+	      *cygwin* | *mingw* | *cegcc* )
+                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+	        ;;
+	      esac
+	    }
+	  else
+	    $opt_dry_run || {
+	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	      case $host in
+	        *cygwin* | *mingw* | *cegcc* )
+	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+	          ;;
+	      esac
+	    }
+	  fi
+	fi
+
+	for dlprefile in $dlprefiles; do
+	  func_verbose "extracting global C symbols from \`$dlprefile'"
+	  func_basename "$dlprefile"
+	  name="$func_basename_result"
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename="$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import library>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
+	done
+
+	$opt_dry_run || {
+	  # Make sure we have at least an empty file.
+	  test -f "$nlist" || : > "$nlist"
+
+	  if test -n "$exclude_expsyms"; then
+	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+	    $MV "$nlist"T "$nlist"
+	  fi
+
+	  # Try sorting and uniquifying the output.
+	  if $GREP -v "^: " < "$nlist" |
+	      if sort -k 3 </dev/null >/dev/null 2>&1; then
+		sort -k 3
+	      else
+		sort +2
+	      fi |
+	      uniq > "$nlist"S; then
+	    :
+	  else
+	    $GREP -v "^: " < "$nlist" > "$nlist"S
+	  fi
+
+	  if test -f "$nlist"S; then
+	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
+	  else
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	  fi
+
+	  echo >> "$output_objdir/$my_dlsyms" "\
+
+/* The mapping between symbol names and symbols.  */
+typedef struct {
+  const char *name;
+  void *address;
+} lt_dlsymlist;
+extern LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[];
+LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[] =
+{\
+  { \"$my_originator\", (void *) 0 },"
+
+	  case $need_lib_prefix in
+	  no)
+	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  *)
+	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  esac
+	  echo >> "$output_objdir/$my_dlsyms" "\
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt_${my_prefix}_LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+	} # !$opt_dry_run
+
+	pic_flag_for_symtable=
+	case "$compile_command " in
+	*" -static "*) ;;
+	*)
+	  case $host in
+	  # compiling the symbol table file with pic_flag works around
+	  # a FreeBSD bug that causes programs to crash when -lm is
+	  # linked before any other PIC object.  But we must not use
+	  # pic_flag when linking with -static.  The problem exists in
+	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
+	  *-*-hpux*)
+	    pic_flag_for_symtable=" $pic_flag"  ;;
+	  *)
+	    if test "X$my_pic_p" != Xno; then
+	      pic_flag_for_symtable=" $pic_flag"
+	    fi
+	    ;;
+	  esac
+	  ;;
+	esac
+	symtab_cflags=
+	for arg in $LTCFLAGS; do
+	  case $arg in
+	  -pie | -fpie | -fPIE) ;;
+	  *) func_append symtab_cflags " $arg" ;;
+	  esac
+	done
+
+	# Now compile the dynamic symbol file.
+	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
+
+	# Clean up the generated files.
+	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'
+
+	# Transform the symbol file into the correct name.
+	symfileobj="$output_objdir/${my_outputname}S.$objext"
+	case $host in
+	*cygwin* | *mingw* | *cegcc* )
+	  if test -f "$output_objdir/$my_outputname.def"; then
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	  else
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  fi
+	  ;;
+	*)
+	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  ;;
+	esac
+	;;
+      *)
+	func_fatal_error "unknown suffix for \`$my_dlsyms'"
+	;;
+      esac
+    else
+      # We keep going just in case the user didn't refer to
+      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
+      # really was required.
+
+      # Nullify the symbol file.
+      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
+    fi
+}
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
+func_win32_libid ()
+{
+  $opt_debug
+  win32_libid_type="unknown"
+  win32_fileres=`file -L $1 2>/dev/null`
+  case $win32_fileres in
+  *ar\ archive\ import\ library*) # definitely import
+    win32_libid_type="x86 archive import"
+    ;;
+  *ar\ archive*) # could be an import, or static
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
+    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
+	$SED -n -e '
+	    1,100{
+		/ I /{
+		    s,.*,import,
+		    p
+		    q
+		}
+	    }'`
+      case $win32_nmres in
+      import*)  win32_libid_type="x86 archive import";;
+      *)        win32_libid_type="x86 archive static";;
+      esac
+    fi
+    ;;
+  *DLL*)
+    win32_libid_type="x86 DLL"
+    ;;
+  *executable*) # but shell scripts are "executable" too...
+    case $win32_fileres in
+    *MS\ Windows\ PE\ Intel*)
+      win32_libid_type="x86 DLL"
+      ;;
+    esac
+    ;;
+  esac
+  $ECHO "$win32_libid_type"
+}
+
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/====MARK====/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^====MARK====/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^====MARK====/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^====MARK====//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=""
+  fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+    $opt_debug
+    f_ex_an_ar_dir="$1"; shift
+    f_ex_an_ar_oldlib="$1"
+    if test "$lock_old_archive_extraction" = yes; then
+      lockfile=$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
+		   'stat=$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" = yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
+    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+     :
+    else
+      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib"
+    fi
+}
+
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+    $opt_debug
+    my_gentop="$1"; shift
+    my_oldlibs=${1+"$@"}
+    my_oldobjs=""
+    my_xlib=""
+    my_xabs=""
+    my_xdir=""
+
+    for my_xlib in $my_oldlibs; do
+      # Extract the objects.
+      case $my_xlib in
+	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+	*) my_xabs=`pwd`"/$my_xlib" ;;
+      esac
+      func_basename "$my_xlib"
+      my_xlib="$func_basename_result"
+      my_xlib_u=$my_xlib
+      while :; do
+        case " $extracted_archives " in
+	*" $my_xlib_u "*)
+	  func_arith $extracted_serial + 1
+	  extracted_serial=$func_arith_result
+	  my_xlib_u=lt$extracted_serial-$my_xlib ;;
+	*) break ;;
+	esac
+      done
+      extracted_archives="$extracted_archives $my_xlib_u"
+      my_xdir="$my_gentop/$my_xlib_u"
+
+      func_mkdir_p "$my_xdir"
+
+      case $host in
+      *-darwin*)
+	func_verbose "Extracting $my_xabs"
+	# Do not bother doing anything if just a dry run
+	$opt_dry_run || {
+	  darwin_orig_dir=`pwd`
+	  cd $my_xdir || exit $?
+	  darwin_archive=$my_xabs
+	  darwin_curdir=`pwd`
+	  darwin_base_archive=`basename "$darwin_archive"`
+	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
+	  if test -n "$darwin_arches"; then
+	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
+	    darwin_arch=
+	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
+	    for darwin_arch in  $darwin_arches ; do
+	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+	      cd "$darwin_curdir"
+	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+	    done # $darwin_arches
+            ## Okay now we've a bunch of thin objects, gotta fatten them up :)
+	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
+	    darwin_file=
+	    darwin_files=
+	    for darwin_file in $darwin_filelist; do
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
+	      $LIPO -create -output "$darwin_file" $darwin_files
+	    done # $darwin_filelist
+	    $RM -rf unfat-$$
+	    cd "$darwin_orig_dir"
+	  else
+	    cd $darwin_orig_dir
+	    func_extract_an_archive "$my_xdir" "$my_xabs"
+	  fi # $darwin_arches
+	} # !$opt_dry_run
+	;;
+      *)
+        func_extract_an_archive "$my_xdir" "$my_xabs"
+	;;
+      esac
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
+    done
+
+    func_extract_archives_result="$my_oldobjs"
+}
+
+
+# func_emit_wrapper [arg=no]
+#
+# Emit a libtool wrapper script on stdout.
+# Don't directly open a file because we may want to
+# incorporate the script contents within a cygwin/mingw
+# wrapper executable.  Must ONLY be called from within
+# func_mode_link because it depends on a number of variables
+# set therein.
+#
+# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
+# variable will take.  If 'yes', then the emitted script
+# will assume that the directory in which it is stored is
+# the $objdir directory.  This is a cygwin/mingw-specific
+# behavior.
+func_emit_wrapper ()
+{
+	func_emit_wrapper_arg1=${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    file=\"\$0\""
+
+    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=
+func_parse_lt_options ()
+{
+  lt_script_arg0=\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=1 ;;
+    --lt-dump-script)
+        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
+        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
+      ;;
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
+      ;;
+    esac
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+  fi
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+    ;;
+
+  *)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+    ;;
+  esac
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  case \" \$* \" in
+  *\\ --lt-*)
+    for lt_wr_arg
+    do
+      case \$lt_wr_arg in
+      --lt-*) ;;
+      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+      esac
+      shift
+    done ;;
+  esac
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
+    esac
+  fi
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
+  fi
+fi\
+"
+}
+
+
+# func_emit_cwrapperexe_src
+# emit the source code for a wrapper executable on stdout
+# Must ONLY be called from within func_mode_link because
+# it depends on a number of variable set therein.
+func_emit_cwrapperexe_src ()
+{
+	cat <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+
+   The $output program cannot be directly executed until all the libtool
+   libraries that it depends on are installed.
+
+   This wrapper executable should never be moved out of the build directory.
+   If it is, it will not operate correctly.
+*/
+EOF
+	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _MSC_VER
+# include <direct.h>
+# include <process.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <stdint.h>
+# ifdef __CYGWIN__
+#  include <io.h>
+# endif
+#endif
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef S_IXOTH
+# define S_IXOTH 0
+#endif
+#ifndef S_IXGRP
+# define S_IXGRP 0
+#endif
+
+/* path handling portability macros */
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+  defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# define FOPEN_WB "wb"
+# ifndef DIR_SEPARATOR_2
+#  define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+#  define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#ifndef FOPEN_WB
+# define FOPEN_WB "w"
+#endif
+#ifndef _O_BINARY
+# define _O_BINARY 0
+#endif
+
+#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+  if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug = 1;
+#else
+static int lt_debug = 0;
+#endif
+
+const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
+
+void *xmalloc (size_t num);
+char *xstrdup (const char *string);
+const char *base_name (const char *name);
+char *find_executable (const char *wrapper);
+char *chase_symlinks (const char *pathspec);
+int make_executable (const char *path);
+int check_executable (const char *path);
+char *strendzap (char *str, const char *pat);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
+void lt_setenv (const char *name, const char *value);
+char *lt_extend_str (const char *orig_value, const char *add, int to_end);
+void lt_update_exe_path (const char *name, const char *value);
+void lt_update_lib_path (const char *name, const char *value);
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
+EOF
+
+	    cat <<EOF
+volatile const char * MAGIC_EXE = "$magic_exe";
+const char * LIB_PATH_VARNAME = "$shlibpath_var";
+EOF
+
+	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+              func_to_host_path "$temp_rpath"
+	      cat <<EOF
+const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * LIB_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test -n "$dllsearchpath"; then
+              func_to_host_path "$dllsearchpath:"
+	      cat <<EOF
+const char * EXE_PATH_VARNAME = "PATH";
+const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * EXE_PATH_VARNAME = "";
+const char * EXE_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test "$fast_install" = yes; then
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
+EOF
+	    else
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */
+EOF
+	    fi
+
+
+	    cat <<"EOF"
+
+#define LTWRAPPER_OPTION_PREFIX         "--lt-"
+
+static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
+static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
+static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
+
+int
+main (int argc, char *argv[])
+{
+  char **newargz;
+  int  newargc;
+  char *tmp_pathspec;
+  char *actual_cwrapper_path;
+  char *actual_cwrapper_name;
+  char *target_name;
+  char *lt_argv_zero;
+  intptr_t rval = 127;
+
+  int i;
+
+  program_name = (char *) xstrdup (base_name (argv[0]));
+  newargz = XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=0;
+  for (i = 1; i < argc; i++)
+    {
+      if (strcmp (argv[i], dumpscript_opt) == 0)
+	{
+EOF
+	    case "$host" in
+	      *mingw* | *cygwin* )
+		# make stdout use "unix" line endings
+		echo "          setmode(1,_O_BINARY);"
+		;;
+	      esac
+
+	    cat <<"EOF"
+	  lt_dump_script (stdout);
+	  return 0;
+	}
+      if (strcmp (argv[i], debug_opt) == 0)
+	{
+          lt_debug = 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
+    }
+  newargz[++newargc] = NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
+
+  tmp_pathspec = find_executable (argv[0]);
+  if (tmp_pathspec == NULL)
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
+
+  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
+  XFREE (tmp_pathspec);
+
+  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
+  strendzap (actual_cwrapper_path, actual_cwrapper_name);
+
+  /* wrapper name transforms */
+  strendzap (actual_cwrapper_name, ".exe");
+  tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1);
+  XFREE (actual_cwrapper_name);
+  actual_cwrapper_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  /* target_name transforms -- use actual target program name; might have lt- prefix */
+  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));
+  strendzap (target_name, ".exe");
+  tmp_pathspec = lt_extend_str (target_name, ".exe", 1);
+  XFREE (target_name);
+  target_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
+EOF
+
+	    cat <<EOF
+  newargz[0] =
+    XMALLOC (char, (strlen (actual_cwrapper_path) +
+		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
+  strcpy (newargz[0], actual_cwrapper_path);
+  strcat (newargz[0], "$objdir");
+  strcat (newargz[0], "/");
+EOF
+
+	    cat <<"EOF"
+  /* stop here, and copy so we don't have to do this twice */
+  tmp_pathspec = xstrdup (newargz[0]);
+
+  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
+  strcat (newargz[0], actual_cwrapper_name);
+
+  /* DO want the lt- prefix here if it exists, so use target_name */
+  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);
+  XFREE (tmp_pathspec);
+  tmp_pathspec = NULL;
+EOF
+
+	    case $host_os in
+	      mingw*)
+	    cat <<"EOF"
+  {
+    char* p;
+    while ((p = strchr (newargz[0], '\\')) != NULL)
+      {
+	*p = '/';
+      }
+    while ((p = strchr (lt_argv_zero, '\\')) != NULL)
+      {
+	*p = '/';
+      }
+  }
+EOF
+	    ;;
+	    esac
+
+	    cat <<"EOF"
+  XFREE (target_name);
+  XFREE (actual_cwrapper_path);
+  XFREE (actual_cwrapper_name);
+
+  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
+  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
+  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
+  for (i = 0; i < newargc; i++)
+    {
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
+    }
+
+EOF
+
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+  /* execv doesn't actually work on mingw as expected on unix */
+  newargz = prepare_spawn (newargz);
+  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  if (rval == -1)
+    {
+      /* failed to start process */
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
+      return 127;
+    }
+  return rval;
+EOF
+		;;
+	      *)
+		cat <<"EOF"
+  execv (lt_argv_zero, newargz);
+  return rval; /* =127, but avoids unused variable warning */
+EOF
+		;;
+	    esac
+
+	    cat <<"EOF"
+}
+
+void *
+xmalloc (size_t num)
+{
+  void *p = (void *) malloc (num);
+  if (!p)
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
+
+  return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
+			  string) : NULL;
+}
+
+const char *
+base_name (const char *name)
+{
+  const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  /* Skip over the disk name in MSDOS pathnames. */
+  if (isalpha ((unsigned char) name[0]) && name[1] == ':')
+    name += 2;
+#endif
+
+  for (base = name; *name; name++)
+    if (IS_DIR_SEPARATOR (*name))
+      base = name + 1;
+  return base;
+}
+
+int
+check_executable (const char *path)
+{
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if ((stat (path, &st) >= 0)
+      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
+    return 1;
+  else
+    return 0;
+}
+
+int
+make_executable (const char *path)
+{
+  int rval = 0;
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if (stat (path, &st) >= 0)
+    {
+      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
+    }
+  return rval;
+}
+
+/* Searches for the full path of the wrapper.  Returns
+   newly allocated full path name if found, NULL otherwise
+   Does not chase symlinks, even on platforms that support them.
+*/
+char *
+find_executable (const char *wrapper)
+{
+  int has_slash = 0;
+  const char *p;
+  const char *p_next;
+  /* static buffer for getcwd */
+  char tmp[LT_PATHMAX + 1];
+  int tmp_len;
+  char *concat_name;
+
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
+
+  if ((wrapper == NULL) || (*wrapper == '\0'))
+    return NULL;
+
+  /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
+    {
+      concat_name = xstrdup (wrapper);
+      if (check_executable (concat_name))
+	return concat_name;
+      XFREE (concat_name);
+    }
+  else
+    {
+#endif
+      if (IS_DIR_SEPARATOR (wrapper[0]))
+	{
+	  concat_name = xstrdup (wrapper);
+	  if (check_executable (concat_name))
+	    return concat_name;
+	  XFREE (concat_name);
+	}
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+    }
+#endif
+
+  for (p = wrapper; *p; p++)
+    if (*p == '/')
+      {
+	has_slash = 1;
+	break;
+      }
+  if (!has_slash)
+    {
+      /* no slashes; search PATH */
+      const char *path = getenv ("PATH");
+      if (path != NULL)
+	{
+	  for (p = path; *p; p = p_next)
+	    {
+	      const char *q;
+	      size_t p_len;
+	      for (q = p; *q; q++)
+		if (IS_PATH_SEPARATOR (*q))
+		  break;
+	      p_len = q - p;
+	      p_next = (*q == '\0' ? q : q + 1);
+	      if (p_len == 0)
+		{
+		  /* empty path: current directory */
+		  if (getcwd (tmp, LT_PATHMAX) == NULL)
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
+		  tmp_len = strlen (tmp);
+		  concat_name =
+		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, tmp, tmp_len);
+		  concat_name[tmp_len] = '/';
+		  strcpy (concat_name + tmp_len + 1, wrapper);
+		}
+	      else
+		{
+		  concat_name =
+		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, p, p_len);
+		  concat_name[p_len] = '/';
+		  strcpy (concat_name + p_len + 1, wrapper);
+		}
+	      if (check_executable (concat_name))
+		return concat_name;
+	      XFREE (concat_name);
+	    }
+	}
+      /* not found in PATH; assume curdir */
+    }
+  /* Relative path | not found in path: prepend cwd */
+  if (getcwd (tmp, LT_PATHMAX) == NULL)
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
+  tmp_len = strlen (tmp);
+  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+  memcpy (concat_name, tmp, tmp_len);
+  concat_name[tmp_len] = '/';
+  strcpy (concat_name + tmp_len + 1, wrapper);
+
+  if (check_executable (concat_name))
+    return concat_name;
+  XFREE (concat_name);
+  return NULL;
+}
+
+char *
+chase_symlinks (const char *pathspec)
+{
+#ifndef S_ISLNK
+  return xstrdup (pathspec);
+#else
+  char buf[LT_PATHMAX];
+  struct stat s;
+  char *tmp_pathspec = xstrdup (pathspec);
+  char *p;
+  int has_symlinks = 0;
+  while (strlen (tmp_pathspec) && !has_symlinks)
+    {
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
+      if (lstat (tmp_pathspec, &s) == 0)
+	{
+	  if (S_ISLNK (s.st_mode) != 0)
+	    {
+	      has_symlinks = 1;
+	      break;
+	    }
+
+	  /* search backwards for last DIR_SEPARATOR */
+	  p = tmp_pathspec + strlen (tmp_pathspec) - 1;
+	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    p--;
+	  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    {
+	      /* no more DIR_SEPARATORS left */
+	      break;
+	    }
+	  *p = '\0';
+	}
+      else
+	{
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
+	}
+    }
+  XFREE (tmp_pathspec);
+
+  if (!has_symlinks)
+    {
+      return xstrdup (pathspec);
+    }
+
+  tmp_pathspec = realpath (pathspec, buf);
+  if (tmp_pathspec == 0)
+    {
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
+    }
+  return xstrdup (tmp_pathspec);
+#endif
+}
+
+char *
+strendzap (char *str, const char *pat)
+{
+  size_t len, patlen;
+
+  assert (str != NULL);
+  assert (pat != NULL);
+
+  len = strlen (str);
+  patlen = strlen (pat);
+
+  if (patlen <= len)
+    {
+      str += len - patlen;
+      if (strcmp (str, pat) == 0)
+	*str = '\0';
+    }
+  return str;
+}
+
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
+static void
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
+	       const char *message, va_list ap)
+{
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
+  vfprintf (stderr, message, ap);
+  fprintf (stderr, ".\n");
+
+  if (exit_status >= 0)
+    exit (exit_status);
+}
+
+void
+lt_fatal (const char *file, int line, const char *message, ...)
+{
+  va_list ap;
+  va_start (ap, message);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
+  va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
+}
+
+void
+lt_setenv (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
+  {
+#ifdef HAVE_SETENV
+    /* always make a copy, for consistency with !HAVE_SETENV */
+    char *str = xstrdup (value);
+    setenv (name, str, 1);
+#else
+    int len = strlen (name) + 1 + strlen (value) + 1;
+    char *str = XMALLOC (char, len);
+    sprintf (str, "%s=%s", name, value);
+    if (putenv (str) != EXIT_SUCCESS)
+      {
+        XFREE (str);
+      }
+#endif
+  }
+}
+
+char *
+lt_extend_str (const char *orig_value, const char *add, int to_end)
+{
+  char *new_value;
+  if (orig_value && *orig_value)
+    {
+      int orig_value_len = strlen (orig_value);
+      int add_len = strlen (add);
+      new_value = XMALLOC (char, add_len + orig_value_len + 1);
+      if (to_end)
+        {
+          strcpy (new_value, orig_value);
+          strcpy (new_value + orig_value_len, add);
+        }
+      else
+        {
+          strcpy (new_value, add);
+          strcpy (new_value + add_len, orig_value);
+        }
+    }
+  else
+    {
+      new_value = xstrdup (add);
+    }
+  return new_value;
+}
+
+void
+lt_update_exe_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      /* some systems can't cope with a ':'-terminated path #' */
+      int len = strlen (new_value);
+      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
+        {
+          new_value[len-1] = '\0';
+        }
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+void
+lt_update_lib_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and calls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >= 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc = 0; argv[argc] != NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv = XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i = 0; i < argc; i++)
+    {
+      const char *string = argv[i];
+
+      if (string[0] == '\0')
+	new_argv[i] = xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
+	{
+	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length = 0;
+	  backslashes = 0;
+	  if (quote_around)
+	    length++;
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		length += backslashes + 1;
+	      length++;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    length += backslashes + 1;
+
+	  quoted_string = XMALLOC (char, length + 1);
+
+	  p = quoted_string;
+	  backslashes = 0;
+	  if (quote_around)
+	    *p++ = '"';
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		{
+		  unsigned int j;
+		  for (j = backslashes + 1; j > 0; j--)
+		    *p++ = '\\';
+		}
+	      *p++ = c;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j = backslashes; j > 0; j--)
+		*p++ = '\\';
+	      *p++ = '"';
+	    }
+	  *p = '\0';
+
+	  new_argv[i] = quoted_string;
+	}
+      else
+	new_argv[i] = (char *) string;
+    }
+  new_argv[argc] = NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+	      $SED -n -e '
+s/^\(.\{79\}\)\(..*\)/\1\
+\2/
+h
+s/\([\\"]\)/\\\1/g
+s/$/\\n/
+s/\([^\n]*\).*/  fputs ("\1", f);/p
+g
+D'
+            cat <<"EOF"
+}
+EOF
+}
+# end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
+    esac
+}
+
+# func_mode_link arg...
+func_mode_link ()
+{
+    $opt_debug
+    case $host in
+    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+      # It is impossible to link a dll without this setting, and
+      # we shouldn't force the makefile maintainer to figure out
+      # which system we are compiling for in order to pass an extra
+      # flag for every libtool invocation.
+      # allow_undefined=no
+
+      # FIXME: Unfortunately, there are problems with the above when trying
+      # to make a dll which has undefined symbols, in which case not
+      # even a static library is built.  For now, we need to specify
+      # -no-undefined on the libtool link line when we can be certain
+      # that all symbols are satisfied, otherwise we get a static library.
+      allow_undefined=yes
+      ;;
+    *)
+      allow_undefined=yes
+      ;;
+    esac
+    libtool_args=$nonopt
+    base_compile="$nonopt $@"
+    compile_command=$nonopt
+    finalize_command=$nonopt
+
+    compile_rpath=
+    finalize_rpath=
+    compile_shlibpath=
+    finalize_shlibpath=
+    convenience=
+    old_convenience=
+    deplibs=
+    old_deplibs=
+    compiler_flags=
+    linker_flags=
+    dllsearchpath=
+    lib_search_path=`pwd`
+    inst_prefix_dir=
+    new_inherited_linker_flags=
+
+    avoid_version=no
+    bindir=
+    dlfiles=
+    dlprefiles=
+    dlself=no
+    export_dynamic=no
+    export_symbols=
+    export_symbols_regex=
+    generated=
+    libobjs=
+    ltlibs=
+    module=no
+    no_install=no
+    objs=
+    non_pic_objects=
+    precious_files_regex=
+    prefer_static_libs=no
+    preload=no
+    prev=
+    prevarg=
+    release=
+    rpath=
+    xrpath=
+    perm_rpath=
+    temp_rpath=
+    thread_safe=no
+    vinfo=
+    vinfo_number=no
+    weak_libs=
+    single_module="${wl}-single_module"
+    func_infer_tag $base_compile
+
+    # We need to know -static, to get the right output filenames.
+    for arg
+    do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	break
+	;;
+      -all-static | -static | -static-libtool-libs)
+	case $arg in
+	-all-static)
+	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+	    func_warning "complete static linking is impossible in this configuration"
+	  fi
+	  if test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	-static)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=built
+	  ;;
+	-static-libtool-libs)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	esac
+	build_libtool_libs=no
+	build_old_libs=yes
+	break
+	;;
+      esac
+    done
+
+    # See if our shared archives depend on static archives.
+    test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+    # Go through the arguments, transforming them on the way.
+    while test "$#" -gt 0; do
+      arg="$1"
+      shift
+      func_quote_for_eval "$arg"
+      qarg=$func_quote_for_eval_unquoted_result
+      func_append libtool_args " $func_quote_for_eval_result"
+
+      # If the previous option needs an argument, assign it.
+      if test -n "$prev"; then
+	case $prev in
+	output)
+	  func_append compile_command " @OUTPUT@"
+	  func_append finalize_command " @OUTPUT@"
+	  ;;
+	esac
+
+	case $prev in
+	bindir)
+	  bindir="$arg"
+	  prev=
+	  continue
+	  ;;
+	dlfiles|dlprefiles)
+	  if test "$preload" = no; then
+	    # Add the symbol object into the linking commands.
+	    func_append compile_command " @SYMFILE@"
+	    func_append finalize_command " @SYMFILE@"
+	    preload=yes
+	  fi
+	  case $arg in
+	  *.la | *.lo) ;;  # We handle these cases below.
+	  force)
+	    if test "$dlself" = no; then
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  self)
+	    if test "$prev" = dlprefiles; then
+	      dlself=yes
+	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+	      dlself=yes
+	    else
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  *)
+	    if test "$prev" = dlfiles; then
+	      func_append dlfiles " $arg"
+	    else
+	      func_append dlprefiles " $arg"
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  esac
+	  ;;
+	expsyms)
+	  export_symbols="$arg"
+	  test -f "$arg" \
+	    || func_fatal_error "symbol file \`$arg' does not exist"
+	  prev=
+	  continue
+	  ;;
+	expsyms_regex)
+	  export_symbols_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	framework)
+	  case $host in
+	    *-*-darwin*)
+	      case "$deplibs " in
+		*" $qarg.ltframework "*) ;;
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
+		   ;;
+	      esac
+	      ;;
+	  esac
+	  prev=
+	  continue
+	  ;;
+	inst_prefix)
+	  inst_prefix_dir="$arg"
+	  prev=
+	  continue
+	  ;;
+	objectlist)
+	  if test -f "$arg"; then
+	    save_arg=$arg
+	    moreargs=
+	    for fil in `cat "$save_arg"`
+	    do
+#	      func_append moreargs " $fil"
+	      arg=$fil
+	      # A libtool-controlled object.
+
+	      # Check to see that this really is a libtool object.
+	      if func_lalib_unsafe_p "$arg"; then
+		pic_object=
+		non_pic_object=
+
+		# Read the .lo file
+		func_source "$arg"
+
+		if test -z "$pic_object" ||
+		   test -z "$non_pic_object" ||
+		   test "$pic_object" = none &&
+		   test "$non_pic_object" = none; then
+		  func_fatal_error "cannot find name of object for \`$arg'"
+		fi
+
+		# Extract subdirectory from the argument.
+		func_dirname "$arg" "/" ""
+		xdir="$func_dirname_result"
+
+		if test "$pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  pic_object="$xdir$pic_object"
+
+		  if test "$prev" = dlfiles; then
+		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		      func_append dlfiles " $pic_object"
+		      prev=
+		      continue
+		    else
+		      # If libtool objects are unsupported, then we need to preload.
+		      prev=dlprefiles
+		    fi
+		  fi
+
+		  # CHECK ME:  I think I busted this.  -Ossama
+		  if test "$prev" = dlprefiles; then
+		    # Preload the old-style object.
+		    func_append dlprefiles " $pic_object"
+		    prev=
+		  fi
+
+		  # A PIC object.
+		  func_append libobjs " $pic_object"
+		  arg="$pic_object"
+		fi
+
+		# Non-PIC object.
+		if test "$non_pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  non_pic_object="$xdir$non_pic_object"
+
+		  # A standard non-PIC object
+		  func_append non_pic_objects " $non_pic_object"
+		  if test -z "$pic_object" || test "$pic_object" = none ; then
+		    arg="$non_pic_object"
+		  fi
+		else
+		  # If the PIC object exists, use it instead.
+		  # $xdir was prepended to $pic_object above.
+		  non_pic_object="$pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+		fi
+	      else
+		# Only an error if not doing a dry-run.
+		if $opt_dry_run; then
+		  # Extract subdirectory from the argument.
+		  func_dirname "$arg" "/" ""
+		  xdir="$func_dirname_result"
+
+		  func_lo2o "$arg"
+		  pic_object=$xdir$objdir/$func_lo2o_result
+		  non_pic_object=$xdir$func_lo2o_result
+		  func_append libobjs " $pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+	        else
+		  func_fatal_error "\`$arg' is not a valid libtool object"
+		fi
+	      fi
+	    done
+	  else
+	    func_fatal_error "link input file \`$arg' does not exist"
+	  fi
+	  arg=$save_arg
+	  prev=
+	  continue
+	  ;;
+	precious_regex)
+	  precious_files_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	release)
+	  release="-$arg"
+	  prev=
+	  continue
+	  ;;
+	rpath | xrpath)
+	  # We need an absolute path.
+	  case $arg in
+	  [\\/]* | [A-Za-z]:[\\/]*) ;;
+	  *)
+	    func_fatal_error "only absolute run-paths are allowed"
+	    ;;
+	  esac
+	  if test "$prev" = rpath; then
+	    case "$rpath " in
+	    *" $arg "*) ;;
+	    *) func_append rpath " $arg" ;;
+	    esac
+	  else
+	    case "$xrpath " in
+	    *" $arg "*) ;;
+	    *) func_append xrpath " $arg" ;;
+	    esac
+	  fi
+	  prev=
+	  continue
+	  ;;
+	shrext)
+	  shrext_cmds="$arg"
+	  prev=
+	  continue
+	  ;;
+	weak)
+	  func_append weak_libs " $arg"
+	  prev=
+	  continue
+	  ;;
+	xcclinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xcompiler)
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xlinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
+	  prev=
+	  func_append compile_command " $wl$qarg"
+	  func_append finalize_command " $wl$qarg"
+	  continue
+	  ;;
+	*)
+	  eval "$prev=\"\$arg\""
+	  prev=
+	  continue
+	  ;;
+	esac
+      fi # test -n "$prev"
+
+      prevarg="$arg"
+
+      case $arg in
+      -all-static)
+	if test -n "$link_static_flag"; then
+	  # See comment for -static flag below, for more details.
+	  func_append compile_command " $link_static_flag"
+	  func_append finalize_command " $link_static_flag"
+	fi
+	continue
+	;;
+
+      -allow-undefined)
+	# FIXME: remove this flag sometime in the future.
+	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
+	;;
+
+      -avoid-version)
+	avoid_version=yes
+	continue
+	;;
+
+      -bindir)
+	prev=bindir
+	continue
+	;;
+
+      -dlopen)
+	prev=dlfiles
+	continue
+	;;
+
+      -dlpreopen)
+	prev=dlprefiles
+	continue
+	;;
+
+      -export-dynamic)
+	export_dynamic=yes
+	continue
+	;;
+
+      -export-symbols | -export-symbols-regex)
+	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+	  func_fatal_error "more than one -exported-symbols argument is not allowed"
+	fi
+	if test "X$arg" = "X-export-symbols"; then
+	  prev=expsyms
+	else
+	  prev=expsyms_regex
+	fi
+	continue
+	;;
+
+      -framework)
+	prev=framework
+	continue
+	;;
+
+      -inst-prefix-dir)
+	prev=inst_prefix
+	continue
+	;;
+
+      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+      # so, if we see these flags be careful not to treat them like -L
+      -L[A-Z][A-Z]*:*)
+	case $with_gcc/$host in
+	no/*-*-irix* | /*-*-irix*)
+	  func_append compile_command " $arg"
+	  func_append finalize_command " $arg"
+	  ;;
+	esac
+	continue
+	;;
+
+      -L*)
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
+	  if test "$#" -gt 0; then
+	    func_fatal_error "require no space between \`-L' and \`$1'"
+	  else
+	    func_fatal_error "need path for \`-L' option"
+	  fi
+	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=$func_resolve_sysroot_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	*)
+	  absdir=`cd "$dir" && pwd`
+	  test -z "$absdir" && \
+	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
+	  dir="$absdir"
+	  ;;
+	esac
+	case "$deplibs " in
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
+	*)
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
+	  ;;
+	esac
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$dir:"*) ;;
+	  ::) dllsearchpath=$dir;;
+	  *) func_append dllsearchpath ":$dir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+	continue
+	;;
+
+      -l*)
+	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # These systems don't actually have a C or math library (as such)
+	    continue
+	    ;;
+	  *-*-os2*)
+	    # These systems don't actually have a C library (as such)
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C and math libraries are in the System framework
+	    func_append deplibs " System.ltframework"
+	    continue
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  esac
+	elif test "X$arg" = "X-lc_r"; then
+	 case $host in
+	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	   # Do not include libc_r directly, use -pthread flag.
+	   continue
+	   ;;
+	 esac
+	fi
+	func_append deplibs " $arg"
+	continue
+	;;
+
+      -module)
+	module=yes
+	continue
+	;;
+
+      # Tru64 UNIX uses -model [arg] to determine the layout of C++
+      # classes, name mangling, and exception handling.
+      # Darwin uses the -arch flag to determine output architecture.
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	prev=xcompiler
+	continue
+	;;
+
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	case "$new_inherited_linker_flags " in
+	    *" $arg "*) ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
+	esac
+	continue
+	;;
+
+      -multi_module)
+	single_module="${wl}-multi_module"
+	continue
+	;;
+
+      -no-fast-install)
+	fast_install=no
+	continue
+	;;
+
+      -no-install)
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
+	  # The PATH hackery in wrapper scripts is required on Windows
+	  # and Darwin in order for the loader to find any dlls it needs.
+	  func_warning "\`-no-install' is ignored for $host"
+	  func_warning "assuming \`-no-fast-install' instead"
+	  fast_install=no
+	  ;;
+	*) no_install=yes ;;
+	esac
+	continue
+	;;
+
+      -no-undefined)
+	allow_undefined=no
+	continue
+	;;
+
+      -objectlist)
+	prev=objectlist
+	continue
+	;;
+
+      -o) prev=output ;;
+
+      -precious-files-regex)
+	prev=precious_regex
+	continue
+	;;
+
+      -release)
+	prev=release
+	continue
+	;;
+
+      -rpath)
+	prev=rpath
+	continue
+	;;
+
+      -R)
+	prev=xrpath
+	continue
+	;;
+
+      -R*)
+	func_stripname '-R' '' "$arg"
+	dir=$func_stripname_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=*)
+	  func_stripname '=' '' "$dir"
+	  dir=$lt_sysroot$func_stripname_result
+	  ;;
+	*)
+	  func_fatal_error "only absolute run-paths are allowed"
+	  ;;
+	esac
+	case "$xrpath " in
+	*" $dir "*) ;;
+	*) func_append xrpath " $dir" ;;
+	esac
+	continue
+	;;
+
+      -shared)
+	# The effects of -shared are defined in a previous loop.
+	continue
+	;;
+
+      -shrext)
+	prev=shrext
+	continue
+	;;
+
+      -static | -static-libtool-libs)
+	# The effects of -static are defined in a previous loop.
+	# We used to do the same as -all-static on platforms that
+	# didn't have a PIC flag, but the assumption that the effects
+	# would be equivalent was wrong.  It would break on at least
+	# Digital Unix and AIX.
+	continue
+	;;
+
+      -thread-safe)
+	thread_safe=yes
+	continue
+	;;
+
+      -version-info)
+	prev=vinfo
+	continue
+	;;
+
+      -version-number)
+	prev=vinfo
+	vinfo_number=yes
+	continue
+	;;
+
+      -weak)
+        prev=weak
+	continue
+	;;
+
+      -Wc,*)
+	func_stripname '-Wc,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Wl,*)
+	func_stripname '-Wl,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Xcompiler)
+	prev=xcompiler
+	continue
+	;;
+
+      -Xlinker)
+	prev=xlinker
+	continue
+	;;
+
+      -XCClinker)
+	prev=xcclinker
+	continue
+	;;
+
+      # -msg_* for osf cc
+      -msg_*)
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=*                Portland pgcc target processor selection
+      # --sysroot=*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+        func_append compile_command " $arg"
+        func_append finalize_command " $arg"
+        func_append compiler_flags " $arg"
+        continue
+        ;;
+
+      # Some other compiler flag.
+      -* | +*)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      *.$objext)
+	# A standard object.
+	func_append objs " $arg"
+	;;
+
+      *.lo)
+	# A libtool-controlled object.
+
+	# Check to see that this really is a libtool object.
+	if func_lalib_unsafe_p "$arg"; then
+	  pic_object=
+	  non_pic_object=
+
+	  # Read the .lo file
+	  func_source "$arg"
+
+	  if test -z "$pic_object" ||
+	     test -z "$non_pic_object" ||
+	     test "$pic_object" = none &&
+	     test "$non_pic_object" = none; then
+	    func_fatal_error "cannot find name of object for \`$arg'"
+	  fi
+
+	  # Extract subdirectory from the argument.
+	  func_dirname "$arg" "/" ""
+	  xdir="$func_dirname_result"
+
+	  if test "$pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    pic_object="$xdir$pic_object"
+
+	    if test "$prev" = dlfiles; then
+	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		func_append dlfiles " $pic_object"
+		prev=
+		continue
+	      else
+		# If libtool objects are unsupported, then we need to preload.
+		prev=dlprefiles
+	      fi
+	    fi
+
+	    # CHECK ME:  I think I busted this.  -Ossama
+	    if test "$prev" = dlprefiles; then
+	      # Preload the old-style object.
+	      func_append dlprefiles " $pic_object"
+	      prev=
+	    fi
+
+	    # A PIC object.
+	    func_append libobjs " $pic_object"
+	    arg="$pic_object"
+	  fi
+
+	  # Non-PIC object.
+	  if test "$non_pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    non_pic_object="$xdir$non_pic_object"
+
+	    # A standard non-PIC object
+	    func_append non_pic_objects " $non_pic_object"
+	    if test -z "$pic_object" || test "$pic_object" = none ; then
+	      arg="$non_pic_object"
+	    fi
+	  else
+	    # If the PIC object exists, use it instead.
+	    # $xdir was prepended to $pic_object above.
+	    non_pic_object="$pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  fi
+	else
+	  # Only an error if not doing a dry-run.
+	  if $opt_dry_run; then
+	    # Extract subdirectory from the argument.
+	    func_dirname "$arg" "/" ""
+	    xdir="$func_dirname_result"
+
+	    func_lo2o "$arg"
+	    pic_object=$xdir$objdir/$func_lo2o_result
+	    non_pic_object=$xdir$func_lo2o_result
+	    func_append libobjs " $pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  else
+	    func_fatal_error "\`$arg' is not a valid libtool object"
+	  fi
+	fi
+	;;
+
+      *.$libext)
+	# An archive.
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
+	continue
+	;;
+
+      *.la)
+	# A libtool-controlled library.
+
+	func_resolve_sysroot "$arg"
+	if test "$prev" = dlfiles; then
+	  # This library was specified with -dlopen.
+	  func_append dlfiles " $func_resolve_sysroot_result"
+	  prev=
+	elif test "$prev" = dlprefiles; then
+	  # The library was specified with -dlpreopen.
+	  func_append dlprefiles " $func_resolve_sysroot_result"
+	  prev=
+	else
+	  func_append deplibs " $func_resolve_sysroot_result"
+	fi
+	continue
+	;;
+
+      # Some other compiler argument.
+      *)
+	# Unknown arguments in both finalize_command and compile_command need
+	# to be aesthetically quoted because they are evaled later.
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+      esac # arg
+
+      # Now actually substitute the argument into the commands.
+      if test -n "$arg"; then
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+      fi
+    done # argument parsing loop
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prevarg' option requires an argument"
+
+    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+      eval arg=\"$export_dynamic_flag_spec\"
+      func_append compile_command " $arg"
+      func_append finalize_command " $arg"
+    fi
+
+    oldlibs=
+    # calculate the name of the file, without its directory
+    func_basename "$output"
+    outputname="$func_basename_result"
+    libobjs_save="$libobjs"
+
+    if test -n "$shlibpath_var"; then
+      # get the directories listed in $shlibpath_var
+      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
+    else
+      shlib_search_path=
+    fi
+    eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+    eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+    func_dirname "$output" "/" ""
+    output_objdir="$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=$func_to_tool_file_result
+    # Create the object directory.
+    func_mkdir_p "$output_objdir"
+
+    # Determine the type of output
+    case $output in
+    "")
+      func_fatal_help "you must specify an output file"
+      ;;
+    *.$libext) linkmode=oldlib ;;
+    *.lo | *.$objext) linkmode=obj ;;
+    *.la) linkmode=lib ;;
+    *) linkmode=prog ;; # Anything else should be a program.
+    esac
+
+    specialdeplibs=
+
+    libs=
+    # Find all interdependent deplibs by searching for libraries
+    # that are linked more than once (e.g. -la -lb -la)
+    for deplib in $deplibs; do
+      if $opt_preserve_dup_deps ; then
+	case "$libs " in
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	esac
+      fi
+      func_append libs " $deplib"
+    done
+
+    if test "$linkmode" = lib; then
+      libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+      # Compute libraries that are listed more than once in $predeps
+      # $postdeps and mark them as special (i.e., whose duplicates are
+      # not to be eliminated).
+      pre_post_deps=
+      if $opt_duplicate_compiler_generated_deps; then
+	for pre_post_dep in $predeps $postdeps; do
+	  case "$pre_post_deps " in
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
+	  esac
+	  func_append pre_post_deps " $pre_post_dep"
+	done
+      fi
+      pre_post_deps=
+    fi
+
+    deplibs=
+    newdependency_libs=
+    newlib_search_path=
+    need_relink=no # whether we're linking any uninstalled libtool libraries
+    notinst_deplibs= # not-installed libtool libraries
+    notinst_path= # paths that contain not-installed libtool libraries
+
+    case $linkmode in
+    lib)
+	passes="conv dlpreopen link"
+	for file in $dlfiles $dlprefiles; do
+	  case $file in
+	  *.la) ;;
+	  *)
+	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
+	    ;;
+	  esac
+	done
+	;;
+    prog)
+	compile_deplibs=
+	finalize_deplibs=
+	alldeplibs=no
+	newdlfiles=
+	newdlprefiles=
+	passes="conv scan dlopen dlpreopen link"
+	;;
+    *)  passes="conv"
+	;;
+    esac
+
+    for pass in $passes; do
+      # The preopen pass in lib mode reverses $deplibs; put it back here
+      # so that -L comes before libs that need it for instance...
+      if test "$linkmode,$pass" = "lib,link"; then
+	## FIXME: Find the place where the list is rebuilt in the wrong
+	##        order, and fix it there properly
+        tmp_deplibs=
+	for deplib in $deplibs; do
+	  tmp_deplibs="$deplib $tmp_deplibs"
+	done
+	deplibs="$tmp_deplibs"
+      fi
+
+      if test "$linkmode,$pass" = "lib,link" ||
+	 test "$linkmode,$pass" = "prog,scan"; then
+	libs="$deplibs"
+	deplibs=
+      fi
+      if test "$linkmode" = prog; then
+	case $pass in
+	dlopen) libs="$dlfiles" ;;
+	dlpreopen) libs="$dlprefiles" ;;
+	link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+	esac
+      fi
+      if test "$linkmode,$pass" = "lib,dlpreopen"; then
+	# Collect and forward deplibs of preopened libtool libs
+	for lib in $dlprefiles; do
+	  # Ignore non-libtool-libs
+	  dependency_libs=
+	  func_resolve_sysroot "$lib"
+	  case $lib in
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
+	  esac
+
+	  # Collect preopened libtool deplibs, except any this library
+	  # has declared as weak libs
+	  for deplib in $dependency_libs; do
+	    func_basename "$deplib"
+            deplib_base=$func_basename_result
+	    case " $weak_libs " in
+	    *" $deplib_base "*) ;;
+	    *) func_append deplibs " $deplib" ;;
+	    esac
+	  done
+	done
+	libs="$dlprefiles"
+      fi
+      if test "$pass" = dlopen; then
+	# Collect dlpreopened libraries
+	save_deplibs="$deplibs"
+	deplibs=
+      fi
+
+      for deplib in $libs; do
+	lib=
+	found=no
+	case $deplib in
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    func_append compiler_flags " $deplib"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-l*)
+	  if test "$linkmode" != lib && test "$linkmode" != prog; then
+	    func_warning "\`-l' is ignored for archives/objects"
+	    continue
+	  fi
+	  func_stripname '-l' '' "$deplib"
+	  name=$func_stripname_result
+	  if test "$linkmode" = lib; then
+	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
+	  else
+	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
+	  fi
+	  for searchdir in $searchdirs; do
+	    for search_ext in .la $std_shrext .so .a; do
+	      # Search the libtool library
+	      lib="$searchdir/lib${name}${search_ext}"
+	      if test -f "$lib"; then
+		if test "$search_ext" = ".la"; then
+		  found=yes
+		else
+		  found=no
+		fi
+		break 2
+	      fi
+	    done
+	  done
+	  if test "$found" != yes; then
+	    # deplib doesn't seem to be a libtool library
+	    if test "$linkmode,$pass" = "prog,link"; then
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      deplibs="$deplib $deplibs"
+	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    continue
+	  else # deplib is a libtool library
+	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+	    # We need to do some special things here, and not later.
+	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	      case " $predeps $postdeps " in
+	      *" $deplib "*)
+		if func_lalib_p "$lib"; then
+		  library_names=
+		  old_library=
+		  func_source "$lib"
+		  for l in $old_library $library_names; do
+		    ll="$l"
+		  done
+		  if test "X$ll" = "X$old_library" ; then # only static version available
+		    found=no
+		    func_dirname "$lib" "" "."
+		    ladir="$func_dirname_result"
+		    lib=$ladir/$old_library
+		    if test "$linkmode,$pass" = "prog,link"; then
+		      compile_deplibs="$deplib $compile_deplibs"
+		      finalize_deplibs="$deplib $finalize_deplibs"
+		    else
+		      deplibs="$deplib $deplibs"
+		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+		    fi
+		    continue
+		  fi
+		fi
+		;;
+	      *) ;;
+	      esac
+	    fi
+	  fi
+	  ;; # -l
+	*.ltframework)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    deplibs="$deplib $deplibs"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-L*)
+	  case $linkmode in
+	  lib)
+	    deplibs="$deplib $deplibs"
+	    test "$pass" = conv && continue
+	    newdependency_libs="$deplib $newdependency_libs"
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  prog)
+	    if test "$pass" = conv; then
+	      deplibs="$deplib $deplibs"
+	      continue
+	    fi
+	    if test "$pass" = scan; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  *)
+	    func_warning "\`-L' is ignored for archives/objects"
+	    ;;
+	  esac # linkmode
+	  continue
+	  ;; # -L
+	-R*)
+	  if test "$pass" = link; then
+	    func_stripname '-R' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=$func_resolve_sysroot_result
+	    # Make sure the xrpath contains only unique directories.
+	    case "$xrpath " in
+	    *" $dir "*) ;;
+	    *) func_append xrpath " $dir" ;;
+	    esac
+	  fi
+	  deplibs="$deplib $deplibs"
+	  continue
+	  ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=$func_resolve_sysroot_result
+	  ;;
+	*.$libext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	    continue
+	  fi
+	  case $linkmode in
+	  lib)
+	    # Linking convenience modules into shared libraries is allowed,
+	    # but linking other static libraries is non-portable.
+	    case " $dlpreconveniencelibs " in
+	    *" $deplib "*) ;;
+	    *)
+	      valid_a_lib=no
+	      case $deplibs_check_method in
+		match_pattern*)
+		  set dummy $deplibs_check_method; shift
+		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
+		    | $EGREP "$match_pattern_regex" > /dev/null; then
+		    valid_a_lib=yes
+		  fi
+		;;
+		pass_all)
+		  valid_a_lib=yes
+		;;
+	      esac
+	      if test "$valid_a_lib" != yes; then
+		echo
+		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me believe"
+		echo "*** that it is just a static archive that I should not use here."
+	      else
+		echo
+		$ECHO "*** Warning: Linking the shared library $output against the"
+		$ECHO "*** static library $deplib is not portable!"
+		deplibs="$deplib $deplibs"
+	      fi
+	      ;;
+	    esac
+	    continue
+	    ;;
+	  prog)
+	    if test "$pass" != link; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    continue
+	    ;;
+	  esac # linkmode
+	  ;; # *.$libext
+	*.lo | *.$objext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	  elif test "$linkmode" = prog; then
+	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+	      # If there is no dlopen support or we're linking statically,
+	      # we need to preload.
+	      func_append newdlprefiles " $deplib"
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      func_append newdlfiles " $deplib"
+	    fi
+	  fi
+	  continue
+	  ;;
+	%DEPLIBS%)
+	  alldeplibs=yes
+	  continue
+	  ;;
+	esac # case $deplib
+
+	if test "$found" = yes || test -f "$lib"; then :
+	else
+	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
+	fi
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$lib" \
+	  || func_fatal_error "\`$lib' is not a valid libtool archive"
+
+	func_dirname "$lib" "" "."
+	ladir="$func_dirname_result"
+
+	dlname=
+	dlopen=
+	dlpreopen=
+	libdir=
+	library_names=
+	old_library=
+	inherited_linker_flags=
+	# If the library was installed with an old release of libtool,
+	# it will not redefine variables installed, or shouldnotlink
+	installed=yes
+	shouldnotlink=no
+	avoidtemprpath=
+
+
+	# Read the .la file
+	func_source "$lib"
+
+	# Convert "-framework foo" to "foo.ltframework"
+	if test -n "$inherited_linker_flags"; then
+	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
+	    case " $new_inherited_linker_flags " in
+	      *" $tmp_inherited_linker_flag "*) ;;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
+	    esac
+	  done
+	fi
+	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	if test "$linkmode,$pass" = "lib,link" ||
+	   test "$linkmode,$pass" = "prog,scan" ||
+	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
+	fi
+
+	if test "$pass" = conv; then
+	  # Only check for convenience libraries
+	  deplibs="$lib $deplibs"
+	  if test -z "$libdir"; then
+	    if test -z "$old_library"; then
+	      func_fatal_error "cannot find name of link library for \`$lib'"
+	    fi
+	    # It is a libtool convenience library, so add in its objects.
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
+	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
+	    func_fatal_error "\`$lib' is not a convenience library"
+	  fi
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    deplibs="$deplib $deplibs"
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done
+	  continue
+	fi # $pass = conv
+
+
+	# Get the name of the library we link against.
+	linklib=
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" = yes ||
+	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	  linklib=$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib="$l"
+	  done
+	fi
+	if test -z "$linklib"; then
+	  func_fatal_error "cannot find name of link library for \`$lib'"
+	fi
+
+	# This library was specified with -dlopen.
+	if test "$pass" = dlopen; then
+	  if test -z "$libdir"; then
+	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
+	  fi
+	  if test -z "$dlname" ||
+	     test "$dlopen_support" != yes ||
+	     test "$build_libtool_libs" = no; then
+	    # If there is no dlname, no dlopen support or we're linking
+	    # statically, we need to preload.  We also need to preload any
+	    # dependent libraries so libltdl's deplib preloader doesn't
+	    # bomb out in the load deplibs phase.
+	    func_append dlprefiles " $lib $dependency_libs"
+	  else
+	    func_append newdlfiles " $lib"
+	  fi
+	  continue
+	fi # $pass = dlopen
+
+	# We need an absolute path.
+	case $ladir in
+	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+	*)
+	  abs_ladir=`cd "$ladir" && pwd`
+	  if test -z "$abs_ladir"; then
+	    func_warning "cannot determine absolute directory name of \`$ladir'"
+	    func_warning "passing it literally to the linker, although it might fail"
+	    abs_ladir="$ladir"
+	  fi
+	  ;;
+	esac
+	func_basename "$lib"
+	laname="$func_basename_result"
+
+	# Find the relevant object directory and library name.
+	if test "X$installed" = Xyes; then
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    func_warning "library \`$lib' was moved."
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    libdir="$abs_ladir"
+	  else
+	    dir="$lt_sysroot$libdir"
+	    absdir="$lt_sysroot$libdir"
+	  fi
+	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+	else
+	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  else
+	    dir="$ladir/$objdir"
+	    absdir="$abs_ladir/$objdir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  fi
+	fi # $installed = yes
+	func_stripname 'lib' '.la' "$laname"
+	name=$func_stripname_result
+
+	# This library was specified with -dlpreopen.
+	if test "$pass" = dlpreopen; then
+	  if test -z "$libdir" && test "$linkmode" = prog; then
+	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
+	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
+	fi # $pass = dlpreopen
+
+	if test -z "$libdir"; then
+	  # Link the convenience library
+	  if test "$linkmode" = lib; then
+	    deplibs="$dir/$old_library $deplibs"
+	  elif test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$dir/$old_library $compile_deplibs"
+	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
+	  else
+	    deplibs="$lib $deplibs" # used for prog,scan pass
+	  fi
+	  continue
+	fi
+
+
+	if test "$linkmode" = prog && test "$pass" != link; then
+	  func_append newlib_search_path " $ladir"
+	  deplibs="$lib $deplibs"
+
+	  linkalldeplibs=no
+	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
+	     test "$build_libtool_libs" = no; then
+	    linkalldeplibs=yes
+	  fi
+
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    case $deplib in
+	    -L*) func_stripname '-L' '' "$deplib"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
+		 ;;
+	    esac
+	    # Need to link against all dependency_libs?
+	    if test "$linkalldeplibs" = yes; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      # Need to hardcode shared library paths
+	      # or/and link against static libraries
+	      newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done # for deplib
+	  continue
+	fi # $linkmode = prog...
+
+	if test "$linkmode,$pass" = "prog,link"; then
+	  if test -n "$library_names" &&
+	     { { test "$prefer_static_libs" = no ||
+	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
+	       test -z "$old_library"; }; then
+	    # We need to hardcode the library path
+	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+	      # Make sure the rpath contains only unique directories.
+	      case "$temp_rpath:" in
+	      *"$absdir:"*) ;;
+	      *) func_append temp_rpath "$absdir:" ;;
+	      esac
+	    fi
+
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi # $linkmode,$pass = prog,link...
+
+	  if test "$alldeplibs" = yes &&
+	     { test "$deplibs_check_method" = pass_all ||
+	       { test "$build_libtool_libs" = yes &&
+		 test -n "$library_names"; }; }; then
+	    # We only need to search for static libraries
+	    continue
+	  fi
+	fi
+
+	link_static=no # Whether the deplib will be linked statically
+	use_static_libs=$prefer_static_libs
+	if test "$use_static_libs" = built && test "$installed" = yes; then
+	  use_static_libs=no
+	fi
+	if test -n "$library_names" &&
+	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
+	  case $host in
+	  *cygwin* | *mingw* | *cegcc*)
+	      # No point in relinking DLLs because paths are not encoded
+	      func_append notinst_deplibs " $lib"
+	      need_relink=no
+	    ;;
+	  *)
+	    if test "$installed" = no; then
+	      func_append notinst_deplibs " $lib"
+	      need_relink=yes
+	    fi
+	    ;;
+	  esac
+	  # This is a shared library
+
+	  # Warn about portability, can't link against -module's on some
+	  # systems (darwin).  Don't bleat about dlopened modules though!
+	  dlopenmodule=""
+	  for dlpremoduletest in $dlprefiles; do
+	    if test "X$dlpremoduletest" = "X$lib"; then
+	      dlopenmodule="$dlpremoduletest"
+	      break
+	    fi
+	  done
+	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
+	    echo
+	    if test "$linkmode" = prog; then
+	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
+	    else
+	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
+	    fi
+	    $ECHO "*** $linklib is not portable!"
+	  fi
+	  if test "$linkmode" = lib &&
+	     test "$hardcode_into_libs" = yes; then
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi
+
+	  if test -n "$old_archive_from_expsyms_cmds"; then
+	    # figure out the soname
+	    set dummy $library_names
+	    shift
+	    realname="$1"
+	    shift
+	    libname=`eval "\\$ECHO \"$libname_spec\""`
+	    # use dlname if we got it. it's perfectly good, no?
+	    if test -n "$dlname"; then
+	      soname="$dlname"
+	    elif test -n "$soname_spec"; then
+	      # bleh windows
+	      case $host in
+	      *cygwin* | mingw* | *cegcc*)
+	        func_arith $current - $age
+		major=$func_arith_result
+		versuffix="-$major"
+		;;
+	      esac
+	      eval soname=\"$soname_spec\"
+	    else
+	      soname="$realname"
+	    fi
+
+	    # Make a new name for the extract_expsyms_cmds to use
+	    soroot="$soname"
+	    func_basename "$soroot"
+	    soname="$func_basename_result"
+	    func_stripname 'lib' '.dll' "$soname"
+	    newlib=libimp-$func_stripname_result.a
+
+	    # If the library has no export list, then create one now
+	    if test -f "$output_objdir/$soname-def"; then :
+	    else
+	      func_verbose "extracting exported symbol list from \`$soname'"
+	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
+	    fi
+
+	    # Create $newlib
+	    if test -f "$output_objdir/$newlib"; then :; else
+	      func_verbose "generating import library for \`$soname'"
+	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
+	    fi
+	    # make sure the library variables are pointing to the new library
+	    dir=$output_objdir
+	    linklib=$newlib
+	  fi # test -n "$old_archive_from_expsyms_cmds"
+
+	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    lib_linked=yes
+	    case $hardcode_action in
+	    immediate | unsupported)
+	      if test "$hardcode_direct" = no; then
+		add="$dir/$linklib"
+		case $host in
+		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+		    *-*-unixware7*) add_dir="-L$dir" ;;
+		  *-*-darwin* )
+		    # if the lib is a (non-dlopened) module then we can not
+		    # link against it, someone is ignoring the earlier warnings
+		    if /usr/bin/file -L $add 2> /dev/null |
+			 $GREP ": [^:]* bundle" >/dev/null ; then
+		      if test "X$dlopenmodule" != "X$lib"; then
+			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
+			if test -z "$old_library" ; then
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
+			else
+			  add="$dir/$old_library"
+			fi
+		      elif test -n "$old_library"; then
+			add="$dir/$old_library"
+		      fi
+		    fi
+		esac
+	      elif test "$hardcode_minus_L" = no; then
+		case $host in
+		*-*-sunos*) add_shlibpath="$dir" ;;
+		esac
+		add_dir="-L$dir"
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = no; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    relink)
+	      if test "$hardcode_direct" = yes &&
+	         test "$hardcode_direct_absolute" = no; then
+		add="$dir/$linklib"
+	      elif test "$hardcode_minus_L" = yes; then
+		add_dir="-L$absdir"
+		# Try looking first in the location we're being installed to.
+		if test -n "$inst_prefix_dir"; then
+		  case $libdir in
+		    [\\/]*)
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
+		      ;;
+		  esac
+		fi
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = yes; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    *) lib_linked=no ;;
+	    esac
+
+	    if test "$lib_linked" != yes; then
+	      func_fatal_configuration "unsupported hardcode properties"
+	    fi
+
+	    if test -n "$add_shlibpath"; then
+	      case :$compile_shlibpath: in
+	      *":$add_shlibpath:"*) ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
+	      esac
+	    fi
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	      if test "$hardcode_direct" != yes &&
+		 test "$hardcode_minus_L" != yes &&
+		 test "$hardcode_shlibpath_var" = yes; then
+		case :$finalize_shlibpath: in
+		*":$libdir:"*) ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
+		esac
+	      fi
+	    fi
+	  fi
+
+	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    # Finalize command for both is simple: just hardcode it.
+	    if test "$hardcode_direct" = yes &&
+	       test "$hardcode_direct_absolute" = no; then
+	      add="$libdir/$linklib"
+	    elif test "$hardcode_minus_L" = yes; then
+	      add_dir="-L$libdir"
+	      add="-l$name"
+	    elif test "$hardcode_shlibpath_var" = yes; then
+	      case :$finalize_shlibpath: in
+	      *":$libdir:"*) ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
+	      esac
+	      add="-l$name"
+	    elif test "$hardcode_automatic" = yes; then
+	      if test -n "$inst_prefix_dir" &&
+		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
+		add="$inst_prefix_dir$libdir/$linklib"
+	      else
+		add="$libdir/$linklib"
+	      fi
+	    else
+	      # We cannot seem to hardcode it, guess we'll fake it.
+	      add_dir="-L$libdir"
+	      # Try looking first in the location we're being installed to.
+	      if test -n "$inst_prefix_dir"; then
+		case $libdir in
+		  [\\/]*)
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
+		    ;;
+		esac
+	      fi
+	      add="-l$name"
+	    fi
+
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	    fi
+	  fi
+	elif test "$linkmode" = prog; then
+	  # Here we assume that one of hardcode_direct or hardcode_minus_L
+	  # is not unsupported.  This is valid on all known static and
+	  # shared platforms.
+	  if test "$hardcode_direct" != unsupported; then
+	    test -n "$old_library" && linklib="$old_library"
+	    compile_deplibs="$dir/$linklib $compile_deplibs"
+	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
+	  else
+	    compile_deplibs="-l$name -L$dir $compile_deplibs"
+	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+	  fi
+	elif test "$build_libtool_libs" = yes; then
+	  # Not a shared library
+	  if test "$deplibs_check_method" != pass_all; then
+	    # We're trying link a shared library against a static one
+	    # but the system doesn't support it.
+
+	    # Just print a warning and add the library to dependency_libs so
+	    # that the program can be linked against the static library.
+	    echo
+	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
+	    echo "*** I have the capability to make that library automatically link in when"
+	    echo "*** you link to this library.  But I can only do this if you have a"
+	    echo "*** shared version of the library, which you do not appear to have."
+	    if test "$module" = yes; then
+	      echo "*** But as you try to build a module library, libtool will still create "
+	      echo "*** a static module, that should work as long as the dlopening application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+	      if test -z "$global_symbol_pipe"; then
+		echo
+		echo "*** However, this would only work if libtool was able to extract symbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	      fi
+	      if test "$build_old_libs" = no; then
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  else
+	    deplibs="$dir/$old_library $deplibs"
+	    link_static=yes
+	  fi
+	fi # link shared/static library?
+
+	if test "$linkmode" = lib; then
+	  if test -n "$dependency_libs" &&
+	     { test "$hardcode_into_libs" != yes ||
+	       test "$build_old_libs" = yes ||
+	       test "$link_static" = yes; }; then
+	    # Extract -R from dependency_libs
+	    temp_deplibs=
+	    for libdir in $dependency_libs; do
+	      case $libdir in
+	      -R*) func_stripname '-R' '' "$libdir"
+	           temp_xrpath=$func_stripname_result
+		   case " $xrpath " in
+		   *" $temp_xrpath "*) ;;
+		   *) func_append xrpath " $temp_xrpath";;
+		   esac;;
+	      *) func_append temp_deplibs " $libdir";;
+	      esac
+	    done
+	    dependency_libs="$temp_deplibs"
+	  fi
+
+	  func_append newlib_search_path " $absdir"
+	  # Link against this library
+	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+	  # ... and its dependency_libs
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    newdependency_libs="$deplib $newdependency_libs"
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $func_resolve_sysroot_result"
+	  done
+
+	  if test "$link_all_deplibs" != no; then
+	    # Add the search paths of all dependency libraries
+	    for deplib in $dependency_libs; do
+	      path=
+	      case $deplib in
+	      -L*) path="$deplib" ;;
+	      *.la)
+	        func_resolve_sysroot "$deplib"
+	        deplib=$func_resolve_sysroot_result
+	        func_dirname "$deplib" "" "."
+		dir=$func_dirname_result
+		# We need an absolute path.
+		case $dir in
+		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+		*)
+		  absdir=`cd "$dir" && pwd`
+		  if test -z "$absdir"; then
+		    func_warning "cannot determine absolute directory name of \`$dir'"
+		    absdir="$dir"
+		  fi
+		  ;;
+		esac
+		if $GREP "^installed=no" $deplib > /dev/null; then
+		case $host in
+		*-*-darwin*)
+		  depdepl=
+		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+		  if test -n "$deplibrary_names" ; then
+		    for tmp in $deplibrary_names ; do
+		      depdepl=$tmp
+		    done
+		    if test -f "$absdir/$objdir/$depdepl" ; then
+		      depdepl="$absdir/$objdir/$depdepl"
+		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
+                      if test -z "$darwin_install_name"; then
+                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
+                      fi
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
+		      path=
+		    fi
+		  fi
+		  ;;
+		*)
+		  path="-L$absdir/$objdir"
+		  ;;
+		esac
+		else
+		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		  test -z "$libdir" && \
+		    func_fatal_error "\`$deplib' is not a valid libtool archive"
+		  test "$absdir" != "$libdir" && \
+		    func_warning "\`$deplib' seems to be moved"
+
+		  path="-L$absdir"
+		fi
+		;;
+	      esac
+	      case " $deplibs " in
+	      *" $path "*) ;;
+	      *) deplibs="$path $deplibs" ;;
+	      esac
+	    done
+	  fi # link_all_deplibs != no
+	fi # linkmode = lib
+      done # for deplib in $libs
+      if test "$pass" = link; then
+	if test "$linkmode" = "prog"; then
+	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
+	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
+	else
+	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	fi
+      fi
+      dependency_libs="$newdependency_libs"
+      if test "$pass" = dlpreopen; then
+	# Link the dlpreopened libraries before other libraries
+	for deplib in $save_deplibs; do
+	  deplibs="$deplib $deplibs"
+	done
+      fi
+      if test "$pass" != dlopen; then
+	if test "$pass" != conv; then
+	  # Make sure lib_search_path contains only unique directories.
+	  lib_search_path=
+	  for dir in $newlib_search_path; do
+	    case "$lib_search_path " in
+	    *" $dir "*) ;;
+	    *) func_append lib_search_path " $dir" ;;
+	    esac
+	  done
+	  newlib_search_path=
+	fi
+
+	if test "$linkmode,$pass" != "prog,link"; then
+	  vars="deplibs"
+	else
+	  vars="compile_deplibs finalize_deplibs"
+	fi
+	for var in $vars dependency_libs; do
+	  # Add libraries to $var in reverse order
+	  eval tmp_libs=\"\$$var\"
+	  new_libs=
+	  for deplib in $tmp_libs; do
+	    # FIXME: Pedantically, this is the right thing to do, so
+	    #        that some nasty dependency loop isn't accidentally
+	    #        broken:
+	    #new_libs="$deplib $new_libs"
+	    # Pragmatically, this seems to cause very few problems in
+	    # practice:
+	    case $deplib in
+	    -L*) new_libs="$deplib $new_libs" ;;
+	    -R*) ;;
+	    *)
+	      # And here is the reason: when a library appears more
+	      # than once as an explicit dependence of a library, or
+	      # is implicitly linked in more than once by the
+	      # compiler, it is considered special, and multiple
+	      # occurrences thereof are not removed.  Compare this
+	      # with having the same library being listed as a
+	      # dependency of multiple other libraries: in this case,
+	      # we know (pedantically, we assume) the library does not
+	      # need to be listed more than once, so we keep only the
+	      # last copy.  This is not always right, but it is rare
+	      # enough that we require users that really mean to play
+	      # such unportable linking tricks to link the library
+	      # using -Wl,-lname, so that libtool does not consider it
+	      # for duplicate removal.
+	      case " $specialdeplibs " in
+	      *" $deplib "*) new_libs="$deplib $new_libs" ;;
+	      *)
+		case " $new_libs " in
+		*" $deplib "*) ;;
+		*) new_libs="$deplib $new_libs" ;;
+		esac
+		;;
+	      esac
+	      ;;
+	    esac
+	  done
+	  tmp_libs=
+	  for deplib in $new_libs; do
+	    case $deplib in
+	    -L*)
+	      case " $tmp_libs " in
+	      *" $deplib "*) ;;
+	      *) func_append tmp_libs " $deplib" ;;
+	      esac
+	      ;;
+	    *) func_append tmp_libs " $deplib" ;;
+	    esac
+	  done
+	  eval $var=\"$tmp_libs\"
+	done # for var
+      fi
+      # Last step: remove runtime libs from dependency_libs
+      # (they stay in deplibs)
+      tmp_libs=
+      for i in $dependency_libs ; do
+	case " $predeps $postdeps $compiler_lib_search_path " in
+	*" $i "*)
+	  i=""
+	  ;;
+	esac
+	if test -n "$i" ; then
+	  func_append tmp_libs " $i"
+	fi
+      done
+      dependency_libs=$tmp_libs
+    done # for pass
+    if test "$linkmode" = prog; then
+      dlfiles="$newdlfiles"
+    fi
+    if test "$linkmode" = prog || test "$linkmode" = lib; then
+      dlprefiles="$newdlprefiles"
+    fi
+
+    case $linkmode in
+    oldlib)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for archives"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for archives" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for archives"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for archives"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info/-version-number' is ignored for archives"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for archives"
+
+      test -n "$export_symbols$export_symbols_regex" && \
+	func_warning "\`-export-symbols' is ignored for archives"
+
+      # Now set the variables for building old libraries.
+      build_libtool_libs=no
+      oldlibs="$output"
+      func_append objs "$old_deplibs"
+      ;;
+
+    lib)
+      # Make sure we only generate libraries of the form `libNAME.la'.
+      case $outputname in
+      lib*)
+	func_stripname 'lib' '.la' "$outputname"
+	name=$func_stripname_result
+	eval shared_ext=\"$shrext_cmds\"
+	eval libname=\"$libname_spec\"
+	;;
+      *)
+	test "$module" = no && \
+	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
+
+	if test "$need_lib_prefix" != no; then
+	  # Add the "lib" prefix for modules if required
+	  func_stripname '' '.la' "$outputname"
+	  name=$func_stripname_result
+	  eval shared_ext=\"$shrext_cmds\"
+	  eval libname=\"$libname_spec\"
+	else
+	  func_stripname '' '.la' "$outputname"
+	  libname=$func_stripname_result
+	fi
+	;;
+      esac
+
+      if test -n "$objs"; then
+	if test "$deplibs_check_method" != pass_all; then
+	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
+	else
+	  echo
+	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
+	  $ECHO "*** objects $objs is not portable!"
+	  func_append libobjs " $objs"
+	fi
+      fi
+
+      test "$dlself" != no && \
+	func_warning "\`-dlopen self' is ignored for libtool libraries"
+
+      set dummy $rpath
+      shift
+      test "$#" -gt 1 && \
+	func_warning "ignoring multiple \`-rpath's for a libtool library"
+
+      install_libdir="$1"
+
+      oldlibs=
+      if test -z "$rpath"; then
+	if test "$build_libtool_libs" = yes; then
+	  # Building a libtool convenience library.
+	  # Some compilers have problems with a `.al' extension so
+	  # convenience libraries should have the same extension an
+	  # archive normally would.
+	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
+	  build_libtool_libs=convenience
+	  build_old_libs=yes
+	fi
+
+	test -n "$vinfo" && \
+	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"
+
+	test -n "$release" && \
+	  func_warning "\`-release' is ignored for convenience libraries"
+      else
+
+	# Parse the version information argument.
+	save_ifs="$IFS"; IFS=':'
+	set dummy $vinfo 0 0 0
+	shift
+	IFS="$save_ifs"
+
+	test -n "$7" && \
+	  func_fatal_help "too many parameters to \`-version-info'"
+
+	# convert absolute version numbers to libtool ages
+	# this retains compatibility with .la files and attempts
+	# to make the code below a bit more comprehensible
+
+	case $vinfo_number in
+	yes)
+	  number_major="$1"
+	  number_minor="$2"
+	  number_revision="$3"
+	  #
+	  # There are really only two kinds -- those that
+	  # use the current revision as the major version
+	  # and those that subtract age and use age as
+	  # a minor version.  But, then there is irix
+	  # which has an extra 1 added just for fun
+	  #
+	  case $version_type in
+	  # correct linux to gnu/linux during the next big refactor
+	  darwin|linux|osf|windows|none)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_revision"
+	    ;;
+	  freebsd-aout|freebsd-elf|qnx|sunos)
+	    current="$number_major"
+	    revision="$number_minor"
+	    age="0"
+	    ;;
+	  irix|nonstopux)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_minor"
+	    lt_irix_increment=no
+	    ;;
+	  esac
+	  ;;
+	no)
+	  current="$1"
+	  revision="$2"
+	  age="$3"
+	  ;;
+	esac
+
+	# Check that each of the things are valid numbers.
+	case $current in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "CURRENT \`$current' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $revision in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "REVISION \`$revision' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $age in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "AGE \`$age' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	if test "$age" -gt "$current"; then
+	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	fi
+
+	# Calculate the version variables.
+	major=
+	versuffix=
+	verstring=
+	case $version_type in
+	none) ;;
+
+	darwin)
+	  # Like Linux, but with the current version available in
+	  # verstring for coding it into the library header
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  # Darwin ld doesn't like 0 for these options...
+	  func_arith $current + 1
+	  minor_current=$func_arith_result
+	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+	  ;;
+
+	freebsd-aout)
+	  major=".$current"
+	  versuffix=".$current.$revision";
+	  ;;
+
+	freebsd-elf)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	irix | nonstopux)
+	  if test "X$lt_irix_increment" = "Xno"; then
+	    func_arith $current - $age
+	  else
+	    func_arith $current - $age + 1
+	  fi
+	  major=$func_arith_result
+
+	  case $version_type in
+	    nonstopux) verstring_prefix=nonstopux ;;
+	    *)         verstring_prefix=sgi ;;
+	  esac
+	  verstring="$verstring_prefix$major.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$revision
+	  while test "$loop" -ne 0; do
+	    func_arith $revision - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring_prefix$major.$iface:$verstring"
+	  done
+
+	  # Before this point, $major must not contain `.'.
+	  major=.$major
+	  versuffix="$major.$revision"
+	  ;;
+
+	linux) # correct to gnu/linux during the next big refactor
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  ;;
+
+	osf)
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix=".$current.$age.$revision"
+	  verstring="$current.$age.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$age
+	  while test "$loop" -ne 0; do
+	    func_arith $current - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring:${iface}.0"
+	  done
+
+	  # Make executables depend on our current version.
+	  func_append verstring ":${current}.0"
+	  ;;
+
+	qnx)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	sunos)
+	  major=".$current"
+	  versuffix=".$current.$revision"
+	  ;;
+
+	windows)
+	  # Use '-' rather than '.', since we only want one
+	  # extension on DOS 8.3 filesystems.
+	  func_arith $current - $age
+	  major=$func_arith_result
+	  versuffix="-$major"
+	  ;;
+
+	*)
+	  func_fatal_configuration "unknown library version type \`$version_type'"
+	  ;;
+	esac
+
+	# Clear the version info if we defaulted, and they specified a release.
+	if test -z "$vinfo" && test -n "$release"; then
+	  major=
+	  case $version_type in
+	  darwin)
+	    # we can't check for "0.0" in archive_cmds due to quoting
+	    # problems, so we reset it completely
+	    verstring=
+	    ;;
+	  *)
+	    verstring="0.0"
+	    ;;
+	  esac
+	  if test "$need_version" = no; then
+	    versuffix=
+	  else
+	    versuffix=".0.0"
+	  fi
+	fi
+
+	# Remove version info from name if versioning should be avoided
+	if test "$avoid_version" = yes && test "$need_version" = no; then
+	  major=
+	  versuffix=
+	  verstring=""
+	fi
+
+	# Check to see if the archive will have undefined symbols.
+	if test "$allow_undefined" = yes; then
+	  if test "$allow_undefined_flag" = unsupported; then
+	    func_warning "undefined symbols not allowed in $host shared libraries"
+	    build_libtool_libs=no
+	    build_old_libs=yes
+	  fi
+	else
+	  # Don't allow undefined symbols.
+	  allow_undefined_flag="$no_undefined_flag"
+	fi
+
+      fi
+
+      func_generate_dlsyms "$libname" "$libname" "yes"
+      func_append libobjs " $symfileobj"
+      test "X$libobjs" = "X " && libobjs=
+
+      if test "$opt_mode" != relink; then
+	# Remove our outputs, but don't remove object files since they
+	# may have been created when compiling PIC objects.
+	removelist=
+	tempremovelist=`$ECHO "$output_objdir/*"`
+	for p in $tempremovelist; do
+	  case $p in
+	    *.$objext | *.gcno)
+	       ;;
+	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+	       if test "X$precious_files_regex" != "X"; then
+		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+		 then
+		   continue
+		 fi
+	       fi
+	       func_append removelist " $p"
+	       ;;
+	    *) ;;
+	  esac
+	done
+	test -n "$removelist" && \
+	  func_show_eval "${RM}r \$removelist"
+      fi
+
+      # Now set the variables for building old libraries.
+      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+	func_append oldlibs " $output_objdir/$libname.$libext"
+
+	# Transform .lo files to .o files.
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
+      fi
+
+      # Eliminate all temporary directories.
+      #for path in $notinst_path; do
+      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
+      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
+      #done
+
+      if test -n "$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	temp_xrpath=
+	for libdir in $xrpath; do
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+	  dependency_libs="$temp_xrpath $dependency_libs"
+	fi
+      fi
+
+      # Make sure dlfiles contains only unique files that won't be dlpreopened
+      old_dlfiles="$dlfiles"
+      dlfiles=
+      for lib in $old_dlfiles; do
+	case " $dlprefiles $dlfiles " in
+	*" $lib "*) ;;
+	*) func_append dlfiles " $lib" ;;
+	esac
+      done
+
+      # Make sure dlprefiles contains only unique files
+      old_dlprefiles="$dlprefiles"
+      dlprefiles=
+      for lib in $old_dlprefiles; do
+	case "$dlprefiles " in
+	*" $lib "*) ;;
+	*) func_append dlprefiles " $lib" ;;
+	esac
+      done
+
+      if test "$build_libtool_libs" = yes; then
+	if test -n "$rpath"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # these systems don't actually have a c library (as such)!
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C library is in the System framework
+	    func_append deplibs " System.ltframework"
+	    ;;
+	  *-*-netbsd*)
+	    # Don't link with libc until the a.out ld.so is fixed.
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    ;;
+	  *)
+	    # Add libc to deplibs on all other systems if necessary.
+	    if test "$build_libtool_need_lc" = "yes"; then
+	      func_append deplibs " -lc"
+	    fi
+	    ;;
+	  esac
+	fi
+
+	# Transform deplibs into only deplibs that can be linked in shared.
+	name_save=$name
+	libname_save=$libname
+	release_save=$release
+	versuffix_save=$versuffix
+	major_save=$major
+	# I'm not sure if I'm treating the release correctly.  I think
+	# release should show up in the -l (ie -lgmp5) so we don't want to
+	# add it in twice.  Is that correct?
+	release=""
+	versuffix=""
+	major=""
+	newdeplibs=
+	droppeddeps=no
+	case $deplibs_check_method in
+	pass_all)
+	  # Don't check for shared/static.  Everything works.
+	  # This might be a little naive.  We might want to check
+	  # whether the library exists or not.  But this is on
+	  # osf3 & osf4 and I'm not really sure... Just
+	  # implementing what was already the behavior.
+	  newdeplibs=$deplibs
+	  ;;
+	test_compile)
+	  # This code stresses the "libraries are programs" paradigm to its
+	  # limits. Maybe even breaks it.  We compile a program, linking it
+	  # against the deplibs as a proxy for the library.  Then we can check
+	  # whether they linked in statically or dynamically with ldd.
+	  $opt_dry_run || $RM conftest.c
+	  cat > conftest.c <<EOF
+	  int main() { return 0; }
+EOF
+	  $opt_dry_run || $RM conftest
+	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
+	    ldd_output=`ldd conftest`
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		  case " $predeps $postdeps " in
+		  *" $i "*)
+		    func_append newdeplibs " $i"
+		    i=""
+		    ;;
+		  esac
+		fi
+		if test -n "$i" ; then
+		  libname=`eval "\\$ECHO \"$libname_spec\""`
+		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		  set dummy $deplib_matches; shift
+		  deplib_match=$1
+		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		    func_append newdeplibs " $i"
+		  else
+		    droppeddeps=yes
+		    echo
+		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		    echo "*** I have the capability to make that library automatically link in when"
+		    echo "*** you link to this library.  But I can only do this if you have a"
+		    echo "*** shared version of the library, which I believe you do not have"
+		    echo "*** because a test_compile did reveal that the linker did not use it for"
+		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
+		  fi
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  else
+	    # Error occurred in the first compile.  Let's try to salvage
+	    # the situation: Compile a separate program for each library.
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		$opt_dry_run || $RM conftest
+		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
+		  ldd_output=`ldd conftest`
+		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		    case " $predeps $postdeps " in
+		    *" $i "*)
+		      func_append newdeplibs " $i"
+		      i=""
+		      ;;
+		    esac
+		  fi
+		  if test -n "$i" ; then
+		    libname=`eval "\\$ECHO \"$libname_spec\""`
+		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		    set dummy $deplib_matches; shift
+		    deplib_match=$1
+		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		      func_append newdeplibs " $i"
+		    else
+		      droppeddeps=yes
+		      echo
+		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		      echo "*** I have the capability to make that library automatically link in when"
+		      echo "*** you link to this library.  But I can only do this if you have a"
+		      echo "*** shared version of the library, which you do not appear to have"
+		      echo "*** because a test_compile did reveal that the linker did not use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+		    fi
+		  fi
+		else
+		  droppeddeps=yes
+		  echo
+		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
+		  echo "*** make it link in!  You will probably need to install it or some"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even better."
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  fi
+	  ;;
+	file_magic*)
+	  set dummy $deplibs_check_method; shift
+	  file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=$libname
+		fi
+		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  if test "$want_nocaseglob" = yes; then
+		    shopt -s nocaseglob
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
+		  for potent_lib in $potential_libs; do
+		      # Follow soft links.
+		      if ls -lLd "$potent_lib" 2>/dev/null |
+			 $GREP " -> " >/dev/null; then
+			continue
+		      fi
+		      # The statement above tries to avoid entering an
+		      # endless loop below, in case of cyclic links.
+		      # We might still enter an endless loop, since a link
+		      # loop can be closed while we follow links,
+		      # but so what?
+		      potlib="$potent_lib"
+		      while test -h "$potlib" 2>/dev/null; do
+			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+			case $potliblink in
+			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
+			esac
+		      done
+		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
+			 $SED -e 10q |
+			 $EGREP "$file_magic_regex" > /dev/null; then
+			func_append newdeplibs " $a_deplib"
+			a_deplib=""
+			break 2
+		      fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a file magic. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	match_pattern*)
+	  set dummy $deplibs_check_method; shift
+	  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+		  for potent_lib in $potential_libs; do
+		    potlib="$potent_lib" # see symlink-check above in file_magic test
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
+		       $EGREP "$match_pattern_regex" > /dev/null; then
+		      func_append newdeplibs " $a_deplib"
+		      a_deplib=""
+		      break 2
+		    fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	none | unknown | *)
+	  newdeplibs=""
+	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
+	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	    for i in $predeps $postdeps ; do
+	      # can't use Xsed below, because $i might contain '/'
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
+	    done
+	  fi
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
+	    if test "X$deplibs_check_method" = "Xnone"; then
+	      echo "*** Warning: inter-library dependencies are not supported in this platform."
+	    else
+	      echo "*** Warning: inter-library dependencies are not known to be supported."
+	    fi
+	    echo "*** All declared inter-library dependencies are being dropped."
+	    droppeddeps=yes
+	    ;;
+	  esac
+	  ;;
+	esac
+	versuffix=$versuffix_save
+	major=$major_save
+	release=$release_save
+	libname=$libname_save
+	name=$name_save
+
+	case $host in
+	*-*-rhapsody* | *-*-darwin1.[012])
+	  # On Rhapsody replace the C library with the System framework
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
+	  ;;
+	esac
+
+	if test "$droppeddeps" = yes; then
+	  if test "$module" = yes; then
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-library"
+	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
+	    if test -z "$global_symbol_pipe"; then
+	      echo
+	      echo "*** However, this would only work if libtool was able to extract symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** not find such a program.  So, this module is probably useless."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	    fi
+	    if test "$build_old_libs" = no; then
+	      oldlibs="$output_objdir/$libname.$libext"
+	      build_libtool_libs=module
+	      build_old_libs=yes
+	    else
+	      build_libtool_libs=no
+	    fi
+	  else
+	    echo "*** The inter-library dependencies that have been dropped here will be"
+	    echo "*** automatically added whenever a program is linked with this library"
+	    echo "*** or is declared to -dlopen it."
+
+	    if test "$allow_undefined" = no; then
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
+	      if test "$build_old_libs" = no; then
+		oldlibs="$output_objdir/$libname.$libext"
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  fi
+	fi
+	# Done checking deplibs!
+	deplibs=$newdeplibs
+      fi
+      # Time to change all our "foo.ltframework" stuff back to "-framework foo"
+      case $host in
+	*-*-darwin*)
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  ;;
+      esac
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      deplibs="$new_libs"
+
+      # All the library-specific variables (install_libdir is set above).
+      library_names=
+      old_library=
+      dlname=
+
+      # Test again, we may have decided not to build it any more
+      if test "$build_libtool_libs" = yes; then
+	# Remove ${wl} instances when linking with ld.
+	# FIXME: should test the right _cmds variable.
+	case $archive_cmds in
+	  *\$LD\ *) wl= ;;
+        esac
+	if test "$hardcode_into_libs" = yes; then
+	  # Hardcode the library paths
+	  hardcode_libdirs=
+	  dep_rpath=
+	  rpath="$finalize_rpath"
+	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
+	  for libdir in $rpath; do
+	    if test -n "$hardcode_libdir_flag_spec"; then
+	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=$func_replace_sysroot_result
+		if test -z "$hardcode_libdirs"; then
+		  hardcode_libdirs="$libdir"
+		else
+		  # Just accumulate the unique libdirs.
+		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		    ;;
+		  *)
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		    ;;
+		  esac
+		fi
+	      else
+		eval flag=\"$hardcode_libdir_flag_spec\"
+		func_append dep_rpath " $flag"
+	      fi
+	    elif test -n "$runpath_var"; then
+	      case "$perm_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append perm_rpath " $libdir" ;;
+	      esac
+	    fi
+	  done
+	  # Substitute the hardcoded libdirs into the rpath.
+	  if test -n "$hardcode_libdir_separator" &&
+	     test -n "$hardcode_libdirs"; then
+	    libdir="$hardcode_libdirs"
+	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
+	  fi
+	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
+	    # We should set the runpath_var.
+	    rpath=
+	    for dir in $perm_rpath; do
+	      func_append rpath "$dir:"
+	    done
+	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+	  fi
+	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+	fi
+
+	shlibpath="$finalize_shlibpath"
+	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	if test -n "$shlibpath"; then
+	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+	fi
+
+	# Get the real and link names of the library.
+	eval shared_ext=\"$shrext_cmds\"
+	eval library_names=\"$library_names_spec\"
+	set dummy $library_names
+	shift
+	realname="$1"
+	shift
+
+	if test -n "$soname_spec"; then
+	  eval soname=\"$soname_spec\"
+	else
+	  soname="$realname"
+	fi
+	if test -z "$dlname"; then
+	  dlname=$soname
+	fi
+
+	lib="$output_objdir/$realname"
+	linknames=
+	for link
+	do
+	  func_append linknames " $link"
+	done
+
+	# Use standard objects if they are pic
+	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	test "X$libobjs" = "X " && libobjs=
+
+	delfiles=
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
+	  export_symbols="$output_objdir/$libname.uexp"
+	  func_append delfiles " $export_symbols"
+	fi
+
+	orig_export_symbols=
+	case $host_os in
+	cygwin* | mingw* | cegcc*)
+	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+	    # exporting using user supplied symfile
+	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
+	      # and it's NOT already a .def file. Must figure out
+	      # which of the given symbols are data symbols and tag
+	      # them as such. So, trigger use of export_symbols_cmds.
+	      # export_symbols gets reassigned inside the "prepare
+	      # the list of exported symbols" if statement, so the
+	      # include_expsyms logic still works.
+	      orig_export_symbols="$export_symbols"
+	      export_symbols=
+	      always_export_symbols=yes
+	    fi
+	  fi
+	  ;;
+	esac
+
+	# Prepare the list of exported symbols
+	if test -z "$export_symbols"; then
+	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+	    func_verbose "generating symbol list for \`$libname.la'"
+	    export_symbols="$output_objdir/$libname.exp"
+	    $opt_dry_run || $RM $export_symbols
+	    cmds=$export_symbols_cmds
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd1 in $cmds; do
+	      IFS="$save_ifs"
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=yes
+		  eval cmd=\"$cmd1\"
+		  func_len " $cmd"
+		  len=$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=no
+		  ;;
+	      esac
+	      if test "$try_normal_branch" = yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
+		func_show_eval "$cmd" 'exit $?'
+		skipped_export=false
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=$func_basename_result
+		save_libobjs=$libobjs
+		save_output=$output
+		output=${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=$save_output
+		libobjs=$save_libobjs
+		skipped_export=false
+	      else
+		# The command line is too long to execute in one step.
+		func_verbose "using reloadable object file for export list..."
+		skipped_export=:
+		# Break out early, otherwise skipped_export may be
+		# set to false by a later but shorter cmd.
+		break
+	      fi
+	    done
+	    IFS="$save_ifs"
+	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+	fi
+
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  tmp_export_symbols="$export_symbols"
+	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	fi
+
+	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
+	  # The given exports_symbols file has to be filtered, so filter it.
+	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	  # 's' commands which not all seds can handle. GNU sed should be fine
+	  # though. Also, the filter scales superlinearly with the number of
+	  # global variables. join(1) would be nice here, but unfortunately
+	  # isn't a blessed tool.
+	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	  export_symbols=$output_objdir/$libname.def
+	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	fi
+
+	tmp_deplibs=
+	for test_deplib in $deplibs; do
+	  case " $convenience " in
+	  *" $test_deplib "*) ;;
+	  *)
+	    func_append tmp_deplibs " $test_deplib"
+	    ;;
+	  esac
+	done
+	deplibs="$tmp_deplibs"
+
+	if test -n "$convenience"; then
+	  if test -n "$whole_archive_flag_spec" &&
+	    test "$compiler_needs_object" = yes &&
+	    test -z "$libobjs"; then
+	    # extract the archives, so we have objects to list.
+	    # TODO: could optimize this to just extract one archive.
+	    whole_archive_flag_spec=
+	  fi
+	  if test -n "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  else
+	    gentop="$output_objdir/${outputname}x"
+	    func_append generated " $gentop"
+
+	    func_extract_archives $gentop $convenience
+	    func_append libobjs " $func_extract_archives_result"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	fi
+
+	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+	  eval flag=\"$thread_safe_flag_spec\"
+	  func_append linker_flags " $flag"
+	fi
+
+	# Make a backup of the uninstalled library when relinking
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
+	fi
+
+	# Do each of the archive commands.
+	if test "$module" = yes && test -n "$module_cmds" ; then
+	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	    eval test_cmds=\"$module_expsym_cmds\"
+	    cmds=$module_expsym_cmds
+	  else
+	    eval test_cmds=\"$module_cmds\"
+	    cmds=$module_cmds
+	  fi
+	else
+	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	    eval test_cmds=\"$archive_expsym_cmds\"
+	    cmds=$archive_expsym_cmds
+	  else
+	    eval test_cmds=\"$archive_cmds\"
+	    cmds=$archive_cmds
+	  fi
+	fi
+
+	if test "X$skipped_export" != "X:" &&
+	   func_len " $test_cmds" &&
+	   len=$func_len_result &&
+	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  :
+	else
+	  # The command line is too long to link in one step, link piecewise
+	  # or, if using GNU ld and skipped_export is not :, use a linker
+	  # script.
+
+	  # Save the value of $output and $libobjs because we want to
+	  # use them later.  If we have whole_archive_flag_spec, we
+	  # want to use save_libobjs as it was before
+	  # whole_archive_flag_spec was expanded, because we can't
+	  # assume the linker understands whole_archive_flag_spec.
+	  # This may have to be revisited, in case too many
+	  # convenience libraries get linked in and end up exceeding
+	  # the spec.
+	  if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	  fi
+	  save_output=$output
+	  func_basename "$output"
+	  output_la=$func_basename_result
+
+	  # Clear the reloadable object creation command queue and
+	  # initialize k to one.
+	  test_cmds=
+	  concat_cmds=
+	  objlist=
+	  last_robj=
+	  k=1
+
+	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
+	    output=${output_objdir}/${output_la}.lnkscript
+	    func_verbose "creating GNU ld script: $output"
+	    echo 'INPUT (' > $output
+	    for obj in $save_libobjs
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$func_to_tool_file_result
+	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
+	    output=${output_objdir}/${output_la}.lnk
+	    func_verbose "creating linker input file list: $output"
+	    : > $output
+	    set x $save_libobjs
+	    shift
+	    firstobj=
+	    if test "$compiler_needs_object" = yes; then
+	      firstobj="$1 "
+	      shift
+	    fi
+	    for obj
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
+	  else
+	    if test -n "$save_libobjs"; then
+	      func_verbose "creating reloadable object files..."
+	      output=$output_objdir/$output_la-${k}.$objext
+	      eval test_cmds=\"$reload_cmds\"
+	      func_len " $test_cmds"
+	      len0=$func_len_result
+	      len=$len0
+
+	      # Loop over the list of objects to be linked.
+	      for obj in $save_libobjs
+	      do
+		func_len " $obj"
+		func_arith $len + $func_len_result
+		len=$func_arith_result
+		if test "X$objlist" = X ||
+		   test "$len" -lt "$max_cmd_len"; then
+		  func_append objlist " $obj"
+		else
+		  # The command $test_cmds is almost too long, add a
+		  # command to the queue.
+		  if test "$k" -eq 1 ; then
+		    # The first file doesn't have a previous command to add.
+		    reload_objs=$objlist
+		    eval concat_cmds=\"$reload_cmds\"
+		  else
+		    # All subsequent reloadable object files will link in
+		    # the last one created.
+		    reload_objs="$objlist $last_robj"
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
+		  fi
+		  last_robj=$output_objdir/$output_la-${k}.$objext
+		  func_arith $k + 1
+		  k=$func_arith_result
+		  output=$output_objdir/$output_la-${k}.$objext
+		  objlist=" $obj"
+		  func_len " $last_robj"
+		  func_arith $len0 + $func_len_result
+		  len=$func_arith_result
+		fi
+	      done
+	      # Handle the remaining objects by creating one last
+	      # reloadable object file.  All subsequent reloadable object
+	      # files will link in the last one created.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      reload_objs="$objlist $last_robj"
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
+	      if test -n "$last_robj"; then
+	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
+	      fi
+	      func_append delfiles " $output"
+
+	    else
+	      output=
+	    fi
+
+	    if ${skipped_export-false}; then
+	      func_verbose "generating symbol list for \`$libname.la'"
+	      export_symbols="$output_objdir/$libname.exp"
+	      $opt_dry_run || $RM $export_symbols
+	      libobjs=$output
+	      # Append the command to create the export file.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\"
+	      if test -n "$last_robj"; then
+		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
+	      fi
+	    fi
+
+	    test -n "$save_libobjs" &&
+	      func_verbose "creating a temporary reloadable object file: $output"
+
+	    # Loop through the commands generated above and execute them.
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd in $concat_cmds; do
+	      IFS="$save_ifs"
+	      $opt_silent || {
+		  func_quote_for_expand "$cmd"
+		  eval "func_echo $func_quote_for_expand_result"
+	      }
+	      $opt_dry_run || eval "$cmd" || {
+		lt_exit=$?
+
+		# Restore the uninstalled library and exit
+		if test "$opt_mode" = relink; then
+		  ( cd "$output_objdir" && \
+		    $RM "${realname}T" && \
+		    $MV "${realname}U" "$realname" )
+		fi
+
+		exit $lt_exit
+	      }
+	    done
+	    IFS="$save_ifs"
+
+	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+
+          if ${skipped_export-false}; then
+	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	      tmp_export_symbols="$export_symbols"
+	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	    fi
+
+	    if test -n "$orig_export_symbols"; then
+	      # The given exports_symbols file has to be filtered, so filter it.
+	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	      # 's' commands which not all seds can handle. GNU sed should be fine
+	      # though. Also, the filter scales superlinearly with the number of
+	      # global variables. join(1) would be nice here, but unfortunately
+	      # isn't a blessed tool.
+	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	      export_symbols=$output_objdir/$libname.def
+	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	    fi
+	  fi
+
+	  libobjs=$output
+	  # Restore the value of output.
+	  output=$save_output
+
+	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	  # Expand the library linking commands again to reset the
+	  # value of $libobjs for piecewise linking.
+
+	  # Do each of the archive commands.
+	  if test "$module" = yes && test -n "$module_cmds" ; then
+	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	      cmds=$module_expsym_cmds
+	    else
+	      cmds=$module_cmds
+	    fi
+	  else
+	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	      cmds=$archive_expsym_cmds
+	    else
+	      cmds=$archive_cmds
+	    fi
+	  fi
+	fi
+
+	if test -n "$delfiles"; then
+	  # Append the command to remove temporary files to $cmds.
+	  eval cmds=\"\$cmds~\$RM $delfiles\"
+	fi
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append libobjs " $func_extract_archives_result"
+	  test "X$libobjs" = "X " && libobjs=
+	fi
+
+	save_ifs="$IFS"; IFS='~'
+	for cmd in $cmds; do
+	  IFS="$save_ifs"
+	  eval cmd=\"$cmd\"
+	  $opt_silent || {
+	    func_quote_for_expand "$cmd"
+	    eval "func_echo $func_quote_for_expand_result"
+	  }
+	  $opt_dry_run || eval "$cmd" || {
+	    lt_exit=$?
+
+	    # Restore the uninstalled library and exit
+	    if test "$opt_mode" = relink; then
+	      ( cd "$output_objdir" && \
+	        $RM "${realname}T" && \
+		$MV "${realname}U" "$realname" )
+	    fi
+
+	    exit $lt_exit
+	  }
+	done
+	IFS="$save_ifs"
+
+	# Restore the uninstalled library and exit
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
+
+	  if test -n "$convenience"; then
+	    if test -z "$whole_archive_flag_spec"; then
+	      func_show_eval '${RM}r "$gentop"'
+	    fi
+	  fi
+
+	  exit $EXIT_SUCCESS
+	fi
+
+	# Create links to the real library.
+	for linkname in $linknames; do
+	  if test "$realname" != "$linkname"; then
+	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?'
+	  fi
+	done
+
+	# If -module or -export-dynamic was specified, set the dlname.
+	if test "$module" = yes || test "$export_dynamic" = yes; then
+	  # On all known operating systems, these are identical.
+	  dlname="$soname"
+	fi
+      fi
+      ;;
+
+    obj)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for objects"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for objects" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for objects"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for objects"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for objects"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for objects"
+
+      case $output in
+      *.lo)
+	test -n "$objs$old_deplibs" && \
+	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"
+
+	libobj=$output
+	func_lo2o "$libobj"
+	obj=$func_lo2o_result
+	;;
+      *)
+	libobj=
+	obj="$output"
+	;;
+      esac
+
+      # Delete the old objects.
+      $opt_dry_run || $RM $obj $libobj
+
+      # Objects from convenience libraries.  This assumes
+      # single-version convenience libraries.  Whenever we create
+      # different ones for PIC/non-PIC, this we'll have to duplicate
+      # the extraction.
+      reload_conv_objs=
+      gentop=
+      # reload_cmds runs $LD directly, so let us get rid of
+      # -Wl from whole_archive_flag_spec and hope we can get by with
+      # turning comma into space..
+      wl=
+
+      if test -n "$convenience"; then
+	if test -n "$whole_archive_flag_spec"; then
+	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
+	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
+	else
+	  gentop="$output_objdir/${obj}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $convenience
+	  reload_conv_objs="$reload_objs $func_extract_archives_result"
+	fi
+      fi
+
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+
+      # Create the old-style object.
+      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+      output="$obj"
+      func_execute_cmds "$reload_cmds" 'exit $?'
+
+      # Exit if we aren't doing a library object file.
+      if test -z "$libobj"; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$build_libtool_libs" != yes; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	# Create an invalid libtool object if no PIC, so that we don't
+	# accidentally link it into a program.
+	# $show "echo timestamp > $libobj"
+	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
+	exit $EXIT_SUCCESS
+      fi
+
+      if test -n "$pic_flag" || test "$pic_mode" != default; then
+	# Only do commands if we really have different PIC objects.
+	reload_objs="$libobjs $reload_conv_objs"
+	output="$libobj"
+	func_execute_cmds "$reload_cmds" 'exit $?'
+      fi
+
+      if test -n "$gentop"; then
+	func_show_eval '${RM}r "$gentop"'
+      fi
+
+      exit $EXIT_SUCCESS
+      ;;
+
+    prog)
+      case $host in
+	*cygwin*) func_stripname '' '.exe' "$output"
+	          output=$func_stripname_result.exe;;
+      esac
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for programs"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for programs"
+
+      test "$preload" = yes \
+        && test "$dlopen_support" = unknown \
+	&& test "$dlopen_self" = unknown \
+	&& test "$dlopen_self_static" = unknown && \
+	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."
+
+      case $host in
+      *-*-rhapsody* | *-*-darwin1.[012])
+	# On Rhapsody replace the C library is the System framework
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	;;
+      esac
+
+      case $host in
+      *-*-darwin*)
+	# Don't allow lazy linking, it breaks C++ global constructors
+	# But is supposedly fixed on 10.4 or later (yay!).
+	if test "$tagname" = CXX ; then
+	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
+	    10.[0123])
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
+	    ;;
+	  esac
+	fi
+	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	;;
+      esac
+
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $compile_deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $compile_deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      compile_deplibs="$new_libs"
+
+
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
+
+      if test -n "$rpath$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	for libdir in $rpath $xrpath; do
+	  # This is the magic to use -rpath.
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+      fi
+
+      # Now hardcode the library paths
+      rpath=
+      hardcode_libdirs=
+      for libdir in $compile_rpath $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append perm_rpath " $libdir" ;;
+	  esac
+	fi
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$libdir:"*) ;;
+	  ::) dllsearchpath=$libdir;;
+	  *) func_append dllsearchpath ":$libdir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      compile_rpath="$rpath"
+
+      rpath=
+      hardcode_libdirs=
+      for libdir in $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$finalize_perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
+	  esac
+	fi
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      finalize_rpath="$rpath"
+
+      if test -n "$libobjs" && test "$build_old_libs" = yes; then
+	# Transform all the library objects into standard objects.
+	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+      fi
+
+      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
+
+      # template prelinking step
+      if test -n "$prelink_cmds"; then
+	func_execute_cmds "$prelink_cmds" 'exit $?'
+      fi
+
+      wrappers_required=yes
+      case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
+      *cygwin* | *mingw* )
+        if test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      *)
+        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      esac
+      if test "$wrappers_required" = no; then
+	# Replace the output file specification.
+	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	link_command="$compile_command$compile_rpath"
+
+	# We have no uninstalled library dependencies, so finalize right now.
+	exit_status=0
+	func_show_eval "$link_command" 'exit_status=$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	# Delete the generated files.
+	if test -f "$output_objdir/${outputname}S.${objext}"; then
+	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
+	fi
+
+	exit $exit_status
+      fi
+
+      if test -n "$compile_shlibpath$finalize_shlibpath"; then
+	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+      fi
+      if test -n "$finalize_shlibpath"; then
+	finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+      fi
+
+      compile_var=
+      finalize_var=
+      if test -n "$runpath_var"; then
+	if test -n "$perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+	if test -n "$finalize_perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $finalize_perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+      fi
+
+      if test "$no_install" = yes; then
+	# We don't need to create a wrapper script.
+	link_command="$compile_var$compile_command$compile_rpath"
+	# Replace the output file specification.
+	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	# Delete the old output file.
+	$opt_dry_run || $RM $output
+	# Link the executable and exit
+	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$hardcode_action" = relink; then
+	# Fast installation is not supported
+	link_command="$compile_var$compile_command$compile_rpath"
+	relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+	func_warning "this platform does not like uninstalled shared libraries"
+	func_warning "\`$output' will be relinked during installation"
+      else
+	if test "$fast_install" != no; then
+	  link_command="$finalize_var$compile_command$finalize_rpath"
+	  if test "$fast_install" = yes; then
+	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
+	  else
+	    # fast_install is set to needless
+	    relink_command=
+	  fi
+	else
+	  link_command="$compile_var$compile_command$compile_rpath"
+	  relink_command="$finalize_var$finalize_command$finalize_rpath"
+	fi
+      fi
+
+      # Replace the output file specification.
+      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+      # Delete the old output files.
+      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+      func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
+
+      # Now create the wrapper script.
+      func_verbose "creating $output"
+
+      # Quote the relink command for shipping.
+      if test -n "$relink_command"; then
+	# Preserve any variables that may affect compiler behavior
+	for var in $variables_saved_for_relink; do
+	  if eval test -z \"\${$var+set}\"; then
+	    relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	  elif eval var_value=\$$var; test -z "$var_value"; then
+	    relink_command="$var=; export $var; $relink_command"
+	  else
+	    func_quote_for_eval "$var_value"
+	    relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	  fi
+	done
+	relink_command="(cd `pwd`; $relink_command)"
+	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      fi
+
+      # Only actually do things if not in dry run mode.
+      $opt_dry_run || {
+	# win32 will think the script is a binary if it has
+	# a .exe suffix, so we strip it off here.
+	case $output in
+	  *.exe) func_stripname '' '.exe' "$output"
+	         output=$func_stripname_result ;;
+	esac
+	# test for cygwin because mv fails w/o .exe extensions
+	case $host in
+	  *cygwin*)
+	    exeext=.exe
+	    func_stripname '' '.exe' "$outputname"
+	    outputname=$func_stripname_result ;;
+	  *) exeext= ;;
+	esac
+	case $host in
+	  *cygwin* | *mingw* )
+	    func_dirname_and_basename "$output" "" "."
+	    output_name=$func_basename_result
+	    output_path=$func_dirname_result
+	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
+	    cwrapper="$output_path/$output_name.exe"
+	    $RM $cwrappersource $cwrapper
+	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_cwrapperexe_src > $cwrappersource
+
+	    # The wrapper executable is built using the $host compiler,
+	    # because it contains $host paths and files. If cross-
+	    # compiling, it, like the target executable, must be
+	    # executed on the $host or under an emulation environment.
+	    $opt_dry_run || {
+	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
+	      $STRIP $cwrapper
+	    }
+
+	    # Now, create the wrapper script for func_source use:
+	    func_ltwrapper_scriptname $cwrapper
+	    $RM $func_ltwrapper_scriptname_result
+	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
+	    $opt_dry_run || {
+	      # note: this script will not be executed, so do not chmod.
+	      if test "x$build" = "x$host" ; then
+		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
+	      else
+		func_emit_wrapper no > $func_ltwrapper_scriptname_result
+	      fi
+	    }
+	  ;;
+	  * )
+	    $RM $output
+	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_wrapper no > $output
+	    chmod +x $output
+	  ;;
+	esac
+      }
+      exit $EXIT_SUCCESS
+      ;;
+    esac
+
+    # See if we need to build an old-fashioned archive.
+    for oldlib in $oldlibs; do
+
+      if test "$build_libtool_libs" = convenience; then
+	oldobjs="$libobjs_save $symfileobj"
+	addlibs="$convenience"
+	build_libtool_libs=no
+      else
+	if test "$build_libtool_libs" = module; then
+	  oldobjs="$libobjs_save"
+	  build_libtool_libs=no
+	else
+	  oldobjs="$old_deplibs $non_pic_objects"
+	  if test "$preload" = yes && test -f "$symfileobj"; then
+	    func_append oldobjs " $symfileobj"
+	  fi
+	fi
+	addlibs="$old_convenience"
+      fi
+
+      if test -n "$addlibs"; then
+	gentop="$output_objdir/${outputname}x"
+	func_append generated " $gentop"
+
+	func_extract_archives $gentop $addlibs
+	func_append oldobjs " $func_extract_archives_result"
+      fi
+
+      # Do each command in the archive commands.
+      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+	cmds=$old_archive_from_new_cmds
+      else
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append oldobjs " $func_extract_archives_result"
+	fi
+
+	# POSIX demands no paths to be encoded in archives.  We have
+	# to avoid creating archives with duplicate basenames if we
+	# might have to extract them afterwards, e.g., when creating a
+	# static archive out of a convenience library, or when linking
+	# the entirety of a libtool archive into another (currently
+	# not supported by libtool).
+	if (for obj in $oldobjs
+	    do
+	      func_basename "$obj"
+	      $ECHO "$func_basename_result"
+	    done | sort | sort -uc >/dev/null 2>&1); then
+	  :
+	else
+	  echo "copying selected object files to avoid basename conflicts..."
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+	  func_mkdir_p "$gentop"
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  counter=1
+	  for obj in $save_oldobjs
+	  do
+	    func_basename "$obj"
+	    objbase="$func_basename_result"
+	    case " $oldobjs " in
+	    " ") oldobjs=$obj ;;
+	    *[\ /]"$objbase "*)
+	      while :; do
+		# Make sure we don't pick an alternate name that also
+		# overlaps.
+		newobj=lt$counter-$objbase
+		func_arith $counter + 1
+		counter=$func_arith_result
+		case " $oldobjs " in
+		*[\ /]"$newobj "*) ;;
+		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
+		esac
+	      done
+	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
+	      ;;
+	    *) func_append oldobjs " $obj" ;;
+	    esac
+	  done
+	fi
+	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+	tool_oldlib=$func_to_tool_file_result
+	eval cmds=\"$old_archive_cmds\"
+
+	func_len " $cmds"
+	len=$func_len_result
+	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
+	  cmds=$old_archive_cmds
+	else
+	  # the command line is too long to link in one step, link in parts
+	  func_verbose "using piecewise archive linking..."
+	  save_RANLIB=$RANLIB
+	  RANLIB=:
+	  objlist=
+	  concat_cmds=
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  # Is there a better way of finding the last object in the list?
+	  for obj in $save_oldobjs
+	  do
+	    last_oldobj=$obj
+	  done
+	  eval test_cmds=\"$old_archive_cmds\"
+	  func_len " $test_cmds"
+	  len0=$func_len_result
+	  len=$len0
+	  for obj in $save_oldobjs
+	  do
+	    func_len " $obj"
+	    func_arith $len + $func_len_result
+	    len=$func_arith_result
+	    func_append objlist " $obj"
+	    if test "$len" -lt "$max_cmd_len"; then
+	      :
+	    else
+	      # the above command should be used before it gets too long
+	      oldobjs=$objlist
+	      if test "$obj" = "$last_oldobj" ; then
+		RANLIB=$save_RANLIB
+	      fi
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+	      objlist=
+	      len=$len0
+	    fi
+	  done
+	  RANLIB=$save_RANLIB
+	  oldobjs=$objlist
+	  if test "X$oldobjs" = "X" ; then
+	    eval cmds=\"\$concat_cmds\"
+	  else
+	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+	  fi
+	fi
+      fi
+      func_execute_cmds "$cmds" 'exit $?'
+    done
+
+    test -n "$generated" && \
+      func_show_eval "${RM}r$generated"
+
+    # Now create the libtool archive.
+    case $output in
+    *.la)
+      old_library=
+      test "$build_old_libs" = yes && old_library="$libname.$libext"
+      func_verbose "creating $output"
+
+      # Preserve any variables that may affect compiler behavior
+      for var in $variables_saved_for_relink; do
+	if eval test -z \"\${$var+set}\"; then
+	  relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	elif eval var_value=\$$var; test -z "$var_value"; then
+	  relink_command="$var=; export $var; $relink_command"
+	else
+	  func_quote_for_eval "$var_value"
+	  relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	fi
+      done
+      # Quote the link command for shipping.
+      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      if test "$hardcode_automatic" = yes ; then
+	relink_command=
+      fi
+
+      # Only create the output if not a dry run.
+      $opt_dry_run || {
+	for installed in no yes; do
+	  if test "$installed" = yes; then
+	    if test -z "$install_libdir"; then
+	      break
+	    fi
+	    output="$output_objdir/$outputname"i
+	    # Replace all uninstalled libtool libraries with the installed ones
+	    newdependency_libs=
+	    for deplib in $dependency_libs; do
+	      case $deplib in
+	      *.la)
+		func_basename "$deplib"
+		name="$func_basename_result"
+		func_resolve_sysroot "$deplib"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
+	      esac
+	    done
+	    dependency_libs="$newdependency_libs"
+	    newdlfiles=
+
+	    for lib in $dlfiles; do
+	      case $lib in
+	      *.la)
+	        func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      *) func_append newdlfiles " $lib" ;;
+	      esac
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+	      *.la)
+		# Only pass preopened files to the pseudo-archive (for
+		# eventual linking with the app. that links it) if we
+		# didn't already link the preopened objects directly into
+		# the library:
+		func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      esac
+	    done
+	    dlprefiles="$newdlprefiles"
+	  else
+	    newdlfiles=
+	    for lib in $dlfiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlfiles " $abs"
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlprefiles " $abs"
+	    done
+	    dlprefiles="$newdlprefiles"
+	  fi
+	  $RM $output
+	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
+	  tdlname=$dlname
+	  case $host,$output,$installed,$module,$dlname in
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" != x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=../bin/$dlname
+	      fi
+	      ;;
+	  esac
+	  $ECHO > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Linker flags that can not go in dependency_libs.
+inherited_linker_flags='$new_inherited_linker_flags'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Names of additional weak libraries provided by this library
+weak_library_names='$weak_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+	  if test "$installed" = no && test "$need_relink" = yes; then
+	    $ECHO >> $output "\
+relink_command=\"$relink_command\""
+	  fi
+	done
+      }
+
+      # Do a symbolic link so that the libtool archive can be found in
+      # LD_LIBRARY_PATH before the program is installed.
+      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?'
+      ;;
+    esac
+    exit $EXIT_SUCCESS
+}
+
+{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
+    func_mode_link ${1+"$@"}
+
+
+# func_mode_uninstall arg...
+func_mode_uninstall ()
+{
+    $opt_debug
+    RM="$nonopt"
+    files=
+    rmforce=
+    exit_status=0
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    for arg
+    do
+      case $arg in
+      -f) func_append RM " $arg"; rmforce=yes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
+      esac
+    done
+
+    test -z "$RM" && \
+      func_fatal_help "you must specify an RM program"
+
+    rmdirs=
+
+    for file in $files; do
+      func_dirname "$file" "" "."
+      dir="$func_dirname_result"
+      if test "X$dir" = X.; then
+	odir="$objdir"
+      else
+	odir="$dir/$objdir"
+      fi
+      func_basename "$file"
+      name="$func_basename_result"
+      test "$opt_mode" = uninstall && odir="$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" = clean; then
+	case " $rmdirs " in
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
+	esac
+      fi
+
+      # Don't error if the file doesn't exist and rm -f was used.
+      if { test -L "$file"; } >/dev/null 2>&1 ||
+	 { test -h "$file"; } >/dev/null 2>&1 ||
+	 test -f "$file"; then
+	:
+      elif test -d "$file"; then
+	exit_status=1
+	continue
+      elif test "$rmforce" = yes; then
+	continue
+      fi
+
+      rmfiles="$file"
+
+      case $name in
+      *.la)
+	# Possibly a libtool archive, so verify it.
+	if func_lalib_p "$file"; then
+	  func_source $dir/$name
+
+	  # Delete the libtool libraries and symlinks.
+	  for n in $library_names; do
+	    func_append rmfiles " $odir/$n"
+	  done
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
+	  clean)
+	    case " $library_names " in
+	    *" $dlname "*) ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
+	    esac
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
+	    ;;
+	  uninstall)
+	    if test -n "$library_names"; then
+	      # Do each command in the postuninstall commands.
+	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+
+	    if test -n "$old_library"; then
+	      # Do each command in the old_postuninstall commands.
+	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+	    # FIXME: should reinstall the best remaining shared library.
+	    ;;
+	  esac
+	fi
+	;;
+
+      *.lo)
+	# Possibly a libtool object, so verify it.
+	if func_lalib_p "$file"; then
+
+	  # Read the .lo file
+	  func_source $dir/$name
+
+	  # Add PIC object to the list of files to remove.
+	  if test -n "$pic_object" &&
+	     test "$pic_object" != none; then
+	    func_append rmfiles " $dir/$pic_object"
+	  fi
+
+	  # Add non-PIC object to the list of files to remove.
+	  if test -n "$non_pic_object" &&
+	     test "$non_pic_object" != none; then
+	    func_append rmfiles " $dir/$non_pic_object"
+	  fi
+	fi
+	;;
+
+      *)
+	if test "$opt_mode" = clean ; then
+	  noexename=$name
+	  case $file in
+	  *.exe)
+	    func_stripname '' '.exe' "$file"
+	    file=$func_stripname_result
+	    func_stripname '' '.exe' "$name"
+	    noexename=$func_stripname_result
+	    # $file with .exe has already been added to rmfiles,
+	    # add $file without .exe
+	    func_append rmfiles " $file"
+	    ;;
+	  esac
+	  # Do a test to see if this is a libtool program.
+	  if func_ltwrapper_p "$file"; then
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      relink_command=
+	      func_source $func_ltwrapper_scriptname_result
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
+	    else
+	      relink_command=
+	      func_source $dir/$noexename
+	    fi
+
+	    # note $name still contains .exe if it was in $file originally
+	    # as does the version of $file that was added into $rmfiles
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
+	    if test "$fast_install" = yes && test -n "$relink_command"; then
+	      func_append rmfiles " $odir/lt-$name"
+	    fi
+	    if test "X$noexename" != "X$name" ; then
+	      func_append rmfiles " $odir/lt-${noexename}.c"
+	    fi
+	  fi
+	fi
+	;;
+      esac
+      func_show_eval "$RM $rmfiles" 'exit_status=1'
+    done
+
+    # Try to remove the ${objdir}s in the directories where we deleted files
+    for dir in $rmdirs; do
+      if test -d "$dir"; then
+	func_show_eval "rmdir $dir >/dev/null 2>&1"
+      fi
+    done
+
+    exit $exit_status
+}
+
+{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
+    func_mode_uninstall ${1+"$@"}
+
+test -z "$opt_mode" && {
+  help="$generic_help"
+  func_fatal_help "you must specify a MODE"
+}
+
+test -z "$exec_cmd" && \
+  func_fatal_help "invalid operation mode \`$opt_mode'"
+
+if test -n "$exec_cmd"; then
+  eval exec "$exec_cmd"
+  exit $EXIT_FAILURE
+fi
+
+exit $exit_status
+
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries.  Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them.  This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration.  But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+build_libtool_libs=no
+build_old_libs=yes
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
+# vi:sw=2
+
Index: /issm/branches/trunk-jpl-ad2-integrated/m4/analyses.m4
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/m4/analyses.m4	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/m4/analyses.m4	(revision 18231)
@@ -0,0 +1,475 @@
+
+dnl   WARNING: DO NOT MODIFY THIS FILE
+dnl            this file has been automatically generated by Synchronize.sh
+dnl            Please read README for more information
+
+# AX_ANALYSES_SELECTION
+# -----------------
+# Check for analyses compilation
+AC_DEFUN([AX_ANALYSES_SELECTION],
+[
+
+dnl with-AdjointBalancethickness{{{
+AC_ARG_WITH([AdjointBalancethickness],
+	AS_HELP_STRING([--with-AdjointBalancethickness = YES], [compile with AdjointBalancethickness capabilities (default is yes)]),
+	[ADJOINTBALANCETHICKNESS=$withval],[ADJOINTBALANCETHICKNESS=yes])
+AC_MSG_CHECKING(for AdjointBalancethickness capability compilation)
+
+HAVE_ADJOINTBALANCETHICKNESS=no 
+if test "x$ADJOINTBALANCETHICKNESS" = "xyes"; then
+	HAVE_ADJOINTBALANCETHICKNESS=yes
+	AC_DEFINE([_HAVE_ADJOINTBALANCETHICKNESS_],[1],[with AdjointBalancethicknesscapability])
+fi
+AM_CONDITIONAL([ADJOINTBALANCETHICKNESS], [test x$HAVE_ADJOINTBALANCETHICKNESS = xyes])
+AC_MSG_RESULT($HAVE_ADJOINTBALANCETHICKNESS)
+dnl }}}
+dnl with-AdjointBalancethickness2{{{
+AC_ARG_WITH([AdjointBalancethickness2],
+	AS_HELP_STRING([--with-AdjointBalancethickness2 = YES], [compile with AdjointBalancethickness2 capabilities (default is yes)]),
+	[ADJOINTBALANCETHICKNESS2=$withval],[ADJOINTBALANCETHICKNESS2=yes])
+AC_MSG_CHECKING(for AdjointBalancethickness2 capability compilation)
+
+HAVE_ADJOINTBALANCETHICKNESS2=no 
+if test "x$ADJOINTBALANCETHICKNESS2" = "xyes"; then
+	HAVE_ADJOINTBALANCETHICKNESS2=yes
+	AC_DEFINE([_HAVE_ADJOINTBALANCETHICKNESS2_],[1],[with AdjointBalancethickness2capability])
+fi
+AM_CONDITIONAL([ADJOINTBALANCETHICKNESS2], [test x$HAVE_ADJOINTBALANCETHICKNESS2 = xyes])
+AC_MSG_RESULT($HAVE_ADJOINTBALANCETHICKNESS2)
+dnl }}}
+dnl with-AdjointHoriz{{{
+AC_ARG_WITH([AdjointHoriz],
+	AS_HELP_STRING([--with-AdjointHoriz = YES], [compile with AdjointHoriz capabilities (default is yes)]),
+	[ADJOINTHORIZ=$withval],[ADJOINTHORIZ=yes])
+AC_MSG_CHECKING(for AdjointHoriz capability compilation)
+
+HAVE_ADJOINTHORIZ=no 
+if test "x$ADJOINTHORIZ" = "xyes"; then
+	HAVE_ADJOINTHORIZ=yes
+	AC_DEFINE([_HAVE_ADJOINTHORIZ_],[1],[with AdjointHorizcapability])
+fi
+AM_CONDITIONAL([ADJOINTHORIZ], [test x$HAVE_ADJOINTHORIZ = xyes])
+AC_MSG_RESULT($HAVE_ADJOINTHORIZ)
+dnl }}}
+dnl with-Balancethickness{{{
+AC_ARG_WITH([Balancethickness],
+	AS_HELP_STRING([--with-Balancethickness = YES], [compile with Balancethickness capabilities (default is yes)]),
+	[BALANCETHICKNESS=$withval],[BALANCETHICKNESS=yes])
+AC_MSG_CHECKING(for Balancethickness capability compilation)
+
+HAVE_BALANCETHICKNESS=no 
+if test "x$BALANCETHICKNESS" = "xyes"; then
+	HAVE_BALANCETHICKNESS=yes
+	AC_DEFINE([_HAVE_BALANCETHICKNESS_],[1],[with Balancethicknesscapability])
+fi
+AM_CONDITIONAL([BALANCETHICKNESS], [test x$HAVE_BALANCETHICKNESS = xyes])
+AC_MSG_RESULT($HAVE_BALANCETHICKNESS)
+dnl }}}
+dnl with-Balancethickness2{{{
+AC_ARG_WITH([Balancethickness2],
+	AS_HELP_STRING([--with-Balancethickness2 = YES], [compile with Balancethickness2 capabilities (default is yes)]),
+	[BALANCETHICKNESS2=$withval],[BALANCETHICKNESS2=yes])
+AC_MSG_CHECKING(for Balancethickness2 capability compilation)
+
+HAVE_BALANCETHICKNESS2=no 
+if test "x$BALANCETHICKNESS2" = "xyes"; then
+	HAVE_BALANCETHICKNESS2=yes
+	AC_DEFINE([_HAVE_BALANCETHICKNESS2_],[1],[with Balancethickness2capability])
+fi
+AM_CONDITIONAL([BALANCETHICKNESS2], [test x$HAVE_BALANCETHICKNESS2 = xyes])
+AC_MSG_RESULT($HAVE_BALANCETHICKNESS2)
+dnl }}}
+dnl with-BalancethicknessSoft{{{
+AC_ARG_WITH([BalancethicknessSoft],
+	AS_HELP_STRING([--with-BalancethicknessSoft = YES], [compile with BalancethicknessSoft capabilities (default is yes)]),
+	[BALANCETHICKNESSSOFT=$withval],[BALANCETHICKNESSSOFT=yes])
+AC_MSG_CHECKING(for BalancethicknessSoft capability compilation)
+
+HAVE_BALANCETHICKNESSSOFT=no 
+if test "x$BALANCETHICKNESSSOFT" = "xyes"; then
+	HAVE_BALANCETHICKNESSSOFT=yes
+	AC_DEFINE([_HAVE_BALANCETHICKNESSSOFT_],[1],[with BalancethicknessSoftcapability])
+fi
+AM_CONDITIONAL([BALANCETHICKNESSSOFT], [test x$HAVE_BALANCETHICKNESSSOFT = xyes])
+AC_MSG_RESULT($HAVE_BALANCETHICKNESSSOFT)
+dnl }}}
+dnl with-Balancevelocity{{{
+AC_ARG_WITH([Balancevelocity],
+	AS_HELP_STRING([--with-Balancevelocity = YES], [compile with Balancevelocity capabilities (default is yes)]),
+	[BALANCEVELOCITY=$withval],[BALANCEVELOCITY=yes])
+AC_MSG_CHECKING(for Balancevelocity capability compilation)
+
+HAVE_BALANCEVELOCITY=no 
+if test "x$BALANCEVELOCITY" = "xyes"; then
+	HAVE_BALANCEVELOCITY=yes
+	AC_DEFINE([_HAVE_BALANCEVELOCITY_],[1],[with Balancevelocitycapability])
+fi
+AM_CONDITIONAL([BALANCEVELOCITY], [test x$HAVE_BALANCEVELOCITY = xyes])
+AC_MSG_RESULT($HAVE_BALANCEVELOCITY)
+dnl }}}
+dnl with-L2ProjectionEPL{{{
+AC_ARG_WITH([L2ProjectionEPL],
+	AS_HELP_STRING([--with-L2ProjectionEPL = YES], [compile with L2ProjectionEPL capabilities (default is yes)]),
+	[L2PROJECTIONEPL=$withval],[L2PROJECTIONEPL=yes])
+AC_MSG_CHECKING(for L2ProjectionEPL capability compilation)
+
+HAVE_L2PROJECTIONEPL=no 
+if test "x$L2PROJECTIONEPL" = "xyes"; then
+	HAVE_L2PROJECTIONEPL=yes
+	AC_DEFINE([_HAVE_L2PROJECTIONEPL_],[1],[with L2ProjectionEPLcapability])
+fi
+AM_CONDITIONAL([L2PROJECTIONEPL], [test x$HAVE_L2PROJECTIONEPL = xyes])
+AC_MSG_RESULT($HAVE_L2PROJECTIONEPL)
+dnl }}}
+dnl with-L2ProjectionBase{{{
+AC_ARG_WITH([L2ProjectionBase],
+	AS_HELP_STRING([--with-L2ProjectionBase = YES], [compile with L2ProjectionBase capabilities (default is yes)]),
+	[L2PROJECTIONBASE=$withval],[L2PROJECTIONBASE=yes])
+AC_MSG_CHECKING(for L2ProjectionBase capability compilation)
+
+HAVE_L2PROJECTIONBASE=no 
+if test "x$L2PROJECTIONBASE" = "xyes"; then
+	HAVE_L2PROJECTIONBASE=yes
+	AC_DEFINE([_HAVE_L2PROJECTIONBASE_],[1],[with L2ProjectionBasecapability])
+fi
+AM_CONDITIONAL([L2PROJECTIONBASE], [test x$HAVE_L2PROJECTIONBASE = xyes])
+AC_MSG_RESULT($HAVE_L2PROJECTIONBASE)
+dnl }}}
+dnl with-DamageEvolution{{{
+AC_ARG_WITH([DamageEvolution],
+	AS_HELP_STRING([--with-DamageEvolution = YES], [compile with DamageEvolution capabilities (default is yes)]),
+	[DAMAGEEVOLUTION=$withval],[DAMAGEEVOLUTION=yes])
+AC_MSG_CHECKING(for DamageEvolution capability compilation)
+
+HAVE_DAMAGEEVOLUTION=no 
+if test "x$DAMAGEEVOLUTION" = "xyes"; then
+	HAVE_DAMAGEEVOLUTION=yes
+	AC_DEFINE([_HAVE_DAMAGEEVOLUTION_],[1],[with DamageEvolutioncapability])
+fi
+AM_CONDITIONAL([DAMAGEEVOLUTION], [test x$HAVE_DAMAGEEVOLUTION = xyes])
+AC_MSG_RESULT($HAVE_DAMAGEEVOLUTION)
+dnl }}}
+dnl with-Stressbalance{{{
+AC_ARG_WITH([Stressbalance],
+	AS_HELP_STRING([--with-Stressbalance = YES], [compile with Stressbalance capabilities (default is yes)]),
+	[STRESSBALANCE=$withval],[STRESSBALANCE=yes])
+AC_MSG_CHECKING(for Stressbalance capability compilation)
+
+HAVE_STRESSBALANCE=no 
+if test "x$STRESSBALANCE" = "xyes"; then
+	HAVE_STRESSBALANCE=yes
+	AC_DEFINE([_HAVE_STRESSBALANCE_],[1],[with Stressbalancecapability])
+fi
+AM_CONDITIONAL([STRESSBALANCE], [test x$HAVE_STRESSBALANCE = xyes])
+AC_MSG_RESULT($HAVE_STRESSBALANCE)
+dnl }}}
+dnl with-StressbalanceSIA{{{
+AC_ARG_WITH([StressbalanceSIA],
+	AS_HELP_STRING([--with-StressbalanceSIA = YES], [compile with StressbalanceSIA capabilities (default is yes)]),
+	[STRESSBALANCESIA=$withval],[STRESSBALANCESIA=yes])
+AC_MSG_CHECKING(for StressbalanceSIA capability compilation)
+
+HAVE_STRESSBALANCESIA=no 
+if test "x$STRESSBALANCESIA" = "xyes"; then
+	HAVE_STRESSBALANCESIA=yes
+	AC_DEFINE([_HAVE_STRESSBALANCESIA_],[1],[with StressbalanceSIAcapability])
+fi
+AM_CONDITIONAL([STRESSBALANCESIA], [test x$HAVE_STRESSBALANCESIA = xyes])
+AC_MSG_RESULT($HAVE_STRESSBALANCESIA)
+dnl }}}
+dnl with-StressbalanceVertical{{{
+AC_ARG_WITH([StressbalanceVertical],
+	AS_HELP_STRING([--with-StressbalanceVertical = YES], [compile with StressbalanceVertical capabilities (default is yes)]),
+	[STRESSBALANCEVERTICAL=$withval],[STRESSBALANCEVERTICAL=yes])
+AC_MSG_CHECKING(for StressbalanceVertical capability compilation)
+
+HAVE_STRESSBALANCEVERTICAL=no 
+if test "x$STRESSBALANCEVERTICAL" = "xyes"; then
+	HAVE_STRESSBALANCEVERTICAL=yes
+	AC_DEFINE([_HAVE_STRESSBALANCEVERTICAL_],[1],[with StressbalanceVerticalcapability])
+fi
+AM_CONDITIONAL([STRESSBALANCEVERTICAL], [test x$HAVE_STRESSBALANCEVERTICAL = xyes])
+AC_MSG_RESULT($HAVE_STRESSBALANCEVERTICAL)
+dnl }}}
+dnl with-Enthalpy{{{
+AC_ARG_WITH([Enthalpy],
+	AS_HELP_STRING([--with-Enthalpy = YES], [compile with Enthalpy capabilities (default is yes)]),
+	[ENTHALPY=$withval],[ENTHALPY=yes])
+AC_MSG_CHECKING(for Enthalpy capability compilation)
+
+HAVE_ENTHALPY=no 
+if test "x$ENTHALPY" = "xyes"; then
+	HAVE_ENTHALPY=yes
+	AC_DEFINE([_HAVE_ENTHALPY_],[1],[with Enthalpycapability])
+fi
+AM_CONDITIONAL([ENTHALPY], [test x$HAVE_ENTHALPY = xyes])
+AC_MSG_RESULT($HAVE_ENTHALPY)
+dnl }}}
+dnl with-HydrologyShreve{{{
+AC_ARG_WITH([HydrologyShreve],
+	AS_HELP_STRING([--with-HydrologyShreve = YES], [compile with HydrologyShreve capabilities (default is yes)]),
+	[HYDROLOGYSHREVE=$withval],[HYDROLOGYSHREVE=yes])
+AC_MSG_CHECKING(for HydrologyShreve capability compilation)
+
+HAVE_HYDROLOGYSHREVE=no 
+if test "x$HYDROLOGYSHREVE" = "xyes"; then
+	HAVE_HYDROLOGYSHREVE=yes
+	AC_DEFINE([_HAVE_HYDROLOGYSHREVE_],[1],[with HydrologyShrevecapability])
+fi
+AM_CONDITIONAL([HYDROLOGYSHREVE], [test x$HAVE_HYDROLOGYSHREVE = xyes])
+AC_MSG_RESULT($HAVE_HYDROLOGYSHREVE)
+dnl }}}
+dnl with-HydrologyDCInefficient{{{
+AC_ARG_WITH([HydrologyDCInefficient],
+	AS_HELP_STRING([--with-HydrologyDCInefficient = YES], [compile with HydrologyDCInefficient capabilities (default is yes)]),
+	[HYDROLOGYDCINEFFICIENT=$withval],[HYDROLOGYDCINEFFICIENT=yes])
+AC_MSG_CHECKING(for HydrologyDCInefficient capability compilation)
+
+HAVE_HYDROLOGYDCINEFFICIENT=no 
+if test "x$HYDROLOGYDCINEFFICIENT" = "xyes"; then
+	HAVE_HYDROLOGYDCINEFFICIENT=yes
+	AC_DEFINE([_HAVE_HYDROLOGYDCINEFFICIENT_],[1],[with HydrologyDCInefficientcapability])
+fi
+AM_CONDITIONAL([HYDROLOGYDCINEFFICIENT], [test x$HAVE_HYDROLOGYDCINEFFICIENT = xyes])
+AC_MSG_RESULT($HAVE_HYDROLOGYDCINEFFICIENT)
+dnl }}}
+dnl with-HydrologyDCEfficient{{{
+AC_ARG_WITH([HydrologyDCEfficient],
+	AS_HELP_STRING([--with-HydrologyDCEfficient = YES], [compile with HydrologyDCEfficient capabilities (default is yes)]),
+	[HYDROLOGYDCEFFICIENT=$withval],[HYDROLOGYDCEFFICIENT=yes])
+AC_MSG_CHECKING(for HydrologyDCEfficient capability compilation)
+
+HAVE_HYDROLOGYDCEFFICIENT=no 
+if test "x$HYDROLOGYDCEFFICIENT" = "xyes"; then
+	HAVE_HYDROLOGYDCEFFICIENT=yes
+	AC_DEFINE([_HAVE_HYDROLOGYDCEFFICIENT_],[1],[with HydrologyDCEfficientcapability])
+fi
+AM_CONDITIONAL([HYDROLOGYDCEFFICIENT], [test x$HAVE_HYDROLOGYDCEFFICIENT = xyes])
+AC_MSG_RESULT($HAVE_HYDROLOGYDCEFFICIENT)
+dnl }}}
+dnl with-Melting{{{
+AC_ARG_WITH([Melting],
+	AS_HELP_STRING([--with-Melting = YES], [compile with Melting capabilities (default is yes)]),
+	[MELTING=$withval],[MELTING=yes])
+AC_MSG_CHECKING(for Melting capability compilation)
+
+HAVE_MELTING=no 
+if test "x$MELTING" = "xyes"; then
+	HAVE_MELTING=yes
+	AC_DEFINE([_HAVE_MELTING_],[1],[with Meltingcapability])
+fi
+AM_CONDITIONAL([MELTING], [test x$HAVE_MELTING = xyes])
+AC_MSG_RESULT($HAVE_MELTING)
+dnl }}}
+dnl with-Masstransport{{{
+AC_ARG_WITH([Masstransport],
+	AS_HELP_STRING([--with-Masstransport = YES], [compile with Masstransport capabilities (default is yes)]),
+	[MASSTRANSPORT=$withval],[MASSTRANSPORT=yes])
+AC_MSG_CHECKING(for Masstransport capability compilation)
+
+HAVE_MASSTRANSPORT=no 
+if test "x$MASSTRANSPORT" = "xyes"; then
+	HAVE_MASSTRANSPORT=yes
+	AC_DEFINE([_HAVE_MASSTRANSPORT_],[1],[with Masstransportcapability])
+fi
+AM_CONDITIONAL([MASSTRANSPORT], [test x$HAVE_MASSTRANSPORT = xyes])
+AC_MSG_RESULT($HAVE_MASSTRANSPORT)
+dnl }}}
+dnl with-FreeSurfaceBase{{{
+AC_ARG_WITH([FreeSurfaceBase],
+	AS_HELP_STRING([--with-FreeSurfaceBase = YES], [compile with FreeSurfaceBase capabilities (default is yes)]),
+	[FREESURFACEBASE=$withval],[FREESURFACEBASE=yes])
+AC_MSG_CHECKING(for FreeSurfaceBase capability compilation)
+
+HAVE_FREESURFACEBASE=no 
+if test "x$FREESURFACEBASE" = "xyes"; then
+	HAVE_FREESURFACEBASE=yes
+	AC_DEFINE([_HAVE_FREESURFACEBASE_],[1],[with FreeSurfaceBasecapability])
+fi
+AM_CONDITIONAL([FREESURFACEBASE], [test x$HAVE_FREESURFACEBASE = xyes])
+AC_MSG_RESULT($HAVE_FREESURFACEBASE)
+dnl }}}
+dnl with-FreeSurfaceTop{{{
+AC_ARG_WITH([FreeSurfaceTop],
+	AS_HELP_STRING([--with-FreeSurfaceTop = YES], [compile with FreeSurfaceTop capabilities (default is yes)]),
+	[FREESURFACETOP=$withval],[FREESURFACETOP=yes])
+AC_MSG_CHECKING(for FreeSurfaceTop capability compilation)
+
+HAVE_FREESURFACETOP=no 
+if test "x$FREESURFACETOP" = "xyes"; then
+	HAVE_FREESURFACETOP=yes
+	AC_DEFINE([_HAVE_FREESURFACETOP_],[1],[with FreeSurfaceTopcapability])
+fi
+AM_CONDITIONAL([FREESURFACETOP], [test x$HAVE_FREESURFACETOP = xyes])
+AC_MSG_RESULT($HAVE_FREESURFACETOP)
+dnl }}}
+dnl with-ExtrudeFromBase{{{
+AC_ARG_WITH([ExtrudeFromBase],
+	AS_HELP_STRING([--with-ExtrudeFromBase = YES], [compile with ExtrudeFromBase capabilities (default is yes)]),
+	[EXTRUDEFROMBASE=$withval],[EXTRUDEFROMBASE=yes])
+AC_MSG_CHECKING(for ExtrudeFromBase capability compilation)
+
+HAVE_EXTRUDEFROMBASE=no 
+if test "x$EXTRUDEFROMBASE" = "xyes"; then
+	HAVE_EXTRUDEFROMBASE=yes
+	AC_DEFINE([_HAVE_EXTRUDEFROMBASE_],[1],[with ExtrudeFromBasecapability])
+fi
+AM_CONDITIONAL([EXTRUDEFROMBASE], [test x$HAVE_EXTRUDEFROMBASE = xyes])
+AC_MSG_RESULT($HAVE_EXTRUDEFROMBASE)
+dnl }}}
+dnl with-ExtrudeFromTop{{{
+AC_ARG_WITH([ExtrudeFromTop],
+	AS_HELP_STRING([--with-ExtrudeFromTop = YES], [compile with ExtrudeFromTop capabilities (default is yes)]),
+	[EXTRUDEFROMTOP=$withval],[EXTRUDEFROMTOP=yes])
+AC_MSG_CHECKING(for ExtrudeFromTop capability compilation)
+
+HAVE_EXTRUDEFROMTOP=no 
+if test "x$EXTRUDEFROMTOP" = "xyes"; then
+	HAVE_EXTRUDEFROMTOP=yes
+	AC_DEFINE([_HAVE_EXTRUDEFROMTOP_],[1],[with ExtrudeFromTopcapability])
+fi
+AM_CONDITIONAL([EXTRUDEFROMTOP], [test x$HAVE_EXTRUDEFROMTOP = xyes])
+AC_MSG_RESULT($HAVE_EXTRUDEFROMTOP)
+dnl }}}
+dnl with-DepthAverage{{{
+AC_ARG_WITH([DepthAverage],
+	AS_HELP_STRING([--with-DepthAverage = YES], [compile with DepthAverage capabilities (default is yes)]),
+	[DEPTHAVERAGE=$withval],[DEPTHAVERAGE=yes])
+AC_MSG_CHECKING(for DepthAverage capability compilation)
+
+HAVE_DEPTHAVERAGE=no 
+if test "x$DEPTHAVERAGE" = "xyes"; then
+	HAVE_DEPTHAVERAGE=yes
+	AC_DEFINE([_HAVE_DEPTHAVERAGE_],[1],[with DepthAveragecapability])
+fi
+AM_CONDITIONAL([DEPTHAVERAGE], [test x$HAVE_DEPTHAVERAGE = xyes])
+AC_MSG_RESULT($HAVE_DEPTHAVERAGE)
+dnl }}}
+dnl with-SmoothedSurfaceSlopeX{{{
+AC_ARG_WITH([SmoothedSurfaceSlopeX],
+	AS_HELP_STRING([--with-SmoothedSurfaceSlopeX = YES], [compile with SmoothedSurfaceSlopeX capabilities (default is yes)]),
+	[SMOOTHEDSURFACESLOPEX=$withval],[SMOOTHEDSURFACESLOPEX=yes])
+AC_MSG_CHECKING(for SmoothedSurfaceSlopeX capability compilation)
+
+HAVE_SMOOTHEDSURFACESLOPEX=no 
+if test "x$SMOOTHEDSURFACESLOPEX" = "xyes"; then
+	HAVE_SMOOTHEDSURFACESLOPEX=yes
+	AC_DEFINE([_HAVE_SMOOTHEDSURFACESLOPEX_],[1],[with SmoothedSurfaceSlopeXcapability])
+fi
+AM_CONDITIONAL([SMOOTHEDSURFACESLOPEX], [test x$HAVE_SMOOTHEDSURFACESLOPEX = xyes])
+AC_MSG_RESULT($HAVE_SMOOTHEDSURFACESLOPEX)
+dnl }}}
+dnl with-SmoothedSurfaceSlopeY{{{
+AC_ARG_WITH([SmoothedSurfaceSlopeY],
+	AS_HELP_STRING([--with-SmoothedSurfaceSlopeY = YES], [compile with SmoothedSurfaceSlopeY capabilities (default is yes)]),
+	[SMOOTHEDSURFACESLOPEY=$withval],[SMOOTHEDSURFACESLOPEY=yes])
+AC_MSG_CHECKING(for SmoothedSurfaceSlopeY capability compilation)
+
+HAVE_SMOOTHEDSURFACESLOPEY=no 
+if test "x$SMOOTHEDSURFACESLOPEY" = "xyes"; then
+	HAVE_SMOOTHEDSURFACESLOPEY=yes
+	AC_DEFINE([_HAVE_SMOOTHEDSURFACESLOPEY_],[1],[with SmoothedSurfaceSlopeYcapability])
+fi
+AM_CONDITIONAL([SMOOTHEDSURFACESLOPEY], [test x$HAVE_SMOOTHEDSURFACESLOPEY = xyes])
+AC_MSG_RESULT($HAVE_SMOOTHEDSURFACESLOPEY)
+dnl }}}
+dnl with-UzawaPressure{{{
+AC_ARG_WITH([UzawaPressure],
+	AS_HELP_STRING([--with-UzawaPressure = YES], [compile with UzawaPressure capabilities (default is yes)]),
+	[UZAWAPRESSURE=$withval],[UZAWAPRESSURE=yes])
+AC_MSG_CHECKING(for UzawaPressure capability compilation)
+
+HAVE_UZAWAPRESSURE=no 
+if test "x$UZAWAPRESSURE" = "xyes"; then
+	HAVE_UZAWAPRESSURE=yes
+	AC_DEFINE([_HAVE_UZAWAPRESSURE_],[1],[with UzawaPressurecapability])
+fi
+AM_CONDITIONAL([UZAWAPRESSURE], [test x$HAVE_UZAWAPRESSURE = xyes])
+AC_MSG_RESULT($HAVE_UZAWAPRESSURE)
+dnl }}}
+dnl with-Thermal{{{
+AC_ARG_WITH([Thermal],
+	AS_HELP_STRING([--with-Thermal = YES], [compile with Thermal capabilities (default is yes)]),
+	[THERMAL=$withval],[THERMAL=yes])
+AC_MSG_CHECKING(for Thermal capability compilation)
+
+HAVE_THERMAL=no 
+if test "x$THERMAL" = "xyes"; then
+	HAVE_THERMAL=yes
+	AC_DEFINE([_HAVE_THERMAL_],[1],[with Thermalcapability])
+fi
+AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
+AC_MSG_RESULT($HAVE_THERMAL)
+dnl }}}
+dnl with-Gia{{{
+AC_ARG_WITH([Gia],
+	AS_HELP_STRING([--with-Gia = YES], [compile with Gia capabilities (default is yes)]),
+	[GIA=$withval],[GIA=yes])
+AC_MSG_CHECKING(for Gia capability compilation)
+
+HAVE_GIA=no 
+if test "x$GIA" = "xyes"; then
+	HAVE_GIA=yes
+	AC_DEFINE([_HAVE_GIA_],[1],[with Giacapability])
+fi
+AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
+AC_MSG_RESULT($HAVE_GIA)
+dnl }}}
+dnl with-Meshdeformation{{{
+AC_ARG_WITH([Meshdeformation],
+	AS_HELP_STRING([--with-Meshdeformation = YES], [compile with Meshdeformation capabilities (default is yes)]),
+	[MESHDEFORMATION=$withval],[MESHDEFORMATION=yes])
+AC_MSG_CHECKING(for Meshdeformation capability compilation)
+
+HAVE_MESHDEFORMATION=no 
+if test "x$MESHDEFORMATION" = "xyes"; then
+	HAVE_MESHDEFORMATION=yes
+	AC_DEFINE([_HAVE_MESHDEFORMATION_],[1],[with Meshdeformationcapability])
+fi
+AM_CONDITIONAL([MESHDEFORMATION], [test x$HAVE_MESHDEFORMATION = xyes])
+AC_MSG_RESULT($HAVE_MESHDEFORMATION)
+dnl }}}
+dnl with-Levelset{{{
+AC_ARG_WITH([Levelset],
+	AS_HELP_STRING([--with-Levelset = YES], [compile with Levelset capabilities (default is yes)]),
+	[LEVELSET=$withval],[LEVELSET=yes])
+AC_MSG_CHECKING(for Levelset capability compilation)
+
+HAVE_LEVELSET=no 
+if test "x$LEVELSET" = "xyes"; then
+	HAVE_LEVELSET=yes
+	AC_DEFINE([_HAVE_LEVELSET_],[1],[with Levelsetcapability])
+fi
+AM_CONDITIONAL([LEVELSET], [test x$HAVE_LEVELSET = xyes])
+AC_MSG_RESULT($HAVE_LEVELSET)
+dnl }}}
+dnl with-Extrapolation{{{
+AC_ARG_WITH([Extrapolation],
+	AS_HELP_STRING([--with-Extrapolation = YES], [compile with Extrapolation capabilities (default is yes)]),
+	[EXTRAPOLATION=$withval],[EXTRAPOLATION=yes])
+AC_MSG_CHECKING(for Extrapolation capability compilation)
+
+HAVE_EXTRAPOLATION=no 
+if test "x$EXTRAPOLATION" = "xyes"; then
+	HAVE_EXTRAPOLATION=yes
+	AC_DEFINE([_HAVE_EXTRAPOLATION_],[1],[with Extrapolationcapability])
+fi
+AM_CONDITIONAL([EXTRAPOLATION], [test x$HAVE_EXTRAPOLATION = xyes])
+AC_MSG_RESULT($HAVE_EXTRAPOLATION)
+dnl }}}
+dnl with-LsfReinitialization{{{
+AC_ARG_WITH([LsfReinitialization],
+	AS_HELP_STRING([--with-LsfReinitialization = YES], [compile with LsfReinitialization capabilities (default is yes)]),
+	[LSFREINITIALIZATION=$withval],[LSFREINITIALIZATION=yes])
+AC_MSG_CHECKING(for LsfReinitialization capability compilation)
+
+HAVE_LSFREINITIALIZATION=no 
+if test "x$LSFREINITIALIZATION" = "xyes"; then
+	HAVE_LSFREINITIALIZATION=yes
+	AC_DEFINE([_HAVE_LSFREINITIALIZATION_],[1],[with LsfReinitializationcapability])
+fi
+AM_CONDITIONAL([LSFREINITIALIZATION], [test x$HAVE_LSFREINITIALIZATION = xyes])
+AC_MSG_RESULT($HAVE_LSFREINITIALIZATION)
+dnl }}}
+
+])
Index: /issm/branches/trunk-jpl-ad2-integrated/m4/ar-lib.m4
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/m4/ar-lib.m4	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/m4/ar-lib.m4	(revision 18231)
@@ -0,0 +1,61 @@
+##                                                          -*- Autoconf -*-
+# Copyright (C) 2011-2012 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 1
+
+# AM_PROG_AR([ACT-IF-FAIL])
+# -------------------------
+# Try to determine the archiver interface, and trigger the ar-lib wrapper
+# if it is needed.  If the detection of archiver interface fails, run
+# ACT-IF-FAIL (default is to abort configure with a proper error message).
+AC_DEFUN([AM_PROG_AR],
+[AC_BEFORE([$0], [LT_INIT])dnl
+AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl
+AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
+AC_REQUIRE_AUX_FILE([ar-lib])dnl
+AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false])
+: ${AR=ar}
+
+AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface],
+  [am_cv_ar_interface=ar
+   AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])],
+     [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([am_ar_try])
+      if test "$ac_status" -eq 0; then
+        am_cv_ar_interface=ar
+      else
+        am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
+        AC_TRY_EVAL([am_ar_try])
+        if test "$ac_status" -eq 0; then
+          am_cv_ar_interface=lib
+        else
+          am_cv_ar_interface=unknown
+        fi
+      fi
+      rm -f conftest.lib libconftest.a
+     ])
+   ])
+
+case $am_cv_ar_interface in
+ar)
+  ;;
+lib)
+  # Microsoft lib, so override with the ar-lib wrapper script.
+  # FIXME: It is wrong to rewrite AR.
+  # But if we don't then we get into trouble of one sort or another.
+  # A longer-term fix would be to have automake use am__AR in this case,
+  # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something
+  # similar.
+  AR="$am_aux_dir/ar-lib $AR"
+  ;;
+unknown)
+  m4_default([$1],
+             [AC_MSG_ERROR([could not determine $AR interface])])
+  ;;
+esac
+AC_SUBST([AR])dnl
+])
Index: /issm/branches/trunk-jpl-ad2-integrated/m4/issm_options.m4
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/m4/issm_options.m4	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/m4/issm_options.m4	(revision 18231)
@@ -0,0 +1,1804 @@
+dnl ISSM Options
+
+AC_DEFUN([ISSM_OPTIONS],[
+
+	AC_MSG_NOTICE(============================================================================)
+	AC_MSG_NOTICE(=                      Checking ISSM specific options                      =)
+	AC_MSG_NOTICE(============================================================================)
+
+	dnl ISSM's internal options
+	dnl Build info{{{
+	AC_PATH_PROGS(DATE, date)
+	AC_MSG_CHECKING(for build date)
+	dnl system checks require uname
+	if test "$DATE" ; then
+		PACKAGE_DATE=`date`
+	else
+		PACKAGE_DATE="unknown"
+	fi
+	AC_DEFINE_UNQUOTED(PACKAGE_BUILD_DATE,"$PACKAGE_DATE", Build date)
+	AC_MSG_RESULT($PACKAGE_DATE)
+	dnl }}}
+	dnl Debugging {{{
+	AC_ARG_ENABLE([debugging],                                        dnl feature
+		AS_HELP_STRING([--enable-debugging],[turn debug support on]),  dnl help string
+		[enable_debugging=$enableval],                                 dnl action if given
+		[enable_debugging=no])                                         dnl action if not given
+
+	AC_MSG_CHECKING(for debugging support)
+	if test "x$enable_debugging" = xyes; then
+		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
+	fi
+	AC_MSG_RESULT($enable_debugging)
+	dnl }}}
+	dnl Development{{{
+	AC_ARG_ENABLE([development],                                      dnl feature
+		AS_HELP_STRING([--enable-development],[turn development on]),  dnl help string
+		[enable_development=$enableval],                                 dnl action if given
+		[enable_development=no])                                      dnl action if not given
+
+	AC_MSG_CHECKING(for development support)
+	if test "x$enable_development" = xyes; then
+		AC_DEFINE([_DEVELOPMENT_],[1],[Macro to enable development version in ISSM])
+	fi
+	AM_CONDITIONAL([DEVELOPMENT], [test x$enable_development = xyes])
+	AC_MSG_RESULT($enable_development)
+	 dnl }}}
+    dnl Shared build {{{
+    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
+        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
+        [enable_sharedlibs=$enableval],                                        dnl action if given
+        [enable_sharedlibs=no])                                                dnl action if not given
+	 AC_MSG_CHECKING(for shared library build)
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+	 AC_MSG_RESULT($enable_sharedlibs)
+    dnl }}}
+    dnl Version{{{
+    AC_ARG_ENABLE([version],                                   dnl feature
+    AS_HELP_STRING([--enable-version],[produce libISSM.so.0]), dnl help string
+    [enable_version=$enableval],                               dnl action if given
+    [enable_version=no])                                       dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
+    dnl }}}
+	dnl Wrappers build {{{
+	AC_ARG_WITH([wrappers],                                           dnl feature
+	AS_HELP_STRING([--with-wrappers = value],[wrappers compilation]), dnl help string
+	[WRAPPERS_VALUE=$withval],                                        dnl action if given
+	[WRAPPERS_VALUE="yes"])                                           dnl action if not given
+	AC_MSG_CHECKING(for wrappers compilation)
+	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
+	AC_MSG_RESULT($WRAPPERS_VALUE) 
+	dnl }}}
+	dnl Extensions{{{
+	ISSMEXT=".exe"
+	AC_SUBST([ISSMEXT])
+	dnl }}}
+
+	dnl ISSM's externalpackages
+	dnl vendor{{{
+	AC_ARG_WITH([vendor],                                              dnl feature
+	AS_HELP_STRING([--with-vendor = VENDOR],[vendor name, ex: intel]), dnl help string
+	[VENDOR=$withval],                                                 dnl action if given
+	[VENDOR=""])                                                       dnl action if not given
+	AC_MSG_CHECKING(for vendor compilers)
+	if test -n "$VENDOR"; then
+		if  test $VENDOR = intel-win32; then
+			export CC=icl
+			export CXX=icl
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_"
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
+		elif  test $VENDOR = intel-win7-32; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif  test $VENDOR = intel-win7-64; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif test $VENDOR = intel-linux; then
+			export CC=icc
+			export CXX=icpc
+			export CFLAGS=" -D_INTEL_LINUX_"
+			export CXXFLAGS=" -D_INTEL_LINUX_"
+		elif test $VENDOR = intel-discover; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+		elif test $VENDOR = intel-pleiades; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+		elif test $VENDOR = intel-acenet; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -D_INTEL_LINUX_ "
+			export CFLAGS=" -D_INTEL_LINUX_ "
+		elif test $VENDOR = intel-pleiades-gcc; then
+			export CC=gcc
+			export CXX=g++
+			export CXXFLAGS="-O3 -march=corei7-avx"
+			export CFLAGS="-O3 -march=corei7-avx"
+        else
+		AC_MSG_ERROR([unknown compiler vendor!])
+		fi
+	fi
+	AC_SUBST([OSLIBS]) 
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl matlab{{{
+
+	dnl 1. See if matlab has been provided
+	AC_ARG_WITH([matlab-dir],                                         dnl feature
+	AS_HELP_STRING([--with-matlab-dir=DIR],[matlab root directory.]), dnl help string
+	[MATLAB_ROOT=$withval],                                           dnl action if given
+	[MATLAB_ROOT="no"])                                               dnl action if not given
+
+	AC_MSG_CHECKING([whether matlab is enabled])
+	if test "x$MATLAB_ROOT" = "xno" ; then
+		 HAVE_MATLAB=no
+	else
+		HAVE_MATLAB=yes
+		if ! test -d "$MATLAB_ROOT"; then
+		  AC_MSG_ERROR([matlab directory provided ($MATLAB_ROOT) does not exist]);
+		fi
+		if ! test -f "$MATLAB_ROOT/extern/include/mex.h"; then
+			AC_MSG_ERROR([Couldn't find mex.h... check your installation of matlab])
+	   fi
+	fi
+	AC_MSG_RESULT($HAVE_MATLAB)
+	AM_CONDITIONAL([MATLAB], [test x$HAVE_MATLAB = xyes])
+
+	dnl 2. Get Matlab libraries
+	if test "x$HAVE_MATLAB" = "xyes"; then
+
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with matlab in ISSM src])
+  		MATLABINCL="-I$MATLAB_ROOT/extern/include/"
+		
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental) except for windows
+		AC_MSG_CHECKING([matlab's mex compilation flags])
+  		case "${host_os}" in
+  			*cygwin*) 
+  				if  test $VENDOR = intel-win7-32; then
+  					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win32/microsoft` -no-undefined -Wl,/export:mexFunction" 
+  				elif  test l-win7-64; then
+  					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -no-undefined -Wl,/export:mexFunction" 
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+  				MEXEXT=".$MEXEXT"
+  			;;
+		   *)
+		      MEXLINK=$($MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
+	         MEXLIB=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
+		      MEXEXT=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
+
+				dnl version 2014 and up
+				if test "x$MEXEXT" = "x" ; then
+					 echo "#include <mex.h>" > conftest.cpp
+					 echo "void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){}" >> conftest.cpp
+					 $MATLAB_ROOT/bin/mex -v -lmex conftest.cpp > conftest.tmp 2>&1 
+					 rm -f conftest.cpp
+					 MEXLINK=$(cat conftest.tmp | grep LDFLAGS  | sed -e "s/LDFLAGS ://g")
+					 MEXLIB=$( cat conftest.tmp | grep LINKLIBS | sed -e "s/LINKLIBS ://g")
+					 MEXEXT=$( cat conftest.tmp | grep LDEXT    | sed -e "s/LDEXT ://g" | awk '{print $[1]}')
+					 rm -f conftest.tmp
+				fi
+
+  			;;
+      esac
+		AC_MSG_RESULT(done)
+	   if test "x$MEXEXT" = "x" ; then
+			AC_MSG_ERROR([Couldn't find mex... check your installation of matlab])
+	   fi
+
+		AC_SUBST([MATLABINCL])
+		MATLABWRAPPEREXT=$MEXEXT
+		AC_SUBST([MATLABWRAPPEREXT])
+	   AC_SUBST([MEXLIB]) 
+		AC_SUBST([MEXLINK])
+	fi
+	dnl }}}
+	dnl triangle {{{
+	AC_ARG_WITH([triangle-dir],
+			  AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory.]),
+			 [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT="no"]) 
+
+  dnl Check whether triangle is enabled
+	AC_MSG_CHECKING([for triangle])
+	if test "x$TRIANGLE_ROOT" = "xno" ; then
+		HAVE_TRIANGLE=no
+	else
+		HAVE_TRIANGLE=yes
+		if ! test -d "$TRIANGLE_ROOT"; then
+			AC_MSG_ERROR([triangle directory provided ($TRIANGLE_ROOT) does not exist]);
+		fi
+		if ! test -f "$TRIANGLE_ROOT/triangle.h" ; then
+			AC_MSG_ERROR([Couldn't find triangle.h... check your installation of triangle])
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_TRIANGLE)
+	AM_CONDITIONAL([TRIANGLE],[test x$HAVE_TRIANGLE = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_TRIANGLE" = "xyes"; then
+		TRIANGLEINCL=-I$TRIANGLE_ROOT/
+		case "${host_os}" in
+				*cygwin*)
+				TRIANGLELIB="-Wl,`cygpath -m $TRIANGLE_ROOT/`triangle.lib"
+				;;
+				*linux*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+				;;
+				*darwin*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+				;;
+			esac
+		AC_DEFINE([_HAVE_TRIANGLE_],[1],[with Triangle in ISSM src])
+		AC_SUBST([TRIANGLEINCL])
+		AC_SUBST([TRIANGLELIB])
+	fi
+	dnl }}}
+	dnl boost{{{
+	AC_ARG_WITH([boost-dir],
+	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
+	  [BOOST_ROOT=$withval],[BOOST_ROOT="no"]) 
+
+	dnl Check whether boost is enabled
+	AC_MSG_CHECKING([for boost])
+	if test "x$BOOST_ROOT" = "xno" ; then
+		HAVE_BOOST=no
+	else
+		HAVE_BOOST=yes
+		if ! test -d "$BOOST_ROOT"; then
+			AC_MSG_ERROR([boost directory provided ($BOOST_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BOOST)
+	AM_CONDITIONAL([BOOST],[test x$HAVE_BOOST = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_BOOST" = "xyes"; then
+		BOOSTINCL=-I$BOOST_ROOT/include
+		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
+		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
+		AC_SUBST([BOOSTINCL])
+		AC_SUBST([BOOSTLIB])
+	fi
+	dnl }}}
+	dnl dakota{{{
+	AC_ARG_WITH([dakota-dir],
+	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory.]),
+	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT="no"]) 
+	
+	dnl Check whether dakota is enabled
+	AC_MSG_CHECKING([for dakota])
+	if test "x$DAKOTA_ROOT" = "xno" ; then
+		HAVE_DAKOTA=no
+	else
+		HAVE_DAKOTA=yes
+		if ! test -d "$DAKOTA_ROOT"; then
+			AC_MSG_ERROR([dakota directory provided ($DAKOTA_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_DAKOTA)
+	AM_CONDITIONAL([DAKOTA],[test x$HAVE_DAKOTA = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_DAKOTA" = "xyes"; then
+		DAKOTAINCL=-I$DAKOTA_ROOT/include
+
+		AC_MSG_CHECKING(for dakota version)
+		if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.C"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.C | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.cpp"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.cpp | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else
+			AC_MSG_ERROR([Dakota CommandLineHandler.C or CommandLineHandler.cpp file not found to determine DAKOTA_VERSION!]);
+		fi
+		fi
+		AC_MSG_RESULT($DAKOTA_VERSION)
+		AC_DEFINE_UNQUOTED([_DAKOTA_VERSION_],"$DAKOTA_VERSION",[Dakota version number])
+
+		DAKOTAFLAGS=""
+		case "${host_os}" in
+			*cygwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*linux*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system -ldl"
+				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.3.1; then
+					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+				fi
+			;;
+			*darwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver" 
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.3.1; then
+					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+                                fi
+			;;
+		esac
+
+		case $DAKOTA_VERSION in
+			@<:@1-9@:>@.@<:@0-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_BUILD=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@+)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			*)
+				AC_MSG_ERROR([Dakota version ($DAKOTA_VERSION) not supported!]);
+		   ;;
+		esac
+		AC_MSG_CHECKING(for dakota major version)
+		AC_MSG_RESULT($DAKOTA_MAJOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MAJOR_],$DAKOTA_MAJOR,[Dakota major version number])
+		AC_MSG_CHECKING(for dakota minor version)
+		AC_MSG_RESULT($DAKOTA_MINOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MINOR_],$DAKOTA_MINOR,[Dakota minor version number])
+		AC_MSG_CHECKING(for dakota build version)
+		AC_MSG_RESULT($DAKOTA_BUILD)
+		AC_DEFINE_UNQUOTED([_DAKOTA_BUILD_],$DAKOTA_BUILD,[Dakota build version number])
+
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
+		AC_SUBST([DAKOTAINCL])
+		AC_SUBST([DAKOTAFLAGS])
+		AC_SUBST([DAKOTALIB])
+	fi
+	dnl }}}
+	dnl python{{{
+	AC_ARG_WITH([python-dir],
+	  AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
+	  [PYTHON_ROOT=$withval],[PYTHON_ROOT="no"]) 
+
+	dnl Check whether python is enabled
+	AC_MSG_CHECKING([for python])
+	if test "x$PYTHON_ROOT" = "xno" ; then
+		HAVE_PYTHON=no
+		HAVE_PYTHON3=no
+	else
+		HAVE_PYTHON=yes
+		if ! test -d "$PYTHON_ROOT"; then
+			AC_MSG_ERROR([python directory provided ($PYTHON_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON)
+	AM_CONDITIONAL([PYTHON],[test x$HAVE_PYTHON = xyes])
+
+	dnl python specifics
+	if test "x$HAVE_PYTHON" = "xyes"; then
+		AC_MSG_CHECKING(for python version)
+		dnl Query Python for its version number.  Getting [:3] seems to be the
+		dnl best way to do this; it's what "site.py" does in the standard library.
+		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
+		AC_MSG_RESULT($PYTHON_VERSION)
+
+		dnl recover major 
+		PYTHON_MAJOR=${PYTHON_VERSION%.*}
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+		if test "x$PYTHON_MAJOR" = "x3"; then
+			HAVE_PYTHON3="yes"
+		else
+			HAVE_PYTHON3="no"
+		fi
+
+		PYTHONINCL=-I$PYTHON_ROOT/include
+		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHON_VERSION"
+		PYTHONEXT=.so
+		case "${host_os}" in
+			*cygwin*)
+			PYTHONLINK="-shared"
+			;;
+			*linux*)
+			PYTHONLINK="-shared"
+			;;
+			*darwin*)
+			PYTHONLINK="-dynamiclib"
+			;;
+		esac
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with python in ISSM src])
+		AC_SUBST([PYTHONINCL])
+		AC_SUBST([PYTHONLIB])
+		PYTHONWRAPPEREXT=$PYTHONEXT
+		AC_SUBST([PYTHONWRAPPEREXT])
+		AC_SUBST([PYTHONLINK])
+	fi
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
+	dnl }}}
+	dnl python-numpy{{{
+	AC_ARG_WITH([python-numpy-dir],
+	  AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
+	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT="no"]) 
+	
+	dnl Check whether numpy is enabled
+	AC_MSG_CHECKING(for python-numpy)
+	if test "x$PYTHON_NUMPY_ROOT" = "xno" ; then
+		HAVE_PYTHON_NUMPY=no
+	else
+		HAVE_PYTHON_NUMPY=yes
+		if ! test -d "$PYTHON_NUMPY_ROOT"; then
+			AC_MSG_ERROR([numpy directory provided ($PYTHON_NUMPY_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+
+	dnl numpy lib
+	if test "x$HAVE_PYTHON_NUMPY" = "xyes"; then
+		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
+		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
+		AC_SUBST([PYTHON_NUMPYINCL])
+	fi
+	dnl }}}
+	dnl chaco{{{
+	AC_ARG_WITH([chaco-dir],
+	  AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
+	  [CHACO_ROOT=$withval],[CHACO_ROOT="no"]) 
+	
+	dnl Check whether chaco is enabled
+	AC_MSG_CHECKING([for chaco])
+	if test "x$CHACO_ROOT" = "xno" ; then
+		HAVE_CHACO=no
+	else
+		HAVE_CHACO=yes
+		if ! test -d "$CHACO_ROOT"; then
+			AC_MSG_ERROR([chaco directory provided ($CHACO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_CHACO)
+	AM_CONDITIONAL([CHACO],[test x$HAVE_CHACO = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_CHACO" = "xyes"; then
+		CHACOINCL=-I$CHACO_ROOT/include
+		CHACOLIB="-L$CHACO_ROOT/lib -lchacominusblas"
+		AC_DEFINE([_HAVE_CHACO_],[1],[with Chaco in ISSM src])
+		AC_SUBST([CHACOINCL])
+		AC_SUBST([CHACOLIB])
+	fi
+	dnl }}}
+	dnl scotch{{{
+	AC_ARG_WITH([scotch-dir],
+	  AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
+	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT="no"]) 
+
+  dnl Check whether scotch is enabled
+	AC_MSG_CHECKING([for scotch])
+	if test "x$SCOTCH_ROOT" = "xno" ; then
+		HAVE_SCOTCH=no
+	else
+		HAVE_SCOTCH=yes
+		if ! test -d "$SCOTCH_ROOT"; then
+			AC_MSG_ERROR([scotch directory provided ($SCOTCH_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SCOTCH)
+	AM_CONDITIONAL([SCOTCH],[test x$HAVE_SCOTCH = xyes])
+	
+	dnl scotch libraries
+	if test "x$HAVE_SCOTCH" = "xyes"; then
+		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
+		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
+		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
+		AC_SUBST([SCOTCHINCL])
+		AC_SUBST([SCOTCHLIB])
+	fi
+	dnl }}}
+	dnl adolc{{{
+	AC_ARG_WITH([adolc-dir],
+		AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
+		[ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
+
+	dnl Check whether adolc is enabled
+	AC_MSG_CHECKING([for adolc])
+	if test "x$ADOLC_ROOT" = "xno" ; then
+		HAVE_ADOLC=no
+	else
+		HAVE_ADOLC=yes
+		if ! test -d "$ADOLC_ROOT"; then
+			AC_MSG_ERROR([adolc directory provided ($ADOLC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ADOLC)
+	
+	dnl adolc headers and libraries
+	if test "x$HAVE_ADOLC" == "xyes"; then
+		ADOLCINCL="-I$ADOLC_ROOT/include"
+		dnl ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc" used to be the path
+		ADOLCLIB="-L$ADOLC_ROOT/lib -ladolc"
+		AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
+		AC_SUBST([ADOLCINCL])
+		AC_SUBST([ADOLCLIB])
+	fi
+	AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
+	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
+	dnl adic2{{{
+	AC_ARG_WITH([adic2-dir],
+	  AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
+	  [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
+
+	dnl Check whether adic2 is enabled
+	AC_MSG_CHECKING([for adic2])
+	if test "x$ADIC2_ROOT" = "xno" ; then
+		HAVE_ADIC2=no
+	else
+		HAVE_ADIC2=yes
+		if ! test -d "$ADIC2_ROOT"; then
+			AC_MSG_ERROR([adic2 directory provided ($ADIC2_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ADIC2)
+
+	dnl adic2 headers and libraries
+	if test "x$HAVE_ADIC2" == "xyes"; then
+		ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
+		ADIC2LIB=""
+		AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
+		AC_SUBST([ADIC2INCL])
+		AC_SUBST([ADIC2LIB])
+	fi
+	AM_CONDITIONAL([ADIC2], [test x$HAVE_ADIC2 = xyes])
+	dnl }}}
+	dnl atlas{{{
+	AC_ARG_WITH([atlas-dir],
+	  AS_HELP_STRING([--with-atlas-dir=DIR],[atlas root directory]),
+	  [ATLAS_ROOT=$withval],[ATLAS_ROOT="no"])
+			  
+	dnl Check whether atlas is enabled
+	AC_MSG_CHECKING(for atlas and cblas libraries)
+	if test "x$ATLAS_ROOT" = "xno" ; then
+		HAVE_ATLAS=no
+	else
+		HAVE_ATLAS=yes
+		if ! test -d "$ATLAS_ROOT"; then
+			AC_MSG_ERROR([atlas directory provided ($ATLAS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ATLAS)
+
+	dnl atlas headers and libraries
+	if test "x$HAVE_ATLAS" == "xyes"; then
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			ATLASLIB="-L`cygpath -m $ATLAS_ROOT` -Wl,libatlas.lib  -Wl,libcblas.lib"
+			;;
+			*linux*)
+			ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm " 
+			;;
+			*darwin*)
+			ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm" 
+			;;
+		esac
+		AC_DEFINE([_HAVE_ATLAS_],[1],[with ATLAS in ISSM src])
+		AC_SUBST([ATLASLIB])
+	fi
+	dnl }}}
+	dnl gsl{{{
+	AC_ARG_WITH([gsl-dir],
+	  AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
+	  [GSL_ROOT=$withval],[GSL_ROOT="no"]) 
+
+	dnl Check whether gsl is enabled
+	AC_MSG_CHECKING([for gsl])
+	if test "x$GSL_ROOT" = "xno" ; then
+		HAVE_GSL=no
+	else
+		HAVE_GSL=yes
+		if ! test -d "$GSL_ROOT"; then
+			AC_MSG_ERROR([gsl directory provided ($GSL_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_GSL)
+	
+	dnl gsl headers and libraries
+	if test "x$HAVE_GSL" == "xyes"; then
+		GSLINCL="-I$GSL_ROOT/include"
+		if test "x$HAVE_ATLAS" = "xyes" ; then
+			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -L$ATLAS_ROOT/lib -lcblas -latlas -lm"
+		else
+			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+		fi
+		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
+		AC_SUBST([GSLINCL])
+		AC_SUBST([GSLLIB])
+	fi
+	AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
+	dnl }}}
+	dnl adjoinable-mpi{{{
+	AC_ARG_WITH([ampi-dir],
+	  AS_HELP_STRING([--with-ampi-dir=DIR], [adjoinable mpi root directory.]),
+	  [AMPI_ROOT=$withval],[AMPI_ROOT="no"]) 
+
+	dnl Check whether ampi is enabled
+	AC_MSG_CHECKING([for ampi])
+	if test "x$AMPI_ROOT" = "xno" ; then
+		HAVE_AMPI=no
+	else
+		HAVE_AMPI=yes
+		if ! test -d "$AMPI_ROOT"; then
+			AC_MSG_ERROR([ampi directory provided ($AMPI_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_AMPI)
+	
+	dnl ampi headers and libraries
+	if test "x$HAVE_AMPI" == "xyes"; then
+		AMPIINCL="-I$AMPI_ROOT/include"
+		if test "x$ADOLC_ROOT" == "xno"; then
+			AC_MSG_ERROR([cannot run adjoinable mpi without adolc]);
+		fi
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib -lampiCommon -L$ADOLC_ROOT/lib -ladolc -L$AMPI_ROOT/lib -lampiCommon -lampiBookkeeping -lampiTape"
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -Wl,--start-group,-lampiCommon,-ladolc,-lampiCommon,-lampiBookkeeping,-lampiTape,-lampiPlainC,-lampiADtoolStubsST,--end-group"
+		dnl AMPILIB="-L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -Wl,--start-group -lampiCommon -ladolc -lampiCommon -lampiBookkeeping -lampiTape -lampiPlainC -lampiADtoolStubsST -Wl,--end-group"
+		dnl AMPILIB="$AMPI_ROOT/lib/libampiCommon.so $ADOLC_ROOT/lib/libadolc.so  $AMPI_ROOT/lib/libampiCommon.so $AMPI_ROOT/lib/libampiBookkeeping.so $AMPI_ROOT/lib/libampiTape.so $AMPI_ROOT/lib/libampiPlainC.so  $AMPI_ROOT/lib/libampiADtoolStubsST.so"
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -lampiCommon -ladolc -lampiCommon -lampiBookkeeping -lampiTape -lampiPlainC -lampiADtoolStubsST"
+		AMPILIB="-dy -L$AMPI_ROOT/lib  -lampiCommon -lampiBookkeeping -lampiTape"
+		AC_DEFINE([_HAVE_AMPI_],[1],[with adjoinable mpi in ISSM src])
+		AC_SUBST([AMPIINCL])
+		AC_SUBST([AMPILIB])
+	fi
+	AM_CONDITIONAL([AMPI], [test x$HAVE_AMPI = xyes])
+	dnl }}}
+	dnl rose{{{
+	AC_ARG_WITH([rose-dir],
+	  AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
+	  [ROSE_ROOT=$withval],[ROSE_ROOT="no"]) 
+
+	dnl Check whether rose is enabled
+	AC_MSG_CHECKING([for rose])
+	if test "x$ROSE_ROOT" = "xno" ; then
+		HAVE_ROSE=no
+	else
+		HAVE_ROSE=yes
+		if ! test -d "$ROSE_ROOT"; then
+			AC_MSG_ERROR([rose directory provided ($ROSE_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ROSE)
+	AM_CONDITIONAL([ROSE],[test x$HAVE_ROSE = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_ROSE" = "xyes"; then
+		ROSEINCL="-I$ROSE_ROOT/include"
+		ROSELIB=""
+		AC_DEFINE([_HAVE_ROSE_],[1],[with rose in ISSM src])
+		AC_SUBST([ROSEINCL])
+		AC_SUBST([ROSELIB])
+	fi
+	dnl }}}
+	dnl mpi{{{
+	AC_MSG_CHECKING(for mpi)
+	
+	AC_ARG_WITH([mpi-include],
+	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
+	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
+
+	AC_ARG_WITH([mpi-libdir],
+	  AS_HELP_STRING([--with-mpi-libdir=DIR],[mpi lib directory, necessary for parallel build]),
+	  [MPI_LIBDIR=$withval],[MPI_LIBDIR=""])
+
+	AC_ARG_WITH([mpi-libflags],
+	  AS_HELP_STRING([--with-mpi-libflags=LIBS],[mpi libraries to be used, necessary for parallel build]),
+	  [MPI_LIBFLAGS=$withval],[MPI_LIBFLAGS=""])
+
+	
+	if test -z "$MPI_INCLUDE" ; then
+		HAVE_MPI=no
+	else
+		HAVE_MPI=yes
+
+		dnl Processing for windows
+		if  test x$VENDOR = xintel-win7-32; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPIINCL=`cygpath -m $MPI_INCLUDE`
+		elif test x$VENDOR = xintel-win7-64; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPI_INCLUDE=`cygpath -m $MPI_INCLUDE`
+		fi
+
+		if test -z "$MPI_LIBDIR"; then
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="$MPI_LIBFLAGS"
+		else
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="-L$MPI_LIBDIR $MPI_LIBFLAGS"
+		fi
+		AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+		AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
+		AC_SUBST([MPIINCL])
+		AC_SUBST([MPILIB])
+	fi
+	AM_CONDITIONAL([MPI], [test x$HAVE_MPI = xyes])
+	AC_MSG_RESULT($HAVE_MPI)
+	dnl }}}
+	dnl petsc{{{
+	AC_ARG_WITH([petsc-dir],
+	  AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
+	  [PETSC_ROOT=$withval],[PETSC_ROOT="no"])
+		
+	dnl Check whether petsc is enabled
+	AC_MSG_CHECKING([for petsc])
+	if test "x$PETSC_ROOT" = "xno" ; then
+		HAVE_PETSC=no
+	else
+		HAVE_PETSC=yes
+		if ! test -d "$PETSC_ROOT"; then
+			AC_MSG_ERROR([petsc directory provided ($PETSC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PETSC)
+	AM_CONDITIONAL([PETSC],[test x$HAVE_PETSC = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_PETSC" = "xyes"; then
+		AC_MSG_CHECKING(for petsc version)
+	   if ! test -f "$PETSC_ROOT/include/petscversion.h"; then
+			AC_MSG_ERROR([PETSc not instaled corretly: file ($PETSC_ROOT/include/petscversion.h) does not exist]);
+		fi
+		PETSC_MAJOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MAJOR" | sed 's/#define PETSC_VERSION_MAJOR//' | sed 's/ //g'`
+		PETSC_MINOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MINOR" | sed 's/#define PETSC_VERSION_MINOR//' | sed 's/ //g'`
+		AC_DEFINE_UNQUOTED([_PETSC_MAJOR_],$PETSC_MAJOR,[PETSc version major])
+		AC_DEFINE_UNQUOTED([_PETSC_MINOR_],$PETSC_MINOR,[PETSc version minor])
+		AC_MSG_RESULT($PETSC_MAJOR.$PETSC_MINOR)
+
+		PETSC_VERSION_DATE_HG=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_DATE_HG" | sed 's/#define PETSC_VERSION_DATE_HG//' | sed 's/ //g' | sed -e 's/\"//g' `
+		PETSC_RELEASE=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_RELEASE" | sed 's/#define PETSC_VERSION_RELEASE//' | sed 's/ //g'`
+
+		AC_MSG_CHECKING(whether petsc is the development version)
+		dnl if test x$PETSC_VERSION_DATE_HG = xunknown; then
+		if test "$PETSC_RELEASE" = "0"; then
+		   AC_DEFINE([_HAVE_PETSCDEV_],[1],[with PETSc-dev])
+			AC_MSG_RESULT(yes)
+		else
+			AC_MSG_RESULT(no)
+		fi
+	
+		AC_ARG_WITH([petsc-arch],
+		  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch, necessary for PETSc < 3.0]),
+		  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+		AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT)
+		dnl To ge PETSc's libraries:
+		dnl cd externalpackages/petsc/src
+		dnl make getlinklibs
+		PETSCINCL=" -I$PETSC_ROOT/include"
+		dnl Add other location (not needed anymore since at least PETSc 3.0)
+		if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+		 PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+		fi
+		if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+		 PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+		fi
+		
+		case "${host_os}" in
+				*cygwin*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB=-Wl,/LIBPATH:`cygpath -w $PETSC_ROOT/lib`  -Wl,libpetscksp.lib  -Wl,libpetscdm.lib  -Wl,libpetscmat.lib  -Wl,libpetscvec.lib  -Wl,libpetscsnes.lib  -Wl,libpetscts.lib  -Wl,libmpiuni.lib  -Wl,libpetsc.lib
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib  -Wl,libpetsc.lib"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+="  -Wl,libmetis.lib"; fi
+				fi
+				;;
+				*linux*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+				fi
+				;;
+				*darwin*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+				fi
+				;;
+		esac
+		AC_MSG_RESULT(done)
+		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
+		AC_SUBST([PETSCINCL])
+		AC_SUBST([PETSCLIB])
+	fi
+	dnl }}}
+	dnl metis{{{
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
+		dnl in petsc >=3.3, metis is provided
+		HAVE_METIS="yes"
+		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="no"])
+
+		dnl Check whether metis is enabled
+		AC_MSG_CHECKING([for metis])
+		if test "x$METIS_ROOT" = "xno" ; then
+			HAVE_METIS=no
+		else
+			HAVE_METIS=yes
+			if ! test -d "$METIS_ROOT"; then
+				AC_MSG_ERROR([metis directory provided ($METIS_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+		AM_CONDITIONAL([METIS],[test x$HAVE_METIS = xyes])
+
+		dnl library and header files
+		if test "x$HAVE_METIS" = "xyes"; then
+
+			AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+			dnl first figure out version of metis: does the VERSION file exist?
+			if test -e "$METIS_ROOT/VERSION"; then
+				METIS_VERSION=4
+			else
+				METIS_VERSION=5
+			fi
+
+			if test "$METIS_VERSION" = "4" ; then
+				METISINCL=-I"$METIS_ROOT/Lib" 
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT -Wl,libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+				esac
+				AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+			fi
+
+			if test "$METIS_VERSION" = "5" ; then
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+				esac
+				METISINCL=-I"$METIS_ROOT/include" 
+				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+			fi
+
+			AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+			AC_SUBST([METISINCL])
+			AC_SUBST([METISLIB])
+		fi
+	fi
+	AM_CONDITIONAL([METIS],[test x$HAVE_METIS = xyes])
+	dnl }}}
+	dnl tao{{{
+	AC_ARG_WITH([tao-dir],
+		AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
+		[TAO_ROOT=$withval],[TAO_ROOT="no"]) 
+
+	dnl Check whether tao is enabled
+	AC_MSG_CHECKING([for tao])
+	if test "x$TAO_ROOT" = "xno" ; then
+		HAVE_TAO=no
+	else
+		HAVE_TAO=yes
+		if ! test -d "$TAO_ROOT"; then
+			AC_MSG_ERROR([tao directory provided ($TAO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_TAO)
+	
+	dnl tao headers and libraries
+	if test "x$HAVE_TAO" == "xyes"; then
+	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
+	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
+	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+	  AC_SUBST([TAOINCL])
+	  AC_SUBST([TAOLIB])
+	fi
+	dnl }}}
+	dnl m1qn3{{{
+	AC_ARG_WITH([m1qn3-dir],
+		AS_HELP_STRING([--with-m1qn3-dir=DIR], [m1qn3 root directory.]),
+		[M1QN3_ROOT=$withval],[M1QN3_ROOT="no"]) 
+
+	dnl Check whether m1qn3 is enabled
+	AC_MSG_CHECKING([for m1qn3])
+	if test "x$M1QN3_ROOT" = "xno" ; then
+		HAVE_M1QN3=no
+	else
+		HAVE_M1QN3=yes
+		if ! test -d "$M1QN3_ROOT"; then
+			AC_MSG_ERROR([m1qn3 directory provided ($M1QN3_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_M1QN3)
+	
+	dnl m1qn3 headers and libraries
+	if test "x$HAVE_M1QN3" == "xyes"; then
+	  M1QN3LIB="$M1QN3_ROOT/libm1qn3.a $M1QN3_ROOT//libddot.a"
+	  AC_DEFINE([_HAVE_M1QN3_],[1],[with M1QN3I in ISSM src])
+	  AC_SUBST([M1QN3LIB])
+	fi
+	dnl }}}
+	dnl slepc{{{
+	AC_ARG_WITH([slepc-dir],
+	  AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
+	  [SLEPC_ROOT=$withval],[SLEPC_ROOT="no"])
+			  
+	dnl Check whether slepc is enabled
+	AC_MSG_CHECKING([for slepc])
+	if test "x$SLEPC_ROOT" = "xno" ; then
+		HAVE_SLEPC=no
+	else
+		HAVE_SLEPC=yes
+		if ! test -d "$SLEPC_ROOT"; then
+			AC_MSG_ERROR([slepc directory provided ($SLEPC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SLEPC)
+	
+	dnl slepc headers and libraries
+	if test "x$HAVE_SLEPC" == "xyes"; then
+		SLEPCINCL=-I"$SLEPC_ROOT/include"
+		SLEPCLIB=-L"$SLEPC_ROOT/lib/ -lslepc"
+		AC_DEFINE([_HAVE_SLEPC_],[1],[with Slepc in ISSM src])
+		AC_SUBST([SLEPCINCL])
+		AC_SUBST([SLEPCLIB])
+	fi
+	dnl }}}
+	dnl shapelib{{{
+	AC_ARG_WITH([shapelib-dir],
+	  AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
+	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT="no"])
+			  
+	dnl Check whether shapelib is enabled
+	AC_MSG_CHECKING([for shapelib])
+	if test "x$SHAPELIB_ROOT" = "xno" ; then
+		HAVE_SHAPELIB=no
+	else
+		HAVE_SHAPELIB=yes
+		if ! test -d "$SHAPELIB_ROOT"; then
+			AC_MSG_ERROR([shapelib directory provided ($SHAPELIB_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SHAPELIB)
+	
+	dnl shapelib headers and libraries
+	if test "x$HAVE_SHAPELIB" == "xyes"; then
+		SHAPELIBINCL=-I"$SHAPELIB_ROOT/include"
+		SHAPELIBLIB=-L"$SHAPELIB_ROOT/lib/ -lshape"
+		AC_DEFINE([_HAVE_SHAPELIB_],[1],[with Shapelib in ISSM src])
+		AC_SUBST([SHAPELIBINCL])
+		AC_SUBST([SHAPELIBLIB])
+	fi
+	dnl }}}
+	dnl scalapack{{{
+	AC_ARG_WITH([scalapack-dir],
+	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
+	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT="no"])
+			  
+	dnl Check whether scalapack is enabled
+	AC_MSG_CHECKING([for scalapack])
+	if test "x$SCALAPACK_ROOT" = "xno" ; then
+		HAVE_SCALAPACK=no
+	else
+		HAVE_SCALAPACK=yes
+		if ! test -d "$SCALAPACK_ROOT"; then
+			AC_MSG_ERROR([scalapack directory provided ($SCALAPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SCALAPACK)
+	
+	dnl scalapack headers and libraries
+	if test "x$HAVE_SCALAPACK" == "xyes"; then
+		if test x$VENDOR = xintel-discover; then
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
+		else
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+		fi
+		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
+		AC_SUBST([SCALAPACKLIB])
+	fi
+	dnl }}}
+	dnl blas-lapack{{{
+	AC_ARG_WITH([blas-lapack-dir],
+	  AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
+	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT="no"])
+			  
+	dnl Check whether blas-lapack is enabled
+	AC_MSG_CHECKING([for blas-lapack])
+	if test "x$BLASLAPACK_ROOT" = "xno" ; then
+		HAVE_BLASLAPACK=no
+	else
+		HAVE_BLASLAPACK=yes
+		if ! test -d "$BLASLAPACK_ROOT"; then
+			AC_MSG_ERROR([blas-lapack directory provided ($BLASLAPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	
+	dnl blas-lapack headers and libraries
+	if test "x$HAVE_BLASLAPACK" == "xyes"; then
+		BLASLAPACKINCL=""
+		if test x$VENDOR = xintel-discover; then
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
+		else
+			dnl: branch on whether we are running on windows or linux.
+			case "${host_os}" in
+				*cygwin*)
+				BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
+				;;
+				*linux*)
+				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+				;;
+				*darwin*)
+				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+				;;
+			esac
+		fi
+		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
+		AC_SUBST([BLASLAPACKLIB])
+		AC_SUBST([BLASLAPACKINCL])
+	fi
+	dnl }}}
+	dnl mkl{{{
+	AC_ARG_WITH([mkl-dir],
+	  AS_HELP_STRING([--with-mkl-dir=DIR],[mkl root directory]),
+	  [MKL_ROOT=$withval],[MKL_ROOT="no"])
+			  
+	dnl Check whether mkl is enabled
+	AC_MSG_CHECKING([for mkl])
+	if test "x$MKL_ROOT" = "xno" ; then
+		HAVE_MKL=no
+	else
+		HAVE_MKL=yes
+		if ! test -d "$MKL_ROOT"; then
+			AC_MSG_ERROR([mkl directory provided ($MKL_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MKL)
+	
+	dnl mkl headers and libraries
+	if test "x$HAVE_MKL" == "xyes"; then
+		MKLINCL=""
+		if test x$VENDOR = xintel-pleiades; then
+			MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread"
+		elif test x$VENDOR = xintel-acenet; then
+			MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -lpthread -lm"
+		else
+			MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64 -lmkl_blacs_sgimpt_ilp64 -lguide -lpthread"
+		fi
+		AC_DEFINE([_HAVE_MKL_],[1],[with mkl in ISSM src])
+		AC_SUBST([MKLLIB])
+		AC_SUBST([MKLINCL])
+	fi
+	dnl }}}
+	dnl plapack{{{
+	AC_MSG_CHECKING(for plapack)
+	
+	AC_ARG_WITH([plapack-lib],
+	  AS_HELP_STRING([--with-plapack-lib = lib],[plapack library]),
+	  [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
+	
+	AC_ARG_WITH([plapack-include],
+			  AS_HELP_STRING([--with-plapack-include = include],
+							 [plapack include ]),
+			  [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
+	  
+	if test -n "$PLAPACK_LIB"; then
+		if test -n "$PLAPACK_INCLUDE"; then
+		
+			HAVE_PLAPACK=yes
+			PLAPACKINCL="$PLAPACK_INCLUDE"
+			PLAPACKLIB="$PLAPACK_LIB"
+			AC_DEFINE([_HAVE_PLAPACK_],[1],[with Plapack in ISSM src])
+			AC_SUBST([PLAPACKINCL])
+			AC_SUBST([PLAPACKLIB])
+		else
+			HAVE_PLAPACK=no
+		fi
+	else
+		HAVE_PLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_PLAPACK)
+	dnl }}}
+	dnl mumps{{{
+	AC_ARG_WITH([mumps-dir],
+	  AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
+	  [MUMPS_ROOT=$withval],[MUMPS_ROOT="no"])
+			  
+	dnl Check whether mumps is enabled
+	AC_MSG_CHECKING([for mumps])
+	if test "x$MUMPS_ROOT" = "xno" ; then
+		HAVE_MUMPS=no
+	else
+		HAVE_MUMPS=yes
+		if ! test -d "$MUMPS_ROOT"; then
+			AC_MSG_ERROR([mumps directory provided ($MUMPS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MUMPS)
+	
+	dnl mumps headers and libraries
+	if test "x$HAVE_MUMPS" == "xyes"; then
+		MUMPSINCL=-I"$MUMPS_ROOT/include"
+		if test "$PETSC_MAJOR" = "2" ; then
+			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+		else
+			dnl MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps"
+			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis"
+		fi
+		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
+		AC_SUBST([MUMPSINCL])
+		AC_SUBST([MUMPSLIB])
+	fi
+	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
+	dnl }}}
+	dnl blacs{{{
+	AC_ARG_WITH([blacs-dir],
+		AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
+			  [BLACS_ROOT=$withval],[BLACS_ROOT="no"])
+			  
+	dnl Check whether blacs is enabled
+	AC_MSG_CHECKING([for blacs])
+	if test "x$BLACS_ROOT" = "xno" ; then
+		HAVE_BLACS=no
+	else
+		HAVE_BLACS=yes
+		if ! test -d "$BLACS_ROOT"; then
+			AC_MSG_ERROR([blacs directory provided ($BLACS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BLACS)
+	
+	dnl blacs headers and libraries
+	if test "x$HAVE_BLACS" == "xyes"; then
+		BLACSINCL=""
+		if test x$VENDOR = xintel-discover; then
+		 BLACSLIB=-L"$BLACS_ROOT/ -lmkl_blacs_intelmpi_lp64"
+		else
+		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+		fi
+		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
+		AC_SUBST([BLACSINCL])
+		AC_SUBST([BLACSLIB])
+	fi
+	dnl }}}
+	dnl hypre{{{
+	AC_ARG_WITH([hypre-dir],
+	  AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
+			  [HYPRE_ROOT=$withval],[HYPRE_ROOT="no"])
+			  
+	dnl Check whether hypre is enabled
+	AC_MSG_CHECKING([for hypre])
+	if test "x$HYPRE_ROOT" = "xno" ; then
+		HAVE_HYPRE=no
+	else
+		HAVE_HYPRE=yes
+		if ! test -d "$HYPRE_ROOT"; then
+			AC_MSG_ERROR([hypre directory provided ($HYPRE_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_HYPRE)
+
+	dnl hypre headers and libraries
+	if test "x$HAVE_HYPRE" == "xyes"; then
+		HYPREINCL=""
+		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
+		AC_DEFINE([_HAVE_HYPRE_],[1],[with Hypre in ISSM src])
+		AC_SUBST([HYPREINCL])
+		AC_SUBST([HYPRELIB])
+	fi
+	dnl }}}
+	dnl prometheus{{{
+	AC_ARG_WITH([prometheus-dir],
+				AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
+				[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT="no"])
+
+		dnl Check whether prometheus is enabled
+		AC_MSG_CHECKING([for prometheus])
+		if test "x$PROMETHEUS_ROOT" = "xno" ; then
+			HAVE_PROMETHEUS=no
+		else
+			HAVE_PROMETHEUS=yes
+			if ! test -d "$PROMETHEUS_ROOT"; then
+				AC_MSG_ERROR([prometheus directory provided ($PROMETHEUS_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_PROMETHEUS)
+
+		dnl prometheus headers and libraries
+		if test "x$HAVE_PROMETHEUS" == "xyes"; then
+			 PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
+			 PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
+			 AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
+			 AC_SUBST([PROMETHEUSINCL])
+			 AC_SUBST([PROMETHEUSLIB])
+	   fi
+		dnl }}}
+dnl spai{{{
+	AC_ARG_WITH([spai-dir],
+				AS_HELP_STRING([--with-spai-dir=DIR],[spai root directory]),
+				[SPAI_ROOT=$withval],[SPAI_ROOT="no"])
+
+		dnl Check whether spai is enabled
+		AC_MSG_CHECKING([for spai])
+		if test "x$SPAI_ROOT" = "xno" ; then
+			HAVE_SPAI=no
+		else
+			HAVE_SPAI=yes
+			if ! test -d "$SPAI_ROOT"; then
+				AC_MSG_ERROR([spai directory provided ($SPAI_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_SPAI)
+
+		dnl spai headers and libraries
+		if test "x$HAVE_SPAI" == "xyes"; then
+			SPAIINCL=-I"$SPAI_ROOT/include"
+			SPAILIB=-L"$SPAI_ROOT/lib -lspai"
+			AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
+			AC_SUBST([SPAIINCL])
+			AC_SUBST([SPAILIB])
+		fi
+	  dnl }}}
+dnl superlu{{{ 
+	AC_ARG_WITH([superlu-dir],
+				AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
+				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT="no"])
+
+	dnl Check whether superlu is enabled
+	AC_MSG_CHECKING([for superlu])
+	if test "x$SUPERLU_ROOT" = "xno" ; then
+		HAVE_SUPERLU=no
+	else
+		HAVE_SUPERLU=yes
+		if ! test -d "$SUPERLU_ROOT"; then
+			AC_MSG_ERROR([superlu directory provided ($SUPERLU_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SUPERLU)
+	
+	dnl superlu headers and libraries
+	if test "x$HAVE_SUPERLU" == "xyes"; then
+		  SUPERLUINCL=-I"$SUPERLU_ROOT/include"
+		  SUPERLULIB=-L"$SUPERLU_ROOT/lib -lsuperlu_4.3"
+		  AC_DEFINE([_HAVE_SUPERLU_],[1],[with Superlu in ISSM src])
+		  AC_SUBST([SUPERLUINCL])
+		  AC_SUBST([SUPERLULIB])
+	 fi
+	 dnl }}}
+dnl spooles{{{ 
+	AC_ARG_WITH([spooles-dir],
+				AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
+				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT="no"])
+
+	dnl Check whether spooles is enabled
+	AC_MSG_CHECKING([for spooles])
+	if test "x$SPOOLES_ROOT" = "xno" ; then
+		HAVE_SPOOLES=no
+	else
+		HAVE_SPOOLES=yes
+		if ! test -d "$SPOOLES_ROOT"; then
+			AC_MSG_ERROR([spooles directory provided ($SPOOLES_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SPOOLES)
+	
+	dnl spooles headers and libraries
+	if test "x$HAVE_SPOOLES" == "xyes"; then
+		  SPOOLESINCL=-I"$SPOOLES_ROOT/include"
+		  SPOOLESLIB=-L"$SPOOLES_ROOT/lib -lspooles"
+		  AC_DEFINE([_HAVE_SPOOLES_],[1],[with Spooles in ISSM src])
+		  AC_SUBST([SPOOLESINCL])
+		  AC_SUBST([SPOOLESLIB])
+	 fi
+	 dnl }}}
+dnl pastix{{{ 
+	AC_ARG_WITH([pastix-dir],
+				AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
+				[PASTIX_ROOT=$withval],[PASTIX_ROOT="no"])
+
+	dnl Check whether pastix is enabled
+	AC_MSG_CHECKING([for pastix])
+	if test "x$PASTIX_ROOT" = "xno" ; then
+		HAVE_PASTIX=no
+	else
+		HAVE_PASTIX=yes
+		if ! test -d "$PASTIX_ROOT"; then
+			AC_MSG_ERROR([pastix directory provided ($PASTIX_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PASTIX)
+	
+	dnl pastix headers and libraries
+	if test "x$HAVE_PASTIX" == "xyes"; then
+		  PASTIXINCL=-I"$PASTIX_ROOT/include"
+		  PASTIXLIB=-L"$PASTIX_ROOT/lib -lpastix_XXbit_mpi_smp_nobubble_int32_simple_real_scotch_i686_pc_linux -lptscotch -lptscotcherr -lpastix"
+		  AC_DEFINE([_HAVE_PASTIX_],[1],[with Pastix in ISSM src])
+		  AC_SUBST([PASTIXINCL])
+		  AC_SUBST([PASTIXLIB])
+  fi
+  dnl }}}
+	dnl ml{{{
+	AC_ARG_WITH([ml-dir],
+	  AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
+			  [ML_ROOT=$withval],[ML_ROOT="no"])
+			  
+	dnl Check whether ml is enabled
+	AC_MSG_CHECKING([for ml])
+	if test "x$ML_ROOT" = "xno" ; then
+		HAVE_ML=no
+	else
+		HAVE_ML=yes
+		if ! test -d "$ML_ROOT"; then
+			AC_MSG_ERROR([ml directory provided ($ML_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ML)
+	
+	dnl ml headers and libraries
+	if test "x$HAVE_ML" == "xyes"; then
+		MLINCL=-I"$ML_ROOT/include"
+		MLLIB=-L"$ML_ROOT/lib -lml"
+		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
+		AC_SUBST([MLINCL])
+		AC_SUBST([MLLIB])
+	fi
+	dnl }}}
+	dnl umfpack{{{
+		AC_ARG_WITH([umfpack-dir],
+		  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
+					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT="no"])
+			  
+	dnl Check whether umfpack is enabled
+	AC_MSG_CHECKING([for umfpack])
+	if test "x$UMFPACK_ROOT" = "xno" ; then
+		HAVE_UMFPACK=no
+	else
+		HAVE_UMFPACK=yes
+		if ! test -d "$UMFPACK_ROOT"; then
+			AC_MSG_ERROR([umfpack directory provided ($UMFPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_UMFPACK)
+	
+	dnl umfpack headers and libraries
+	if test "x$HAVE_UMFPACK" == "xyes"; then
+		UMFPACKINCL=""
+		UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
+		AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
+		AC_SUBST([UMFPACKINCL])
+		AC_SUBST([UMFPACKLIB])
+	fi
+	dnl }}}
+dnl math{{{
+	AC_MSG_CHECKING(for math library)
+	AC_ARG_WITH([math-lib],
+	  AS_HELP_STRING([--with-math-lib = otions],[math options, for ex: "/usr/lib/libm.a]),
+	  [MATH_LIB=$withval],[MATH_LIB=""])
+
+	dnl check that --with-math-lib may have been provided
+	if test -n "$MATH_LIB" ; then
+		HAVE_MATH=yes
+		MATHLIB="$MATH_LIB"
+		AC_DEFINE([_HAVE_MATH_],[1],[with MATH in ISSM src])
+		AC_SUBST([MATHLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl math77{{{
+		AC_ARG_WITH([math77-dir],
+					AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
+					[MATH77_ROOT=$withval],[MATH77_ROOT="no"]) 
+		  
+	dnl Check whether math77 is enabled
+	AC_MSG_CHECKING([for math77])
+	if test "x$MATH77_ROOT" = "xno" ; then
+		HAVE_MATH77=no
+	else
+		HAVE_MATH77=yes
+		if ! test -d "$MATH77_ROOT"; then
+			AC_MSG_ERROR([math77 directory provided ($MATH77_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MATH77)
+	
+	dnl math77 headers and libraries
+	if test "x$HAVE_MATH77" == "xyes"; then
+		MATH77LIB="-L$MATH77_ROOT/ -lmath77"
+		AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
+		AC_SUBST([MATH77LIB])
+   fi
+	dnl }}}
+	dnl fortran{{{
+	AC_ARG_WITH([fortran],
+		AS_HELP_STRING([--with-fortran = YES], [do we compile fortran code (default is yes)]),
+		[FORTRAN=$withval],[FORTRAN=yes]) 
+	AC_MSG_CHECKING(for fortran compilation)
+	if test "x$FORTRAN" = "xyes"; then
+		dnl defaults
+		HAVE_FORTRAN=yes
+		AC_DEFINE([_HAVE_FORTRAN_],[1],[with fortran capability])
+	else
+		HAVE_FORTRAN=no
+	fi
+	AM_CONDITIONAL([FORTRAN], [test x$FORTRAN = xyes])
+	AC_MSG_RESULT($FORTRAN)
+
+	if test "x$FORTRAN" = "xyes"; then
+		dnl fortran library  option
+		AC_MSG_CHECKING(for fortran library)
+		AC_ARG_WITH([fortran-lib],
+		  AS_HELP_STRING([--with-fortran-lib = options],[fortran options, for ex: "/usr/lib/gfortran.a]),
+			[FORTRAN_LIB=$withval],[FORTRAN_LIB=""])
+
+		dnl check that --with-fortran-lib may have been provided
+		if test -n "$FORTRAN_LIB" ; then
+			dnl check that library provided EXISTS!
+		   FORTRAN_DIR=$(echo $FORTRAN_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+			if test -d "$FORTRAN_DIR" || test -f "$FORTRAN_DIR"; then
+				FORTRANLIB="$FORTRAN_LIB"
+				AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+				AC_SUBST([FORTRANLIB])
+			else
+			 if test "x$HAVE_MPI" = "xyes"; then
+				FORTRANLIB=$(mpif77 -print-file-name="libgfortran.a")
+				if test -f "$FORTRANLIB"; then
+					 AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist, MPI suggests the following library: $FORTRANLIB]);
+				fi
+			 fi
+				AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist!]);
+			fi
+		fi
+		AC_MSG_RESULT(done)
+	fi
+	dnl }}}
+	dnl graphics{{{
+	AC_MSG_CHECKING(for graphics library)
+	AC_ARG_WITH([graphics-lib],
+	  AS_HELP_STRING([--with-graphics-lib = options],[graphics options, for ex: "/usr/X11/lib/libX11.a]),
+	  [GRAPHICS_LIB=$withval],[GRAPHICS_LIB=""])
+
+	dnl check that --with-graphics-lib may have been provided
+	if test -n "$GRAPHICS_LIB" ; then
+		dnl check that library provided EXISTS!
+		GRAPHICS_DIR=$(echo $GRAPHICS_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+		if test -d "$GRAPHICS_DIR" || test -f "$GRAPHICS_DIR"; then
+			HAVE_GRAPHICS=yes
+			GRAPHICSLIB="$GRAPHICS_LIB"
+			AC_DEFINE([_HAVE_GRAPHICS_],[1],[with GRAPHICS in ISSM src])
+			AC_SUBST([GRAPHICSLIB])
+		else
+			if test -f "$PETSC_ROOT/conf/petscvariables"; then
+				GRAPHICSLIB=$(cat $PETSC_ROOT/conf/petscvariables | grep X_LIB)
+				AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB) does not exist, PETSc suggests the following library: $GRAPHICSLIB]);
+			fi
+			AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB$) does not exist!]);
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl meteoio{{{
+	AC_ARG_WITH([meteoio-dir],
+	  AS_HELP_STRING([--with-meteoio-dir=DIR], [use meteoio in conjunction with snowpack model.]),
+	  [METEOIO_ROOT=$withval],[METEOIO_ROOT="no"]) 
+
+	dnl Check whether meteoio is enabled
+	AC_MSG_CHECKING([for meteoio])
+	if test "x$METEOIO_ROOT" = "xno" ; then
+		HAVE_METEOIO=no
+	else
+		HAVE_METEOIO=yes
+		if ! test -d "$METEOIO_ROOT"; then
+			AC_MSG_ERROR([meteoio directory provided ($METEOIO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_METEOIO)
+	
+	dnl meteoio headers and libraries
+	if test "x$HAVE_METEOIO" == "xyes"; then
+		METEOIOINCL="-I$METEOIO_ROOT/include"
+		METEOIOLIB="-dy -L$METEOIO_ROOT/lib  -lmeteoio "
+
+		AC_DEFINE([_HAVE_METEOIO_],[1],[with meteoio])
+		AC_SUBST([METEOIOINCL])
+		AC_SUBST([METEOIOLIB])
+	fi
+	AM_CONDITIONAL([METEOIO], [test x$HAVE_METEOIO = xyes])
+	dnl }}}
+	dnl snowpack{{{
+	AC_ARG_WITH([snowpack-dir],
+	  AS_HELP_STRING([--with-snowpack-dir=DIR], [use snowpack for surface mass balance model.]),
+	  [SNOWPACK_ROOT=$withval],[SNOWPACK_ROOT="no"]) 
+
+	dnl Check whether snowpack is enabled
+	AC_MSG_CHECKING([for snowpack])
+	if test "x$SNOWPACK_ROOT" = "xno" ; then
+		HAVE_SNOWPACK=no
+	else
+		HAVE_SNOWPACK=yes
+		if ! test -d "$SNOWPACK_ROOT"; then
+			AC_MSG_ERROR([snowpack directory provided ($SNOWPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SNOWPACK)
+	
+	dnl snowpack headers and libraries
+	if test "x$HAVE_SNOWPACK" == "xyes"; then
+		SNOWPACKINCL="-I$SNOWPACK_ROOT/include"
+		SNOWPACKLIB="-dy -L$SNOWPACK_ROOT/lib  -lsnowpack "
+
+		AC_DEFINE([_HAVE_SNOWPACK_],[1],[with snowpack for surface mass balance model])
+		AC_SUBST([SNOWPACKINCL])
+		AC_SUBST([SNOWPACKLIB])
+	fi
+	AM_CONDITIONAL([SNOWPACK], [test x$HAVE_SNOWPACK = xyes])
+	dnl }}}
+
+	dnl Capabilities
+	dnl with-kml{{{
+	AC_ARG_WITH([kml],
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
+		[KML=$withval],[KML=yes]) 
+	AC_MSG_CHECKING(for kml capability compilation)
+
+	HAVE_KML=no
+	if test "x$KML" = "xyes"; then
+		HAVE_KML=yes
+		AC_DEFINE([_HAVE_KML_],[1],[with kml capability])
+	fi
+	AM_CONDITIONAL([KML], [test x$HAVE_KML = xyes])
+	AC_MSG_RESULT($HAVE_KML)
+	dnl }}}
+	dnl with-kriging{{{
+	AC_ARG_WITH([kriging],
+		AS_HELP_STRING([--with-kriging = YES],[compile with kriging capabilities (default is yes)]),
+		[KRIGING=$withval],[KRIGING=yes]) 
+	AC_MSG_CHECKING(for kriging capability compilation)
+
+	HAVE_KRIGING=no
+	if test "x$KRIGING" = "xyes"; then
+		HAVE_KRIGING=yes
+		AC_DEFINE([_HAVE_KRIGING_],[1],[with kriging capability])
+	fi
+	AM_CONDITIONAL([KRIGING], [test x$HAVE_KRIGING = xyes])
+	AC_MSG_RESULT($HAVE_KRIGING)
+	dnl }}}
+	dnl with-gia{{{
+		AC_ARG_WITH([gia],
+		AS_HELP_STRING([--with-gia = YES], [compile with gia capabilities (default is no)]),
+		[GIA=$withval],[GIA=no]) 
+	   AC_MSG_CHECKING(for gia capability compilation)
+
+		HAVE_GIA=no
+		if test "x$GIA" = "xyes"; then
+			if test "x$HAVE_MATH77" = "xno"; then
+				 AC_MSG_ERROR([gia requires compilation of math77 library! Reconfigure with --with-math77 option on]);
+			else
+				HAVE_GIA=yes
+				AC_DEFINE([_HAVE_GIA_],[1],[with gia capability])
+		   fi
+		fi
+		AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
+		AC_MSG_RESULT($HAVE_GIA)
+		dnl }}}
+	AX_ANALYSES_SELECTION
+
+	dnl Platform specifics
+	dnl with-ios{{{
+	AC_ARG_WITH([ios],
+		AS_HELP_STRING([--with-ios = YES], [compile with iOS capabilities (default is no, alternatives are yes)]),
+		[IOS=$withval],[IOS=no]) 
+	AC_MSG_CHECKING(for iOS compilation)
+
+	if test "x$IOS" = "xyes"; then
+		dnl defaults
+		HAVE_IOS=yes
+
+		AC_DEFINE([_HAVE_IOS_],[1],[with android capability])
+	elif test "x$IOS" = "xno"; then
+		HAVE_IOS=no
+	else
+	  AC_MSG_ERROR([--with-ios should be either no or yes])
+	fi
+	AM_CONDITIONAL([IOS], [test x$HAVE_IOS != xno])
+	AC_MSG_RESULT($HAVE_IOS)
+	dnl }}}
+	dnl with-android{{{
+	AC_ARG_WITH([android],
+		AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
+		[ANDROID=$withval],[ANDROID=no]) 
+	AC_MSG_CHECKING(for android capability compilation)
+
+	if test "x$ANDROID" = "xjni"; then
+
+		dnl defaults
+		HAVE_ANDROID=jni
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+		AC_DEFINE([_HAVE_ANDROID_JNI_],[1],[with android jni])
+	elif test "x$ANDROID" = "xexe"; then
+		dnl defaults
+		HAVE_ANDROID=exe
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xno"; then
+		HAVE_ANDROID=no
+	else
+	  AC_MSG_ERROR([--with-android should be either no, exe or jni])
+	fi
+	AM_CONDITIONAL([ANDROID], [test x$HAVE_ANDROID != xno])
+	AM_CONDITIONAL([ANDROIDJNI], [test x$HAVE_ANDROID = xjni])
+	AM_CONDITIONAL([ANDROIDEXE], [test x$HAVE_ANDROID = xexe])
+	AC_MSG_RESULT($HAVE_ANDROID)
+	dnl }}}
+	dnl with-android-ndk{{{
+	AC_ARG_WITH([android-ndk],
+	  AS_HELP_STRING([--with-android-ndk=DIR], [android-ndk root directory.]),
+	  [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""]) 
+	AC_MSG_CHECKING(with android ndk)
+	
+	if test -d "$ANDROID_NDK_ROOT"; then
+		dnl defaults
+		HAVE_ANDROID_NDK=yes
+		ANDROID_NDKINCL="-I$ANDROID_NDK_ROOT/arm-linux-android-install/sysroot/usr/include"
+
+		AC_DEFINE([_HAVE_ANDROID_NDK_],[1],[with android ndk in ISSM src])
+		AC_SUBST([ANDROID_NDKINCL])
+	else
+		HAVE_ANDROID_NDK=no
+	fi
+	AC_MSG_RESULT($HAVE_ANDROID_NDK)
+	dnl }}}
+
+	dnl other options
+	dnl optimization{{{
+	dnl bypass standard optimization -g -O2 ? 
+	AC_ARG_WITH([cxxoptflags],
+	  AS_HELP_STRING([--with-cxxoptflags = CXXOPTFLAGS], [optimization using CXX flags, ex: --with-cxxoptflags=-march=opteron -O3]),
+	  [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2"]) 
+	AC_MSG_CHECKING(for c++ optimization flags)
+	AC_SUBST([CXXOPTFLAGS])
+	AC_MSG_RESULT(done)
+
+	dnl }}}
+	dnl multithreading{{{
+	AC_ARG_WITH([numthreads],
+	  AS_HELP_STRING([--with-numthreads = NUMTHREADS_VALUE],[numthreads, default is 1. ]),
+	  [NUMTHREADS_VALUE=$withval],[NUMTHREADS_VALUE=1])
+	AC_MSG_CHECKING(for number of threads)
+	dnl defaults
+	MULTITHREADING=no
+	MULTITHREADINLIB=""
+	if test "$NUMTHREADS_VALUE" != "1"; then
+		
+		MULTITHREADINGLIB="-lpthread -lrt"
+		case "${host_os}" in
+		*cygwin*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*linux*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*darwin*)
+		MULTITHREADINGLIB="-lpthread"
+		;;
+		esac
+		AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
+	fi
+	AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
+	AC_SUBST([MULTITHREADINGLIB])
+	AC_MSG_RESULT($NUMTHREADS_VALUE) 
+	dnl }}}
+	dnl 64bit {{{
+	AC_ARG_WITH([64bit-indices],
+	  AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
+	  [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
+	AC_MSG_CHECKING(for 64 bit indices)
+
+	if test "$USE_64BIT_INDICES" == "1"; then
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[1],[with 64 bits indices])
+	else
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[0],[with 64 bits indices])
+	fi
+	AC_MSG_RESULT($USE_64BIT_INDICES)
+	dnl }}}
+
+	dnl Checks
+	dnl checks{{{
+		AC_MSG_CHECKING(consistency between all libraries)
+
+		  dnl check that if petsc is requested , mpi should be specified
+		  if test "$HAVE_PETSC" = "yes" ; then
+				if test "$HAVE_MPI" = "NO";  then
+					 AC_MSG_ERROR([petsc requires mpi!]);
+				fi
+		  fi
+
+		  dnl check that we have either python or matlab support if we compile the modules
+		  if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
+				AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
+		  fi
+
+		  dnl check that if we have MPI, we have metis
+		  if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
+				AC_MSG_ERROR([need mpi if using the metis partitioner!]);
+		  fi
+		
+		dnl check that if we run adolc, we don't compile krigging.exe
+		if test "$HAVE_ADOLC" = "yes"  && test "$HAVE_KRIGING" = "yes" ; then
+			AC_MSG_ERROR([cannot compile kriging.exe under adolc conditions!]);
+		fi
+		dnl check that if we run meteoio, we have snowpack also
+		if test "$HAVE_METEOIO" = "yes"  && test "$HAVE_SNOWPACK" = "no" ; then
+			AC_MSG_ERROR([cannot compile MeteoIO package without Snowpack!]);
+		fi
+		dnl check that if we run snowpack, we have meteoio also
+		if test "$HAVE_METEOIO" = "no"  && test "$HAVE_SNOWPACK" = "yes" ; then
+			AC_MSG_ERROR([cannot compile Snowpack package without MeteoIO!]);
+		fi
+
+		AC_MSG_RESULT(done)
+		dnl }}}
+])
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/Info.plist
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/Info.plist	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/Info.plist	(revision 18231)
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleAllowMixedLocalizations</key>
+	<true/>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>English</string>
+	<key>CFBundleExecutable</key>
+	<string>applet</string>
+	<key>CFBundleIconFile</key>
+	<string>applet</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>ISSM</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleSignature</key>
+	<string>aplt</string>
+	<key>LSMinimumSystemVersionByArchitecture</key>
+	<dict>
+		<key>x86_64</key>
+		<string>10.6</string>
+	</dict>
+	<key>LSRequiresCarbon</key>
+	<true/>
+	<key>WindowState</key>
+	<dict>
+		<key>dividerCollapsed</key>
+		<false/>
+		<key>eventLogLevel</key>
+		<integer>-1</integer>
+		<key>name</key>
+		<string>ScriptWindowState</string>
+		<key>positionOfDivider</key>
+		<real>333</real>
+		<key>savedFrame</key>
+		<string>3 428 602 597 0 0 1680 1028 </string>
+		<key>selectedTabView</key>
+		<string>result</string>
+	</dict>
+</dict>
+</plist>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/PkgInfo
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/PkgInfo	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.app/Contents/PkgInfo	(revision 18231)
@@ -0,0 +1,1 @@
+APPLaplt
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.appscript
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.appscript	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.appscript	(revision 18231)
@@ -0,0 +1,1 @@
+do shell script "open ~/ISSM/bin/matlabissm"
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm-contents.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm-contents.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm-contents.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkg-contents spec="1.12"><f n="ISSM.app" o="larour" g="admin" p="16893" pt="/Users/larour/issm-uci/trunk-jpl/packagers/macosx/ISSM.app" m="true" t="file"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="Contents" o="larour" g="admin" p="16893"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><f n="Info.plist.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="PkgInfo.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="Info.plist" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="MacOS" o="larour" g="admin" p="16893"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><f n="applet.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><f n="applet.svn-base" o="larour" g="admin" p="33277"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="applet" o="larour" g="admin" p="33277"><mod>mode</mod></f><mod>mode</mod></f><f n="PkgInfo" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="Resources" o="larour" g="admin" p="16893"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><f n="applet.icns.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="applet.rsrc.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><f n="applet.icns.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="applet.rsrc.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="applet.icns" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="applet.rsrc" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="description.rtfd" o="larour" g="admin" p="16893"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><f n="TXT.rtf.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="TXT.rtf" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="Scripts" o="larour" g="admin" p="16893"><f n=".svn" o="larour" g="admin" p="16893"><f n="all-wcprops" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="larour" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="larour" g="admin" p="16893"><f n="main.scpt.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><f n="main.scpt.svn-base" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="larour" g="admin" p="16893"><f n="prop-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="larour" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="larour" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="main.scpt" o="larour" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><mod>group</mod><mod>mode</mod></f></pkg-contents>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/01issm.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkgref spec="1.12" uuid="280C4FF1-FB54-447F-B616-1EB3C56397F9"><config><identifier>ISSM.pkg</identifier><version>1.0</version><description></description><post-install type="none"/><requireAuthorization/><installFrom mod="true" includeRoot="true">/Users/larour/issm-uci/trunk-jpl/packagers/macosx/ISSM.app</installFrom><installTo mod="true">/ISSM/</installTo><flags><followSymbolicLinks/></flags><packageStore type="internal"></packageStore><mod>installTo</mod><mod>relocatable</mod><mod>installFrom.path</mod><mod>identifier</mod><mod>parent</mod><mod>includeRoot</mod><mod>requireAuthorization</mod><mod>installTo.path</mod></config><contents><file-list>01issm-contents.xml</file-list><filter>/CVS$</filter><filter>/\.svn$</filter><filter>/\.cvsignore$</filter><filter>/\.cvspass$</filter><filter>/\.DS_Store$</filter></contents></pkgref>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin-contents.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin-contents.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin-contents.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkg-contents spec="1.12"><f n="bin" o="root" g="admin" p="16877" pt="/Users/larour/issm-uci/trunk-jpl/packagers/macosx/bin" m="false" t="file"><f n="startup.m" o="root" g="admin" p="33277"><mod>mode</mod></f><mod>group</mod><mod>owner</mod></f></pkg-contents>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/02bin.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkgref spec="1.12" uuid="18E7DF11-93BD-47ED-B9FE-56870B61EB72"><config><identifier>issm.bin.pkg</identifier><version>1.0</version><description></description><post-install type="none"/><requireAuthorization/><installFrom mod="true">/Users/larour/issm-uci/trunk-jpl/packagers/macosx/bin</installFrom><installTo mod="true">/ISSM/bin</installTo><flags><followSymbolicLinks/></flags><packageStore type="internal"></packageStore><mod>installTo.path</mod><mod>parent</mod><mod>installFrom.path</mod><mod>includeRoot</mod><mod>identifier</mod><mod>installTo</mod></config><contents><file-list>02bin-contents.xml</file-list><filter>/CVS$</filter><filter>/\.svn$</filter><filter>/\.cvsignore$</filter><filter>/\.cvspass$</filter><filter>/\.DS_Store$</filter></contents></pkgref>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test-contents.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test-contents.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test-contents.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkg-contents spec="1.12"><f n="test" o="root" g="admin" p="16877" pt="/Users/larour/issm-uci/trunk-jpl/packagers/macosx/test" m="false" t="file"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="Archives" o="root" g="admin" p="16893"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><f n="Archive101.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive102.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive103.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive104.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive105.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive106.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive107.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive108.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive109.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive110.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1101.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1102.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1103.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1104.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1105.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1106.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1107.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1108.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1109.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive111.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1110.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive112.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive113.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive114.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive115.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive116.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive117.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive118.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive119.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive120.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1201.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1202.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1203.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1204.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1205.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1206.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1207.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1208.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive121.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive122.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive123.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive124.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive125.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive126.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive127.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive128.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive129.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive130.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1301.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1302.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1303.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1304.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive131.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive132.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive133.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive134.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive135.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive136.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive137.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive139.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive140.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1401.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1402.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive141.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive142.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive143.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive144.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1501.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1502.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1601.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1602.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive201.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive202.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive203.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive204.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive205.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive206.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive207.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive208.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive209.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive210.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive211.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive212.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive213.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive214.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive215.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive216.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive217.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive218.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive219.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive220.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive221.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive222.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive223.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive224.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive225.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive226.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive227.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive228.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive229.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive230.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive232.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive233.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive234.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive235.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive236.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive237.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive238.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive239.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive240.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive241.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive242.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive243.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive244.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive245.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive246.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive247.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive248.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive249.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive250.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive251.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive252.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive253.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive254.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive255.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive256.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive257.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive258.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive259.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive260.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive261.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive262.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive263.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive264.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive265.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive266.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive267.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive268.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive301.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive302.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive303.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive304.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive305.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive306.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive307.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive308.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive309.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive310.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive311.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive312.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive313.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive314.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive315.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive316.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive317.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive318.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive319.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive320.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive321.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive322.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive323.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive324.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive325.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive326.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive327.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive328.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive329.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive330.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive331.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive332.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive333.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive334.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive335.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive336.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive337.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive338.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive339.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive340.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive341.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive342.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive343.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive344.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive345.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive346.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive347.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive348.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive349.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive350.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive351.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive352.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive353.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive354.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive401.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive402.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive403.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive404.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive405.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive406.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive407.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive408.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive409.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive410.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive411.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive412.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive413.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive414.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive415.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive416.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive417.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive418.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive419.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive420.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive421.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive422.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive423.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive424.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive425.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive426.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive427.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive428.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive429.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive430.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive431.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive432.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive434.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive435.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive437.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive438.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive439.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive440.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive441.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive442.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive443.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive444.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive445.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive446.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive447.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive448.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive449.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive450.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive451.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive452.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive453.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive454.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive501.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive502.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive503.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive504.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive505.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive506.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive507.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive508.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive509.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive510.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive511.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive512.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive513.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive514.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive515.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive516.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive517.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive518.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive519.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive520.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive521.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive522.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive523.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive524.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive525.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive526.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive527.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive529.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive530.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive531.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive532.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive601.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive602.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive603.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive604.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive605.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive606.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive607.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive608.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive609.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive610.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive611.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive612.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive613.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive614.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive615.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive616.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive617.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive618.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive619.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive620.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive621.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive622.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive623.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive624.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive625.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive626.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><f n="Archive101.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive102.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive103.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive104.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive105.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive106.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive107.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive108.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive109.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive110.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1101.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1102.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1103.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1104.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1105.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1106.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1107.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1108.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1109.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive111.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1110.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive112.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive113.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive114.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive115.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive116.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive117.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive118.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive119.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive120.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1201.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1202.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1203.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1204.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1205.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1206.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1207.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1208.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive121.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive122.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive123.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive124.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive125.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive126.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive127.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive128.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive129.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive130.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1301.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1302.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1303.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1304.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive131.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive132.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive133.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive134.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive135.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive136.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive137.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive139.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive140.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1401.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1402.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive141.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive142.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive143.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive144.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1501.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1502.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1601.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1602.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive201.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive202.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive203.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive204.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive205.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive206.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive207.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive208.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive209.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive210.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive211.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive212.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive213.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive214.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive215.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive216.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive217.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive218.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive219.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive220.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive221.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive222.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive223.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive224.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive225.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive226.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive227.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive228.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive229.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive230.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive232.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive233.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive234.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive235.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive236.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive237.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive238.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive239.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive240.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive241.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive242.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive243.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive244.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive245.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive246.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive247.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive248.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive249.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive250.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive251.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive252.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive253.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive254.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive255.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive256.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive257.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive258.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive259.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive260.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive261.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive262.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive263.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive264.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive265.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive266.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive267.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive268.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive301.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive302.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive303.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive304.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive305.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive306.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive307.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive308.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive309.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive310.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive311.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive312.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive313.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive314.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive315.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive316.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive317.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive318.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive319.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive320.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive321.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive322.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive323.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive324.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive325.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive326.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive327.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive328.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive329.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive330.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive331.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive332.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive333.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive334.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive335.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive336.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive337.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive338.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive339.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive340.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive341.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive342.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive343.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive344.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive345.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive346.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive347.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive348.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive349.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive350.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive351.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive352.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive353.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive354.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive401.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive402.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive403.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive404.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive405.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive406.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive407.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive408.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive409.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive410.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive411.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive412.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive413.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive414.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive415.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive416.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive417.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive418.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive419.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive420.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive421.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive422.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive423.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive424.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive425.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive426.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive427.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive428.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive429.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive430.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive431.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive432.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive434.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive435.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive437.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive438.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive439.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive440.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive441.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive442.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive443.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive444.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive445.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive446.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive447.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive448.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive449.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive450.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive451.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive452.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive453.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive454.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive501.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive502.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive503.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive504.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive505.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive506.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive507.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive508.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive509.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive510.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive511.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive512.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive513.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive514.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive515.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive516.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive517.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive518.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive519.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive520.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive521.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive522.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive523.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive524.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive525.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive526.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive527.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive529.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive530.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive531.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive532.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive601.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive602.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive603.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive604.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive605.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive606.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive607.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive608.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive609.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive610.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive611.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive612.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive613.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive614.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive615.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive616.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive617.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive618.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive619.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive620.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive621.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive622.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive623.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive624.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive625.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive626.mat.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="Archive101.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive102.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive103.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive104.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive105.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive106.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive107.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive108.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive109.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive110.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1101.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1102.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1103.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1104.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1105.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1106.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1107.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1108.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1109.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive111.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1110.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive112.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive113.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive114.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive115.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive116.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive117.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive118.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive119.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive120.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1201.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1202.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1203.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1204.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1205.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1206.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1207.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1208.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive121.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive122.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive123.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive124.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive125.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive126.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive127.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive128.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive129.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive130.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1301.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1302.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1303.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1304.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive131.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive132.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive133.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive134.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive135.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive136.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive137.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive139.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive140.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1401.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1402.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive141.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive142.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive143.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive144.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1501.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1502.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1601.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive1602.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive201.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive202.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive203.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive204.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive205.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive206.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive207.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive208.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive209.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive210.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive211.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive212.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive213.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive214.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive215.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive216.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive217.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive218.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive219.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive220.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive221.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive222.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive223.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive224.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive225.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive226.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive227.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive228.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive229.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive230.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive232.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive233.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive234.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive235.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive236.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive237.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive238.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive239.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive240.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive241.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive242.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive243.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive244.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive245.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive246.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive247.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive248.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive249.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive250.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive251.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive252.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive253.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive254.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive255.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive256.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive257.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive258.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive259.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive260.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive261.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive262.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive263.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive264.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive265.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive266.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive267.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive268.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive301.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive302.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive303.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive304.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive305.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive306.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive307.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive308.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive309.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive310.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive311.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive312.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive313.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive314.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive315.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive316.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive317.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive318.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive319.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive320.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive321.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive322.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive323.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive324.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive325.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive326.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive327.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive328.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive329.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive330.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive331.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive332.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive333.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive334.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive335.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive336.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive337.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive338.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive339.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive340.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive341.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive342.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive343.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive344.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive345.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive346.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive347.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive348.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive349.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive350.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive351.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive352.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive353.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive354.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive401.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive402.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive403.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive404.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive405.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive406.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive407.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive408.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive409.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive410.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive411.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive412.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive413.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive414.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive415.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive416.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive417.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive418.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive419.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive420.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive421.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive422.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive423.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive424.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive425.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive426.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive427.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive428.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive429.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive430.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive431.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive432.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive434.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive435.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive437.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive438.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive439.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive440.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive441.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive442.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive443.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive444.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive445.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive446.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive447.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive448.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive449.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive450.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive451.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive452.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive453.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive454.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive501.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive502.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive503.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive504.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive505.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive506.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive507.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive508.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive509.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive510.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive511.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive512.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive513.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive514.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive515.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive516.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive517.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive518.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive519.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive520.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive521.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive522.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive523.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive524.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive525.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive526.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive527.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive529.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive530.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive531.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive532.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive601.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive602.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive603.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive604.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive605.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive606.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive607.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive608.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive609.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive610.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive611.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive612.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive613.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive614.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive615.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive616.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive617.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive618.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive619.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive620.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive621.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive622.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive623.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive624.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive625.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Archive626.mat" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="Data" o="root" g="admin" p="16893"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><f n="79North.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetShelf.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelfConstrained.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><f n="79North.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetShelf.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelfConstrained.data.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="79North.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetShelf.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.data" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelfConstrained.data" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="Exp" o="root" g="admin" p="16893"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><f n="ISMIP10000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP100000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP160000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP20000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP40000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP5000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP80000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_10000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_160000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_20000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_40000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_5000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_80000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareFront.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareHalfRight.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareHole.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareISMIP.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><f n="79North.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="79NorthShelf.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="CrossLineEISMINT.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP10000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP100000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP160000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP20000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP40000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP5000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP80000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux1.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux2.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux3.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux4.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux5.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux6.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="PigIslands.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="PigShelves.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Rifts.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundFrontEISMINT.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_10000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_160000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_20000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_40000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_5000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square_80000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareEISMINT.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareEISMINT750000.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareFront.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareFrontEISMINT.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareHalfRight.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareHole.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareISMIP.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareRifts.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareRiftsLateral.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.exp.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="79North.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="79NorthShelf.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="CrossLineEISMINT.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIP10000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP100000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP160000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP20000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP40000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP5000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIP80000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPE.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="MassFlux1.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux2.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux3.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux4.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux5.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="MassFlux6.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="PigIslands.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="PigShelves.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Rifts.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundFrontEISMINT.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Square.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_10000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_160000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_20000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_40000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_5000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Square_80000.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareEISMINT.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareEISMINT750000.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareFront.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareFrontEISMINT.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareHalfRight.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareHole.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareISMIP.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareRifts.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareRiftsLateral.exp" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.exp" o="root" g="admin" p="33277"><mod>mode</mod></f><mod>mode</mod></f><f n="NightlyRun" o="root" g="admin" p="16893"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="dir-prop-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><f n="IdToName.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="runme.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1205.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1206.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1207.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1208.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1301.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1302.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1303.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1304.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><f n="dak.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="IdFromString.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="IdToName.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Makefile.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="README.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="runme.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test101.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test102.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test103.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test104.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test105.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test106.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test107.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test108.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test109.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test110.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1101.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1102.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1103.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1104.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1105.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1106.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1107.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1108.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1109.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test111.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1110.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test112.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test113.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test114.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test115.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test116.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test117.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test118.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test119.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test120.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1201.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1202.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1203.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1204.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1205.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1206.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1207.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1208.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test121.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test122.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test123.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test124.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test125.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test126.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test127.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test128.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test129.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test130.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1301.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1302.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1303.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1304.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test131.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test132.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test133.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test134.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test135.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test136.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test137.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test139.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test140.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1401.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1402.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test141.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test142.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test143.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test144.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1501.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1502.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1601.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1602.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test201.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test202.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test203.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test204.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test205.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test206.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test207.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test208.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test209.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test210.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test211.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test212.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test213.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test214.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test215.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test216.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test217.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test218.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test219.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test220.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test221.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test222.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test223.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test224.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test225.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test226.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test227.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test228.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test229.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test230.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test232.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test233.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test234.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test235.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test236.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test237.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test238.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test239.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test240.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test241.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test242.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test243.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test244.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test245.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test246.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test247.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test248.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test249.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test250.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test251.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test252.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test253.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test254.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test255.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test256.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test257.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test258.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test259.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test260.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test261.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test262.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test263.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test264.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test265.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test266.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test267.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test268.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test301.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test302.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test303.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test304.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test305.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test306.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test307.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test308.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test309.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test310.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test311.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test312.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test313.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test314.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test315.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test316.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test317.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test318.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test319.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test320.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test321.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test322.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test323.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test324.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test325.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test326.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test327.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test328.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test329.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test330.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test331.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test332.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test333.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test334.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test335.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test336.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test337.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test338.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test339.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test340.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test341.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test342.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test343.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test344.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test345.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test346.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test347.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test348.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test349.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test350.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test351.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test352.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test353.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test354.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test401.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test402.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test403.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test404.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test405.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test406.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test407.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test408.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test409.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test410.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test411.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test412.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test413.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test414.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test415.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test416.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test417.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test418.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test419.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test420.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test421.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test422.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test423.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test424.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test425.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test426.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test427.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test428.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test429.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test430.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test431.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test432.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test434.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test435.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test437.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test438.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test439.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test440.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test441.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test442.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test443.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test444.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test445.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test446.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test447.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test448.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test449.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test450.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test451.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test452.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test453.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test454.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test501.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test502.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test503.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test504.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test505.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test506.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test507.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test508.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test509.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test510.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test511.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test512.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test513.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test514.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test515.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test516.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test517.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test518.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test519.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test520.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test521.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test522.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test523.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test524.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test525.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test526.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test527.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test529.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test530.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test531.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test532.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test601.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test602.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test603.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test604.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test605.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test606.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test607.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test608.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test609.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test610.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test611.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test612.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test613.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test614.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test615.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test616.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test617.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test618.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test619.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test620.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test621.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test622.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test623.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test624.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test625.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test626.m.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="dak.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="IdFromString.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="IdToName.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Makefile" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="README" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="runme.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test101.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test102.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test103.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test104.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test105.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test106.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test107.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test108.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test109.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test110.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1101.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1102.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1103.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1104.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1105.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1106.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1107.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1108.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1109.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test111.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1110.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test112.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test113.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test114.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test115.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test116.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test117.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test118.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test119.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test120.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1201.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1202.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1203.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1204.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1205.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1206.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1207.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1208.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test121.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test122.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test123.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test124.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test125.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test126.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test127.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test128.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test129.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test130.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1301.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1302.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1303.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test1304.m" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="test131.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test132.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test133.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test134.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test135.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test136.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test137.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test139.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test140.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1401.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1402.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test141.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test142.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test143.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test144.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1501.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1502.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1601.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test1602.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test201.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test202.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test203.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test204.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test205.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test206.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test207.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test208.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test209.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test210.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test211.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test212.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test213.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test214.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test215.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test216.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test217.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test218.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test219.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test220.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test221.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test222.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test223.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test224.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test225.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test226.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test227.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test228.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test229.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test230.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test232.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test233.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test234.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test235.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test236.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test237.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test238.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test239.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test240.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test241.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test242.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test243.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test244.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test245.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test246.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test247.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test248.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test249.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test250.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test251.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test252.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test253.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test254.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test255.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test256.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test257.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test258.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test259.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test260.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test261.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test262.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test263.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test264.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test265.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test266.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test267.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test268.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test301.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test302.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test303.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test304.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test305.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test306.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test307.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test308.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test309.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test310.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test311.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test312.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test313.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test314.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test315.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test316.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test317.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test318.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test319.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test320.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test321.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test322.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test323.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test324.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test325.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test326.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test327.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test328.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test329.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test330.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test331.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test332.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test333.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test334.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test335.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test336.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test337.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test338.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test339.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test340.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test341.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test342.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test343.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test344.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test345.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test346.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test347.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test348.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test349.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test350.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test351.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test352.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test353.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test354.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test401.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test402.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test403.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test404.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test405.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test406.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test407.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test408.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test409.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test410.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test411.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test412.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test413.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test414.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test415.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test416.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test417.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test418.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test419.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test420.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test421.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test422.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test423.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test424.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test425.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test426.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test427.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test428.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test429.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test430.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test431.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test432.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test434.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test435.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test437.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test438.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test439.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test440.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test441.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test442.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test443.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test444.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test445.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test446.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test447.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test448.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test449.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test450.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test451.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test452.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test453.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test454.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test501.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test502.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test503.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test504.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test505.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test506.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test507.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test508.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test509.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test510.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test511.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test512.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test513.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test514.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test515.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test516.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test517.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test518.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test519.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test520.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test521.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test522.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test523.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test524.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test525.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test526.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test527.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test529.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test530.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test531.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test532.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test601.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test602.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test603.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test604.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test605.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test606.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test607.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test608.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test609.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test610.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test611.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test612.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test613.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test614.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test615.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test616.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test617.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test618.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test619.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test620.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test621.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test622.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test623.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test624.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test625.m" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="test626.m" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="Par" o="root" g="admin" p="16893"><f n=".svn" o="root" g="admin" p="16893"><f n="all-wcprops" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="entries" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="prop-base" o="root" g="admin" p="16893"><f n="79North.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPA.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPB.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPC.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPD.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPF.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetEISMINT.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetStaticEISMINT.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelfConstrained.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareThermal.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><f n="79North.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPA.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPB.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPC.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPD.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPE.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="ISMIPF.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="Pig.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetEISMINT.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="RoundSheetStaticEISMINT.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareEISMINT.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelf.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareShelfConstrained.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareThermal.par.svn-base" o="root" g="admin" p="33204"><mod>mode</mod></f><mod>mode</mod></f><f n="tmp" o="root" g="admin" p="16893"><f n="prop-base" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="props" o="root" g="admin" p="16893"><mod>mode</mod></f><f n="text-base" o="root" g="admin" p="16893"><mod>mode</mod></f><mod>mode</mod></f><mod>mode</mod></f><f n="79North.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPA.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPB.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPC.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPD.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPE.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="ISMIPF.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="Pig.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="RoundSheetEISMINT.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="RoundSheetShelf.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="RoundSheetStaticEISMINT.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareEISMINT.par" o="root" g="admin" p="33204"><mod>mode</mod></f><f n="SquareSheetConstrained.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareSheetShelf.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareShelf.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareShelfConstrained.par" o="root" g="admin" p="33277"><mod>mode</mod></f><f n="SquareThermal.par" o="root" g="admin" p="33277"><mod>mode</mod></f><mod>mode</mod></f><mod>group</mod><mod>owner</mod></f></pkg-contents>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/03test.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkgref spec="1.12" uuid="B3D6E8F8-4650-477C-8E99-0122145B211E"><config><identifier>issm.test.pkg</identifier><version>1.0</version><description></description><post-install type="none"/><requireAuthorization/><installFrom mod="true">/Users/larour/issm-uci/trunk-jpl/packagers/macosx/test</installFrom><installTo mod="true">/ISSM/test</installTo><flags><followSymbolicLinks/></flags><packageStore type="internal"></packageStore><mod>installTo</mod><mod>relocatable</mod><mod>installFrom.path</mod><mod>scripts.postinstall.path</mod><mod>identifier</mod><mod>parent</mod><mod>includeRoot</mod><mod>installTo.path</mod></config><contents><file-list>03test-contents.xml</file-list><filter>/CVS$</filter><filter>/\.svn$</filter><filter>/\.cvsignore$</filter><filter>/\.cvspass$</filter><filter>/\.DS_Store$</filter></contents></pkgref>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/index.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/index.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/ISSM.pmdoc/index.xml	(revision 18231)
@@ -0,0 +1,1 @@
+<pkmkdoc spec="1.12"><properties><title>ISSM</title><build>/Users/larour/issm-uci/trunk-jpl/packagers/macosx/ISSM.pkg</build><organization>http://issm.jpl.nasa.gov</organization><userSees ui="both"/><min-target os="3"/><domain user="true"/></properties><distribution><versions min-spec="1.000000"/><scripts></scripts></distribution><description>Ice Sheet System Model</description><contents><choice title="ISSM" id="choice3" starts_selected="true" starts_enabled="true" starts_hidden="false"><pkgref id="ISSM.pkg"/></choice><choice title="bin" id="choice6" starts_selected="true" starts_enabled="true" starts_hidden="false"><pkgref id="issm.bin.pkg"/></choice><choice title="test" id="choice16" starts_selected="true" starts_enabled="true" starts_hidden="false"><pkgref id="issm.test.pkg"/></choice></contents><resources bg-scale="none" bg-align="topleft"><locale lang="en"/></resources><flags/><item type="file">01issm.xml</item><item type="file">02bin.xml</item><item type="file">03test.xml</item><mod>properties.title</mod><mod>properties.userDomain</mod><mod>description</mod><mod>properties.anywhereDomain</mod></pkmkdoc>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/README	(revision 18231)
@@ -0,0 +1,16 @@
+Files needsed to package ISSM into a MacOSX delivery: 
+
+ISSM.appscript : applescript file used by Script Editor to build ISSM.app. Just edit using applescript, and save 
+as application. 
+
+ISSM.app: result of above. 
+
+ISSM.pmdoc: Package Maker project, which outputs ISSM.pkg
+
+ISSM.pkg: result of above. 
+
+Package Maker can be command line driven, using the pmdoc project directly. This is what package.sh does.
+
+issm.icns: icon file for ISSM install.
+matlabissm: used by the Package Maker to launch matlab with ISSM path sourced. 
+startup.m: needed to be sourced by Matlab to point towards mac executables.
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/matlabissm
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/matlabissm	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/matlabissm	(revision 18231)
@@ -0,0 +1,4 @@
+#/bin/bash
+user_home=`echo ~`;
+export  ISSM_TIER="$user_home/ISSM"
+matlab -r "name=getenv('USER'); issm=['/Users/' name '/ISSM']; cd(issm); cd bin; startup; cd ../;"
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package.sh	(revision 18231)
@@ -0,0 +1,25 @@
+#/bin/bash
+
+#Package using the Package Maker from OSX, driven by command line.
+echo "Cleanup first" 
+sudo sh -c "rm -rf ISSM-MacOSX.pkg bin test"
+
+#We need to copy all the relevant files and set the permissions, as PackageMaker 
+#is not good at that. 
+echo "Copy bin" 
+cp -Rf $ISSM_TIER/bin ./
+echo "Copy test" 
+cp -Rf $ISSM_TIER/test ./
+cp matlabissm startup.m ./bin
+
+#Now change group and ownership: 
+echo "Change group and ownership" 
+sudo sh -c "chown -R root ./bin && chgrp -R admin ./bin"
+sudo sh -c "chown -R root ./test && chgrp -R admin ./test"
+
+echo "Launch packagemaker" 
+PackageMaker -d ISSM.pmdoc -o ISSM-MacOSX.pkg
+
+#cleanup
+echo "Final cleanup"
+sudo sh -c "rm -rf ./bin && rm -rf ./test"
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package_incomplete.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package_incomplete.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/package_incomplete.sh	(revision 18231)
@@ -0,0 +1,16 @@
+#/bin/bash
+
+#Package using the Package Maker from OSX, driven by command line.
+sudo sh -c "rm -rf ISSM-MacOSX.pkg bin test"
+
+#We need to copy all the relevant files and set the permissions, as PackageMaker 
+#is not good at that. 
+cp -Rf $ISSM_TIER/bin ./
+cp -Rf $ISSM_TIER/test ./
+cp matlabissm startup.m ./bin
+
+#Now change group and ownership: 
+sudo sh -c "chown -R root ./bin && chgrp -R admin ./bin"
+sudo sh -c "chown -R root ./test && chgrp -R admin ./test"
+
+#Run PackageMaker now, using the ISSM.pmdoc project
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/startup.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/startup.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/macosx/startup.m	(revision 18231)
@@ -0,0 +1,45 @@
+%STARTUP - Matlab startup script
+%
+%   startup.m is a script run by matlab at the beginning of a session, just
+%   before handing over the prompt to the user. This delivery startup.m script
+%   has been customized here for the ISSM code. This startup script should be
+%   run by users before trying to use ISSM. The best way to do that is to put
+%   the startup file in the location where Matlab starts and established its
+%   root directory.
+
+% clear the last warning to focus on the warnings of the ISSM path
+lastwarn(''); 
+
+%Recover ISSM_TIER , or if on a Windows machine, ISSM_TIER_WIN
+ISSM_TIER=getenv('ISSM_TIER');
+
+if (isempty(ISSM_TIER)),
+	error('issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!');
+end
+
+%Now add all issm code paths necessary to run issm smoothly. 
+%We capture the error output, so that we can warn the user to update 
+%the variable ISSM_TIER in this file, in case it is not correctly setup. 
+
+%ISSM path
+addpath(pwd); %add current path first
+
+%Check on any warning messages that might indicate that the paths were not correct. 
+if ~isempty(lastwarn),
+	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_TIER variable in your .cshrc or .bashrc!\n');
+	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
+else
+	fprintf('\n  To get started with ISSM, type issmdoc at the command prompt.\n\n');
+end
+
+%disable matlab bell!
+beep off;
+
+% no warning if we try to plot while in nojvm (will not be supported in future releases)
+warning off MATLAB:HandleGraphics:noJVM
+
+%at the end, get to tests directory if ISSM_TESTS exists: 
+ISSM_TESTS=getenv('ISSM_TESTS');
+if ~isempty(ISSM_TESTS),
+	cd(ISSM_TESTS);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/README	(revision 18231)
@@ -0,0 +1,60 @@
+TARBALL INSTALLATION:
+
+To install ISSM, untar ISSM-Ubuntu32.tar.gz 
+You will get an ISSM directory. 
+
+You then need to setup the following environment variable in your 
+.bashrc or .cshrc: 
+
+in your .bashrc: 
+export ISSM_TIER='path_to_untarred_ISSM/bin'
+
+or in your .cshrc: 
+setenv ISSM_TIER 'path_to_untarred_ISSM'
+
+Once this is done, fireup matlab from inside the ISSM directory: 
+matlab -nojvm -r "startup;"
+
+
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
+-------------------------------------------------------------------------------
+				OR THE RIGHT WAY....
+DPKG/DEB INSTALLATION:
+
+To install from deb archives (*.deb), use:
+
+	> sudo dpkg --install <debarchive>
+
+That's it! But not really. Do make sure that you install petsc and metis first.
+When you first try to install issm, dpkg will tell you that you are missing
+dependencies. Just:
+
+	> sudo apt-get install -f
+
+to fix the dependencies and complete the install. When apt-get is done, you 
+should see something that says that ISSM is installed correctly on your 
+machine. That's it! For real this time.
+
+Uninstalling is simple too:
+
+	> sudo apt-get remove <issmPackageName>
+
+That'll do all the work for you. This won't delete any configuration or user
+defined environment stuff. Just swap "remove" out for "purge" and that'll
+delete everything. And apt-get might ask you to remove unneeded dependencies,
+so you should probably do that to keep your system clean.
+
+To create your own custom debian archive, see the README in issmpkg.
+
+-------------------------------------------------------------------------------
+
+APT-GET INSTALLATION: (this doesnot work yet)
+
+To install from apt-get:
+
+	> sudo add-apt-repository <issm_PPA_URL>
+	> sudo apt-get install <issmPackageName>
+
+Just say yes to everything apt asks you, and you're good.
+
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/README	(revision 18231)
@@ -0,0 +1,138 @@
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
+
+PREFACE:
+	There are configuration files included in the dir where this document
+	 resides. Use them, that's why they're there. But I know, since some of
+	 you like to go against the grain, at least one of you is going to try
+	 building a package from an install that differs from mine.
+
+	If you choose to go down that dark road, then bear in mind that there
+	 are ways to do this right, and there are ways to do this wrong....
+	 Make sure that you mind where you decide to install the bin and lib.
+	 If you specify a target outside of the trunk, and don't, let's say,
+	 write the same dir somewhere else, then the package won't work. 
+
+	Make sure when putting together a dir hierarchy for a package, that you
+	 create something sime to what you specifed during compile. If you
+	 change "--bindir" then create a dir in the package that corresponds to
+	 that. The trunk doesn't necessarily have to be in the same place as it
+	 is on the build system.
+
+-------------------------------------------------------------------------------
+		    Installing ISSM to create a deb package:
+-------------------------------------------------------------------------------
+
+1.	Install mpich from the ubuntu repositories:
+
+		> sudo apt-get install mpich2 (or something similar)
+
+		Check to make sure that it installs the "-dev" libs
+			if not:
+			 > sudo apt-get install libmpich-dev (or something similar)
+			Otherwise you won't get "/usr/lib/mpich2"
+
+		You can use "apt-cache search" to find a package's full name
+
+2a.	Compile petsc and metis (preferred versions: 3.2 and 4.0, respectively):
+
+		Make sure that petsc's installer file is pointing to the
+		 correct mpich dir
+
+			You should use "/usr/lib/mpich2" (or something similar)
+
+		As of now, it is preferable to use the separate mpich package
+		 because the infrastructure of the mpich package under petsc
+		 is having issues with being packaged
+
+		Also make sure that you mind the target of the installation.
+			Right now /usr/share/petsc and /usr/share/metis are the
+			 best options suffixed by version numbers
+
+2b.	Install dependencies from the ubuntu repositories
+
+		Use apt-get install to install:
+			triangle-bin, libtriangle-dev, python2.7-dev, 
+			 python-scipy, python-netcdf4, netcdf-bin, python-nose, 
+			 libnetcdfc++4, hdf5-tools
+
+		REMEMBER: that this tutorial assumes you are creating the
+		 python interface
+			
+3.	Be sure to patch the system triangle.h file
+
+		> sudo patch /usr/include/triangle.h $ISSM_DIR/externalpackages/triangle/triangle.h.patch
+			the header may also be called "libtriangle.h"
+
+		Just like always, this will move the original to 
+		 "triangle.h.old" incase you need to revert
+
+4.	Compile ISSM
+
+		> autoreconf -iv && configs/config-*-packaging.sh && make && sudo -E make install
+
+-------------------------------------------------------------------------------
+		          Creating an issm.deb package
+-------------------------------------------------------------------------------
+	THIS ASSUMES YOU ARE USING THE CONFIG FILE SUPPLIED HERE.
+	IF YOU ARE DOING AN ALTERNATE CONFIG, MAKE SURE THE DIR
+	HIERARCHY IS PROPERLY REFLECTED BY THE BINDIR AND LIBDIR!
+
+1.	Make a directory to work from (the dir dpkg-deb will build)
+		Anywhere will do, but using a ~/tmp dir works best
+
+		> mkdir issmpkgdir
+		> cd issmpkgdir
+
+2.	Create the dir hierarchy:
+
+		> mkdir -p usr/{bin,lib,share/issm-trunk} etc/issm DEBIAN
+
+		This is will create:
+		issmpkgdir/
+		|_ usr/
+		|  |_ bin/
+		|  |_ lib/
+		|  |_ share/
+		|     |_issm-trunk/ - this is the trunk
+		|_ etc/
+		|  |_ issm/ - this is where issmrc and other conf files go
+		|_DEBIAN/ - where control files and install scripts go
+
+		As stated, if you change "--bindir" or "--libdir" in the config
+		 file, then make sure that you create matching dirs in this
+		 step, or vice-versa.
+
+3.	Copy the contents of the package over:
+
+		> sudo cp -r /usr/bin/issm usr/bin
+		> sudo cp -r /usr/lib/issm usr/lib
+		> cp -r $ISSM_DIR/* usr/share/issm-trunk
+
+		When you copy the trunk over, this your opportunity to weed out
+		 anything you don't want included in the build.
+		Again, the config file installs the bin and lib files to a dir
+		 that's separate from the rest of the bin and lib files. If you
+		 change "--bindir" or "--libdir", make sure you install them to
+		 a subdirectory of your target to keep things neat or else 
+		 you'll have to pick them out, one-by-one to complete this step.
+
+4.	Write your control file. A template is provided, that is the bare minimum to
+		 create the package 
+
+		You will NEED the following dependencies:
+		mpich2, petsc3.2-issm, metis4.0-issm, triangle-bin, libtriangle-dev, 
+		 python2.7-dev, python-scipy, python-netcdf4, netcdf-bin, python-nose, 
+		 libnetcdfc++4, hdf5-tools
+
+5.	Create any install/uninstall scripts needed (preinst, postinst, prerm, postrm)
+		There are already some templates provided for you.
+
+		Make sure you address the issue of any user created content. By
+		 default, apt-get won't remove anything that wasn't created by
+		 the installer, even if you use purge. Put this in a rm script.
+
+6.	Build the package:
+
+		> dpkg-deb --build <workingDir> <nameOfPackage>
+
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/environment.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/environment.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/environment.sh	(revision 18231)
@@ -0,0 +1,287 @@
+#ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+pathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		export PATH="$1:$PATH"
+	fi
+} #}}}
+pathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		export PATH="$PATH:$1"
+	fi
+} #}}}
+libpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$1:$LD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+libpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+dylibpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$1:$DYLD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+dylibpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+
+#FIXME: during installation packages are installed one by one but environment.sh was sourced
+#before so new packages are NOT in the path.
+#may resource environment.sh with:
+#if [ -z $(echo "$PATH" | grep "$MATLAB_DIR") ]; then export $PATH...; fi
+
+#Windows compilers: 
+if [[ "$ISSM_ARCH" == "cygwin-intel" ]]; then
+	source $ISSM_DIR/externalpackages/windows/windows_environment.sh
+fi
+
+#Some basic path, in case it is not included by default
+libpathappend "/usr/local/lib"
+
+#Load ISSM scripts
+pathappend "$ISSM_DIR/scripts"
+
+MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+export MATLAB_DIR
+pathprepend   "$MATLAB_DIR/bin" #take precedence over /usr/local/bin/matlab
+libpathappend "$MATLAB_DIR/lib"
+
+#legacy mpich2 (To be removed)
+MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+MPI_DIR="$ISSM_DIR/externalpackages/mpich/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+export PETSC_DIR
+libpathappend "$PETSC_DIR/lib"
+
+SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+libpathappend "$SLEPC_DIR/lib"
+
+TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+libpathappend "$TAO_DIR/lib"
+
+DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+pathappend "$DAKOTA_DIR/bin"
+libpathappend "$DAKOTA_DIR/lib"
+
+DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+pathprepend "$DOXYGEN_DIR/bin"
+
+AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+pathprepend "$AUTOTOOLS_DIR/bin"
+
+SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+pathappend "$SDK_DIR"
+
+SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+pathappend "$SSH_DIR"
+
+VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install"
+pathprepend "$VALGRIND_DIR/bin"
+
+CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
+pathappend "$CPPCHECK_DIR/bin"
+
+GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
+pathprepend "$GDAL_DIR/bin"
+libpathappend "$GDAL_DIR/lib"
+
+PROJ4_DIR="$ISSM_DIR/externalpackages/proj.4/install"
+libpathappend "$PROJ4_DIR/lib"
+
+MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if [ -d "$MERCURIAL_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+	pathappend "$MERCURIAL_DIR"
+fi
+
+BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if [ -d "$BOOST_DIR" ]; then
+	export BOOSTROOT
+	export BOOST_DIR
+	libpathappend   "$BOOST_DIR/lib"
+	dylibpathappend "$BOOST_DIR/lib"
+	pathappend      "$BOOST_DIR/bin"
+fi
+
+XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
+if [ -d "$XERCESROOT" ]; then
+	export XERCESROOT 
+	export XERCESCROOT
+fi
+
+XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
+XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+PLATFORM="x86-Linux"
+if [ -d "$XAIF_DIR" ]; then
+	export XAIFBOOSTERROOT
+	export XAIFBOOSTER_HOME
+	export XAIF_DIR
+	export PLATFORM
+fi
+
+ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
+if [ -d "$ANGELROOT" ]; then
+	export ANGELROOT
+fi
+
+OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
+if [ -d "$OPENANALYSISROOT" ]; then
+	export OPENANALYSISROOT
+	libpathappend "$OPENANALYSISROOT/lib"
+fi
+
+JVM_DIR="/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/"
+libpathappend "$JVM_DIR"
+
+BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
+pathappend "$BBFTP_DIR/bin"
+
+ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
+pathappend "$ADIC_DIR/bin"
+libpathappend "$ADIC_DIR/lib"
+
+COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
+libpathappend "$COLPACK_DIR/lib"
+
+ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
+pathappend "$ECLIPSE_DIR"
+
+APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan/install"
+pathappend "$APPSCAN_DIR/bin"
+
+RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
+pathappend "$RATS_DIR/bin"
+
+DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
+pathappend "$DYSON_DIR"
+
+CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+pathprepend "$CMAKE_DIR/bin"
+
+SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
+pathappend "$SHAPELIB_DIR/exec"
+
+CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
+pathappend "$CCCL_DIR/bin"
+
+PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
+pathappend "$PACKAGEMAKER_DIR"
+
+#android-dev-dir
+export ANDROID_DIR="$ISSM_DIR/externalpackages/android"
+
+export ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
+pathappend "$ANDROID_NDK_DIR/arm-linux-android-install/bin"
+
+export ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install"
+pathappend "$ANDROID_SDK_DIR/"
+
+GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+libpathappend "$GSL_DIR/lib"
+
+GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
+pathprepend "$GMAKE_DIR/bin"
+
+PYTHON_DIR="/usr"
+if [ -d "$PYTHON_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
+	export PYTHONSTARTUP="$ISSM_DIR/startup.py"
+	pathprepend    "/usr"
+	libpathprepend "$ISSM_DIR/lib"
+	libpathprepend "/usr/lib/python2.7"
+fi
+
+MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
+pathappend "$MODELE_DIR/src/exec"
+
+GIT_DIR="$ISSM_DIR/externalpackages/git/install"
+pathprepend "$GIT_DIR/bin"
+
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
+pathappend "$NCVIEW_DIR"
+
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+libpathappend "$TCLX_DIR"
+
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/install"
+pathappend "$ASPELL_DIR/bin"
+
+HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+dylibpathappend "$HDF5_DIR/lib"
+libpathappend "$HDF5_DIR/lib"
+if [ -d "$HDF5_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+fi
+
+NETCDF_DIR="$ISSM_DIR/externalpackages/netcdf/install"
+pathappend "$NETCDF_DIR/bin"
+dylibpathappend "$NETCDF_DIR/lib"
+libpathappend "$NETCDF_DIR/lib"
+if [ -d "$NETCDF_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$NETCDF_DIR/lib"
+	dylibpathappend "$NETCDF_DIR/lib"
+	libpathappend "$NETCDF_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$NETCDF_DIR/include"
+fi
+
+NETCDF_CXX_DIR="$ISSM_DIR/externalpackages/netcdf-cxx/install"
+libpathappend "$NETCDF_CXX_DIR/lib"
+
+SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
+pathprepend   "$SVN_DIR/bin"
+libpathappend "$SVN_DIR/lib"
+
+APR_DIR="$ISSM_DIR/externalpackages/apr/install"
+pathappend    "$APR_DIR/bin"
+libpathappend "$APR_DIR/lib"
+
+APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
+pathappend   "$APR_UTIL_DIR/bin:$PATH"
+libpathappend "$APR_UTIL_DIR/lib"
+
+SQLITE_DIR="$ISSM_DIR/externalpackages/sqlite/install"
+pathappend   "$SQLITE_DIR/bin"
+libpathappend "$SQLITE_DIR/lib"
+
+YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+pathappend   "$YAMS_DIR"
+
+SWIG_DIR="$ISSM_DIR/externalpackages/swig/install"
+pathappend   "$SWIG_DIR"
+
+#AUX-CONFIG
+pathappend   "$ISSM_DIR/aux-config"
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/install-3.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/install-3.2-linux64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/install-3.2-linux64.sh	(revision 18231)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="/usr/lib/mpich2/" \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/issm_options.m4
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/issm_options.m4	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/issm_options.m4	(revision 18231)
@@ -0,0 +1,1690 @@
+dnl ISSM Options
+
+AC_DEFUN([ISSM_OPTIONS],[
+
+	dnl ISSM's internal options
+	dnl Debugging {{{
+	AC_ARG_ENABLE([debugging],                                        dnl feature
+		AS_HELP_STRING([--enable-debugging],[turn debug support on]),  dnl help string
+		[enable_debugging=$enableval],                                 dnl action if given
+		[enable_debugging=no])                                         dnl action if not given
+	if test "x$enable_debugging" = xyes; then
+		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
+	fi
+
+	dnl }}}
+    dnl Shared build {{{
+    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
+        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
+        [enable_sharedlibs=$enableval],                                        dnl action if given
+        [enable_sharedlibs=no])                                                dnl action if not given
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+    dnl }}}
+    dnl Version{{{
+    AC_ARG_ENABLE([version],                                                dnl feature
+        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
+        [enable_version=$enableval],                                        dnl action if given
+        [enable_version=no])                                                dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
+    dnl }}}
+	dnl Wrappers build {{{
+	AC_ARG_WITH([wrappers],
+		AS_HELP_STRING([--with-wrappers = value],[wrappers compilation. ]),
+		[WRAPPERS_VALUE=$withval],[WRAPPERS_VALUE="yes"])
+	AC_MSG_CHECKING(for wrappers compilation)
+	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
+	AC_MSG_RESULT($WRAPPERS_VALUE) 
+	dnl }}}
+	dnl Extensions{{{
+	ISSMEXT=".exe"
+	AC_SUBST([ISSMEXT])
+	dnl }}}
+
+	dnl ISSM's externalpackages
+	dnl vendor{{{
+	AC_ARG_WITH([vendor],
+	  AS_HELP_STRING([--with-vendor = VENDOR], [vendor name, ex: intel]),
+	  [VENDOR=$withval],[VENDOR=""]) 
+	AC_MSG_CHECKING(for vendor compilers)
+	if test -n "$VENDOR"; then
+
+		if  test $VENDOR = intel-win32; then
+			export CC=icl
+			export CXX=icl
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_"
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
+		elif  test $VENDOR = intel-win7-32; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif  test $VENDOR = intel-win7-64; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif test $VENDOR = intel-linux; then
+			export CC=icc
+			export CXX=icpc
+			export CFLAGS=" -D_INTEL_LINUX_"
+			export CXXFLAGS=" -D_INTEL_LINUX_"
+		elif test $VENDOR = intel-discover; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+		elif test $VENDOR = intel-pleiades; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+        else
+		AC_MSG_ERROR([unknown compiler vendor!])
+		fi
+	fi
+	AC_SUBST([OSLIBS]) 
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl matlab{{{
+
+	dnl 1. See if matlab has been provided
+	AC_ARG_WITH([matlab-dir],
+		AS_HELP_STRING([--with-matlab-dir=DIR], [matlab root directory. necessary for serial build.]),
+		[MATLAB_ROOT=$withval],[MATLAB_ROOT=""]) 
+
+	AC_MSG_CHECKING([whether matlab is enabled])
+	if test -d "$MATLAB_ROOT"; then
+		HAVE_MATLAB=yes
+	else
+		HAVE_MATLAB=no
+	fi
+	if test x$HAVE_MATLAB = xyes; then
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with Matlab in ISSM src])
+	fi
+	AC_MSG_RESULT($HAVE_MATLAB)
+	AM_CONDITIONAL([MATLAB], [test x$HAVE_MATLAB = xyes])
+
+	dnl 2. Get Matlab libraries
+	if test x$HAVE_MATLAB = xyes; then
+
+		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
+  		MATLABINCL="-I$MATLAB_ROOT/extern/include/"
+		
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
+      dnl OS-dependent variables and checks
+  		case "${host_os}" in
+  			*cygwin*) 
+  				if  test $VENDOR = intel-win7-32; then
+  					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win32/microsoft` -no-undefined -Wl,/export:mexFunction" 
+  				elif  test l-win7-64; then
+  					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -no-undefined -Wl,/export:mexFunction" 
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+  				MEXEXT=".$MEXEXT"
+  			;;
+		   *)
+		      MEXLINK=$(mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
+	         MEXLIB=$( mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
+		      MEXEXT=$( mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
+  			;;
+      esac
+	   AC_MSG_RESULT(done)
+
+		AC_SUBST([MATLABINCL])
+		AC_SUBST([MEX])
+		MATLABWRAPPEREXT=$MEXEXT
+		AC_SUBST([MATLABWRAPPEREXT])
+	   AC_SUBST([MEXLIB]) 
+		AC_SUBST([MEXLINK])
+	fi
+	dnl }}}
+	dnl triangle {{{
+	AC_ARG_WITH([triangle-dir],
+		AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory. necessary for serial build]),
+		[TRIANGLE_ROOT=$withval],
+		[TRIANGLE_ROOT=""]) 
+	AC_ARG_WITH([triangle-include-dir],
+		AS_HELP_STRING([--with-triangle-include-dir], [triangle include dir]),
+		[TRIANGLE_INCL=$withval],
+		[TRIANGLE_INCL="$TRIANGLE_ROOT"])
+	AC_ARG_WITH([triangle-lib-dir],
+		AS_HELP_STRING([--with-triangle-lib-dir], [triangle lib dir]),
+		[TRIANGLE_LIB=$withval],
+		[TRIANGLE_LIB="$TRIANGLE_ROOT"])
+	AC_MSG_CHECKING(for triangle headers and libraries)
+
+	if test -d "$TRIANGLE_ROOT"; then
+
+		dnl defaults
+		HAVE_TRIANGLE=yes
+		TRIANGLEINCL=-I$TRIANGLE_INCL
+
+		case "${host_os}" in
+				*cygwin*)
+				TRIANGLELIB="-Wl,`cygpath -m $TRIANGLE_LIB/`triangle.lib"
+				;;
+				*linux*)
+				TRIANGLELIB="-ltriangle"
+				;;
+				*darwin*)
+				TRIANGLELIB=$TRIANGLE_LIB/triangle.a
+				;;
+			esac
+
+		AC_DEFINE([_HAVE_TRIANGLE_],[1],[with Triangle in ISSM src])
+		AC_SUBST([TRIANGLEINCL])
+		AC_SUBST([TRIANGLELIB])
+
+	else
+		HAVE_TRIANGLE=no
+	fi
+	AC_MSG_RESULT($HAVE_TRIANGLE)
+	dnl }}}
+	dnl boost{{{
+	AC_ARG_WITH([boost-dir],
+	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
+	  [BOOST_ROOT=$withval],[BOOST_ROOT=""]) 
+	AC_MSG_CHECKING(for boost)
+	
+	if test -d "$BOOST_ROOT"; then
+		dnl defaults
+		HAVE_BOOST=yes
+		BOOSTINCL=-I$BOOST_ROOT/include
+		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
+
+		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
+		AC_SUBST([BOOSTINCL])
+		AC_SUBST([BOOSTLIB])
+	else
+		HAVE_BOOST=no
+	fi
+	AM_CONDITIONAL([BOOST], [test x$HAVE_BOOST = xyes])
+	AC_MSG_RESULT($HAVE_BOOST)
+	dnl }}}
+	dnl dakota{{{
+	AC_ARG_WITH([dakota-dir],
+	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory. necessary for serial build]),
+	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT=""]) 
+	AC_MSG_CHECKING(for dakota)
+	
+	if test -d "$DAKOTA_ROOT"; then
+
+		dnl defaults
+		HAVE_DAKOTA=yes
+		AC_MSG_RESULT($HAVE_DAKOTA)
+		DAKOTAINCL=-I$DAKOTA_ROOT/include
+		AC_MSG_CHECKING(for dakota version)
+		if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.C"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.C | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.cpp"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.cpp | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else
+			AC_MSG_ERROR([Dakota CommandLineHandler.C or CommandLineHandler.cpp file not found to determine DAKOTA_VERSION!]);
+		fi
+		fi
+
+		AC_MSG_RESULT($DAKOTA_VERSION)
+		AC_DEFINE_UNQUOTED([_DAKOTA_VERSION_],"$DAKOTA_VERSION",[Dakota version number])
+		DAKOTAFLAGS=""
+		case "${host_os}" in
+			*cygwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*linux*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system -ldl"
+				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.3.1; then
+					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+				fi
+			;;
+			*darwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver" 
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
+
+		case $DAKOTA_VERSION in
+			@<:@1-9@:>@.@<:@0-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_BUILD=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@+)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			*)
+				AC_MSG_ERROR([Dakota version ($DAKOTA_VERSION) not supported!]);
+		   ;;
+		esac
+		AC_MSG_CHECKING(for dakota major version)
+		AC_MSG_RESULT($DAKOTA_MAJOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MAJOR_],$DAKOTA_MAJOR,[Dakota major version number])
+		AC_MSG_CHECKING(for dakota minor version)
+		AC_MSG_RESULT($DAKOTA_MINOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MINOR_],$DAKOTA_MINOR,[Dakota minor version number])
+		AC_MSG_CHECKING(for dakota build version)
+		AC_MSG_RESULT($DAKOTA_BUILD)
+		AC_DEFINE_UNQUOTED([_DAKOTA_BUILD_],$DAKOTA_BUILD,[Dakota build version number])
+
+		AC_SUBST([DAKOTAINCL])
+		AC_SUBST([DAKOTAFLAGS])
+		AC_SUBST([DAKOTALIB])
+
+	else
+		HAVE_DAKOTA=no
+		AC_MSG_RESULT($HAVE_DAKOTA)
+	fi
+
+	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
+	dnl }}}
+	dnl python{{{
+	AC_ARG_WITH([python-dir],
+		AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
+		[PYTHON_ROOT=$withval],
+		[PYTHON_ROOT=""]) 
+
+	AC_ARG_WITH([python-include-dir],
+		AS_HELP_STRING([--with-python-include-dir=DIR], [python include directory.]),
+		[PYTHON_INCL=$withval],
+		[PYTHON_INCL="$PYTHON_ROOT/include"]) 
+
+	AC_ARG_WITH([python-lib-dir],
+		AS_HELP_STRING([--with-python-lib-dir=DIR], [python lib directory.]),
+		[PYTHON_LIB=$withval],
+		[PYTHON_LIB="$PYTHON_ROOT/lib"]) 
+
+	AC_MSG_CHECKING(for python)
+	if test -d "$PYTHON_ROOT"; then
+		HAVE_PYTHON="yes"
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
+	else
+		HAVE_PYTHON=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON)
+
+	dnl get python version
+	if test x$HAVE_PYTHON = xyes; then
+		AC_MSG_CHECKING(for python version)
+		dnl Query Python for its version number.  Getting [:3] seems to be
+		dnl the best way to do this; it's what "site.py" does in the standard
+		dnl library.
+		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
+		AC_MSG_RESULT($PYTHON_VERSION)
+
+		dnl recover major: 
+		PYTHON_MAJOR=${PYTHON_VERSION%.*}
+		if test x$PYTHON_MAJOR = x3; then
+			dnl are we running python 3?
+			HAVE_PYTHON3="yes"
+		else
+			HAVE_PYTHON3="no"
+		fi
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+
+		PYTHONINCL="-I$PYTHON_INCL"
+		PYTHONLIB="-L$PYTHON_LIB -lpython$PYTHON_VERSION"
+		PYTHONEXT=.so
+
+		case "${host_os}" in
+			*cygwin*)
+			PYTHONLINK="-shared"
+			;;
+			*linux*)
+			PYTHONLINK="-shared"
+			;;
+			*darwin*)
+			PYTHONLINK="-dynamiclib"
+			;;
+		esac
+
+		AC_SUBST([PYTHONINCL])
+		AC_SUBST([PYTHONLIB])
+		PYTHONWRAPPEREXT=$PYTHONEXT
+		AC_SUBST([PYTHONWRAPPEREXT])
+		AC_SUBST([PYTHONLINK])
+	fi
+	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
+	dnl }}}
+	dnl python-numpy{{{
+	AC_ARG_WITH([python-numpy-dir],
+	  AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
+	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT=""]) 
+	AC_MSG_CHECKING(for python-numpy)
+	
+	if test -d "$PYTHON_NUMPY_ROOT"; then
+		dnl defaults
+		HAVE_PYTHON_NUMPY=yes
+		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
+
+		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
+		AC_SUBST([PYTHON_NUMPYINCL])
+	else
+		HAVE_PYTHON_NUMPY=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+	dnl }}}
+	dnl chaco{{{
+	AC_ARG_WITH([chaco-dir],
+	  AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
+	  [CHACO_ROOT=$withval],[CHACO_ROOT=""]) 
+	AC_MSG_CHECKING(for chaco)
+	
+	if test -d "$CHACO_ROOT"; then
+
+		dnl defaults
+		HAVE_CHACO=yes
+		CHACOINCL=-I$CHACO_ROOT/include
+		CHACOLIB="-L$CHACO_ROOT/lib -lchacominusblas"
+
+		AC_DEFINE([_HAVE_CHACO_],[1],[with Chaco in ISSM src])
+		AC_SUBST([CHACOINCL])
+		AC_SUBST([CHACOLIB])
+
+	else
+		HAVE_CHACO=no
+	fi
+	AC_MSG_RESULT($HAVE_CHACO)
+	dnl }}}
+	dnl scotch{{{
+	AC_ARG_WITH([scotch-dir],
+	  AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
+	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT=""]) 
+	AC_MSG_CHECKING(for scotch)
+	
+	if test -d "$SCOTCH_ROOT"; then
+
+		dnl defaults
+		HAVE_SCOTCH=yes
+		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
+		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
+
+		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
+		AC_SUBST([SCOTCHINCL])
+		AC_SUBST([SCOTCHLIB])
+
+	else
+		HAVE_SCOTCH=no
+	fi
+	AC_MSG_RESULT($HAVE_SCOTCH)
+	dnl }}}
+	dnl adolc{{{
+	AC_ARG_WITH([adolc-dir],
+		AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
+		[ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
+	AC_MSG_CHECKING(for adolc)
+
+	if test "x$ADOLC_ROOT" = "xno"; then
+		HAVE_ADOLC=no
+	else
+		if test -d "$ADOLC_ROOT"; then
+
+			dnl defaults
+			HAVE_ADOLC=yes
+			ADOLCINCL="-I$ADOLC_ROOT/include"
+			ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc"
+
+			AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
+			AC_SUBST([ADOLCINCL])
+			AC_SUBST([ADOLCLIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
+	AC_MSG_RESULT($HAVE_ADOLC)
+	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
+	dnl adic2{{{
+	AC_ARG_WITH([adic2-dir],
+	  AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
+	  [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
+	AC_MSG_CHECKING(for adic2)
+
+	if test "x$ADIC2_ROOT" = "xno"; then
+		HAVE_ADIC2=no
+	else
+		if test -d "$ADIC2_ROOT"; then
+
+			dnl defaults
+			HAVE_ADIC2=yes
+			ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
+			ADIC2LIB=""
+
+			AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
+			AC_SUBST([ADIC2INCL])
+			AC_SUBST([ADIC2LIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADIC2], [test x$HAVE_ADIC2 = xyes])
+	AC_MSG_RESULT($HAVE_ADIC2)
+	dnl }}}
+	dnl gsl{{{
+	AC_ARG_WITH([gsl-dir],
+	  AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
+	  [GSL_ROOT=$withval],[GSL_ROOT=""]) 
+	AC_MSG_CHECKING(for gsl)
+	
+	if test -d "$GSL_ROOT"; then
+
+		dnl defaults
+		HAVE_GSL=yes
+		GSLINCL="-I$GSL_ROOT/include"
+		GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+
+		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
+		AC_SUBST([GSLINCL])
+		AC_SUBST([GSLLIB])
+
+	else
+		HAVE_GSL=no
+	fi
+	AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
+	AC_MSG_RESULT($HAVE_GSL)
+	dnl }}}
+	dnl rose{{{
+	AC_ARG_WITH([rose-dir],
+	  AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
+	  [ROSE_ROOT=$withval],[ROSE_ROOT=""]) 
+	AC_MSG_CHECKING(for rose)
+	
+	if test -d "$ROSE_ROOT"; then
+
+		dnl defaults
+		HAVE_ROSE=yes
+		ROSEINCL="-I$ROSE_ROOT/include"
+		ROSELIB=""
+
+		AC_DEFINE([_HAVE_ROSE_],[1],[with rose in ISSM src])
+		AC_SUBST([ROSEINCL])
+		AC_SUBST([ROSELIB])
+
+	else
+		HAVE_ROSE=no
+	fi
+	AM_CONDITIONAL([ROSE], [test x$HAVE_ROSE = xyes])
+	AC_MSG_RESULT($HAVE_ROSE)
+	dnl }}}
+	dnl mpi{{{
+	AC_MSG_CHECKING(for mpi)
+	
+	AC_ARG_WITH([mpi-include],
+	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
+	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
+
+	AC_ARG_WITH([mpi-libdir],
+	  AS_HELP_STRING([--with-mpi-libdir=DIR],[mpi lib directory, necessary for parallel build]),
+	  [MPI_LIBDIR=$withval],[MPI_LIBDIR=""])
+
+	AC_ARG_WITH([mpi-libflags],
+	  AS_HELP_STRING([--with-mpi-libflags=LIBS],[mpi libraries to be used, necessary for parallel build]),
+	  [MPI_LIBFLAGS=$withval],[MPI_LIBFLAGS=""])
+
+	
+	if test -z "$MPI_INCLUDE" ; then
+		HAVE_MPI=no
+	else
+		HAVE_MPI=yes
+
+		dnl Processing for windows
+		if  test x$VENDOR = xintel-win7-32; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPIINCL=`cygpath -m $MPI_INCLUDE`
+		elif test x$VENDOR = xintel-win7-64; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPI_INCLUDE=`cygpath -m $MPI_INCLUDE`
+		fi
+
+		if test -z "$MPI_LIBDIR"; then
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="$MPI_LIBFLAGS"
+		else
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="-L$MPI_LIBDIR $MPI_LIBFLAGS"
+		fi
+		AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+		AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
+		AC_SUBST([MPIINCL])
+		AC_SUBST([MPILIB])
+	fi
+
+	AM_CONDITIONAL([MPI], [test x$HAVE_MPI = xyes])
+	AC_MSG_RESULT($HAVE_MPI)
+	dnl }}}
+	dnl petsc{{{
+	AC_ARG_WITH([petsc-dir],
+	  AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
+	  [PETSC_ROOT=$withval],[PETSC_ROOT=""])
+		
+	if test -d "$PETSC_ROOT"; then
+		AC_MSG_CHECKING(for petsc version)
+		PETSC_MAJOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MAJOR" | sed 's/#define PETSC_VERSION_MAJOR//' | sed 's/ //g'`
+		PETSC_MINOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MINOR" | sed 's/#define PETSC_VERSION_MINOR//' | sed 's/ //g'`
+		AC_DEFINE_UNQUOTED([_PETSC_MAJOR_],$PETSC_MAJOR,[PETSc version major])
+		AC_DEFINE_UNQUOTED([_PETSC_MINOR_],$PETSC_MINOR,[PETSc version minor])
+		AC_MSG_RESULT($PETSC_MAJOR.$PETSC_MINOR)
+
+		PETSC_VERSION_DATE_HG=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_DATE_HG" | sed 's/#define PETSC_VERSION_DATE_HG//' | sed 's/ //g' | sed -e 's/\"//g' `
+		PETSC_RELEASE=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_RELEASE" | sed 's/#define PETSC_VERSION_RELEASE//' | sed 's/ //g'`
+
+		AC_MSG_CHECKING(whether petsc is the development version)
+		dnl if test x$PETSC_VERSION_DATE_HG = xunknown; then
+		if test "$PETSC_RELEASE" = "0"; then
+		   AC_DEFINE([_HAVE_PETSCDEV_],[1],[with PETSc-dev])
+			AC_MSG_RESULT(yes)
+		else
+			AC_MSG_RESULT(no)
+		fi
+	fi
+	
+	AC_ARG_WITH([petsc-arch],
+	  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch , necessary for parallel build]),
+	  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+	AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
+	
+	dnl To ge PETSc's libraries:
+	dnl cd externalpackages/petsc/src
+	dnl make getlinklibs
+	if test -d "$PETSC_ROOT"; then
+
+	 PETSCINCL=" -I$PETSC_ROOT/include"
+	 dnl Add other location (not needed anymore since at least PETSc 3.0)
+	 if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+	  PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+	 fi
+	 if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+	  PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+	 fi
+	
+	 case "${host_os}" in
+			*cygwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB=-Wl,/LIBPATH:`cygpath -w $PETSC_ROOT/lib`  -Wl,libpetscksp.lib  -Wl,libpetscdm.lib  -Wl,libpetscmat.lib  -Wl,libpetscvec.lib  -Wl,libpetscsnes.lib  -Wl,libpetscts.lib  -Wl,libmpiuni.lib  -Wl,libpetsc.lib
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib  -Wl,libpetsc.lib"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+="  -Wl,libmetis.lib"; fi
+			fi
+			;;
+			*linux*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+			*darwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
+		AC_SUBST([PETSCINCL])
+		AC_SUBST([PETSCLIB])
+		HAVE_PETSC=yes
+	else
+		HAVE_PETSC=no
+	fi
+	
+	AM_CONDITIONAL([PETSC], [test x$HAVE_PETSC = xyes])
+	AC_MSG_RESULT($HAVE_PETSC)
+	dnl }}}
+	dnl metis{{{
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
+
+		dnl in petsc >=3.3, metis is provided
+		HAVE_METIS="yes"
+		AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+	else
+		AC_ARG_WITH([metis-dir],
+		  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
+		  [METIS_ROOT=$withval],[METIS_ROOT=""])
+
+		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+
+		if test -d "$METIS_ROOT"; then
+
+			dnl first figure out version of metis: does the VERSION file exist?
+			if test -e "$METIS_ROOT/VERSION"; then
+				METIS_VERSION=4
+			else
+				METIS_VERSION=5
+			fi
+
+			dnl defaults
+			HAVE_METIS=yes
+
+			if test "$METIS_VERSION" = "4" ; then
+					
+				METISINCL=-I"$METIS_ROOT/Lib" 
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT -Wl,libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+				esac
+
+					AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+			fi
+			if test "$METIS_VERSION" = "5" ; then
+		
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+				esac
+
+				METISINCL=-I"$METIS_ROOT/include" 
+				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+			fi
+
+			AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+			AC_SUBST([METISINCL])
+			AC_SUBST([METISLIB])
+		else
+			HAVE_METIS=no
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+	fi
+	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+	dnl }}}
+	dnl tao{{{
+	AC_ARG_WITH([tao-dir],
+		AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
+		[TAO_ROOT=$withval],[TAO_ROOT=""]) 
+	AC_MSG_CHECKING(for tao)
+
+	if test -d "$TAO_ROOT"; then
+
+	  HAVE_TAO=yes
+	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
+	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
+
+	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+	  AC_SUBST([TAOINCL])
+	  AC_SUBST([TAOLIB])
+	else
+		HAVE_TAO=no
+	fi
+	AC_MSG_RESULT($HAVE_TAO)
+	dnl }}}
+	dnl slepc{{{
+	AC_ARG_WITH([slepc-dir],
+	  AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
+	  [SLEPC_ROOT=$withval],[SLEPC_ROOT=""])
+			  
+	AC_MSG_CHECKING(for slepc headers and libraries in $SLEPC_ROOT)
+	if test -d "$SLEPC_ROOT"; then
+		HAVE_SLEPC=yes
+		SLEPCINCL=-I"$SLEPC_ROOT/include"
+		SLEPCLIB=-L"$SLEPC_ROOT/lib/ -lslepc"
+
+		AC_DEFINE([_HAVE_SLEPC_],[1],[with Slepc in ISSM src])
+		AC_SUBST([SLEPCINCL])
+		AC_SUBST([SLEPCLIB])
+	else
+		HAVE_SLEPC=no
+	fi
+	AC_MSG_RESULT($HAVE_SLEPC)
+	dnl }}}
+	dnl shapelib{{{
+	AC_ARG_WITH([shapelib-dir],
+	  AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
+	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT=""])
+			  
+	AC_MSG_CHECKING(for shapelib headers and libraries in $SHAPELIB_ROOT)
+	if test -d "$SHAPELIB_ROOT"; then
+
+		dnl defaults
+		HAVE_SHAPELIB=yes
+		SHAPELIBINCL=-I"$SHAPELIB_ROOT/include"
+		SHAPELIBLIB=-L"$SHAPELIB_ROOT/lib/ -lshape"
+
+		AC_DEFINE([_HAVE_SHAPELIB_],[1],[with Shapelib in ISSM src])
+		AC_SUBST([SHAPELIBINCL])
+		AC_SUBST([SHAPELIBLIB])
+	else
+		HAVE_SHAPELIB=no
+	fi
+	AC_MSG_RESULT($HAVE_SHAPELIB)
+	dnl }}}
+	dnl scalapack{{{
+	AC_ARG_WITH([scalapack-dir],
+	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
+	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for scalapack headers and libraries in $SCALAPACK_ROOT)
+	if test -d "$SCALAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_SCALAPACK=yes
+		if test x$VENDOR = xintel-discover; then
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
+		else
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+		fi
+
+		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
+		AC_SUBST([SCALAPACKLIB])
+	else
+		HAVE_SCALAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_SCALAPACK)
+	dnl }}}
+	dnl blas{{{
+	AC_ARG_WITH([blas-lapack-dir],
+	  AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
+	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blas and lapack headers and libraries in $BLASLAPACK_ROOT)
+	if test -d "$BLASLAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_BLASLAPACK=yes
+		BLASLAPACKINCL=""
+	
+		if test x$VENDOR = xintel-discover; then
+		 BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
+		else
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
+			;;
+			*linux*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+			;;
+			*darwin*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+			;;
+		esac
+		fi
+
+		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
+		AC_SUBST([BLASLAPACKLIB])
+		AC_SUBST([BLASLAPACKINCL])
+	else
+		HAVE_BLASLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	dnl }}}
+	dnl mkl{{{
+	AC_ARG_WITH([mkl-dir],
+	  AS_HELP_STRING([--with-mkl-dir=DIR],[mkl root directory]),
+	  [MKL_ROOT=$withval],[MKL_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mkl headers and libraries in $MKL_ROOT)
+	if test -d "$MKL_ROOT"; then
+
+		dnl defaults
+		HAVE_MKL=yes
+		MKLINCL=""
+		if test x$VENDOR = xintel-pleiades; then
+		 MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread"
+		else
+		 MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64 -lmkl_blacs_sgimpt_ilp64 -lguide -lpthread"
+		fi
+		AC_DEFINE([_HAVE_MKL_],[1],[with mkl in ISSM src])
+		AC_SUBST([MKLLIB])
+		AC_SUBST([MKLINCL])
+	else
+		HAVE_MKL=no
+	fi
+	AC_MSG_RESULT($HAVE_MKL)
+	dnl }}}
+	dnl plapack{{{
+	AC_MSG_CHECKING(for plapack)
+	
+	AC_ARG_WITH([plapack-lib],
+	  AS_HELP_STRING([--with-plapack-lib = lib],[plapack library]),
+	  [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
+	
+	AC_ARG_WITH([plapack-include],
+			  AS_HELP_STRING([--with-plapack-include = include],
+							 [plapack include ]),
+			  [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
+	  
+	if test -n "$PLAPACK_LIB"; then
+		if test -n "$PLAPACK_INCLUDE"; then
+		
+			dnl defaults
+			HAVE_PLAPACK=yes
+			PLAPACKINCL="$PLAPACK_INCLUDE"
+			PLAPACKLIB="$PLAPACK_LIB"
+
+			AC_DEFINE([_HAVE_PLAPACK_],[1],[with Plapack in ISSM src])
+			AC_SUBST([PLAPACKINCL])
+			AC_SUBST([PLAPACKLIB])
+		else
+			HAVE_PLAPACK=no
+		fi
+	else
+		HAVE_PLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_PLAPACK)
+	dnl }}}
+	dnl mumps{{{
+	AC_ARG_WITH([mumps-dir],
+	  AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
+	  [MUMPS_ROOT=$withval],[MUMPS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mumps headers and libraries in $MUMPS_ROOT)
+	if test -d "$MUMPS_ROOT"; then
+
+		dnl defaults
+		HAVE_MUMPS=yes
+		MUMPSINCL=-I"$MUMPS_ROOT/include"
+		if test "$PETSC_MAJOR" = "2" ; then
+		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+		else
+		dnl MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps"
+		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis"
+		fi
+
+		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
+		AC_SUBST([MUMPSINCL])
+		AC_SUBST([MUMPSLIB])
+	else
+		HAVE_MUMPS=no
+	fi
+	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
+	AC_MSG_RESULT($HAVE_MUMPS)
+	dnl }}}
+	dnl blacs{{{
+	AC_ARG_WITH([blacs-dir],
+		AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
+			  [BLACS_ROOT=$withval],[BLACS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blacs headers and libraries in $BLACS_ROOT)
+	if test -d "$BLACS_ROOT"; then
+
+		dnl defaults
+		HAVE_BLACS=yes
+		BLACSINCL=""
+		if test x$VENDOR = xintel-discover; then
+		 BLACSLIB=-L"$BLACS_ROOT/ -lmkl_blacs_intelmpi_lp64"
+		else
+		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+		fi
+        
+		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
+		AC_SUBST([BLACSINCL])
+		AC_SUBST([BLACSLIB])
+	else
+		HAVE_BLACS=no
+	fi
+	AC_MSG_RESULT($HAVE_BLACS)
+	dnl }}}
+	dnl hypre{{{
+	AC_ARG_WITH([hypre-dir],
+	  AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
+			  [HYPRE_ROOT=$withval],[HYPRE_ROOT=""])
+			  
+	AC_MSG_CHECKING(for hypre headers and libraries in $HYPRE_ROOT)
+	if test -d "$HYPRE_ROOT"; then
+
+		dnl defaults
+		HAVE_HYPRE=yes
+		HYPREINCL=""
+		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
+        
+		AC_DEFINE([_HAVE_HYPRE_],[1],[with Blacs in ISSM src])
+		AC_SUBST([HYPREINCL])
+		AC_SUBST([HYPRELIB])
+	else
+		HAVE_HYPRE=no
+	fi
+	AC_MSG_RESULT($HAVE_HYPRE)
+	dnl }}}
+	dnl prometheus{{{
+		AC_ARG_WITH([prometheus-dir],
+					AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
+					[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT=""])
+
+		  AC_MSG_CHECKING(for prometheus headers and libraries in $PROMETHEUS_ROOT)
+		  if test -d "$PROMETHEUS_ROOT"; then
+
+			dnl defaults
+			  HAVE_PROMETHEUS=yes
+			  PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
+			  PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
+
+			  AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
+			  AC_SUBST([PROMETHEUSINCL])
+			  AC_SUBST([PROMETHEUSLIB])
+		  else
+				HAVE_PROMETHEUS=no
+			fi
+			AC_MSG_RESULT($HAVE_PROMETHEUS)
+		dnl }}}
+dnl spai{{{
+	AC_ARG_WITH([spai-dir],
+				AS_HELP_STRING([--with-spai-dir=DIR],[spai root directory]),
+				[SPAI_ROOT=$withval],[SPAI_ROOT=""])
+
+	  AC_MSG_CHECKING(for spai headers and libraries in $SPAI_ROOT)
+	  if test -d "$SPAI_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPAI=yes
+		  SPAIINCL=-I"$SPAI_ROOT/include"
+		  SPAILIB=-L"$SPAI_ROOT/lib -lspai"
+
+		  AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
+		  AC_SUBST([SPAIINCL])
+		  AC_SUBST([SPAILIB])
+	  else
+		HAVE_SPAI=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPAI)
+		  dnl }}}
+dnl superlu{{{ 
+	AC_ARG_WITH([superlu-dir],
+				AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
+				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT=""])
+
+	  AC_MSG_CHECKING(for superlu headers and libraries in $SUPERLU_ROOT)
+	  if test -d "$SUPERLU_ROOT"; then
+
+		dnl defaults
+		  HAVE_SUPERLU=yes
+		  SUPERLUINCL=-I"$SUPERLU_ROOT/include"
+		  SUPERLULIB=-L"$SUPERLU_ROOT/lib -lsuperlu_4.3"
+
+		  AC_DEFINE([_HAVE_SUPERLU_],[1],[with Superlu in ISSM src])
+		  AC_SUBST([SUPERLUINCL])
+		  AC_SUBST([SUPERLULIB])
+	  else
+		HAVE_SUPERLU=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SUPERLU)
+		  dnl }}}
+dnl spooles{{{ 
+	AC_ARG_WITH([spooles-dir],
+				AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
+				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT=""])
+
+	  AC_MSG_CHECKING(for spooles headers and libraries in $SPOOLES_ROOT)
+	  if test -d "$SPOOLES_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPOOLES=yes
+		  SPOOLESINCL=-I"$SPOOLES_ROOT/include"
+		  SPOOLESLIB=-L"$SPOOLES_ROOT/lib -lspooles"
+
+		  AC_DEFINE([_HAVE_SPOOLES_],[1],[with Spooles in ISSM src])
+		  AC_SUBST([SPOOLESINCL])
+		  AC_SUBST([SPOOLESLIB])
+	  else
+		HAVE_SPOOLES=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPOOLES)
+		  dnl }}}
+dnl pastix{{{ 
+	AC_ARG_WITH([pastix-dir],
+				AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
+				[PASTIX_ROOT=$withval],[PASTIX_ROOT=""])
+
+	  AC_MSG_CHECKING(for pastix headers and libraries in $PASTIX_ROOT)
+	  if test -d "$PASTIX_ROOT"; then
+
+		dnl defaults
+		  HAVE_PASTIX=yes
+		  PASTIXINCL=-I"$PASTIX_ROOT/include"
+		  PASTIXLIB=-L"$PASTIX_ROOT/lib -lpastix_XXbit_mpi_smp_nobubble_int32_simple_real_scotch_i686_pc_linux -lptscotch -lptscotcherr -lpastix"
+
+		  AC_DEFINE([_HAVE_PASTIX_],[1],[with Pastix in ISSM src])
+		  AC_SUBST([PASTIXINCL])
+		  AC_SUBST([PASTIXLIB])
+	  else
+		HAVE_PASTIX=no
+		  fi
+		  AC_MSG_RESULT($HAVE_PASTIX)
+		  dnl }}}
+	dnl ml{{{
+	AC_ARG_WITH([ml-dir],
+	  AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
+			  [ML_ROOT=$withval],[ML_ROOT=""])
+			  
+	AC_MSG_CHECKING(for ml headers and libraries in $ML_ROOT)
+	if test -d "$ML_ROOT"; then
+
+		dnl defaults
+		HAVE_ML=yes
+		MLINCL=-I"$ML_ROOT/include"
+		MLLIB=-L"$ML_ROOT/lib -lml"
+        
+		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
+		AC_SUBST([MLINCL])
+		AC_SUBST([MLLIB])
+	else
+		HAVE_ML=no
+	fi
+	AC_MSG_RESULT($HAVE_ML)
+	dnl }}}
+	dnl umfpack{{{
+		AC_ARG_WITH([umfpack-dir],
+		  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
+					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT=""])
+
+		AC_MSG_CHECKING(for UMFPACK headers and libraries in $UMFPACK_ROOT)
+		if test -d "$UMFPACK_ROOT"; then
+
+			dnl defaults
+			HAVE_UMFPACK=yes
+			UMFPACKINCL=""
+			UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
+
+			AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
+			AC_SUBST([UMFPACKINCL])
+			AC_SUBST([UMFPACKLIB])
+		else
+			HAVE_UMFPACK=no
+		fi
+		AC_MSG_RESULT($HAVE_UMFPACK)
+	dnl }}}
+dnl math{{{
+	AC_MSG_CHECKING(for math library)
+	AC_ARG_WITH([math-lib],
+	  AS_HELP_STRING([--with-math-lib = otions],[math options, for ex: "/usr/lib/libm.a]),
+	  [MATH_LIB=$withval],[MATH_LIB=""])
+
+	dnl check that --with-math-lib may have been provided
+	if test -n "$MATH_LIB" ; then
+		HAVE_MATH=yes
+		MATHLIB="$MATH_LIB"
+
+		AC_DEFINE([_HAVE_MATH_],[1],[with MATH in ISSM src])
+		AC_SUBST([MATHLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl fortran{{{
+	AC_ARG_WITH([fortran],
+		AS_HELP_STRING([--with-fortran = YES], [do we compile fortran code (default is yes)]),
+		[FORTRAN=$withval],[FORTRAN=yes]) 
+	AC_MSG_CHECKING(for fortran compilation)
+	if test "x$FORTRAN" = "xyes"; then
+		dnl defaults
+		HAVE_FORTRAN=yes
+
+		AC_DEFINE([_HAVE_FORTRAN_],[1],[with fortran capability])
+	else
+		HAVE_FORTRAN=no
+	fi
+	AM_CONDITIONAL([FORTRAN], [test x$FORTRAN = xyes])
+	AC_MSG_RESULT($FORTRAN)
+
+	if test "x$FORTRAN" = "xyes"; then
+		dnl fortran library  option
+		AC_MSG_CHECKING(for fortran library)
+		AC_ARG_WITH([fortran-lib],
+		  AS_HELP_STRING([--with-fortran-lib = options],[fortran options, for ex: "/usr/lib/gfortran.a]),
+			[FORTRAN_LIB=$withval],[FORTRAN_LIB=""])
+
+		dnl check that --with-fortran-lib may have been provided
+		if test -n "$FORTRAN_LIB" ; then
+			dnl check that library provided EXISTS!
+		   FORTRAN_DIR=$(echo $FORTRAN_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+			if test -d "$FORTRAN_DIR" || test -f "$FORTRAN_DIR"; then
+				FORTRANLIB="$FORTRAN_LIB"
+				AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+				AC_SUBST([FORTRANLIB])
+			else
+			 if test "x$HAVE_MPI" = "xyes"; then
+				FORTRANLIB=$(mpif77 -print-file-name="libgfortran.a")
+				if test -f "$FORTRANLIB"; then
+					 AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist, MPI suggests the following library: $FORTRANLIB]);
+				fi
+			 fi
+				AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist!]);
+			fi
+		fi
+		AC_MSG_RESULT(done)
+	fi
+	dnl }}}
+	dnl graphics{{{
+	AC_MSG_CHECKING(for graphics library)
+	AC_ARG_WITH([graphics-lib],
+	  AS_HELP_STRING([--with-graphics-lib = options],[graphics options, for ex: "/usr/X11/lib/libX11.a]),
+	  [GRAPHICS_LIB=$withval],[GRAPHICS_LIB=""])
+
+	dnl check that --with-graphics-lib may have been provided
+	
+	if test -n "$GRAPHICS_LIB" ; then
+		dnl check that library provided EXISTS!
+		GRAPHICS_DIR=$(echo $GRAPHICS_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+		if test -d "$GRAPHICS_DIR" || test -f "$GRAPHICS_DIR"; then
+			HAVE_GRAPHICS=yes
+			GRAPHICSLIB="$GRAPHICS_LIB"
+			AC_DEFINE([_HAVE_GRAPHICS_],[1],[with GRAPHICS in ISSM src])
+			AC_SUBST([GRAPHICSLIB])
+		else
+			if test -f "$PETSC_ROOT/conf/petscvariables"; then
+				GRAPHICSLIB=$(cat $PETSC_ROOT/conf/petscvariables | grep X_LIB)
+				AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB) does not exist, PETSc suggests the following library: $GRAPHICSLIB]);
+			fi
+			AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB$) does not exist!]);
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl Capabilities
+	dnl with-kml{{{
+	AC_ARG_WITH([kml],
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
+		[KML=$withval],[KML=yes]) 
+	AC_MSG_CHECKING(for kml capability compilation)
+
+	if test "x$KML" = "xyes"; then
+		HAVE_KML=yes
+		AC_DEFINE([_HAVE_KML_],[1],[with kml capability])
+	else
+		HAVE_KML=no
+	fi
+	AM_CONDITIONAL([KML], [test x$HAVE_KML = xyes])
+	AC_MSG_RESULT($HAVE_KML)
+	dnl }}}
+	dnl with-kriging{{{
+	AC_ARG_WITH([kriging],
+		AS_HELP_STRING([--with-kriging = YES],[compile with kriging capabilities (default is yes)]),
+		[KRIGING=$withval],[KRIGING=yes]) 
+	AC_MSG_CHECKING(for kriging capability compilation)
+
+	if test "x$KRIGING" = "xyes"; then
+		HAVE_KRIGING=yes
+		AC_DEFINE([_HAVE_KRIGING_],[1],[with kriging capability])
+	else
+		HAVE_KRIGING=no
+	fi
+	AM_CONDITIONAL([KRIGING], [test x$HAVE_KRIGING = xyes])
+	AC_MSG_RESULT($HAVE_KRIGING)
+	dnl }}}
+	dnl with-steadystate{{{
+	AC_ARG_WITH([steadystate],
+		AS_HELP_STRING([--with-steadystate = YES],[compile with steadystate capabilities (default is yes)]),
+		[STEADYSTATE=$withval],[STEADYSTATE=yes]) 
+	AC_MSG_CHECKING(for steadystate capability compilation)
+
+	if test "x$STEADYSTATE" = "xyes"; then
+
+		dnl defaults
+		HAVE_STEADYSTATE=yes
+
+		AC_DEFINE([_HAVE_STEADYSTATE_],[1],[with steadystate capability])
+	else
+		HAVE_STEADYSTATE=no
+	fi
+	AM_CONDITIONAL([STEADYSTATE], [test x$HAVE_STEADYSTATE = xyes])
+	AC_MSG_RESULT($HAVE_STEADYSTATE)
+	dnl }}}
+	dnl with-transient{{{
+	AC_ARG_WITH([transient],
+		AS_HELP_STRING([--with-transient = YES], [compile with transient capabilities (default is yes)]),
+		[TRANSIENT=$withval],[TRANSIENT=yes]) 
+	AC_MSG_CHECKING(for transient capability compilation)
+
+	if test "x$TRANSIENT" = "xyes"; then
+
+		dnl defaults
+		HAVE_TRANSIENT=yes
+
+		AC_DEFINE([_HAVE_TRANSIENT_],[1],[with transient capability])
+	else
+		HAVE_TRANSIENT=no
+	fi
+	AM_CONDITIONAL([TRANSIENT], [test x$HAVE_TRANSIENT = xyes])
+	AC_MSG_RESULT($HAVE_TRANSIENT)
+	dnl }}}
+	dnl with-thermal{{{
+	AC_ARG_WITH([thermal],
+		AS_HELP_STRING([--with-thermal = YES], [compile with thermal capabilities (default is yes)]),
+		[THERMAL=$withval],[THERMAL=yes]) 
+	AC_MSG_CHECKING(for thermal capability compilation)
+
+	if test "x$THERMAL" = "xyes"; then
+
+		dnl defaults
+		HAVE_THERMAL=yes
+
+		AC_DEFINE([_HAVE_THERMAL_],[1],[with thermal capability])
+	else
+		HAVE_THERMAL=no
+	fi
+	AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
+	AC_MSG_RESULT($HAVE_THERMAL)
+	dnl }}}
+	dnl with-prognostic{{{
+	AC_ARG_WITH([prognostic],
+		AS_HELP_STRING([--with-prognostic = YES], [compile with prognostic capabilities (default is yes)]),
+		[PROGNOSTIC=$withval],[PROGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for prognostic capability compilation)
+
+	if test "x$PROGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_PROGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_PROGNOSTIC_],[1],[with prognostic capability])
+	else
+		HAVE_PROGNOSTIC=no
+	fi
+	AM_CONDITIONAL([PROGNOSTIC], [test x$HAVE_PROGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_PROGNOSTIC)
+	dnl }}}
+	dnl with-control{{{
+	AC_ARG_WITH([control],
+		AS_HELP_STRING([--with-control = YES], [compile with control capabilities (default is yes)]),
+		[CONTROL=$withval],[CONTROL=yes]) 
+	AC_MSG_CHECKING(for control capability compilation)
+
+	if test "x$CONTROL" = "xyes"; then
+
+		dnl defaults
+		HAVE_CONTROL=yes
+
+		AC_DEFINE([_HAVE_CONTROL_],[1],[with control capability])
+	else
+		HAVE_CONTROL=no
+	fi
+	AM_CONDITIONAL([CONTROL], [test x$HAVE_CONTROL = xyes])
+	AC_MSG_RESULT($HAVE_CONTROL)
+	dnl }}}
+	dnl with-hydrology{{{
+	AC_ARG_WITH([hydrology],
+		AS_HELP_STRING([--with-hydrology = YES], [compile with hydrology capabilities (default is yes)]),
+		[HYDROLOGY=$withval],[HYDROLOGY=yes]) 
+	AC_MSG_CHECKING(for hydrology capability compilation)
+
+	if test "x$HYDROLOGY" = "xyes"; then
+
+		dnl defaults
+		HAVE_HYDROLOGY=yes
+
+		AC_DEFINE([_HAVE_HYDROLOGY_],[1],[with hydrology capability])
+	else
+		HAVE_HYDROLOGY=no
+	fi
+	AM_CONDITIONAL([HYDROLOGY], [test x$HAVE_HYDROLOGY = xyes])
+	AC_MSG_RESULT($HAVE_HYDROLOGY)
+	dnl }}}
+	dnl with-diagnostic{{{
+	AC_ARG_WITH([diagnostic],
+		AS_HELP_STRING([--with-diagnostic = YES], [compile with diagnostic capabilities (default is yes)]),
+		[DIAGNOSTIC=$withval],[DIAGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for diagnostic capability compilation)
+
+	if test "x$DIAGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_DIAGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_DIAGNOSTIC_],[1],[with diagnostic capability])
+	else
+		HAVE_DIAGNOSTIC=no
+	fi
+	AM_CONDITIONAL([DIAGNOSTIC], [test x$HAVE_DIAGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_DIAGNOSTIC)
+	dnl }}}
+	dnl with-balanced{{{
+	AC_ARG_WITH([balanced],
+		AS_HELP_STRING([--with-balanced = YES], [compile with balanced capabilities (default is yes)]),
+		[BALANCED=$withval],[BALANCED=yes]) 
+	AC_MSG_CHECKING(for balanced capability compilation)
+
+	if test "x$BALANCED" = "xyes"; then
+
+		dnl defaults
+		HAVE_BALANCED=yes
+
+		AC_DEFINE([_HAVE_BALANCED_],[1],[with balanced capability])
+	else
+		HAVE_BALANCED=no
+	fi
+	AM_CONDITIONAL([BALANCED], [test x$HAVE_BALANCED = xyes])
+	AC_MSG_RESULT($HAVE_BALANCED)
+	dnl }}}
+	dnl with-responses{{{
+	AC_ARG_WITH([responses],
+		AS_HELP_STRING([--with-responses = YES], [compile with responses capabilities (default is yes)]),
+		[RESPONSES=$withval],[RESPONSES=yes]) 
+	AC_MSG_CHECKING(for responses capability compilation)
+
+	if test "x$RESPONSES" = "xyes"; then
+
+		dnl defaults
+		HAVE_RESPONSES=yes
+
+		AC_DEFINE([_HAVE_RESPONSES_],[1],[with responses capability])
+	else
+		HAVE_RESPONSES=no
+	fi
+	AM_CONDITIONAL([RESPONSES], [test x$HAVE_RESPONSES = xyes])
+	AC_MSG_RESULT($HAVE_RESPONSES)
+	dnl }}}
+	dnl with-slope{{{
+	AC_ARG_WITH([slope],
+		AS_HELP_STRING([--with-slope = YES], [compile with slope capabilities (default is yes)]),
+		[SLOPE=$withval],[SLOPE=yes]) 
+	AC_MSG_CHECKING(for slope capability compilation)
+
+	if test "x$SLOPE" = "xyes"; then
+
+		dnl defaults
+		HAVE_SLOPE=yes
+
+		AC_DEFINE([_HAVE_SLOPE_],[1],[with slope capability])
+	else
+		HAVE_SLOPE=no
+	fi
+	AM_CONDITIONAL([SLOPE], [test x$HAVE_SLOPE = xyes])
+	AC_MSG_RESULT($HAVE_SLOPE)
+	dnl }}}
+	dnl with-groundingline{{{
+	AC_ARG_WITH([groundingline],
+		AS_HELP_STRING([--with-groundingline = YES], [compile with groundingline capabilities (default is yes)]),
+		[GROUNDINGLINE=$withval],[GROUNDINGLINE=yes]) 
+	AC_MSG_CHECKING(for groundingline capability compilation)
+
+	if test "x$GROUNDINGLINE" = "xyes"; then
+
+		dnl defaults
+		HAVE_GROUNDINGLINE=yes
+
+		AC_DEFINE([_HAVE_GROUNDINGLINE_],[1],[with groundingline capability])
+	else
+		HAVE_GROUNDINGLINE=no
+	fi
+	AM_CONDITIONAL([GROUNDINGLINE], [test x$HAVE_GROUNDINGLINE = xyes])
+	AC_MSG_RESULT($HAVE_GROUNDINGLINE)
+	dnl }}}
+	dnl with-rifts{{{
+	AC_ARG_WITH([rifts],
+		AS_HELP_STRING([--with-rifts = YES], [compile with rifts capabilities (default is yes)]),
+		[RIFTS=$withval],[RIFTS=yes]) 
+	AC_MSG_CHECKING(for rifts capability compilation)
+
+	if test "x$RIFTS" = "xyes"; then
+
+		dnl defaults
+		HAVE_RIFTS=yes
+
+		AC_DEFINE([_HAVE_RIFTS_],[1],[with rifts capability])
+	else
+		HAVE_RIFTS=no
+	fi
+	AM_CONDITIONAL([RIFTS], [test x$HAVE_RIFTS = xyes])
+	AC_MSG_RESULT($HAVE_RIFTS)
+	dnl }}}
+	dnl math77{{{
+	AC_ARG_WITH([math77-dir],
+		AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
+		[MATH77_ROOT=$withval],[MATH77_ROOT=""]) 
+	AC_MSG_CHECKING(for math77)
+
+	if test -d "$MATH77_ROOT"; then
+
+	  HAVE_MATH77=yes
+	  MATH77LIB="-L$MATH77_ROOT/ -lmath77"
+
+	  AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
+	  AC_SUBST([MATH77LIB])
+	else
+		HAVE_MATH77=no
+	fi
+	AC_MSG_RESULT($HAVE_MATH77)
+	dnl }}}
+	dnl with-gia{{{
+	AC_ARG_WITH([gia],
+		AS_HELP_STRING([--with-gia = YES], [compile with gia capabilities (default is yes)]),
+		[GIA=$withval],[GIA=no]) 
+	AC_MSG_CHECKING(for gia capability compilation)
+
+	if test "x$GIA" = "xyes"; then
+	  
+	  if test "x$HAVE_MATH77" = "xno"; then
+		  HAVE_GIA=no
+		  AC_MSG_ERROR([gia requires compilation of math77 library! Reconfigure with --with-math77 option on]);
+	  else
+		dnl defaults
+		HAVE_GIA=yes
+		AC_DEFINE([_HAVE_GIA_],[1],[with gia capability])
+	  fi
+
+	else
+		HAVE_GIA=no
+	fi
+	AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
+	AC_MSG_RESULT($HAVE_GIA)
+	dnl }}}
+	dnl with-ios{{{
+	AC_ARG_WITH([ios],
+		AS_HELP_STRING([--with-ios = YES], [compile with iOS capabilities (default is no, alternatives are yes)]),
+		[IOS=$withval],[IOS=no]) 
+	AC_MSG_CHECKING(for iOS compilation)
+
+	if test "x$IOS" = "xyes"; then
+		dnl defaults
+		HAVE_IOS=yes
+
+		AC_DEFINE([_HAVE_IOS_],[1],[with android capability])
+	elif test "x$IOS" = "xno"; then
+		HAVE_IOS=no
+	else
+	  AC_MSG_ERROR([--with-ios should be either no or yes])
+	fi
+	AM_CONDITIONAL([IOS], [test x$HAVE_IOS != xno])
+	AC_MSG_RESULT($HAVE_IOS)
+	dnl }}}
+	dnl with-android{{{
+	AC_ARG_WITH([android],
+		AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
+		[ANDROID=$withval],[ANDROID=no]) 
+	AC_MSG_CHECKING(for android capability compilation)
+
+	if test "x$ANDROID" = "xjni"; then
+
+		dnl defaults
+		HAVE_ANDROID=jni
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+		AC_DEFINE([_HAVE_ANDROID_JNI_],[1],[with android jni])
+	elif test "x$ANDROID" = "xexe"; then
+		dnl defaults
+		HAVE_ANDROID=exe
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xno"; then
+		HAVE_ANDROID=no
+	else
+	  AC_MSG_ERROR([--with-android should be either no, exe or jni])
+	fi
+	AM_CONDITIONAL([ANDROID], [test x$HAVE_ANDROID != xno])
+	AM_CONDITIONAL([ANDROIDJNI], [test x$HAVE_ANDROID = xjni])
+	AM_CONDITIONAL([ANDROIDEXE], [test x$HAVE_ANDROID = xexe])
+	AC_MSG_RESULT($HAVE_ANDROID)
+	dnl }}}
+	dnl with-android-ndk{{{
+	AC_ARG_WITH([android-ndk],
+	  AS_HELP_STRING([--with-android-ndk=DIR], [android-ndk root directory.]),
+	  [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""]) 
+	AC_MSG_CHECKING(with android ndk)
+	
+	if test -d "$ANDROID_NDK_ROOT"; then
+		dnl defaults
+		HAVE_ANDROID_NDK=yes
+		ANDROID_NDKINCL="-I$ANDROID_NDK_ROOT/arm-linux-android-install/sysroot/usr/include"
+
+		AC_DEFINE([_HAVE_ANDROID_NDK_],[1],[with android ndk in ISSM src])
+		AC_SUBST([ANDROID_NDKINCL])
+	else
+		HAVE_ANDROID_NDK=no
+	fi
+	AC_MSG_RESULT($HAVE_ANDROID_NDK)
+	dnl }}}
+	dnl with-3d{{{
+	AC_ARG_WITH([3d],
+		AS_HELP_STRING([--with-3d = YES], [compile with 3d capabilities (default is yes)]),
+		[THREED=$withval],[THREED=yes]) 
+	AC_MSG_CHECKING(for 3d capability compilation)
+
+	if test "x$THREED" = "xyes"; then
+
+		dnl defaults
+		HAVE_3D=yes
+
+		AC_DEFINE([_HAVE_3D_],[1],[with 3d capability])
+	else
+		HAVE_3D=no
+	fi
+	AM_CONDITIONAL([THREED], [test x$HAVE_3D = xyes])
+	AC_MSG_RESULT($HAVE_3D)
+	dnl }}}
+	dnl checks{{{
+	AC_MSG_CHECKING(consistency between all libraries)
+	
+	dnl check that if petsc is requested , mpi should be specified
+	if test "$HAVE_PETSC" = "yes" ; then
+		if test "$HAVE_MPI" = "NO";  then
+			AC_MSG_ERROR([petsc requires mpi!]);
+		fi
+	fi
+
+	dnl check that we have either python or matlab support if we compile the modules
+	if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
+		AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
+	fi
+
+	dnl check that if we have MPI, we have metis
+	if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
+	AC_MSG_ERROR([need mpi if using the metis partitioner!]);
+	fi
+
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl other options
+	dnl optimization{{{
+	dnl bypass standard optimization -g -O2 ? 
+	AC_ARG_WITH([cxxoptflags],
+	  AS_HELP_STRING([--with-cxxoptflags = CXXOPTFLAGS], [optimization using CXX flags, ex: --with-cxxoptflags=-march=opteron -O3]),
+	  [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2"]) 
+	AC_MSG_CHECKING(for c++ optimization flags)
+	AC_SUBST([CXXOPTFLAGS])
+	AC_MSG_RESULT(done)
+
+	dnl }}}
+	dnl multithreading{{{
+	AC_ARG_WITH([numthreads],
+	  AS_HELP_STRING([--with-numthreads = NUMTHREADS_VALUE],[numthreads, default is 1. ]),
+	  [NUMTHREADS_VALUE=$withval],[NUMTHREADS_VALUE=1])
+	AC_MSG_CHECKING(for number of threads)
+	dnl defaults
+	MULTITHREADING=no
+	MULTITHREADINLIB=""
+	if test "$NUMTHREADS_VALUE" != "1"; then
+		
+		MULTITHREADINGLIB="-lpthread -lrt"
+		case "${host_os}" in
+		*cygwin*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*linux*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*darwin*)
+		MULTITHREADINGLIB="-lpthread"
+		;;
+		esac
+
+		AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
+		AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
+	fi
+	AC_SUBST([MULTITHREADINGLIB])
+	AC_MSG_RESULT($NUMTHREADS_VALUE) 
+	dnl }}}
+	dnl 64bit {{{
+	AC_ARG_WITH([64bit-indices],
+	  AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
+	  [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
+	AC_MSG_CHECKING(for 64 bit indices)
+
+	if test "$USE_64BIT_INDICES" == "1"; then
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[1],[with 64 bits indices])
+	else
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[0],[with 64 bits indices])
+	fi
+	AC_MSG_RESULT($USE_64BIT_INDICES)
+	dnl }}}
+])
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/templates/sampleControl
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/templates/sampleControl	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/templates/sampleControl	(revision 18231)
@@ -0,0 +1,6 @@
+Package: issm-python
+Version: 1.1.3
+Architecture: amd64
+Depends: mpich2, petsc3.2-issm, metis4.0-issm, triangle-bin, libtriangle-dev, python2.7-dev, python-scipy, python-netcdf4, netcdf-bin, python-nose, libnetcdfc++4, hdf5-tools
+Maintainer: issm/jpl (issm@jpl.nasa.gov)
+Description: Ice Sheet System Model, ubuntu/debian package
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/triangle.h.patch
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/triangle.h.patch	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/issmpkg/triangle.h.patch	(revision 18231)
@@ -0,0 +1,12 @@
+250a251,257
+> /*Patch for ISSM*/
+> #ifndef REAL
+> typedef double REAL;
+> typedef void VOID;
+> #endif
+> /*End patch*/
+> 
+283c290
+< void triangulate(char *, struct triangulateio *, struct triangulateio *,
+---
+> extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/package.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/package.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/package.sh	(revision 18231)
@@ -0,0 +1,15 @@
+#/bin/bash
+
+#Just tar gz the bin/ directory and test/ directory and put a startup.m file.
+
+rm -rf ISSM ISSM-Ubuntu32.tar.gz
+
+mkdir ISSM
+cd ISSM
+ln -s $ISSM_TIER/bin ./bin
+ln -s $ISSM_TIER/test ./test
+cp ../startup.m ./
+cp ../README.m ./
+cd ..
+tar  zcvfh  ISSM-Ubuntu32.tar.gz --exclude='.svn' ./ISSM
+rm -rf ISSM
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/startup.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/startup.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/ubuntu/startup.m	(revision 18231)
@@ -0,0 +1,40 @@
+%STARTUP - Matlab startup script
+%
+%   startup.m is a script run by matlab at the beginning of a session, just
+%   before handing over the prompt to the user. This delivery startup.m script
+%   has been customized here for the ISSM code. This startup script should be
+%   run by users before trying to use ISSM. The best way to do that is to put
+%   the startup file in the location where Matlab starts and established its
+%   root directory.
+
+% clear the last warning to focus on the warnings of the ISSM path
+lastwarn(''); 
+
+%Recover ISSM_TIER , or if on a Windows machine, ISSM_TIER_WIN
+ISSM_TIER=getenv('ISSM_TIER');
+
+if (isempty(ISSM_TIER)),
+	error('issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!');
+end
+
+%Now add all issm code paths necessary to run issm smoothly. 
+%We capture the error output, so that we can warn the user to update 
+%the variable ISSM_TIER in this file, in case it is not correctly setup. 
+
+%ISSM path
+addpath(ISSM_TIER);
+addpath([ISSM_TIER '/bin']);
+
+%Check on any warning messages that might indicate that the paths were not correct. 
+if ~isempty(lastwarn),
+	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_TIER variable in your .cshrc or .bashrc!\n');
+	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
+else
+	fprintf('\n  To get started with ISSM, type issmdoc at the command prompt.\n\n');
+end
+
+%disable matlab bell!
+beep off;
+
+% no warning if we try to plot while in nojvm (will not be supported in future releases)
+warning off MATLAB:HandleGraphics:noJVM
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/ISSM.initial.aip
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/ISSM.initial.aip	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/ISSM.initial.aip	(revision 18231)
@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<DOCUMENT Type="Advanced Installer" CreateVersion="8.9" version="10.1" Modules="simple" RootPath="." Language="en" Id="{36DC7549-63BC-4A22-AE82-A96C27BF7B21}">
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiPropsComponent">
+    <ROW Property="ALLUSERS" Value="2"/>
+    <ROW Property="ARPCOMMENTS" Value="This installer database contains the logic and data required to install [|ProductName]." ValueLocId="*"/>
+    <ROW Property="ARPCONTACT" Value="Eric Larour, Helene Seroussi and Mathieu Morlighem"/>
+    <ROW Property="ARPHELPTELEPHONE" Value="001 (818) 393-2435"/>
+    <ROW Property="ARPURLINFOABOUT" Value="http://issm.jpl.nasa.gov"/>
+    <ROW Property="CTRLS" Value="1"/>
+    <ROW Property="Manufacturer" Value="JPL-UCI" ValueLocId="*"/>
+    <ROW Property="ProductCode" Value="1033:{387D11EC-1489-4A6F-8CA2-BA65601C19BE} " Type="16"/>
+    <ROW Property="ProductLanguage" Value="1033"/>
+    <ROW Property="ProductName" Value="ISSM" ValueLocId="*"/>
+    <ROW Property="ProductVersion" Value="1.0" Type="32"/>
+    <ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND"/>
+    <ROW Property="UpgradeCode" Value="{F12D1A74-5079-41A3-A02A-15754B89E390}"/>
+    <ROW Property="VIEWREADME" Value="1" Type="4"/>
+    <ROW Property="WindowsType9X" MultiBuildValue="DefaultBuild:Windows 9x/ME" ValueLocId="-"/>
+    <ROW Property="WindowsType9XDisplay" MultiBuildValue="DefaultBuild:Windows 9x/ME" ValueLocId="-"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiDirsComponent">
+    <ROW Directory="APPDIR" Directory_Parent="TARGETDIR" DefaultDir="APPDIR:." IsPseudoRoot="1"/>
+    <ROW Directory="AppDataFolder" Directory_Parent="TARGETDIR" DefaultDir="AppDat~1|AppDataFolder" IsPseudoRoot="1"/>
+    <ROW Directory="DesktopFolder" Directory_Parent="TARGETDIR" DefaultDir="Deskto~1|DesktopFolder" IsPseudoRoot="1"/>
+    <ROW Directory="InternetExplorer_Dir" Directory_Parent="Microsoft_Dir" DefaultDir="Intern~1|Internet Explorer"/>
+    <ROW Directory="Microsoft_Dir" Directory_Parent="AppDataFolder" DefaultDir="Micros~1|Microsoft"/>
+    <ROW Directory="QuickLaunch_Dir" Directory_Parent="InternetExplorer_Dir" DefaultDir="QuickL~1|Quick Launch"/>
+    <ROW Directory="SHORTCUTDIR" Directory_Parent="TARGETDIR" DefaultDir="SHORTC~1|SHORTCUTDIR" IsPseudoRoot="1"/>
+    <ROW Directory="StartMenuFolder" Directory_Parent="TARGETDIR" DefaultDir="StartM~1|StartMenuFolder" IsPseudoRoot="1"/>
+    <ROW Directory="TARGETDIR" DefaultDir="SourceDir"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiCompsComponent">
+    <ROW Component="ProductInformation" ComponentId="{9BA1DCE1-2716-4161-BFC1-9427FF450B3F}" Directory_="APPDIR" Attributes="4" KeyPath="Version"/>
+    <ROW Component="QuickLaunch" ComponentId="{73BCCA29-216A-4FD5-A030-FFEAC0435857}" Directory_="QuickLaunch_Dir" Attributes="0"/>
+    <ROW Component="SHORTCUTDIR" ComponentId="{92285889-F321-4F14-B289-6895275D45D7}" Directory_="SHORTCUTDIR" Attributes="0"/>
+    <ROW Component="matlabissm.bat" ComponentId="{239E0327-22CA-433B-B84D-609A42F7F608}" Directory_="APPDIR" Attributes="0" KeyPath="matlabissm.bat" Type="0"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiFeatsComponent">
+    <ROW Feature="MainFeature" Title="MainFeature" Description="Description" Display="1" Level="1" Directory_="APPDIR" Attributes="0" Components="ProductInformation QuickLaunch SHORTCUTDIR matlabissm.bat"/>
+    <ATTRIBUTE name="CurrentFeature" value="MainFeature"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiFilesComponent">
+    <ROW File="README.rtf" Component_="matlabissm.bat" FileName="README.rtf" Attributes="0" SourcePath="..\..\bin\README.rtf" SelfReg="false"/>
+    <ROW File="matlabissm.bat" Component_="matlabissm.bat" FileName="matlab~1.bat|matlabissm.bat" Attributes="0" SourcePath="..\..\scripts\matlabissm.bat" SelfReg="false" NextFile="README.rtf"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.BuildComponent">
+    <ROW BuildKey="DefaultBuild" BuildName="DefaultBuild" BuildOrder="1" BuildType="0" Languages="en" InstallationType="4" MsiPackageType="x64"/>
+    <ATTRIBUTE name="CurrentBuild" value="DefaultBuild"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.CacheComponent">
+    <ATTRIBUTE name="Enable" value="false"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.DictionaryComponent">
+    <ROW Path="&lt;AI_DICTS&gt;ui.ail"/>
+    <ROW Path="&lt;AI_DICTS&gt;ui_en.ail"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.FragmentComponent">
+    <ROW Fragment="CommonUI.aip" Path="&lt;AI_FRAGS&gt;CommonUI.aip"/>
+    <ROW Fragment="FolderDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\FolderDlg.aip"/>
+    <ROW Fragment="MaintenanceTypeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\MaintenanceTypeDlg.aip"/>
+    <ROW Fragment="MaintenanceWelcomeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\MaintenanceWelcomeDlg.aip"/>
+    <ROW Fragment="SequenceDialogs.aip" Path="&lt;AI_THEMES&gt;classic\fragments\SequenceDialogs.aip"/>
+    <ROW Fragment="Sequences.aip" Path="&lt;AI_FRAGS&gt;Sequences.aip"/>
+    <ROW Fragment="StaticUIStrings.aip" Path="&lt;AI_FRAGS&gt;StaticUIStrings.aip"/>
+    <ROW Fragment="UI.aip" Path="&lt;AI_THEMES&gt;classic\fragments\UI.aip"/>
+    <ROW Fragment="Validation.aip" Path="&lt;AI_FRAGS&gt;Validation.aip"/>
+    <ROW Fragment="VerifyRemoveDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\VerifyRemoveDlg.aip"/>
+    <ROW Fragment="VerifyRepairDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\VerifyRepairDlg.aip"/>
+    <ROW Fragment="WelcomeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\WelcomeDlg.aip"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiBinaryComponent">
+    <ROW Name="aicustact.dll" SourcePath="&lt;AI_CUSTACTS&gt;aicustact.dll"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiControlComponent">
+    <ATTRIBUTE name="FixedSizeBitmaps" value="0"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiControlEventComponent">
+    <ROW Dialog_="FolderDlg" Control_="Back" Event="NewDialog" Argument="WelcomeDlg" Condition="AI_INSTALL" Ordering="1"/>
+    <ROW Dialog_="WelcomeDlg" Control_="Next" Event="NewDialog" Argument="FolderDlg" Condition="AI_INSTALL" Ordering="1"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Back" Event="NewDialog" Argument="FolderDlg" Condition="AI_INSTALL" Ordering="201"/>
+    <ROW Dialog_="FolderDlg" Control_="Next" Event="NewDialog" Argument="VerifyReadyDlg" Condition="AI_INSTALL" Ordering="201"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_INSTALL" Ordering="197"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceWelcomeDlg" Condition="AI_MAINT" Ordering="1"/>
+    <ROW Dialog_="MaintenanceWelcomeDlg" Control_="Next" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT" Ordering="99"/>
+    <ROW Dialog_="CustomizeDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT" Ordering="1"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="ChangeButton" Event="NewDialog" Argument="CustomizeDlg" Condition="AI_MAINT" Ordering="401"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Back" Event="NewDialog" Argument="CustomizeDlg" Condition="AI_MAINT" Ordering="202"/>
+    <ROW Dialog_="CustomizeDlg" Control_="Next" Event="NewDialog" Argument="VerifyReadyDlg" Condition="AI_MAINT" Ordering="101"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_MAINT" Ordering="198"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Back" Event="NewDialog" Argument="PatchWelcomeDlg" Condition="AI_PATCH" Ordering="203"/>
+    <ROW Dialog_="PatchWelcomeDlg" Control_="Next" Event="NewDialog" Argument="VerifyReadyDlg" Condition="AI_PATCH" Ordering="201"/>
+    <ROW Dialog_="VerifyReadyDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_PATCH" Ordering="199"/>
+    <ROW Dialog_="ResumeDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_RESUME" Ordering="299"/>
+    <ROW Dialog_="VerifyRemoveDlg" Control_="Remove" Event="EndDialog" Argument="Return" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="299"/>
+    <ROW Dialog_="VerifyRepairDlg" Control_="Repair" Event="EndDialog" Argument="Return" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="399"/>
+    <ROW Dialog_="VerifyRemoveDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="1"/>
+    <ROW Dialog_="VerifyRepairDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="1"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="RemoveButton" Event="NewDialog" Argument="VerifyRemoveDlg" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="601"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="RepairButton" Event="NewDialog" Argument="VerifyRepairDlg" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="601"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiCreateFolderComponent">
+    <ROW Directory_="SHORTCUTDIR" Component_="SHORTCUTDIR"/>
+    <ROW Directory_="QuickLaunch_Dir" Component_="QuickLaunch"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiCustActComponent">
+    <ROW Action="AI_DOWNGRADE" Type="19" Target="4010"/>
+    <ROW Action="AI_InstallModeCheck" Type="1" Source="aicustact.dll" Target="UpdateInstallMode" WithoutSeq="true"/>
+    <ROW Action="AI_PREPARE_UPGRADE" Type="65" Source="aicustact.dll" Target="PrepareUpgrade"/>
+    <ROW Action="AI_RESTORE_LOCATION" Type="65" Source="aicustact.dll" Target="RestoreLocation"/>
+    <ROW Action="AI_ResolveKnownFolders" Type="1" Source="aicustact.dll" Target="AI_ResolveKnownFolders"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Type="1" Source="aicustact.dll" Target="GetLocalizedCredentials"/>
+    <ROW Action="AI_SHOW_LOG" Type="65" Source="aicustact.dll" Target="LaunchLogFile" WithoutSeq="true"/>
+    <ROW Action="AI_STORE_LOCATION" Type="51" Source="ARPINSTALLLOCATION" Target="[APPDIR]"/>
+    <ROW Action="AI_ViewReadme" Type="1" Source="aicustact.dll" Target="[#README.rtf]"/>
+    <ROW Action="SET_APPDIR" Type="307" Source="APPDIR" Target="[ProgramFilesFolder][Manufacturer]\[ProductName]" MultiBuildTarget="DefaultBuild:[ProgramFiles64Folder][Manufacturer]\[ProductName]"/>
+    <ROW Action="SET_SHORTCUTDIR" Type="307" Source="SHORTCUTDIR" Target="[ProgramMenuFolder][ProductName]"/>
+    <ROW Action="SET_TARGETDIR_TO_APPDIR" Type="51" Source="TARGETDIR" Target="[APPDIR]"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiEnvComponent">
+    <ROW Environment="ISSM_TESTS_1" Name="=-ISSM_TESTS" Value="[test_Dir]" Component_="ProductInformation"/>
+    <ROW Environment="ISSM_TIER" Name="=-ISSM_TIER" Value="[APPDIR]" Component_="ProductInformation"/>
+    <ROW Environment="ISSM_TIER_WIN" Name="=-ISSM_TIER_WIN" Value="[APPDIR]" Component_="ProductInformation"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiIconsComponent">
+    <ROW Name="matlabissm.exe" SourcePath="ISSMlogo.ico" Index="0"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiInstExSeqComponent">
+    <ROW Action="AI_DOWNGRADE" Condition="AI_NEWERPRODUCTFOUND AND (UILevel &lt;&gt; 5)" Sequence="210"/>
+    <ROW Action="AI_RESTORE_LOCATION" Condition="APPDIR=&quot;&quot;" Sequence="749"/>
+    <ROW Action="AI_STORE_LOCATION" Condition="(Not Installed) OR REINSTALL" Sequence="1501"/>
+    <ROW Action="AI_PREPARE_UPGRADE" Condition="AI_UPGRADE=&quot;No&quot; AND (Not Installed)" Sequence="1399"/>
+    <ROW Action="AI_ResolveKnownFolders" Sequence="52"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Sequence="51"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiInstallUISequenceComponent">
+    <ROW Action="AI_RESTORE_LOCATION" Condition="APPDIR=&quot;&quot;" Sequence="749"/>
+    <ROW Action="AI_ResolveKnownFolders" Sequence="52"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Sequence="51"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiLaunchConditionsComponent">
+    <ROW Condition="Privileged" Description="[ProductName] requires administrative privileges to install." DescriptionLocId="AI.LaunchCondition.Privileged" IsPredefined="true" Builds="DefaultBuild"/>
+    <ROW Condition="VersionNT" Description="[ProductName] cannot be installed on [WindowsType9XDisplay]" DescriptionLocId="AI.LaunchCondition.No9X" IsPredefined="true" Builds="DefaultBuild"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiRegsComponent">
+    <ROW Registry="Path" Root="-1" Key="Software\[Manufacturer]\[ProductName]" Name="Path" Value="[APPDIR]" Component_="ProductInformation"/>
+    <ROW Registry="Version" Root="-1" Key="Software\[Manufacturer]\[ProductName]" Name="Version" Value="[ProductVersion]" Component_="ProductInformation"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiShortsComponent">
+    <ROW Shortcut="ISSM" Directory_="SHORTCUTDIR" Name="ISSM" Component_="matlabissm.bat" Target="[#matlabissm.bat]" Hotkey="0" Icon_="matlabissm.exe" IconIndex="0" ShowCmd="1" WkDir="APPDIR"/>
+    <ROW Shortcut="ISSM_1" Directory_="DesktopFolder" Name="ISSM" Component_="matlabissm.bat" Target="[#matlabissm.bat]" Hotkey="0" Icon_="matlabissm.exe" IconIndex="0" ShowCmd="1" WkDir="APPDIR"/>
+    <ROW Shortcut="ISSM_2" Directory_="QuickLaunch_Dir" Name="ISSM" Component_="matlabissm.bat" Target="[#matlabissm.bat]" Hotkey="0" Icon_="matlabissm.exe" IconIndex="0" ShowCmd="1" WkDir="APPDIR"/>
+    <ROW Shortcut="ISSM_3" Directory_="StartMenuFolder" Name="ISSM" Component_="matlabissm.bat" Target="[#matlabissm.bat]" Hotkey="0" Icon_="matlabissm.exe" IconIndex="0" ShowCmd="1" WkDir="APPDIR"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiThemeComponent">
+    <ATTRIBUTE name="UsedTheme" value="classic"/>
+  </COMPONENT>
+  <COMPONENT cid="caphyon.advinst.msicomp.MsiUpgradeComponent">
+    <ROW UpgradeCode="[|UpgradeCode]" VersionMax="[|ProductVersion]" Attributes="1025" ActionProperty="OLDPRODUCTS"/>
+    <ROW UpgradeCode="[|UpgradeCode]" VersionMin="[|ProductVersion]" Attributes="2" ActionProperty="AI_NEWERPRODUCTFOUND"/>
+  </COMPONENT>
+</DOCUMENT>
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package32.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package32.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package32.sh	(revision 18231)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+#get brand new project: 
+rm -rf ISSM.aip  ISSM-SetupFiles ISSM.msi
+cp ISSM.initial.aip ISSM.aip
+
+#get windows style path to files
+export ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#build list of files to put into the installer: 
+rm -rf ISSM.aic 
+cat << END > ISSM.aic
+;aic
+SetVersion "1.0"
+SetPackageName "ISSM.msi"
+END
+
+ls $ISSM_DIR_WIN/scripts/*.bat startup.m  | awk '{printf("AddFile APPDIR %s\n",$1);}' | sed 's/\//\\/g' >> ISSM.aic
+
+cat << END >> ISSM.aic
+AddFolder PersonalFolder $ISSM_DIR_WIN\test
+AddFolder APPDIR $ISSM_DIR_WIN\bin
+NewEnvironment -name ISSM_TESTS -value [test_Dir]
+NewEnvironment -name ISSM_DIR -value [APPDIR]
+NewEnvironment -name ISSM_DIR_WIN -value [APPDIR]
+Save
+Rebuild
+END
+#Not needed anymore? 
+#DelEnvironment ISSM_TESTS
+#DelEnvironment ISSM_DIR
+#DelEnvironment ISSM_DIR_WIN
+
+#Run installer: 
+"C:/Program Files (x86)/Caphyon/Advanced Installer 10.8/bin/x86/AdvancedInstaller.com" /execute  ./ISSM.aip ./ISSM.aic
+
+#Get rid of temporary files: 
+cp ISSM-SetupFiles/ISSM.msi ./
+rm -rf ISSM.aip ISSM-SetupFiles ISSM.aic
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package64.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package64.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/package64.sh	(revision 18231)
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+#get brand new project: 
+rm -rf ISSM.aip  ISSM-SetupFiles ISSM.msi
+cp ISSM.initial.aip ISSM.aip
+
+#recover version: 
+version=`svn info | grep Revision | awk '{printf("%s\n",$2);}'`
+
+#get windows style path to files
+export ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#build list of files to put into the installer: 
+rm -rf ISSM.aic 
+cat << END > ISSM.aic
+;aic
+SetVersion "$version"
+SetPackageName "ISSM.msi"
+END
+
+ls $ISSM_DIR_WIN/scripts/*.bat startup.m | awk '{printf("AddFile APPDIR %s\n",$1);}' | sed 's/\//\\/g' >> ISSM.aic
+
+cat << END >> ISSM.aic
+AddFolder PersonalFolder $ISSM_DIR_WIN\test
+AddFolder PersonalFolder $ISSM_DIR_WIN\examples
+AddFolder APPDIR $ISSM_DIR_WIN\bin
+AddFolder APPDIR $ISSM_DIR_WIN\lib
+NewEnvironment -name ISSM_TESTS -value [test_Dir]
+NewEnvironment -name ISSM_DIR -value [APPDIR]
+NewEnvironment -name ISSM_DIR_WIN -value [APPDIR]
+Save
+Rebuild
+END
+#Not needed anymore? 
+#DelEnvironment ISSM_TESTS
+#DelEnvironment ISSM_DIR
+#DelEnvironment ISSM_DIR_WIN
+
+#Run installer: 
+"C:/Program Files (x86)/Caphyon/Advanced Installer 10.8/bin/x86/AdvancedInstaller.com" /execute  ./ISSM.aip ./ISSM.aic
+
+#Get rid of temporary files: 
+cp ISSM-SetupFiles/ISSM.msi ./
+rm -rf ISSM.aip ISSM-SetupFiles ISSM.aic
+
+#To upload to website: 
+#scp ISSM.msi websites:/home/larour/files/ISSM64.msi
Index: /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/startup.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/startup.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/packagers/win7/startup.m	(revision 18231)
@@ -0,0 +1,47 @@
+%STARTUP - Matlab startup script
+%
+%   startup.m is a script run by matlab at the beginning of a session, just
+%   before handing over the prompt to the user. This delivery startup.m script
+%   has been customized here for the ISSM code. This startup script should be
+%   run by users before trying to use ISSM. The best way to do that is to put
+%   the startup file in the location where Matlab starts and established its
+%   root directory.
+
+% clear the last warning to focus on the warnings of the ISSM path
+lastwarn(''); 
+
+%Recover ISSM_TIER , or if on a Windows machine, ISSM_TIER_WIN
+ISSM_TIER=getenv('ISSM_TIER_WIN');
+
+if (isempty(ISSM_TIER)),
+	error('issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!');
+end
+
+%Now add all issm code paths necessary to run issm smoothly. 
+%We capture the error output, so that we can warn the user to update 
+%the variable ISSM_TIER in this file, in case it is not correctly setup. 
+
+%ISSM path
+addpath(pwd); %add current path first
+addpath([pwd '\bin']);
+addpath([pwd '\lib']);
+
+%Check on any warning messages that might indicate that the paths were not correct. 
+if ~isempty(lastwarn),
+	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_TIER variable in your .cshrc or .bashrc!\n');
+	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
+else
+	fprintf('\n  To get started with ISSM, type issmdoc at the command prompt.\n\n');
+end
+
+%disable matlab bell!
+beep off;
+
+% no warning if we try to plot while in nojvm (will not be supported in future releases)
+warning off MATLAB:HandleGraphics:noJVM
+
+%at the end, get to tests directory if ISSM_TESTS exists: 
+ISSM_TESTS=getenv('ISSM_TESTS');
+if ~isempty(ISSM_TESTS),
+	cd(ISSM_TESTS);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_C
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_C	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_C	(revision 18231)
@@ -0,0 +1,1018 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@
+
+EXEEXT=$(ISSMEXT)
+
+#Library declaration {{{
+lib_LIBRARIES = libISSMCore.a libISSMOverload.a
+
+if WRAPPERS
+lib_LIBRARIES += libISSMModules.a 
+endif
+#}}}
+
+#sources
+#Core sources{{{
+core_sources = ./main/issm.h\
+			   ./main/globals.h\
+			   ./datastructures/DataSet.h\
+					./datastructures/DataSet.cpp\
+					./datastructures/Object.h\
+					./datastructures/datastructures.h\
+					./classes/classes.h\
+					./classes/gauss/GaussTria.h\
+					./classes/gauss/GaussTria.cpp\
+					./classes/Update.h\
+					./classes/Element.h\
+					./classes/FemModel.h\
+					./classes/FemModel.cpp\
+					./classes/Material.h\
+					./classes/Load.h\
+					./classes/Contour.h\
+					./classes/Loads/Friction.h\
+					./classes/Loads/Friction.cpp\
+					./classes/Inputs/TransientInput.h\
+					./classes/Inputs/TransientInput.cpp\
+					./classes/Constraints/SpcTransient.cpp\
+					./classes/Constraints/SpcTransient.h\
+					./classes/IndependentObject.h\
+					./classes/IndependentObject.cpp\
+					./classes/DependentObject.h\
+					./classes/DependentObject.cpp\
+					./classes/DofIndexing.h\
+					./classes/DofIndexing.cpp\
+					./classes/IoModel.h\
+					./classes/IoModel.cpp\
+					./classes/Contours.h\
+					./classes/Contours.cpp\
+					./classes/Nodes.h\
+					./classes/Nodes.cpp\
+					./classes/Vertices.h\
+					./classes/Vertices.cpp\
+					./classes/Node.h\
+					./classes/Node.cpp\
+					./classes/Segment.h\
+					./classes/Vertex.h\
+					./classes/Vertex.cpp\
+					./classes/Hook.h\
+					./classes/Hook.cpp\
+					./classes/Patch.h\
+					./classes/Patch.cpp\
+					./classes/ElementResults/ElementResultLocal.h\
+					./classes/ElementResults/DoubleElementResult.h\
+					./classes/ElementResults/DoubleElementResult.cpp\
+					./classes/ElementResults/TriaP1ElementResult.h\
+					./classes/ElementResults/TriaP1ElementResult.cpp\
+					./classes/ElementResults/BoolElementResult.h\
+					./classes/ElementResults/BoolElementResult.cpp\
+					./classes/ExternalResults/Results.h\
+					./classes/ExternalResults/Results.cpp\
+					./classes/ExternalResults/ExternalResult.h\
+					./classes/ExternalResults/GenericExternalResult.h\
+					./classes/Elements/Elements.h\
+					./classes/Elements/Elements.cpp\
+					./classes/Elements/Tria.h\
+					./classes/Elements/Tria.cpp\
+					./classes/Elements/TriaHook.h\
+					./classes/Elements/TriaHook.cpp\
+					./classes/Elements/TriaRef.h\
+					./classes/Elements/TriaRef.cpp\
+					./classes/Inputs/Inputs.h\
+					./classes/Inputs/Inputs.cpp\
+					./classes/Inputs/Input.h\
+					./classes/Inputs/InputLocal.h\
+					./classes/Inputs/TriaP1Input.h\
+					./classes/Inputs/TriaP1Input.cpp\
+					./classes/Inputs/BoolInput.h\
+					./classes/Inputs/BoolInput.cpp\
+					./classes/Inputs/IntInput.h\
+					./classes/Inputs/IntInput.cpp\
+					./classes/Inputs/DoubleInput.h\
+					./classes/Inputs/DoubleInput.cpp\
+					./classes/Inputs/DatasetInput.h\
+					./classes/Inputs/DatasetInput.cpp\
+					./classes/Materials/Materials.h\
+					./classes/Materials/Materials.cpp\
+					./classes/Materials/Matice.h\
+					./classes/Materials/Matice.cpp\
+					./classes/Materials/Matdamageice.h\
+					./classes/Materials/Matdamageice.cpp\
+					./classes/Materials/Matpar.h\
+					./classes/Materials/Matpar.cpp\
+					./classes/Constraints/Constraints.h\
+					./classes/Constraints/Constraints.cpp\
+					./classes/Constraints/Constraint.h\
+					./classes/Constraints/SpcStatic.cpp\
+					./classes/Constraints/SpcStatic.h\
+					./classes/Constraints/SpcDynamic.cpp\
+					./classes/Constraints/SpcDynamic.h\
+					./classes/Loads/Loads.h\
+					./classes/Loads/Loads.cpp\
+					./classes/Loads/Penpair.cpp\
+					./classes/Loads/Penpair.h\
+					./classes/Loads/Pengrid.cpp\
+					./classes/Loads/Pengrid.h\
+					./classes/Loads/Icefront.cpp\
+					./classes/Loads/Icefront.h\
+					./classes/Loads/Numericalflux.cpp\
+					./classes/Loads/Numericalflux.h\
+					./classes/matrix/matrixobjects.h\
+					./classes/matrix/ElementMatrix.h\
+					./classes/matrix/ElementMatrix.cpp\
+					./classes/matrix/ElementVector.h\
+					./classes/matrix/ElementVector.cpp\
+					./classes/Params/Parameters.h\
+					./classes/Params/Parameters.cpp\
+					./classes/Params/Param.h\
+					./classes/Params/GenericParam.h\
+					./classes/Params/BoolParam.cpp\
+					./classes/Params/BoolParam.h\
+					./classes/Params/IntParam.cpp\
+					./classes/Params/IntParam.h\
+					./classes/Params/IntVecParam.cpp\
+					./classes/Params/IntVecParam.h\
+					./classes/Params/IntMatParam.cpp\
+					./classes/Params/IntMatParam.h\
+					./classes/Params/DoubleParam.cpp\
+					./classes/Params/DoubleParam.h\
+					./classes/Params/FileParam.cpp\
+					./classes/Params/FileParam.h\
+					./classes/Params/StringArrayParam.cpp\
+					./classes/Params/StringArrayParam.h\
+					./classes/Params/DoubleMatParam.cpp\
+					./classes/Params/DoubleMatParam.h\
+					./classes/Params/DoubleTransientMatParam.cpp\
+					./classes/Params/DoubleTransientMatParam.h\
+					./classes/Params/DoubleMatArrayParam.cpp\
+					./classes/Params/DoubleMatArrayParam.h\
+					./classes/Params/DoubleVecParam.cpp\
+					./classes/Params/DoubleVecParam.h\
+					./classes/Params/StringParam.cpp\
+					./classes/Params/StringParam.h\
+					./classes/Params/MatrixParam.h\
+					./classes/Params/MatrixParam.cpp\
+					./classes/Params/VectorParam.h\
+					./classes/Params/VectorParam.cpp\
+					./classes/Params/TransientParam.h\
+					./classes/Params/TransientParam.cpp\
+					./classes/Params/DataSetParam.h\
+					./classes/Params/DataSetParam.cpp\
+					./classes/Profiler.h\
+					./classes/Profiler.cpp\
+					./shared/shared.h\
+					./shared/MemOps/MemOps.h\
+					./shared/Matrix/matrix.h\
+					./shared/Matrix/MatrixUtils.cpp\
+					./shared/io/io.h\
+					./shared/io/Disk/diskio.h\
+					./shared/io/Disk/pfopen.cpp\
+					./shared/io/Disk/pfclose.cpp\
+					./shared/io/Disk/WriteLockFile.cpp\
+					./shared/io/Print/PrintfFunction.cpp\
+					./shared/io/Print/Print.h\
+					./shared/io/Comm/Comm.h\
+					./shared/io/Comm/CommDef.h\
+					./shared/io/Comm/IssmComm.h\
+					./shared/io/Comm/IssmComm.cpp\
+					./shared/LatLong/Ll2xyx.cpp\
+					./shared/LatLong/Xy2llx.cpp\
+					./shared/Enum/Enum.h\
+					./shared/Enum/EnumDefinitions.h\
+					./shared/Enum/EnumToStringx.cpp\
+					./shared/Enum/StringToEnumx.cpp\
+					./shared/Numerics/numerics.h\
+					./shared/Numerics/types.h\
+					./shared/Numerics/constants.h\
+					./shared/Numerics/Verbosity.h\
+					./shared/Numerics/Verbosity.cpp\
+					./shared/Numerics/GaussPoints.h\
+					./shared/Numerics/GaussPoints.cpp\
+					./shared/Numerics/cross.cpp\
+					./shared/Numerics/isnan.h\
+					./shared/Numerics/isnan.cpp\
+					./shared/Numerics/cubic.cpp\
+					./shared/Numerics/extrema.cpp\
+					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
+					./shared/Numerics/UnitConversion.cpp\
+					./shared/Numerics/OptArgs.h\
+					./shared/Numerics/OptPars.h\
+					./shared/Exceptions/exceptions.h\
+					./shared/Exceptions/Exceptions.cpp\
+					./shared/Exceptions/exprintf.cpp\
+					./shared/Sorting/binary_search.cpp\
+					./shared/Sorting/sorting.h\
+					./shared/Elements/elements.h\
+					./shared/Elements/Paterson.cpp\
+					./shared/Elements/Arrhenius.cpp\
+					./shared/Elements/PrintArrays.cpp\
+					./shared/Elements/PddSurfaceMassBalance.cpp\
+					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
+					./shared/String/sharedstring.h\
+					./shared/String/DescriptorIndex.cpp\
+					./toolkits/metis/metisincludes.h\
+					./toolkits/issm/issmtoolkit.h\
+					./toolkits/issm/IssmToolkitUtils.h\
+					./toolkits/issm/IssmToolkitUtils.cpp\
+					./toolkits/issm/IssmAbsMat.h\
+					./toolkits/issm/IssmAbsVec.h\
+					./toolkits/issm/IssmDenseMat.h\
+					./toolkits/issm/IssmMat.h\
+					./toolkits/issm/IssmSeqVec.h\
+					./toolkits/issm/IssmVec.h\
+					./toolkits/issm/IssmSolver.h\
+					./toolkits/issm/IssmSolver.cpp\
+					./toolkits/issm/Bucket.h\
+					./toolkits/adolc/adolcincludes.h\
+					./toolkits/adolc/AdolcEdf.h\
+					./toolkits/ToolkitOptions.h\
+					./toolkits/ToolkitOptions.cpp\
+					./toolkits/triangle/triangleincludes.h\
+					./toolkits/objects/toolkitobjects.h\
+					./toolkits/objects/Matrix.h\
+					./toolkits/objects/Vector.h\
+					./toolkits/objects/Solver.h\
+					./toolkitsenums.h\
+					./toolkits.h\
+					./modules/ModelProcessorx/ModelProcessorx.h\
+					./modules/ModelProcessorx/ModelProcessorx.cpp\
+					./modules/ModelProcessorx/DistributeNumDofs.cpp\
+					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
+					./modules/ModelProcessorx/NodesPartitioning.cpp\
+					./modules/ModelProcessorx/SortDataSets.cpp\
+					./modules/ModelProcessorx/UpdateCounters.cpp\
+					./modules/ModelProcessorx/CreateDataSets.cpp\
+					./modules/ModelProcessorx/CreateParameters.cpp\
+					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
+					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
+					./modules/NodesDofx/NodesDofx.h\
+					./modules/NodesDofx/NodesDofx.cpp\
+					./modules/NodalValuex/NodalValuex.h\
+					./modules/NodalValuex/NodalValuex.cpp\
+					./modules/VerticesDofx/VerticesDofx.h\
+					./modules/VerticesDofx/VerticesDofx.cpp\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.h\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp\
+					./modules/OutputResultsx/OutputResultsx.h\
+					./modules/OutputResultsx/OutputResultsx.cpp\
+					./modules/InputDuplicatex/InputDuplicatex.h\
+					./modules/InputDuplicatex/InputDuplicatex.cpp\
+					./modules/InputScalex/InputScalex.h\
+					./modules/InputScalex/InputScalex.cpp\
+					./modules/SurfaceAreax/SurfaceAreax.h\
+					./modules/SurfaceAreax/SurfaceAreax.cpp\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.h\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.h\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
+					./modules/InputArtificialNoisex/InputArtificialNoisex.h\
+					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
+					./modules/ComputeBasalStressx/ComputeBasalStressx.h\
+					./modules/ComputeBasalStressx/ComputeBasalStressx.cpp\
+					./modules/ComputeStrainRatex/ComputeStrainRatex.h\
+					./modules/ComputeStrainRatex/ComputeStrainRatex.cpp\
+					./modules/SpcNodesx/SpcNodesx.h\
+					./modules/SpcNodesx/SpcNodesx.cpp\
+					./modules/PositiveDegreeDayx/PositiveDegreeDayx.h\
+					./modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp\
+					./modules/Delta18oParameterizationx/Delta18oParameterizationx.h\
+					./modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp\
+					./modules/SmbGradientsx/SmbGradientsx.h\
+					./modules/SmbGradientsx/SmbGradientsx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.h\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
+					./modules/Reduceloadx/Reduceloadx.h\
+					./modules/Reduceloadx/Reduceloadx.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.h\
+					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp\
+					./modules/Solverx/Solverx.cpp\
+					./modules/Solverx/Solverx.h\
+					./modules/VecMergex/VecMergex.cpp\
+					./modules/VecMergex/VecMergex.h\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
+					./modules/InputToResultx/InputToResultx.cpp\
+					./modules/InputToResultx/InputToResultx.h\
+					./analyses/ProcessArguments.cpp\
+					./analyses/ResetBoundaryConditions.cpp\
+					./analyses/AnalysisConfiguration.cpp\
+					./analyses/WrapperCorePointerFromSolutionEnum.cpp\
+					./analyses/CorePointerFromSolutionEnum.cpp\
+					./analyses/EnvironmentInit.cpp\
+					./analyses/EnvironmentFinalize.cpp\
+					./analyses/ad_core.cpp\
+					./solutionsequences/solutionsequence_linear.cpp\
+					./solutionsequences/solutionsequence_nonlinear.cpp\
+					./solutionsequences/solutionsequence_newton.cpp\
+					./solutionsequences/convergence.cpp\
+					./classes/Options/Options.h\
+					./classes/Options/Options.cpp\
+					./classes/Options/Option.h\
+					./classes/Options/GenericOption.h\
+					./classes/Options/OptionUtilities.cpp\
+					./classes/Options/OptionUtilities.h\
+					./classes/RiftStruct.cpp\
+					./classes/RiftStruct.h
+#}}}
+#DAKOTA sources  {{{
+dakota_sources = ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
+					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
+					  ./analyses/dakota_core.cpp\
+					  ./analyses/DakotaSpawnCore.h\
+					  ./analyses/DakotaSpawnCore.cpp
+#}}}
+#Transient sources  {{{
+transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
+							./analyses/transient_core.cpp
+#}}}
+#Steadystate sources  {{{
+steadystate_sources = ./analyses/steadystate_core.cpp
+#}}}
+#Prognostic sources  {{{
+prognostic_sources = ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp\
+							./analyses/prognostic_core.cpp
+#}}}
+#Thermal sources  {{{
+thermal_sources = ./modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp\
+					   ./modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp\
+					   ./modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp\
+					   ./modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp\
+					   ./modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp\
+					   ./modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp\
+					   ./modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp\
+					   ./modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp\
+					   ./modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp\
+					   ./modules/ModelProcessorx/Melting/CreateNodesMelting.cpp\
+					   ./modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp\
+					   ./modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp\
+					   ./modules/ConstraintsStatex/ThermalConstraintsState.cpp\
+					   ./modules/ConstraintsStatex/ThermalIsPresent.cpp\
+					   ./modules/ResetConstraintsx/ThermalConstraintsReset.cpp \
+					   ./analyses/thermal_core.cpp\
+					   ./analyses/enthalpy_core.cpp\
+					   ./solutionsequences/solutionsequence_thermal_nonlinear.cpp
+#}}}
+#Control sources  {{{
+control_sources= ./modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp\
+					  ./modules/ControlInputGetGradientx/ControlInputGetGradientx.h\
+					  ./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp\
+					  ./modules/ControlInputSetGradientx/ControlInputSetGradientx.h\
+					  ./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp\
+					  ./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h\
+					  ./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp\
+					  ./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h\
+					  ./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp\
+					  ./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h\
+					  ./modules/ModelProcessorx/Control/CreateParametersControl.cpp\
+					  ./modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp\
+					  ./modules/InputControlUpdatex/InputControlUpdatex.h\
+					  ./modules/InputControlUpdatex/InputControlUpdatex.cpp\
+					  ./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h\
+					  ./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp\
+					  ./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h\
+					  ./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp\
+					  ./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h\
+					  ./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp\
+					  ./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h\
+					  ./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp\
+					  ./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h\
+					  ./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp\
+					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
+					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
+					  ./modules/Orthx/Orthx.h\
+					  ./modules/Orthx/Orthx.cpp\
+					  ./modules/Gradjx/Gradjx.h\
+					  ./modules/Gradjx/Gradjx.cpp\
+					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
+					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
+					  ./classes/Inputs/ControlInput.h\
+					  ./classes/Inputs/ControlInput.cpp\
+					  ./shared/Numerics/BrentSearch.cpp\
+					  ./shared/Numerics/OptimalSearch.cpp \
+					  ./analyses/control_core.cpp\
+					  ./analyses/controltao_core.cpp\
+					  ./analyses/objectivefunction.cpp\
+					  ./analyses/gradient_core.cpp\
+					  ./analyses/adjointdiagnostic_core.cpp\
+					  ./analyses/adjointbalancethickness_core.cpp\
+					  ./analyses/AdjointCorePointerFromSolutionEnum.cpp\
+					  ./solutionsequences/solutionsequence_adjoint_linear.cpp
+
+#}}}
+#Hydrology sources  {{{
+hydrology_sources  = ./modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp\
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp\
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp\
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp \
+							./modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp \
+							./modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp \
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp \
+							./modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp\
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp \
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp \
+							./analyses/hydrology_core.cpp\
+							./solutionsequences/solutionsequence_hydro_nonlinear.cpp
+#}}}
+#Diagnostic sources  {{{
+diagnostic_sources = ./modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp\
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp \
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp \
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp\
+					      ./modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp\
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp \
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp \
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp\
+					      ./modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp\
+					      ./modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp \
+					      ./modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp \
+							./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp \
+							./analyses/diagnostic_core.cpp\
+							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
+#}}}
+#Balanced sources  {{{
+balanced_sources = ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp\
+					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
+					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
+						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
+						 ./analyses/balancethickness_core.cpp \
+						 ./analyses/dummy_core.cpp
+#}}}
+#Slope sources  {{{
+slope_sources =  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp\
+					  ./modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp \
+					  ./modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp\
+					  ./modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp\
+					  ./modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp\
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp \
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp\
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp\
+					  ./analyses/surfaceslope_core.cpp\
+					  ./analyses/bedslope_core.cpp
+#}}}
+#Gia sources  {{{
+gia_sources =  ./analyses/gia_core.cpp\
+					./modules/ModelProcessorx/Gia/UpdateElementsGia.cpp\
+					./modules/ModelProcessorx/Gia/CreateNodesGia.cpp \
+					./modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp\
+					./modules/ModelProcessorx/Gia/CreateLoadsGia.cpp\
+					./modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp\
+					./modules/GiaDeflectionCorex/GiaDeflectionCorex.h\
+					./modules/GiaDeflectionCorex/distme.f\
+					./modules/GiaDeflectionCorex/freed.f\
+					./modules/GiaDeflectionCorex/ojrule.f\
+					./modules/GiaDeflectionCorex/pwise.f\
+					./modules/GiaDeflectionCorex/qwise.f\
+					./modules/GiaDeflectionCorex/stot.f\
+					./modules/GiaDeflectionCorex/what0.f\
+					./classes/GiaDeflectionCoreArgs.h
+
+#}}}
+#Groundingline sources  {{{
+groundingline_sources= ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
+					        ./modules/GroundinglineMigrationx/GroundinglineMigrationx.h
+#}}}
+#Rifts sources  {{{
+rifts_sources = ./classes/Loads/Riftfront.cpp\
+				    ./classes/Loads/Riftfront.h\
+				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
+#}}}
+#Android sources  {{{
+android_sources = 
+#}}}
+#3D sources  {{{
+threed_sources = ./classes/gauss/GaussPenta.h\
+				     ./classes/gauss/GaussPenta.cpp\
+				     ./classes/ElementResults/PentaP1ElementResult.h\
+				     ./classes/ElementResults/PentaP1ElementResult.cpp\
+				     ./classes/Inputs/PentaP1Input.h\
+				     ./classes/Inputs/PentaP1Input.cpp\
+				     ./classes/Elements/Penta.h\
+				     ./classes/Elements/Penta.cpp\
+				     ./classes/Elements/PentaHook.h\
+				     ./classes/Elements/PentaHook.cpp\
+				     ./classes/Elements/PentaRef.h\
+				     ./classes/Elements/PentaRef.cpp
+#}}}
+#Bamg sources  {{{
+bamg_sources =  ./bamg/bamgobjects.h\
+				./bamg/BamgGeom.h\
+				./bamg/BamgGeom.cpp\
+				./bamg/BamgMesh.h\
+				./bamg/BamgMesh.cpp\
+				./bamg/BamgOpts.h\
+				./bamg/BamgOpts.cpp\
+				./bamg/CrackedEdge.h\
+				./bamg/CrackedEdge.cpp\
+				./bamg/Curve.h\
+				./bamg/Curve.cpp\
+				./bamg/Direction.h\
+				./bamg/Direction.cpp\
+				./bamg/DoubleAndInt.h\
+				./bamg/Edge.h\
+				./bamg/Edge.cpp\
+				./bamg/GeomEdge.h\
+				./bamg/GeomEdge.cpp\
+				./bamg/GeomSubDomain.h\
+				./bamg/GeomSubDomain.cpp\
+				./bamg/GeomVertex.h\
+				./bamg/GeomVertex.cpp\
+				./bamg/Geometry.cpp\
+				./bamg/Geometry.h\
+				./bamg/ListofIntersectionTriangles.cpp\
+				./bamg/ListofIntersectionTriangles.h\
+				./bamg/EigenMetric.cpp\
+				./bamg/Metric.cpp\
+				./bamg/Metric.h\
+				./bamg/BamgQuadtree.cpp\
+				./bamg/BamgQuadtree.h\
+				./bamg/R2.h\
+				./bamg/SetOfE4.cpp\
+				./bamg/SetOfE4.h\
+				./bamg/SubDomain.h\
+				./bamg/SubDomain.cpp\
+				./bamg/AdjacentTriangle.h\
+				./bamg/AdjacentTriangle.cpp\
+				./bamg/Triangle.cpp\
+				./bamg/det.h \
+				./bamg/Triangle.h\
+				./bamg/BamgVertex.cpp\
+				./bamg/BamgVertex.h\
+				./bamg/VertexOnEdge.h\
+				./bamg/VertexOnEdge.cpp\
+				./bamg/VertexOnGeom.h\
+				./bamg/VertexOnGeom.cpp\
+				./bamg/VertexOnVertex.h\
+				./bamg/VertexOnVertex.cpp\
+				./bamg/Mesh.cpp\
+				./bamg/Mesh.h\
+				./shared/Bamg/Abs.h \
+				./shared/Bamg/BigPrimeNumber.h\
+				./shared/Bamg/BigPrimeNumber.cpp\
+				./shared/Bamg/BinaryRand.h \
+				./shared/Bamg/Exchange.h \
+				./shared/Bamg/extrema.h \
+				./shared/Bamg/HeapSort.h \
+				./shared/Bamg/OppositeAngle.h \
+				./modules/Bamgx/Bamgx.cpp\
+				./modules/Bamgx/Bamgx.h\
+				./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
+				./modules/BamgConvertMeshx/BamgConvertMeshx.h\
+				./modules/BamgTriangulatex/BamgTriangulatex.cpp\
+				./modules/BamgTriangulatex/BamgTriangulatex.h
+#}}}
+#Kriging sources  {{{
+kriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
+						./classes/kriging/Variogram.h \
+						./classes/kriging/GaussianVariogram.h\
+						./classes/kriging/GaussianVariogram.cpp\
+						./classes/kriging/ExponentialVariogram.h\
+						./classes/kriging/ExponentialVariogram.cpp\
+						./classes/kriging/SphericalVariogram.h\
+						./classes/kriging/SphericalVariogram.cpp\
+						./classes/kriging/PowerVariogram.h\
+						./classes/kriging/PowerVariogram.cpp\
+						./classes/kriging/Quadtree.h\
+						./classes/kriging/Quadtree.cpp\
+						./classes/kriging/Observation.h\
+						./classes/kriging/Observation.cpp\
+						./modules/Krigingx/Krigingx.cpp\
+						./modules/Krigingx/Krigingx.h
+
+#For parallel kriging, only difference is ./modules/Krigingx/pKrigingx.cpp with no multithreading
+pkriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
+						./classes/kriging/Variogram.h \
+						./classes/kriging/GaussianVariogram.h\
+						./classes/kriging/GaussianVariogram.cpp\
+						./classes/kriging/ExponentialVariogram.h\
+						./classes/kriging/ExponentialVariogram.cpp\
+						./classes/kriging/SphericalVariogram.h\
+						./classes/kriging/SphericalVariogram.cpp\
+						./classes/kriging/PowerVariogram.h\
+						./classes/kriging/PowerVariogram.cpp\
+						./classes/kriging/Quadtree.h\
+						./classes/kriging/Quadtree.cpp\
+						./classes/kriging/Observation.h\
+						./classes/kriging/Observation.cpp\
+						./modules/Krigingx/pKrigingx.cpp\
+						./modules/Krigingx/Krigingx.h
+
+#}}}
+#Kml sources  {{{
+kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.h\
+			     ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
+			     ./modules/Kml2Expx/Kml2Expx.h\
+			     ./modules/Kml2Expx/Kml2Expx.cpp\
+			     ./modules/Shp2Expx/Shp2Expx.h\
+			     ./modules/Shp2Expx/Shp2Expx.cpp\
+			     ./modules/Shp2Kmlx/Shp2Kmlx.h\
+			     ./modules/Shp2Kmlx/Shp2Kmlx.cpp\
+			     ./modules/KMLFileReadx/KMLFileReadx.h\
+			     ./modules/KMLFileReadx/KMLFileReadx.cpp\
+			     ./modules/KMLMeshWritex/KMLMeshWritex.h\
+			     ./modules/KMLMeshWritex/KMLMeshWritex.cpp\
+			     ./modules/KMLOverlayx/KMLOverlayx.h\
+			     ./modules/KMLOverlayx/KMLOverlayx.cpp\
+			     ./kml/kmlobjects.h\
+			     ./kml/KML_Attribute.cpp\
+			     ./kml/KML_Attribute.h\
+			     ./kml/KML_Comment.cpp\
+			     ./kml/KML_Comment.h\
+			     ./kml/KML_ColorStyle.cpp\
+			     ./kml/KML_ColorStyle.h\
+			     ./kml/KML_Container.cpp\
+			     ./kml/KML_Container.h\
+			     ./kml/KML_Document.cpp\
+			     ./kml/KML_Document.h\
+			     ./kml/KML_Feature.cpp\
+			     ./kml/KML_Feature.h\
+			     ./kml/KML_File.cpp\
+			     ./kml/KML_File.h\
+			     ./kml/KML_Folder.cpp\
+			     ./kml/KML_Folder.h\
+			     ./kml/KML_Geometry.cpp\
+			     ./kml/KML_Geometry.h\
+			     ./kml/KML_GroundOverlay.cpp\
+			     ./kml/KML_GroundOverlay.h\
+			     ./kml/KML_Icon.cpp\
+			     ./kml/KML_Icon.h\
+			     ./kml/KML_LatLonBox.cpp\
+		  	     ./kml/KML_LatLonBox.h\
+			     ./kml/KML_LinearRing.cpp\
+			     ./kml/KML_LinearRing.h\
+			     ./kml/KML_LineString.cpp\
+			     ./kml/KML_LineString.h\
+			     ./kml/KML_LineStyle.cpp\
+			     ./kml/KML_LineStyle.h\
+			     ./kml/KML_MultiGeometry.cpp\
+			     ./kml/KML_MultiGeometry.h\
+			     ./kml/KML_Object.cpp\
+			     ./kml/KML_Object.h\
+			     ./kml/KML_Overlay.cpp\
+			     ./kml/KML_Overlay.h\
+			     ./kml/KML_Point.cpp\
+			     ./kml/KML_Point.h\
+			     ./kml/KML_Placemark.cpp\
+			     ./kml/KML_Placemark.h\
+			     ./kml/KML_Polygon.cpp\
+			     ./kml/KML_Polygon.h\
+			     ./kml/KML_PolyStyle.cpp\
+			     ./kml/KML_PolyStyle.h\
+			     ./kml/KML_Style.cpp\
+			     ./kml/KML_Style.h\
+			     ./kml/KML_StyleSelector.cpp\
+			     ./kml/KML_StyleSelector.h\
+			     ./kml/KML_SubStyle.cpp\
+			     ./kml/KML_SubStyle.h\
+			     ./kml/KML_Unknown.cpp\
+			     ./kml/KML_Unknown.h\
+			     ./kml/KMLFileReadUtils.cpp\
+			     ./kml/KMLFileReadUtils.h
+#}}}
+#Petsc sources  {{{
+petsc_sources= ./toolkits/petsc\
+					./toolkits/petsc/patches\
+					./toolkits/petsc/patches/SolverEnum.h\
+					./toolkits/petsc/patches/petscpatches.h\
+					./toolkits/petsc/patches/VecToMPISerial.cpp\
+					./toolkits/petsc/patches/MatToSerial.cpp\
+					./toolkits/petsc/patches/VecMerge.cpp\
+					./toolkits/petsc/patches/NewVec.cpp\
+					./toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp\
+					./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp\
+					./toolkits/petsc/patches/NewMat.cpp\
+					./toolkits/petsc/patches/VecFree.cpp\
+					./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp\
+					./toolkits/petsc/patches/PetscVectorToDoubleVector.cpp\
+					./toolkits/petsc/patches/VecDuplicatePatch.cpp\
+					./toolkits/petsc/patches/KSPFree.cpp\
+					./toolkits/petsc/patches/MatFree.cpp\
+					./toolkits/petsc/patches/MatMultPatch.cpp\
+					./toolkits/petsc/patches/ISSMToPetscMatrixType.cpp\
+					./toolkits/petsc/patches/ISSMToPetscInsertMode.cpp\
+					./toolkits/petsc/patches/ISSMToPetscNormMode.cpp\
+					./toolkits/petsc/objects/petscobjects.h\
+					./toolkits/petsc/objects/PetscMat.h\
+					./toolkits/petsc/objects/PetscMat.cpp\
+					./toolkits/petsc/objects/PetscVec.h\
+					./toolkits/petsc/objects/PetscVec.cpp\
+					./toolkits/petsc/objects/PetscSolver.cpp\
+					./toolkits/petsc/objects/PetscSolver.h\
+					./toolkits/petsc/petscincludes.h
+
+#}}}
+#Mumps sources  {{{
+mumps_sources=      ./toolkits/mumps\
+					./toolkits/mumps/mumpsincludes.h\
+					./toolkits/mumps/MpiDenseMumpsSolve.cpp
+#}}}
+#Gsl sources  {{{
+gsl_sources=      ./toolkits/gsl\
+					./toolkits/gsl/gslincludes.h\
+					./toolkits/gsl/DenseGslSolve.cpp
+#}}}
+#Mpi sources  {{{
+mpi_sources= ./toolkits/mpi/mpiincludes.h\
+				./toolkits/mpi/patches/mpipatches.h\
+				./toolkits/mpi/patches/DetermineLocalSize.cpp\
+				./toolkits/mpi/patches/DetermineGlobalSize.cpp\
+				./toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp\
+				./toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp\
+				./toolkits/issm/IssmMpiDenseMat.h\
+				./toolkits/issm/IssmMpiVec.h
+#}}}
+#Metis sources  {{{
+metis_sources= ./toolkits/metis/patches/metispatches.h\
+					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
+#}}}
+#Modules sources{{{
+modules_sources= ./shared/Threads/issm_threads.h\
+			./shared/Threads/LaunchThread.cpp\
+			./shared/Threads/PartitionRange.cpp\
+			./shared/Exp/exp.h\
+			./shared/Exp/exp.cpp\
+			./shared/TriMesh/trimesh.h\
+			./shared/TriMesh/AssociateSegmentToElement.cpp\
+			./shared/TriMesh/GridInsideHole.cpp\
+			./shared/TriMesh/OrderSegments.cpp\
+			./shared/TriMesh/SplitMeshForRifts.cpp\
+			./shared/TriMesh/TriMeshUtils.cpp\
+			./modules/Chacox/Chacox.h\
+			./modules/Chacox/Chacox.cpp\
+			./modules/Chacox/input_parse.cpp\
+			./modules/Chacox/chaco_seconds.cpp\
+			./modules/Chacox/user_params.cpp\
+			./modules/TriaSearchx/TriaSearchx.h\
+			./modules/TriaSearchx/TriaSearchx.cpp\
+			./modules/TriMeshx/TriMeshx.h\
+			./modules/TriMeshx/TriMeshx.cpp\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.h\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h\
+			./modules/HoleFillerx/HoleFillerx.cpp\
+			./modules/HoleFillerx/HoleFillerx.h\
+			./modules/EdgeDetectionx/EdgeDetectionx.cpp\
+			./modules/EdgeDetectionx/EdgeDetectionx.h\
+			./modules/AverageFilterx/AverageFilterx.cpp\
+			./modules/AverageFilterx/AverageFilterx.h\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
+			./modules/ContourToMeshx/ContourToMeshx.cpp\
+			./modules/ContourToMeshx/ContourToMeshxt.cpp\
+			./modules/ContourToMeshx/ContourToMeshx.h\
+			./modules/ContourToNodesx/ContourToNodesx.cpp\
+			./modules/ContourToNodesx/ContourToNodesx.h\
+			./modules/Reducevectorgtosx/Reducevectorgtosx.cpp\
+			./modules/Reducevectorgtosx/Reducevectorgtosx.h\
+			./modules/NodeConnectivityx/NodeConnectivityx.cpp\
+			./modules/NodeConnectivityx/NodeConnectivityx.h\
+			./modules/ElementConnectivityx/ElementConnectivityx.cpp\
+			./modules/ElementConnectivityx/ElementConnectivityx.h\
+			./modules/Scotchx/Scotchx.cpp\
+			./modules/Scotchx/Scotchx.h\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
+#}}}
+
+#{{{ Conditional build-up of sources
+#ISSM sources are a combination of core sources and sources related to specific capabilities (which can 
+#be activated by autotools conditionals 
+
+#First the core
+issm_sources  =  $(core_sources)
+
+#Now the optional source
+if DAKOTA
+issm_sources  +=  $(dakota_sources)
+endif
+
+if PETSC
+issm_sources  +=  $(petsc_sources)
+endif
+
+if MUMPS
+issm_sources  +=  $(mumps_sources)
+endif
+
+if GSL
+issm_sources  +=  $(gsl_sources)
+endif
+
+if TRANSIENT
+issm_sources  +=  $(transient_sources)
+endif
+
+if STEADYSTATE
+issm_sources  +=  $(steadystate_sources)
+endif
+
+if PROGNOSTIC
+issm_sources  +=  $(prognostic_sources)
+endif
+
+if THERMAL
+issm_sources  +=  $(thermal_sources)
+endif
+
+if GIA
+issm_sources  +=  $(gia_sources)
+endif
+
+if CONTROL
+issm_sources  +=  $(control_sources)
+endif
+
+if HYDROLOGY
+issm_sources  +=  $(hydrology_sources)
+endif
+
+if DIAGNOSTIC
+issm_sources  +=  $(diagnostic_sources)
+endif
+
+if BALANCED
+issm_sources  +=  $(balanced_sources)
+endif
+
+if SLOPE
+issm_sources  +=  $(slope_sources)
+endif
+
+if GROUNDINGLINE
+issm_sources +=  $(groundingline_sources)
+endif
+
+if RIFTS
+issm_sources +=  $(rifts_sources)
+endif
+
+if ANDROID
+issm_sources +=  $(android_sources)
+endif
+
+if THREED
+issm_sources +=  $(threed_sources)
+endif
+
+if MPI
+issm_sources +=  $(mpi_sources)
+endif
+
+if METIS
+issm_sources +=  $(metis_sources)
+endif
+
+if KRIGING
+issm_sources +=  $(pkriging_sources)
+endif
+#}}}
+#Library flags and sources {{{
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  $(CXXFLAGS) $(CXXOPTFLAGS) 
+
+libISSMCore_a_SOURCES  = $(issm_sources)
+libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMCore_a_FFLAGS = $(AM_FFLAGS)
+
+if WRAPPERS
+libISSMModules_a_SOURCES = $(modules_sources)
+libISSMModules_a_SOURCES += $(bamg_sources)
+if KRIGING
+libISSMModules_a_SOURCES += $(kriging_sources)
+endif
+if KML
+libISSMModules_a_SOURCES += $(kml_sources)
+endif
+libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMModules_a_LIBADD = ./libISSMCore.a
+endif
+
+if VERSION
+AM_LDFLAGS =
+else
+AM_LDFLAGS = -avoid-version
+endif
+#}}}
+#Overload library, to overload any non-standard symbols. {{{
+libISSMOverload_a_SOURCES = ./shared/String/stricmp.c
+libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
+#}}}
+
+#Executable {{{
+if ANDROID
+if ANDROIDEXE
+bin_PROGRAMS = issm 
+else
+bin_PROGRAMS = 
+endif
+else
+bin_PROGRAMS = issm 
+endif
+
+#Standard libraries
+LDADD = ./libISSMCore.a ./libISSMOverload.a
+
+#External packages
+LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
+
+if FORTRAN
+LDADD += $(FLIBS)
+endif
+
+issm_SOURCES = main/issm.cpp
+issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+
+if KRIGING
+bin_PROGRAMS += kriging
+kriging_SOURCES = main/kriging.cpp
+kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+endif
+#}}}
+#Automatic differentiation: append this fold to the end of the src/c/Makefile.am to get this Makefile.am {{{
+if ADIC2 
+lib_LIBRARIES += libAD.a libISSMRose.a
+
+#ADIC2 library, for automatic differentiation 
+#libAD_a_SOURCES = ./mini1.ad.c
+libAD_a_SOURCES = 
+libAD_a_CFLAGS = -fPIC -D_C_ $(COPTFLAGS)
+
+
+#test rose preprocessing 
+%.r2cpp.cpp : %.cpp
+	testTranslator -rose:o $@ -rose:skipfinalCompileStep -DHAVE_CONFIG_H -D_C_ -I. -I../.. $(INCLUDES) $<
+libISSMRose_a_SOURCES = $(libISSMCore_a_SOURCES:.cpp=.r2cpp.cpp)
+libISSMRose_a_CXXFLAGS= -fPIC -D_C_ $(CXXOPTFLAGS)
+
+
+
+#Automatic differentiation rules: 
+%.ad.c: %.c
+	adic2 -mforward  $< --nary
+
+
+
+#Executable
+bin_PROGRAMS +=  issmRose.exe
+issmRose_exe_LDADD = ./libISSMRose.a $(LDADD)
+issmRose_exe_SOURCES = main/issm.cpp
+issmRose_exe_CXXFLAGS= -fPIC $(CXXOPTFLAGS) $(COPTFLAGS) 
+LDADD +=  $(ADIC2LIB) 
+
+endif #}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_MATLAB
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_MATLAB	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/patches/Makefile.am_MATLAB	(revision 18231)
@@ -0,0 +1,267 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@
+
+lib_LIBRARIES = libISSMMatlab.a 
+
+EXEEXT=$(MATLABWRAPPEREXT)
+
+#matlab io{{{
+io_sources = ./include/matlabincludes.h\
+				./io/matlabio.h\
+				./io/MatlabNArrayToNArray.cpp\
+				./io/CheckNumMatlabArguments.cpp\
+				./io/mxGetAssignedField.cpp\
+				./io/WriteMatlabData.cpp\
+				./io/FetchMatlabData.cpp\
+				./io/OptionParse.cpp\
+				./io/MatlabMatrixToMatrix.cpp\
+				./io/MatlabVectorToVector.cpp\
+				./io/MatlabVectorToDoubleVector.cpp\
+				./io/MatlabMatrixToDoubleMatrix.cpp\
+				./io/MatlabMatrixToIssmMat.cpp\
+				./io/MatlabVectorToIssmVec.cpp
+				
+if PETSC
+io_sources += ./io/MatlabMatrixToPetscMat.cpp\
+				./io/MatlabVectorToPetscVec.cpp
+endif
+
+ALLCXXFLAGS = /D_GNU_SOURCE /D_CPP_ /D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+libISSMMatlab_a_SOURCES = $(io_sources)
+libISSMMatlab_a_CXXFLAGS = $(ALLCXXFLAGS)
+
+#}}}
+#Wrappers {{{
+if WRAPPERS
+bin_PROGRAMS =  AverageFilter\
+						 BamgMesher\
+						 BamgConvertMesh\
+						 BamgTriangulate\
+						 ContourToMesh\
+						 ContourToNodes\
+						 EdgeDetection\
+						 ElementConnectivity\
+						 EnumToString\
+						 ExpSimplify\
+						 HoleFiller\
+						 InternalFront\
+						 InterpFromGridToMesh\
+						 InterpFromMeshToMesh2d\
+						 InterpFromMeshToMesh3d\
+						 InterpFromMeshToGrid\
+						 InterpFromMesh2d\
+						 Ll2xy\
+						 NodeConnectivity\
+						 MeshPartition\
+						 MeshProfileIntersection\
+						 PointCloudFindNeighbors\
+						 PropagateFlagsFromConnectivity\
+						 StringToEnum\
+						 TriaSearch\
+						 TriMesh\
+						 TriMeshProcessRifts\
+						 Scotch\
+						 Xy2ll\
+						 Chaco
+
+if KRIGING
+bin_PROGRAMS +=  Kriging
+endif
+if KML
+bin_PROGRAMS +=  KMLFileRead\
+				   KMLMeshWrite\
+				   KMLOverlay\
+				   Exp2Kml\
+				   Kml2Exp\
+				   Shp2Exp\
+				   Shp2Kml
+endif
+endif
+#}}}
+#Flags and libraries {{{
+#if SHAREDLIBS
+#deps = ../../c/libISSMCore ../../c/libISSMModules.la
+#else
+#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+#endif
+#deps +=  $(MATHLIB)
+deps =  $(MATHLIB)
+
+#Triangle library
+AM_CXXFLAGS =  /DTRILIBRARY /DANSI_DECLARATORS /DNO_TIMER
+
+#Matlab part
+AM_LDFLAGS = 
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+deps += ./libISSMMatlab.a
+AM_LDFLAGS += --no-warnings 
+
+AM_CXXFLAGS +=  /D_HAVE_MATLAB_MODULES_  /D_GNU_SOURCE 
+
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a  
+if ADOLC
+deps += $(ADOLCLIB)
+endif
+
+#MEXLIB needs to be the last (undefined references on larsen)
+deps += ${MEXLIB}
+
+#Optimization flags:
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+#}}}
+#Bin sources {{{
+AverageFilter_SOURCES = ../AverageFilter/AverageFilter.cpp\
+									../AverageFilter/AverageFilter.h
+AverageFilter_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgMesher_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgConvertMesh_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgTriangulate_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
+									  ../BamgTriangulate/BamgTriangulate.h
+BamgTriangulate_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Chaco_SOURCES = ../Chaco/Chaco.cpp\
+						 ../Chaco/Chaco.h
+Chaco_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB) $(GSLLIB)
+
+ContourToMesh_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									../ContourToMesh/ContourToMesh.h
+ContourToMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+ContourToNodes_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ElementConnectivity_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EnumToString_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+StringToEnum_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+HoleFiller_SOURCES = ../HoleFiller/HoleFiller.cpp\
+								../HoleFiller/HoleFiller.h
+HoleFiller_LDADD = ${deps} $(MPILIB) $(PETSCLIB)  $(GSLLIB)
+
+InternalFront_SOURCES = ../InternalFront/InternalFront.cpp\
+									../InternalFront/InternalFront.h
+InternalFront_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromGridToMesh_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh3d_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+InterpFromMeshToMesh3d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMeshToGrid_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
+InterpFromMeshToGrid_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMesh2d_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
+										../InterpFromMesh2d/InterpFromMesh2d.h
+InterpFromMesh2d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+KMLFileRead_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
+								 ../KMLFileRead/KMLFileRead.h
+KMLFileRead_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLMeshWrite_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
+								  ../KMLMeshWrite/KMLMeshWrite.h
+KMLMeshWrite_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLOverlay_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
+								../KMLOverlay/KMLOverlay.h
+KMLOverlay_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Xy2ll_SOURCES = ../Xy2ll/Xy2ll.cpp\
+						 ../Xy2ll/Xy2ll.h
+Xy2ll_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Ll2xy_SOURCES = ../Ll2xy/Ll2xy.cpp\
+						 ../Ll2xy/Ll2xy.h
+Ll2xy_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EdgeDetection_SOURCES = ../EdgeDetection/EdgeDetection.cpp\
+							../EdgeDetection/EdgeDetection.h
+EdgeDetection_LDADD= ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ExpSimplify_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
+							../ExpSimplify/ExpSimplify.h
+ExpSimplify_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Exp2Kml_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
+							../Exp2Kml/Exp2Kml.h
+Exp2Kml_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kml2Exp_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
+							../Kml2Exp/Kml2Exp.h
+Kml2Exp_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kriging_SOURCES = ../Kriging/Kriging.cpp\
+							../Kriging/Kriging.h
+Kriging_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+MeshPartition_SOURCES = ../MeshPartition/MeshPartition.cpp\
+									../MeshPartition/MeshPartition.h
+MeshPartition_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB)
+
+MeshProfileIntersection_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+												 ../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+NodeConnectivity_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+PointCloudFindNeighbors_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
+PointCloudFindNeighbors_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+PropagateFlagsFromConnectivity_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
+PropagateFlagsFromConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Scotch_SOURCES = ../Scotch/Scotch.cpp\
+						  ../Scotch/Scotch.h
+Scotch_LDADD = ${deps} $(SCOTCHLIB) $(MPILIB)
+
+Shp2Exp_SOURCES = ../Shp2Exp/Shp2Exp.cpp\
+							../Shp2Exp/Shp2Exp.h
+Shp2Exp_LDADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Shp2Kml_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
+							../Shp2Kml/Shp2Kml.h
+Shp2Kml_LDADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriaSearch_SOURCES = ../TriaSearch/TriaSearch.cpp\
+								../TriaSearch/TriaSearch.h
+TriaSearch_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
+
+TriMeshProcessRifts_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/patches/configure.ac
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/patches/configure.ac	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/patches/configure.ac	(revision 18231)
@@ -0,0 +1,44 @@
+# Process this file with autoconf to produce a configure script.
+
+#AUTOCONF
+AC_INIT([ISSM],[4.2.5],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
+AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
+m4_include([m4/issm_options.m4])
+AC_CANONICAL_TARGET                       #Determine the system type
+
+#Compilers
+AC_PROG_CC([icc cccl cl icl gcc])
+AC_PROG_CPP
+AC_PROG_CXX([icpc cccl cl icl g++])
+AC_PROG_F77([ifort g77 gfortran])
+
+#Libraries and linking
+AC_F77_LIBRARY_LDFLAGS
+AC_PATH_XTRA      #figure out X library and include paths
+AC_PROG_RANLIB
+
+#AUTOMAKE
+#Initialize automake and declare foreign so that we don't need a ChangeLog, INSTALL, etc
+AM_INIT_AUTOMAKE([foreign])
+AC_CONFIG_HEADERS([./config.h])   #Config file must be config.h
+AM_SILENT_RULES([yes])           #Do not show compilation command by default
+AM_PROG_CC_C_O
+AM_PROG_AR
+
+#Libtool
+#LT_INIT
+
+#Run issm_options.m4
+ISSM_OPTIONS
+
+#List all Makefiles
+AC_CONFIG_FILES([Makefile
+			src/Makefile
+			src/c/Makefile 
+			src/wrappers/Makefile
+			src/wrappers/matlab/Makefile
+			src/m/Makefile])
+
+#End of configure.ac
+AC_OUTPUT
Index: /issm/branches/trunk-jpl-ad2-integrated/patches/issm_options.m4
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/patches/issm_options.m4	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/patches/issm_options.m4	(revision 18231)
@@ -0,0 +1,1621 @@
+dnl ISSM Options
+
+AC_DEFUN([ISSM_OPTIONS],[
+
+	dnl ISSM's internal options
+	dnl Debugging {{{
+	AC_ARG_ENABLE([debugging],                                        dnl feature
+		AS_HELP_STRING([--enable-debugging],[turn debug support on]),  dnl help string
+		[enable_debugging=$enableval],                                 dnl action if given
+		[enable_debugging=no])                                         dnl action if not given
+	if test "x$enable_debugging" = xyes; then
+		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
+	fi
+
+	dnl }}}
+    dnl Shared build {{{
+    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
+        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
+        [enable_sharedlibs=$enableval],                                        dnl action if given
+        [enable_sharedlibs=no])                                                dnl action if not given
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+    dnl }}}
+    dnl Version{{{
+    AC_ARG_ENABLE([version],                                                dnl feature
+        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
+        [enable_version=$enableval],                                        dnl action if given
+        [enable_version=no])                                                dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
+    dnl }}}
+	dnl Wrappers build {{{
+	AC_ARG_WITH([wrappers],
+		AS_HELP_STRING([--with-wrappers = value],[wrappers compilation. ]),
+		[WRAPPERS_VALUE=$withval],[WRAPPERS_VALUE="yes"])
+	AC_MSG_CHECKING(for wrappers compilation)
+	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
+	AC_MSG_RESULT($WRAPPERS_VALUE) 
+	dnl }}}
+	dnl Extensions{{{
+	ISSMEXT=".exe"
+	AC_SUBST([ISSMEXT])
+	dnl }}}
+
+	dnl ISSM's externalpackages
+	dnl vendor{{{
+	AC_ARG_WITH([vendor],
+	  AS_HELP_STRING([--with-vendor = VENDOR], [vendor name, ex: intel]),
+	  [VENDOR=$withval],[VENDOR=""]) 
+	AC_MSG_CHECKING(for vendor compilers)
+	if test -n "$VENDOR"; then
+
+		if  test $VENDOR = intel-win32; then
+			export CC=icl
+			export CXX=icl
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_"
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
+		elif  test $VENDOR = intel-win7-32; then
+			export CC=cccl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export RANLIB=true
+			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"
+		elif  test $VENDOR = intel-win7-64; then
+			export CC=cccl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export RANLIB=true
+			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"
+		elif test $VENDOR = intel-linux; then
+			export CC=icc
+			export CXX=icpc
+			export CFLAGS=" -D_INTEL_LINUX_"
+			export CXXFLAGS=" -D_INTEL_LINUX_"
+		elif test $VENDOR = intel-discover; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+		elif test $VENDOR = intel-pleiades; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+        else
+		AC_MSG_ERROR([unknow compiler vendor!])
+		fi
+	fi
+	AC_SUBST([OSLIBS]) 
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl matlab{{{
+
+	dnl 1. See if matlab has been provided
+	AC_ARG_WITH([matlab-dir],
+		AS_HELP_STRING([--with-matlab-dir=DIR], [matlab root directory. necessary for serial build.]),
+		[MATLAB_ROOT=$withval],[MATLAB_ROOT=""]) 
+
+	AC_MSG_CHECKING([whether matlab is enabled])
+	if test -d "$MATLAB_ROOT"; then
+		HAVE_MATLAB=yes
+	else
+		HAVE_MATLAB=no
+	fi
+	if test x$HAVE_MATLAB = xyes; then
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with Matlab in ISSM src])
+	fi
+	AC_MSG_RESULT($HAVE_MATLAB)
+	AM_CONDITIONAL([MATLAB], [test x$HAVE_MATLAB = xyes])
+
+	dnl 2. Get Matlab libraries
+	if test x$HAVE_MATLAB = xyes; then
+
+		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
+  		MATLABINCL="-I$MATLAB_ROOT/extern/include"
+
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
+      dnl OS-dependent variables and checks
+  		case "${host_os}" in
+  			*linux*)
+  				if test "${host_cpu}" = "x86_64";
+  				then
+  					MEXLIB=-L"$MATLAB_ROOT/bin/glnxa64/ -lmex"
+  					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnxa64/mexFunction.map";
+  				else
+  					MEXLIB=-L"$MATLAB_ROOT/bin/glnx86/ -lmex"
+  					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnx86/mexFunction.map";
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+  				MEXEXT=".$MEXEXT"
+  			;;
+  			*darwin*)
+  				dnl mex -v gives all the flags for compilation of mex files
+  				dnl if matlab version is 7.9 or more, we must use mexmaci64 (64 bits)
+  				MEXLINK="-O -Wl,-flat_namespace -undefined suppress -arch i386 -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci/mexFunction.map"
+  				MEXLIB=" -L$MATLAB_ROOT/bin/maci/ -lmx -lmex -lmat -lstdc++ -largeArrayDims"
+  				if test $MATLAB_MAJOR -ge 7; then 
+  					 if test $MATLAB_MINOR -ge 9; then 
+  						  MEXLINK="-O -Wl,-flat_namespace -undefined suppress -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci64/mexFunction.map"
+  							 MEXLIB=" -L$MATLAB_ROOT/bin/maci64/ -lmx -lmex -lmat -lstdc++"
+  					 fi
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+  				MEXEXT=".$MEXEXT"
+  			;;
+  			*cygwin*) 
+  				if  test $VENDOR = intel-win7-32; then
+					MATLABLIB="$MATLAB_ROOT/extern/lib/win32/microsoft"
+  					MEXLIB="/link /DLL /export:mexFunction -L$MATLABLIB libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib" 
+  				elif  test $VENDOR = intel-win7-64; then
+					MATLABLIB="$MATLAB_ROOT/extern/lib/win64/microsoft"
+  					MEXLIB="/link /DLL /export:mexFunction -L$MATLABLIB libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib " 
+  				fi
+  				MEXEXT=".$MEXEXT"
+  			;;
+      esac
+	   AC_MSG_RESULT(done)
+
+		AC_SUBST([MATLABINCL])
+		AC_SUBST([MEX])
+		MATLABWRAPPEREXT=$MEXEXT
+		AC_SUBST([MATLABWRAPPEREXT])
+	    AC_SUBST([MEXLIB]) 
+		AC_SUBST([MEXLINK])
+	fi
+	dnl }}}
+	dnl triangle {{{
+	AC_ARG_WITH([triangle-dir],
+			  AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory. necessary for serial build]),
+			 [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT=""]) 
+	AC_MSG_CHECKING(for triangle headers and libraries)
+
+	if test -d "$TRIANGLE_ROOT"; then
+
+		dnl defaults
+		HAVE_TRIANGLE=yes
+		TRIANGLEINCL=-I$TRIANGLE_ROOT/
+
+		case "${host_os}" in
+				*cygwin*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.lib
+				;;
+				*linux*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+				;;
+				*darwin*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+				;;
+			esac
+
+		AC_DEFINE([_HAVE_TRIANGLE_],[1],[with Triangle in ISSM src])
+		AC_SUBST([TRIANGLEINCL])
+		AC_SUBST([TRIANGLELIB])
+
+	else
+		HAVE_TRIANGLE=no
+	fi
+	AC_MSG_RESULT($HAVE_TRIANGLE)
+	dnl }}}
+	dnl dakota{{{
+	AC_ARG_WITH([dakota-dir],
+	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory. necessary for serial build]),
+	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT=""]) 
+	AC_MSG_CHECKING(for dakota)
+	
+	if test -d "$DAKOTA_ROOT"; then
+
+		dnl defaults
+		HAVE_DAKOTA=yes
+		AC_MSG_RESULT($HAVE_DAKOTA)
+		DAKOTAINCL=-I$DAKOTA_ROOT/include
+		AC_MSG_CHECKING(for dakota version)
+		DAKOTA_VERSION=`cat $DAKOTA_ROOT/include/dakota_config.h | grep "#define PACKAGE_VERSION" | sed 's/#define PACKAGE_VERSION//' | sed 's/ //g' | sed -e 's/\"//g' `
+		AC_MSG_RESULT($DAKOTA_VERSION)
+		AC_DEFINE_UNQUOTED([DAKOTA_VERSION],"$DAKOTA_VERSION",[Dakota version number])
+		case "${host_os}" in
+			*cygwin*)
+				if      test x$DAKOTA_VERSION = x4.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*linux*)
+				if      test x$DAKOTA_VERSION = x4.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system -ldl"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*darwin*)
+				if      test x$DAKOTA_VERSION = x4.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver" 
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.2; then
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
+		AC_SUBST([DAKOTAINCL])
+		AC_SUBST([DAKOTALIB])
+
+	else
+		HAVE_DAKOTA=no
+		AC_MSG_RESULT($HAVE_DAKOTA)
+	fi
+	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
+	dnl }}}
+	dnl boost{{{
+	AC_ARG_WITH([boost-dir],
+	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
+	  [BOOST_ROOT=$withval],[BOOST_ROOT=""]) 
+	AC_MSG_CHECKING(for boost)
+	
+	if test -d "$BOOST_ROOT"; then
+		dnl defaults
+		HAVE_BOOST=yes
+		BOOSTINCL=-I$BOOST_ROOT/include
+		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
+
+		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
+		AC_SUBST([BOOSTINCL])
+		AC_SUBST([BOOSTLIB])
+	else
+		HAVE_BOOST=no
+	fi
+	AM_CONDITIONAL([BOOST], [test x$HAVE_BOOST = xyes])
+	AC_MSG_RESULT($HAVE_BOOST)
+	dnl }}}
+	dnl python{{{
+	AC_ARG_WITH([python-dir],
+	  AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
+	  [PYTHON_ROOT=$withval],[PYTHON_ROOT=""]) 
+
+	AC_MSG_CHECKING(for python)
+	if test -d "$PYTHON_ROOT"; then
+		HAVE_PYTHON="yes"
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
+	else
+		HAVE_PYTHON=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON)
+
+	dnl get python version
+	if test x$HAVE_PYTHON = xyes; then
+		AC_MSG_CHECKING(for python version)
+		dnl Query Python for its version number.  Getting [:3] seems to be
+		dnl the best way to do this; it's what "site.py" does in the standard
+		dnl library.
+		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
+		AC_MSG_RESULT($PYTHON_VERSION)
+
+		dnl recover major: 
+		PYTHON_MAJOR=${PYTHON_VERSION%.*}
+		if test x$PYTHON_MAJOR = x3; then
+			dnl are we running python 3?
+			HAVE_PYTHON3="yes"
+		else
+			HAVE_PYTHON3="no"
+		fi
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+
+		PYTHONINCL=-I$PYTHON_ROOT/include
+		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHON_VERSION"
+		PYTHONEXT=.so
+
+		case "${host_os}" in
+			*cygwin*)
+			PYTHONLINK="-shared"
+			;;
+			*linux*)
+			PYTHONLINK="-shared"
+			;;
+			*darwin*)
+			PYTHONLINK="-dynamiclib"
+			;;
+		esac
+
+		AC_SUBST([PYTHONINCL])
+		AC_SUBST([PYTHONLIB])
+		PYTHONWRAPPEREXT=$PYTHONEXT
+		AC_SUBST([PYTHONWRAPPEREXT])
+		AC_SUBST([PYTHONLINK])
+	fi
+	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
+	dnl }}}
+	dnl python-numpy{{{
+	AC_ARG_WITH([python-numpy-dir],
+	  AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
+	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT=""]) 
+	AC_MSG_CHECKING(for python-numpy)
+	
+	if test -d "$PYTHON_NUMPY_ROOT"; then
+		dnl defaults
+		HAVE_PYTHON_NUMPY=yes
+		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
+
+		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
+		AC_SUBST([PYTHON_NUMPYINCL])
+	else
+		HAVE_PYTHON_NUMPY=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+	dnl }}}
+	dnl chaco{{{
+	AC_ARG_WITH([chaco-dir],
+	  AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
+	  [CHACO_ROOT=$withval],[CHACO_ROOT=""]) 
+	AC_MSG_CHECKING(for chaco)
+	
+	if test -d "$CHACO_ROOT"; then
+
+		dnl defaults
+		HAVE_CHACO=yes
+		CHACOINCL=-I$CHACO_ROOT/include
+		CHACOLIB="-L$CHACO_ROOT/lib -lchacominusblas"
+
+		AC_DEFINE([_HAVE_CHACO_],[1],[with Chaco in ISSM src])
+		AC_SUBST([CHACOINCL])
+		AC_SUBST([CHACOLIB])
+
+	else
+		HAVE_CHACO=no
+	fi
+	AC_MSG_RESULT($HAVE_CHACO)
+	dnl }}}
+	dnl scotch{{{
+	AC_ARG_WITH([scotch-dir],
+	  AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
+	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT=""]) 
+	AC_MSG_CHECKING(for scotch)
+	
+	if test -d "$SCOTCH_ROOT"; then
+
+		dnl defaults
+		HAVE_SCOTCH=yes
+		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
+		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
+
+		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
+		AC_SUBST([SCOTCHINCL])
+		AC_SUBST([SCOTCHLIB])
+
+	else
+		HAVE_SCOTCH=no
+	fi
+	AC_MSG_RESULT($HAVE_SCOTCH)
+	dnl }}}
+	dnl adolc{{{
+	AC_ARG_WITH([adolc-dir],
+		AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
+		[ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
+	AC_MSG_CHECKING(for adolc)
+
+	if test "x$ADOLC_ROOT" = "xno"; then
+		HAVE_ADOLC=no
+	else
+		if test -d "$ADOLC_ROOT"; then
+
+			dnl defaults
+			HAVE_ADOLC=yes
+			ADOLCINCL="-I$ADOLC_ROOT/include"
+			ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc"
+
+			AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
+			AC_SUBST([ADOLCINCL])
+			AC_SUBST([ADOLCLIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
+	AC_MSG_RESULT($HAVE_ADOLC)
+	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
+	dnl adic2{{{
+	AC_ARG_WITH([adic2-dir],
+	  AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
+	  [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
+	AC_MSG_CHECKING(for adic2)
+
+	if test "x$ADIC2_ROOT" = "xno"; then
+		HAVE_ADIC2=no
+	else
+		if test -d "$ADIC2_ROOT"; then
+
+			dnl defaults
+			HAVE_ADIC2=yes
+			ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
+			ADIC2LIB=""
+
+			AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
+			AC_SUBST([ADIC2INCL])
+			AC_SUBST([ADIC2LIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADIC2], [test x$HAVE_ADIC2 = xyes])
+	AC_MSG_RESULT($HAVE_ADIC2)
+	dnl }}}
+	dnl gsl{{{
+	AC_ARG_WITH([gsl-dir],
+	  AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
+	  [GSL_ROOT=$withval],[GSL_ROOT=""]) 
+	AC_MSG_CHECKING(for gsl)
+	
+	if test -d "$GSL_ROOT"; then
+
+		dnl defaults
+		HAVE_GSL=yes
+		GSLINCL="-I$GSL_ROOT/include"
+		GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+
+		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
+		AC_SUBST([GSLINCL])
+		AC_SUBST([GSLLIB])
+
+	else
+		HAVE_GSL=no
+	fi
+	AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
+	AC_MSG_RESULT($HAVE_GSL)
+	dnl }}}
+	dnl rose{{{
+	AC_ARG_WITH([rose-dir],
+	  AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
+	  [ROSE_ROOT=$withval],[ROSE_ROOT=""]) 
+	AC_MSG_CHECKING(for rose)
+	
+	if test -d "$ROSE_ROOT"; then
+
+		dnl defaults
+		HAVE_ROSE=yes
+		ROSEINCL="-I$ROSE_ROOT/include"
+		ROSELIB=""
+
+		AC_DEFINE([_HAVE_ROSE_],[1],[with rose in ISSM src])
+		AC_SUBST([ROSEINCL])
+		AC_SUBST([ROSELIB])
+
+	else
+		HAVE_ROSE=no
+	fi
+	AM_CONDITIONAL([ROSE], [test x$HAVE_ROSE = xyes])
+	AC_MSG_RESULT($HAVE_ROSE)
+	dnl }}}
+	dnl mpi{{{
+	AC_MSG_CHECKING(for mpi)
+	AC_ARG_WITH([mpi-lib],
+		AS_HELP_STRING([--with-mpi-lib = options],[mpi options, for ex: "-L$MPIROOT -lmpich]),
+		[MPILIB=$withval],[MPILIB=""])
+	
+	AC_ARG_WITH([mpi-include],
+	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
+	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
+	
+	if test -z "$MPILIB" ; then
+		HAVE_MPI=no
+	else
+		if test -z "$MPI_INCLUDE" ; then
+			HAVE_MPI=no
+		else
+			HAVE_MPI=yes
+			MPIINCL=-I"$MPI_INCLUDE"
+			AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+			AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
+			AC_SUBST([MPIINCL])
+			AC_SUBST([MPILIB])
+		fi
+	fi
+	AM_CONDITIONAL([MPI], [test x$HAVE_MPI = xyes])
+	AC_MSG_RESULT($HAVE_MPI)
+	dnl }}}
+	dnl petsc{{{
+	AC_ARG_WITH([petsc-dir],
+	  AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
+	  [PETSC_ROOT=$withval],[PETSC_ROOT=""])
+		
+	if test -d "$PETSC_ROOT"; then
+		AC_MSG_CHECKING(for petsc version)
+		PETSC_MAJOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MAJOR" | sed 's/#define PETSC_VERSION_MAJOR//' | sed 's/ //g'`
+		PETSC_MINOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MINOR" | sed 's/#define PETSC_VERSION_MINOR//' | sed 's/ //g'`
+		AC_DEFINE_UNQUOTED([_PETSC_MAJOR_],$PETSC_MAJOR,[PETSc version major])
+		AC_DEFINE_UNQUOTED([_PETSC_MINOR_],$PETSC_MINOR,[PETSc version minor])
+		AC_MSG_RESULT($PETSC_MAJOR.$PETSC_MINOR)
+
+		PETSC_VERSION_DATE_HG=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_DATE_HG" | sed 's/#define PETSC_VERSION_DATE_HG//' | sed 's/ //g' | sed -e 's/\"//g' `
+		PETSC_RELEASE=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_RELEASE" | sed 's/#define PETSC_VERSION_RELEASE//' | sed 's/ //g'`
+
+		AC_MSG_CHECKING(whether petsc is the development version)
+		dnl if test x$PETSC_VERSION_DATE_HG = xunknown; then
+		if test "$PETSC_RELEASE" = "0"; then
+		   AC_DEFINE([_HAVE_PETSCDEV_],[1],[with PETSc-dev])
+			AC_MSG_RESULT(yes)
+		else
+			AC_MSG_RESULT(no)
+		fi
+	fi
+	
+	AC_ARG_WITH([petsc-arch],
+	  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch , necessary for parallel build]),
+	  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+	AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
+	
+	dnl To ge PETSc's libraries:
+	dnl cd externalpackages/petsc/src
+	dnl make getlinklibs
+	if test -d "$PETSC_ROOT"; then
+
+	 PETSCINCL=" -I$PETSC_ROOT/include"
+	 dnl Add other location (maybe not needed anymore)
+	 if test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+	  PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+	 fi
+	 if test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+	  PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+	 fi
+	
+	 case "${host_os}" in
+			*cygwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib libpetscksp.lib libpetscdm.lib libpetscmat.lib libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib libpetsc.lib"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" libmetis.lib"; fi
+			fi
+			;;
+			*linux*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+			*darwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
+		AC_SUBST([PETSCINCL])
+		AC_SUBST([PETSCLIB])
+		HAVE_PETSC=yes
+	else
+		HAVE_PETSC=no
+	fi
+	
+	AM_CONDITIONAL([PETSC], [test x$HAVE_PETSC = xyes])
+	AC_MSG_RESULT($HAVE_PETSC)
+	dnl }}}
+	dnl metis{{{
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
+
+		dnl in petsc >=3.3, metis is provided
+		HAVE_METIS="yes"
+		AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+	else
+		AC_ARG_WITH([metis-dir],
+		  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
+		  [METIS_ROOT=$withval],[METIS_ROOT=""])
+
+		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+
+		if test -d "$METIS_ROOT"; then
+
+			dnl first figure out version of metis: does the VERSION file exist?
+			if test -e "$METIS_ROOT/VERSION"; then
+				METIS_VERSION=4
+			else
+				METIS_VERSION=5
+			fi
+
+			dnl defaults
+			HAVE_METIS=yes
+
+			if test "$METIS_VERSION" = "4" ; then
+					
+				METISINCL=-I"$METIS_ROOT/Lib" 
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+				esac
+
+					AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+			fi
+			if test "$METIS_VERSION" = "5" ; then
+		
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+				esac
+
+				METISINCL=-I"$METIS_ROOT/include" 
+				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+			fi
+
+			AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+			AC_SUBST([METISINCL])
+			AC_SUBST([METISLIB])
+		else
+			HAVE_METIS=no
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+	fi
+	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+	dnl }}}
+	dnl tao{{{
+	AC_ARG_WITH([tao-dir],
+		AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
+		[TAO_ROOT=$withval],[TAO_ROOT=""]) 
+	AC_MSG_CHECKING(for tao)
+
+	if test -d "$TAO_ROOT"; then
+
+	  HAVE_TAO=yes
+	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
+	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
+
+	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+	  AC_SUBST([TAOINCL])
+	  AC_SUBST([TAOLIB])
+	else
+		HAVE_TAO=no
+	fi
+	AC_MSG_RESULT($HAVE_TAO)
+	dnl }}}
+	dnl slepc{{{
+	AC_ARG_WITH([slepc-dir],
+	  AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
+	  [SLEPC_ROOT=$withval],[SLEPC_ROOT=""])
+			  
+	AC_MSG_CHECKING(for slepc headers and libraries in $SLEPC_ROOT)
+	if test -d "$SLEPC_ROOT"; then
+		HAVE_SLEPC=yes
+		SLEPCINCL=-I"$SLEPC_ROOT/include"
+		SLEPCLIB=-L"$SLEPC_ROOT/lib/ -lslepc"
+
+		AC_DEFINE([_HAVE_SLEPC_],[1],[with Slepc in ISSM src])
+		AC_SUBST([SLEPCINCL])
+		AC_SUBST([SLEPCLIB])
+	else
+		HAVE_SLEPC=no
+	fi
+	AC_MSG_RESULT($HAVE_SLEPC)
+	dnl }}}
+	dnl shapelib{{{
+	AC_ARG_WITH([shapelib-dir],
+	  AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
+	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT=""])
+			  
+	AC_MSG_CHECKING(for shapelib headers and libraries in $SHAPELIB_ROOT)
+	if test -d "$SHAPELIB_ROOT"; then
+
+		dnl defaults
+		HAVE_SHAPELIB=yes
+		SHAPELIBINCL=-I"$SHAPELIB_ROOT/include"
+		SHAPELIBLIB=-L"$SHAPELIB_ROOT/lib/ -lshape"
+
+		AC_DEFINE([_HAVE_SHAPELIB_],[1],[with Shapelib in ISSM src])
+		AC_SUBST([SHAPELIBINCL])
+		AC_SUBST([SHAPELIBLIB])
+	else
+		HAVE_SHAPELIB=no
+	fi
+	AC_MSG_RESULT($HAVE_SHAPELIB)
+	dnl }}}
+	dnl scalapack{{{
+	AC_ARG_WITH([scalapack-dir],
+	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
+	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for scalapack headers and libraries in $SCALAPACK_ROOT)
+	if test -d "$SCALAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_SCALAPACK=yes
+		if test x$VENDOR = xintel-discover; then
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
+		else
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+		fi
+
+		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
+		AC_SUBST([SCALAPACKLIB])
+	else
+		HAVE_SCALAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_SCALAPACK)
+	dnl }}}
+	dnl blas{{{
+	AC_ARG_WITH([blas-lapack-dir],
+	  AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
+	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blas and lapack headers and libraries in $BLASLAPACK_ROOT)
+	if test -d "$BLASLAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_BLASLAPACK=yes
+		BLASLAPACKINCL=""
+	
+		if test x$VENDOR = xintel-discover; then
+		 BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
+		else
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			BLASLAPACKLIB="-L$BLASLAPACK_ROOT libf2cblas.lib  libf2clapack.lib"
+			;;
+			*linux*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			;;
+			*darwin*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			;;
+		esac
+		fi
+
+		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
+		AC_SUBST([BLASLAPACKLIB])
+		AC_SUBST([BLASLAPACKINCL])
+	else
+		HAVE_BLASLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	dnl }}}
+	dnl mkl{{{
+	AC_ARG_WITH([mkl-dir],
+	  AS_HELP_STRING([--with-mkl-dir=DIR],[mkl root directory]),
+	  [MKL_ROOT=$withval],[MKL_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mkl headers and libraries in $MKL_ROOT)
+	if test -d "$MKL_ROOT"; then
+
+		dnl defaults
+		HAVE_MKL=yes
+		MKLINCL=""
+		MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64   -lmkl_blacs_sgimpt_ilp64 -lguide  -lpthread"
+		AC_DEFINE([_HAVE_MKL_],[1],[with mkl in ISSM src])
+		AC_SUBST([MKLLIB])
+		AC_SUBST([MKLINCL])
+	else
+		HAVE_MKL=no
+	fi
+	AC_MSG_RESULT($HAVE_MKL)
+	dnl }}}
+	dnl plapack{{{
+	AC_MSG_CHECKING(for plapack)
+	
+	AC_ARG_WITH([plapack-lib],
+	  AS_HELP_STRING([--with-plapack-lib = lib],[plapack library]),
+	  [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
+	
+	AC_ARG_WITH([plapack-include],
+			  AS_HELP_STRING([--with-plapack-include = include],
+							 [plapack include ]),
+			  [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
+	  
+	if test -n "$PLAPACK_LIB"; then
+		if test -n "$PLAPACK_INCLUDE"; then
+		
+			dnl defaults
+			HAVE_PLAPACK=yes
+			PLAPACKINCL="$PLAPACK_INCLUDE"
+			PLAPACKLIB="$PLAPACK_LIB"
+
+			AC_DEFINE([_HAVE_PLAPACK_],[1],[with Plapack in ISSM src])
+			AC_SUBST([PLAPACKINCL])
+			AC_SUBST([PLAPACKLIB])
+		else
+			HAVE_PLAPACK=no
+		fi
+	else
+		HAVE_PLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_PLAPACK)
+	dnl }}}
+	dnl mumps{{{
+	AC_ARG_WITH([mumps-dir],
+	  AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
+	  [MUMPS_ROOT=$withval],[MUMPS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mumps headers and libraries in $MUMPS_ROOT)
+	if test -d "$MUMPS_ROOT"; then
+
+		dnl defaults
+		HAVE_MUMPS=yes
+		MUMPSINCL=-I"$MUMPS_ROOT/include"
+		if test "$PETSC_MAJOR" = "2" ; then
+		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+		else
+		dnl MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps"
+		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis"
+		fi
+
+		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
+		AC_SUBST([MUMPSINCL])
+		AC_SUBST([MUMPSLIB])
+	else
+		HAVE_MUMPS=no
+	fi
+	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
+	AC_MSG_RESULT($HAVE_MUMPS)
+	dnl }}}
+	dnl blacs{{{
+	AC_ARG_WITH([blacs-dir],
+		AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
+			  [BLACS_ROOT=$withval],[BLACS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blacs headers and libraries in $BLACS_ROOT)
+	if test -d "$BLACS_ROOT"; then
+
+		dnl defaults
+		HAVE_BLACS=yes
+		BLACSINCL=""
+		if test x$VENDOR = xintel-discover; then
+		 BLACSLIB=-L"$BLACS_ROOT/ -lmkl_blacs_intelmpi_lp64"
+		else
+		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+		fi
+        
+		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
+		AC_SUBST([BLACSINCL])
+		AC_SUBST([BLACSLIB])
+	else
+		HAVE_BLACS=no
+	fi
+	AC_MSG_RESULT($HAVE_BLACS)
+	dnl }}}
+	dnl hypre{{{
+	AC_ARG_WITH([hypre-dir],
+	  AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
+			  [HYPRE_ROOT=$withval],[HYPRE_ROOT=""])
+			  
+	AC_MSG_CHECKING(for hypre headers and libraries in $HYPRE_ROOT)
+	if test -d "$HYPRE_ROOT"; then
+
+		dnl defaults
+		HAVE_HYPRE=yes
+		HYPREINCL=""
+		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
+        
+		AC_DEFINE([_HAVE_HYPRE_],[1],[with Blacs in ISSM src])
+		AC_SUBST([HYPREINCL])
+		AC_SUBST([HYPRELIB])
+	else
+		HAVE_HYPRE=no
+	fi
+	AC_MSG_RESULT($HAVE_HYPRE)
+	dnl }}}
+	dnl prometheus{{{
+		AC_ARG_WITH([prometheus-dir],
+					AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
+					[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT=""])
+
+		  AC_MSG_CHECKING(for prometheus headers and libraries in $PROMETHEUS_ROOT)
+		  if test -d "$PROMETHEUS_ROOT"; then
+
+			dnl defaults
+			  HAVE_PROMETHEUS=yes
+			  PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
+			  PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
+
+			  AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
+			  AC_SUBST([PROMETHEUSINCL])
+			  AC_SUBST([PROMETHEUSLIB])
+		  else
+				HAVE_PROMETHEUS=no
+			fi
+			AC_MSG_RESULT($HAVE_PROMETHEUS)
+		dnl }}}
+dnl spai{{{
+	AC_ARG_WITH([spai-dir],
+				AS_HELP_STRING([--with-spai-dir=DIR],[spai root directory]),
+				[SPAI_ROOT=$withval],[SPAI_ROOT=""])
+
+	  AC_MSG_CHECKING(for spai headers and libraries in $SPAI_ROOT)
+	  if test -d "$SPAI_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPAI=yes
+		  SPAIINCL=-I"$SPAI_ROOT/include"
+		  SPAILIB=-L"$SPAI_ROOT/lib -lspai"
+
+		  AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
+		  AC_SUBST([SPAIINCL])
+		  AC_SUBST([SPAILIB])
+	  else
+		HAVE_SPAI=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPAI)
+		  dnl }}}
+dnl superlu{{{ 
+	AC_ARG_WITH([superlu-dir],
+				AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
+				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT=""])
+
+	  AC_MSG_CHECKING(for superlu headers and libraries in $SUPERLU_ROOT)
+	  if test -d "$SUPERLU_ROOT"; then
+
+		dnl defaults
+		  HAVE_SUPERLU=yes
+		  SUPERLUINCL=-I"$SUPERLU_ROOT/include"
+		  SUPERLULIB=-L"$SUPERLU_ROOT/lib -lsuperlu_4.3"
+
+		  AC_DEFINE([_HAVE_SUPERLU_],[1],[with Superlu in ISSM src])
+		  AC_SUBST([SUPERLUINCL])
+		  AC_SUBST([SUPERLULIB])
+	  else
+		HAVE_SUPERLU=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SUPERLU)
+		  dnl }}}
+dnl spooles{{{ 
+	AC_ARG_WITH([spooles-dir],
+				AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
+				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT=""])
+
+	  AC_MSG_CHECKING(for spooles headers and libraries in $SPOOLES_ROOT)
+	  if test -d "$SPOOLES_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPOOLES=yes
+		  SPOOLESINCL=-I"$SPOOLES_ROOT/include"
+		  SPOOLESLIB=-L"$SPOOLES_ROOT/lib -lspooles"
+
+		  AC_DEFINE([_HAVE_SPOOLES_],[1],[with Spooles in ISSM src])
+		  AC_SUBST([SPOOLESINCL])
+		  AC_SUBST([SPOOLESLIB])
+	  else
+		HAVE_SPOOLES=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPOOLES)
+		  dnl }}}
+dnl pastix{{{ 
+	AC_ARG_WITH([pastix-dir],
+				AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
+				[PASTIX_ROOT=$withval],[PASTIX_ROOT=""])
+
+	  AC_MSG_CHECKING(for pastix headers and libraries in $PASTIX_ROOT)
+	  if test -d "$PASTIX_ROOT"; then
+
+		dnl defaults
+		  HAVE_PASTIX=yes
+		  PASTIXINCL=-I"$PASTIX_ROOT/include"
+		  PASTIXLIB=-L"$PASTIX_ROOT/lib -lpastix_XXbit_mpi_smp_nobubble_int32_simple_real_scotch_i686_pc_linux -lptscotch -lptscotcherr -lpastix"
+
+		  AC_DEFINE([_HAVE_PASTIX_],[1],[with Pastix in ISSM src])
+		  AC_SUBST([PASTIXINCL])
+		  AC_SUBST([PASTIXLIB])
+	  else
+		HAVE_PASTIX=no
+		  fi
+		  AC_MSG_RESULT($HAVE_PASTIX)
+		  dnl }}}
+	dnl ml{{{
+	AC_ARG_WITH([ml-dir],
+	  AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
+			  [ML_ROOT=$withval],[ML_ROOT=""])
+			  
+	AC_MSG_CHECKING(for ml headers and libraries in $ML_ROOT)
+	if test -d "$ML_ROOT"; then
+
+		dnl defaults
+		HAVE_ML=yes
+		MLINCL=-I"$ML_ROOT/include"
+		MLLIB=-L"$ML_ROOT/lib -lml"
+        
+		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
+		AC_SUBST([MLINCL])
+		AC_SUBST([MLLIB])
+	else
+		HAVE_ML=no
+	fi
+	AC_MSG_RESULT($HAVE_ML)
+	dnl }}}
+	dnl umfpack{{{
+		AC_ARG_WITH([umfpack-dir],
+		  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
+					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT=""])
+
+		AC_MSG_CHECKING(for UMFPACK headers and libraries in $UMFPACK_ROOT)
+		if test -d "$UMFPACK_ROOT"; then
+
+			dnl defaults
+			HAVE_UMFPACK=yes
+			UMFPACKINCL=""
+			UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
+
+			AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
+			AC_SUBST([UMFPACKINCL])
+			AC_SUBST([UMFPACKLIB])
+		else
+			HAVE_UMFPACK=no
+		fi
+		AC_MSG_RESULT($HAVE_UMFPACK)
+	dnl }}}
+dnl math{{{
+	AC_MSG_CHECKING(for math library)
+	AC_ARG_WITH([math-lib],
+	  AS_HELP_STRING([--with-math-lib = otions],[math options, for ex: "/usr/lib/libm.a]),
+	  [MATH_LIB=$withval],[MATH_LIB=""])
+
+	dnl check that --with-math-lib may have been provided
+	if test -n "$MATH_LIB" ; then
+		HAVE_MATH=yes
+		MATHLIB="$MATH_LIB"
+
+		AC_DEFINE([_HAVE_MATH_],[1],[with MATH in ISSM src])
+		AC_SUBST([MATHLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl fortran{{{
+	AC_ARG_WITH([fortran],
+		AS_HELP_STRING([--with-fortran = YES], [do we compile fortran code (default is yes)]),
+		[FORTRAN=$withval],[FORTRAN=yes]) 
+	AC_MSG_CHECKING(for fortran compilation)
+	if test "x$FORTRAN" = "xyes"; then
+		dnl defaults
+		HAVE_FORTRAN=yes
+
+		AC_DEFINE([_HAVE_FORTRAN_],[1],[with fortran capability])
+	else
+		HAVE_FORTRAN=no
+	fi
+	AM_CONDITIONAL([FORTRAN], [test x$FORTRAN = xyes])
+	AC_MSG_RESULT($FORTRAN)
+
+	if test "x$FORTRAN" = "xyes"; then
+		dnl fortran library  option
+		AC_MSG_CHECKING(for fortran library)
+		AC_ARG_WITH([fortran-lib],
+		  AS_HELP_STRING([--with-fortran-lib = options],[fortran options, for ex: "/usr/lib/gfortran.a]),
+			[FORTRAN_LIB=$withval],[FORTRAN_LIB=""])
+
+		dnl check that --with-fortran-lib may have been provided
+		if test -n "$FORTRAN_LIB" ; then
+			dnl check that library provided EXISTS!
+		   FORTRAN_DIR=$(echo $FORTRAN_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+			if test -d "$FORTRAN_DIR" || test -f "$FORTRAN_DIR"; then
+				FORTRANLIB="$FORTRAN_LIB"
+				AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+				AC_SUBST([FORTRANLIB])
+			else
+			 if test "x$HAVE_MPI" = "xyes"; then
+				FORTRANLIB=$(mpif77 -print-file-name="libgfortran.a")
+				if test -f "$FORTRANLIB"; then
+					 AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist, MPI suggests the following library: $FORTRANLIB]);
+				fi
+			 fi
+				AC_MSG_ERROR([frtran library provided ($FORTRAN_LIB$) does not exist!]);
+			fi
+		fi
+		AC_MSG_RESULT(done)
+	fi
+	dnl }}}
+	dnl graphics{{{
+	AC_MSG_CHECKING(for graphics library)
+	AC_ARG_WITH([graphics-lib],
+	  AS_HELP_STRING([--with-graphics-lib = options],[graphics options, for ex: "/usr/X11/lib/libX11.a]),
+	  [GRAPHICS_LIB=$withval],[GRAPHICS_LIB=""])
+
+	dnl check that --with-graphics-lib may have been provided
+	
+	if test -n "$GRAPHICS_LIB" ; then
+		dnl check that library provided EXISTS!
+		GRAPHICS_DIR=$(echo $GRAPHICS_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+		if test -d "$GRAPHICS_DIR" || test -f "$GRAPHICS_DIR"; then
+			HAVE_GRAPHICS=yes
+			GRAPHICSLIB="$GRAPHICS_LIB"
+			AC_DEFINE([_HAVE_GRAPHICS_],[1],[with GRAPHICS in ISSM src])
+			AC_SUBST([GRAPHICSLIB])
+		else
+			if test -f "$PETSC_ROOT/conf/petscvariables"; then
+				GRAPHICSLIB=$(cat $PETSC_ROOT/conf/petscvariables | grep X_LIB)
+				AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB) does not exist, PETSc suggests the following library: $GRAPHICSLIB]);
+			fi
+			AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB$) does not exist!]);
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl Capabilities
+	dnl with-kml{{{
+	AC_ARG_WITH([kml],
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
+		[KML=$withval],[KML=yes]) 
+	AC_MSG_CHECKING(for kml capability compilation)
+
+	if test "x$KML" = "xyes"; then
+		HAVE_KML=yes
+		AC_DEFINE([_HAVE_KML_],[1],[with kml capability])
+	else
+		HAVE_KML=no
+	fi
+	AM_CONDITIONAL([KML], [test x$HAVE_KML = xyes])
+	AC_MSG_RESULT($HAVE_KML)
+	dnl }}}
+	dnl with-kriging{{{
+	AC_ARG_WITH([kriging],
+		AS_HELP_STRING([--with-kriging = YES],[compile with kriging capabilities (default is yes)]),
+		[KRIGING=$withval],[KRIGING=yes]) 
+	AC_MSG_CHECKING(for kriging capability compilation)
+
+	if test "x$KRIGING" = "xyes"; then
+		HAVE_KRIGING=yes
+		AC_DEFINE([_HAVE_KRIGING_],[1],[with kriging capability])
+	else
+		HAVE_KRIGING=no
+	fi
+	AM_CONDITIONAL([KRIGING], [test x$HAVE_KRIGING = xyes])
+	AC_MSG_RESULT($HAVE_KRIGING)
+	dnl }}}
+	dnl with-steadystate{{{
+	AC_ARG_WITH([steadystate],
+		AS_HELP_STRING([--with-steadystate = YES],[compile with steadystate capabilities (default is yes)]),
+		[STEADYSTATE=$withval],[STEADYSTATE=yes]) 
+	AC_MSG_CHECKING(for steadystate capability compilation)
+
+	if test "x$STEADYSTATE" = "xyes"; then
+
+		dnl defaults
+		HAVE_STEADYSTATE=yes
+
+		AC_DEFINE([_HAVE_STEADYSTATE_],[1],[with steadystate capability])
+	else
+		HAVE_STEADYSTATE=no
+	fi
+	AM_CONDITIONAL([STEADYSTATE], [test x$HAVE_STEADYSTATE = xyes])
+	AC_MSG_RESULT($HAVE_STEADYSTATE)
+	dnl }}}
+	dnl with-transient{{{
+	AC_ARG_WITH([transient],
+		AS_HELP_STRING([--with-transient = YES], [compile with transient capabilities (default is yes)]),
+		[TRANSIENT=$withval],[TRANSIENT=yes]) 
+	AC_MSG_CHECKING(for transient capability compilation)
+
+	if test "x$TRANSIENT" = "xyes"; then
+
+		dnl defaults
+		HAVE_TRANSIENT=yes
+
+		AC_DEFINE([_HAVE_TRANSIENT_],[1],[with transient capability])
+	else
+		HAVE_TRANSIENT=no
+	fi
+	AM_CONDITIONAL([TRANSIENT], [test x$HAVE_TRANSIENT = xyes])
+	AC_MSG_RESULT($HAVE_TRANSIENT)
+	dnl }}}
+	dnl with-thermal{{{
+	AC_ARG_WITH([thermal],
+		AS_HELP_STRING([--with-thermal = YES], [compile with thermal capabilities (default is yes)]),
+		[THERMAL=$withval],[THERMAL=yes]) 
+	AC_MSG_CHECKING(for thermal capability compilation)
+
+	if test "x$THERMAL" = "xyes"; then
+
+		dnl defaults
+		HAVE_THERMAL=yes
+
+		AC_DEFINE([_HAVE_THERMAL_],[1],[with thermal capability])
+	else
+		HAVE_THERMAL=no
+	fi
+	AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
+	AC_MSG_RESULT($HAVE_THERMAL)
+	dnl }}}
+	dnl with-prognostic{{{
+	AC_ARG_WITH([prognostic],
+		AS_HELP_STRING([--with-prognostic = YES], [compile with prognostic capabilities (default is yes)]),
+		[PROGNOSTIC=$withval],[PROGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for prognostic capability compilation)
+
+	if test "x$PROGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_PROGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_PROGNOSTIC_],[1],[with prognostic capability])
+	else
+		HAVE_PROGNOSTIC=no
+	fi
+	AM_CONDITIONAL([PROGNOSTIC], [test x$HAVE_PROGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_PROGNOSTIC)
+	dnl }}}
+	dnl with-control{{{
+	AC_ARG_WITH([control],
+		AS_HELP_STRING([--with-control = YES], [compile with control capabilities (default is yes)]),
+		[CONTROL=$withval],[CONTROL=yes]) 
+	AC_MSG_CHECKING(for control capability compilation)
+
+	if test "x$CONTROL" = "xyes"; then
+
+		dnl defaults
+		HAVE_CONTROL=yes
+
+		AC_DEFINE([_HAVE_CONTROL_],[1],[with control capability])
+	else
+		HAVE_CONTROL=no
+	fi
+	AM_CONDITIONAL([CONTROL], [test x$HAVE_CONTROL = xyes])
+	AC_MSG_RESULT($HAVE_CONTROL)
+	dnl }}}
+	dnl with-hydrology{{{
+	AC_ARG_WITH([hydrology],
+		AS_HELP_STRING([--with-hydrology = YES], [compile with hydrology capabilities (default is yes)]),
+		[HYDROLOGY=$withval],[HYDROLOGY=yes]) 
+	AC_MSG_CHECKING(for hydrology capability compilation)
+
+	if test "x$HYDROLOGY" = "xyes"; then
+
+		dnl defaults
+		HAVE_HYDROLOGY=yes
+
+		AC_DEFINE([_HAVE_HYDROLOGY_],[1],[with hydrology capability])
+	else
+		HAVE_HYDROLOGY=no
+	fi
+	AM_CONDITIONAL([HYDROLOGY], [test x$HAVE_HYDROLOGY = xyes])
+	AC_MSG_RESULT($HAVE_HYDROLOGY)
+	dnl }}}
+	dnl with-diagnostic{{{
+	AC_ARG_WITH([diagnostic],
+		AS_HELP_STRING([--with-diagnostic = YES], [compile with diagnostic capabilities (default is yes)]),
+		[DIAGNOSTIC=$withval],[DIAGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for diagnostic capability compilation)
+
+	if test "x$DIAGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_DIAGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_DIAGNOSTIC_],[1],[with diagnostic capability])
+	else
+		HAVE_DIAGNOSTIC=no
+	fi
+	AM_CONDITIONAL([DIAGNOSTIC], [test x$HAVE_DIAGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_DIAGNOSTIC)
+	dnl }}}
+	dnl with-balanced{{{
+	AC_ARG_WITH([balanced],
+		AS_HELP_STRING([--with-balanced = YES], [compile with balanced capabilities (default is yes)]),
+		[BALANCED=$withval],[BALANCED=yes]) 
+	AC_MSG_CHECKING(for balanced capability compilation)
+
+	if test "x$BALANCED" = "xyes"; then
+
+		dnl defaults
+		HAVE_BALANCED=yes
+
+		AC_DEFINE([_HAVE_BALANCED_],[1],[with balanced capability])
+	else
+		HAVE_BALANCED=no
+	fi
+	AM_CONDITIONAL([BALANCED], [test x$HAVE_BALANCED = xyes])
+	AC_MSG_RESULT($HAVE_BALANCED)
+	dnl }}}
+	dnl with-responses{{{
+	AC_ARG_WITH([responses],
+		AS_HELP_STRING([--with-responses = YES], [compile with responses capabilities (default is yes)]),
+		[RESPONSES=$withval],[RESPONSES=yes]) 
+	AC_MSG_CHECKING(for responses capability compilation)
+
+	if test "x$RESPONSES" = "xyes"; then
+
+		dnl defaults
+		HAVE_RESPONSES=yes
+
+		AC_DEFINE([_HAVE_RESPONSES_],[1],[with responses capability])
+	else
+		HAVE_RESPONSES=no
+	fi
+	AM_CONDITIONAL([RESPONSES], [test x$HAVE_RESPONSES = xyes])
+	AC_MSG_RESULT($HAVE_RESPONSES)
+	dnl }}}
+	dnl with-slope{{{
+	AC_ARG_WITH([slope],
+		AS_HELP_STRING([--with-slope = YES], [compile with slope capabilities (default is yes)]),
+		[SLOPE=$withval],[SLOPE=yes]) 
+	AC_MSG_CHECKING(for slope capability compilation)
+
+	if test "x$SLOPE" = "xyes"; then
+
+		dnl defaults
+		HAVE_SLOPE=yes
+
+		AC_DEFINE([_HAVE_SLOPE_],[1],[with slope capability])
+	else
+		HAVE_SLOPE=no
+	fi
+	AM_CONDITIONAL([SLOPE], [test x$HAVE_SLOPE = xyes])
+	AC_MSG_RESULT($HAVE_SLOPE)
+	dnl }}}
+	dnl with-groundingline{{{
+	AC_ARG_WITH([groundingline],
+		AS_HELP_STRING([--with-groundingline = YES], [compile with groundingline capabilities (default is yes)]),
+		[GROUNDINGLINE=$withval],[GROUNDINGLINE=yes]) 
+	AC_MSG_CHECKING(for groundingline capability compilation)
+
+	if test "x$GROUNDINGLINE" = "xyes"; then
+
+		dnl defaults
+		HAVE_GROUNDINGLINE=yes
+
+		AC_DEFINE([_HAVE_GROUNDINGLINE_],[1],[with groundingline capability])
+	else
+		HAVE_GROUNDINGLINE=no
+	fi
+	AM_CONDITIONAL([GROUNDINGLINE], [test x$HAVE_GROUNDINGLINE = xyes])
+	AC_MSG_RESULT($HAVE_GROUNDINGLINE)
+	dnl }}}
+	dnl with-rifts{{{
+	AC_ARG_WITH([rifts],
+		AS_HELP_STRING([--with-rifts = YES], [compile with rifts capabilities (default is yes)]),
+		[RIFTS=$withval],[RIFTS=yes]) 
+	AC_MSG_CHECKING(for rifts capability compilation)
+
+	if test "x$RIFTS" = "xyes"; then
+
+		dnl defaults
+		HAVE_RIFTS=yes
+
+		AC_DEFINE([_HAVE_RIFTS_],[1],[with rifts capability])
+	else
+		HAVE_RIFTS=no
+	fi
+	AM_CONDITIONAL([RIFTS], [test x$HAVE_RIFTS = xyes])
+	AC_MSG_RESULT($HAVE_RIFTS)
+	dnl }}}
+	dnl math77{{{
+	AC_ARG_WITH([math77-dir],
+		AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
+		[MATH77_ROOT=$withval],[MATH77_ROOT=""]) 
+	AC_MSG_CHECKING(for math77)
+
+	if test -d "$MATH77_ROOT"; then
+
+	  HAVE_MATH77=yes
+	  MATH77LIB="-L$MATH77_ROOT/ -lmath77"
+
+	  AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
+	  AC_SUBST([MATH77LIB])
+	else
+		HAVE_MATH77=no
+	fi
+	AC_MSG_RESULT($HAVE_MATH77)
+	dnl }}}
+	dnl with-gia{{{
+	AC_ARG_WITH([gia],
+		AS_HELP_STRING([--with-gia = YES], [compile with gia capabilities (default is yes)]),
+		[GIA=$withval],[GIA=no]) 
+	AC_MSG_CHECKING(for gia capability compilation)
+
+	if test "x$GIA" = "xyes"; then
+	  
+	  if test "x$HAVE_MATH77" = "xno"; then
+		  HAVE_GIA=no
+		  AC_MSG_ERROR([gia requires compilation of math77 library! Reconfigure with --with-math77 option on]);
+	  else
+		dnl defaults
+		HAVE_GIA=yes
+		AC_DEFINE([_HAVE_GIA_],[1],[with gia capability])
+	  fi
+
+	else
+		HAVE_GIA=no
+	fi
+	AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
+	AC_MSG_RESULT($HAVE_GIA)
+	dnl }}}
+	dnl with-ios{{{
+	AC_ARG_WITH([ios],
+		AS_HELP_STRING([--with-ios = YES], [compile with iOS capabilities (default is no, alternatives are yes)]),
+		[IOS=$withval],[IOS=no]) 
+	AC_MSG_CHECKING(for iOS compilation)
+
+	if test "x$IOS" = "xyes"; then
+		dnl defaults
+		HAVE_IOS=yes
+
+		AC_DEFINE([_HAVE_IOS_],[1],[with android capability])
+	elif test "x$IOS" = "xno"; then
+		HAVE_IOS=no
+	else
+	  AC_MSG_ERROR([--with-ios should be either no or yes])
+	fi
+	AM_CONDITIONAL([IOS], [test x$HAVE_IOS != xno])
+	AC_DEFINE([_HAVE_IOS_],[1],[with ios.])
+	AC_MSG_RESULT($HAVE_IOS)
+	dnl }}}
+	dnl with-android{{{
+	AC_ARG_WITH([android],
+		AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
+		[ANDROID=$withval],[ANDROID=no]) 
+	AC_MSG_CHECKING(for android capability compilation)
+
+	if test "x$ANDROID" = "xjni"; then
+
+		dnl defaults
+		HAVE_ANDROID=jni
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+		AC_DEFINE([_HAVE_ANDROID_JNI_],[1],[with android jni])
+	elif test "x$ANDROID" = "xexe"; then
+		dnl defaults
+		HAVE_ANDROID=exe
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xno"; then
+		HAVE_ANDROID=no
+	else
+	  AC_MSG_ERROR([--with-android should be either no, exe or jni])
+	fi
+	AM_CONDITIONAL([ANDROID], [test x$HAVE_ANDROID != xno])
+	AM_CONDITIONAL([ANDROIDJNI], [test x$HAVE_ANDROID = xjni])
+	AM_CONDITIONAL([ANDROIDEXE], [test x$HAVE_ANDROID = xexe])
+	AC_DEFINE([_HAVE_ANDROID_],[1],[with android.])
+	AC_MSG_RESULT($HAVE_ANDROID)
+	dnl }}}
+	dnl with-android-ndk{{{
+	AC_ARG_WITH([android-ndk],
+	  AS_HELP_STRING([--with-android-ndk=DIR], [android-ndk root directory.]),
+	  [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""]) 
+	AC_MSG_CHECKING(with android ndk)
+	
+	if test -d "$ANDROID_NDK_ROOT"; then
+		dnl defaults
+		HAVE_ANDROID_NDK=yes
+		ANDROID_NDKINCL="-I$ANDROID_NDK_ROOT/arm-linux-android-install/sysroot/usr/include"
+
+		AC_DEFINE([_HAVE_ANDROID_NDK_],[1],[with android ndk in ISSM src])
+		AC_SUBST([ANDROID_NDKINCL])
+	else
+		HAVE_ANDROID_NDK=no
+	fi
+	AC_MSG_RESULT($HAVE_ANDROID_NDK)
+	dnl }}}
+	dnl with-3d{{{
+	AC_ARG_WITH([3d],
+		AS_HELP_STRING([--with-3d = YES], [compile with 3d capabilities (default is yes)]),
+		[THREED=$withval],[THREED=yes]) 
+	AC_MSG_CHECKING(for 3d capability compilation)
+
+	if test "x$THREED" = "xyes"; then
+
+		dnl defaults
+		HAVE_3D=yes
+
+		AC_DEFINE([_HAVE_3D_],[1],[with 3d capability])
+	else
+		HAVE_3D=no
+	fi
+	AM_CONDITIONAL([THREED], [test x$HAVE_3D = xyes])
+	AC_MSG_RESULT($HAVE_3D)
+	dnl }}}
+	dnl checks{{{
+	AC_MSG_CHECKING(consistency between all libraries)
+	
+	dnl check that if petsc is requested , mpi should be specified
+	if test "$HAVE_PETSC" = "yes" ; then
+		if test "$HAVE_MPI" = "NO";  then
+			AC_MSG_ERROR([petsc requires mpi!]);
+		fi
+	fi
+
+	dnl check that we have either python or matlab support if we compile the modules
+	if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
+		AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
+	fi
+
+	dnl check that if we have MPI, we have metis
+	if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
+	AC_MSG_ERROR([need mpi if using the metis partitioner!]);
+	fi
+
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl other options
+	dnl optimization{{{
+	dnl bypass standard optimization -g -O2 ? 
+	AC_ARG_WITH([cxxoptflags],
+	  AS_HELP_STRING([--with-cxxoptflags = CXXOPTFLAGS], [optimization using CXX flags, ex: --with-cxxoptflags=-march=opteron -O3]),
+	  [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2"]) 
+	AC_MSG_CHECKING(for c++ optimization flags)
+	AC_SUBST([CXXOPTFLAGS])
+	AC_MSG_RESULT(done)
+
+	dnl }}}
+	dnl multithreading{{{
+	AC_ARG_WITH([numthreads],
+	  AS_HELP_STRING([--with-numthreads = NUMTHREADS_VALUE],[numthreads, default is 1. ]),
+	  [NUMTHREADS_VALUE=$withval],[NUMTHREADS_VALUE=1])
+	AC_MSG_CHECKING(for number of threads)
+	dnl defaults
+	MULTITHREADING=no
+	MULTITHREADINLIB=""
+	if test "$NUMTHREADS_VALUE" != "1"; then
+		
+		MULTITHREADINGLIB="-lpthread -lrt"
+		case "${host_os}" in
+		*cygwin*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*linux*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*darwin*)
+		MULTITHREADINGLIB="-lpthread"
+		;;
+		esac
+
+		AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
+		AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
+	fi
+	AC_SUBST([MULTITHREADINGLIB])
+	AC_MSG_RESULT($NUMTHREADS_VALUE) 
+	dnl }}}
+	dnl 64bit {{{
+	AC_ARG_WITH([64bit-indices],
+	  AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
+	  [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
+	AC_MSG_CHECKING(for 64 bit indices)
+
+	if test "$USE_64BIT_INDICES" == "1"; then
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[1],[with 64 bits indices])
+	else
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[0],[with 64 bits indices])
+	fi
+	AC_MSG_RESULT($USE_64BIT_INDICES)
+	dnl }}}
+])
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/BinRead.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/BinRead.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/BinRead.py	(revision 18231)
@@ -0,0 +1,169 @@
+#! /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.
+	"""
+	from MatlabFuncs import *
+
+	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/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage.py	(revision 18231)
@@ -0,0 +1,139 @@
+#!/usr/bin/env python
+# -*- coding: ISO-8859-1 -*-
+#
+# TODO: Improve upon extension recognition by checking for mismatches in found targets
+# and specified local file.
+#
+
+# imports {{{
+import os,sys,re
+import urllib
+from HTMLParser import HTMLParser
+from urllib import FancyURLopener
+# }}}
+class MyHTMLParser(HTMLParser): #{{{
+
+    def __init__(self, pattern):
+        HTMLParser.__init__(self)
+        self.matcher = re.compile(pattern) 
+        self.targets = []
+
+    def handle_starttag(self, tag, attrs):
+        for i in attrs:
+            if "href" == i[0] and str(self.matcher.match(i[1])) != "None":
+                self.targets.append(i[1])
+#}}}
+def main(argv=None): # {{{
+    # Separates the URL into a directory and the file or pattern based on the
+    # last appearance of '/'.
+	if len(sys.argv) > 1:
+	    pivot = sys.argv[1].rfind("/")
+	    url = (sys.argv[1])[:pivot]
+	    pivot += 1
+	    find = (sys.argv[1])[pivot:]
+	else:
+	    print "******************************************************************************************************************************"
+	    print "* Invalid input!                                                                                                             *"
+	    print "*                                                                                                                            *"
+	    print "* Try: 'DownloadExternalPackage.py url [localFile]'                                                                          *"
+	    print "*                                                                                                                            *"
+	    print "* Where 'URL' is the URL with an explicit package name or the URL followed by the truncated package name. And 'localFile' is *"
+	    print "* the file name (including extension) that you would like to save as.                                                        *"
+	    print "*                                                                                                                            *"
+	    print "* Examples:                                                                                                                  *" 
+	    print "*                                                                                                                            *"
+	    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz' *"
+	    print "*                                                                                                                            *"
+	    print "*     This is the old style and the safest way to download a package.                                                        *"
+	    print "*                                                                                                                            *"
+	    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool' 'libtool.tar.gz'                      *"
+	    print "*                                                                                                                            *"
+	    print "*     This is the new style. For packages like 'Libtool', which we never expect to be using multiple versions, this will     *"
+	    print "*     download the most recent version and save it as the generic 'libtool.tar.gz'.                                          *"
+	    print "*                                                                                                                            *"
+	    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'                      *"
+	    print "*                                                                                                                            *"
+	    print "*     This is the new style. This is a demonstration of how this script can be used to disambiguate a package name if there  *"
+	    print "*     are more than once package matching 'gsl-'.                                                                            *"
+	    print "*                                                                                                                            *"
+	    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool'                                       *"
+	    print "*                                                                                                                            *"
+	    print "*     This is the new style. This will download a package with 'libtool' as a prefix and save it as its canonical name.      *"
+	    print "*                                                                                                                            *"
+	    print "*                                                                                                                            *"
+	    print "******************************************************************************************************************************"
+	
+	if len(sys.argv) > 2:
+	    localFile=sys.argv[2]
+	    print "Downloaded file will be saved as: " + localFile
+	else:
+	    localFile = None
+	    print "Downloaded file will saved with the same file name."
+	
+	
+	print "Looking for: " + find
+	
+	# As an extra precaution, if no extension is given for a particular package
+	# such as '.../libtool', then ensure that files found are of appropriate
+	# file extensions. 
+	#
+	# WARNING: The external packages directory includes executable binaries with
+	# '.exe' extensions. As such, '.exe' is an acceptable suffix, but this is 
+	# inherently dangerous since this script can be used to download from any
+	# valid website. Furthermore, if an individual attempts a "man-in-the-middle"  
+	# attack, then the user would be capable of downloading executables from 
+	# an untrusted source.
+	pattern = find + "[\w.-]*(\.tar\.gz|tar\.gz2|tgz|zip|exe)?"
+	parser = MyHTMLParser(pattern)
+	
+	# Creates a 'FancyURL' which allows the script to fail gracefully by catching
+	# HTTP error codes 30X and several 40X(where 'X' is a natural number).
+	urlObject = FancyURLopener()
+	obj = urlObject.open(url)
+	parser.feed(obj.read())
+	
+	# If a file pattern was used to describe the file that should be downloaded,
+	# then there is the potential for multiple file matches. Currently, the script
+	# will detect this ambiguity and print out all the matches, while informing 
+	# the user that he must refine his search.
+	#
+	# TODO: Prompt the user to select from a list his/her preferred target.
+	if len(parser.targets) > 1:
+	    print "Could not resolve your download due to the number of hits."
+	    print "Refine your search."
+	    for i in parser.targets:
+	        print i
+	
+	elif len(parser.targets) == 1:
+	    print "Found: " + parser.targets[0]
+	    url += "/" + parser.targets[0]
+	
+	    if localFile is None:
+	        if os.path.exists(parser.targets[0]): 
+	            print "File " + parser.targets[0] + " already exists and will not be downloaded..."
+	        else:
+	            urllib.urlretrieve(url, parser.targets[0])
+	            print "File saved as: " + parser.targets[0]
+	    else:
+	        if os.path.exists(localFile): 
+	            print "File "+ localFile +" already exists and will not be downloaded..."
+	        else:
+	            if parser.targets[0] == localFile:
+	                print "File found and destination match."
+	            elif parser.matcher.match(localFile) != "None":
+	                print "File found matches destination pattern."
+	            else:
+	                print "WARNING: the file found \'" + parser.targets[0] + "\' does not match \'" + localFile + "\'"
+	                print "Ensure the downloaded version is suitable."
+	
+	            urllib.urlretrieve(url, localFile)
+	            print "File saved as: " + localFile
+	
+	else:
+	    print "No matches found!"
+	
+	obj.close()
+# End 'main' function. }}}
+
+if __name__ == "__main__":
+    main()
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage2.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage2.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/DownloadExternalPackage2.py	(revision 18231)
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+# -*- coding: ISO-8859-1 -*-
+
+import os,sys
+import urllib
+
+#Check inputs
+if(len(sys.argv)!=3): raise NameError('usage: ./DownloadExternalPackage.py URL localfile')
+
+url=sys.argv[1];
+localFile=sys.argv[2]
+
+#Remove file if it already exists
+if os.path.exists(localFile):
+	print "File "+ localFile +" already exists and will not be downloaded..."
+	sys.exit()
+
+#Try to download from url
+httpfail=-1
+try:
+	print "Fetching %s" % localFile
+	urllib.urlretrieve(url,localFile)
+	httpfail=0
+except Exception, e:
+	httpfail=1
+
+#Error message in case it failed
+if (httpfail):
+	failureMessage = '''
+===========================================================================
+Unable to download package %s from: %s
+* If URL specified manually - perhaps there is a typo?
+* If your network is disconnected - please reconnect 
+* Alternatively, you can download the above URL manually
+===========================================================================
+''' % (localFile,url)
+	raise RuntimeError(failureMessage)
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/GenerateReferences.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/GenerateReferences.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/GenerateReferences.sh	(revision 18231)
@@ -0,0 +1,38 @@
+#!/bin/bash
+#Generate a RTF file with references provided in CITE
+#Use AGU bibliography style and delete labels for easy copy/paste
+#Version: 04/28/11
+
+#Genetare a pdf with the list of references provided in $CITE
+CITE="Joughin2009,Rignot2002,Frey2001"
+
+#First erase files; 
+rm -rf references.rtf
+
+#create Latex file
+cat <<END > references.tex
+\documentclass{article}
+\bibliographystyle{agu}
+\begin{document}
+\nocite{$CITE}
+\bibliography{$JPL_SVN/publications/bibtex/references}
+\end{document}
+END
+#Generate pdf
+echo "Compiling document"
+latex  -interaction=batchmode -file-line-error references.tex > /dev/null
+echo "Running Bibtex"
+bibtex references
+echo "Removing labels"
+cat references.bbl | sed -e "s-ibitem.*\]-DELETE-" | grep -v DELETE > references.bak1 #delete labels that hold in one line
+cat references.bak1 | sed -e "/ibitem/,/]/d" > references.bak2                        #delete labels that are on multiple lines
+mv references.bak2 references.bbl
+echo "Converting to rtf"
+$ISSM_DIR/externalpackages/latex2rtf/install/latex2rtf -P $ISSM_DIR/externalpackages/latex2rtf/install/cfg/ references
+
+#Remove all but rtf file
+rm -rf references.[!rtf]*
+rm -rf references.tex
+
+#open output
+#open references.rtf
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/automakererun.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/automakererun.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/automakererun.sh	(revision 18231)
@@ -0,0 +1,11 @@
+#!/bin/sh
+#  this shell script will automatically reconfigure the entire ISSM 
+#  archive.
+
+# As it turns out, the autoreconf script provided by Autotools
+# encompasses the functionality of this script. As such, the 
+# following two lines will replace the remainder of the script.
+# If all goes well, then the script will be shortened in the future.
+
+cd $ISSM_DIR
+autoreconf -iv 
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc-1.60.pl
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc-1.60.pl	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc-1.60.pl	(revision 18231)
@@ -0,0 +1,9064 @@
+#!/usr/bin/env perl
+# cloc -- Count Lines of Code                  {{{1
+# Copyright (C) 2006-2013 Northrop Grumman Corporation
+# Author:  Al Danial <al.danial@gmail.com>
+#          First release August 2006
+#
+# Includes code from:
+#   - SLOCCount v2.26 
+#     http://www.dwheeler.com/sloccount/
+#     by David Wheeler.
+#   - Regexp::Common v2.120
+#     http://search.cpan.org/~abigail/Regexp-Common-2.120/lib/Regexp/Common.pm
+#     by Damian Conway and Abigail.
+#   - Win32::Autoglob 
+#     http://search.cpan.org/~sburke/Win32-Autoglob-1.01/Autoglob.pm
+#     by Sean M. Burke.
+#   - Algorithm::Diff
+#     http://search.cpan.org/~tyemq/Algorithm-Diff-1.1902/lib/Algorithm/Diff.pm
+#     by Tye McQueen.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details:
+# <http://www.gnu.org/licenses/gpl.txt>.
+#
+# 1}}}
+my $VERSION = "1.60";  # odd number == beta; even number == stable
+my $URL     = "http://cloc.sourceforge.net";
+require 5.006;
+# use modules                                  {{{1
+use warnings;
+use strict;
+use Getopt::Long;
+use File::Basename;
+use File::Temp qw { tempfile tempdir };
+use File::Find;
+use File::Path;
+use File::Spec;
+use IO::File;
+use POSIX "strftime";
+
+# Digest::MD5 isn't in the standard distribution. Use it only if installed.
+my $HAVE_Digest_MD5 = 0;
+eval "use Digest::MD5;";
+if (defined $Digest::MD5::VERSION) {
+    $HAVE_Digest_MD5 = 1;
+} else {
+    warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
+}
+
+# Time::HiRes became standard with Perl 5.8
+my $HAVE_Time_HiRes = 0;
+eval "use Time::HiRes;";
+$HAVE_Time_HiRes = 1 if defined $Time::HiRes::VERSION;
+
+my $HAVE_Rexexp_Common;
+# Regexp::Common isn't in the standard distribution.  It will
+# be installed in a temp directory if necessary.
+BEGIN {
+    if (eval "use Regexp::Common;") {
+        $HAVE_Rexexp_Common = 1;
+    } else {
+        $HAVE_Rexexp_Common = 0;
+    }
+}
+
+my $HAVE_Algorith_Diff = 0;
+# Algorithm::Diff isn't in the standard distribution.  It will
+# be installed in a temp directory if necessary.
+eval "use Algorithm::Diff qw ( sdiff ) ";
+if (defined $Algorithm::Diff::VERSION) {
+    $HAVE_Algorith_Diff = 1;
+} else {
+    Install_Algorithm_Diff();
+}
+# print "2 HAVE_Algorith_Diff = $HAVE_Algorith_Diff\n";
+# test_alg_diff($ARGV[$#ARGV - 1], $ARGV[$#ARGV]); die;
+
+# Uncomment next two lines when building Windows executable with perl2exe
+# or if running on a system that already has Regexp::Common.
+#use Regexp::Common;
+#$HAVE_Rexexp_Common = 1;
+
+#perl2exe_include "Regexp/Common/whitespace.pm"
+#perl2exe_include "Regexp/Common/URI.pm"
+#perl2exe_include "Regexp/Common/URI/fax.pm"
+#perl2exe_include "Regexp/Common/URI/file.pm"
+#perl2exe_include "Regexp/Common/URI/ftp.pm"
+#perl2exe_include "Regexp/Common/URI/gopher.pm"
+#perl2exe_include "Regexp/Common/URI/http.pm"
+#perl2exe_include "Regexp/Common/URI/pop.pm"
+#perl2exe_include "Regexp/Common/URI/prospero.pm"
+#perl2exe_include "Regexp/Common/URI/news.pm"
+#perl2exe_include "Regexp/Common/URI/tel.pm"
+#perl2exe_include "Regexp/Common/URI/telnet.pm"
+#perl2exe_include "Regexp/Common/URI/tv.pm"
+#perl2exe_include "Regexp/Common/URI/wais.pm"
+#perl2exe_include "Regexp/Common/CC.pm"
+#perl2exe_include "Regexp/Common/SEN.pm"
+#perl2exe_include "Regexp/Common/number.pm"
+#perl2exe_include "Regexp/Common/delimited.pm"
+#perl2exe_include "Regexp/Common/profanity.pm"
+#perl2exe_include "Regexp/Common/net.pm"
+#perl2exe_include "Regexp/Common/zip.pm"
+#perl2exe_include "Regexp/Common/comment.pm"
+#perl2exe_include "Regexp/Common/balanced.pm"
+#perl2exe_include "Regexp/Common/lingua.pm"
+#perl2exe_include "Regexp/Common/list.pm"
+#perl2exe_include "File/Glob.pm"
+
+use Text::Tabs qw { expand };
+use Cwd qw { cwd };
+use File::Glob;
+my $PERL_516 = $] >= 5.016 ? 1 : 0;  # 5.16 deprecates defined(@array)
+no warnings 'deprecated';            # will need to comment this out to test
+                                     # each new Perl version
+# 1}}}
+# Usage information, options processing.       {{{1
+my $ON_WINDOWS = 0;
+   $ON_WINDOWS = 1 if ($^O =~ /^MSWin/) or ($^O eq "Windows_NT");
+if ($ON_WINDOWS and $ENV{'SHELL'}) {
+    if ($ENV{'SHELL'} =~ m{^/}) {
+        $ON_WINDOWS = 0;  # make Cygwin look like Unix
+    } else {
+        $ON_WINDOWS = 1;  # MKS defines $SHELL but still acts like Windows
+    }
+}
+
+my $NN     = chr(27) . "[0m";  # normal
+   $NN     = "" if $ON_WINDOWS or !(-t STDERR); # -t STDERR:  is it a terminal?
+my $BB     = chr(27) . "[1m";  # bold
+   $BB     = "" if $ON_WINDOWS or !(-t STDERR);
+my $script = basename $0;
+my $usage  = "
+Usage: $script [options] <file(s)/dir(s)> | <set 1> <set 2> | <report files>
+
+ Count, or compute differences of, physical lines of source code in the
+ given files (may be archives such as compressed tarballs or zip files)
+ and/or recursively below the given directories.
+
+ ${BB}Input Options${NN}
+   --extract-with=<cmd>      This option is only needed if cloc is unable
+                             to figure out how to extract the contents of
+                             the input file(s) by itself.
+                             Use <cmd> to extract binary archive files (e.g.:
+                             .tar.gz, .zip, .Z).  Use the literal '>FILE<' as
+                             a stand-in for the actual file(s) to be
+                             extracted.  For example, to count lines of code
+                             in the input files
+                                gcc-4.2.tar.gz  perl-5.8.8.tar.gz
+                             on Unix use
+                               --extract-with='gzip -dc >FILE< | tar xf -'
+                             or, if you have GNU tar,
+                               --extract-with='tar zxf >FILE<'
+                             and on Windows use, for example:
+                               --extract-with=\"\\\"c:\\Program Files\\WinZip\\WinZip32.exe\\\" -e -o >FILE< .\"
+                             (if WinZip is installed there).
+   --list-file=<file>        Take the list of file and/or directory names to
+                             process from <file> which has one file/directory
+                             name per line.  See also --exclude-list-file.
+   --unicode                 Check binary files to see if they contain Unicode
+                             expanded ASCII text.  This causes performance to
+                             drop noticably.
+
+ ${BB}Processing Options${NN}
+   --autoconf                Count .in files (as processed by GNU autoconf) of
+                             recognized languages.
+   --by-file                 Report results for every source file encountered.
+   --by-file-by-lang         Report results for every source file encountered
+                             in addition to reporting by language.
+   --diff <set1> <set2>      Compute differences in code and comments between
+                             source file(s) of <set1> and <set2>.  The inputs
+                             may be pairs of files, directories, or archives.
+                             Use --diff-alignment to generate a list showing
+                             which file pairs where compared.  See also
+                             --ignore-case, --ignore-whitespace.
+   --diff-timeout <N>        Ignore files which take more than <N> seconds
+                             to process.  Default is 10 seconds.
+                             (Large files with many repeated lines can cause 
+                             Algorithm::Diff::sdiff() to take hours.)
+   --follow-links            [Unix only] Follow symbolic links to directories
+                             (sym links to files are always followed).
+   --force-lang=<lang>[,<ext>]
+                             Process all files that have a <ext> extension
+                             with the counter for language <lang>.  For
+                             example, to count all .f files with the
+                             Fortran 90 counter (which expects files to
+                             end with .f90) instead of the default Fortran 77
+                             counter, use
+                               --force-lang=\"Fortran 90\",f
+                             If <ext> is omitted, every file will be counted
+                             with the <lang> counter.  This option can be
+                             specified multiple times (but that is only
+                             useful when <ext> is given each time).
+                             See also --script-lang, --lang-no-ext.
+   --force-lang-def=<file>   Load language processing filters from <file>,
+                             then use these filters instead of the built-in
+                             filters.  Note:  languages which map to the same 
+                             file extension (for example:
+                             MATLAB/Objective C/MUMPS;  Pascal/PHP; 
+                             Lisp/OpenCL) will be ignored as these require 
+                             additional processing that is not expressed in 
+                             language definition files.  Use --read-lang-def 
+                             to define new language filters without replacing 
+                             built-in filters (see also --write-lang-def).
+   --ignore-whitespace       Ignore horizontal white space when comparing files
+                             with --diff.  See also --ignore-case.
+   --ignore-case             Ignore changes in case; consider upper- and lower-
+                             case letters equivalent when comparing files with
+                             --diff.  See also --ignore-whitespace.
+   --lang-no-ext=<lang>      Count files without extensions using the <lang>
+                             counter.  This option overrides internal logic
+                             for files without extensions (where such files
+                             are checked against known scripting languages
+                             by examining the first line for #!).  See also
+                             --force-lang, --script-lang.
+   --max-file-size=<MB>      Skip files larger than <MB> megabytes when
+                             traversing directories.  By default, <MB>=100.
+                             cloc's memory requirement is roughly twenty times 
+                             larger than the largest file so running with 
+                             files larger than 100 MB on a computer with less 
+                             than 2 GB of memory will cause problems.  
+                             Note:  this check does not apply to files 
+                             explicitly passed as command line arguments.
+   --read-binary-files       Process binary files in addition to text files.
+                             This is usually a bad idea and should only be
+                             attempted with text files that have embedded
+                             binary data.
+   --read-lang-def=<file>    Load new language processing filters from <file>
+                             and merge them with those already known to cloc.  
+                             If <file> defines a language cloc already knows 
+                             about, cloc's definition will take precedence.  
+                             Use --force-lang-def to over-ride cloc's 
+                             definitions (see also --write-lang-def ).
+   --script-lang=<lang>,<s>  Process all files that invoke <s> as a #!
+                             scripting language with the counter for language
+                             <lang>.  For example, files that begin with
+                                #!/usr/local/bin/perl5.8.8
+                             will be counted with the Perl counter by using
+                                --script-lang=Perl,perl5.8.8
+                             The language name is case insensitive but the
+                             name of the script language executable, <s>,
+                             must have the right case.  This option can be
+                             specified multiple times.  See also --force-lang,
+                             --lang-no-ext.
+   --sdir=<dir>              Use <dir> as the scratch directory instead of
+                             letting File::Temp chose the location.  Files
+                             written to this location are not removed at
+                             the end of the run (as they are with File::Temp).
+   --skip-uniqueness         Skip the file uniqueness check.  This will give
+                             a performance boost at the expense of counting
+                             files with identical contents multiple times
+                             (if such duplicates exist).
+   --stdin-name=<file>       Give a file name to use to determine the language
+                             for standard input.
+   --strip-comments=<ext>    For each file processed, write to the current
+                             directory a version of the file which has blank
+                             lines and comments removed.  The name of each
+                             stripped file is the original file name with
+                             .<ext> appended to it.  It is written to the
+                             current directory unless --original-dir is on.
+   --original-dir            [Only effective in combination with
+                             --strip-comments]  Write the stripped files
+                             to the same directory as the original files.
+   --sum-reports             Input arguments are report files previously
+                             created with the --report-file option.  Makes
+                             a cumulative set of results containing the
+                             sum of data from the individual report files.
+   --unix                    Override the operating system autodetection
+                             logic and run in UNIX mode.  See also
+                             --windows, --show-os.
+   --windows                 Override the operating system autodetection
+                             logic and run in Microsoft Windows mode.
+                             See also --unix, --show-os.
+
+ ${BB}Filter Options${NN}
+   --exclude-dir=<D1>[,D2,]  Exclude the given comma separated directories
+                             D1, D2, D3, et cetera, from being scanned.  For
+                             example  --exclude-dir=.cache,test  will skip
+                             all files that have /.cache/ or /test/ as part
+                             of their path.
+                             Directories named .bzr, .cvs, .hg, .git, and
+                             .svn are always excluded.
+   --exclude-ext=<ext1>[,<ext2>[...]]
+                             Do not count files having the given file name
+                             extensions.
+   --exclude-lang=<L1>[,L2,] Exclude the given comma separated languages
+                             L1, L2, L3, et cetera, from being counted.
+   --exclude-list-file=<file>  Ignore files and/or directories whose names
+                             appear in <file>.  <file> should have one entry
+                             per line.  Relative path names will be resolved
+                             starting from the directory where cloc is
+                             invoked.  See also --list-file.
+   --match-d=<regex>         Only count files in directories matching the Perl
+                             regex.  For example
+                               --match-d='/(src|include)/'
+                             only counts files in directories containing
+                             /src/ or /include/.
+   --not-match-d=<regex>     Count all files except those in directories
+                             matching the Perl regex.
+   --match-f=<regex>         Only count files whose basenames match the Perl
+                             regex.  For example
+                               --match-f='^[Ww]idget'
+                             only counts files that start with Widget or widget.
+   --not-match-f=<regex>     Count all files except those whose basenames
+                             match the Perl regex.
+   --skip-archive=<regex>    Ignore files that end with the given Perl regular
+                             expression.  For example, if given
+                               --skip-archive='(zip|tar(\.(gz|Z|bz2|xz|7z))?)'
+                             the code will skip files that end with .zip,
+                             .tar, .tar.gz, .tar.Z, .tar.bz2, .tar.xz, and
+                             .tar.7z.
+   --skip-win-hidden         On Windows, ignore hidden files.
+
+ ${BB}Debug Options${NN}
+   --categorized=<file>      Save names of categorized files to <file>.
+   --counted=<file>          Save names of processed source files to <file>.
+   --diff-alignment=<file>   Write to <file> a list of files and file pairs
+                             showing which files were added, removed, and/or
+                             compared during a run with --diff.  This switch
+                             forces the --diff mode on.
+   --help                    Print this usage information and exit.
+   --found=<file>            Save names of every file found to <file>.
+   --ignored=<file>          Save names of ignored files and the reason they
+                             were ignored to <file>.
+   --print-filter-stages     Print to STDOUT processed source code before and
+                             after each filter is applied.
+   --show-ext[=<ext>]        Print information about all known (or just the
+                             given) file extensions and exit.
+   --show-lang[=<lang>]      Print information about all known (or just the
+                             given) languages and exit.
+   --show-os                 Print the value of the operating system mode
+                             and exit.  See also --unix, --windows.
+   -v[=<n>]                  Verbose switch (optional numeric value).
+   --version                 Print the version of this program and exit.
+   --write-lang-def=<file>   Writes to <file> the language processing filters
+                             then exits.  Useful as a first step to creating
+                             custom language definitions (see also
+                             --force-lang-def, --read-lang-def).
+
+ ${BB}Output Options${NN}
+   --3                       Print third-generation language output.
+                             (This option can cause report summation to fail
+                             if some reports were produced with this option
+                             while others were produced without it.)
+   --progress-rate=<n>       Show progress update after every <n> files are
+                             processed (default <n>=100).  Set <n> to 0 to
+                             suppress progress output (useful when redirecting
+                             output to STDOUT).
+   --quiet                   Suppress all information messages except for
+                             the final report.
+   --report-file=<file>      Write the results to <file> instead of STDOUT.
+   --out=<file>              Synonym for --report-file=<file>.
+   --csv                     Write the results as comma separated values.
+   --csv-delimiter=<C>       Use the character <C> as the delimiter for comma
+                             separated files instead of ,.  This switch forces
+                             --csv to be on.
+   --sql=<file>              Write results as SQL create and insert statements
+                             which can be read by a database program such as
+                             SQLite.  If <file> is -, output is sent to STDOUT.
+   --sql-project=<name>      Use <name> as the project identifier for the
+                             current run.  Only valid with the --sql option.
+   --sql-append              Append SQL insert statements to the file specified
+                             by --sql and do not generate table creation
+                             statements.  Only valid with the --sql option.
+   --sum-one                 For plain text reports, show the SUM: output line
+                             even if only one input file is processed.
+   --xml                     Write the results in XML.
+   --xsl=<file>              Reference <file> as an XSL stylesheet within
+                             the XML output.  If <file> is 1 (numeric one),
+                             writes a default stylesheet, cloc.xsl (or
+                             cloc-diff.xsl if --diff is also given).
+                             This switch forces --xml on.
+   --yaml                    Write the results in YAML.
+
+";
+#  Help information for options not yet implemented:
+#  --inline                  Process comments that appear at the end
+#                            of lines containing code.
+#  --html                    Create HTML files of each input file showing
+#                            comment and code lines in different colors.
+
+$| = 1;  # flush STDOUT
+my $start_time = get_time();
+my (
+    $opt_categorized          ,
+    $opt_found                ,
+    @opt_force_lang           ,
+    $opt_lang_no_ext          ,
+    @opt_script_lang          ,
+    $opt_diff                 ,
+    $opt_diff_alignment       ,
+    $opt_diff_timeout         ,
+    $opt_html                 ,
+    $opt_ignored              ,
+    $opt_counted              ,
+    $opt_show_ext             ,
+    $opt_show_lang            ,
+    $opt_progress_rate        ,
+    $opt_print_filter_stages  ,
+    $opt_v                    ,
+    $opt_version              ,
+    $opt_exclude_lang         ,
+    $opt_exclude_list_file    ,
+    $opt_exclude_dir          ,
+    $opt_force_lang_def       ,
+    $opt_read_lang_def        ,
+    $opt_write_lang_def       ,
+    $opt_strip_comments       ,
+    $opt_original_dir         ,
+    $opt_quiet                ,
+    $opt_report_file          ,
+    $opt_sdir                 ,
+    $opt_sum_reports          ,
+    $opt_unicode              ,
+    $opt_no3                  ,   # accept it but don't use it
+    $opt_3                    ,
+    $opt_extract_with         ,
+    $opt_by_file              ,
+    $opt_by_file_by_lang      ,
+    $opt_xml                  ,
+    $opt_xsl                  ,
+    $opt_yaml                 ,
+    $opt_csv                  ,
+    $opt_csv_delimiter        ,
+    $opt_match_f              ,
+    $opt_not_match_f          ,
+    $opt_match_d              ,
+    $opt_not_match_d          ,
+    $opt_skip_uniqueness      ,
+    $opt_list_file            ,
+    $opt_help                 ,
+    $opt_skip_win_hidden      ,
+    $opt_read_binary_files    ,
+    $opt_sql                  ,
+    $opt_sql_append           ,
+    $opt_sql_project          ,
+    $opt_inline               ,
+    $opt_exclude_ext          ,
+    $opt_ignore_whitespace    ,
+    $opt_ignore_case          ,
+    $opt_follow_links         ,
+    $opt_autoconf             ,
+    $opt_sum_one              ,
+    $opt_stdin_name           ,
+    $opt_force_on_windows     ,
+    $opt_force_on_unix        ,   # actually forces !$ON_WINDOWS
+    $opt_show_os              ,
+    $opt_skip_archive         ,
+    $opt_max_file_size        ,   # in MB
+   );
+my $getopt_success = GetOptions(
+   "by_file|by-file"                         => \$opt_by_file             ,
+   "by_file_by_lang|by-file-by-lang"         => \$opt_by_file_by_lang     ,
+   "categorized=s"                           => \$opt_categorized         ,
+   "counted=s"                               => \$opt_counted             ,
+   "exclude_lang|exclude-lang=s"             => \$opt_exclude_lang        ,
+   "exclude_dir|exclude-dir=s"               => \$opt_exclude_dir         ,
+   "exclude_list_file|exclude-list-file=s"   => \$opt_exclude_list_file   ,
+   "extract_with|extract-with=s"             => \$opt_extract_with        ,
+   "found=s"                                 => \$opt_found               ,
+   "diff"                                    => \$opt_diff                ,
+   "diff-alignment|diff_alignment=s"         => \$opt_diff_alignment      ,
+   "diff-timeout|diff_timeout=i"             => \$opt_diff_timeout        ,
+   "html"                                    => \$opt_html                ,
+   "ignored=s"                               => \$opt_ignored             ,
+   "quiet"                                   => \$opt_quiet               ,
+   "force_lang_def|force-lang-def=s"         => \$opt_force_lang_def      ,
+   "read_lang_def|read-lang-def=s"           => \$opt_read_lang_def       ,
+   "show_ext|show-ext:s"                     => \$opt_show_ext            ,
+   "show_lang|show-lang:s"                   => \$opt_show_lang           ,
+   "progress_rate|progress-rate=i"           => \$opt_progress_rate       ,
+   "print_filter_stages|print-filter-stages" => \$opt_print_filter_stages ,
+   "report_file|report-file=s"               => \$opt_report_file         ,
+   "out=s"                                   => \$opt_report_file         ,
+   "script_lang|script-lang=s"               => \@opt_script_lang         ,
+   "sdir=s"                                  => \$opt_sdir                ,
+   "skip_uniqueness|skip-uniqueness"         => \$opt_skip_uniqueness     ,
+   "strip_comments|strip-comments=s"         => \$opt_strip_comments      ,
+   "original_dir|original-dir"               => \$opt_original_dir        ,
+   "sum_reports|sum-reports"                 => \$opt_sum_reports         ,
+   "unicode"                                 => \$opt_unicode             ,
+   "no3"                                     => \$opt_no3                 ,  # ignored
+   "3"                                       => \$opt_3                   ,
+   "v:i"                                     => \$opt_v                   ,
+   "version"                                 => \$opt_version             ,
+   "write_lang_def|write-lang-def=s"         => \$opt_write_lang_def      ,
+   "xml"                                     => \$opt_xml                 ,
+   "xsl=s"                                   => \$opt_xsl                 ,
+   "force_lang|force-lang=s"                 => \@opt_force_lang          ,
+   "lang_no_ext|lang-no-ext=s"               => \$opt_lang_no_ext         ,
+   "yaml"                                    => \$opt_yaml                ,
+   "csv"                                     => \$opt_csv                 ,
+   "csv_delimeter|csv-delimiter=s"           => \$opt_csv_delimiter       ,
+   "match_f|match-f=s"                       => \$opt_match_f             ,
+   "not_match_f|not-match-f=s"               => \$opt_not_match_f         ,
+   "match_d|match-d=s"                       => \$opt_match_d             ,
+   "not_match_d|not-match-d=s"               => \$opt_not_match_d         ,
+   "list_file|list-file=s"                   => \$opt_list_file           ,
+   "help"                                    => \$opt_help                ,
+   "skip_win_hidden|skip-win-hidden"         => \$opt_skip_win_hidden     ,
+   "read_binary_files|read-binary-files"     => \$opt_read_binary_files   ,
+   "sql=s"                                   => \$opt_sql                 ,
+   "sql_project|sql-project=s"               => \$opt_sql_project         ,
+   "sql_append|sql-append"                   => \$opt_sql_append          ,
+   "inline"                                  => \$opt_inline              ,
+   "exclude_ext|exclude-ext=s"               => \$opt_exclude_ext         ,
+   "ignore_whitespace|ignore-whitespace"     => \$opt_ignore_whitespace   ,
+   "ignore_case|ignore-case"                 => \$opt_ignore_case         ,
+   "follow_links|follow-links"               => \$opt_follow_links        ,
+   "autoconf"                                => \$opt_autoconf            ,
+   "sum_one|sum-one"                         => \$opt_sum_one             ,
+   "stdin_name|stdin-name=s"                 => \$opt_stdin_name          ,
+   "windows"                                 => \$opt_force_on_windows    ,
+   "unix"                                    => \$opt_force_on_unix       ,
+   "show_os|show-os"                         => \$opt_show_os             ,
+   "skip_archive|skip-archive=s"             => \$opt_skip_archive        ,
+   "max_file_size|max-file-size=i"           => \$opt_max_file_size       ,
+  );
+$opt_by_file  = 1 if defined  $opt_by_file_by_lang;
+my $CLOC_XSL = "cloc.xsl"; # created with --xsl
+   $CLOC_XSL = "cloc-diff.xsl" if $opt_diff;
+die "\n" unless $getopt_success;
+die $usage if $opt_help;
+my %Exclude_Language = ();
+   %Exclude_Language = map { $_ => 1 } split(/,/, $opt_exclude_lang) 
+        if $opt_exclude_lang;
+my %Exclude_Dir      = ();
+   %Exclude_Dir      = map { $_ => 1 } split(/,/, $opt_exclude_dir ) 
+        if $opt_exclude_dir ;
+# Forcibly exclude .svn, .cvs, .hg, .git, .bzr directories.  The contents of these
+# directories often conflict with files of interest.
+$opt_exclude_dir       = 1;
+$Exclude_Dir{".svn"}   = 1;
+$Exclude_Dir{".cvs"}   = 1;
+$Exclude_Dir{".hg"}    = 1;
+$Exclude_Dir{".git"}   = 1;
+$Exclude_Dir{".bzr"}   = 1;
+$opt_diff              = 1  if $opt_diff_alignment;
+$opt_exclude_ext       = "" unless $opt_exclude_ext;
+$opt_ignore_whitespace = 0  unless $opt_ignore_whitespace;
+$opt_ignore_case       = 0  unless $opt_ignore_case;
+$opt_lang_no_ext       = 0  unless $opt_lang_no_ext;
+$opt_follow_links      = 0  unless $opt_follow_links;
+$opt_diff_timeout      =10  unless $opt_diff_timeout;
+$opt_csv               = 1  if $opt_csv_delimiter;
+$ON_WINDOWS            = 1  if $opt_force_on_windows;
+$ON_WINDOWS            = 0  if $opt_force_on_unix;
+$opt_max_file_size     = 100 unless $opt_max_file_size;
+
+# Options defaults:
+$opt_progress_rate = 100 unless defined $opt_progress_rate;
+if (!defined $opt_v) {
+    $opt_v  = 0;
+} elsif (!$opt_v) {
+    $opt_v  = 1;
+}
+if (defined $opt_xsl) {
+    $opt_xsl = $CLOC_XSL if $opt_xsl eq "1";
+    $opt_xml = 1;
+}
+my $skip_generate_report = 0;
+$opt_sql = 0 unless defined $opt_sql;
+if ($opt_sql eq "-" || $opt_sql eq "1") { # stream SQL output to STDOUT
+    $opt_quiet            = 1;
+    $skip_generate_report = 1;
+    $opt_by_file          = 1;
+    $opt_sum_reports      = 0;
+    $opt_progress_rate    = 0;
+} elsif ($opt_sql)  { # write SQL output to a file
+    $opt_by_file          = 1;
+    $skip_generate_report = 1;
+    $opt_sum_reports      = 0;
+}
+
+die $usage unless defined $opt_version         or
+                  defined $opt_show_lang       or
+                  defined $opt_show_ext        or
+                  defined $opt_show_os         or
+                  defined $opt_write_lang_def  or
+                  defined $opt_list_file       or
+                  defined $opt_xsl             or
+                  scalar @ARGV >= 1;
+die "--diff requires at least two arguments\n" 
+    if $opt_diff and scalar @ARGV < 2;
+if ($opt_version) {
+    printf "$VERSION\n";
+    exit;
+}
+# 1}}}
+# Step 1:  Initialize global constants.        {{{1
+#
+my $nFiles_Found = 0;  # updated in make_file_list
+my (%Language_by_Extension, %Language_by_Script,
+    %Filters_by_Language, %Not_Code_Extension, %Not_Code_Filename,
+    %Language_by_File, %Scale_Factor, %Known_Binary_Archives,
+    %EOL_Continuation_re,
+   );
+my $ALREADY_SHOWED_HEADER = 0;
+my $ALREADY_SHOWED_XML_SECTION = 0;
+my %Error_Codes = ( 'Unable to read'                => -1,
+                    'Neither file nor directory'    => -2, 
+                    'Diff error (quoted comments?)' => -3, 
+                    'Diff error, exceeded timeout'  => -4, 
+                  );
+if ($opt_force_lang_def) {
+    # replace cloc's definitions
+    read_lang_def(
+        $opt_force_lang_def    , #        Sample values:
+        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77' 
+        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
+        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
+        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] = 
+                                 #      [ 'remove_matches' , '^\s*#'  ]
+        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
+        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
+        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
+        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
+        );
+} else {
+    set_constants(               #
+        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77' 
+        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
+        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
+        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] = 
+                                 #      [ 'remove_matches' , '^\s*#'  ]
+        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
+        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
+        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
+        \%Known_Binary_Archives, # Known_Binary_Archives{.tar} = 1
+        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
+        );
+}
+if ($opt_read_lang_def) {
+    # augment cloc's definitions (keep cloc's where there are overlaps)
+    merge_lang_def(
+        $opt_read_lang_def     , #        Sample values:
+        \%Language_by_Extension, # Language_by_Extension{f}    = 'Fortran 77' 
+        \%Language_by_Script   , # Language_by_Script{sh}      = 'Bourne Shell'
+        \%Language_by_File     , # Language_by_File{makefile}  = 'make'
+        \%Filters_by_Language  , # Filters_by_Language{Bourne Shell}[0] = 
+                                 #      [ 'remove_matches' , '^\s*#'  ]
+        \%Not_Code_Extension   , # Not_Code_Extension{jpg}     = 1
+        \%Not_Code_Filename    , # Not_Code_Filename{README}   = 1
+        \%Scale_Factor         , # Scale_Factor{Perl}          = 4.0
+        \%EOL_Continuation_re  , # EOL_Continuation_re{C++}    = '\\$'
+        );
+}
+if ($opt_lang_no_ext and !defined $Filters_by_Language{$opt_lang_no_ext}) {
+    die_unknown_lang($opt_lang_no_ext, "--lang-no-ext")
+}
+
+# Process command line provided extention-to-language mapping overrides.
+# Make a hash of known languages in lower case for easier matching.
+my %Recognized_Language_lc = (); # key = language name in lc, value = true name
+foreach my $language (keys %Filters_by_Language) {
+    my $lang_lc = lc $language;
+    $Recognized_Language_lc{$lang_lc} = $language;
+}
+my %Forced_Extension = (); # file name extensions which user wants to count
+my $All_One_Language = 0;  # set to !0 if --force-lang's <ext> is missing
+foreach my $pair (@opt_force_lang) {
+    my ($lang, $extension) = split(',', $pair);
+    my $lang_lc = lc $lang;
+    if (defined $extension) {
+        $Forced_Extension{$extension} = $lang;
+
+        die_unknown_lang($lang, "--force-lang")
+            unless $Recognized_Language_lc{$lang_lc}; 
+
+        $Language_by_Extension{$extension} = $Recognized_Language_lc{$lang_lc};
+    } else {
+        # the scary case--count everything as this language
+        $All_One_Language = $Recognized_Language_lc{$lang_lc};
+    }
+}
+
+foreach my $pair (@opt_script_lang) {
+    my ($lang, $script_name) = split(',', $pair);
+    my $lang_lc = lc $lang;
+    if (!defined $script_name) {
+        die "The --script-lang option requires a comma separated pair of ".
+            "strings.\n";
+    }
+
+    die_unknown_lang($lang, "--script-lang")
+        unless $Recognized_Language_lc{$lang_lc}; 
+
+    $Language_by_Script{$script_name} = $Recognized_Language_lc{$lang_lc};
+}
+
+# If user provided file extensions to ignore, add these to
+# the exclusion list.
+foreach my $ext (map { $_ => 1 } split(/,/, $opt_exclude_ext ) ) {
+    $ext = lc $ext if $ON_WINDOWS;
+    $Not_Code_Extension{$ext} = 1;
+}
+
+# If SQL or --by-file output is requested, keep track of directory names
+# generated by File::Temp::tempdir and used to temporarily hold the results
+# of compressed archives.  Contents of the SQL table 't' will be much
+# cleaner if these meaningless directory names are stripped from the front
+# of files pulled from the archives.
+my %TEMP_DIR = ();
+my $TEMP_OFF =  0;  # Needed for --sdir; keep track of the number of
+                    # scratch directories made in this run to avoid
+                    # file overwrites by multiple extractions to same
+                    # sdir.
+# Also track locations where temporary installations, if necessary, of
+# Algorithm::Diff and/or Regexp::Common are done.  Make sure these 
+# directories are not counted as inputs (ref bug #80 2012-11-23).
+my %TEMP_INST = ();
+
+# invert %Language_by_Script hash to get an easy-to-look-up list of known
+# scripting languages
+my %Script_Language = map { $_ => 1 } values %Language_by_Script ;
+# 1}}}
+# Step 2:  Early exits for display, summation. {{{1
+#
+print_extension_info($opt_show_ext ) if defined $opt_show_ext ;
+print_language_info( $opt_show_lang) if defined $opt_show_lang;
+exit if (defined $opt_show_ext) or (defined $opt_show_lang);
+
+#print "Before glob have [", join(",", @ARGV), "]\n";
+@ARGV = windows_glob(@ARGV) if $ON_WINDOWS;
+#print "after  glob have [", join(",", @ARGV), "]\n";
+
+# filter out archive files if requested to do so
+if (defined $opt_skip_archive) {
+    my @non_archive = ();
+    foreach my $candidate (@ARGV) {
+        if ($candidate !~ m/${opt_skip_archive}$/) {
+            push @non_archive, $candidate;
+
+        } 
+    }
+    @ARGV = @non_archive;
+}
+
+if ($opt_sum_reports and $opt_diff) {
+    my @results = ();
+    if ($opt_list_file) { # read inputs from the list file
+        my @list = read_list_file($opt_list_file);
+        @results = combine_diffs(\@list);
+    } else { # get inputs from the command line
+        @results = combine_diffs(\@ARGV);
+    }
+    if ($opt_report_file) {
+        write_file($opt_report_file, @results);
+    } else {
+        print "\n", join("\n", @results), "\n";
+    }
+    exit;
+}
+if ($opt_sum_reports) {
+    my %Results = ();
+    foreach my $type( "by language", "by report file" ) {
+        my $found_lang = undef; 
+        if ($opt_list_file) { # read inputs from the list file
+            my @list = read_list_file($opt_list_file);
+            $found_lang = combine_results(\@list, 
+                                           $type, 
+                                          \%{$Results{ $type }}, 
+                                          \%Filters_by_Language );
+        } else { # get inputs from the command line
+            $found_lang = combine_results(\@ARGV, 
+                                           $type, 
+                                          \%{$Results{ $type }}, 
+                                          \%Filters_by_Language );
+        }
+        next unless %Results;
+        my $end_time = get_time();
+        my @results  = generate_report($VERSION, $end_time - $start_time,
+                                       $type,
+                                      \%{$Results{ $type }}, \%Scale_Factor);
+        if ($opt_report_file) {
+            my $ext  = ".lang";
+               $ext  = ".file" unless $type eq "by language";
+            next if !$found_lang and  $ext  eq ".lang";
+            write_file($opt_report_file . $ext, @results);
+        } else {
+            print "\n", join("\n", @results), "\n";
+        }
+    }
+    exit;
+}
+if ($opt_write_lang_def) {
+    write_lang_def($opt_write_lang_def   ,
+                  \%Language_by_Extension,
+                  \%Language_by_Script   ,
+                  \%Language_by_File     ,
+                  \%Filters_by_Language  ,
+                  \%Not_Code_Extension   ,
+                  \%Not_Code_Filename    ,
+                  \%Scale_Factor         ,
+                  \%EOL_Continuation_re  ,
+                  );
+    exit;
+}
+if ($opt_show_os) {
+    if ($ON_WINDOWS) {
+        print "Windows\n";
+    } else {
+        print "UNIX\n";
+    }
+    exit;
+}
+# 1}}}
+# Step 3:  Create a list of files to consider. {{{1
+#  a) If inputs are binary archives, first cd to a temp
+#     directory, expand the archive with the user-given
+#     extraction tool, then add the temp directory to
+#     the list of dirs to process.
+#  b) Create a list of every file that might contain source
+#     code.  Ignore binary files, zero-sized files, and
+#     any file in a directory the user says to exclude.
+#  c) Determine the language for each file in the list.
+#
+my @binary_archive = ();
+my $cwd            = cwd();
+if ($opt_extract_with) {
+#print "cwd main = [$cwd]\n";
+    my @extract_location = ();
+    foreach my $bin_file (@ARGV) {
+        my $extract_dir = undef;
+        if ($opt_sdir) {
+            ++$TEMP_OFF;
+            $extract_dir = "$opt_sdir/$TEMP_OFF";
+            File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
+            File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
+        } else {
+            $extract_dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+        }
+        $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
+        print "mkdir $extract_dir\n"  if $opt_v;
+        print "cd    $extract_dir\n"  if $opt_v;
+        chdir $extract_dir;
+        my $bin_file_full_path = "";
+        if (File::Spec->file_name_is_absolute( $bin_file )) {
+            $bin_file_full_path = $bin_file;
+#print "bin_file_full_path (was ful) = [$bin_file_full_path]\n";
+        } else {
+            $bin_file_full_path = File::Spec->catfile( $cwd, $bin_file );
+#print "bin_file_full_path (was rel) = [$bin_file_full_path]\n";
+        }
+        my     $extract_cmd = uncompress_archive_cmd($bin_file_full_path);
+        print  $extract_cmd, "\n" if $opt_v;
+        system $extract_cmd;
+        push @extract_location, $extract_dir;
+        chdir $cwd;
+    }
+    # It is possible that the binary archive itself contains additional
+    # files compressed the same way (true for Java .ear files).  Go
+    # through all the files that were extracted, see if they are binary
+    # archives and try to extract them.  Lather, rinse, repeat.
+    my $binary_archives_exist = 1;
+    my $count_binary_archives = 0;
+    my $previous_count        = 0;
+    my $n_pass                = 0;
+    while ($binary_archives_exist) {
+        @binary_archive = ();
+        foreach my $dir (@extract_location) {
+            find(\&archive_files, $dir);  # populates global @binary_archive
+        }
+        foreach my $archive (@binary_archive) {
+            my $extract_dir = undef;
+            if ($opt_sdir) {
+                ++$TEMP_OFF;
+                $extract_dir = "$opt_sdir/$TEMP_OFF";
+                File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
+                File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
+            } else {
+                $extract_dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+            }
+            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
+            print "mkdir $extract_dir\n"  if $opt_v;
+            print "cd    $extract_dir\n"  if $opt_v;
+            chdir  $extract_dir;
+
+            my     $extract_cmd = uncompress_archive_cmd($archive);
+            print  $extract_cmd, "\n" if $opt_v;
+            system $extract_cmd;
+            push @extract_location, $extract_dir;
+            unlink $archive;  # otherwise will be extracting it forever 
+        }
+        $count_binary_archives = scalar @binary_archive;
+        if ($count_binary_archives == $previous_count) {
+            $binary_archives_exist = 0;
+        }
+        $previous_count = $count_binary_archives;
+    }
+    chdir $cwd;
+
+    @ARGV = @extract_location;
+} else {
+    # see if any of the inputs need to be auto-uncompressed &/or expanded
+    my @updated_ARGS = ();
+    foreach my $Arg (@ARGV) {
+        if (is_dir($Arg)) {
+            push @updated_ARGS, $Arg;
+            next;
+        }
+        my $full_path = "";
+        if (File::Spec->file_name_is_absolute( $Arg )) {
+            $full_path = $Arg;
+        } else {
+            $full_path = File::Spec->catfile( $cwd, $Arg );
+        }
+#print "full_path = [$full_path]\n";
+        my $extract_cmd = uncompress_archive_cmd($full_path);
+        if ($extract_cmd) {
+            my $extract_dir = undef;
+            if ($opt_sdir) {
+                ++$TEMP_OFF;
+                $extract_dir = "$opt_sdir/$TEMP_OFF";
+                File::Path::rmtree($extract_dir) if     is_dir($extract_dir);
+                File::Path::mkpath($extract_dir) unless is_dir($extract_dir);
+            } else {
+                $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+            }
+            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql or $opt_by_file;
+            print "mkdir $extract_dir\n"  if $opt_v;
+            print "cd    $extract_dir\n"  if $opt_v;
+            chdir  $extract_dir;
+            print  $extract_cmd, "\n" if $opt_v;
+            system $extract_cmd;
+            push @updated_ARGS, $extract_dir;
+            chdir $cwd;
+        } else {
+            # this is a conventional, uncompressed, unarchived file
+            # or a directory; keep as-is
+            push @updated_ARGS, $Arg;
+        }
+    }
+    @ARGV = @updated_ARGS;
+
+    # make sure we're not counting any directory containing
+    # temporary installations of Regexp::Common, Algorithm::Diff
+    foreach my $d (sort keys %TEMP_INST) {
+        foreach my $a (@ARGV) {
+            next unless is_dir($a);
+            if ($opt_v > 2) {
+                printf "Comparing %s (location of %s) to input [%s]\n",
+                        $d, $TEMP_INST{$d}, $a;
+            }
+            if ($a eq $d) {
+                die "File::Temp::tempdir chose directory ",
+                    $d, " to install ", $TEMP_INST{$d}, " but this ",
+                    "matches one of your input directories.  Rerun ",
+                    "with --sdir and supply a different temporary ",
+                    "directory for ", $TEMP_INST{$d}, "\n";
+            }
+        }
+    }
+}
+# 1}}}
+my @Errors    = ();
+my @file_list = ();  # global variable updated in files()
+my %Ignored   = ();  # files that are not counted (language not recognized or
+                     # problems reading the file)
+my @Lines_Out = ();
+if ($opt_diff) {
+# Step 4:  Separate code from non-code files.  {{{1
+my @fh            = ();
+my @files_for_set = ();
+# make file lists for each separate argument
+if ($opt_exclude_list_file) {
+    process_exclude_list_file($opt_exclude_list_file, 
+                             \%Exclude_Dir,
+                             \%Ignored);
+}
+for (my $i = 0; $i < scalar @ARGV; $i++) {
+    push @fh, 
+         make_file_list([ $ARGV[$i] ], \%Error_Codes, \@Errors, \%Ignored);
+    @{$files_for_set[$i]} = @file_list;
+    @file_list = ();
+}
+# 1}}}
+# Step 5:  Remove duplicate files.             {{{1
+#
+my %Language           = ();
+my %unique_source_file = ();
+my $n_set = 0;
+foreach my $FH (@fh) {  # loop over each pair of file sets
+    ++$n_set;
+    remove_duplicate_files($FH, 
+                               \%{$Language{$FH}}               , 
+                               \%{$unique_source_file{$FH}}     , 
+                          \%Error_Codes                         , 
+                               \@Errors                         , 
+                               \%Ignored                        );
+    printf "%2d: %8d unique file%s.                          \r", 
+        $n_set,
+        plural_form(scalar keys %unique_source_file) 
+        unless $opt_quiet;
+}
+# 1}}}
+# Step 6:  Count code, comments, blank lines.  {{{1
+#
+my %Results_by_Language = ();
+my %Results_by_File     = ();
+my %Delta_by_Language   = ();
+my %Delta_by_File       = ();
+my $nFiles_added        = 0;
+my $nFiles_removed      = 0;
+my $nFiles_modified     = 0;
+my $nFiles_same         = 0;
+
+foreach (my $F = 0; $F < scalar @fh - 1; $F++) { 
+    # loop over file sets; do diff between set $F to $F+1
+
+    my $nCounted = 0;
+
+    my @file_pairs    = ();
+    my @files_added   = ();
+    my @files_removed = ();
+
+    align_by_pairs(\%{$unique_source_file{$fh[$F  ]}}    , # in
+                   \%{$unique_source_file{$fh[$F+1]}}    , # in
+                   \@files_added                         , # out
+                   \@files_removed                       , # out
+                   \@file_pairs                          , # out
+                   );
+    my %already_counted = (); # already_counted{ filename } = 1
+                              
+    if (!@file_pairs) {
+        # Special case where all files were either added or deleted.
+        # In this case, one of these arrays will be empty: 
+        #   @files_added, @files_removed
+        # so loop over both to cover both cases.
+        my $status = @files_added ? 'added' : 'removed';
+        my $offset = @files_added ? 1       : 0        ;
+        foreach my $file (@files_added, @files_removed) {
+            next unless defined $Language{$fh[$F+$offset]}{$file};
+            my $Lang = $Language{$fh[$F+$offset]}{$file};
+            next if $Lang eq '(unknown)';
+            my ($all_line_count,
+                $blank_count   ,
+                $comment_count ,
+               ) = call_counter($file, $Lang, \@Errors);
+            $already_counted{$file} = 1;
+            my $code_count = $all_line_count-$blank_count-$comment_count;
+            if ($opt_by_file) {
+                $Delta_by_File{$file}{'code'   }{$status} += $code_count   ;
+                $Delta_by_File{$file}{'blank'  }{$status} += $blank_count  ;
+                $Delta_by_File{$file}{'comment'}{$status} += $comment_count;
+                $Delta_by_File{$file}{'lang'   }{$status}  = $Lang         ;
+                $Delta_by_File{$file}{'nFiles' }{$status} += 1             ;
+            }
+            $Delta_by_Language{$Lang}{'code'   }{$status} += $code_count   ;
+            $Delta_by_Language{$Lang}{'blank'  }{$status} += $blank_count  ;
+            $Delta_by_Language{$Lang}{'comment'}{$status} += $comment_count;
+            $Delta_by_Language{$Lang}{'nFiles' }{$status} += 1             ;
+        }
+    }
+   #use Data::Dumper::Simple;
+   #use Data::Dumper;
+   #print Dumper(\@files_added, \@files_removed, \@file_pairs);
+    my @alignment = (); # only  used if --diff-alignment
+#print "after align_by_pairs:\n";
+
+#print "added:\n";
+    push @alignment, sprintf "Files added: %d\n", scalar @files_added
+        if $opt_diff_alignment;
+    foreach my $f (@files_added) {
+        next if $already_counted{$f};
+#printf "%10s -> %s\n", $f, $Language{$fh[$F+1]}{$f};
+        # Don't proceed unless the file (both L and R versions)
+        # is in a known language.
+        next if $Language{$fh[$F+1]}{$f} eq "(unknown)";
+        next if $Exclude_Language{$Language{$fh[$F+1]}{$f}};
+        push @alignment, sprintf "  + %s ; %s\n", $f, $Language{$fh[$F+1]}{$f}
+            if $opt_diff_alignment;
+        ++$Delta_by_Language{ $Language{$fh[$F+1]}{$f} }{'nFiles'}{'added'};
+        # Additionally, add contents of file $f to 
+        #        Delta_by_File{$f}{comment/blank/code}{'added'}
+        #        Delta_by_Language{$lang}{comment/blank/code}{'added'}
+        my ($all_line_count,
+            $blank_count   ,
+            $comment_count ,
+           ) = call_counter($f, $Language{$fh[$F+1]}{$f}, \@Errors);
+        $Delta_by_Language{ $Language{$fh[$F+1]}{$f} }{'comment'}{'added'} +=
+            $comment_count;
+        $Delta_by_Language{ $Language{$fh[$F+1]}{$f} }{'blank'}{'added'}   +=
+            $blank_count;
+        $Delta_by_Language{ $Language{$fh[$F+1]}{$f} }{'code'}{'added'}    +=
+            $all_line_count - $blank_count - $comment_count;
+        $Delta_by_File{ $f }{'comment'}{'added'} = $comment_count;
+        $Delta_by_File{ $f }{'blank'}{'added'}   = $blank_count;
+        $Delta_by_File{ $f }{'code'}{'added'}    = 
+            $all_line_count - $blank_count - $comment_count;
+    }
+    push @alignment, "\n";
+
+#print "removed:\n";
+    push @alignment, sprintf "Files removed: %d\n", scalar @files_removed
+        if $opt_diff_alignment;
+    foreach my $f (@files_removed) {
+        next if $already_counted{$f};
+        # Don't proceed unless the file (both L and R versions)
+        # is in a known language.
+        next if $Language{$fh[$F  ]}{$f} eq "(unknown)";
+        next if $Exclude_Language{$Language{$fh[$F  ]}{$f}};
+        ++$Delta_by_Language{ $Language{$fh[$F  ]}{$f} }{'nFiles'}{'removed'};
+        push @alignment, sprintf "  - %s ; %s\n", $f, $Language{$fh[$F]}{$f}
+            if $opt_diff_alignment;
+#printf "%10s -> %s\n", $f, $Language{$fh[$F  ]}{$f};
+        # Additionally, add contents of file $f to 
+        #        Delta_by_File{$f}{comment/blank/code}{'removed'}
+        #        Delta_by_Language{$lang}{comment/blank/code}{'removed'}
+        my ($all_line_count,
+            $blank_count   ,
+            $comment_count ,
+           ) = call_counter($f, $Language{$fh[$F  ]}{$f}, \@Errors);
+        $Delta_by_Language{ $Language{$fh[$F  ]}{$f} }{'comment'}{'removed'} +=
+            $comment_count;
+        $Delta_by_Language{ $Language{$fh[$F  ]}{$f} }{'blank'}{'removed'}   +=
+            $blank_count;
+        $Delta_by_Language{ $Language{$fh[$F  ]}{$f} }{'code'}{'removed'}    +=
+            $all_line_count - $blank_count - $comment_count;
+        $Delta_by_File{ $f }{'comment'}{'removed'} = $comment_count;
+        $Delta_by_File{ $f }{'blank'}{'removed'}   = $blank_count;
+        $Delta_by_File{ $f }{'code'}{'removed'}    = 
+            $all_line_count - $blank_count - $comment_count;
+    }
+    push @alignment, "\n";
+
+    my $alignment_pairs_index = scalar @alignment;
+    my $n_file_pairs_compared = 0;
+    # Don't know ahead of time how many file pairs will be compared
+    # since duplicates are weeded out below.  The answer is
+    # scalar @file_pairs only if there are no duplicates.
+    push @alignment, sprintf "File pairs compared: UPDATE_ME\n"
+        if $opt_diff_alignment;
+
+    foreach my $pair (@file_pairs) {
+        my $file_L = $pair->[0];
+        my $file_R = $pair->[1];
+        my $Lang_L = $Language{$fh[$F  ]}{$file_L};
+        my $Lang_R = $Language{$fh[$F+1]}{$file_R};
+#print "main step 6 file_L=$file_L    file_R=$file_R\n";
+        ++$nCounted;
+        printf "Counting:  %d\r", $nCounted 
+            unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
+        next if $Ignored{$file_L};
+
+        # filter out excluded or unrecognized languages
+        if ($Exclude_Language{$Lang_L} or $Exclude_Language{$Lang_R}) {
+            $Ignored{$file_L} = "--exclude-lang=$Lang_L}";
+            $Ignored{$file_R} = "--exclude-lang=$Lang_R}";
+            next;
+        }
+        my $not_Filters_by_Language_Lang_LR = 0;
+        if ($PERL_516) {
+            if (!(@{$Filters_by_Language{$Lang_L} }) or
+                !(@{$Filters_by_Language{$Lang_R} })) {
+                $not_Filters_by_Language_Lang_LR = 1;
+            }
+        } else {
+            if (!defined(@{$Filters_by_Language{$Lang_L} }) or
+                !defined(@{$Filters_by_Language{$Lang_R} })) {
+                $not_Filters_by_Language_Lang_LR = 1;
+            }
+        }
+        if ($not_Filters_by_Language_Lang_LR) {
+            if (($Lang_L eq "(unknown)") or ($Lang_R eq "(unknown)")) {
+                $Ignored{$fh[$F  ]}{$file_L} = "language unknown (#1)";
+                $Ignored{$fh[$F+1]}{$file_R} = "language unknown (#1)";
+            } else {
+                $Ignored{$fh[$F  ]}{$file_L} = "missing Filters_by_Language{$Lang_L}";
+                $Ignored{$fh[$F+1]}{$file_R} = "missing Filters_by_Language{$Lang_R}";
+            }
+            next;
+        }
+
+#print "DIFF($file_L, $file_R)\n";
+        # step 0: compare the two files' contents 
+        chomp ( my @lines_L = read_file($file_L) );
+        chomp ( my @lines_R = read_file($file_R) );
+        my $language_file_L = "";
+        if (defined $Language{$fh[$F]}{$file_L}) {
+            $language_file_L = $Language{$fh[$F]}{$file_L};
+        } else {
+            # files $file_L and $file_R do not contain known language
+            next;
+        }
+        my $contents_are_same = 1;
+        if (scalar @lines_L == scalar @lines_R) {
+            # same size, must compare line-by-line
+            for (my $i = 0; $i < scalar @lines_L; $i++) {
+                if ($lines_L[$i] ne $lines_R[$i]) {
+                    $contents_are_same = 0;
+                    last;
+                }
+            }
+            if ($contents_are_same) {
+                ++$Delta_by_Language{$language_file_L}{'nFiles'}{'same'};
+            } else {
+                ++$Delta_by_Language{$language_file_L}{'nFiles'}{'modified'};
+            }
+        } else {
+            $contents_are_same = 0;
+            # different sizes, contents have changed
+            ++$Delta_by_Language{$language_file_L}{'nFiles'}{'modified'};
+        }
+        if ($opt_diff_alignment) {
+            my $str =  "$file_L | $file_R ; $language_file_L";
+            if ($contents_are_same) {
+                push @alignment, "  == $str";
+            } else {
+                push @alignment, "  != $str";
+            }
+            ++$n_file_pairs_compared;
+        }
+
+        # step 1: identify comments in both files
+#print "Diff blank removal L language= $Lang_L";
+#print " scalar(lines_L)=", scalar @lines_L, "\n";
+        my @original_minus_blanks_L 
+                    = rm_blanks(  \@lines_L, $Lang_L, \%EOL_Continuation_re);
+#print "1: scalar(original_minus_blanks_L)=", scalar @original_minus_blanks_L, "\n";
+        @lines_L    = @original_minus_blanks_L;
+#print "2: scalar(lines_L)=", scalar @lines_L, "\n";
+        @lines_L    = add_newlines(\@lines_L); # compensate for rm_comments()
+        @lines_L    = rm_comments( \@lines_L, $Lang_L, $file_L,
+                                   \%EOL_Continuation_re);
+#print "3: scalar(lines_L)=", scalar @lines_L, "\n";
+
+#print "Diff blank removal R language= $Lang_R\n";
+        my @original_minus_blanks_R 
+                    = rm_blanks(  \@lines_R, $Lang_R, \%EOL_Continuation_re);
+        @lines_R    = @original_minus_blanks_R;
+        @lines_R    = add_newlines(\@lines_R); # taken away by rm_comments()
+        @lines_R    = rm_comments( \@lines_R, $Lang_R, $file_R,
+                                   \%EOL_Continuation_re);
+
+        my (@diff_LL, @diff_LR, );
+        array_diff( $file_L                  ,   # in
+                   \@original_minus_blanks_L ,   # in
+                   \@lines_L                 ,   # in
+                   "comment"                 ,   # in
+                   \@diff_LL, \@diff_LR      ,   # out
+                   \@Errors);                    # in/out
+
+        my (@diff_RL, @diff_RR, );
+        array_diff( $file_R                  ,   # in
+                   \@original_minus_blanks_R ,   # in
+                   \@lines_R                 ,   # in
+                   "comment"                 ,   # in
+                   \@diff_RL, \@diff_RR      ,   # out
+                   \@Errors);                    # in/out
+        # each line of each file is now classified as
+        # code or comment
+
+#use Data::Dumper; 
+#print Dumper("diff_LL", \@diff_LL, "diff_LR", \@diff_LR, );
+#print Dumper("diff_RL", \@diff_RL, "diff_RR", \@diff_RR, );
+#die;
+        # step 2: separate code from comments for L and R files
+        my @code_L = ();
+        my @code_R = ();
+        my @comm_L = ();
+        my @comm_R = ();
+        foreach my $line_info (@diff_LL) {
+            if      ($line_info->{'type'} eq "code"   ) {
+                push @code_L, $line_info->{char};
+            } elsif ($line_info->{'type'} eq "comment") {
+                push @comm_L, $line_info->{char};
+            } else {
+                die "Diff unexpected line type ",
+                    $line_info->{'type'}, "for $file_L line ",
+                    $line_info->{'lnum'};
+            }
+        }
+        foreach my $line_info (@diff_RL) {
+            if      ($line_info->{type} eq "code"   ) {
+                push @code_R, $line_info->{'char'};
+            } elsif ($line_info->{type} eq "comment") {
+                push @comm_R, $line_info->{'char'};
+            } else {
+                die "Diff unexpected line type ",
+                    $line_info->{'type'}, "for $file_R line ",
+                    $line_info->{'lnum'};
+            }
+        }
+
+        if ($opt_ignore_whitespace) {
+            # strip all whitespace from each line of source code
+            # and comments then use these stripped arrays in diffs
+            foreach (@code_L) { s/\s+//g }
+            foreach (@code_R) { s/\s+//g }
+            foreach (@comm_L) { s/\s+//g }
+            foreach (@comm_R) { s/\s+//g }
+        }
+        if ($opt_ignore_case) {
+            # change all text to lowercase in diffs
+            foreach (@code_L) { $_ = lc }
+            foreach (@code_R) { $_ = lc }
+            foreach (@comm_L) { $_ = lc }
+            foreach (@comm_R) { $_ = lc }
+        }
+        # step 3: compute code diffs
+        array_diff("$file_L v. $file_R"   ,   # in
+                   \@code_L               ,   # in
+                   \@code_R               ,   # in
+                   "revision"             ,   # in
+                   \@diff_LL, \@diff_LR   ,   # out
+                   \@Errors);                 # in/out
+#print Dumper("diff_LL", \@diff_LL, "diff_LR", \@diff_LR, );
+#print Dumper("diff_LR", \@diff_LR);
+        foreach my $line_info (@diff_LR) {
+            my $status = $line_info->{'desc'}; # same|added|removed|modified
+            ++$Delta_by_Language{$Lang_L}{'code'}{$status};
+            if ($opt_by_file) {
+                ++$Delta_by_File{$file_L}{'code'}{$status};
+            }
+        }
+#use Data::Dumper;
+#print Dumper("code diffs:", \@diff_LL, \@diff_LR);
+
+        # step 4: compute comment diffs
+        array_diff("$file_L v. $file_R"   ,   # in
+                   \@comm_L               ,   # in
+                   \@comm_R               ,   # in
+                   "revision"             ,   # in
+                   \@diff_LL, \@diff_LR   ,   # out
+                   \@Errors);                 # in/out
+#print Dumper("comment diff_LR", \@diff_LR);
+        foreach my $line_info (@diff_LR) {
+            my $status = $line_info->{'desc'}; # same|added|removed|modified
+            ++$Delta_by_Language{$Lang_L}{'comment'}{$status};
+            if ($opt_by_file) {
+                ++$Delta_by_File{$file_L}{'comment'}{$status};
+            }
+        }
+#print Dumper("comment diffs:", \@diff_LL, \@diff_LR);
+#die; here=  need to save original line number in diff result for html display
+
+        # step 5: compute difference in blank lines (kind of pointless)
+        next if $Lang_L eq '(unknown)' or 
+                $Lang_R eq '(unknown)';
+        my ($all_line_count_L,
+            $blank_count_L   ,
+            $comment_count_L ,
+           ) = call_counter($file_L, $Lang_L, \@Errors);
+
+        my ($all_line_count_R,
+            $blank_count_R   ,
+            $comment_count_R ,
+           ) = call_counter($file_R, $Lang_R, \@Errors);
+
+        if ($blank_count_L <  $blank_count_R) {
+            my $D = $blank_count_R - $blank_count_L;
+            $Delta_by_Language{$Lang_L}{'blank'}{'added'}   += $D;
+        } else {
+            my $D = $blank_count_L - $blank_count_R;
+            $Delta_by_Language{$Lang_L}{'blank'}{'removed'} += $D;
+        }
+        if ($opt_by_file) {
+            if ($blank_count_L <  $blank_count_R) {
+                my $D = $blank_count_R - $blank_count_L;
+                $Delta_by_File{$file_L}{'blank'}{'added'}   += $D;
+            } else {
+                my $D = $blank_count_L - $blank_count_R;
+                $Delta_by_File{$file_L}{'blank'}{'removed'} += $D;
+            }
+        }
+
+        my $code_count_L = $all_line_count_L-$blank_count_L-$comment_count_L;
+        if ($opt_by_file) {
+            $Results_by_File{$file_L}{'code'   } = $code_count_L    ;
+            $Results_by_File{$file_L}{'blank'  } = $blank_count_L   ;
+            $Results_by_File{$file_L}{'comment'} = $comment_count_L ;
+            $Results_by_File{$file_L}{'lang'   } = $Lang_L          ;
+            $Results_by_File{$file_L}{'nFiles' } = 1                ;
+        } else {
+            $Results_by_File{$file_L} = 1;  # just keep track of counted files
+        }
+   
+        $Results_by_Language{$Lang_L}{'nFiles'}++;
+        $Results_by_Language{$Lang_L}{'code'}    += $code_count_L   ;
+        $Results_by_Language{$Lang_L}{'blank'}   += $blank_count_L  ;
+        $Results_by_Language{$Lang_L}{'comment'} += $comment_count_L;
+    }
+    if ($opt_diff_alignment) {
+        $alignment[$alignment_pairs_index] =~ s/UPDATE_ME/$n_file_pairs_compared/;
+        write_file($opt_diff_alignment, @alignment);
+    }
+
+}
+#use Data::Dumper;
+#print Dumper("Delta_by_Language:"  , \%Delta_by_Language);
+#print Dumper("Results_by_Language:", \%Results_by_Language);
+#print Dumper("Delta_by_File:"      , \%Delta_by_File);
+#print Dumper("Results_by_File:"    , \%Results_by_File);
+#die;
+my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
+write_file($opt_ignored, @ignored_reasons   ) if $opt_ignored;
+write_file($opt_counted, sort keys %Results_by_File) if $opt_counted;
+# 1}}}
+# Step 7:  Assemble results.                   {{{1
+#
+my $end_time = get_time();
+printf "%8d file%s ignored.                           \n", 
+    plural_form(scalar keys %Ignored) unless $opt_quiet;
+print_errors(\%Error_Codes, \@Errors) if @Errors;
+if (!%Delta_by_Language) {
+    print "Nothing to count.\n";
+    exit;
+}
+
+if ($opt_by_file) {
+    @Lines_Out = diff_report($VERSION, get_time() - $start_time,
+                            "by file",
+                            \%Delta_by_File, \%Scale_Factor);
+} else {
+    @Lines_Out = diff_report($VERSION, get_time() - $start_time,
+                            "by language",
+                            \%Delta_by_Language, \%Scale_Factor);
+}
+
+# 1}}}
+} else {
+# Step 4:  Separate code from non-code files.  {{{1
+my $fh = 0;
+if ($opt_list_file) {
+    my @list = read_list_file($opt_list_file);
+    $fh = make_file_list(\@list, \%Error_Codes, \@Errors, \%Ignored);
+} else {
+    $fh = make_file_list(\@ARGV, \%Error_Codes, \@Errors, \%Ignored);
+    #     make_file_list populates global variable @file_list via call to 
+    #     File::Find's find() which in turn calls files()
+}
+if ($opt_exclude_list_file) {
+    process_exclude_list_file($opt_exclude_list_file, 
+                             \%Exclude_Dir,
+                             \%Ignored);
+}
+if ($opt_skip_win_hidden and $ON_WINDOWS) {
+    my @file_list_minus_hidded = ();
+    # eval code to run on Unix without 'missing Win32::File module' error.
+    my $win32_file_invocation = '
+        use Win32::File;
+        foreach my $F (@file_list) {
+            my $attr = undef;
+            Win32::File::GetAttributes($F, $attr);
+            if ($attr & HIDDEN) {
+                $Ignored{$F} = "Windows hidden file";
+                print "Ignoring $F since it is a Windows hidden file\n" 
+                    if $opt_v > 1;
+            } else {
+                push @file_list_minus_hidded, $F;
+            }
+        }';
+    eval $win32_file_invocation;
+    @file_list = @file_list_minus_hidded;
+}
+#printf "%8d file%s excluded.                     \n", 
+#   plural_form(scalar keys %Ignored) 
+#   unless $opt_quiet;
+# die print ": ", join("\n: ", @file_list), "\n";
+# 1}}}
+# Step 5:  Remove duplicate files.             {{{1
+#
+my %Language           = ();
+my %unique_source_file = ();
+remove_duplicate_files($fh                          ,   # in 
+                           \%Language               ,   # out
+                           \%unique_source_file     ,   # out
+                      \%Error_Codes                 ,   # in
+                           \@Errors                 ,   # out
+                           \%Ignored                );  # out
+printf "%8d unique file%s.                              \n", 
+    plural_form(scalar keys %unique_source_file) 
+    unless $opt_quiet;
+# 1}}}
+# Step 6:  Count code, comments, blank lines.  {{{1
+#
+
+my %Results_by_Language = ();
+my %Results_by_File     = ();
+my $nCounted = 0;
+foreach my $file (sort keys %unique_source_file) {
+    ++$nCounted;
+    printf "Counting:  %d\r", $nCounted 
+        unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
+    next if $Ignored{$file};
+    if ($Exclude_Language{$Language{$file}}) {
+        $Ignored{$file} = "--exclude-lang=$Language{$file}";
+        next;
+    }
+    my $Filters_by_Language_Language_file = !defined @{$Filters_by_Language{$Language{$file}} };
+    if ($Filters_by_Language_Language_file) {
+        if ($Language{$file} eq "(unknown)") {
+            $Ignored{$file} = "language unknown (#1)";
+        } else {
+            $Ignored{$file} = "missing Filters_by_Language{$Language{$file}}";
+        }
+        next;
+    }
+
+    my ($all_line_count,
+        $blank_count   ,
+        $comment_count ,
+       ) = call_counter($file, $Language{$file}, \@Errors);
+    my $code_count = $all_line_count - $blank_count - $comment_count;
+    if ($opt_by_file) {
+        $Results_by_File{$file}{'code'   } = $code_count     ;
+        $Results_by_File{$file}{'blank'  } = $blank_count    ;
+        $Results_by_File{$file}{'comment'} = $comment_count  ;
+        $Results_by_File{$file}{'lang'   } = $Language{$file};
+        $Results_by_File{$file}{'nFiles' } = 1;
+    } else {
+        $Results_by_File{$file} = 1;  # just keep track of counted files
+    }
+
+    $Results_by_Language{$Language{$file}}{'nFiles'}++;
+    $Results_by_Language{$Language{$file}}{'code'}    += $code_count   ;
+    $Results_by_Language{$Language{$file}}{'blank'}   += $blank_count  ;
+    $Results_by_Language{$Language{$file}}{'comment'} += $comment_count;
+}
+my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
+write_file($opt_ignored, @ignored_reasons   ) if $opt_ignored;
+write_file($opt_counted, sort keys %Results_by_File) if $opt_counted;
+# 1}}}
+# Step 7:  Assemble results.                   {{{1
+#
+my $end_time = get_time();
+printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored) 
+    unless $opt_quiet;
+print_errors(\%Error_Codes, \@Errors) if @Errors;
+exit unless %Results_by_Language;
+
+generate_sql($end_time - $start_time,
+            \%Results_by_File, \%Scale_Factor) if $opt_sql;
+
+exit if $skip_generate_report;
+if      ($opt_by_file_by_lang) {
+    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
+                                      "by file",
+                                      \%Results_by_File,    \%Scale_Factor);
+    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
+                                      "by language",
+                                      \%Results_by_Language, \%Scale_Factor);
+} elsif ($opt_by_file) {
+    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
+                                      "by file",
+                                      \%Results_by_File,    \%Scale_Factor);
+} else {
+    push @Lines_Out, generate_report( $VERSION, $end_time - $start_time,
+                                      "by language",
+                                      \%Results_by_Language, \%Scale_Factor);
+}
+# 1}}}
+}
+if ($opt_report_file) { write_file($opt_report_file, @Lines_Out); } 
+else                  { print "\n", join("\n", @Lines_Out), "\n"; }
+
+sub process_exclude_list_file {              # {{{1
+    my ($list_file      , # in
+        $rh_exclude_dir , # out
+        $rh_ignored     , # out
+       ) = @_;
+    print "-> process_exclude_list_file($list_file)\n" if $opt_v > 2;
+    # reject a specific set of files and/or directories
+    my @reject_list   = read_list_file($list_file);
+    my @file_reject_list = ();
+    foreach my $F_or_D (@reject_list) {
+        if (is_dir($F_or_D)) {
+            $rh_exclude_dir->{$F_or_D} = 1;
+        } elsif (is_file($F_or_D)) {
+            push @file_reject_list, $F_or_D;
+        }
+    }
+
+    # Normalize file names for better comparison.
+    my %normalized_input   = normalize_file_names(@file_list);
+    my %normalized_reject  = normalize_file_names(@file_reject_list);
+    my %normalized_exclude = normalize_file_names(keys %{$rh_exclude_dir});
+    foreach my $F (keys %normalized_input) {
+        if ($normalized_reject{$F} or is_excluded($F, \%normalized_exclude)) {
+            my $orig_F = $normalized_input{$F};
+            $rh_ignored->{$orig_F} = "listed in exclusion file $opt_exclude_list_file";
+            print "Ignoring $orig_F because it appears in $opt_exclude_list_file\n" 
+                if $opt_v > 1;
+        }
+    }
+    print "<- process_exclude_list_file\n" if $opt_v > 2;
+} # 1}}}
+sub combine_results {                        # {{{1
+    # returns 1 if the inputs are categorized by language
+    #         0 if no identifiable language was found
+    my ($ra_report_files, # in
+        $report_type    , # in  "by language" or "by report file"
+        $rhh_count      , # out count{TYPE}{nFiles|code|blank|comment|scaled}
+        $rhaa_Filters_by_Language , # in
+       ) = @_;
+
+    print "-> combine_results(report_type=$report_type)\n" if $opt_v > 2;
+    my $found_language = 0;
+
+    foreach my $file (@{$ra_report_files}) {
+        my $IN = new IO::File $file, "r";
+        if (!defined $IN) {
+            warn "Unable to read $file; ignoring.\n";
+            next;
+        }
+        while (<$IN>) {
+            next if /^(http|Language|SUM|-----)/;
+            if (!$opt_by_file  and
+                m{^(.*?)\s+         # language
+                   (\d+)\s+         # files
+                   (\d+)\s+         # blank
+                   (\d+)\s+         # comments
+                   (\d+)\s+         # code
+                   (                #    next four entries missing with -nno3
+                   x\s+             # x
+                   \d+\.\d+\s+      # scale
+                   =\s+             # =
+                   (\d+\.\d+)\s*    # scaled code
+                   )?
+                   $}x) {
+                if ($report_type eq "by language") {
+                    if ($PERL_516) {
+                        next unless         @{$rhaa_Filters_by_Language->{$1}};
+                    } else {
+                        next unless defined @{$rhaa_Filters_by_Language->{$1}};
+                    }
+                    # above test necessary to avoid trying to sum reports
+                    # of reports (which have no language breakdown).
+                    $found_language = 1;
+                    $rhh_count->{$1   }{'nFiles' } += $2;
+                    $rhh_count->{$1   }{'blank'  } += $3;
+                    $rhh_count->{$1   }{'comment'} += $4;
+                    $rhh_count->{$1   }{'code'   } += $5;
+                    $rhh_count->{$1   }{'scaled' } += $7 if $opt_3;
+                } else {
+                    $rhh_count->{$file}{'nFiles' } += $2;
+                    $rhh_count->{$file}{'blank'  } += $3;
+                    $rhh_count->{$file}{'comment'} += $4;
+                    $rhh_count->{$file}{'code'   } += $5;
+                    $rhh_count->{$file}{'scaled' } += $7 if $opt_3;
+                }
+            } elsif ($opt_by_file  and
+                m{^(.*?)\s+         # language
+                   (\d+)\s+         # blank
+                   (\d+)\s+         # comments
+                   (\d+)\s+         # code
+                   (                #    next four entries missing with -nno3
+                   x\s+             # x
+                   \d+\.\d+\s+      # scale
+                   =\s+             # =
+                   (\d+\.\d+)\s*    # scaled code
+                   )?
+                   $}x) {
+                if ($report_type eq "by language") {
+                    next unless %{$rhaa_Filters_by_Language->{$1}};
+                    # above test necessary to avoid trying to sum reports
+                    # of reports (which have no language breakdown).
+                    $found_language = 1;
+                    $rhh_count->{$1   }{'nFiles' } +=  1;
+                    $rhh_count->{$1   }{'blank'  } += $2;
+                    $rhh_count->{$1   }{'comment'} += $3;
+                    $rhh_count->{$1   }{'code'   } += $4;
+                    $rhh_count->{$1   }{'scaled' } += $6 if $opt_3;
+                } else {
+                    $rhh_count->{$file}{'nFiles' } +=  1;
+                    $rhh_count->{$file}{'blank'  } += $2;
+                    $rhh_count->{$file}{'comment'} += $3;
+                    $rhh_count->{$file}{'code'   } += $4;
+                    $rhh_count->{$file}{'scaled' } += $6 if $opt_3;
+                }
+            }
+        }
+    }
+    print "<- combine_results\n" if $opt_v > 2;
+    return $found_language;
+} # 1}}}
+sub diff_report     {                        # {{{1
+    # returns an array of lines containing the results
+    print "-> diff_report\n" if $opt_v > 2;
+
+    if ($opt_xml or $opt_yaml) {
+        print "<- diff_report\n" if $opt_v > 2;
+        return diff_xml_yaml_report(@_) 
+    } elsif ($opt_csv) {
+        print "<- diff_report\n" if $opt_v > 2;
+        return diff_csv_report(@_) 
+    }
+
+    my ($version    , # in
+        $elapsed_sec, # in
+        $report_type, # in  "by language" | "by report file" | "by file"
+        $rhhh_count , # in  count{TYPE}{nFiles|code|blank|comment}{a|m|r|s}
+        $rh_scale   , # in
+       ) = @_;
+
+#use Data::Dumper;
+#print "diff_report: ", Dumper($rhhh_count), "\n";
+    my @results       = ();
+
+    my $languages     = ();
+    my %sum           = (); # sum{nFiles|blank|comment|code}{same|modified|added|removed}
+    my $max_len       = 0;
+    foreach my $language (keys %{$rhhh_count}) {
+        foreach my $V (qw(nFiles blank comment code)) {
+            foreach my $S (qw(added same modified removed)) {
+                $rhhh_count->{$language}{$V}{$S} = 0 unless
+                    defined $rhhh_count->{$language}{$V}{$S};
+                $sum{$V}{$S}  += $rhhh_count->{$language}{$V}{$S};
+            }
+        }
+        $max_len      = length($language) if length($language) > $max_len;
+    }
+    my $column_1_offset = 0;
+       $column_1_offset = $max_len - 17 if $max_len > 17;
+    $elapsed_sec = 0.5 unless $elapsed_sec;
+
+    my $spacing_0 = 23;
+    my $spacing_1 = 13;
+    my $spacing_2 =  9;
+    my $spacing_3 = 17;
+    if (!$opt_3) {
+        $spacing_1 = 19;
+        $spacing_2 = 14;
+        $spacing_3 = 28;
+    }
+    $spacing_0 += $column_1_offset;
+    $spacing_1 += $column_1_offset;
+    $spacing_3 += $column_1_offset;
+    my %Format = (
+        '1' => { 'xml' => 'name="%s" ',
+                 'txt' => "\%-${spacing_0}s ",
+               },
+        '2' => { 'xml' => 'name="%s" ',
+                 'txt' => "\%-${spacing_3}s ",
+               },
+        '3' => { 'xml' => 'files_count="%d" ',
+                 'txt' => '%5d ',
+               },
+        '4' => { 'xml' => 'blank="%d" comment="%d" code="%d" ',
+                 'txt' => "\%${spacing_2}d \%${spacing_2}d \%${spacing_2}d",
+               },
+        '5' => { 'xml' => 'factor="%.2f" scaled="%.2f" ',
+                 'txt' => ' x %6.2f = %14.2f',
+               },
+    );
+    my $Style = "txt";
+       $Style = "xml" if $opt_xml ;
+       $Style = "xml" if $opt_yaml;  # not a typo; just set to anything but txt
+       $Style = "xml" if $opt_csv ;  # not a typo; just set to anything but txt
+
+    my $hyphen_line = sprintf "%s", '-' x (79 + $column_1_offset);
+       $hyphen_line = sprintf "%s", '-' x (68 + $column_1_offset) 
+            if (!$opt_3) and (68 + $column_1_offset) > 79;
+    my $data_line  = "";
+    my $first_column;
+    my $BY_LANGUAGE = 0;
+    my $BY_FILE     = 0;
+    if      ($report_type eq "by language") {
+        $first_column = "Language";
+        $BY_LANGUAGE  = 1;
+    } elsif ($report_type eq "by file")     {
+        $first_column = "File";
+        $BY_FILE      = 1;
+    } else {
+        $first_column = "Report File";
+    }
+
+    my $header_line  = sprintf "%s v %s", $URL, $version;
+    my $sum_files    = 1;
+    my $sum_lines    = 1;
+       $header_line .= sprintf("  T=%.2f s (%.1f files/s, %.1f lines/s)",
+                        $elapsed_sec           ,
+                        $sum_files/$elapsed_sec,
+                        $sum_lines/$elapsed_sec) unless $opt_sum_reports;
+    if ($Style eq "txt") {
+        push @results, output_header($header_line, $hyphen_line, $BY_FILE);
+    } elsif ($Style eq "csv") {
+        die "csv";
+    }
+
+    # column headers
+    if (!$opt_3 and $BY_FILE) {
+        my $spacing_n = $spacing_1 - 11;
+        $data_line  = sprintf "%-${spacing_n}s" , $first_column;
+    } else {
+        $data_line  = sprintf "%-${spacing_1}s ", $first_column;
+    }
+    if ($BY_FILE) {
+        $data_line .= sprintf "%${spacing_2}s"   , ""     ;
+    } else {
+        $data_line .= sprintf "%${spacing_2}s "  , "files";
+    }
+    $data_line .= sprintf "%${spacing_2}s %${spacing_2}s %${spacing_2}s",
+        "blank"         ,
+        "comment"       ,
+        "code";
+
+    if ($Style eq "txt") {
+        push @results, $data_line;
+        push @results, $hyphen_line;
+    }
+
+####foreach my $lang_or_file (keys %{$rhhh_count}) {
+####    $rhhh_count->{$lang_or_file}{'code'} = 0 unless 
+####        defined $rhhh_count->{$lang_or_file}{'code'};
+####}
+    foreach my $lang_or_file (sort {
+                                 $rhhh_count->{$b}{'code'} <=>
+                                 $rhhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhhh_count}) {
+
+        if ($BY_FILE) {
+            push @results, rm_leading_tempdir($lang_or_file, \%TEMP_DIR);
+        } else {
+            push @results, $lang_or_file;
+        }
+        foreach my $S (qw(same modified added removed)) {
+            my $indent = $spacing_1 - 2;
+            my $line .= sprintf " %-${indent}s", $S;
+            if ($BY_FILE) {
+                $line .= sprintf "   ";
+            } else {
+                $line .= sprintf "  %${spacing_2}s", $rhhh_count->{$lang_or_file}{'nFiles'}{$S};
+            }
+            $line .= sprintf " %${spacing_2}s %${spacing_2}s %${spacing_2}s",
+                $rhhh_count->{$lang_or_file}{'blank'}{$S}   ,
+                $rhhh_count->{$lang_or_file}{'comment'}{$S} ,
+                $rhhh_count->{$lang_or_file}{'code'}{$S}    ;
+            push @results, $line;
+        }
+    }
+    push @results, "-" x 79;
+    push @results, "SUM:";
+    foreach my $S (qw(same modified added removed)) {
+        my $indent = $spacing_1 - 2;
+        my $line .= sprintf " %-${indent}s", $S;
+            if ($BY_FILE) {
+                $line .= sprintf "   ";
+            } else {
+                $line .= sprintf "  %${spacing_2}s", $sum{'nFiles'}{$S};
+            }
+        $line .= sprintf " %${spacing_2}s %${spacing_2}s %${spacing_2}s",
+            $sum{'blank'}{$S}   ,
+            $sum{'comment'}{$S} ,
+            $sum{'code'}{$S}    ;
+        push @results, $line;
+    }
+    push @results, "-" x 79;
+    write_xsl_file() if $opt_xsl and $opt_xsl eq $CLOC_XSL;
+    print "<- diff_report\n" if $opt_v > 2;
+
+    return @results;
+} # 1}}}
+sub xml_or_yaml_header {                     # {{{1
+    my ($URL, $version, $elapsed_sec, $sum_files, $sum_lines, $by_file) = @_;
+    print "-> xml_or_yaml_header\n" if $opt_v > 2;
+    my $header      = "";
+    my $file_rate   = $sum_files/$elapsed_sec;
+    my $line_rate   = $sum_lines/$elapsed_sec;
+    my $type        = ""; 
+       $type        = "diff_" if $opt_diff;
+    my $report_file = "";
+    if ($opt_report_file) {
+        if ($opt_sum_reports) {
+            if ($by_file) {
+                $report_file = "  <report_file>$opt_report_file.file</report_file>"
+            } else {
+                $report_file = "  <report_file>$opt_report_file.lang</report_file>"
+            }
+        } else {
+            $report_file = "  <report_file>$opt_report_file</report_file>"
+        }
+    }
+    if ($opt_xml) {
+        $header = "<?xml version=\"1.0\"?>";
+        $header .= "\n<?xml-stylesheet type=\"text/xsl\" href=\"" . $opt_xsl . "\"?>" if $opt_xsl;
+        $header .= "<${type}results>
+<header>
+  <cloc_url>$URL</cloc_url>
+  <cloc_version>$version</cloc_version>
+  <elapsed_seconds>$elapsed_sec</elapsed_seconds>
+  <n_files>$sum_files</n_files>
+  <n_lines>$sum_lines</n_lines>
+  <files_per_second>$file_rate</files_per_second>
+  <lines_per_second>$line_rate</lines_per_second>";
+        $header .= "\n$report_file"
+            if $opt_report_file;
+        $header .= "\n</header>";
+    } elsif ($opt_yaml) {
+        $header = "---\n# $URL
+header :
+  cloc_url           : http://cloc.sourceforge.net
+  cloc_version       : $version
+  elapsed_seconds    : $elapsed_sec
+  n_files            : $sum_files
+  n_lines            : $sum_lines
+  files_per_second   : $file_rate
+  lines_per_second   : $line_rate";
+        if ($opt_report_file) {
+            if ($opt_sum_reports) {
+                if ($by_file) {
+                    $header .= "\n  report_file        : $opt_report_file.file"
+                } else {
+                    $header .= "\n  report_file        : $opt_report_file.lang"
+                }
+            } else {
+                $header .= "\n  report_file        : $opt_report_file";
+            }
+        }
+    }
+    print "<- xml_or_yaml_header\n" if $opt_v > 2;
+    return $header;
+} # 1}}}
+sub diff_xml_yaml_report {                   # {{{1
+    # returns an array of lines containing the results
+    my ($version    , # in
+        $elapsed_sec, # in
+        $report_type, # in  "by language" | "by report file" | "by file"
+        $rhhh_count , # in  count{TYPE}{nFiles|code|blank|comment}{a|m|r|s}
+        $rh_scale   , # in
+       ) = @_;
+    print "-> diff_xml_yaml_report\n" if $opt_v > 2;
+
+#print "diff_report: ", Dumper($rhhh_count), "\n";
+    my @results       = ();
+    
+    my $languages     = ();
+    my %sum           = (); # sum{nFiles|blank|comment|code}{same|modified|added|removed}
+
+    my $sum_files = 0;
+    my $sum_lines = 0;
+    foreach my $language (keys %{$rhhh_count}) {
+        foreach my $V (qw(nFiles blank comment code)) {
+            foreach my $S (qw(added same modified removed)) {
+                $rhhh_count->{$language}{$V}{$S} = 0 unless
+                    defined $rhhh_count->{$language}{$V}{$S};
+                $sum{$V}{$S}  += $rhhh_count->{$language}{$V}{$S};
+                if ($V eq "nFiles") {
+                    $sum_files += $rhhh_count->{$language}{$V}{$S};
+                } else {
+                    $sum_lines += $rhhh_count->{$language}{$V}{$S};
+                }
+            }
+        }
+    }
+    $elapsed_sec = 0.5 unless $elapsed_sec;
+
+    my $data_line   = "";
+    my $BY_LANGUAGE = 0;
+    my $BY_FILE     = 0;
+    if      ($report_type eq "by language") {
+        $BY_LANGUAGE  = 1;
+    } elsif ($report_type eq "by file")     {
+        $BY_FILE      = 1;
+    }
+
+    if (!$ALREADY_SHOWED_HEADER) {
+        push @results,
+              xml_or_yaml_header($URL, $version, $elapsed_sec, 
+                                 $sum_files, $sum_lines, $BY_FILE);
+        $ALREADY_SHOWED_HEADER = 1;
+    }
+
+    foreach my $S (qw(same modified added removed)) {
+        if ($opt_xml) {
+            push @results, "  <$S>";
+        } elsif ($opt_yaml) {
+            push @results, "$S :";
+        }
+########foreach my $lang_or_file (keys %{$rhhh_count}) {
+########    $rhhh_count->{$lang_or_file}{'code'} = 0 unless 
+########        defined $rhhh_count->{$lang_or_file}{'code'};
+########}
+        foreach my $lang_or_file (sort {
+                                     $rhhh_count->{$b}{'code'} <=>
+                                     $rhhh_count->{$a}{'code'}
+                                   }
+                              keys %{$rhhh_count}) {
+            my $L = "";
+            if ($opt_xml) {
+                if ($BY_FILE) {
+                    $L .= sprintf "    <file name=\"%s\" files_count=\"1\" ", 
+                            rm_leading_tempdir($lang_or_file, \%TEMP_DIR);
+                } else {
+                    $L .= sprintf "    <language name=\"%s\" files_count=\"%d\" ",
+                            $lang_or_file ,
+                            $rhhh_count->{$lang_or_file}{'nFiles'}{$S};
+                }
+                foreach my $T (qw(blank comment code)) {
+                    $L .= sprintf "%s=\"%d\" ", 
+                            $T, $rhhh_count->{$lang_or_file}{$T}{$S};
+                }
+                push @results, $L . "/>";
+            } elsif ($opt_yaml) {
+                if ($BY_FILE) {
+                    push @results, sprintf "  - file : %s", 
+                                   rm_leading_tempdir($lang_or_file, \%TEMP_DIR);
+                    push @results, sprintf "    files_count : 1", 
+                } else {
+                    push @results, sprintf "  - language : %s", $lang_or_file;
+                    push @results, sprintf "    files_count : %d", 
+                            $rhhh_count->{$lang_or_file}{'nFiles'}{$S};
+                }
+                foreach my $T (qw(blank comment code)) {
+                    push @results, sprintf "    %s : %d", 
+                            $T, $rhhh_count->{$lang_or_file}{$T}{$S};
+                }
+            }
+        }
+
+        if ($opt_xml) {
+            my $L = sprintf "    <total sum_files=\"%d\" ", $sum{'nFiles'}{$S};
+            foreach my $V (qw(blank comment code)) {
+                $L .= sprintf "%s=\"%d\" ", $V, $sum{$V}{$S};
+            }
+            push @results, $L . "/>";
+            push @results, "  </$S>";
+        } elsif ($opt_yaml) {
+            push @results, sprintf "%s_total :\n    sum_files : %d", 
+                                $S, $sum{'nFiles'}{$S};
+            foreach my $V (qw(blank comment code)) {
+                push @results, sprintf "    %s : %d", $V, $sum{$V}{$S};
+            }
+        }
+    }
+
+    if ($opt_xml) {
+        push @results, "</diff_results>";
+    }
+    write_xsl_file() if $opt_xsl and $opt_xsl eq $CLOC_XSL;
+    print "<- diff_xml_yaml_report\n" if $opt_v > 2;
+    return @results;
+} # 1}}}
+sub diff_csv_report {                        # {{{1
+    # returns an array of lines containing the results
+    my ($version    , # in
+        $elapsed_sec, # in
+        $report_type, # in  "by language" | "by report file" | "by file"
+        $rhhh_count , # in  count{TYPE}{nFiles|code|blank|comment}{a|m|r|s}
+        $rh_scale   , # in  unused
+       ) = @_;
+    print "-> diff_csv_report\n" if $opt_v > 2;
+
+#use Data::Dumper;
+#print "diff_csv_report: ", Dumper($rhhh_count), "\n";
+#die;
+    my @results       = ();
+    my $languages     = ();
+
+    my $data_line   = "";
+    my $BY_LANGUAGE = 0;
+    my $BY_FILE     = 0;
+    if      ($report_type eq "by language") {
+        $BY_LANGUAGE  = 1;
+    } elsif ($report_type eq "by file")     {
+        $BY_FILE      = 1;
+    }
+    my $DELIM = ",";
+       $DELIM = $opt_csv_delimiter if defined $opt_csv_delimiter;
+
+    $elapsed_sec = 0.5 unless $elapsed_sec;
+
+    my $line = "Language${DELIM} ";
+       $line = "File${DELIM} " if $BY_FILE;
+    foreach my $item (qw(files blank comment code)) {
+        next if $BY_FILE and $item eq 'files';
+        foreach my $symbol ( '==', '!=', '+', '-', ) {
+            $line .= "$symbol $item${DELIM} ";
+        }
+    }
+    $line .= "\"$URL v $version T=$elapsed_sec s\"";
+    push @results, $line;
+
+    foreach my $lang_or_file (keys %{$rhhh_count}) {
+        $rhhh_count->{$lang_or_file}{'code'}{'added'} = 0 unless 
+            defined $rhhh_count->{$lang_or_file}{'code'};
+    }
+    foreach my $lang_or_file (sort {
+                                 $rhhh_count->{$b}{'code'} <=>
+                                 $rhhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhhh_count}) {
+        if ($BY_FILE) {
+            $line = rm_leading_tempdir($lang_or_file, \%TEMP_DIR) . "$DELIM ";
+        } else {
+            $line = $lang_or_file . "${DELIM} ";
+        }
+        foreach my $item (qw(nFiles blank comment code)) {
+            next if $BY_FILE and $item eq 'nFiles';
+            foreach my $symbol (qw(same modified added removed)) {
+                if (defined $rhhh_count->{$lang_or_file}{$item}{$symbol}) {
+                    $line .= "$rhhh_count->{$lang_or_file}{$item}{$symbol}${DELIM} ";
+                } else {
+                    $line .= "0${DELIM} ";
+                }
+            }
+        }
+        push @results, $line;
+    }
+
+    print "<- diff_csv_report\n" if $opt_v > 2;
+    return @results;
+} # 1}}}
+sub rm_leading_tempdir {                     # {{{1
+    my ($in_file, $rh_temp_dirs, ) = @_;
+    my $clean_filename = $in_file;
+    foreach my $temp_d (keys %{$rh_temp_dirs}) {
+        if ($ON_WINDOWS) {
+        # \ -> / necessary to allow the next if test's
+        # m{} to work in the presence of spaces in file names
+            $temp_d         =~ s{\\}{/}g;
+            $clean_filename =~ s{\\}{/}g;
+        }
+        if ($clean_filename =~ m{^$temp_d/}) {
+            $clean_filename =~ s{^$temp_d/}{};
+            last;
+        }
+    }
+    $clean_filename =~ s{/}{\\}g if $ON_WINDOWS; # then go back from / to \
+    return $clean_filename;
+} # 1}}}
+sub generate_sql    {                        # {{{1
+    my ($elapsed_sec, # in
+        $rhh_count  , # in  count{TYPE}{lang|code|blank|comment|scaled}
+        $rh_scale   , # in
+       ) = @_;
+    print "-> generate_sql\n" if $opt_v > 2;
+
+    $opt_sql_project = cwd() unless defined $opt_sql_project;
+    $opt_sql_project =~ s{/}{\\}g if $ON_WINDOWS;
+
+    my $schema = "
+create table metadata (          -- $URL v $VERSION
+                timestamp text,    
+                Project   text,    
+                elapsed_s real);   
+create table t        (
+                Project   text   ,  
+                Language  text   ,  
+                File      text   ,  
+                nBlank    integer,  
+                nComment  integer,  
+                nCode     integer,  
+                nScaled   real   ); 
+";
+    $opt_sql = "-" if $opt_sql eq "1";
+
+    my $open_mode = ">";
+       $open_mode = ">>" if $opt_sql_append;
+
+    my $fh = new IO::File; # $opt_sql, "w";
+    if (!$fh->open("${open_mode}${opt_sql}")) {
+        die "Unable to write to $opt_sql  $!\n";
+    }
+    print $fh $schema unless defined $opt_sql_append;
+
+    print $fh "begin transaction;\n";
+    printf $fh "insert into metadata values('%s', '%s', %f);\n",
+                strftime("%Y-%m-%d %H:%M:%S", localtime(time())),
+                $opt_sql_project, $elapsed_sec;
+
+    my $nIns = 0;
+    foreach my $file (keys %{$rhh_count}) {
+        my $language = $rhh_count->{$file}{'lang'};
+        my $clean_filename = $file;
+        # If necessary (that is, if the input contained an
+        # archive file [.tar.gz, etc]), strip the temporary
+        # directory name which was used to expand the archive
+        # from the file name.
+
+        $clean_filename = rm_leading_tempdir($clean_filename, \%TEMP_DIR);
+        printf $fh "insert into t values('%s', '%s', '%s', %d, %d, %d, %f);\n",
+                    $opt_sql_project           ,
+                    $language                  ,
+                    $clean_filename            ,
+                    $rhh_count->{$file}{'blank'},
+                    $rhh_count->{$file}{'comment'},
+                    $rhh_count->{$file}{'code'}   ,
+                    $rhh_count->{$file}{'code'}*$rh_scale->{$language};
+        ++$nIns;
+        if (!($nIns % 10_000)) {
+            print $fh "commit;\n";
+            print $fh "begin transaction;\n";
+        }
+    }
+    print $fh "commit;\n";
+
+    $fh->close unless $opt_sql eq "-"; # don't try to close STDOUT
+    print "<- generate_sql\n" if $opt_v > 2;
+
+    # sample query:
+    #
+    #   select project, language, 
+    #          sum(nCode)     as Code, 
+    #          sum(nComment)  as Comments, 
+    #          sum(nBlank)    as Blank,  
+    #          sum(nCode)+sum(nComment)+sum(nBlank) as All_Lines,
+    #          100.0*sum(nComment)/(sum(nCode)+sum(nComment)) as Comment_Pct
+    #          from t group by Project, Language order by Project, Code desc;
+    #
+} # 1}}}
+sub output_header   {                        # {{{1
+    my ($header_line, 
+        $hyphen_line,
+        $BY_FILE    ,)    = @_;
+    print "-> output_header\n" if $opt_v > 2;
+    my @R = ();
+    if      ($opt_xml) {
+        if (!$ALREADY_SHOWED_XML_SECTION) {
+            push @R, "<?xml version=\"1.0\"?>";
+            push @R, '<?xml-stylesheet type="text/xsl" href="' .
+                            $opt_xsl . '"?>' if $opt_xsl;
+            push @R, "<results>";
+            push @R, "<header>$header_line</header>";
+            $ALREADY_SHOWED_XML_SECTION = 1;
+        }
+        if ($BY_FILE) {
+            push @R, "<files>";
+        } else {
+            push @R, "<languages>";
+        }
+    } elsif ($opt_yaml) {
+        push @R, "---\n# $header_line";
+    } elsif ($opt_csv) {
+        # append the header to the end of the column headers
+        # to keep the output a bit cleaner from a spreadsheet
+        # perspective
+    } else {
+        if ($ALREADY_SHOWED_HEADER) {
+            push @R, "";
+        } else {
+            push @R, $header_line;
+            $ALREADY_SHOWED_HEADER = 1;
+        }
+        push @R, $hyphen_line;
+    }
+    print "<- output_header\n" if $opt_v > 2;
+    return @R;
+} # 1}}}
+sub generate_report {                        # {{{1
+    # returns an array of lines containing the results
+    my ($version    , # in
+        $elapsed_sec, # in
+        $report_type, # in  "by language" | "by report file" | "by file"
+        $rhh_count  , # in  count{TYPE}{nFiles|code|blank|comment|scaled}
+        $rh_scale   , # in
+       ) = @_;
+
+    print "-> generate_report\n" if $opt_v > 2;
+    my $DELIM = ",";
+       $DELIM = $opt_csv_delimiter if defined $opt_csv_delimiter;
+
+    my @results       = ();
+    
+    my $languages     = ();
+
+    my $sum_files     = 0;
+    my $sum_code      = 0;
+    my $sum_blank     = 0;
+    my $sum_comment   = 0;
+    my $max_len       = 0;
+    foreach my $language (keys %{$rhh_count}) {
+        $sum_files   += $rhh_count->{$language}{'nFiles'} ;
+        $sum_blank   += $rhh_count->{$language}{'blank'}  ;
+        $sum_comment += $rhh_count->{$language}{'comment'};
+        $sum_code    += $rhh_count->{$language}{'code'}   ;
+        $max_len      = length($language) if length($language) > $max_len;
+    }
+    my $column_1_offset = 0;
+       $column_1_offset = $max_len - 17 if $max_len > 17;
+    my $sum_lines = $sum_blank + $sum_comment + $sum_code;
+    $elapsed_sec = 0.5 unless $elapsed_sec;
+
+    my $spacing_0 = 23;
+    my $spacing_1 = 13;
+    my $spacing_2 =  9;
+    my $spacing_3 = 17;
+    if (!$opt_3) {
+        $spacing_1 = 19;
+        $spacing_2 = 14;
+        $spacing_3 = 28;
+    }
+    $spacing_0 += $column_1_offset;
+    $spacing_1 += $column_1_offset;
+    $spacing_3 += $column_1_offset;
+    my %Format = (
+        '1' => { 'xml' => 'name="%s" ',
+                 'txt' => "\%-${spacing_0}s ",
+               },
+        '2' => { 'xml' => 'name="%s" ',
+                 'txt' => "\%-${spacing_3}s ",
+               },
+        '3' => { 'xml' => 'files_count="%d" ',
+                 'txt' => '%5d ',
+               },
+        '4' => { 'xml' => 'blank="%d" comment="%d" code="%d" ',
+                 'txt' => "\%${spacing_2}d \%${spacing_2}d \%${spacing_2}d",
+               },
+        '5' => { 'xml' => 'factor="%.2f" scaled="%.2f" ',
+                 'txt' => ' x %6.2f = %14.2f',
+               },
+    );
+    my $Style = "txt";
+       $Style = "xml" if $opt_xml ;
+       $Style = "xml" if $opt_yaml;  # not a typo; just set to anything but txt
+       $Style = "xml" if $opt_csv ;  # not a typo; just set to anything but txt
+
+    my $hyphen_line = sprintf "%s", '-' x (79 + $column_1_offset);
+       $hyphen_line = sprintf "%s", '-' x (68 + $column_1_offset) 
+            if (!$opt_3) and (68 + $column_1_offset) > 79;
+    my $data_line  = "";
+    my $first_column;
+    my $BY_LANGUAGE = 0;
+    my $BY_FILE     = 0;
+    if      ($report_type eq "by language") {
+        $first_column = "Language";
+        $BY_LANGUAGE  = 1;
+    } elsif ($report_type eq "by file")     {
+        $first_column = "File";
+        $BY_FILE      = 1;
+    } elsif ($report_type eq "by report file")     {
+        $first_column = "File";
+        $BY_FILE      = 1;
+    } else {
+        $first_column = "Report File";
+    }
+
+    my $header_line  = sprintf "%s v %s", $URL, $version;
+       $header_line .= sprintf("  T=%.2f s (%.1f files/s, %.1f lines/s)",
+                        $elapsed_sec           ,
+                        $sum_files/$elapsed_sec,
+                        $sum_lines/$elapsed_sec) unless $opt_sum_reports;
+    if ($opt_xml or $opt_yaml) {
+        if (!$ALREADY_SHOWED_HEADER) {
+            push @results, xml_or_yaml_header($URL, $version, $elapsed_sec, 
+                                              $sum_files, $sum_lines, $BY_FILE);
+            $ALREADY_SHOWED_HEADER = 1 unless $opt_sum_reports;
+            # --sum-reports yields two xml or yaml files, one by
+            # language and one by report file, each of which needs a header
+        }
+        if ($opt_xml) {
+            if ($BY_FILE) {
+                push @results, "<files>";
+            } else {
+                push @results, "<languages>";
+            }
+        }
+    } else {
+        push @results, output_header($header_line, $hyphen_line, $BY_FILE);
+    }
+
+    if ($Style eq "txt") {
+        # column headers
+        if (!$opt_3 and $BY_FILE) {
+            my $spacing_n = $spacing_1 - 11;
+            $data_line  = sprintf "%-${spacing_n}s ", $first_column;
+        } else {
+            $data_line  = sprintf "%-${spacing_1}s ", $first_column;
+        }
+        if ($BY_FILE) {
+            $data_line .= sprintf "%${spacing_2}s "  , " "    ;
+        } else {
+            $data_line .= sprintf "%${spacing_2}s "  , "files";
+        }
+        $data_line .= sprintf "%${spacing_2}s %${spacing_2}s %${spacing_2}s",
+            "blank"         ,
+            "comment"       ,
+            "code";
+        $data_line .= sprintf " %8s   %14s",
+            "scale"         ,
+            "3rd gen. equiv"
+              if $opt_3;
+        push @results, $data_line;
+        push @results, $hyphen_line;
+    }
+    if ($opt_csv) {
+        my $header2;
+        if ($BY_FILE) {
+            $header2 = "language${DELIM}filename";
+        } else {
+            $header2 = "files${DELIM}language";
+        }
+        $header2 .= "${DELIM}blank${DELIM}comment${DELIM}code";
+        $header2 .= "${DELIM}scale${DELIM}3rd gen. equiv" if $opt_3;
+        $header2 .= ${DELIM} . '"' . $header_line . '"';
+        push @results, $header2;
+    }
+
+    my $sum_scaled = 0;
+####foreach my $lang_or_file (keys %{$rhh_count}) {
+####    $rhh_count->{$lang_or_file}{'code'} = 0 unless 
+####        defined $rhh_count->{$lang_or_file}{'code'};
+####}
+    foreach my $lang_or_file (sort {
+                                 $rhh_count->{$b}{'code'} <=>
+                                 $rhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhh_count}) {
+        next if $lang_or_file eq "by report file";
+        my ($factor, $scaled);
+        if ($BY_LANGUAGE or $BY_FILE) {
+            $factor = 1;
+            if ($BY_LANGUAGE) {
+                if (defined $rh_scale->{$lang_or_file}) {
+                    $factor = $rh_scale->{$lang_or_file};
+                } else {
+                    warn "No scale factor for $lang_or_file; using 1.00";
+                }
+            } else { # by individual code file
+                if ($report_type ne "by report file") {
+                    next unless defined $rhh_count->{$lang_or_file}{'lang'};
+                    next unless defined $rh_scale->{$rhh_count->{$lang_or_file}{'lang'}};
+                    $factor = $rh_scale->{$rhh_count->{$lang_or_file}{'lang'}};
+                }
+            }
+            $scaled = $factor*$rhh_count->{$lang_or_file}{'code'};
+        } else {
+            if (!defined $rhh_count->{$lang_or_file}{'scaled'}) {
+                $opt_3 = 0;
+                # If we're summing together files previously generated
+                # with --no3 then rhh_count->{$lang_or_file}{'scaled'}
+                # this variable will be undefined.  That should only
+                # happen when summing together by file however.
+            } elsif ($BY_LANGUAGE) {
+                warn "Missing scaled language info for $lang_or_file\n";
+            }
+            if ($opt_3) {
+                $scaled =         $rhh_count->{$lang_or_file}{'scaled'};
+                $factor = $scaled/$rhh_count->{$lang_or_file}{'code'};
+            }
+        }
+
+        if ($BY_FILE) {
+            my $clean_filename = rm_leading_tempdir($lang_or_file, \%TEMP_DIR);
+            $data_line  = sprintf $Format{'1'}{$Style}, $clean_filename;
+        } else {
+            $data_line  = sprintf $Format{'2'}{$Style}, $lang_or_file;
+        }
+        $data_line .= sprintf $Format{3}{$Style}  , 
+                        $rhh_count->{$lang_or_file}{'nFiles'} unless $BY_FILE;
+        $data_line .= sprintf $Format{4}{$Style}  , 
+            $rhh_count->{$lang_or_file}{'blank'}  ,
+            $rhh_count->{$lang_or_file}{'comment'},
+            $rhh_count->{$lang_or_file}{'code'}   ;
+        $data_line .= sprintf $Format{5}{$Style}  ,
+            $factor                               ,
+            $scaled if $opt_3;
+        $sum_scaled  += $scaled if $opt_3;
+
+        if ($opt_xml) {
+            if (defined $rhh_count->{$lang_or_file}{'lang'}) {
+                my $lang = $rhh_count->{$lang_or_file}{'lang'};
+                if (!defined $languages->{$lang}) {
+                    $languages->{$lang} = $lang;
+                }
+                $data_line.=' language="' . $lang . '" ';
+            }
+            if ($BY_FILE) {
+                push @results, "  <file " . $data_line . "/>";
+            } else {
+                push @results, "  <language " . $data_line . "/>";
+            }
+        } elsif ($opt_yaml) {
+            push @results,$lang_or_file . ":";
+            push @results,"  nFiles: "  .$rhh_count->{$lang_or_file}{'nFiles'} 
+                unless $BY_FILE;
+            push @results,"  blank: "   .$rhh_count->{$lang_or_file}{'blank'}  ;
+            push @results,"  comment: " .$rhh_count->{$lang_or_file}{'comment'};
+            push @results,"  code: "    .$rhh_count->{$lang_or_file}{'code'}   ;
+            push @results,"  language: ".$rhh_count->{$lang_or_file}{'lang'} 
+                if $BY_FILE;
+            if ($opt_3) {
+                push @results, "  scaled: " . $scaled;
+                push @results, "  factor: " . $factor;
+            }
+        } elsif ($opt_csv) {
+            my $extra_3 = "";
+               $extra_3 = "${DELIM}$factor${DELIM}$scaled" if $opt_3;
+            my $first_column = undef;
+            my $clean_name   = $lang_or_file;
+            if ($BY_FILE) { 
+                $first_column = $rhh_count->{$lang_or_file}{'lang'};
+                $clean_name   = rm_leading_tempdir($lang_or_file, \%TEMP_DIR);
+            } else {
+                $first_column = $rhh_count->{$lang_or_file}{'nFiles'};
+            } 
+            my $str = $first_column                         . ${DELIM} .
+                      $clean_name                           . ${DELIM} .
+                      $rhh_count->{$lang_or_file}{'blank'}  . ${DELIM} .
+                      $rhh_count->{$lang_or_file}{'comment'}. ${DELIM} .
+                      $rhh_count->{$lang_or_file}{'code'}   .
+                      $extra_3;
+            push @results, $str;
+        } else {
+            push @results, $data_line;
+        }
+    }
+
+    my $avg_scale = 1;  # weighted average of scale factors
+       $avg_scale = sprintf("%.2f", $sum_scaled / $sum_code) 
+            if $sum_code and $opt_3;
+
+    if ($opt_xml) {
+        $data_line = "";
+        if (!$BY_FILE) {
+            $data_line .= sprintf "sum_files=\"%d\" ", $sum_files;
+        }
+        $data_line .= sprintf $Format{'4'}{$Style},
+            $sum_blank   ,
+            $sum_comment ,
+            $sum_code    ;
+        $data_line .= sprintf $Format{'5'}{$Style},
+            $avg_scale   ,
+            $sum_scaled  if $opt_3;
+        push @results, "  <total " . $data_line . "/>";
+
+        if ($BY_FILE) {
+            push @results, "</files>";
+        } else {
+            foreach my $language (keys %{$languages}) {
+                push @results, '  <language name="' . $language . '"/>';
+            }
+            push @results, "</languages>";
+        }
+
+        if (!$opt_by_file_by_lang or $ALREADY_SHOWED_XML_SECTION) {
+    	    push @results, "</results>";
+        } else {
+            $ALREADY_SHOWED_XML_SECTION = 1;
+        }
+    } elsif ($opt_yaml) {
+        push @results, "SUM:";
+        push @results, "  blank: "  . $sum_blank  ;
+        push @results, "  code: "   . $sum_code   ;
+        push @results, "  comment: ". $sum_comment;
+        push @results, "  nFiles: " . $sum_files  ;
+        if ($opt_3) {
+            push @results, "  scaled: " . $sum_scaled;
+            push @results, "  factor: " . $avg_scale ;
+        }
+    } elsif ($opt_csv) {
+        # do nothing
+    } else {
+
+        if ($BY_FILE) {
+            $data_line  = sprintf "%-${spacing_0}s ", "SUM:"  ;
+        } else {
+            $data_line  = sprintf "%-${spacing_1}s ", "SUM:"  ;
+            $data_line .= sprintf "%${spacing_2}d ", $sum_files;
+        }
+        $data_line .= sprintf $Format{'4'}{$Style},
+            $sum_blank   ,
+            $sum_comment ,
+            $sum_code    ;
+        $data_line .= sprintf $Format{'5'}{$Style},
+            $avg_scale   ,
+            $sum_scaled if $opt_3;
+        push @results, $hyphen_line if $sum_files > 1 or $opt_sum_one;
+        push @results, $data_line   if $sum_files > 1 or $opt_sum_one;
+        push @results, $hyphen_line;
+    }
+    write_xsl_file() if $opt_xsl and $opt_xsl eq $CLOC_XSL;
+    print "<- generate_report\n" if $opt_v > 2;
+    return @results;
+} # 1}}}
+sub print_errors {                           # {{{1
+    my ($rh_Error_Codes, # in
+        $raa_errors    , # in
+       ) = @_;
+
+    print "-> print_errors\n" if $opt_v > 2;
+    my %error_string = reverse(%{$rh_Error_Codes});
+    my $nErrors      = scalar @{$raa_errors};
+    warn sprintf "\n%d error%s:\n", plural_form(scalar @Errors);
+    for (my $i = 0; $i < $nErrors; $i++) {
+        warn sprintf "%s:  %s\n", 
+                     $error_string{ $raa_errors->[$i][0] },
+                     $raa_errors->[$i][1] ;
+    }
+    print "<- print_errors\n" if $opt_v > 2;
+
+} # 1}}}
+sub write_lang_def {                         # {{{1
+    my ($file                     ,
+        $rh_Language_by_Extension , # in
+        $rh_Language_by_Script    , # in
+        $rh_Language_by_File      , # in
+        $rhaa_Filters_by_Language , # in
+        $rh_Not_Code_Extension    , # in
+        $rh_Not_Code_Filename     , # in
+        $rh_Scale_Factor          , # in
+        $rh_EOL_Continuation_re   , # in
+       ) = @_;
+
+    print "-> write_lang_def($file)\n" if $opt_v > 2;
+    my $OUT = new IO::File $file, "w";
+    die "Unable to write to $file\n" unless defined $OUT;
+
+    foreach my $language (sort keys %{$rhaa_Filters_by_Language}) {
+        next if $language eq "MATLAB/Objective C/MUMPS" or
+                $language eq "PHP/Pascal"               or
+                $language eq "Lisp/OpenCL";
+        printf $OUT "%s\n", $language;
+        foreach my $filter (@{$rhaa_Filters_by_Language->{$language}}) {
+            printf $OUT "    filter %s", $filter->[0];
+            printf $OUT " %s", $filter->[1] if defined $filter->[1];
+            print  $OUT "\n";
+        }
+        foreach my $ext (sort keys %{$rh_Language_by_Extension}) {
+            if ($language eq $rh_Language_by_Extension->{$ext}) {
+                printf $OUT "    extension %s\n", $ext;
+            }
+        }
+        foreach my $filename (sort keys %{$rh_Language_by_File}) {
+            if ($language eq $rh_Language_by_File->{$filename}) {
+                printf $OUT "    filename %s\n", $filename;
+            }
+        }
+        foreach my $script_exe (sort keys %{$rh_Language_by_Script}) {
+            if ($language eq $rh_Language_by_Script->{$script_exe}) {
+                printf $OUT "    script_exe %s\n", $script_exe;
+            }
+        }
+        printf $OUT "    3rd_gen_scale %.2f\n", $rh_Scale_Factor->{$language};
+        if (defined $rh_EOL_Continuation_re->{$language}) {
+            printf $OUT "    end_of_line_continuation %s\n", 
+                $rh_EOL_Continuation_re->{$language};
+        }
+    }
+
+    $OUT->close;
+    print "<- write_lang_def\n" if $opt_v > 2;
+} # 1}}}
+sub read_lang_def {                          # {{{1
+    my ($file                     ,
+        $rh_Language_by_Extension , # out
+        $rh_Language_by_Script    , # out
+        $rh_Language_by_File      , # out
+        $rhaa_Filters_by_Language , # out
+        $rh_Not_Code_Extension    , # out
+        $rh_Not_Code_Filename     , # out
+        $rh_Scale_Factor          , # out
+        $rh_EOL_Continuation_re   , # out
+        $rh_EOL_abc,
+       ) = @_;
+
+
+    print "-> read_lang_def($file)\n" if $opt_v > 2;
+    my $IN = new IO::File $file, "r";
+    die "Unable to read $file.\n" unless defined $IN;
+
+    my $language = "";
+    while (<$IN>) {
+        next if /^\s*#/ or /^\s*$/;
+
+        if (/^(\w+.*?)\s*$/) {
+            $language = $1;
+            next;
+        }
+        die "Missing computer language name, line $. of $file\n"
+            unless $language;
+
+        if      (/^    filter\s+(\w+)\s*$/) {
+            push @{$rhaa_Filters_by_Language->{$language}}, [ $1 ]
+
+        } elsif (/^    filter\s+(\w+)\s+(.*?)\s*$/) {
+            push @{$rhaa_Filters_by_Language->{$language}}, [ $1 , $2 ]
+
+        } elsif (/^    extension\s+(\S+)\s*$/) {
+            if (defined $rh_Language_by_Extension->{$1}) {
+                die "File extension collision:  $1 ",
+                    "maps to languages '$rh_Language_by_Extension->{$1}' ",
+                    "and '$language'\n" ,
+                    "Edit $file and remove $1 from one of these two ",
+                    "language definitions.\n";
+            }
+            $rh_Language_by_Extension->{$1} = $language;
+
+        } elsif (/^    filename\s+(\S+)\s*$/) {
+            $rh_Language_by_File->{$1} = $language;
+
+        } elsif (/^    script_exe\s+(\S+)\s*$/) {
+            $rh_Language_by_Script->{$1} = $language;
+
+        } elsif (/^    3rd_gen_scale\s+(\S+)\s*$/) {
+            $rh_Scale_Factor->{$language} = $1;
+
+        } elsif (/^    end_of_line_continuation\s+(\S+)\s*$/) {
+            $rh_EOL_Continuation_re->{$language} = $1;
+
+        } else {
+            die "Unexpected data line $. of $file:\n$_\n";
+        }
+
+    }
+    $IN->close;
+    print "<- read_lang_def\n" if $opt_v > 2;
+} # 1}}}
+sub merge_lang_def {                         # {{{1
+    my ($file                     ,
+        $rh_Language_by_Extension , # in/out
+        $rh_Language_by_Script    , # in/out
+        $rh_Language_by_File      , # in/out
+        $rhaa_Filters_by_Language , # in/out
+        $rh_Not_Code_Extension    , # in/out
+        $rh_Not_Code_Filename     , # in/out
+        $rh_Scale_Factor          , # in/out
+        $rh_EOL_Continuation_re   , # in/out
+        $rh_EOL_abc,
+       ) = @_;
+
+
+    print "-> merge_lang_def($file)\n" if $opt_v > 2;
+    my $IN = new IO::File $file, "r";
+    die "Unable to read $file.\n" unless defined $IN;
+
+    my $language        = "";  
+    my $already_know_it = undef;
+    while (<$IN>) {
+        next if /^\s*#/ or /^\s*$/;
+
+        if (/^(\w+.*?)\s*$/) {
+            $language = $1;
+            $already_know_it = defined $rh_Scale_Factor->{$language};
+            next;
+        }
+        die "Missing computer language name, line $. of $file\n"
+            unless $language;
+
+        if      (/^    filter\s+(\w+)\s*$/) {
+            next if $already_know_it;
+            push @{$rhaa_Filters_by_Language->{$language}}, [ $1 ]
+
+        } elsif (/^    filter\s+(\w+)\s+(.*?)\s*$/) {
+            next if $already_know_it;
+            push @{$rhaa_Filters_by_Language->{$language}}, [ $1 , $2 ]
+
+        } elsif (/^    extension\s+(\S+)\s*$/) {
+            next if $already_know_it;
+            if (defined $rh_Language_by_Extension->{$1}) {
+                die "File extension collision:  $1 ",
+                    "maps to languages '$rh_Language_by_Extension->{$1}' ",
+                    "and '$language'\n" ,
+                    "Edit $file and remove $1 from one of these two ",
+                    "language definitions.\n";
+            }
+            $rh_Language_by_Extension->{$1} = $language;
+
+        } elsif (/^    filename\s+(\S+)\s*$/) {
+            next if $already_know_it;
+            $rh_Language_by_File->{$1} = $language;
+
+        } elsif (/^    script_exe\s+(\S+)\s*$/) {
+            next if $already_know_it;
+            $rh_Language_by_Script->{$1} = $language;
+
+        } elsif (/^    3rd_gen_scale\s+(\S+)\s*$/) {
+            next if $already_know_it;
+            $rh_Scale_Factor->{$language} = $1;
+
+        } elsif (/^    end_of_line_continuation\s+(\S+)\s*$/) {
+            next if $already_know_it;
+            $rh_EOL_Continuation_re->{$language} = $1;
+
+        } else {
+            die "Unexpected data line $. of $file:\n$_\n";
+        }
+
+    }
+    $IN->close;
+    print "<- merge_lang_def\n" if $opt_v > 2;
+} # 1}}}
+sub print_extension_info {                   # {{{1
+    my ($extension,) = @_;
+    if ($extension) {  # show information on this extension
+        foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+            # Language_by_Extension{f}    = 'Fortran 77' 
+            printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext}
+                if $ext =~ m{$extension}i;
+        }
+    } else {           # show information on all  extensions
+        foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+            # Language_by_Extension{f}    = 'Fortran 77' 
+            printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext};
+        }
+    }
+} # 1}}}
+sub print_language_info {                    # {{{1
+    my ($language,) = @_;
+    my %extensions = (); # the subset matched by the given $language value
+    if ($language) {  # show information on this language
+        foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+            # Language_by_Extension{f}    = 'Fortran 77' 
+            push @{$extensions{$Language_by_Extension{$ext}} }, $ext
+                if $Language_by_Extension{$ext} =~ m{$language}i;
+        }
+    } else {          # show information on all  languages
+        foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+            # Language_by_Extension{f}    = 'Fortran 77' 
+            push @{$extensions{$Language_by_Extension{$ext}} }, $ext
+        }
+    }
+
+    # add exceptions (one file extension mapping to multiple languages)
+    if (!$language or 
+        $language =~ /^(Objective C|MATLAB|MUMPS)$/i) {
+        push @{$extensions{'Objective C'}}, "m";
+        push @{$extensions{'MATLAB'}}     , "m";
+        push @{$extensions{'MUMPS'}}      , "m";
+        delete $extensions{'MATLAB/Objective C/MUMPS'};
+    } elsif ($language =~ /^(Lisp|OpenCL)$/i) {
+        push @{$extensions{'Lisp'}}  , "cl";
+        push @{$extensions{'OpenCL'}}, "cl";
+        delete $extensions{'Lisp/OpenCL'};
+    } elsif ($language =~ /^(Ant)$/i) {
+        push @{$extensions{'Ant'}}  , "build.xml";
+        delete $extensions{'Ant/XML'};
+    }
+
+    if (%extensions) {
+        foreach my $lang (sort {lc $a cmp lc $b } keys %extensions) {
+            printf "%-26s (%s)\n", $lang, join(", ", @{$extensions{$lang}});
+        }
+    }
+} # 1}}}
+sub make_file_list {                         # {{{1
+    my ($ra_arg_list,  # in   file and/or directory names to examine
+        $rh_Err     ,  # in   hash of error codes
+        $raa_errors ,  # out  errors encountered
+        $rh_ignored ,  # out  files not recognized as computer languages
+        ) = @_;
+    print "-> make_file_list(@{$ra_arg_list})\n" if $opt_v > 2;
+
+    my ($fh, $filename);
+    if ($opt_categorized) {
+        $filename = $opt_categorized;
+        $fh = new IO::File $filename, "+>";  # open for read/write
+        die "Unable to write to $filename:  $!\n" unless defined $fh;
+    } elsif ($opt_sdir) {
+        # write to the user-defined scratch directory
+        $filename = $opt_sdir . '/cloc_file_list.txt';
+        $fh = new IO::File $filename, "+>";  # open for read/write
+        die "Unable to write to $filename:  $!\n" unless defined $fh;
+    } else {
+        # let File::Temp create a suitable temporary file
+        ($fh, $filename) = tempfile(UNLINK => 1);  # delete file on exit
+        print "Using temp file list [$filename]\n" if $opt_v;
+    }
+
+    my @dir_list = ();
+    foreach my $file_or_dir (@{$ra_arg_list}) {
+#print "make_file_list file_or_dir=$file_or_dir\n";
+        my $size_in_bytes = 0;
+        if (!-r $file_or_dir) {
+            push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file_or_dir];
+            next;
+        }
+        if (is_file($file_or_dir)) {
+            if (!(-s $file_or_dir)) {   # 0 sized file, named pipe, socket 
+                $rh_ignored->{$file_or_dir} = 'zero sized file';
+                next;
+            } elsif (-B $file_or_dir and !$opt_read_binary_files) { 
+                # avoid binary files unless user insists on reading them
+                if ($opt_unicode) {
+                    # only ignore if not a Unicode file w/trivial 
+                    # ASCII transliteration
+                    if (!unicode_file($file_or_dir)) {
+                        $rh_ignored->{$file_or_dir} = 'binary file';
+                        next;
+                    }
+                } else {
+                    $rh_ignored->{$file_or_dir} = 'binary file';
+                    next;
+                }
+            }
+            push @file_list, "$file_or_dir";
+        } elsif (is_dir($file_or_dir)) {
+            push @dir_list, $file_or_dir;
+        } else {
+            push @{$raa_errors}, [$rh_Err->{'Neither file nor directory'} , $file_or_dir];
+            $rh_ignored->{$file_or_dir} = 'not file, not directory';
+        }
+    }
+    foreach my $dir (@dir_list) {
+#print "make_file_list dir=$dir\n";
+        # populates global variable @file_list
+        find({wanted => \&files, follow => $opt_follow_links }, $dir);  
+    }
+    $nFiles_Found = scalar @file_list;
+    printf "%8d text file%s.\n", plural_form($nFiles_Found) unless $opt_quiet;
+    write_file($opt_found, sort @file_list) if $opt_found;
+
+    my $nFiles_Categorized = 0;
+    foreach my $file (@file_list) {
+        printf "classifying $file\n" if $opt_v > 2;
+
+        my $basename = basename $file;
+        if ($Not_Code_Filename{$basename}) {
+            $rh_ignored->{$file} = "listed in " . '$' .
+                "Not_Code_Filename{$basename}";
+            next;
+        } elsif ($basename =~ m{~$}) {
+            $rh_ignored->{$file} = "temporary editor file";
+            next;
+        }
+
+        my $size_in_bytes = (stat $file)[7];
+        my $language      = "";
+        if ($All_One_Language) {
+            # user over-rode auto-language detection by using
+            # --force-lang with just a language name (no extension)
+            $language      = $All_One_Language;
+        } else {
+            $language      = classify_file($file      ,
+                                           $rh_Err    ,
+                                           $raa_errors,
+                                           $rh_ignored);
+        }
+die  "make_file_list($file) undef size" unless defined $size_in_bytes;
+die  "make_file_list($file) undef lang" unless defined $language;
+        printf $fh "%d,%s,%s\n", $size_in_bytes, $language, $file;
+        ++$nFiles_Categorized;
+        #printf "classified %d files\n", $nFiles_Categorized 
+        #    unless (!$opt_progress_rate or 
+        #            ($nFiles_Categorized % $opt_progress_rate));
+    }
+    printf "classified %d files\r", $nFiles_Categorized 
+        if !$opt_quiet and $nFiles_Categorized > 1;
+
+    print "<- make_file_list()\n" if $opt_v > 2;
+
+    return $fh;   # handle to the file containing the list of files to process
+}  # 1}}}
+sub remove_duplicate_files {                 # {{{1
+    my ($fh                   , # in 
+        $rh_Language          , # out
+        $rh_unique_source_file, # out
+        $rh_Err               , # in
+        $raa_errors           , # out  errors encountered
+        $rh_ignored           , # out
+        ) = @_;
+
+    # Check for duplicate files by comparing file sizes.
+    # Where files are equally sized, compare their MD5 checksums.
+    print "-> remove_duplicate_files\n" if $opt_v > 2;
+
+    my $n = 0;
+    my %files_by_size = (); # files_by_size{ # bytes } = [ list of files ]
+    seek($fh, 0, 0); # rewind to beginning of the temp file
+    while (<$fh>) {
+        ++$n;
+        my ($size_in_bytes, $language, $file) = split(/,/, $_, 3);
+        chomp($file);
+        $rh_Language->{$file} = $language;
+        push @{$files_by_size{$size_in_bytes}}, $file;
+        if ($opt_skip_uniqueness) {
+            $rh_unique_source_file->{$file} = 1;
+        }
+    }
+    return if $opt_skip_uniqueness;
+    if ($opt_progress_rate and ($n > $opt_progress_rate)) {
+        printf "Duplicate file check %d files (%d known unique)\r", 
+            $n, scalar keys %files_by_size;
+    }
+    $n = 0;
+    foreach my $bytes (sort {$a <=> $b} keys %files_by_size) {
+        ++$n;
+        printf "Unique: %8d files                                          \r",
+            $n unless (!$opt_progress_rate or ($n % $opt_progress_rate));
+        if (scalar @{$files_by_size{$bytes}} == 1) {
+            # only one file is this big; must be unique
+            $rh_unique_source_file->{$files_by_size{$bytes}[0]} = 1;
+            next;
+        } else {
+#print "equally sized files: ",join(", ", @{$files_by_size{$bytes}}), "\n";
+            # Files in the list @{$files_by_size{$bytes} all are
+            # $bytes long.  Sort the list by file basename.
+            my @sorted_bn = ();
+            my %BN = map { basename($_) => $_ } @{$files_by_size{$bytes}};
+            foreach my $F (sort keys %BN) {
+                push @sorted_bn, $BN{$F};
+            }
+            foreach my $F (different_files(\@sorted_bn  ,
+                                            $rh_Err     ,
+                                            $raa_errors ,
+                                            $rh_ignored ) ) {
+                $rh_unique_source_file->{$F} = 1;
+            }
+        }
+    }
+    print "<- remove_duplicate_files\n" if $opt_v > 2;
+} # 1}}}
+sub files {                                  # {{{1
+    # invoked by File::Find's find()   Populates global variables,
+    # @file_list, %Ignored
+    if ($opt_exclude_dir or $opt_exclude_list_file) {
+        my $return = 0;
+        foreach my $skip_dir (keys %Exclude_Dir) {
+            # File::Find::dir used to always start with / but
+            # newer versions (1.13) no longer do; have to correct for this
+            my $dir = $File::Find::dir;
+               $dir = "./$dir" unless $dir =~ m{^/};
+            if ($dir =~ m{/\Q$skip_dir\E(/|$)} ) {
+                $Ignored{$File::Find::name} = "--exclude-dir=$skip_dir";
+                $return = 1;
+                last;
+            }
+        }
+        return if $return;
+    }
+    my $Dir = cwd(); # not $File::Find::dir which just gives relative path
+	if ($opt_match_f    ) {	return unless /$opt_match_f/;     }
+    if ($opt_not_match_f) {	return if     /$opt_not_match_f/; }
+	if ($opt_match_d    ) {	return unless $Dir =~ m{$opt_match_d}     }
+    if ($opt_not_match_d) {	return if     $Dir =~ m{$opt_not_match_d} }
+
+    my $nBytes = -s     $_ ;
+    if (!$nBytes) {
+        $Ignored{$File::Find::name} = 'zero sized file';
+        printf "files(%s)  zero size\n", $File::Find::name if $opt_v > 5;
+    }
+    return unless $nBytes  ; # attempting other tests w/pipe or socket will hang
+    if ($nBytes > $opt_max_file_size*1024**2) {
+        $Ignored{$File::Find::name} = "file size of " .
+            $nBytes/1024**2 . " MB exceeds max file size of " .
+            "$opt_max_file_size MB";
+        printf "file(%s)  exceeds $opt_max_file_size MB\n", 
+            $File::Find::name if $opt_v > 5;
+        return;
+    }
+    my $is_dir = is_dir($_);
+    my $is_bin = -B     $_ ;
+    printf "files(%s)  size=%d is_dir=%d  -B=%d\n",
+        $File::Find::name, $nBytes, $is_dir, $is_bin if $opt_v > 5;
+    $is_bin = 0 if $opt_unicode and unicode_file($_);
+    $is_bin = 0 if $opt_read_binary_files;
+    return if $is_dir or $is_bin;
+    ++$nFiles_Found;
+    printf "%8d files\r", $nFiles_Found 
+        unless (!$opt_progress_rate or ($nFiles_Found % $opt_progress_rate));
+    push @file_list, $File::Find::name;
+} # 1}}}
+sub archive_files {                          # {{{1
+    # invoked by File::Find's find()  Populates global variable @binary_archive
+    foreach my $ext (keys %Known_Binary_Archives) {
+        push @binary_archive, $File::Find::name 
+            if $File::Find::name =~ m{$ext$};
+    }
+} # 1}}}
+sub is_file {                                # {{{1
+    # portable method to test if item is a file
+    # (-f doesn't work in ActiveState Perl on Windows)
+    my $item = shift @_;
+
+    if ($ON_WINDOWS) {
+        my $mode = (stat $item)[2];
+           $mode = 0 unless $mode;
+        if ($mode & 0100000) { return 1; } 
+        else                 { return 0; }
+    } else {
+        return (-f $item);  # works on Unix, Linux, CygWin, z/OS
+    }
+} # 1}}}
+sub is_dir {                                 # {{{1
+    # portable method to test if item is a directory
+    # (-d doesn't work in ActiveState Perl on Windows)
+    my $item = shift @_;
+
+    if ($ON_WINDOWS) {
+        my $mode = (stat $item)[2];
+           $mode = 0 unless $mode;
+        if ($mode & 0040000) { return 1; } 
+        else                 { return 0; }
+    } else {
+        return (-d $item);  # works on Unix, Linux, CygWin, z/OS
+    }
+} # 1}}}
+sub is_excluded {                            # {{{1
+    my ($file       , # in
+        $excluded   , # in   hash of excluded directories
+       ) = @_;
+    my($filename, $filepath, $suffix) = fileparse($file);
+    foreach my $path (sort keys %{$excluded}) {
+        return 1 if ($filepath =~ m{^$path/}i);
+    }
+} # 1}}}
+sub classify_file {                          # {{{1
+    my ($full_file   , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+        $rh_ignored  , # out
+       ) = @_;
+
+    print "-> classify_file($full_file)\n" if $opt_v > 2;
+    my $language = "(unknown)";
+
+    if (basename($full_file) eq "-" && defined $opt_stdin_name) {
+       $full_file = $opt_stdin_name;
+    }
+
+    my $look_at_first_line = 0;
+    my $file = basename $full_file; 
+    if ($opt_autoconf and $file =~ /\.in$/) {
+       $file =~ s/\.in$//;
+    }
+    return $language if $Not_Code_Filename{$file}; # (unknown)
+    return $language if $file =~ m{~$}; # a temp edit file (unknown)
+    if (defined $Language_by_File{$file}) {
+        if      ($Language_by_File{$file} eq "Ant/XML") {
+            return Ant_or_XML(  $full_file, $rh_Err, $raa_errors);
+        } elsif ($Language_by_File{$file} eq "Maven/XML") {
+            return Maven_or_XML($full_file, $rh_Err, $raa_errors);
+        } else {
+            return $Language_by_File{$file};
+        }
+    }
+
+    if ($file =~ /\.(\w+)$/) { # has an extension
+      print "$full_file extension=[$1]\n" if $opt_v > 2;
+      my $extension = $1;
+         # Windows file names are case insensitive so map 
+         # all extensions to lowercase there.
+         $extension = lc $extension if $ON_WINDOWS;  
+      my @extension_list = ( $extension );
+      if ($file =~ /\.(\w+\.\w+)$/) { # has a double extension
+          my $extension = $1;
+          $extension = lc $extension if $ON_WINDOWS;  
+          unshift @extension_list, $extension;  # examine double ext first
+      }
+      foreach my $extension (@extension_list) {
+        if ($Not_Code_Extension{$extension} and 
+           !$Forced_Extension{$extension}) {
+           # If .1 (for example) is an extention that would ordinarily be
+           # ignored but the user has insisted this be counted with the
+           # --force-lang option, then go ahead and count it.
+            $rh_ignored->{$full_file} = 
+                'listed in $Not_Code_Extension{' . $extension . '}';
+            return $language;
+        }
+        if (defined $Language_by_Extension{$extension}) {
+            if ($Language_by_Extension{$extension} eq
+                'MATLAB/Objective C/MUMPS') {
+                my $lang_M_or_O = "";
+                matlab_or_objective_C($full_file , 
+                                      $rh_Err    ,
+                                      $raa_errors,
+                                     \$lang_M_or_O);
+                if ($lang_M_or_O) {
+                    return $lang_M_or_O;
+                } else { # an error happened in matlab_or_objective_C()
+                    $rh_ignored->{$full_file} = 
+                        'failure in matlab_or_objective_C()';
+                    return $language; # (unknown)
+                }
+            } elsif ($Language_by_Extension{$extension} eq 'PHP/Pascal') {
+                if (really_is_php($full_file)) {
+                    return 'PHP';
+                } elsif (really_is_incpascal($full_file)) {
+                    return 'Pascal';
+                } else {
+                    return $language; # (unknown)
+                }
+            } elsif ($Language_by_Extension{$extension} eq 'Lisp/OpenCL') {
+                return Lisp_or_OpenCL($full_file, $rh_Err, $raa_errors);
+            } elsif ($Language_by_Extension{$extension} eq 'Smarty') {
+                # Smarty extension .tpl is generic; make sure the
+                # file at least roughly resembles PHP.  Alternatively,
+                # if the user forces the issue, do the count.
+                my $force_smarty = 0;
+                foreach (@opt_force_lang) {
+                    if (lc($_) eq "smarty,tpl") {
+                        $force_smarty = 1; 
+                        last;
+                    }
+                }
+                if (really_is_php($full_file) or $force_smarty) {
+                    return 'Smarty';
+                } else {
+                    return $language; # (unknown)
+                }
+            } else {
+                return $Language_by_Extension{$extension};
+            }
+        } else { # has an unmapped file extension
+            $look_at_first_line = 1;
+        }
+      }
+    } elsif (defined $Language_by_File{lc $file}) {
+        return $Language_by_File{lc $file};
+    } elsif ($opt_lang_no_ext and 
+             defined $Filters_by_Language{$opt_lang_no_ext}) {
+        return $opt_lang_no_ext;
+    } else {  # no file extension
+        $look_at_first_line = 1;
+    }
+
+    if ($look_at_first_line) {
+        # maybe it is a shell/Perl/Python/Ruby/etc script that
+        # starts with pound bang:
+        #   #!/usr/bin/perl
+        #   #!/usr/bin/env perl
+        my $script_language = peek_at_first_line($full_file , 
+                                                 $rh_Err    , 
+                                                 $raa_errors);
+        if (!$script_language) {
+            $rh_ignored->{$full_file} = "language unknown (#2)";
+            # returns (unknown)
+        }
+        if (defined $Language_by_Script{$script_language}) {
+            if (defined $Filters_by_Language{
+                            $Language_by_Script{$script_language}}) {
+                $language = $Language_by_Script{$script_language};
+            } else {
+                $rh_ignored->{$full_file} = 
+                    "undefined:  Filters_by_Language{" . 
+                    $Language_by_Script{$script_language} .
+                    "} for scripting language $script_language";
+                # returns (unknown)
+            }
+        } else {
+            $rh_ignored->{$full_file} = "language unknown (#3)";
+            # returns (unknown)
+        }
+    }
+    print "<- classify_file($full_file)\n" if $opt_v > 2;
+    return $language;
+} # 1}}}
+sub peek_at_first_line {                     # {{{1
+    my ($file        , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+       ) = @_;
+
+    print "-> peek_at_first_line($file)\n" if $opt_v > 2;
+
+    my $script_language = "";
+    if (!-r $file) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        return $script_language;
+    }
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        print "<- peek_at_first_line($file)\n" if $opt_v > 2;
+        return $script_language;
+    }
+    chomp(my $first_line = <$IN>);
+    if (defined $first_line) {
+#print "peek_at_first_line of [$file] first_line=[$first_line]\n";
+        if ($first_line =~ /^#\!\s*(\S.*?)$/) {
+#print "peek_at_first_line 1=[$1]\n";
+            my @pound_bang = split(' ', $1);
+#print "peek_at_first_line basename 0=[", basename($pound_bang[0]), "]\n";
+            if (basename($pound_bang[0]) eq "env" and 
+                scalar @pound_bang > 1) {
+                $script_language = $pound_bang[1];
+#print "peek_at_first_line pound_bang A $pound_bang[1]\n";
+            } else {
+                $script_language = basename $pound_bang[0];
+#print "peek_at_first_line pound_bang B $script_language\n";
+            }
+        }
+    }
+    $IN->close;
+    print "<- peek_at_first_line($file)\n" if $opt_v > 2;
+    return $script_language;
+} # 1}}}
+sub different_files {                        # {{{1
+    # See which of the given files are unique by computing each file's MD5
+    # sum.  Return the subset of files which are unique.
+    my ($ra_files    , # in
+        $rh_Err      , # in
+        $raa_errors  , # out
+        $rh_ignored  , # out
+       ) = @_;
+
+    print "-> different_files(@{$ra_files})\n" if $opt_v > 2;
+    my %file_hash = ();  # file_hash{md5 hash} = [ file1, file2, ... ]
+    foreach my $F (@{$ra_files}) {
+        next if is_dir($F);  # needed for Windows
+        my $IN = new IO::File $F, "r";
+        if (!defined $IN) {
+            push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $F];
+            $rh_ignored->{$F} = 'cannot read';
+        } else {
+            if ($HAVE_Digest_MD5) {
+                binmode $IN;
+                my $MD5 = Digest::MD5->new->addfile($IN)->hexdigest;
+#print "$F, $MD5\n";
+                push @{$file_hash{$MD5}}, $F;
+            } else {
+                # all files treated unique
+                push @{$file_hash{$F}}, $F;
+            }
+            $IN->close;
+        }
+    }
+
+    # Loop over file sets having identical MD5 sums.  Within
+    # each set, pick the file that most resembles known source 
+    # code.
+    my @unique = ();
+    for my $md5 (sort keys %file_hash) {
+        my $i_best = 0;
+        for (my $i = 1; $i < scalar(@{$file_hash{$md5}}); $i++) {
+            my $F = $file_hash{$md5}[$i];
+            my (@nul_a, %nul_h);
+            my $language = classify_file($F, $rh_Err, 
+                                        # don't save these errors; pointless
+                                        \@nul_a, \%nul_h);
+            $i_best = $i if $language ne "(unknown)";
+        }
+        # keep the best one found and identify the rest as ignored
+        for (my $i = 0; $i < scalar(@{$file_hash{$md5}}); $i++) {
+            if ($i == $i_best) {
+                push @unique, $file_hash{$md5}[$i_best];
+            } else {
+                $rh_ignored->{$file_hash{$md5}[$i]} = "duplicate of " .
+                    $file_hash{$md5}[$i_best];
+            }
+        }
+
+    }
+    print "<- different_files(@unique)\n" if $opt_v > 2;
+    return @unique;
+} # 1}}}
+sub call_counter {                           # {{{1
+    my ($file     , # in
+        $language , # in
+        $ra_Errors, # out
+       ) = @_;
+
+    # Logic:  pass the file through the following filters:
+    #         1. remove blank lines
+    #         2. remove comments using each filter defined for this language
+    #            (example:  SQL has two, remove_starts_with(--) and 
+    #             remove_c_comments() )
+    #         3. compute comment lines as 
+    #               total lines - blank lines - lines left over after all
+    #                   comment filters have been applied
+
+    print "-> call_counter($file, $language)\n" if $opt_v > 2;
+#print "call_counter:  ", Dumper(@routines), "\n";
+
+    my @lines = ();
+    my $ascii = "";
+    if (-B $file and $opt_unicode) {
+        # was binary so must be unicode
+
+        $/ = undef;
+        my $IN = new IO::File $file, "r";
+        my $bin_text = <$IN>;
+        $IN->close;
+        $/ = "\n";
+
+        $ascii = unicode_to_ascii( $bin_text );
+        @lines = split("\n", $ascii );
+        foreach (@lines) { $_ = "$_\n"; }
+
+    } else {
+        # regular text file
+        @lines = read_file($file);
+        $ascii = join('', @lines);
+    }
+
+    my @original_lines = @lines;
+    my $total_lines    = scalar @lines;
+
+    print_lines($file, "Original file:", \@lines) if $opt_print_filter_stages;
+    @lines = rm_blanks(\@lines, $language, \%EOL_Continuation_re); # remove blank lines
+    my $blank_lines = $total_lines - scalar @lines;
+    print_lines($file, "Blank lines removed:", \@lines) 
+        if $opt_print_filter_stages;
+
+    @lines = rm_comments(\@lines, $language, $file,
+                               \%EOL_Continuation_re);
+
+    my $comment_lines = $total_lines - $blank_lines - scalar  @lines;
+    if ($opt_strip_comments) {
+        my $stripped_file = "";
+        if ($opt_original_dir) {
+            $stripped_file =          $file . ".$opt_strip_comments";
+        } else {
+            $stripped_file = basename $file . ".$opt_strip_comments";
+        }
+        write_file($stripped_file, @lines);
+    }
+    if ($opt_html and !$opt_diff) {
+        chomp(@original_lines);  # includes blank lines, comments
+        chomp(@lines);           # no blank lines, no comments
+
+        my (@diff_L, @diff_R, %count);
+
+        # remove blank lines to get better quality diffs; count
+        # blank lines separately
+        my @original_lines_minus_white = ();
+        # however must keep track of how many blank lines were removed and
+        # where they were removed so that the HTML display can include it
+        my %blank_line  = ();
+        my $insert_line = 0;
+        foreach (@original_lines) {
+            if (/^\s*$/) {
+               ++$count{blank}{same};
+               ++$blank_line{ $insert_line };
+            } else {
+                ++$insert_line;
+                push @original_lines_minus_white, $_;
+            }
+        }
+
+        array_diff( $file                       ,   # in
+                   \@original_lines_minus_white ,   # in
+                   \@lines                      ,   # in
+                   "comment"                    ,   # in
+                   \@diff_L, \@diff_R,          ,   # out
+                    $ra_Errors);                    # in/out
+        write_comments_to_html($file, \@diff_L, \@diff_R, \%blank_line);
+#print Dumper("count", \%count);
+    }
+
+    print "<- call_counter($total_lines, $blank_lines, $comment_lines)\n" 
+        if $opt_v > 2;
+    return ($total_lines, $blank_lines, $comment_lines);
+} # 1}}}
+sub windows_glob {                           # {{{1
+    # Windows doesn't expand wildcards.  Use code from Sean M. Burke's 
+    # Win32::Autoglob module to do this.
+    return map {;
+        ( defined($_) and m/[\*\?]/ ) ? sort(glob($_)) : $_
+          } @_; 
+} # 1}}}
+sub write_file {                             # {{{1
+    my ($file  , # in
+        @lines , # in
+       ) = @_;
+
+#print "write_file 1 [$file]\n";
+    # Do ~ expansion (by Tim LaBerge, fixes bug 2787984)
+    my $preglob_filename = $file;
+#print "write_file 2 [$preglob_filename]\n";
+    if ($ON_WINDOWS) {
+        $file = (windows_glob($file))[0];
+    } else {
+        $file = File::Glob::glob($file);
+    }
+#print "write_file 3 [$file]\n";
+    $file = $preglob_filename unless $file;
+#print "write_file 4 [$file]\n";
+
+    print "-> write_file($file)\n" if $opt_v > 2;
+
+    # Create the destination directory if it doesn't already exist.
+    my $abs_file_path = File::Spec->rel2abs( $file );
+    my ($volume, $directories, $filename) = File::Spec->splitpath( $abs_file_path );
+    mkpath($volume . $directories, 1, 0777);
+    
+    my $OUT = new IO::File $file, "w";
+    if (defined $OUT) {
+        chomp(@lines);
+        print $OUT join("\n", @lines), "\n";
+        $OUT->close;
+    } else {
+        warn "Unable to write to $file\n";
+    }
+    print "Wrote $file" unless $opt_quiet;
+    print ", $CLOC_XSL" if $opt_xsl and $opt_xsl eq $CLOC_XSL;
+    print "\n" unless $opt_quiet;
+    
+    print "<- write_file\n" if $opt_v > 2;
+} # 1}}}
+sub read_file  {                             # {{{1
+    my ($file, ) = @_;
+
+    print "-> read_file($file)\n" if $opt_v > 2;
+    my @lines = ();
+    my $IN = new IO::File $file, "r";
+    if (defined $IN) {
+        @lines = <$IN>;
+        $IN->close;
+        if ($lines[$#lines]) {  # test necessary for zero content files
+                                # (superfluous?)
+            # Some files don't end with a new line.  Force this:
+            $lines[$#lines] .= "\n" unless $lines[$#lines] =~ m/\n$/;
+        }
+    } else {
+        warn "Unable to read $file\n";
+    }
+    print "<- read_file\n" if $opt_v > 2;
+    return @lines;
+} # 1}}}
+sub rm_blanks {                              # {{{1
+    my ($ra_in    ,
+        $language ,
+        $rh_EOL_continuation_re) = @_;
+    print "-> rm_blanks(language=$language)\n" if $opt_v > 2;
+#print "rm_blanks: language = [$language]\n";
+    my @out = ();
+    if ($language eq "COBOL") {
+        @out = remove_cobol_blanks($ra_in);
+    } else {
+        # removes blank lines
+        if (defined $rh_EOL_continuation_re->{$language}) {
+            @out = remove_matches_2re($ra_in, '^\s*$', 
+                                      $rh_EOL_continuation_re->{$language}); 
+        } else {
+            @out = remove_matches($ra_in, '^\s*$');
+        }
+    }
+    print "<- rm_blanks(language=$language)\n" if $opt_v > 2;
+    return @out;
+} # 1}}}
+sub rm_comments {                            # {{{1
+    my ($ra_lines , # in, must be free of blank lines
+        $language , # in
+        $file     , # in (some language counters, eg Haskell, need 
+                    #     access to the original file)
+        $rh_EOL_continuation_re , # in
+       ) = @_;
+    print "-> rm_comments(file=$file)\n" if $opt_v > 2;
+    my @routines       = @{$Filters_by_Language{$language}};
+    my @lines          = @{$ra_lines};
+    my @original_lines = @{$ra_lines};
+
+    foreach my $call_string (@routines) {
+        my $subroutine = $call_string->[0];
+        if (! defined &{$subroutine}) {
+            warn "rm_comments undefined subroutine $subroutine for $file\n";
+            next;
+        }
+        print "rm_comments file=$file sub=$subroutine\n" if $opt_v > 1;
+        my @args  = @{$call_string};
+        shift @args; # drop the subroutine name
+        if (@args and $args[0] eq '>filename<') {
+            shift   @args;
+            unshift @args, $file;
+        }
+
+        no strict 'refs';
+        @lines = &{$subroutine}(\@lines, @args);   # apply filter...
+
+        print_lines($file, "After $subroutine(@args)", \@lines) 
+            if $opt_print_filter_stages;
+        # then remove blank lines which are created by comment removal
+        if (defined $rh_EOL_continuation_re->{$language}) {
+            @lines = remove_matches_2re(\@lines, '^\s*$',
+                                        $rh_EOL_continuation_re->{$language});
+        } else {
+            @lines = remove_matches(\@lines, '^\s*$');
+        }
+        
+        print_lines($file, "post $subroutine(@args) blank cleanup:", \@lines) 
+            if $opt_print_filter_stages;
+    }
+    # Exception for scripting languages:  treat the first #! line as code.
+    # Will need to add it back in if it was removed earlier.
+    if ($Script_Language{$language} and 
+        $original_lines[0] =~ /^#!/ and
+        (scalar(@lines) == 0 or 
+         $lines[0] ne $original_lines[0])) {
+        unshift @lines, $original_lines[0];  # add the first line back
+    }
+    print "<- rm_comments\n" if $opt_v > 2;
+    return @lines;
+} # 1}}}
+sub remove_f77_comments {                    # {{{1
+    my ($ra_lines, ) = @_;
+    print "-> remove_f77_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    foreach (@{$ra_lines}) {
+        next if m{^[*cC]};
+        next if m{^\s*!};
+        push @save_lines, $_;
+    }
+
+    print "<- remove_f77_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_f90_comments {                    # {{{1
+    # derived from SLOCCount
+    my ($ra_lines, ) = @_;
+    print "-> remove_f90_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    foreach (@{$ra_lines}) {
+        # a comment is              m/^\s*!/
+        # an empty line is          m/^\s*$/
+        # a HPF statement is        m/^\s*!hpf\$/i
+        # an Open MP statement is   m/^\s*!omp\$/i
+        if (! m/^(\s*!|\s*$)/ || m/^\s*!(hpf|omp)\$/i) {
+            push @save_lines, $_;
+        }
+    }
+
+    print "<- remove_f90_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_matches {                         # {{{1
+    my ($ra_lines, # in
+        $pattern , # in   Perl regular expression (case insensitive)
+       ) = @_;
+    print "-> remove_matches(pattern=$pattern)\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    foreach (@{$ra_lines}) {
+#chomp; print "remove_matches [$pattern] [$_]\n";
+        next if m{$pattern}i;
+        push @save_lines, $_;
+    }
+
+    print "<- remove_matches\n" if $opt_v > 2;
+#print "remove_matches returning\n   ", join("\n   ", @save_lines), "\n";
+    return @save_lines;
+} # 1}}}
+sub remove_matches_2re {                     # {{{1
+    my ($ra_lines, # in
+        $pattern1, # in Perl regex 1 (case insensitive) to match
+        $pattern2, # in Perl regex 2 (case insensitive) to not match prev line
+       ) = @_;
+    print "-> remove_matches_2re(pattern=$pattern1,$pattern2)\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    for (my $i = 0; $i < scalar @{$ra_lines}; $i++) {
+#print "remove_matches_2re [$pattern1] [$pattern2] [$ra_lines->[$i]]\n";
+        if ($i) {
+#print "remove_matches_2re prev=[$ra_lines->[$i-1]] this=[$ra_lines->[$i]]\n";
+            next if ($ra_lines->[$i]   =~ m{$pattern1}i) and 
+                    ($ra_lines->[$i-1] !~ m{$pattern2}i);
+        } else {
+            # on first line
+            next if $ra_lines->[$i]   =~  m{$pattern1}i;
+        }
+        push @save_lines, $ra_lines->[$i];
+    }
+
+    print "<- remove_matches_2re\n" if $opt_v > 2;
+#print "remove_matches_2re returning\n   ", join("\n   ", @save_lines), "\n";
+    return @save_lines;
+} # 1}}}
+sub remove_inline {                          # {{{1
+    my ($ra_lines, # in
+        $pattern , # in   Perl regular expression (case insensitive)
+       ) = @_;
+    print "-> remove_inline(pattern=$pattern)\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    unless ($opt_inline) {
+        return @{$ra_lines};
+    }
+    my $nLines_affected = 0;
+    foreach (@{$ra_lines}) {
+#chomp; print "remove_inline [$pattern] [$_]\n";
+        if (m{$pattern}i) {
+            ++$nLines_affected;
+            s{$pattern}{}i;
+        }
+        push @save_lines, $_;
+    }
+
+    print "<- remove_inline\n" if $opt_v > 2;
+#print "remove_inline returning\n   ", join("\n   ", @save_lines), "\n";
+    return @save_lines;
+} # 1}}}
+sub remove_above {                           # {{{1
+    my ($ra_lines, $marker, ) = @_;
+    print "-> remove_above(marker=$marker)\n" if $opt_v > 2;
+
+    # Make two passes through the code:
+    # 1. check if the marker exists
+    # 2. remove anything above the marker if it exists,
+    #    do nothing if the marker does not exist
+
+    # Pass 1
+    my $found_marker = 0;
+    for (my $line_number  = 1;
+            $line_number <= scalar @{$ra_lines};
+            $line_number++) {
+        if ($ra_lines->[$line_number-1] =~ m{$marker}) {
+            $found_marker = $line_number;
+            last;
+        }
+    }
+
+    # Pass 2 only if needed
+    my @save_lines = ();
+    if ($found_marker) {
+        my $n = 1;
+        foreach (@{$ra_lines}) {
+            push @save_lines, $_
+                if $n >= $found_marker;
+            ++$n;
+        }
+    } else { # marker wasn't found; save all lines
+        foreach (@{$ra_lines}) {
+            push @save_lines, $_;
+        }
+    }
+
+    print "<- remove_above\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_below {                           # {{{1
+    my ($ra_lines, $marker, ) = @_;
+    print "-> remove_below(marker=$marker)\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    foreach (@{$ra_lines}) {
+        last if m{$marker};
+        push @save_lines, $_;
+    }
+
+    print "<- remove_below\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_below_above {                     # {{{1
+    my ($ra_lines, $marker_below, $marker_above, ) = @_;
+    # delete lines delimited by start and end line markers such
+    # as Perl POD documentation
+    print "-> remove_below_above(markerB=$marker_below, A=$marker_above)\n" 
+        if $opt_v > 2;
+
+    my @save_lines = ();
+    my $between    = 0;
+    foreach (@{$ra_lines}) {
+        if (!$between and m{$marker_below}) {
+            $between    = 1;
+            next;
+        }
+        if ($between and m{$marker_above}) {
+            $between    = 0;
+            next;
+        }
+        next if $between;
+        push @save_lines, $_;
+    }
+
+    print "<- remove_below_above\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_between {                         # {{{1
+    my ($ra_lines, $marker, ) = @_;
+    # $marker must contain one of the balanced pairs understood
+    # by Regexp::Common::balanced, namely
+    # '{}'  '()'  '[]'  or  '<>'
+
+    print "-> remove_between(marker=$marker)\n" if $opt_v > 2;
+    my %acceptable = ('{}'=>1,  '()'=>1,  '[]'=>1,  '<>'=>1, );
+    die "remove_between:  invalid delimiter '$marker'\n",
+        "the delimiter must be one of these four pairs:\n",
+        "{}  ()  []  <>\n" unless
+        $acceptable{$marker};
+
+    Install_Regexp_Common() unless $HAVE_Rexexp_Common;
+
+    my $all_lines = join("", @{$ra_lines});
+
+    no strict 'vars';
+    # otherwise get:
+    #  Global symbol "%RE" requires explicit package name at cloc line xx.
+    if ($all_lines =~ m/$RE{balanced}{-parens => $marker}/) {
+        no warnings; 
+        $all_lines =~ s/$1//g;
+    }
+
+    print "<- remove_between\n" if $opt_v > 2;
+    return split("\n", $all_lines);
+} # 1}}}
+sub remove_between_general {                 # {{{1
+    my ($ra_lines, $start_marker, $end_marker, ) = @_;
+    # Start and end markers may be any length strings.
+
+    print "-> remove_between_general(start=$start_marker, end=$end_marker)\n"
+        if $opt_v > 2;
+
+    my $all_lines = join("", @{$ra_lines});
+
+    my @save_lines = ();
+    my $in_comment = 0;
+    foreach (@{$ra_lines}) {
+
+        next if /^\s*$/;
+        s/\Q$start_marker\E.*?\Q$end_marker\E//g;  # strip one-line comments
+        next if /^\s*$/;
+        if ($in_comment) {
+            if (/\Q$end_marker\E/) {
+                s/^.*?\Q$end_marker\E//;
+                $in_comment = 0;
+            }
+        }
+        next if /^\s*$/;
+        $in_comment = 1 if /^(.*?)\Q$start_marker\E/;
+        next if defined $1 and $1 =~ /^\s*$/;
+        next if ($in_comment);
+        push @save_lines, $_;
+    }
+
+    print "<- remove_between_general\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_cobol_blanks {                    # {{{1
+    # subroutines derived from SLOCCount
+    my ($ra_lines, ) = @_;
+
+    my $free_format = 0;  # Support "free format" source code.
+    my @save_lines  = ();
+  
+    foreach (@{$ra_lines}) {
+        next if m/^\s*$/;
+        my $line = expand($_);  # convert tabs to equivalent spaces
+        $free_format = 1 if $line =~ m/^......\$.*SET.*SOURCEFORMAT.*FREE/i;
+        if ($free_format) {
+            push @save_lines, $_;
+        } else {
+            # Greg Toth:
+            #  (1) Treat lines with any alphanum in cols 1-6 and 
+            #      blanks in cols 7 through 71 as blank line, and
+            #  (2) Treat lines with any alphanum in cols 1-6 and 
+            #      slash (/) in col 7 as blank line (this is a 
+            #      page eject directive). 
+            push @save_lines, $_ unless m/^\d{6}\s*$/             or 
+                                        ($line =~ m/^.{6}\s{66}/) or 
+                                        ($line =~ m/^......\//);
+        }
+    }
+    return @save_lines;
+} # 1}}}
+sub remove_cobol_comments {                  # {{{1
+    # subroutines derived from SLOCCount
+    my ($ra_lines, ) = @_;
+
+    my $free_format = 0;  # Support "free format" source code.
+    my @save_lines  = ();
+  
+    foreach (@{$ra_lines}) {
+        if (m/^......\$.*SET.*SOURCEFORMAT.*FREE/i) {$free_format = 1;}
+        if ($free_format) {
+            push @save_lines, $_ unless m{^\s*\*};
+        } else {
+            push @save_lines, $_ unless m{^......\*} or m{^\*};
+        }
+    }
+    return @save_lines;
+} # 1}}}
+sub remove_jcl_comments {                    # {{{1
+    my ($ra_lines, ) = @_;
+
+    print "-> remove_jcl_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    my $in_comment = 0;
+    foreach (@{$ra_lines}) {
+        next if /^\s*$/;
+        next if m{^\s*//\*};
+        last if m{^\s*//\s*$};
+        push @save_lines, $_;
+    }
+
+    print "<- remove_jcl_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_jsp_comments {                    # {{{1
+    #  JSP comment is   <%--  body of comment   --%>
+    my ($ra_lines, ) = @_;
+
+    print "-> remove_jsp_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    my $in_comment = 0;
+    foreach (@{$ra_lines}) {
+
+        next if /^\s*$/;
+        s/<\%\-\-.*?\-\-\%>//g;  # strip one-line comments
+        next if /^\s*$/;
+        if ($in_comment) {
+            if (/\-\-\%>/) {
+                s/^.*?\-\-\%>//;
+                $in_comment = 0;
+            }
+        }
+        next if /^\s*$/;
+        $in_comment = 1 if /^(.*?)<\%\-\-/;
+        next if defined $1 and $1 =~ /^\s*$/;
+        next if ($in_comment);
+        push @save_lines, $_;
+    }
+
+    print "<- remove_jsp_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub remove_html_comments {                   # {{{1
+    #  HTML comment is   <!--  body of comment   -->
+    #  Need to use my own routine until the HTML comment regex in
+    #  the Regexp::Common module can handle  <!--  --  -->
+    my ($ra_lines, ) = @_;
+
+    print "-> remove_html_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    my $in_comment = 0;
+    foreach (@{$ra_lines}) {
+
+        next if /^\s*$/;
+        s/<!\-\-.*?\-\->//g;  # strip one-line comments
+        next if /^\s*$/;
+        if ($in_comment) {
+            if (/\-\->/) {
+                s/^.*?\-\->//;
+                $in_comment = 0;
+            }
+        }
+        next if /^\s*$/;
+        $in_comment = 1 if /^(.*?)<!\-\-/;
+        next if defined $1 and $1 =~ /^\s*$/;
+        next if ($in_comment);
+        push @save_lines, $_;
+    }
+
+    print "<- remove_html_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub add_newlines {                           # {{{1
+    my ($ra_lines, ) = @_;
+    print "-> add_newlines \n" if $opt_v > 2;
+
+    my @save_lines = ();
+    foreach (@{$ra_lines}) {
+
+        push @save_lines, "$_\n";
+    }
+
+    print "<- add_newlines \n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub docstring_to_C {                         # {{{1
+    my ($ra_lines, ) = @_;
+    # Converts Python docstrings to C comments.
+
+    print "-> docstring_to_C()\n" if $opt_v > 2;
+
+    my $in_docstring = 0;
+    foreach (@{$ra_lines}) {
+        while (/"""/) {
+            if (!$in_docstring) {
+                s{"""}{/*};
+                $in_docstring = 1;
+            } else {
+                s{"""}{*/};
+                $in_docstring = 0;
+            }
+        }
+    }
+
+    print "<- docstring_to_C\n" if $opt_v > 2;
+    return @{$ra_lines};
+} # 1}}}
+sub powershell_to_C {                        # {{{1
+    my ($ra_lines, ) = @_;
+    # Converts PowerShell block comment markers to C comments.
+
+    print "-> powershell_to_C()\n" if $opt_v > 2;
+
+    my $in_docstring = 0;
+    foreach (@{$ra_lines}) {
+        s{<#}{/*}g;
+        s{#>}{*/}g;
+    }
+
+    print "<- powershell_to_C\n" if $opt_v > 2;
+    return @{$ra_lines};
+} # 1}}}
+sub smarty_to_C {                            # {{{1
+    my ($ra_lines, ) = @_;
+    # Converts Smarty comments to C comments.
+
+    print "-> smarty_to_C()\n" if $opt_v > 2;
+
+    foreach (@{$ra_lines}) {
+        s[{\*][/*]g;
+        s[\*}][*/]g;
+    }
+
+    print "<- smarty_to_C\n" if $opt_v > 2;
+    return @{$ra_lines};
+} # 1}}}
+sub determine_lit_type {                     # {{{1
+  my ($file) = @_;
+
+  open (FILE, $file);
+  while (<FILE>) {
+    if (m/^\\begin{code}/) { close FILE; return 2; }
+    if (m/^>\s/) { close FILE; return 1; }
+  }
+
+  return 0;
+} # 1}}}
+sub remove_haskell_comments {                # {{{1
+    # Bulk of code taken from SLOCCount's haskell_count script.
+    # Strips out {- .. -} and -- comments and counts the rest.
+    # Pragmas, {-#...}, are counted as SLOC.
+    # BUG: Doesn't handle strings with embedded block comment markers gracefully.
+    #      In practice, that shouldn't be a problem.
+    my ($ra_lines, $file, ) = @_;
+
+    print "-> remove_haskell_comments\n" if $opt_v > 2;
+
+    my @save_lines = ();
+    my $in_comment = 0;
+    my $incomment  = 0;
+    my ($literate, $inlitblock) = (0,0);
+  
+    $literate = 1 if $file =~ /\.lhs$/;
+    if($literate) { $literate = determine_lit_type($file) }
+
+    foreach (@{$ra_lines}) {
+        if ($literate == 1) {
+            if (!s/^>//) { s/.*//; }
+        } elsif ($literate == 2) {
+            if ($inlitblock) {
+                if (m/^\\end{code}/) { s/.*//; $inlitblock = 0; }
+            } elsif (!$inlitblock) {
+                if (m/^\\begin{code}/) { s/.*//; $inlitblock = 1; }
+                else { s/.*//; }
+            }
+        }
+
+        if ($incomment) {
+            if (m/\-\}/) { s/^.*?\-\}//;  $incomment = 0;}
+            else { s/.*//; }
+        }
+        if (!$incomment) {
+            s/--.*//;
+            s!{-[^#].*?-}!!g;
+            if (m/{-/ && (!m/{-#/)) {
+              s/{-.*//;
+              $incomment = 1;
+            }
+        }
+        if (m/\S/) { push @save_lines, $_; }
+    }
+#   if ($incomment) {print "ERROR: ended in comment in $ARGV\n";}
+
+    print "<- remove_haskell_comments\n" if $opt_v > 2;
+    return @save_lines;
+} # 1}}}
+sub print_lines {                            # {{{1
+    my ($file     , # in
+        $title    , # in
+        $ra_lines , # in
+       ) = @_;
+    printf "->%-30s %s\n", $file, $title;
+    for (my $i = 0; $i < scalar @{$ra_lines}; $i++) {
+        printf "%5d | %s", $i+1, $ra_lines->[$i];
+        print "\n" unless $ra_lines->[$i] =~ m{\n$}
+    }
+} # 1}}}
+sub set_constants {                          # {{{1
+    my ($rh_Language_by_Extension , # out
+        $rh_Language_by_Script    , # out
+        $rh_Language_by_File      , # out
+        $rhaa_Filters_by_Language , # out
+        $rh_Not_Code_Extension    , # out
+        $rh_Not_Code_Filename     , # out
+        $rh_Scale_Factor          , # out
+        $rh_Known_Binary_Archives , # out
+        $rh_EOL_continuation_re   , # out
+       ) = @_;
+# 1}}}
+%{$rh_Language_by_Extension} = (             # {{{1
+            'abap'        => 'ABAP'                  ,
+            'ac'          => 'm4'                    ,
+            'ada'         => 'Ada'                   ,
+            'adb'         => 'Ada'                   ,
+            'ads'         => 'Ada'                   ,
+            'adso'        => 'ADSO/IDSM'             ,
+            'ahk'         => 'AutoHotkey'            ,
+            'am'          => 'make'                  ,
+            'ample'       => 'AMPLE'                 ,
+            'as'          => 'ActionScript'          ,
+            'dofile'      => 'AMPLE'                 ,
+            'startup'     => 'AMPLE'                 ,
+            'asa'         => 'ASP'                   ,
+            'asax'        => 'ASP.Net'               ,
+            'ascx'        => 'ASP.Net'               ,
+            'asm'         => 'Assembly'              ,
+            'asmx'        => 'ASP.Net'               ,
+            'asp'         => 'ASP'                   ,
+            'aspx'        => 'ASP.Net'               ,
+            'master'      => 'ASP.Net'               ,
+            'sitemap'     => 'ASP.Net'               ,
+            'cshtml'      => 'Razor'                 ,
+            'awk'         => 'awk'                   ,
+            'bash'        => 'Bourne Again Shell'    ,
+            'bas'         => 'Visual Basic'          ,
+            'bat'         => 'DOS Batch'             ,
+            'BAT'         => 'DOS Batch'             ,
+            'build.xml'   => 'Ant'                   ,
+            'cbl'         => 'COBOL'                 ,
+            'CBL'         => 'COBOL'                 ,
+            'c'           => 'C'                     ,
+            'C'           => 'C++'                   ,
+            'cc'          => 'C++'                   ,
+            'ccs'         => 'CCS'                   ,
+            'cfc'         => 'ColdFusion CFScript'   ,
+            'cfm'         => 'ColdFusion'            ,
+            'cl'          => 'Lisp/OpenCL'           ,
+            'clj'         => 'Clojure'               ,
+            'cljs'        => 'ClojureScript'         ,
+            'cls'         => 'Visual Basic'          , # also Apex Class
+            'CMakeLists.txt' => 'CMake'              ,
+            'cmake'       => 'CMake'                 ,
+            'cob'         => 'COBOL'                 ,
+            'COB'         => 'COBOL'                 ,
+            'coffee'      => 'CoffeeScript'          ,
+            'component'   => 'Visualforce Component' ,
+            'config'      => 'ASP.Net'               ,
+            'cpp'         => 'C++'                   ,
+            'cs'          => 'C#'                    ,
+            'csh'         => 'C Shell'               ,
+            'css'         => "CSS"                   ,
+            'ctl'         => 'Visual Basic'          ,
+            'cxx'         => 'C++'                   ,
+            'd'           => 'D'                     ,
+            'da'          => 'DAL'                   ,
+            'dart'        => 'Dart'                  ,
+            'def'         => 'Teamcenter def'        ,
+            'dmap'        => 'NASTRAN DMAP'          ,
+            'dpr'         => 'Pascal'                ,
+            'dsr'         => 'Visual Basic'          ,
+            'dtd'         => 'DTD'                   ,
+            'ec'          => 'C'                     ,
+            'el'          => 'Lisp'                  ,
+            'erl'         => 'Erlang'                ,
+            'exp'         => 'Expect'                ,
+            'f77'         => 'Fortran 77'            ,
+            'F77'         => 'Fortran 77'            ,
+            'f90'         => 'Fortran 90'            ,
+            'F90'         => 'Fortran 90'            ,
+            'f95'         => 'Fortran 95'            ,
+            'F95'         => 'Fortran 95'            ,
+            'f'           => 'Fortran 77'            ,
+            'F'           => 'Fortran 77'            ,
+            'fmt'         => 'Oracle Forms'          ,
+            'focexec'     => 'Focus'                 ,
+            'frm'         => 'Visual Basic'          ,
+            'gnumakefile' => 'make'                  ,
+            'Gnumakefile' => 'make'                  ,
+            'go'          => 'Go'                    ,
+            'groovy'      => 'Groovy'                ,
+            'gant'        => 'Groovy'                ,
+            'h'           => 'C/C++ Header'          ,
+            'H'           => 'C/C++ Header'          ,
+            'hh'          => 'C/C++ Header'          ,
+            'hpp'         => 'C/C++ Header'          ,
+            'hrl'         => 'Erlang'                ,
+            'hs'          => 'Haskell'               , 
+            'htm'         => 'HTML'                  ,
+            'html'        => 'HTML'                  ,
+            'i3'          => 'Modula3'               ,
+            'idl'         => 'IDL'                   ,
+            'ism'         => 'InstallShield'         ,
+            'pro'         => 'IDL'                   ,
+            'ig'          => 'Modula3'               ,
+            'il'          => 'SKILL'                 ,
+            'ils'         => 'SKILL++'               ,
+            'inc'         => 'PHP/Pascal'            , # might be PHP or Pascal
+            'ino'         => 'Arduino Sketch'        ,
+            'pde'         => 'Arduino Sketch'        , # pre 1.0
+            'itk'         => 'Tcl/Tk'                ,
+            'java'        => 'Java'                  ,
+            'jcl'         => 'JCL'                   , # IBM Job Control Lang.
+            'jl'          => 'Lisp'                  ,
+            'js'          => 'Javascript'            ,
+            'jsf'         => 'JavaServer Faces'      ,
+            'xhtml'       => 'JavaServer Faces'      ,
+            'jsp'         => 'JSP'                   , # Java server pages
+            'ksc'         => 'Kermit'                ,
+            'ksh'         => 'Korn Shell'            ,
+            'lhs'         => 'Haskell'               ,
+            'l'           => 'lex'                   ,
+            'less'        => 'LESS'                  ,
+            'lsp'         => 'Lisp'                  ,
+            'lisp'        => 'Lisp'                  ,
+            'lua'         => 'Lua'                   ,
+            'm3'          => 'Modula3'               ,
+            'm4'          => 'm4'                    ,
+            'makefile'    => 'make'                  ,
+            'Makefile'    => 'make'                  ,
+            'met'         => 'Teamcenter met'        ,
+            'mg'          => 'Modula3'               , 
+#           'mli'         => 'ML'                    , # ML not implemented
+#           'ml'          => 'ML'                    , 
+            'ml'          => 'OCaml'                 , 
+            'mli'         => 'OCaml'                 , 
+            'mly'         => 'OCaml'                 , 
+            'mll'         => 'OCaml'                 , 
+            'm'           => 'MATLAB/Objective C/MUMPS' ,
+            'mm'          => 'Objective C++'         ,
+            'wdproj'      => 'MSBuild scripts'       ,
+            'csproj'      => 'MSBuild scripts'       ,
+            'mps'         => 'MUMPS'                 ,
+            'mth'         => 'Teamcenter mth'        ,
+            'oscript'     => 'LiveLink OScript'      ,
+            'pad'         => 'Ada'                   , # Oracle Ada preprocessor
+            'page'        => 'Visualforce Page'      ,
+            'pas'         => 'Pascal'                ,
+            'pcc'         => 'C++'                   , # Oracle C++ preprocessor
+            'perl'        => 'Perl'                  ,
+            'pfo'         => 'Fortran 77'            ,
+            'pgc'         => 'C'                     , # Postgres embedded C/C++
+            'php3'        => 'PHP'                   ,
+            'php4'        => 'PHP'                   ,
+            'php5'        => 'PHP'                   ,
+            'php'         => 'PHP'                   ,
+            'pig'         => 'Pig Latin'             ,
+            'plh'         => 'Perl'                  ,
+            'pl'          => 'Perl'                  ,
+            'PL'          => 'Perl'                  ,
+            'plx'         => 'Perl'                  ,
+            'pm'          => 'Perl'                  ,
+            'pom.xml'     => 'Maven'                 ,
+            'pom'         => 'Maven'                 ,
+            'p'           => 'Pascal'                ,
+            'pp'          => 'Pascal'                ,
+            'psql'        => 'SQL'                   ,
+            'py'          => 'Python'                ,
+            'pyx'         => 'Cython'                ,
+            'qml'         => 'QML'                   ,
+            'rb'          => 'Ruby'                  ,
+         #  'resx'        => 'ASP.Net'               ,
+            'rex'         => 'Oracle Reports'        ,
+            'rexx'        => 'Rexx'                  ,
+            'rhtml'       => 'Ruby HTML'             ,
+            'rs'          => 'Rust'                  ,
+            's'           => 'Assembly'              ,
+            'S'           => 'Assembly'              ,
+            'scala'       => 'Scala'                 ,
+            'sbl'         => 'Softbridge Basic'      ,
+            'SBL'         => 'Softbridge Basic'      ,
+            'sc'          => 'Lisp'                  ,
+            'scm'         => 'Lisp'                  ,
+            'sed'         => 'sed'                   ,
+            'ses'         => 'Patran Command Language'   ,
+            'pcl'         => 'Patran Command Language'   ,
+            'ps1'         => 'PowerShell'            ,
+            'sass'        => 'SASS'                  ,
+            'scss'        => 'SASS'                  ,
+            'sh'          => 'Bourne Shell'          ,
+            'smarty'      => 'Smarty'                ,
+            'sql'         => 'SQL'                   ,
+            'SQL'         => 'SQL'                   ,
+            'sproc.sql'   => 'SQL Stored Procedure'  ,
+            'spoc.sql'    => 'SQL Stored Procedure'  ,
+            'spc.sql'     => 'SQL Stored Procedure'  ,
+            'udf.sql'     => 'SQL Stored Procedure'  ,
+            'data.sql'    => 'SQL Data'              ,
+            'v'           => 'Verilog-SystemVerilog' ,
+            'sv'          => 'Verilog-SystemVerilog' ,
+            'svh'         => 'Verilog-SystemVerilog' ,
+            'tcl'         => 'Tcl/Tk'                ,
+            'tcsh'        => 'C Shell'               ,
+            'tk'          => 'Tcl/Tk'                ,
+            'tpl'         => 'Smarty'                ,
+            'trigger'     => 'Apex Trigger'          ,
+            'vala'        => 'Vala'                  ,
+            'vapi'        => 'Vala Header'           ,
+            'vhd'         => 'VHDL'                  ,
+            'VHD'         => 'VHDL'                  ,
+            'vhdl'        => 'VHDL'                  ,
+            'VHDL'        => 'VHDL'                  ,
+            'vba'         => 'Visual Basic'          ,
+            'VBA'         => 'Visual Basic'          ,
+         #  'vbp'         => 'Visual Basic'          , # .vbp - autogenerated
+            'vb'          => 'Visual Basic'          ,
+            'VB'          => 'Visual Basic'          ,
+         #  'vbw'         => 'Visual Basic'          , # .vbw - autogenerated
+            'vbs'         => 'Visual Basic'          ,
+            'VBS'         => 'Visual Basic'          ,
+            'webinfo'     => 'ASP.Net'               ,
+            'xml'         => 'XML'                   ,
+            'XML'         => 'XML'                   ,
+            'mxml'        => 'MXML'                  ,
+            'build'       => 'NAnt scripts'          ,
+            'vim'         => 'vim script'            ,
+            'xaml'        => 'XAML'                  ,
+            'xsd'         => 'XSD'                   ,
+            'XSD'         => 'XSD'                   ,
+            'xslt'        => 'XSLT'                  ,
+            'XSLT'        => 'XSLT'                  ,
+            'xsl'         => 'XSLT'                  ,
+            'XSL'         => 'XSLT'                  ,
+            'y'           => 'yacc'                  ,
+            'yaml'        => 'YAML'                  ,
+            'yml'         => 'YAML'                  ,
+            );
+# 1}}}
+%{$rh_Language_by_Script}    = (             # {{{1
+            'awk'      => 'awk'                   ,
+            'bash'     => 'Bourne Again Shell'    ,
+            'bc'       => 'bc'                    ,# calculator
+            'csh'      => 'C Shell'               ,
+            'dmd'      => 'D'                     ,
+            'idl'      => 'IDL'                   ,
+            'kermit'   => 'Kermit'                ,
+            'ksh'      => 'Korn Shell'            ,
+            'lua'      => 'Lua'                   ,
+            'make'     => 'make'                  ,
+            'octave'   => 'Octave'                ,
+            'perl5'    => 'Perl'                  ,
+            'perl'     => 'Perl'                  ,
+            'ruby'     => 'Ruby'                  ,
+            'sed'      => 'sed'                   ,
+            'sh'       => 'Bourne Shell'          ,
+            'tcl'      => 'Tcl/Tk'                ,
+            'tclsh'    => 'Tcl/Tk'                ,
+            'tcsh'     => 'C Shell'               ,
+            'wish'     => 'Tcl/Tk'                ,
+            );
+# 1}}}
+%{$rh_Language_by_File}      = (             # {{{1
+            'Makefile'       => 'make'               ,
+            'makefile'       => 'make'               ,
+            'gnumakefile'    => 'make'               ,
+            'Gnumakefile'    => 'make'               ,
+            'CMakeLists.txt' => 'CMake'              ,
+            'build.xml'      => 'Ant/XML'            ,
+            'pom.xml'        => 'Maven/XML'          ,
+            );
+# 1}}}
+%{$rhaa_Filters_by_Language} = (             # {{{1
+    'ABAP'               => [   [ 'remove_matches'      , '^\*'    ], ],
+    'ActionScript'       => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+
+    'ASP'                => [   [ 'remove_matches'      , '^\s*\47'], ],  # \47 = '
+    'ASP.Net'            => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Ada'                => [   [ 'remove_matches'      , '^\s*--' ], ],
+    'ADSO/IDSM'          => [   [ 'remove_matches'      , '^\s*\*[\+\!]' ], ],
+    'AMPLE'              => [   [ 'remove_matches'      , '^\s*//' ], ],
+    'Ant/XML'            => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'Ant'                => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'Apex Trigger'       => [
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ],
+                            ],
+    'Arduino Sketch'     => [   # same as C
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ],
+                            ], 
+    'Assembly'           => [  
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'remove_matches'      , '^\s*;'  ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'remove_inline'       , ';.*$'   ],
+                            ],
+    'AutoHotkey'         => [   
+                                [ 'remove_matches'      , '^\s*;'  ],
+                                [ 'remove_inline'       , ';.*$'   ],
+                            ],
+    'awk'                => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'bc'                 => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'C'                  => [   
+                                [ 'remove_matches'      , '^\s*//' ], # C99
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], # C99
+                            ], 
+    'C++'                => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'C/C++ Header'       => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Clojure'            => [   [ 'remove_matches'      , '^\s*;'  ], ],
+    'ClojureScript'      => [   [ 'remove_matches'      , '^\s*;'  ], ],
+    'CMake'              => [   
+                                [ 'remove_matches'      , '^\s*#'  ],
+                                [ 'remove_inline'       , '#.*$'   ], 
+                            ],
+    'Cython'             => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'docstring_to_C'                 ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'C#'                 => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'CCS'                => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'CSS'                => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'COBOL'              => [   [ 'remove_cobol_comments',         ], ],
+    'CoffeeScript'       => [   
+                                [ 'remove_matches'      , '^\s*#'  ],
+                                [ 'remove_inline'       , '#.*$'   ], 
+                            ],
+    'ColdFusion'         => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'ColdFusion CFScript'=> [
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Crystal Reports'    => [   [ 'remove_matches'      , '^\s*//' ], ],
+    'D'                  => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_between_general', '/+', '+/' ],
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'DAL'                => [   [ 'remove_between'      , '[]',    ], ],
+    'Dart'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'NASTRAN DMAP'       => [   
+                                [ 'remove_matches'      , '^\s*\$' ], 
+                                [ 'remove_inline'       , '\$.*$'  ], 
+                            ],
+    'DOS Batch'          => [   [ 'remove_matches'      , '^\s*rem', ], ],
+    'DTD'                => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'Erlang'             => [   
+                                [ 'remove_matches'      , '^\s*%'  ], 
+                                [ 'remove_inline'       , '%.*$'   ],
+                            ],
+    'Expect'             => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Focus'              => [   [ 'remove_matches'      , '^\s*\-\*'  ], ],
+    'Fortran 77'         => [   
+                                [ 'remove_f77_comments' ,          ], 
+                                [ 'remove_inline'       , '\!.*$'  ],
+                            ],
+    'Fortran 90'         => [   
+                                [ 'remove_f77_comments' ,          ],
+                                [ 'remove_f90_comments' ,          ], 
+                                [ 'remove_inline'       , '\!.*$'  ],
+                            ],
+    'Fortran 95'         => [   
+                                [ 'remove_f77_comments' ,          ],
+                                [ 'remove_f90_comments' ,          ], 
+                                [ 'remove_inline'       , '\!.*$'  ],
+                            ],
+    'Go'                 => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'Groovy'             => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'HTML'               => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'Haskell'            => [   [ 'remove_haskell_comments', '>filename<' ], ],
+    'IDL'                => [   [ 'remove_matches'      , '^\s*;'  ], ],
+    'InstallShield'      => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'JSP'                => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ],
+                                [ 'remove_jsp_comments' ,          ], 
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'add_newlines'        ,          ],
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'JavaServer Faces'   => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Java'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Javascript'         => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'JCL'                => [   [ 'remove_jcl_comments' ,          ], ],
+    'LESS'               => [
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Lisp'               => [   [ 'remove_matches'      , '^\s*;'  ], ],
+    'Lisp/OpenCL'        => [ [ 'die' ,          ], ], # never called
+    'LiveLink OScript'   => [   [ 'remove_matches'      , '^\s*//' ], ],
+#   'Lua'                => [   [ 'call_regexp_common'  , 'lua'    ], ],
+    'Lua'                => [   [ 'remove_matches'      , '^\s*\-\-' ], ],
+    'make'               => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'MATLAB'             => [   
+                                [ 'remove_matches'      , '^\s*%'  ], 
+                                [ 'remove_inline'       , '%.*$'   ],
+                            ], 
+    'Maven/XML'          => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'Maven'              => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'Modula3'            => [   [ 'call_regexp_common'  , 'Pascal' ], ],
+        # Modula 3 comments are (* ... *) so applying the Pascal filter
+        # which also treats { ... } as a comment is not really correct.
+    'Objective C'        => [   
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ], 
+    'Objective C++'      => [   
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ], 
+    'OCaml'              => [   
+                                [ 'call_regexp_common'  , 'Pascal' ], 
+                            ],
+    'OpenCL'             => [   
+                                [ 'remove_matches'      , '^\s*//' ], # C99
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], # C99
+                            ],
+    'PHP/Pascal'               => [ [ 'die' ,          ], ], # never called
+    'MATLAB/Objective C/MUMPS' => [ [ 'die' ,          ], ], # never called
+    'MUMPS'              => [   [ 'remove_matches'      , '^\s*;'  ], ], 
+    'Octave'             => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Oracle Forms'       => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Oracle Reports'     => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Pascal'             => [   
+                                [ 'call_regexp_common'  , 'Pascal' ], 
+                                [ 'remove_matches'      , '^\s*//' ],
+                            ],
+    'Patran Command Language'=> [   
+                                [ 'remove_matches'      , '^\s*#'   ], 
+                                [ 'remove_matches'      , '^\s*\$#' ], 
+                                [ 'call_regexp_common'  , 'C'       ],
+                            ],
+    'Perl'               => [   [ 'remove_below'        , '^__(END|DATA)__'],
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_below_above'  , '^=head1', '^=cut'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Pig Latin'          => [   
+                                [ 'remove_matches'      , '^\s*--' ],
+                                [ 'remove_inline'       , '--.*$'  ],
+                                [ 'call_regexp_common'  , 'C'       ],
+                            ],
+    'PowerShell'         => [ 
+                                [ 'powershell_to_C'                ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Python'             => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'docstring_to_C'                 ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'PHP'                => [   
+                                [ 'remove_matches'      , '^\s*#'  ],
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                                [ 'remove_inline'       , '//.*$'  ],
+                            ],
+    'QML'                => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Razor'              => [
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'remove_between_general', '@*', '*@' ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ],
+                            ], 
+    'Rexx'               => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Ruby'               => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_below_above'  , '^=begin', '^=end' ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Ruby HTML'          => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'Rust'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'SASS'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Scala'              => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'SKILL'              => [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*;'  ],
+                            ],
+    'SKILL++'            => [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*;'  ],
+                            ],
+    'SQL'                => [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*--' ],
+                                [ 'remove_inline'       , '--.*$'  ],
+                            ],
+    'SQL Stored Procedure'=> [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*--' ],
+                                [ 'remove_inline'       , '--.*$'  ],
+                            ],
+    'SQL Data'           => [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*--' ],
+                                [ 'remove_inline'       , '--.*$'  ],
+                            ],
+    'sed'                => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Smarty'             => [   
+                                [ 'smarty_to_C'                    ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ], 
+    'Bourne Again Shell' => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Bourne Shell'       => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'm4'                 => [   [ 'remove_matches'      , '^dnl '  ], ], 
+    'C Shell'            => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Kermit'             => [  
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_matches'      , '^\s*;'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Korn Shell'         => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Tcl/Tk'             => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Teamcenter def'     => [   [ 'remove_matches'      , '^\s*#'  ], ], 
+    'Teamcenter met'     => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Teamcenter mth'     => [   [ 'remove_matches'      , '^\s*#'  ], ], 
+    'Softbridge Basic'   => [   [ 'remove_above'        , '^\s*Attribute\s+VB_Name\s+=' ],               
+                                [ 'remove_matches'      , '^\s*Attribute\s+'],
+                                [ 'remove_matches'      , '^\s*\47'], ],  # \47 = '
+    # http://www.altium.com/files/learningguides/TR0114%20VHDL%20Language%20Reference.pdf
+    'Vala'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Vala Header'        => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Verilog-SystemVerilog' => [
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'VHDL'               => [   
+                                [ 'remove_matches'      , '^\s*--' ],
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '--.*$'  ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'vim script'         => [   
+                                [ 'remove_matches'      , '^\s*"'  ], 
+                                [ 'remove_inline'       , '".*$'   ], 
+                            ],
+    'Visual Basic'       => [   [ 'remove_above'        , '^\s*Attribute\s+VB_Name\s+=' ],               
+                                [ 'remove_matches'      , '^\s*Attribute\s+'],
+                                [ 'remove_matches'      , '^\s*\47'], ],  # \47 = '
+    'Visualforce Component' => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'Visualforce Page'   => [
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                            ],
+    'yacc'               => [   
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'YAML'               => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ], 
+                            ],
+    'lex'                => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'XAML'               => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'MXML'               => [   
+                                [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], 
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'add_newlines'        ,          ], 
+                                [ 'call_regexp_common'  , 'C'      ], 
+                            ],
+    'XML'                => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'XSD'                => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'XSLT'               => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'NAnt scripts'       => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'MSBuild scripts'    => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    );
+# 1}}}
+%{$rh_EOL_continuation_re} = (               # {{{1
+    'ActionScript'       =>     '\\\\$'         ,
+    'Assembly'           =>     '\\\\$'         ,
+    'ASP'                =>     '\\\\$'         ,
+    'ASP.Net'            =>     '\\\\$'         ,
+    'Ada'                =>     '\\\\$'         ,
+    'awk'                =>     '\\\\$'         ,
+    'bc'                 =>     '\\\\$'         ,
+    'C'                  =>     '\\\\$'         ,
+    'C++'                =>     '\\\\$'         ,
+    'C/C++ Header'       =>     '\\\\$'         ,
+    'CMake'              =>     '\\\\$'         ,
+    'Cython'             =>     '\\\\$'         ,
+    'C#'                 =>     '\\\\$'         ,
+    'D'                  =>     '\\\\$'         ,
+    'Dart'               =>     '\\\\$'         ,
+    'Expect'             =>     '\\\\$'         ,
+    'Go'                 =>     '\\\\$'         ,
+    'Java'               =>     '\\\\$'         ,
+    'Javascript'         =>     '\\\\$'         ,
+    'LESS'               =>     '\\\\$'         ,
+    'Lua'                =>     '\\\\$'         ,
+    'make'               =>     '\\\\$'         ,
+    'MATLAB'             =>     '\.\.\.\s*$'    ,
+    'MXML'               =>     '\\\\$'         ,
+    'Objective C'        =>     '\\\\$'         ,
+    'Objective C++'      =>     '\\\\$'         ,
+    'OCaml'              =>     '\\\\$'         ,
+    'Octave'             =>     '\.\.\.\s*$'    ,
+    'Patran Command Language'=> '\\\\$'         ,
+    'PowerShell'         =>     '\\\\$'         ,
+    'Python'             =>     '\\\\$'         ,
+    'Ruby'               =>     '\\\\$'         ,
+    'sed'                =>     '\\\\$'         ,
+    'Bourne Again Shell' =>     '\\\\$'         ,
+    'Bourne Shell'       =>     '\\\\$'         ,
+    'C Shell'            =>     '\\\\$'         ,
+    'Kermit'             =>     '\\\\$'         ,
+    'Korn Shell'         =>     '\\\\$'         ,
+    'Tcl/Tk'             =>     '\\\\$'         ,
+    'lex'                =>     '\\\\$'         ,
+    'Vala'               =>     '\\\\$'         ,
+    'Vala Header'        =>     '\\\\$'         ,
+    );
+# 1}}}
+%{$rh_Not_Code_Extension}    = (             # {{{1
+   '1'       => 1,  # Man pages (documentation):
+   '2'       => 1,
+   '3'       => 1,
+   '4'       => 1,
+   '5'       => 1,
+   '6'       => 1,
+   '7'       => 1,
+   '8'       => 1,
+   '9'       => 1,
+   'a'       => 1,  # Static object code.
+   'ad'      => 1,  # X application default resource file.
+   'afm'     => 1,  # font metrics
+   'arc'     => 1,  # arc(1) archive
+   'arj'     => 1,  # arj(1) archive
+   'au'      => 1,  # Audio sound filearj(1) archive
+   'bak'     => 1,  # Backup files - we only want to count the "real" files.
+   'bdf'     => 1,
+   'bmp'     => 1,
+   'bz2'     => 1,  # bzip2(1) compressed file
+   'csv'     => 1,  # comma separated values
+   'desktop' => 1,
+   'dic'     => 1,
+   'doc'     => 1,
+   'elc'     => 1,
+   'eps'     => 1,
+   'fig'     => 1,
+   'gif'     => 1,
+   'gz'      => 1,
+   'hdf'     => 1,  # hierarchical data format
+   'in'      => 1,  # Debatable.
+   'jpg'     => 1,
+   'kdelnk'  => 1,
+   'man'     => 1,
+   'mf'      => 1,
+   'mp3'     => 1,
+   'n'       => 1,
+   'o'       => 1,  # Object code is generated from source code.
+   'pbm'     => 1,
+   'pdf'     => 1,
+   'pfb'     => 1,
+   'png'     => 1,
+   'po'      => 1,
+   'ps'      => 1,  # Postscript is _USUALLY_ generated automatically.
+   'sgm'     => 1,
+   'sgml'    => 1,
+   'so'      => 1,  # Dynamically-loaded object code.
+   'Tag'     => 1,
+   'tex'     => 1,
+   'text'    => 1,
+   'tfm'     => 1,
+   'tgz'     => 1,  # gzipped tarball
+   'tiff'    => 1,
+   'txt'     => 1, 
+   'vf'      => 1,
+   'wav'     => 1,
+   'xbm'     => 1,
+   'xpm'     => 1,
+   'Y'       => 1,  # file compressed with "Yabba"
+   'Z'       => 1,  # file compressed with "compress"
+   'zip'     => 1,  # zip archive
+); # 1}}}
+%{$rh_Not_Code_Filename}     = (             # {{{1
+   'AUTHORS'     => 1,
+   'BUGS'        => 1,
+   'BUGS'        => 1,
+   'Changelog'   => 1,
+   'ChangeLog'   => 1,
+   'ChangeLog'   => 1,
+   'Changes'     => 1,
+   'CHANGES'     => 1,
+   'COPYING'     => 1,
+   'COPYING'     => 1,
+   '.cvsignore'  => 1,
+   'Entries'     => 1,
+   'FAQ'         => 1,
+   'iconfig.h'   => 1, # Skip "iconfig.h" files; they're used in Imakefiles.
+   'INSTALL'     => 1,
+   'MAINTAINERS' => 1,
+   'MD5SUMS'     => 1,
+   'NEWS'        => 1,
+   'readme'      => 1,
+   'Readme'      => 1,
+   'README'      => 1,
+   'README.tk'   => 1, # used in kdemultimedia, it's confusing.
+   'Repository'  => 1,
+   'Root'        => 1, # CVS
+   'TODO'        => 1,
+);
+# 1}}}
+%{$rh_Scale_Factor}          = (             # {{{1
+    '1032/af'                      =>   5.00,
+    '1st generation default'       =>   0.25,
+    '2nd generation default'       =>   0.75,
+    '3rd generation default'       =>   1.00,
+    '4th generation default'       =>   4.00,
+    '5th generation default'       =>  16.00,
+    'aas macro'                    =>   0.88,
+    'abap/4'                       =>   5.00,
+    'ABAP'                         =>   5.00,
+    'accel'                        =>   4.21,
+    'access'                       =>   2.11,
+    'ActionScript'                 =>   1.36,
+    'actor'                        =>   3.81,
+    'acumen'                       =>   2.86,
+    'Ada'                          =>   0.52,
+    'Ada 83'                       =>   1.13,
+    'Ada 95'                       =>   1.63,
+    'adr/dl'                       =>   2.00,
+    'adr/ideal/pdl'                =>   4.00,
+    'ads/batch'                    =>   4.00,
+    'ads/online'                   =>   4.00,
+    'ADSO/IDSM'                    =>   3.00,
+    'advantage'                    =>   2.11,
+    'ai shell default'             =>   1.63,
+    'ai shells'                    =>   1.63,
+    'algol 68'                     =>   0.75,
+    'algol w'                      =>   0.75,
+    'ambush'                       =>   2.50,
+    'aml'                          =>   1.63,
+    'AMPLE'                        =>   2.00,
+    'Ant/XML'                      =>   1.90,
+    'Ant'                          =>   1.90,
+    'amppl ii'                     =>   1.25,
+    'ansi basic'                   =>   1.25,
+    'ansi cobol 74'                =>   0.75,
+    'ansi cobol 85'                =>   0.88,
+    'SQL'                          =>   6.15,
+    'SQL Stored Procedure'         =>   6.15,
+    'SQL Data'                     =>   1.00,
+    'answer/db'                    =>   6.15,
+    'apl 360/370'                  =>   2.50,
+    'apl default'                  =>   2.50,
+    'apl*plus'                     =>   2.50,
+    'applesoft basic'              =>   0.63,
+    'application builder'          =>   4.00,
+    'application manager'          =>   2.22,
+    'aps'                          =>   0.96,
+    'aps'                          =>   4.71,
+    'apt'                          =>   1.13,
+    'aptools'                      =>   4.00,
+    'arc'                          =>   1.63,
+    'ariel'                        =>   0.75,
+    'arity'                        =>   1.63,
+    'arity prolog'                 =>   1.25,
+    'art'                          =>   1.63,
+    'art enterprise'               =>   1.74,
+    'artemis'                      =>   2.00,
+    'artim'                        =>   1.74,
+    'as/set'                       =>   4.21,
+    'asi/inquiry'                  =>   6.15,
+    'ask windows'                  =>   1.74,
+'asa'                         =>   1.29,
+'ASP'                         =>   1.29,
+'ASP.Net'                     =>   1.29,
+'aspx'                        =>   1.29,
+#'resx'                        =>   1.29,
+'asax'                        =>   1.29,
+'ascx'                        =>   1.29,
+'asmx'                        =>   1.29,
+'config'                      =>   1.29,
+'webinfo'                     =>   1.29,
+'CCS'                         =>   5.33,
+
+    'Apex Trigger'                 =>   1.4 ,
+#   'assembler (basic)'            =>   0.25,
+    'Arduino Sketch'               =>   1.00,
+    'Assembly'                     =>   0.25,
+
+    'Assembly (macro)'             =>   0.51,
+    'associative default'          =>   1.25,
+    'autocoder'                    =>   0.25,
+    'AutoHotkey'                   =>   1.29,
+    'awk'                          =>   3.81,
+    'aztec c'                      =>   0.63,
+    'balm'                         =>   0.75,
+    'base sas'                     =>   1.51,
+    'basic'                        =>   0.75,
+    'basic a'                      =>   0.63,
+#   'basic assembly'               =>   0.25,
+    'bc'                           =>   1.50,
+    'berkeley pascal'              =>   0.88,
+    'better basic'                 =>   0.88,
+    'bliss'                        =>   0.75,
+    'bmsgen'                       =>   2.22,
+    'boeingcalc'                   =>  13.33,
+    'bteq'                         =>   6.15,
+
+    'C'                            =>   0.77,
+
+    'c set 2'                      =>   0.88,
+
+    'C#'                           =>   1.36,
+
+    'C++'                          =>   1.51,
+
+    'c86plus'                      =>   0.63,
+    'cadbfast'                     =>   2.00,
+    'caearl'                       =>   2.86,
+    'cast'                         =>   1.63,
+    'cbasic'                       =>   0.88,
+    'cdadl'                        =>   4.00,
+    'cellsim'                      =>   1.74,
+    'ColdFusion'                   =>   4.00,
+    'ColdFusion CFScript'          =>   4.00,
+    'chili'                        =>   0.75,
+    'chill'                        =>   0.75,
+    'cics'                         =>   1.74,
+    'clarion'                      =>   1.38,
+    'clascal'                      =>   1.00,
+    'cli'                          =>   2.50,
+    'clipper'                      =>   2.05,
+    'clipper db'                   =>   2.00,
+    'clos'                         =>   3.81,
+    'Clojure'                      =>   1.25,
+    'ClojureScript'                =>   1.25,
+    'clout'                        =>   2.00,
+    'CMake'                        =>   1.00,
+    'cms2'                         =>   0.75,
+    'cmsgen'                       =>   4.21,
+    'COBOL'                        =>   1.04,
+    'COBOL ii'                     =>   0.75,
+    'COBOL/400'                    =>   0.88,
+    'cobra'                        =>   4.00,
+    'codecenter'                   =>   2.22,
+    'cofac'                        =>   2.22,
+    'CoffeeScript'                 =>   2.00,
+    'cogen'                        =>   2.22,
+    'cognos'                       =>   2.22,
+    'cogo'                         =>   1.13,
+    'comal'                        =>   1.00,
+    'comit ii'                     =>   1.25,
+    'common lisp'                  =>   1.25,
+    'concurrent pascal'            =>   1.00,
+    'conniver'                     =>   1.25,
+    'cool:gen/ief'                 =>   2.58,
+    'coral 66'                     =>   0.75,
+    'corvet'                       =>   4.21,
+    'corvision'                    =>   5.33,
+    'cpl'                          =>   0.50,
+    'Crystal Reports'              =>   4.00,
+    'csl'                          =>   1.63,
+    'csp'                          =>   1.51,
+    'cssl'                         =>   1.74,
+    
+'CSS' => 1.0,
+    
+    'culprit'                      =>   1.57,
+    'cxpert'                       =>   1.63,
+    'cygnet'                       =>   4.21,
+    'D'                            =>   1.70,
+    'DAL'                          =>   1.50,
+    'Dart'                         =>   2.00,
+    'data base default'            =>   2.00,
+    'dataflex'                     =>   2.00,
+    'datatrieve'                   =>   4.00,
+    'dbase iii'                    =>   2.00,
+    'dbase iv'                     =>   1.54,
+    'dcl'                          =>   0.38,
+    'decision support default'     =>   2.22,
+    'decrally'                     =>   2.00,
+    'delphi'                       =>   2.76,
+    'dl/1'                         =>   2.00,
+    'NASTRAN DMAP'                 =>   2.35,
+    'dna4'                         =>   4.21,
+    'DOS Batch'                    =>   0.63,
+    'dsp assembly'                 =>   0.50,
+    'dtabl'                        =>   1.74,
+    'dtipt'                        =>   1.74,
+    'dyana'                        =>   1.13,
+    'dynamoiii'                    =>   1.74,
+    'easel'                        =>   2.76,
+    'easy'                         =>   1.63,
+    'easytrieve+'                  =>   2.35,
+    'eclipse'                      =>   1.63,
+    'eda/sql'                      =>   6.67,
+    'edscheme 3.4'                 =>   1.51,
+    'eiffel'                       =>   3.81,
+    'enform'                       =>   1.74,
+    'englishbased default'         =>   1.51,
+    'ensemble'                     =>   2.76,
+    'epos'                         =>   4.00,
+    'Erlang'                       =>   2.11,
+    'esf'                          =>   2.00,
+    'espadvisor'                   =>   1.63,
+    'espl/i'                       =>   1.13,
+    'euclid'                       =>   0.75,
+    'excel'                        =>   1.74,
+    'excel 12'                     =>  13.33,
+    'excel 34'                     =>  13.33,
+    'excel 5'                      =>  13.33,
+    'express'                      =>   2.22,
+    'exsys'                        =>   1.63,
+    'extended common lisp'         =>   1.43,
+    'eznomad'                      =>   2.22,
+    'facets'                       =>   4.00,
+    'factorylink iv'               =>   2.76,
+    'fame'                         =>   2.22,
+    'filemaker pro'                =>   2.22,
+    'flavors'                      =>   2.76,
+    'flex'                         =>   1.74,
+    'flexgen'                      =>   2.76,
+    'Focus'                        =>   1.90,
+    'foil'                         =>   1.51,
+    'forte'                        =>   4.44,
+    'forth'                        =>   1.25,
+    'Fortran 66'                   =>   0.63,
+    'Fortran 77'                   =>   0.75,
+    'Fortran 90'                   =>   1.00,
+    'Fortran 95'                   =>   1.13,
+    'Fortran II'                   =>   0.63,
+    'foundation'                   =>   2.76,
+    'foxpro'                       =>   2.29,
+    'foxpro 1'                     =>   2.00,
+    'foxpro 2.5'                   =>   2.35,
+    'framework'                    =>  13.33,
+    'g2'                           =>   1.63,
+    'gamma'                        =>   5.00,
+    'genascript'                   =>   2.96,
+    'gener/ol'                     =>   6.15,
+    'genexus'                      =>   5.33,
+    'genifer'                      =>   4.21,
+    'geode 2.0'                    =>   5.00,
+    'gfa basic'                    =>   2.35,
+    'gml'                          =>   1.74,
+    'golden common lisp'           =>   1.25,
+    'gpss'                         =>   1.74,
+    'guest'                        =>   2.86,
+    'guru'                         =>   1.63,
+    'Go'                           =>   2.50,
+    'Groovy'                       =>   4.10,
+    'gw basic'                     =>   0.82,
+    'Haskell'                      =>   2.11,
+    'high c'                       =>   0.63,
+    'hlevel'                       =>   1.38,
+    'hp basic'                     =>   0.63,
+
+'HTML'          => 1.90 ,
+'XML'           => 1.90 ,
+'MXML'          => 1.90 ,
+'XSLT'          => 1.90 ,
+'DTD'           => 1.90 ,
+'XSD'           => 1.90 ,
+'NAnt scripts'    => 1.90 ,
+'MSBuild scripts' => 1.90 , 
+
+    'HTML 2'                       =>   5.00,
+    'HTML 3'                       =>   5.33,
+    'huron'                        =>   5.00,
+    'ibm adf i'                    =>   4.00,
+    'ibm adf ii'                   =>   4.44,
+    'ibm advanced basic'           =>   0.82,
+    'ibm cics/vs'                  =>   2.00,
+    'ibm compiled basic'           =>   0.88,
+    'ibm vs cobol'                 =>   0.75,
+    'ibm vs cobol ii'              =>   0.88,
+    'ices'                         =>   1.13,
+    'icon'                         =>   1.00,
+    'ideal'                        =>   1.54,
+    'idms'                         =>   2.00,
+    'ief'                          =>   5.71,
+    'ief/cool:gen'                 =>   2.58,
+    'iew'                          =>   5.71,
+    'ifps/plus'                    =>   2.50,
+    'imprs'                        =>   2.00,
+    'informix'                     =>   2.58,
+    'ingres'                       =>   2.00,
+    'inquire'                      =>   6.15,
+    'insight2'                     =>   1.63,
+    'install/1'                    =>   5.00,
+    'InstallShield'                =>   1.90,
+    'intellect'                    =>   1.51,
+    'interlisp'                    =>   1.38,
+    'interpreted basic'            =>   0.75,
+    'interpreted c'                =>   0.63,
+    'iqlisp'                       =>   1.38,
+    'iqrp'                         =>   6.15,
+    'j2ee'                         =>   1.60,
+    'janus'                        =>   1.13,
+    'Java'                         =>   1.36,
+    'Javascript'                   =>   1.48,
+    'JavaServer Faces'             =>   1.5 ,
+    'JSP'                          =>   1.48,
+    'JCL'                          =>   1.67,
+    'joss'                         =>   0.75,
+    'jovial'                       =>   0.75,
+    'jsp'                          =>   1.36,
+    'kappa'                        =>   2.00,
+    'kbms'                         =>   1.63,
+    'kcl'                          =>   1.25,
+    'kee'                          =>   1.63,
+    'keyplus'                      =>   2.00,
+    'kl'                           =>   1.25,
+    'klo'                          =>   1.25,
+    'knowol'                       =>   1.63,
+    'krl'                          =>   1.38,
+    'Kermit'                       =>   2.00,
+    'Korn Shell'                   =>   3.81,
+    'ladder logic'                 =>   2.22,
+    'lambit/l'                     =>   1.25,
+    'lattice c'                    =>   0.63,
+    'LESS'                         =>   1.50,
+    'liana'                        =>   0.63,
+    'lilith'                       =>   1.13,
+    'linc ii'                      =>   5.71,
+    'Lisp'                         =>   1.25,
+    'LiveLink OScript'             =>   3.5 ,
+    'loglisp'                      =>   1.38,
+    'loops'                        =>   3.81,
+    'lotus 123 dos'                =>  13.33,
+    'lotus macros'                 =>   0.75,
+    'lotus notes'                  =>   3.64,
+    'lucid 3d'                     =>  13.33,
+    'lyric'                        =>   1.51,
+    'm4'                           =>   1.00,
+    'm'                            =>   5.00,
+    'macforth'                     =>   1.25,
+    'mach1'                        =>   2.00,
+    'machine language'             =>   0.13,
+    'maestro'                      =>   5.00,
+    'magec'                        =>   5.00,
+    'magik'                        =>   3.81,
+    'Lake'                         =>   3.81,
+    'make'                         =>   2.50,
+    'mantis'                       =>   2.96,
+    'mapper'                       =>   0.99,
+    'mark iv'                      =>   2.00,
+    'mark v'                       =>   2.22,
+    'mathcad'                      =>  16.00,
+    'Maven'                        =>   1.90,
+    'mdl'                          =>   2.22,
+    'mentor'                       =>   1.51,
+    'mesa'                         =>   0.75,
+    'microfocus cobol'             =>   1.00,
+    'microforth'                   =>   1.25,
+    'microsoft c'                  =>   0.63,
+    'microstep'                    =>   4.00,
+    'miranda'                      =>   2.00,
+    'model 204'                    =>   2.11,
+    'modula 2'                     =>   1.00,
+    'mosaic'                       =>  13.33,
+    # 'ms c ++ v. 7'                 =>   1.51,
+    'ms compiled basic'            =>   0.88,
+    'msl'                          =>   1.25,
+    'mulisp'                       =>   1.25,
+    'MUMPS'                        =>   4.21,
+    'Nastran'                      =>   1.13,
+    'natural'                      =>   1.54,
+    'natural 1'                    =>   1.51,
+    'natural 2'                    =>   1.74,
+    'natural construct'            =>   3.20,
+    'natural language'             =>   0.03,
+    'netron/cap'                   =>   4.21,
+    'nexpert'                      =>   1.63,
+    'nial'                         =>   1.63,
+    'nomad2'                       =>   2.00,
+    'nonprocedural default'        =>   2.22,
+    'notes vip'                    =>   2.22,
+    'nroff'                        =>   1.51,
+    'object assembler'             =>   1.25,
+    'object lisp'                  =>   2.76,
+    'object logo'                  =>   2.76,
+    'object pascal'                =>   2.76,
+    'object star'                  =>   5.00,
+    'Objective C'                  =>   2.96,
+    'Objective C++'                =>   2.96,
+    'objectoriented default'       =>   2.76,
+    'objectview'                   =>   3.20,
+    'OCaml'                        =>   3.00,
+    'ogl'                          =>   1.00,
+    'omnis 7'                      =>   2.00,
+    'oodl'                         =>   2.76,
+    'ops'                          =>   1.74,
+    'ops5'                         =>   1.38,
+    'oracle'                       =>   2.76,
+    'Oracle Reports'               =>   2.76,
+    'Oracle Forms'                 =>   2.67,
+    'Oracle Developer/2000'        =>   3.48,
+    'oscar'                        =>   0.75,
+    'pacbase'                      =>   1.67,
+    'pace'                         =>   2.00,
+    'paradox/pal'                  =>   2.22,
+    'Pascal'                       =>   0.88,
+    'Patran Command Language'      =>   2.50,
+    'pc focus'                     =>   2.22,
+    'pdl millenium'                =>   3.81,
+    'pdp11 ade'                    =>   1.51,
+    'peoplesoft'                   =>   2.50,
+    'Perl'                         =>   4.00,
+    'persistance object builder'   =>   3.81,
+    'Pig Latin'                    =>   1.00,
+    'pilot'                        =>   1.51,
+    'pl/1'                         =>   1.38,
+    'pl/m'                         =>   1.13,
+    'pl/s'                         =>   0.88,
+    'pl/sql'                       =>   2.58,
+    'planit'                       =>   1.51,
+    'planner'                      =>   1.25,
+    'planperfect 1'                =>  11.43,
+    'plato'                        =>   1.51,
+    'polyforth'                    =>   1.25,
+    'pop'                          =>   1.38,
+    'poplog'                       =>   1.38,
+    'power basic'                  =>   1.63,
+    'powerbuilder'                 =>   3.33,
+    'powerhouse'                   =>   5.71,
+    'PowerShell'                   =>   3.00,
+    'ppl (plus)'                   =>   2.00,
+    'problemoriented default'      =>   1.13,
+    'proc'                         =>   2.96,
+    'procedural default'           =>   0.75,
+    'professional pascal'          =>   0.88,
+    'program generator default'    =>   5.00,
+    'progress v4'                  =>   2.22,
+    'proiv'                        =>   1.38,
+    'prolog'                       =>   1.25,
+    'prose'                        =>   0.75,
+    'proteus'                      =>   0.75,
+    'qbasic'                       =>   1.38,
+    'qbe'                          =>   6.15,
+    'qmf'                          =>   5.33,
+    'QML'                          =>   1.25,
+    'qnial'                        =>   1.63,
+    'quattro'                      =>  13.33,
+    'quattro pro'                  =>  13.33,
+    'query default'                =>   6.15,
+    'quick basic 1'                =>   1.25,
+    'quick basic 2'                =>   1.31,
+    'quick basic 3'                =>   1.38,
+    'quick c'                      =>   0.63,
+    'quickbuild'                   =>   2.86,
+    'quiz'                         =>   5.33,
+    'rally'                        =>   2.00,
+    'ramis ii'                     =>   2.00,
+    'rapidgen'                     =>   2.86,
+    'ratfor'                       =>   0.88,
+    'rdb'                          =>   2.00,
+    'realia'                       =>   1.74,
+    'realizer 1.0'                 =>   2.00,
+    'realizer 2.0'                 =>   2.22,
+    'relate/3000'                  =>   2.00,
+    'reuse default'                =>  16.00,
+    'Razor'                        =>   2.00,
+    'Rexx'                         =>   1.19,
+    'Rexx (mvs)'                   =>   1.00,
+    'Rexx (os/2)'                  =>   1.74,
+    'rm basic'                     =>   0.88,
+    'rm cobol'                     =>   0.75,
+    'rm fortran'                   =>   0.75,
+    'rpg i'                        =>   1.00,
+    'rpg ii'                       =>   1.63,
+    'rpg iii'                      =>   1.63,
+    'rtexpert 1.4'                 =>   1.38,
+    'Rust'                         =>   1.00,
+    'sabretalk'                    =>   0.90,
+    'sail'                         =>   0.75,
+    'sapiens'                      =>   5.00,
+    'sas'                          =>   1.95,
+    'savvy'                        =>   6.15,
+    'sbasic'                       =>   0.88,
+    'Scala'                        =>   4.10,
+    'sceptre'                      =>   1.13,
+    'scheme'                       =>   1.51,
+    'screen painter default'       =>  13.33,
+    'sequal'                       =>   6.67,
+    'Bourne Shell'                 =>   3.81,
+    'Bourne Again Shell'           =>   3.81,
+    'ksh'                          =>   3.81,
+    'C Shell'                      =>   3.81,
+    'siebel tools '                =>   6.15,
+    'SASS'                         =>   1.5 ,
+    'simplan'                      =>   2.22,
+    'simscript'                    =>   1.74,
+    'simula'                       =>   1.74,
+    'simula 67'                    =>   1.74,
+    'simulation default'           =>   1.74,
+    'SKILL'                        =>   2.00,
+    'SKILL++'                      =>   2.00,
+    'slogan'                       =>   0.98,
+    'smalltalk'                    =>   2.50,
+    'smalltalk 286'                =>   3.81,
+    'smalltalk 80'                 =>   3.81,
+    'smalltalk/v'                  =>   3.81,
+    'Smarty'                       =>   3.50,
+    'snap'                         =>   1.00,
+    'snobol24'                     =>   0.63,
+    'softscreen'                   =>   5.71,
+    'Softbridge Basic'             =>   2.76,
+    'solo'                         =>   1.38,
+    'speakeasy'                    =>   2.22,
+    'spinnaker ppl'                =>   2.22,
+    'splus'                        =>   2.50,
+    'spreadsheet default'          =>  13.33,
+    'sps'                          =>   0.25,
+    'spss'                         =>   2.50,
+    'SQL'                          =>   2.29,
+    'sqlwindows'                   =>   6.67,
+    'statistical default'          =>   2.50,
+    'strategem'                    =>   2.22,
+    'stress'                       =>   1.13,
+    'strongly typed default'       =>   0.88,
+    'style'                        =>   1.74,
+    'superbase 1.3'                =>   2.22,
+    'surpass'                      =>  13.33,
+    'sybase'                       =>   2.00,
+    'symantec c++'                 =>   2.76,
+    'symbolang'                    =>   1.25,
+    'synchroworks'                 =>   4.44,
+    'synon/2e'                     =>   4.21,
+    'systemw'                      =>   2.22,
+    'tandem access language'       =>   0.88,
+    'Tcl/Tk'                       =>   4.00,
+    'Teamcenter def'               =>   1.00,
+    'Teamcenter met'               =>   1.00,
+    'Teamcenter mth'               =>   1.00,
+    'telon'                        =>   5.00,
+    'tessaract'                    =>   2.00,
+    'the twin'                     =>  13.33,
+    'themis'                       =>   6.15,
+    'tiief'                        =>   5.71,
+    'topspeed c++'                 =>   2.76,
+    'transform'                    =>   5.33,
+    'translisp plus'               =>   1.43,
+    'treet'                        =>   1.25,
+    'treetran'                     =>   1.25,
+    'trs80 basic'                  =>   0.63,
+    'true basic'                   =>   1.25,
+    'turbo c'                      =>   0.63,
+    # 'turbo c++'                    =>   1.51,
+    'turbo expert'                 =>   1.63,
+    'turbo pascal >5'              =>   1.63,
+    'turbo pascal 14'              =>   1.00,
+    'turbo pascal 45'              =>   1.13,
+    'turbo prolog'                 =>   1.00,
+    'turing'                       =>   1.00,
+    'tutor'                        =>   1.51,
+    'twaice'                       =>   1.63,
+    'ucsd pascal'                  =>   0.88,
+    'ufo/ims'                      =>   2.22,
+    'uhelp'                        =>   2.50,
+    'uniface'                      =>   5.00,
+    # 'unix shell scripts'           =>   3.81,
+    'Vala'                         =>   1.50,
+    'Vala Header'                  =>   1.40,
+    'vax acms'                     =>   1.38,
+    'vax ade'                      =>   2.00,
+    'vbscript'                     =>   2.35,
+    'vectran'                      =>   0.75,
+    'Verilog-SystemVerilog'        =>   1.51,
+    'VHDL'                         =>   4.21,
+    'vim script'                   =>   3.00,
+    'visible c'                    =>   1.63,
+    'visible cobol'                =>   2.00,
+    'visicalc 1'                   =>   8.89,
+    'visual 4.0'                   =>   2.76,
+    'visual basic'                 =>   1.90,
+    'visual basic 1'               =>   1.74,
+    'visual basic 2'               =>   1.86,
+    'visual basic 3'               =>   2.00,
+    'visual basic 4'               =>   2.22,
+    'visual basic 5'               =>   2.76,
+    'Visual Basic'                 =>   2.76,
+    'visual basic dos'             =>   2.00,
+    'visual c++'                   =>   2.35,
+    'visual cobol'                 =>   4.00,
+    'visual objects'               =>   5.00,
+    'visualage'                    =>   3.81,
+    'Visualforce Component'        =>   1.9 ,
+    'Visualforce Page'             =>   1.9 ,
+    'visualgen'                    =>   4.44,
+    'vpf'                          =>   0.84,
+    'vsrexx'                       =>   2.50,
+    'vulcan'                       =>   1.25,
+    'vz programmer'                =>   2.22,
+    'warp x'                       =>   2.00,
+    'watcom c'                     =>   0.63,
+    'watcom c/386'                 =>   0.63,
+    'waterloo c'                   =>   0.63,
+    'waterloo pascal'              =>   0.88,
+    'watfiv'                       =>   0.94,
+    'watfor'                       =>   0.88,
+    'web scripts'                  =>   5.33,
+    'whip'                         =>   0.88,
+    'wizard'                       =>   2.86,
+    'xlisp'                        =>   1.25,
+    'XAML'                         =>   1.90,
+    'yacc'                         =>   1.51,
+    'yacc++'                       =>   1.51,
+    'YAML'                         =>   0.90,
+    'zbasic'                       =>   0.88,
+    'zim'                          =>   4.21,
+    'zlisp'                        =>   1.25,
+
+'Expect'  => 2.00,
+'C/C++ Header'  => 1.00, 
+'inc'     => 1.00,
+'lex'     => 1.00,
+'MATLAB'  => 4.00,
+'Maven/XML' => 2.5,
+'IDL'     => 3.80,
+'Octave'  => 4.00,
+'ML'      => 3.00,
+'Modula3' => 2.00,
+'PHP'     => 3.50,
+'Python'  => 4.20,
+'Cython'  => 3.80,
+'Ruby'    => 4.20,
+'Ruby HTML' => 4.00,
+'sed'     => 4.00,
+'Lua'     => 4.00,
+'OpenCL'  => 1.50,
+);
+# 1}}}
+%{$rh_Known_Binary_Archives} = (             # {{{1
+            '.tar'     => 1 ,
+            '.tar.Z'   => 1 ,
+            '.tar.gz'  => 1 ,
+            '.tar.bz2' => 1 ,
+            '.zip'     => 1 ,
+            '.Zip'     => 1 ,
+            '.ZIP'     => 1 ,
+            '.ear'     => 1 ,  # Java
+            '.war'     => 1 ,  # contained within .ear
+            '.xz'      => 1 ,
+            );
+# 1}}}
+} # end sub set_constants()
+sub Install_Regexp_Common {                  # {{{1
+    # Installs portions of Damian Conway's & Abigail's Regexp::Common
+    # module, v2.120, into a temporary directory for the duration of
+    # this run.
+
+    my %Regexp_Common_Contents = ();
+$Regexp_Common_Contents{'Common'} = <<'EOCommon'; # {{{2
+package Regexp::Common;
+
+use 5.00473;
+use strict;
+
+local $^W = 1;
+
+use vars qw /$VERSION %RE %sub_interface $AUTOLOAD/;
+
+($VERSION) = q $Revision: 2.120 $ =~ /([\d.]+)/;
+
+
+sub _croak {
+    require Carp;
+    goto &Carp::croak;
+}
+
+sub _carp {
+    require Carp;
+    goto &Carp::carp;
+}
+
+sub new {
+    my ($class, @data) = @_;
+    my %self;
+    tie %self, $class, @data;
+    return \%self;
+}
+
+sub TIEHASH {
+    my ($class, @data) = @_;
+    bless \@data, $class;
+}
+
+sub FETCH {
+    my ($self, $extra) = @_;
+    return bless ref($self)->new(@$self, $extra), ref($self);
+}
+
+# Modification for cloc:  only need a few modules from Regexp::Common.
+my %imports = map {$_ => "Regexp::Common::$_"}
+              qw /balanced comment delimited /;
+#my %imports = map {$_ => "Regexp::Common::$_"}
+#              qw /balanced CC     comment   delimited lingua list
+#                  net      number profanity SEN       URI    whitespace
+#                  zip/;
+
+sub import {
+    shift;  # Shift off the class.
+    tie %RE, __PACKAGE__;
+    {
+        no strict 'refs';
+        *{caller() . "::RE"} = \%RE;
+    }
+
+    my $saw_import;
+    my $no_defaults;
+    my %exclude;
+    foreach my $entry (grep {!/^RE_/} @_) {
+        if ($entry eq 'pattern') {
+            no strict 'refs';
+            *{caller() . "::pattern"} = \&pattern;
+            next;
+        }
+        # This used to prevent $; from being set. We still recognize it,
+        # but we won't do anything.
+        if ($entry eq 'clean') {
+            next;
+        }
+        if ($entry eq 'no_defaults') {
+            $no_defaults ++;
+            next;
+        }
+        if (my $module = $imports {$entry}) {
+            $saw_import ++;
+            eval "require $module;";
+            die $@ if $@;
+            next;
+        }
+        if ($entry =~ /^!(.*)/ && $imports {$1}) {
+            $exclude {$1} ++;
+            next;
+        }
+        # As a last resort, try to load the argument.
+        my $module = $entry =~ /^Regexp::Common/
+                            ? $entry
+                            : "Regexp::Common::" . $entry;
+        eval "require $module;";
+        die $@ if $@;
+    }
+
+    unless ($saw_import || $no_defaults) {
+        foreach my $module (values %imports) {
+            next if $exclude {$module};
+            eval "require $module;";
+            die $@ if $@;
+        }
+    }
+
+    my %exported;
+    foreach my $entry (grep {/^RE_/} @_) {
+        if ($entry =~ /^RE_(\w+_)?ALL$/) {
+            my $m  = defined $1 ? $1 : "";
+            my $re = qr /^RE_${m}.*$/;
+            while (my ($sub, $interface) = each %sub_interface) {
+                next if $exported {$sub};
+                next unless $sub =~ /$re/;
+                {
+                    no strict 'refs';
+                    *{caller() . "::$sub"} = $interface;
+                }
+                $exported {$sub} ++;
+            }
+        }
+        else {
+            next if $exported {$entry};
+            _croak "Can't export unknown subroutine &$entry"
+                unless $sub_interface {$entry};
+            {
+                no strict 'refs';
+                *{caller() . "::$entry"} = $sub_interface {$entry};
+            }
+            $exported {$entry} ++;
+        }
+    }
+}
+
+sub AUTOLOAD { _croak "Can't $AUTOLOAD" }
+
+sub DESTROY {}
+
+my %cache;
+
+my $fpat = qr/^(-\w+)/;
+
+sub _decache {
+        my @args = @{tied %{$_[0]}};
+        my @nonflags = grep {!/$fpat/} @args;
+        my $cache = get_cache(@nonflags);
+        _croak "Can't create unknown regex: \$RE{"
+            . join("}{",@args) . "}"
+                unless exists $cache->{__VAL__};
+        _croak "Perl $] does not support the pattern "
+            . "\$RE{" . join("}{",@args)
+            . "}.\nYou need Perl $cache->{__VAL__}{version} or later"
+                unless ($cache->{__VAL__}{version}||0) <= $];
+        my %flags = ( %{$cache->{__VAL__}{default}},
+                      map { /$fpat\Q$;\E(.*)/ ? ($1 => $2)
+                          : /$fpat/           ? ($1 => undef)
+                          :                     ()
+                          } @args);
+        $cache->{__VAL__}->_clone_with(\@args, \%flags);
+}
+
+use overload q{""} => \&_decache;
+
+
+sub get_cache {
+        my $cache = \%cache;
+        foreach (@_) {
+                $cache = $cache->{$_}
+                      || ($cache->{$_} = {});
+        }
+        return $cache;
+}
+
+sub croak_version {
+        my ($entry, @args) = @_;
+}
+
+sub pattern {
+        my %spec = @_;
+        _croak 'pattern() requires argument: name => [ @list ]'
+                unless $spec{name} && ref $spec{name} eq 'ARRAY';
+        _croak 'pattern() requires argument: create => $sub_ref_or_string'
+                unless $spec{create};
+
+        if (ref $spec{create} ne "CODE") {
+                my $fixed_str = "$spec{create}";
+                $spec{create} = sub { $fixed_str }
+        }
+
+        my @nonflags;
+        my %default;
+        foreach ( @{$spec{name}} ) {
+                if (/$fpat=(.*)/) {
+                        $default{$1} = $2;
+                }
+                elsif (/$fpat\s*$/) {
+                        $default{$1} = undef;
+                }
+                else {
+                        push @nonflags, $_;
+                }
+        }
+
+        my $entry = get_cache(@nonflags);
+
+        if ($entry->{__VAL__}) {
+                _carp "Overriding \$RE{"
+                   . join("}{",@nonflags)
+                   . "}";
+        }
+
+        $entry->{__VAL__} = bless {
+                                create  => $spec{create},
+                                match   => $spec{match} || \&generic_match,
+                                subs    => $spec{subs}  || \&generic_subs,
+                                version => $spec{version},
+                                default => \%default,
+                            }, 'Regexp::Common::Entry';
+
+        foreach (@nonflags) {s/\W/X/g}
+        my $subname = "RE_" . join ("_", @nonflags);
+        $sub_interface{$subname} = sub {
+                push @_ => undef if @_ % 2;
+                my %flags = @_;
+                my $pat = $spec{create}->($entry->{__VAL__},
+                               {%default, %flags}, \@nonflags);
+                if (exists $flags{-keep}) { $pat =~ s/\Q(?k:/(/g; }
+                else { $pat =~ s/\Q(?k:/(?:/g; }
+                return exists $flags {-i} ? qr /(?i:$pat)/ : qr/$pat/;
+        };
+
+        return 1;
+}
+
+sub generic_match {$_ [1] =~  /$_[0]/}
+sub generic_subs  {$_ [1] =~ s/$_[0]/$_[2]/}
+
+sub matches {
+        my ($self, $str) = @_;
+        my $entry = $self -> _decache;
+        $entry -> {match} -> ($entry, $str);
+}
+
+sub subs {
+        my ($self, $str, $newstr) = @_;
+        my $entry = $self -> _decache;
+        $entry -> {subs} -> ($entry, $str, $newstr);
+        return $str;
+}
+
+
+package Regexp::Common::Entry;
+# use Carp;
+
+local $^W = 1;
+
+use overload
+    q{""} => sub {
+        my ($self) = @_;
+        my $pat = $self->{create}->($self, $self->{flags}, $self->{args});
+        if (exists $self->{flags}{-keep}) {
+            $pat =~ s/\Q(?k:/(/g;
+        }
+        else {
+            $pat =~ s/\Q(?k:/(?:/g;
+        }
+        if (exists $self->{flags}{-i})   { $pat = "(?i)$pat" }
+        return $pat;
+    };
+
+sub _clone_with {
+    my ($self, $args, $flags) = @_;
+    bless { %$self, args=>$args, flags=>$flags }, ref $self;
+}
+# 
+#    Copyright (c) 2001 - 2005, Damian Conway and Abigail. All Rights
+#  Reserved. This module is free software. It may be used, redistributed
+#      and/or modified under the terms of the Perl Artistic License
+#            (see http://www.perl.com/perl/misc/Artistic.html)
+EOCommon
+# 2}}}
+$Regexp_Common_Contents{'Common/comment'} = <<'EOC';   # {{{2
+# $Id: comment.pm,v 2.116 2005/03/16 00:00:02 abigail Exp $
+
+package Regexp::Common::comment;
+
+use strict;
+local $^W = 1;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+use vars qw /$VERSION/;
+
+($VERSION) = q $Revision: 2.116 $ =~ /[\d.]+/g;
+
+my @generic = (
+    {languages => [qw /ABC Forth/],
+     to_eol    => ['\\\\']},   # This is for just a *single* backslash.
+
+    {languages => [qw /Ada Alan Eiffel lua/],
+     to_eol    => ['--']},
+
+    {languages => [qw /Advisor/],
+     to_eol    => ['#|//']},
+
+    {languages => [qw /Advsys CQL Lisp LOGO M MUMPS REBOL Scheme
+                       SMITH zonefile/],
+     to_eol    => [';']},
+
+    {languages => ['Algol 60'],
+     from_to   => [[qw /comment ;/]]},
+
+    {languages => [qw {ALPACA B C C-- LPC PL/I}],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw /awk fvwm2 Icon mutt Perl Python QML R Ruby shell Tcl/],
+     to_eol    => ['#']},
+
+    {languages => [[BASIC => 'mvEnterprise']],
+     to_eol    => ['[*!]|REM']},
+
+    {languages => [qw /Befunge-98 Funge-98 Shelta/],
+     id        => [';']},
+
+    {languages => ['beta-Juliet', 'Crystal Report', 'Portia'],
+     to_eol    => ['//']},
+
+    {languages => ['BML'],
+     from_to   => [['<?_c', '_c?>']],
+    },
+
+    {languages => [qw /C++/, 'C#', qw /Cg ECMAScript FPL Java JavaScript/],
+     to_eol    => ['//'],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw /CLU LaTeX slrn TeX/],
+     to_eol    => ['%']},
+
+    {languages => [qw /False/],
+     from_to   => [[qw !{ }!]]},
+
+    {languages => [qw /Fortran/],
+     to_eol    => ['!']},
+
+    {languages => [qw /Haifu/],
+     id        => [',']},
+
+    {languages => [qw /ILLGOL/],
+     to_eol    => ['NB']},
+
+    {languages => [qw /INTERCAL/],
+     to_eol    => [q{(?:(?:PLEASE(?:\s+DO)?|DO)\s+)?(?:NOT|N'T)}]},
+
+    {languages => [qw /J/],
+     to_eol    => ['NB[.]']},
+
+    {languages => [qw /Nickle/],
+     to_eol    => ['#'],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw /Oberon/],
+     from_to   => [[qw /(* *)/]]},
+     
+    {languages => [[qw /Pascal Delphi/], [qw /Pascal Free/], [qw /Pascal GPC/]],
+     to_eol    => ['//'],
+     from_to   => [[qw !{ }!], [qw !(* *)!]]},
+
+    {languages => [[qw /Pascal Workshop/]],
+     id        => [qw /"/],
+     from_to   => [[qw !{ }!], [qw !(* *)!], [qw !/* */!]]},
+
+    {languages => [qw /PEARL/],
+     to_eol    => ['!'],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw /PHP/],
+     to_eol    => ['#', '//'],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw !PL/B!],
+     to_eol    => ['[.;]']},
+
+    {languages => [qw !PL/SQL!],
+     to_eol    => ['--'],
+     from_to   => [[qw {/* */}]]},
+
+    {languages => [qw /Q-BAL/],
+     to_eol    => ['`']},
+
+    {languages => [qw /Smalltalk/],
+     id        => ['"']},
+
+    {languages => [qw /SQL/],
+     to_eol    => ['-{2,}']},
+
+    {languages => [qw /troff/],
+     to_eol    => ['\\\"']},
+
+    {languages => [qw /vi/],
+     to_eol    => ['"']},
+
+    {languages => [qw /*W/],
+     from_to   => [[qw {|| !!}]]},
+);
+
+my @plain_or_nested = (
+   [Caml         =>  undef,       "(*"  => "*)"],
+   [Dylan        =>  "//",        "/*"  => "*/"],
+   [Haskell      =>  "-{2,}",     "{-"  => "-}"],
+   [Hugo         =>  "!(?!\\\\)", "!\\" => "\\!"],
+   [SLIDE        =>  "#",         "(*"  => "*)"],
+);
+
+#
+# Helper subs.
+#
+
+sub combine      {
+    local $_ = join "|", @_;
+    if (@_ > 1) {
+        s/\(\?k:/(?:/g;
+        $_ = "(?k:$_)";
+    }
+    $_
+}
+
+sub to_eol  ($)  {"(?k:(?k:$_[0])(?k:[^\\n]*)(?k:\\n))"}
+sub id      ($)  {"(?k:(?k:$_[0])(?k:[^$_[0]]*)(?k:$_[0]))"}  # One char only!
+sub from_to      {
+    local $^W = 1;
+    my ($begin, $end) = @_;
+
+    my $qb  = quotemeta $begin;
+    my $qe  = quotemeta $end;
+    my $fe  = quotemeta substr $end   => 0, 1;
+    my $te  = quotemeta substr $end   => 1;
+
+    "(?k:(?k:$qb)(?k:(?:[^$fe]+|$fe(?!$te))*)(?k:$qe))";
+}
+
+
+my $count = 0;
+sub nested {
+    local $^W = 1;
+    my ($begin, $end) = @_;
+
+    $count ++;
+    my $r = '(??{$Regexp::Common::comment ['. $count . ']})';
+
+    my $qb  = quotemeta $begin;
+    my $qe  = quotemeta $end;
+    my $fb  = quotemeta substr $begin => 0, 1;
+    my $fe  = quotemeta substr $end   => 0, 1;
+
+    my $tb  = quotemeta substr $begin => 1;
+    my $te  = quotemeta substr $end   => 1;
+
+    use re 'eval';
+
+    my $re;
+    if ($fb eq $fe) {
+        $re = qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
+    }
+    else {
+        local $"      =  "|";
+        my   @clauses =  "(?>[^$fb$fe]+)";
+        push @clauses => "$fb(?!$tb)" if length $tb;
+        push @clauses => "$fe(?!$te)" if length $te;
+        push @clauses =>  $r;
+        $re           =   qr /(?:$qb(?:@clauses)*$qe)/;
+    }
+
+    $Regexp::Common::comment [$count] = qr/$re/;
+}
+
+#
+# Process data.
+#
+
+foreach my $info (@plain_or_nested) {
+    my ($language, $mark, $begin, $end) = @$info;
+    pattern name    => [comment => $language],
+            create  =>
+                sub {my $re     = nested $begin => $end;
+                     my $prefix = defined $mark ? $mark . "[^\n]*\n|" : "";
+                     exists $_ [1] -> {-keep} ? qr /($prefix$re)/
+                                              : qr  /$prefix$re/
+                },
+            version => 5.006,
+            ;
+}
+
+
+foreach my $group (@generic) {
+    my $pattern = combine +(map {to_eol   $_} @{$group -> {to_eol}}),
+                           (map {from_to @$_} @{$group -> {from_to}}),
+                           (map {id       $_} @{$group -> {id}}),
+                  ;
+    foreach my $language  (@{$group -> {languages}}) {
+        pattern name    => [comment => ref $language ? @$language : $language],
+                create  => $pattern,
+                ;
+    }
+}
+                
+
+    
+#
+# Other languages.
+#
+
+# http://www.pascal-central.com/docs/iso10206.txt
+pattern name    => [qw /comment Pascal/],
+        create  => '(?k:' . '(?k:[{]|[(][*])'
+                          . '(?k:[^}*]*(?:[*][^)][^}*]*)*)'
+                          . '(?k:[}]|[*][)])'
+                          . ')'
+        ;
+
+# http://www.templetons.com/brad/alice/language/
+pattern name    =>  [qw /comment Pascal Alice/],
+        create  =>  '(?k:(?k:[{])(?k:[^}\n]*)(?k:[}]))'
+        ;
+
+
+# http://westein.arb-phys.uni-dortmund.de/~wb/a68s.txt
+pattern name    => [qw (comment), 'Algol 68'],
+        create  => q {(?k:(?:#[^#]*#)|}                           .
+                   q {(?:\bco\b(?:[^c]+|\Bc|\bc(?!o\b))*\bco\b)|} .
+                   q {(?:\bcomment\b(?:[^c]+|\Bc|\bc(?!omment\b))*\bcomment\b))}
+        ;
+
+
+# See rules 91 and 92 of ISO 8879 (SGML).
+# Charles F. Goldfarb: "The SGML Handbook".
+# Oxford: Oxford University Press. 1990. ISBN 0-19-853737-9.
+# Ch. 10.3, pp 390.
+pattern name    => [qw (comment HTML)],
+        create  => q {(?k:(?k:<!)(?k:(?:--(?k:[^-]*(?:-[^-]+)*)--\s*)*)(?k:>))},
+        ;
+
+
+pattern name    => [qw /comment SQL MySQL/],
+        create  => q {(?k:(?:#|-- )[^\n]*\n|} .
+                   q {/\*(?:(?>[^*;"']+)|"[^"]*"|'[^']*'|\*(?!/))*(?:;|\*/))},
+        ;
+
+# Anything that isn't <>[]+-.,
+# http://home.wxs.nl/~faase009/Ha_BF.html
+pattern name    => [qw /comment Brainfuck/],
+        create  => '(?k:[^<>\[\]+\-.,]+)'
+        ;
+
+# Squeak is a variant of Smalltalk-80.
+# http://www.squeak.
+# http://mucow.com/squeak-qref.html
+pattern name    => [qw /comment Squeak/],
+        create  => '(?k:(?k:")(?k:[^"]*(?:""[^"]*)*)(?k:"))'
+        ;
+
+#
+# Scores of less than 5 or above 17....
+# http://www.cliff.biffle.org/esoterica/beatnik.html
+@Regexp::Common::comment::scores = (1,  3,  3,  2,  1,  4,  2,  4,  1,  8,
+                                    5,  1,  3,  1,  1,  3, 10,  1,  1,  1,
+                                    1,  4,  4,  8,  4, 10);
+pattern name    =>  [qw /comment Beatnik/],
+        create  =>  sub {
+            use re 'eval';
+            my ($s, $x);
+            my $re = qr {\b([A-Za-z]+)\b
+                         (?(?{($s, $x) = (0, lc $^N);
+                              $s += $Regexp::Common::comment::scores
+                                    [ord (chop $x) - ord ('a')] while length $x;
+                              $s  >= 5 && $s < 18})XXX|)}x;
+            $re;
+        },
+        version  => 5.008,
+        ;
+
+
+# http://www.cray.com/craydoc/manuals/007-3692-005/html-007-3692-005/
+#  (Goto table of contents/3.3 Source Form)
+# Fortran, in fixed format. Comments start with a C, c or * in the first
+# column, or a ! anywhere, but the sixth column. Then end with a newline.
+pattern name    =>  [qw /comment Fortran fixed/],
+        create  =>  '(?k:(?k:(?:^[Cc*]|(?<!^.....)!))(?k:[^\n]*)(?k:\n))'
+        ;
+
+
+# http://www.csis.ul.ie/cobol/Course/COBOLIntro.htm
+# Traditionally, comments in COBOL were indicated with an asteriks in
+# the seventh column. Modern compilers may be more lenient.
+pattern name    =>  [qw /comment COBOL/],
+        create  =>  '(?<=^......)(?k:(?k:[*])(?k:[^\n]*)(?k:\n))',
+        version =>  '5.008',
+        ;
+
+1;
+#
+#    Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+#      This module is free software. It may be used, redistributed
+#     and/or modified under the terms of the Perl Artistic License
+#           (see http://www.perl.com/perl/misc/Artistic.html)
+EOC
+# 2}}}
+$Regexp_Common_Contents{'Common/balanced'} = <<'EOB';   # {{{2
+package Regexp::Common::balanced; {
+
+use strict;
+local $^W = 1;
+
+use vars qw /$VERSION/;
+($VERSION) = q $Revision: 2.101 $ =~ /[\d.]+/g;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+
+my %closer = ( '{'=>'}', '('=>')', '['=>']', '<'=>'>' );
+my $count = -1;
+my %cache;
+
+sub nested {
+    local $^W = 1;
+    my ($start, $finish) = @_;
+
+    return $Regexp::Common::balanced [$cache {$start} {$finish}]
+            if exists $cache {$start} {$finish};
+
+    $count ++;
+    my $r = '(??{$Regexp::Common::balanced ['. $count . ']})';
+
+    my @starts   = map {s/\\(.)/$1/g; $_} grep {length}
+                        $start  =~ /([^|\\]+|\\.)+/gs;
+    my @finishes = map {s/\\(.)/$1/g; $_} grep {length}
+                        $finish =~ /([^|\\]+|\\.)+/gs;
+
+    push @finishes => ($finishes [-1]) x (@starts - @finishes);
+
+    my @re;
+    local $" = "|";
+    foreach my $begin (@starts) {
+        my $end = shift @finishes;
+
+        my $qb  = quotemeta $begin;
+        my $qe  = quotemeta $end;
+        my $fb  = quotemeta substr $begin => 0, 1;
+        my $fe  = quotemeta substr $end   => 0, 1;
+
+        my $tb  = quotemeta substr $begin => 1;
+        my $te  = quotemeta substr $end   => 1;
+
+        use re 'eval';
+
+        my $add;
+        if ($fb eq $fe) {
+            push @re =>
+                   qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
+        }
+        else {
+            my   @clauses =  "(?>[^$fb$fe]+)";
+            push @clauses => "$fb(?!$tb)" if length $tb;
+            push @clauses => "$fe(?!$te)" if length $te;
+            push @clauses =>  $r;
+            push @re      =>  qr /(?:$qb(?:@clauses)*$qe)/;
+        }
+    }
+
+    $cache {$start} {$finish} = $count;
+    $Regexp::Common::balanced [$count] = qr/@re/;
+}
+
+
+pattern name    => [qw /balanced -parens=() -begin= -end=/],
+        create  => sub {
+            my $flag = $_[1];
+            unless (defined $flag -> {-begin} && length $flag -> {-begin} &&
+                    defined $flag -> {-end}   && length $flag -> {-end}) {
+                my @open  = grep {index ($flag->{-parens}, $_) >= 0}
+                             ('[','(','{','<');
+                my @close = map {$closer {$_}} @open;
+                $flag -> {-begin} = join "|" => @open;
+                $flag -> {-end}   = join "|" => @close;
+            }
+            my $pat = nested @$flag {qw /-begin -end/};
+            return exists $flag -> {-keep} ? qr /($pat)/ : $pat;
+        },
+        version => 5.006,
+        ;
+
+}
+
+1;
+#
+#     Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+#       This module is free software. It may be used, redistributed
+#      and/or modified under the terms of the Perl Artistic License
+#            (see http://www.perl.com/perl/misc/Artistic.html)
+EOB
+# 2}}}
+$Regexp_Common_Contents{'Common/delimited'} = <<'EOD';   # {{{2
+# $Id: delimited.pm,v 2.104 2005/03/16 00:22:45 abigail Exp $
+
+package Regexp::Common::delimited;
+
+use strict;
+local $^W = 1;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+use vars qw /$VERSION/;
+
+($VERSION) = q $Revision: 2.104 $ =~ /[\d.]+/g;
+
+sub gen_delimited {
+
+    my ($dels, $escs) = @_;
+    # return '(?:\S*)' unless $dels =~ /\S/;
+    if (length $escs) {
+        $escs .= substr ($escs, -1) x (length ($dels) - length ($escs));
+    }
+    my @pat = ();
+    my $i;
+    for ($i=0; $i < length $dels; $i++) {
+        my $del = quotemeta substr ($dels, $i, 1);
+        my $esc = length($escs) ? quotemeta substr ($escs, $i, 1) : "";
+        if ($del eq $esc) {
+            push @pat,
+                 "(?k:$del)(?k:[^$del]*(?:(?:$del$del)[^$del]*)*)(?k:$del)";
+        }
+        elsif (length $esc) {
+            push @pat,
+                 "(?k:$del)(?k:[^$esc$del]*(?:$esc.[^$esc$del]*)*)(?k:$del)";
+        }
+        else {
+            push @pat, "(?k:$del)(?k:[^$del]*)(?k:$del)";
+        }
+    }
+    my $pat = join '|', @pat;
+    return "(?k:$pat)";
+}
+
+sub _croak {
+    require Carp;
+    goto &Carp::croak;
+}
+
+pattern name   => [qw( delimited -delim= -esc=\\ )],
+        create => sub {my $flags = $_[1];
+                       _croak 'Must specify delimiter in $RE{delimited}'
+                             unless length $flags->{-delim};
+                       return gen_delimited (@{$flags}{-delim, -esc});
+                  },
+        ;
+
+pattern name   => [qw( quoted -esc=\\ )],
+        create => sub {my $flags = $_[1];
+                       return gen_delimited (q{"'`}, $flags -> {-esc});
+                  },
+        ;
+
+
+1;
+#
+#     Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+#       This module is free software. It may be used, redistributed
+#      and/or modified under the terms of the Perl Artistic License
+#            (see http://www.perl.com/perl/misc/Artistic.html)
+EOD
+# 2}}}
+    my $problems        = 0;
+    $HAVE_Rexexp_Common = 0;
+    my $dir             = "";
+    if ($opt_sdir) {
+        ++$TEMP_OFF;
+        $dir = "$opt_sdir/$TEMP_OFF";
+        File::Path::rmtree($dir) if     is_dir($dir);
+        File::Path::mkpath($dir) unless is_dir($dir);
+    } else {
+        # let File::Temp create a suitable temporary directory
+        $dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+        $TEMP_INST{ $dir } = "Regexp::Common";
+    }
+    print "Using temp dir [$dir] to install Regexp::Common\n" if $opt_v;
+    my $Regexp_dir        = "$dir/Regexp";
+    my $Regexp_Common_dir = "$dir/Regexp/Common";
+    mkdir $Regexp_dir       ;
+    mkdir $Regexp_Common_dir;
+
+    foreach my $module_file (keys %Regexp_Common_Contents) {
+        my $OUT = new IO::File "$dir/Regexp/${module_file}.pm", "w";
+        if (defined $OUT) {
+            print $OUT $Regexp_Common_Contents{$module_file};
+            $OUT->close;
+        } else {
+            warn "Failed to install Regexp::${module_file}.pm\n";
+            $problems = 1;
+        }
+    }
+
+    push @INC, $dir;
+    eval "use Regexp::Common qw /comment RE_comment_HTML balanced/";
+    $HAVE_Rexexp_Common = 1 unless $problems;
+} # 1}}}
+sub Install_Algorithm_Diff {                 # {{{1
+    # Installs Tye McQueen's Algorithm::Diff module, v1.1902, into a 
+    # temporary directory for the duration of this run.
+
+my $Algorithm_Diff_Contents = <<'EOAlgDiff'; # {{{2
+package Algorithm::Diff;
+# Skip to first "=head" line for documentation.
+use strict;
+
+use integer;    # see below in _replaceNextLargerWith() for mod to make
+                # if you don't use this
+use vars qw( $VERSION @EXPORT_OK );
+$VERSION = 1.19_02;
+#          ^ ^^ ^^-- Incremented at will
+#          | \+----- Incremented for non-trivial changes to features
+#          \-------- Incremented for fundamental changes
+require Exporter;
+*import    = \&Exporter::import;
+@EXPORT_OK = qw(
+    prepare LCS LCSidx LCS_length
+    diff sdiff compact_diff
+    traverse_sequences traverse_balanced
+);
+
+# McIlroy-Hunt diff algorithm
+# Adapted from the Smalltalk code of Mario I. Wolczko, <mario@wolczko.com>
+# by Ned Konz, perl@bike-nomad.com
+# Updates by Tye McQueen, http://perlmonks.org/?node=tye
+
+# Create a hash that maps each element of $aCollection to the set of
+# positions it occupies in $aCollection, restricted to the elements
+# within the range of indexes specified by $start and $end.
+# The fourth parameter is a subroutine reference that will be called to
+# generate a string to use as a key.
+# Additional parameters, if any, will be passed to this subroutine.
+#
+# my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
+
+sub _withPositionsOfInInterval
+{
+    my $aCollection = shift;    # array ref
+    my $start       = shift;
+    my $end         = shift;
+    my $keyGen      = shift;
+    my %d;
+    my $index;
+    for ( $index = $start ; $index <= $end ; $index++ )
+    {
+        my $element = $aCollection->[$index];
+        my $key = &$keyGen( $element, @_ );
+        if ( exists( $d{$key} ) )
+        {
+            unshift ( @{ $d{$key} }, $index );
+        }
+        else
+        {
+            $d{$key} = [$index];
+        }
+    }
+    return wantarray ? %d : \%d;
+}
+
+# Find the place at which aValue would normally be inserted into the
+# array. If that place is already occupied by aValue, do nothing, and
+# return undef. If the place does not exist (i.e., it is off the end of
+# the array), add it to the end, otherwise replace the element at that
+# point with aValue.  It is assumed that the array's values are numeric.
+# This is where the bulk (75%) of the time is spent in this module, so
+# try to make it fast!
+
+sub _replaceNextLargerWith
+{
+    my ( $array, $aValue, $high ) = @_;
+    $high ||= $#$array;
+
+    # off the end?
+    if ( $high == -1 || $aValue > $array->[-1] )
+    {
+        push ( @$array, $aValue );
+        return $high + 1;
+    }
+
+    # binary search for insertion point...
+    my $low = 0;
+    my $index;
+    my $found;
+    while ( $low <= $high )
+    {
+        $index = ( $high + $low ) / 2;
+
+        # $index = int(( $high + $low ) / 2);  # without 'use integer'
+        $found = $array->[$index];
+
+        if ( $aValue == $found )
+        {
+            return undef;
+        }
+        elsif ( $aValue > $found )
+        {
+            $low = $index + 1;
+        }
+        else
+        {
+            $high = $index - 1;
+        }
+    }
+
+    # now insertion point is in $low.
+    $array->[$low] = $aValue;    # overwrite next larger
+    return $low;
+}
+
+# This method computes the longest common subsequence in $a and $b.
+
+# Result is array or ref, whose contents is such that
+#   $a->[ $i ] == $b->[ $result[ $i ] ]
+# foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
+
+# An additional argument may be passed; this is a hash or key generating
+# function that should return a string that uniquely identifies the given
+# element.  It should be the case that if the key is the same, the elements
+# will compare the same. If this parameter is undef or missing, the key
+# will be the element as a string.
+
+# By default, comparisons will use "eq" and elements will be turned into keys
+# using the default stringizing operator '""'.
+
+# Additional parameters, if any, will be passed to the key generation
+# routine.
+
+sub _longestCommonSubsequence
+{
+    my $a        = shift;    # array ref or hash ref
+    my $b        = shift;    # array ref or hash ref
+    my $counting = shift;    # scalar
+    my $keyGen   = shift;    # code ref
+    my $compare;             # code ref
+
+    if ( ref($a) eq 'HASH' )
+    {                        # prepared hash must be in $b
+        my $tmp = $b;
+        $b = $a;
+        $a = $tmp;
+    }
+
+    # Check for bogus (non-ref) argument values
+    if ( !ref($a) || !ref($b) )
+    {
+        my @callerInfo = caller(1);
+        die 'error: must pass array or hash references to ' . $callerInfo[3];
+    }
+
+    # set up code refs
+    # Note that these are optimized.
+    if ( !defined($keyGen) )    # optimize for strings
+    {
+        $keyGen = sub { $_[0] };
+        $compare = sub { my ( $a, $b ) = @_; $a eq $b };
+    }
+    else
+    {
+        $compare = sub {
+            my $a = shift;
+            my $b = shift;
+            &$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
+        };
+    }
+
+    my ( $aStart, $aFinish, $matchVector ) = ( 0, $#$a, [] );
+    my ( $prunedCount, $bMatches ) = ( 0, {} );
+
+    if ( ref($b) eq 'HASH' )    # was $bMatches prepared for us?
+    {
+        $bMatches = $b;
+    }
+    else
+    {
+        my ( $bStart, $bFinish ) = ( 0, $#$b );
+
+        # First we prune off any common elements at the beginning
+        while ( $aStart <= $aFinish
+            and $bStart <= $bFinish
+            and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
+        {
+            $matchVector->[ $aStart++ ] = $bStart++;
+            $prunedCount++;
+        }
+
+        # now the end
+        while ( $aStart <= $aFinish
+            and $bStart <= $bFinish
+            and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
+        {
+            $matchVector->[ $aFinish-- ] = $bFinish--;
+            $prunedCount++;
+        }
+
+        # Now compute the equivalence classes of positions of elements
+        $bMatches =
+          _withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
+    }
+    my $thresh = [];
+    my $links  = [];
+
+    my ( $i, $ai, $j, $k );
+    for ( $i = $aStart ; $i <= $aFinish ; $i++ )
+    {
+        $ai = &$keyGen( $a->[$i], @_ );
+        if ( exists( $bMatches->{$ai} ) )
+        {
+            $k = 0;
+            for $j ( @{ $bMatches->{$ai} } )
+            {
+
+                # optimization: most of the time this will be true
+                if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
+                {
+                    $thresh->[$k] = $j;
+                }
+                else
+                {
+                    $k = _replaceNextLargerWith( $thresh, $j, $k );
+                }
+
+                # oddly, it's faster to always test this (CPU cache?).
+                if ( defined($k) )
+                {
+                    $links->[$k] =
+                      [ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
+                }
+            }
+        }
+    }
+
+    if (@$thresh)
+    {
+        return $prunedCount + @$thresh if $counting;
+        for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
+        {
+            $matchVector->[ $link->[1] ] = $link->[2];
+        }
+    }
+    elsif ($counting)
+    {
+        return $prunedCount;
+    }
+
+    return wantarray ? @$matchVector : $matchVector;
+}
+
+sub traverse_sequences
+{
+    my $a                 = shift;          # array ref
+    my $b                 = shift;          # array ref
+    my $callbacks         = shift || {};
+    my $keyGen            = shift;
+    my $matchCallback     = $callbacks->{'MATCH'} || sub { };
+    my $discardACallback  = $callbacks->{'DISCARD_A'} || sub { };
+    my $finishedACallback = $callbacks->{'A_FINISHED'};
+    my $discardBCallback  = $callbacks->{'DISCARD_B'} || sub { };
+    my $finishedBCallback = $callbacks->{'B_FINISHED'};
+    my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
+
+    # Process all the lines in @$matchVector
+    my $lastA = $#$a;
+    my $lastB = $#$b;
+    my $bi    = 0;
+    my $ai;
+
+    for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
+    {
+        my $bLine = $matchVector->[$ai];
+        if ( defined($bLine) )    # matched
+        {
+            &$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
+            &$matchCallback( $ai,    $bi++, @_ );
+        }
+        else
+        {
+            &$discardACallback( $ai, $bi, @_ );
+        }
+    }
+
+    # The last entry (if any) processed was a match.
+    # $ai and $bi point just past the last matching lines in their sequences.
+
+    while ( $ai <= $lastA or $bi <= $lastB )
+    {
+
+        # last A?
+        if ( $ai == $lastA + 1 and $bi <= $lastB )
+        {
+            if ( defined($finishedACallback) )
+            {
+                &$finishedACallback( $lastA, @_ );
+                $finishedACallback = undef;
+            }
+            else
+            {
+                &$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
+            }
+        }
+
+        # last B?
+        if ( $bi == $lastB + 1 and $ai <= $lastA )
+        {
+            if ( defined($finishedBCallback) )
+            {
+                &$finishedBCallback( $lastB, @_ );
+                $finishedBCallback = undef;
+            }
+            else
+            {
+                &$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
+            }
+        }
+
+        &$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
+        &$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
+    }
+
+    return 1;
+}
+
+sub traverse_balanced
+{
+    my $a                 = shift;              # array ref
+    my $b                 = shift;              # array ref
+    my $callbacks         = shift || {};
+    my $keyGen            = shift;
+    my $matchCallback     = $callbacks->{'MATCH'} || sub { };
+    my $discardACallback  = $callbacks->{'DISCARD_A'} || sub { };
+    my $discardBCallback  = $callbacks->{'DISCARD_B'} || sub { };
+    my $changeCallback    = $callbacks->{'CHANGE'};
+    my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
+
+    # Process all the lines in match vector
+    my $lastA = $#$a;
+    my $lastB = $#$b;
+    my $bi    = 0;
+    my $ai    = 0;
+    my $ma    = -1;
+    my $mb;
+
+    while (1)
+    {
+
+        # Find next match indices $ma and $mb
+        do {
+            $ma++;
+        } while(
+                $ma <= $#$matchVector
+            &&  !defined $matchVector->[$ma]
+        );
+
+        last if $ma > $#$matchVector;    # end of matchVector?
+        $mb = $matchVector->[$ma];
+
+        # Proceed with discard a/b or change events until
+        # next match
+        while ( $ai < $ma || $bi < $mb )
+        {
+
+            if ( $ai < $ma && $bi < $mb )
+            {
+
+                # Change
+                if ( defined $changeCallback )
+                {
+                    &$changeCallback( $ai++, $bi++, @_ );
+                }
+                else
+                {
+                    &$discardACallback( $ai++, $bi, @_ );
+                    &$discardBCallback( $ai, $bi++, @_ );
+                }
+            }
+            elsif ( $ai < $ma )
+            {
+                &$discardACallback( $ai++, $bi, @_ );
+            }
+            else
+            {
+
+                # $bi < $mb
+                &$discardBCallback( $ai, $bi++, @_ );
+            }
+        }
+
+        # Match
+        &$matchCallback( $ai++, $bi++, @_ );
+    }
+
+    while ( $ai <= $lastA || $bi <= $lastB )
+    {
+        if ( $ai <= $lastA && $bi <= $lastB )
+        {
+
+            # Change
+            if ( defined $changeCallback )
+            {
+                &$changeCallback( $ai++, $bi++, @_ );
+            }
+            else
+            {
+                &$discardACallback( $ai++, $bi, @_ );
+                &$discardBCallback( $ai, $bi++, @_ );
+            }
+        }
+        elsif ( $ai <= $lastA )
+        {
+            &$discardACallback( $ai++, $bi, @_ );
+        }
+        else
+        {
+
+            # $bi <= $lastB
+            &$discardBCallback( $ai, $bi++, @_ );
+        }
+    }
+
+    return 1;
+}
+
+sub prepare
+{
+    my $a       = shift;    # array ref
+    my $keyGen  = shift;    # code ref
+
+    # set up code ref
+    $keyGen = sub { $_[0] } unless defined($keyGen);
+
+    return scalar _withPositionsOfInInterval( $a, 0, $#$a, $keyGen, @_ );
+}
+
+sub LCS
+{
+    my $a = shift;                  # array ref
+    my $b = shift;                  # array ref or hash ref
+    my $matchVector = _longestCommonSubsequence( $a, $b, 0, @_ );
+    my @retval;
+    my $i;
+    for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
+    {
+        if ( defined( $matchVector->[$i] ) )
+        {
+            push ( @retval, $a->[$i] );
+        }
+    }
+    return wantarray ? @retval : \@retval;
+}
+
+sub LCS_length
+{
+    my $a = shift;                          # array ref
+    my $b = shift;                          # array ref or hash ref
+    return _longestCommonSubsequence( $a, $b, 1, @_ );
+}
+
+sub LCSidx
+{
+    my $a= shift @_;
+    my $b= shift @_;
+    my $match= _longestCommonSubsequence( $a, $b, 0, @_ );
+    my @am= grep defined $match->[$_], 0..$#$match;
+    my @bm= @{$match}[@am];
+    return \@am, \@bm;
+}
+
+sub compact_diff
+{
+    my $a= shift @_;
+    my $b= shift @_;
+    my( $am, $bm )= LCSidx( $a, $b, @_ );
+    my @cdiff;
+    my( $ai, $bi )= ( 0, 0 );
+    push @cdiff, $ai, $bi;
+    while( 1 ) {
+        while(  @$am  &&  $ai == $am->[0]  &&  $bi == $bm->[0]  ) {
+            shift @$am;
+            shift @$bm;
+            ++$ai, ++$bi;
+        }
+        push @cdiff, $ai, $bi;
+        last   if  ! @$am;
+        $ai = $am->[0];
+        $bi = $bm->[0];
+        push @cdiff, $ai, $bi;
+    }
+    push @cdiff, 0+@$a, 0+@$b
+        if  $ai < @$a || $bi < @$b;
+    return wantarray ? @cdiff : \@cdiff;
+}
+
+sub diff
+{
+    my $a      = shift;    # array ref
+    my $b      = shift;    # array ref
+    my $retval = [];
+    my $hunk   = [];
+    my $discard = sub {
+        push @$hunk, [ '-', $_[0], $a->[ $_[0] ] ];
+    };
+    my $add = sub {
+        push @$hunk, [ '+', $_[1], $b->[ $_[1] ] ];
+    };
+    my $match = sub {
+        push @$retval, $hunk
+            if 0 < @$hunk;
+        $hunk = []
+    };
+    traverse_sequences( $a, $b,
+        { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
+    &$match();
+    return wantarray ? @$retval : $retval;
+}
+
+sub sdiff
+{
+    my $a      = shift;    # array ref
+    my $b      = shift;    # array ref
+    my $retval = [];
+    my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
+    my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
+    my $change = sub {
+        push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
+    };
+    my $match = sub {
+        push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
+    };
+    traverse_balanced(
+        $a,
+        $b,
+        {
+            MATCH     => $match,
+            DISCARD_A => $discard,
+            DISCARD_B => $add,
+            CHANGE    => $change,
+        },
+        @_
+    );
+    return wantarray ? @$retval : $retval;
+}
+
+########################################
+my $Root= __PACKAGE__;
+package Algorithm::Diff::_impl;
+use strict;
+
+sub _Idx()  { 0 } # $me->[_Idx]: Ref to array of hunk indices
+            # 1   # $me->[1]: Ref to first sequence
+            # 2   # $me->[2]: Ref to second sequence
+sub _End()  { 3 } # $me->[_End]: Diff between forward and reverse pos
+sub _Same() { 4 } # $me->[_Same]: 1 if pos 1 contains unchanged items
+sub _Base() { 5 } # $me->[_Base]: Added to range's min and max
+sub _Pos()  { 6 } # $me->[_Pos]: Which hunk is currently selected
+sub _Off()  { 7 } # $me->[_Off]: Offset into _Idx for current position
+sub _Min() { -2 } # Added to _Off to get min instead of max+1
+
+sub Die
+{
+    require Carp;
+    Carp::confess( @_ );
+}
+
+sub _ChkPos
+{
+    my( $me )= @_;
+    return   if  $me->[_Pos];
+    my $meth= ( caller(1) )[3];
+    Die( "Called $meth on 'reset' object" );
+}
+
+sub _ChkSeq
+{
+    my( $me, $seq )= @_;
+    return $seq + $me->[_Off]
+        if  1 == $seq  ||  2 == $seq;
+    my $meth= ( caller(1) )[3];
+    Die( "$meth: Invalid sequence number ($seq); must be 1 or 2" );
+}
+
+sub getObjPkg
+{
+    my( $us )= @_;
+    return ref $us   if  ref $us;
+    return $us . "::_obj";
+}
+
+sub new
+{
+    my( $us, $seq1, $seq2, $opts ) = @_;
+    my @args;
+    for( $opts->{keyGen} ) {
+        push @args, $_   if  $_;
+    }
+    for( $opts->{keyGenArgs} ) {
+        push @args, @$_   if  $_;
+    }
+    my $cdif= Algorithm::Diff::compact_diff( $seq1, $seq2, @args );
+    my $same= 1;
+    if(  0 == $cdif->[2]  &&  0 == $cdif->[3]  ) {
+        $same= 0;
+        splice @$cdif, 0, 2;
+    }
+    my @obj= ( $cdif, $seq1, $seq2 );
+    $obj[_End] = (1+@$cdif)/2;
+    $obj[_Same] = $same;
+    $obj[_Base] = 0;
+    my $me = bless \@obj, $us->getObjPkg();
+    $me->Reset( 0 );
+    return $me;
+}
+
+sub Reset
+{
+    my( $me, $pos )= @_;
+    $pos= int( $pos || 0 );
+    $pos += $me->[_End]
+        if  $pos < 0;
+    $pos= 0
+        if  $pos < 0  ||  $me->[_End] <= $pos;
+    $me->[_Pos]= $pos || !1;
+    $me->[_Off]= 2*$pos - 1;
+    return $me;
+}
+
+sub Base
+{
+    my( $me, $base )= @_;
+    my $oldBase= $me->[_Base];
+    $me->[_Base]= 0+$base   if  defined $base;
+    return $oldBase;
+}
+
+sub Copy
+{
+    my( $me, $pos, $base )= @_;
+    my @obj= @$me;
+    my $you= bless \@obj, ref($me);
+    $you->Reset( $pos )   if  defined $pos;
+    $you->Base( $base );
+    return $you;
+}
+
+sub Next {
+    my( $me, $steps )= @_;
+    $steps= 1   if  ! defined $steps;
+    if( $steps ) {
+        my $pos= $me->[_Pos];
+        my $new= $pos + $steps;
+        $new= 0   if  $pos  &&  $new < 0;
+        $me->Reset( $new )
+    }
+    return $me->[_Pos];
+}
+
+sub Prev {
+    my( $me, $steps )= @_;
+    $steps= 1   if  ! defined $steps;
+    my $pos= $me->Next(-$steps);
+    $pos -= $me->[_End]   if  $pos;
+    return $pos;
+}
+
+sub Diff {
+    my( $me )= @_;
+    $me->_ChkPos();
+    return 0   if  $me->[_Same] == ( 1 & $me->[_Pos] );
+    my $ret= 0;
+    my $off= $me->[_Off];
+    for my $seq ( 1, 2 ) {
+        $ret |= $seq
+            if  $me->[_Idx][ $off + $seq + _Min ]
+            <   $me->[_Idx][ $off + $seq ];
+    }
+    return $ret;
+}
+
+sub Min {
+    my( $me, $seq, $base )= @_;
+    $me->_ChkPos();
+    my $off= $me->_ChkSeq($seq);
+    $base= $me->[_Base] if !defined $base;
+    return $base + $me->[_Idx][ $off + _Min ];
+}
+
+sub Max {
+    my( $me, $seq, $base )= @_;
+    $me->_ChkPos();
+    my $off= $me->_ChkSeq($seq);
+    $base= $me->[_Base] if !defined $base;
+    return $base + $me->[_Idx][ $off ] -1;
+}
+
+sub Range {
+    my( $me, $seq, $base )= @_;
+    $me->_ChkPos();
+    my $off = $me->_ChkSeq($seq);
+    if( !wantarray ) {
+        return  $me->[_Idx][ $off ]
+            -   $me->[_Idx][ $off + _Min ];
+    }
+    $base= $me->[_Base] if !defined $base;
+    return  ( $base + $me->[_Idx][ $off + _Min ] )
+        ..  ( $base + $me->[_Idx][ $off ] - 1 );
+}
+
+sub Items {
+    my( $me, $seq )= @_;
+    $me->_ChkPos();
+    my $off = $me->_ChkSeq($seq);
+    if( !wantarray ) {
+        return  $me->[_Idx][ $off ]
+            -   $me->[_Idx][ $off + _Min ];
+    }
+    return
+        @{$me->[$seq]}[
+                $me->[_Idx][ $off + _Min ]
+            ..  ( $me->[_Idx][ $off ] - 1 )
+        ];
+}
+
+sub Same {
+    my( $me )= @_;
+    $me->_ChkPos();
+    return wantarray ? () : 0
+        if  $me->[_Same] != ( 1 & $me->[_Pos] );
+    return $me->Items(1);
+}
+
+my %getName;
+BEGIN {
+    %getName= (
+        same => \&Same,
+        diff => \&Diff,
+        base => \&Base,
+        min  => \&Min,
+        max  => \&Max,
+        range=> \&Range,
+        items=> \&Items, # same thing
+    );
+}
+
+sub Get
+{
+    my $me= shift @_;
+    $me->_ChkPos();
+    my @value;
+    for my $arg (  @_  ) {
+        for my $word (  split ' ', $arg  ) {
+            my $meth;
+            if(     $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/
+                ||  not  $meth= $getName{ lc $2 }
+            ) {
+                Die( $Root, ", Get: Invalid request ($word)" );
+            }
+            my( $base, $name, $seq )= ( $1, $2, $3 );
+            push @value, scalar(
+                4 == length($name)
+                    ? $meth->( $me )
+                    : $meth->( $me, $seq, $base )
+            );
+        }
+    }
+    if(  wantarray  ) {
+        return @value;
+    } elsif(  1 == @value  ) {
+        return $value[0];
+    }
+    Die( 0+@value, " values requested from ",
+        $Root, "'s Get in scalar context" );
+}
+
+
+my $Obj= getObjPkg($Root);
+no strict 'refs';
+
+for my $meth (  qw( new getObjPkg )  ) {
+    *{$Root."::".$meth} = \&{$meth};
+    *{$Obj ."::".$meth} = \&{$meth};
+}
+for my $meth (  qw(
+    Next Prev Reset Copy Base Diff
+    Same Items Range Min Max Get
+    _ChkPos _ChkSeq
+)  ) {
+    *{$Obj."::".$meth} = \&{$meth};
+}
+
+1;
+# This version released by Tye McQueen (http://perlmonks.org/?node=tye).
+# 
+# =head1 LICENSE
+# 
+# Parts Copyright (c) 2000-2004 Ned Konz.  All rights reserved.
+# Parts by Tye McQueen.
+# 
+# This program is free software; you can redistribute it and/or modify it
+# under the same terms as Perl.
+# 
+# =head1 MAILING LIST
+# 
+# Mark-Jason still maintains a mailing list.  To join a low-volume mailing
+# list for announcements related to diff and Algorithm::Diff, send an
+# empty mail message to mjd-perl-diff-request@plover.com.
+# =head1 CREDITS
+# 
+# Versions through 0.59 (and much of this documentation) were written by:
+# 
+# Mark-Jason Dominus, mjd-perl-diff@plover.com
+# 
+# This version borrows some documentation and routine names from
+# Mark-Jason's, but Diff.pm's code was completely replaced.
+# 
+# This code was adapted from the Smalltalk code of Mario Wolczko
+# <mario@wolczko.com>, which is available at
+# ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
+# 
+# C<sdiff> and C<traverse_balanced> were written by Mike Schilli
+# <m@perlmeister.com>.
+# 
+# The algorithm is that described in
+# I<A Fast Algorithm for Computing Longest Common Subsequences>,
+# CACM, vol.20, no.5, pp.350-353, May 1977, with a few
+# minor improvements to improve the speed.
+# 
+# Much work was done by Ned Konz (perl@bike-nomad.com).
+# 
+# The OO interface and some other changes are by Tye McQueen.
+# 
+EOAlgDiff
+# 2}}}
+    my $problems        = 0;
+    $HAVE_Algorith_Diff = 0;
+    my $dir             = "";
+    if ($opt_sdir) {
+        ++$TEMP_OFF;
+        $dir = "$opt_sdir/$TEMP_OFF";
+        File::Path::rmtree($dir) if     is_dir($dir);
+        File::Path::mkpath($dir) unless is_dir($dir);
+    } else {
+        # let File::Temp create a suitable temporary directory
+        $dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+        $TEMP_INST{ $dir } = "Algorithm::Diff";
+    }
+    print "Using temp dir [$dir] to install Algorithm::Diff\n" if $opt_v;
+    my $Algorithm_dir      = "$dir/Algorithm";
+    my $Algorithm_Diff_dir = "$dir/Algorithm/Diff";
+    mkdir $Algorithm_dir     ;
+    mkdir $Algorithm_Diff_dir;
+
+    my $OUT = new IO::File "$dir/Algorithm/Diff.pm", "w";
+    if (defined $OUT) {
+        print $OUT $Algorithm_Diff_Contents;
+        $OUT->close;
+    } else {
+        warn "Failed to install Algorithm/Diff.pm\n";
+        $problems = 1;
+    }
+
+    push @INC, $dir;  # between this & Regexp::Common only need to do once
+    eval "use Algorithm::Diff qw / sdiff /";
+    $HAVE_Algorith_Diff = 1 unless $problems;
+} # 1}}}
+sub call_regexp_common {                     # {{{1
+    my ($ra_lines, $language ) = @_;
+    print "-> call_regexp_common\n" if $opt_v > 2;
+
+    Install_Regexp_Common() unless $HAVE_Rexexp_Common;
+
+    my $all_lines = join("", @{$ra_lines});
+
+    no strict 'vars';
+    # otherwise get:
+    #  Global symbol "%RE" requires explicit package name at cloc line xx.
+    if ($all_lines =~ $RE{comment}{$language}) {
+        # Suppress "Use of uninitialized value in regexp compilation" that
+        # pops up when $1 is undefined--happens if there's a bug in the $RE
+        # This Pascal comment will trigger it:
+        #         (* This is { another } test. **)
+        # Curiously, testing for "defined $1" breaks the substitution.
+        no warnings; 
+        # remove   comments
+        $all_lines =~ s/$1//g;
+    }
+    # a bogus use of %RE to avoid:
+    # Name "main::RE" used only once: possible typo at cloc line xx.
+    print scalar keys %RE if $opt_v < -20;
+#?#print "$all_lines\n";
+    print "<- call_regexp_common\n" if $opt_v > 2;
+    return split("\n", $all_lines);
+} # 1}}}
+sub plural_form {                            # {{{1
+    # For getting the right plural form on some English nouns.
+    my $n = shift @_;
+    if ($n == 1) { return ( 1, "" ); }
+    else         { return ($n, "s"); }
+} # 1}}}
+sub matlab_or_objective_C {                  # {{{1
+    # Decide if code is MATLAB, Objective C, or MUMPS
+    my ($file        , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+        $rs_language , # out
+       ) = @_;
+
+    print "-> matlab_or_objective_C\n" if $opt_v > 2;
+    # matlab markers:
+    #   first line starts with "function"
+    #   some lines start with "%"
+    #   high marks for lines that start with [
+    #
+    # Objective C markers:
+    #   must have at least two brace characters, { }
+    #   has /* ... */ style comments
+    #   some lines start with @
+    #   some lines start with #include
+    #
+    # MUMPS:
+    #   has ; comment markers
+    #   do not match:  \w+\s*=\s*\w
+    #   lines begin with   \s*\.?\w+\s+\w
+    #   high marks for lines that start with \s*K\s+ or \s*Kill\s+
+
+    ${$rs_language} = "";
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        return;
+    }
+
+    my $DEBUG              = 0;
+
+    my $matlab_points      = 0;
+    my $objective_C_points = 0;
+    my $mumps_points       = 0;
+    my $has_braces         = 0;
+    while (<$IN>) {
+        ++$has_braces if m/[{}]/;
+        ++$mumps_points if $. == 1 and m{^[A-Z]};
+        if      (m{^\s*/\*}) {           #   /*
+            ++$objective_C_points;
+            --$matlab_points;
+printf ".m:  /*     obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{\w+\s*=\s*\[}) {      # matrix assignment, very matlab
+            $matlab_points += 5;
+printf ".m:  \\w=[   obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*\w+\s*=\s*}) {    # definitely not MUMPS
+            --$mumps_points;
+printf ".m:  \\w=    obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*\.?(\w)\s+(\w)} and $1 !~ /\d/ and $2 !~ /\d/) {
+            ++$mumps_points;
+printf ".m:  \\w \\w  obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*;}) {
+            ++$mumps_points;
+printf ".m:  ;      obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*#(include|import)}) {
+            # Objective C without a doubt
+            $objective_C_points = 1;
+            $matlab_points      = 0;
+printf ".m: #includ obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+            last;
+        } elsif (m{^\s*@(interface|implementation|protocol|public|protected|private|end)\s}o) {
+            # Objective C without a doubt
+            $objective_C_points = 1;
+            $matlab_points      = 0;
+printf ".m: keyword obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+            last;
+        } elsif (m{^\s*\[}) {             #   line starts with [  -- very matlab
+            $matlab_points += 5;
+printf ".m:  [      obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\sK(ill)?\s+}) {
+            $mumps_points  += 5;
+printf ".m:  Kill   obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*function}) {
+            --$objective_C_points;
+            ++$matlab_points;
+printf ".m:  funct  obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        } elsif (m{^\s*%}) {              #   %
+            # matlab commented line
+            --$objective_C_points;
+            ++$matlab_points;
+printf ".m:  pcent  obj C=% 2d  matlab=% 2d  mumps=% 2d\n", $objective_C_points, $matlab_points, $mumps_points if $DEBUG;
+        }
+    }
+    $IN->close;
+
+    print "<- matlab_or_objective_C(matlab=$matlab_points, C=$objective_C_points, mumps=$mumps_points)\n"
+        if $opt_v > 2;
+    $objective_C_points = -9.9e20 unless $has_braces >= 2;
+    if      (($matlab_points > $objective_C_points) and
+             ($matlab_points > $mumps_points)      ) {
+        ${$rs_language} = "MATLAB";
+    } elsif (($mumps_points > $objective_C_points) and
+             ($mumps_points > $matlab_points)      ) {
+        ${$rs_language} = "MUMPS";
+    } else {
+        ${$rs_language} = "Objective C";
+    }
+
+} # 1}}}
+sub Lisp_or_OpenCL {                         # {{{1
+    my ($file        , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+       ) = @_;
+
+    print "-> Lisp_or_OpenCL\n" if $opt_v > 2;
+
+    my $lang = undef;
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        return $lang;
+    }
+    my $lisp_points   = 0;
+    my $opcl_points = 0;
+    while (<$IN>) {
+        ++$lisp_points if  /^\s*;/;
+        ++$lisp_points if  /\((def|eval|require|export|let|loop|dec|format)/;
+        ++$opcl_points if  /^\s*(int|float|const|{)/;
+    }
+    $IN->close;
+    # print "lisp_points=$lisp_points   opcl_points=$opcl_points\n";
+    if ($lisp_points > $opcl_points) {
+        $lang = "Lisp";
+    } else {
+        $lang = "OpenCL";
+    }
+
+    print "<- Lisp_or_OpenCL\n" if $opt_v > 2;
+    return $lang;
+} # 1}}}
+sub Ant_or_XML {                             # {{{1
+    my ($file        , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+       ) = @_;
+
+    print "-> Ant_or_XML($file)\n" if $opt_v > 2;
+
+    my $lang = "XML";
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        return $lang;
+    }
+    my $Ant_points   = 0;
+    my $XML_points   = 1;
+    while (<$IN>) {
+        if (/^\s*<project\s+/) {
+            ++$Ant_points  ;
+            --$XML_points  ;
+        }
+        if (/xmlns:artifact="antlib:org.apache.maven.artifact.ant"/) {
+            ++$Ant_points  ;
+            --$XML_points  ;
+        }
+    }
+    $IN->close;
+
+    if ($XML_points >= $Ant_points) {
+        # tie or better goes to XML
+        $lang = "XML";
+    } else {
+        $lang = "Ant";
+    }
+
+    print "<- Ant_or_XML($lang)\n" if $opt_v > 2;
+    return $lang;
+} # 1}}}
+sub Maven_or_XML {                           # {{{1
+    my ($file        , # in
+        $rh_Err      , # in   hash of error codes
+        $raa_errors  , # out
+       ) = @_;
+
+    print "-> Maven_or_XML($file)\n" if $opt_v > 2;
+
+    my $lang = "XML";
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+        return $lang;
+    }
+    my $Mvn_points   = 0;
+    my $XML_points   = 1;
+    while (<$IN>) {
+        if (/^\s*<project\s+/) {
+            ++$Mvn_points  ;
+            --$XML_points  ;
+        }
+        if (m{xmlns="http://maven.apache.org/POM/}) {
+            ++$Mvn_points  ;
+            --$XML_points  ;
+        }
+    }
+    $IN->close;
+
+    if ($XML_points >= $Mvn_points) {
+        # tie or better goes to XML
+        $lang = "XML";
+    } else {
+        $lang = "Maven";
+    }
+
+    print "<- Maven_or_XML($lang)\n" if $opt_v > 2;
+    return $lang;
+} # 1}}}
+sub html_colored_text {                      # {{{1
+    # http://www.pagetutor.com/pagetutor/makapage/pics/net216-2.gif
+    my ($color, $text) = @_;
+#?#die "html_colored_text($text)";
+    if      ($color =~ /^red$/i)   {
+        $color = "#ff0000";
+    } elsif ($color =~ /^green$/i) {
+        $color = "#00ff00";
+    } elsif ($color =~ /^blue$/i)  {
+        $color = "#0000ff";
+    } elsif ($color =~ /^grey$/i)  {
+        $color = "#cccccc";
+    }
+#   return "" unless $text;
+    return '<font color="' . $color . '">' . html_metachars($text) . "</font>";
+} # 1}}}
+sub html_metachars {                         # {{{1
+    # Replace HTML metacharacters with their printable forms.
+    # Future:  use HTML-Encoder-0.00_04/lib/HTML/Encoder.pm
+    # from Fabiano Reese Righetti's HTML::Encoder module if 
+    # this subroutine proves to be too simplistic.
+    my ($string, ) = shift @_;
+
+    my  @in_chars    = split(//, $string);
+    my  @out_chars   = ();
+    foreach my $c (@in_chars) {
+        if      ($c eq '<') {
+            push @out_chars, '&lt;'
+        } elsif ($c eq '>') {
+            push @out_chars, '&gt;'
+        } elsif ($c eq '&') {
+            push @out_chars, '&amp;'
+        } else {
+            push @out_chars, $c;
+        }
+    }
+    return join "", @out_chars; 
+} # 1}}}
+sub test_alg_diff {                          # {{{1
+    my ($file_1 ,
+        $file_2 )
+       = @_;
+    my $fh_1 = new IO::File $file_1, "r";
+    die "Unable to read $file_1:  $!\n" unless defined $fh_1;
+    chomp(my @lines_1 = <$fh_1>);
+    $fh_1->close;
+
+    my $fh_2 = new IO::File $file_2, "r";
+    die "Unable to read $file_2:  $!\n" unless defined $fh_2;
+    chomp(my @lines_2 = <$fh_2>);
+    $fh_2->close;
+
+    my $n_no_change = 0;
+    my $n_modified  = 0;
+    my $n_added     = 0;
+    my $n_deleted   = 0;
+    my @min_sdiff   = ();
+my $NN = chr(27) . "[0m";  # normal
+my $BB = chr(27) . "[1m";  # bold
+
+    my @sdiffs = sdiff( \@lines_1, \@lines_2 );
+    foreach my $entry (@sdiffs) {
+        my ($out_1, $out_2) = ('', '');
+        if ($entry->[0] eq 'u') { 
+            ++$n_no_change; 
+          # $out_1 = $entry->[1];
+          # $out_2 = $entry->[2];
+            next; 
+        }
+#       push @min_sdiff, $entry;
+        if      ($entry->[0] eq 'c') { 
+            ++$n_modified;
+            ($out_1, $out_2) = diff_two_strings($entry->[1], $entry->[2]);
+            $out_1 =~ s/\cA(\w)/${BB}$1${NN}/g;
+            $out_2 =~ s/\cA(\w)/${BB}$1${NN}/g;
+          # $out_1 =~ s/\cA//g;
+          # $out_2 =~ s/\cA//g;
+        } elsif ($entry->[0] eq '+') { 
+            ++$n_added;
+            $out_1 = $entry->[1];
+            $out_2 = $entry->[2];
+        } elsif ($entry->[0] eq '-') { 
+            ++$n_deleted;
+            $out_1 = $entry->[1];
+            $out_2 = $entry->[2];
+        } elsif ($entry->[0] eq 'u') { 
+        } else { die "unknown entry->[0]=[$entry->[0]]\n"; }
+        printf "%-80s | %s\n", $out_1, $out_2;
+    }
+
+#   foreach my $entry (@min_sdiff) {
+#       printf "DIFF:  %s  %s  %s\n", @{$entry};
+#   }
+} # 1}}}
+sub write_comments_to_html {                 # {{{1
+    my ($filename      , # in
+        $rah_diff_L    , # in  see routine array_diff() for explanation
+        $rah_diff_R    , # in  see routine array_diff() for explanation
+        $rh_blank      , # in  location and counts of blank lines
+       ) = @_;
+
+    print "-> write_comments_to_html($filename)\n" if $opt_v > 2;
+    my $file = $filename . ".html";
+#use Data::Dumper;
+#print Dumper("rah_diff_L", $rah_diff_L, "rah_diff_R", $rah_diff_R);
+    my $OUT = new IO::File $file, "w";
+    if (!defined $OUT) {
+        warn "Unable to write to $file\n";
+        print "<- write_comments_to_html\n" if $opt_v > 2;
+        return;
+    }
+
+    my $approx_line_count = scalar @{$rah_diff_L};
+    my $n_digits = 1 + int(log($approx_line_count)/2.30258509299405); # log_10
+
+    my $html_out = html_header($filename);
+
+    my $comment_line_number = 0;
+    for (my $i = 0; $i < scalar @{$rah_diff_R}; $i++) {
+        if (defined $rh_blank->{$i}) {
+            foreach (1..$rh_blank->{$i}) {
+                $html_out .= "<!-- blank -->\n";
+            }
+        }
+        my $line_num = "";
+        my $pre      = "";
+        my $post     = '</span> &nbsp;';
+warn "undef rah_diff_R[$i]{type} " unless defined $rah_diff_R->[$i]{type};
+        if ($rah_diff_R->[$i]{type} eq 'nonexist') {
+            ++$comment_line_number;
+            $line_num = sprintf "\&nbsp; <span class=\"clinenum\"> %0${n_digits}d %s",
+                            $comment_line_number, $post;
+            $pre = '<span class="comment">';
+            $html_out .= $line_num;  
+            $html_out .= $pre .  
+                         html_metachars($rah_diff_L->[$i]{char}) . 
+                         $post . "\n";
+            next;
+        }
+        if      ($rah_diff_R->[$i]{type} eq 'code' and
+                 $rah_diff_R->[$i]{desc} eq 'same') {
+            # entire line remains as-is
+            $line_num = sprintf "\&nbsp; <span class=\"linenum\"> %0${n_digits}d %s",
+                            $rah_diff_R->[$i]{lnum}, $post;
+            $pre    = '<span class="normal">';
+            $html_out .= $line_num;  
+            $html_out .= $pre . 
+                         html_metachars($rah_diff_R->[$i]{char}) . $post;
+#XX     } elsif ($rah_diff_R->[$i]{type} eq 'code') { # code+comments
+#XX
+#XX         $line_num = '<span class="linenum">' .
+#XX                      $rah_diff_R->[$i]{lnum} . $post;
+#XX         $html_out .= $line_num;  
+#XX
+#XX         my @strings = @{$rah_diff_R->[$i]{char}{strings}}; 
+#XX         my @type    = @{$rah_diff_R->[$i]{char}{type}}; 
+#XX         for (my $i = 0; $i < scalar @strings; $i++) {
+#XX             if ($type[$i] eq 'u') {
+#XX                 $pre = '<span class="normal">';
+#XX             } else {
+#XX                 $pre = '<span class="comment">';
+#XX             }
+#XX             $html_out .= $pre .  html_metachars($strings[$i]) . $post;
+#XX         }
+# print Dumper(@strings, @type); die;
+
+        } elsif ($rah_diff_R->[$i]{type} eq 'comment') {
+            $line_num = '<span class="clinenum">' . $comment_line_number . $post;
+            # entire line is a comment
+            $pre    = '<span class="comment">';
+            $html_out .= $pre .
+                         html_metachars($rah_diff_R->[$i]{char}) . $post;
+        }
+#printf "%-30s %s %-30s\n", $line_1, $separator, $line_2;
+        $html_out .= "\n";
+    }
+
+    $html_out .= html_end();
+
+    my $out_file = "$filename.html";
+    open  OUT, ">$out_file" or die "Cannot write to $out_file $!\n";
+    print OUT $html_out;
+    close OUT;
+    print "Wrote $out_file\n" unless $opt_quiet;
+    $OUT->close;
+
+    print "<- write_comments_to_html\n" if $opt_v > 2;
+} # 1}}}
+sub array_diff {                             # {{{1
+    my ($file          , # in  only used for error reporting
+        $ra_lines_L    , # in  array of lines in Left  file (no blank lines)
+        $ra_lines_R    , # in  array of lines in Right file (no blank lines)
+        $mode          , # in  "comment" | "revision"
+        $rah_diff_L    , # out
+        $rah_diff_R    , # out
+        $raa_Errors    , # in/out
+       ) = @_;
+
+    # This routine operates in two ways:
+    # A. Computes diffs of the same file with and without comments.
+    #    This is used to classify lines as code, comments, or blank.
+    # B. Computes diffs of two revisions of a file.  This method
+    #    requires a prior run of method A using the older version
+    #    of the file because it needs lines to be classified.
+
+    # $rah_diff structure:
+    # An array with n entries where n equals the number of lines in 
+    # an sdiff of the two files.  Each entry in the array describes
+    # the contents of the corresponding line in file Left and file Right:
+    #  diff[]{type} = blank | code | code+comment | comment | nonexist
+    #        {lnum} = line number within the original file (1-based)
+    #        {desc} = same | added | removed | modified
+    #        {char} = the input line unless {desc} = 'modified' in
+    #                 which case
+    #        {char}{strings} = [ substrings ]
+    #        {char}{type}    = [ disposition (added, removed, etc)]
+    #
+
+    @{$rah_diff_L} = ();
+    @{$rah_diff_R} = ();
+
+    print "-> array_diff()\n" if $opt_v > 2;
+    my $COMMENT_MODE = 0;
+       $COMMENT_MODE = 1 if $mode eq "comment";
+
+#print "array_diff(mode=$mode)\n";
+#print Dumper("block left:" , $ra_lines_L);
+#print Dumper("block right:", $ra_lines_R);
+
+    my @sdiffs = ();
+    eval {
+        local $SIG{ALRM} = sub { die "alarm\n" };
+        alarm $opt_diff_timeout;
+        @sdiffs = sdiff($ra_lines_L, $ra_lines_R);
+        alarm 0;
+    };
+    if ($@) {
+        # timed out
+        die unless $@ eq "alarm\n"; # propagate unexpected errors
+        push @{$raa_Errors}, 
+             [ $Error_Codes{'Diff error, exceeded timeout'}, $file ];
+        if ($opt_v) {
+          warn "array_diff: diff timeout failure for $file--ignoring\n";
+        }
+        return;
+    }
+
+#use Data::Dumper::Simple;
+#print Dumper($ra_lines_L, $ra_lines_R, @sdiffs);
+#die;
+
+    my $n_L        = 0;
+    my $n_R        = 0;
+    my $n_sdiff    = 0;  # index to $rah_diff_L, $rah_diff_R
+    foreach my $triple (@sdiffs) {
+        my $flag   = $triple->[0];
+        my $line_L = $triple->[1];
+        my $line_R = $triple->[2];
+        $rah_diff_L->[$n_sdiff]{char} = $line_L;
+        $rah_diff_R->[$n_sdiff]{char} = $line_R;
+        if      ($flag eq 'u') {  # u = unchanged
+            ++$n_L;
+            ++$n_R;
+            if ($COMMENT_MODE) {
+                # line exists in both with & without comments, must be code
+                $rah_diff_L->[$n_sdiff]{type} = "code";
+                $rah_diff_R->[$n_sdiff]{type} = "code";
+            }
+            $rah_diff_L->[$n_sdiff]{desc} = "same";
+            $rah_diff_R->[$n_sdiff]{desc} = "same";
+            $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+            $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+        } elsif ($flag eq 'c') {  # c = changed
+# warn "per line sdiff() commented out\n"; if (0) {
+            ++$n_L;
+            ++$n_R;
+
+            if ($COMMENT_MODE) {
+                # line has text both with & without comments;
+                # count as code
+                $rah_diff_L->[$n_sdiff]{type} = "code";
+                $rah_diff_R->[$n_sdiff]{type} = "code";
+            }
+
+            my @chars_L = split '', $line_L;
+            my @chars_R = split '', $line_R;
+
+#XX         my @inline_sdiffs = sdiff( \@chars_L, \@chars_R );
+
+#use Data::Dumper::Simple; 
+#if ($n_R == 6 or $n_R == 1 or $n_R == 2) {
+#print "L=[$line_L]\n";
+#print "R=[$line_R]\n";
+#print Dumper(@chars_L, @chars_R, @inline_sdiffs);
+#}
+#XX         my @index = ();
+#XX         foreach my $il_triple (@inline_sdiffs) {
+#XX             # make an array of u|c|+|- corresponding
+#XX             # to each character
+#XX             push @index, $il_triple->[0];
+#XX         }
+#XX#print Dumper(@index); die;
+#XX          # expect problems if arrays @index and $inline_sdiffs[1];
+#XX          # (@{$inline_sdiffs->[1]} are the characters of line_L)
+#XX          # aren't the same length
+#XX          my $prev_type = $index[0];
+#XX          my @strings   = ();  # blocks of consecutive code or comment
+#XX          my @type      = ();  # u (=code) or c (=comment)
+#XX          my $j_str     = 0;
+#XX          $strings[$j_str] .= $chars_L[0];
+#XX          $type[$j_str] = $prev_type;
+#XX          for (my $i = 1; $i < scalar @chars_L; $i++) {
+#XX              if ($index[$i] ne $prev_type) {
+#XX                  ++$j_str;
+#XX#print "change at j_str=$j_str type=$index[$i]\n";
+#XX                  $type[$j_str] = $index[$i];
+#XX                  $prev_type    = $index[$i];
+#XX              }
+#XX              $strings[$j_str] .= $chars_L[$i];
+#XX          }
+# print Dumper(@strings, @type); die;
+#XX         delete $rah_diff_R->[$n_sdiff]{char};
+#XX         @{$rah_diff_R->[$n_sdiff]{char}{strings}} = @strings;
+#XX         @{$rah_diff_R->[$n_sdiff]{char}{type}}    = @type;
+            $rah_diff_L->[$n_sdiff]{desc} = "modified";
+            $rah_diff_R->[$n_sdiff]{desc} = "modified";
+            $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+            $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+#}
+
+        } elsif ($flag eq '+') {  # + = added
+            ++$n_R;
+            if ($COMMENT_MODE) {
+                # should never get here
+                @{$rah_diff_L} = ();
+                @{$rah_diff_R} = ();
+                push @{$raa_Errors}, 
+                     [ $Error_Codes{'Diff error (quoted comments?)'}, $file ];
+                if ($opt_v) {
+                  warn "array_diff: diff failure (diff says the\n";
+                  warn "comment-free file has added lines).\n";
+                  warn "$n_sdiff  $line_L\n";
+                }
+                last;
+            }
+            $rah_diff_L->[$n_sdiff]{type} = "nonexist";
+            $rah_diff_L->[$n_sdiff]{desc} = "removed";
+            $rah_diff_R->[$n_sdiff]{desc} = "added";
+            $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+        } elsif ($flag eq '-') {  # - = removed
+            ++$n_L;
+            if ($COMMENT_MODE) {
+                # line must be comment because blanks already gone
+                $rah_diff_L->[$n_sdiff]{type} = "comment";
+            }
+            $rah_diff_R->[$n_sdiff]{type} = "nonexist";
+            $rah_diff_R->[$n_sdiff]{desc} = "removed";
+            $rah_diff_L->[$n_sdiff]{desc} = "added";
+            $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+        }
+#printf "%-30s %s %-30s\n", $line_L, $separator, $line_R;
+        ++$n_sdiff;
+    }
+#use Data::Dumper::Simple;
+#print Dumper($rah_diff_L, $rah_diff_R);
+
+    print "<- array_diff\n" if $opt_v > 2;
+} # 1}}}
+sub remove_leading_dir {                     # {{{1 
+    my @filenames = @_;
+    #
+    #  Input should be a list of file names
+    #  with the same leading directory such as
+    # 
+    #      dir1/dir2/a.txt
+    #      dir1/dir2/b.txt
+    #      dir1/dir2/dir3/c.txt
+    #
+    #  Output is the same list minus the common
+    #  directory path:
+    # 
+    #      a.txt
+    #      b.txt
+    #      dir3/c.txt
+    #
+    print "-> remove_leading_dir()\n" if $opt_v > 2;
+    my @D = (); # a matrix:   [ [ dir1, dir2 ],         # dir1/dir2/a.txt
+                #               [ dir1, dir2 ],         # dir1/dir2/b.txt
+                #               [ dir1, dir2 , dir3] ]  # dir1/dir2/dir3/c.txt
+    if ($ON_WINDOWS) {
+        foreach my $F (@filenames) {
+            $F =~ s{\\}{/}g;
+            $F = ucfirst($F) if $F =~ /^\w:/;  # uppercase drive letter
+        }
+    }
+    if (scalar @filenames == 1) {
+        # special case:  with only one filename
+        # cannot determine a baseline, just remove first directory level
+        $filenames[0] =~ s{^.*?/}{};
+        print "-> $filenames[0]\n";
+        return $filenames[0];
+    }
+    foreach my $F (@filenames) {
+        my ($Vol, $Dir, $File) = File::Spec->splitpath($F);
+        my @x = File::Spec->splitdir( $Dir );
+        pop @x unless $x[$#x]; # last entry usually null, remove it
+        if ($ON_WINDOWS) {
+            if (defined($Vol) and $Vol) {
+                # put the drive letter, eg, C:, at the front
+                unshift @x, uc $Vol;
+            }
+        }
+#print "F=$F, Dir=$Dir  x=[", join("][", @x), "]\n";
+        push @D, [ @x ];
+    }
+
+    # now loop over columns until either they are all
+    # eliminated or a unique column is found
+
+#use Data::Dumper::Simple;
+#print Dumper("remove_leading_dir after ", @D);
+
+    my @common   = ();  # to contain the common leading directories
+    my $mismatch = 0;
+    while (!$mismatch) {
+        for (my $row = 1; $row < scalar @D; $row++) {
+#print "comparing $D[$row][0] to $D[0][0]\n";
+
+            if (!defined $D[$row][0] or !defined $D[0][0] or
+                ($D[$row][0] ne $D[0][0])) {
+                $mismatch = 1;
+                last;
+            }
+        }
+#print "mismatch=$mismatch\n";
+        if (!$mismatch) {
+            push @common, $D[0][0];
+            # all terms in the leading match; unshift the batch
+            foreach my $ra (@D) {
+                shift @{$ra};
+            }
+        }
+    }
+
+    push @common, " ";  # so that $leading will end with "/ "
+    my $leading = File::Spec->catdir( @common );
+       $leading =~ s{ $}{};  # now take back the bogus appended space
+#print "remove_leading_dir leading=[$leading]\n"; die;
+    if ($ON_WINDOWS) {
+       $leading =~ s{\\}{/}g;
+    }
+    foreach my $F (@filenames) {
+        $F =~ s{^$leading}{};
+    }
+
+    print "<- remove_leading_dir()\n" if $opt_v > 2;
+    return @filenames;
+
+} # 1}}}
+sub align_by_pairs {                         # {{{1 
+    my ($rh_file_list_L        , # in
+        $rh_file_list_R        , # in
+        $ra_added              , # out
+        $ra_removed            , # out
+        $ra_compare_list       , # out
+        ) = @_;
+    print "-> align_by_pairs()\n" if $opt_v > 2;
+    @{$ra_compare_list} = ();
+
+    my @files_L = sort keys %{$rh_file_list_L};
+    my @files_R = sort keys %{$rh_file_list_R};
+    return () unless @files_L or  @files_R;  # at least one must have stuff
+    if      ( @files_L and !@files_R) {
+        # left side has stuff, right side is empty; everything deleted
+        @{$ra_added   }     = ();
+        @{$ra_removed }     = @files_L;
+        @{$ra_compare_list} = ();
+        return;
+    } elsif (!@files_L and  @files_R) {
+        # left side is empty, right side has stuff; everything added
+        @{$ra_added   }     = @files_R;
+        @{$ra_removed }     = ();
+        @{$ra_compare_list} = ();
+        return;
+    }
+#use Data::Dumper::Simple;
+#print Dumper("align_by_pairs", @files_L, @files_R);
+#die;
+    if (scalar @files_L == 1 and scalar @files_R == 1) {
+        # The easy case:  compare two files.
+        push @{$ra_compare_list}, [ $files_L[0],  $files_R[0] ]; 
+        @{$ra_added  } = ();
+        @{$ra_removed} = ();
+        return;
+    }
+    # The harder case:  compare groups of files.  This only works
+    # if the groups are in different directories so the first step
+    # is to strip the leading directory names from file lists to
+    # make it possible to align by file names.
+    my @files_L_minus_dir = remove_leading_dir(@files_L);
+    my @files_R_minus_dir = remove_leading_dir(@files_R);
+
+    # Keys of the stripped_X arrays are canonical file names;
+    # should overlap mostly.  Keys in stripped_L but not in
+    # stripped_R are files that have been deleted.  Keys in
+    # stripped_R but not in stripped_L have been added.
+    my %stripped_L = ();
+       @stripped_L{ @files_L_minus_dir } = @files_L;
+    my %stripped_R = ();
+       @stripped_R{ @files_R_minus_dir } = @files_R;
+
+    my %common = ();
+    foreach my $f (keys %stripped_L) {
+        $common{$f}  = 1 if     defined $stripped_R{$f};
+    }
+
+    my %deleted = ();
+    foreach my $f (keys %stripped_L) {
+        $deleted{$stripped_L{$f}} = $f unless defined $stripped_R{$f};
+    }
+
+    my %added = ();
+    foreach my $f (keys %stripped_R) {
+        $added{$stripped_R{$f}}   = $f unless defined $stripped_L{$f};
+    }
+
+#use Data::Dumper::Simple;
+#print Dumper("align_by_pairs", %stripped_L, %stripped_R);
+#print Dumper("align_by_pairs", %common, %added, %deleted);
+    
+    foreach my $f (keys %common) {
+        push @{$ra_compare_list}, [ $stripped_L{$f},  
+                                    $stripped_R{$f} ]; 
+    }
+    @{$ra_added   } = keys %added  ;
+    @{$ra_removed } = keys %deleted;
+
+    print "<- align_by_pairs()\n" if $opt_v > 2;
+    return;
+#print Dumper("align_by_pairs", @files_L_minus_dir, @files_R_minus_dir);
+#die;
+} # 1}}}
+sub html_header {                            # {{{1
+    my ($title , ) = @_;
+
+    print "-> html_header\n" if $opt_v > 2;
+    return 
+'<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<meta name="GENERATOR" content="cloc http://cloc.sourceforge.net">
+' .
+"
+<!-- Created by $script v$VERSION -->
+<title>$title</title>
+" .
+'
+<style TYPE="text/css">
+<!--
+    body {
+        color: black;
+        background-color: white;
+        font-family: monospace
+    }
+
+    .whitespace {
+        background-color: gray;
+    }
+
+    .comment {
+        color: gray;
+        font-style: italic;
+    }
+
+    .clinenum {
+        color: red;
+    }
+
+    .linenum {
+        color: green;
+    }
+ -->
+</style>
+</head>
+<body>
+<pre><tt>
+';
+    print "<- html_header\n" if $opt_v > 2;
+} # 1}}}
+sub html_end {                               # {{{1
+return 
+'</tt></pre>
+</body>
+</html>
+';
+} # 1}}}
+sub die_unknown_lang {                       # {{{1
+    my ($lang, $option_name) = @_;
+    die "Unknown language '$lang' used with $option_name option.  " .
+        "The command\n  $script --show-lang\n" .
+        "will print all recognized languages.  Language names are " .
+        "case sensitive.\n" ;
+} # 1}}}
+sub unicode_file {                           # {{{1
+    my $file = shift @_; 
+
+    print "-> unicode_file($file)\n" if $opt_v > 2;
+    return 0 if (-s $file > 2_000_000);  
+    # don't bother trying to test binary files bigger than 2 MB
+
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        warn "Unable to read $file; ignoring.\n";
+        return 0;
+    }
+    my @lines = <$IN>;
+    $IN->close;
+
+    if (unicode_to_ascii( join('', @lines) )) {
+        print "<- unicode_file()\n" if $opt_v > 2;
+        return 1;
+    } else {
+        print "<- unicode_file()\n" if $opt_v > 2;
+        return 0;
+    }
+
+} # 1}}}
+sub unicode_to_ascii {                       # {{{1
+    my $string = shift @_; 
+
+    # A trivial attempt to convert UTF-16 little or big endian
+    # files into ASCII.  These files exhibit the following byte
+    # sequence:
+    #   byte   1:  255
+    #   byte   2:  254
+    #   byte   3:  ord of ASCII character
+    #   byte   4:    0
+    #   byte 3+i:  ord of ASCII character
+    #   byte 4+i:    0
+    # or
+    #   byte   1:  255
+    #   byte   2:  254
+    #   byte   3:    0
+    #   byte   4:  ord of ASCII character
+    #   byte 3+i:    0
+    #   byte 4+i:  ord of ASCII character
+
+    my $length  = length $string;
+#print "length=$length\n";
+    return '' if $length <= 3;
+    my @unicode = split(//, $string);
+
+    # check the first 100 characters for big or little endian UTF-16 encoding
+    my $max_peek = $length < 200 ? $length : 200;
+    my @view_1   = ();
+    for (my $i = 2; $i < $max_peek; $i += 2) { push @view_1, $unicode[$i] }
+    my @view_2   = ();
+    for (my $i = 3; $i < $max_peek; $i += 2) { push @view_2, $unicode[$i] }
+
+    my $points_1 = 0;
+    foreach my $C (@view_1) {
+        ++$points_1 if (32 <= ord($C) and ord($C) <= 127) or ord($C) == 13
+                                                          or ord($C) == 10
+                                                          or ord($C) ==  9;
+    }
+
+    my $points_2 = 0;
+    foreach my $C (@view_2) {
+        ++$points_2 if (32 <= ord($C) and ord($C) <= 127) or ord($C) == 13
+                                                          or ord($C) == 10
+                                                          or ord($C) ==  9;
+    }
+#print "points 1: $points_1\n";
+#print "points 2: $points_2\n";
+
+    my $offset = undef;
+    if    ($points_1 > 90) { $offset = 2; }
+    elsif ($points_2 > 90) { $offset = 3; }
+    else                   { return '' }  # neither big or little endian UTF-16
+
+    my @ascii              = ();
+    for (my $i = $offset; $i < $length; $i += 2) { push @ascii, $unicode[$i]; }
+    return join("", @ascii);
+} # 1}}}
+sub uncompress_archive_cmd {                 # {{{1
+    my ($archive_file, ) = @_;
+
+    # Wrap $archive_file in single or double quotes in the system
+    # commands below to avoid filename chicanery (including
+    # spaces in the names).
+
+    print "-> uncompress_archive_cmd($archive_file)\n" if $opt_v > 2;
+    my $extract_cmd = "";
+    my $missing     = "";
+    if ($opt_extract_with) {
+        ( $extract_cmd = $opt_extract_with ) =~ s/>FILE</$archive_file/g;
+    } elsif (basename($archive_file) eq "-" and !$ON_WINDOWS) {
+        $extract_cmd = "cat > -";
+    } elsif (($archive_file =~ /\.tar\.(gz|Z)$/ or 
+              $archive_file =~ /\.tgz$/       ) and !$ON_WINDOWS)    {
+        if (external_utility_exists("gzip --version")) {
+            if (external_utility_exists("tar --version")) {
+                $extract_cmd = "gzip -dc '$archive_file' | tar xf -";
+            } else {
+                $missing = "tar";
+            }
+        } else {
+            $missing = "gzip";
+        }
+    } elsif ($archive_file =~ /\.tar\.bz2$/ and !$ON_WINDOWS)    {
+        if (external_utility_exists("bzip2 --help")) {
+            if (external_utility_exists("tar --version")) {
+                $extract_cmd = "bzip2 -dc '$archive_file' | tar xf -";
+            } else {
+                $missing = "tar";
+            }
+        } else {
+            $missing = "bzip2";
+        }
+    } elsif ($archive_file =~ /\.tar\.xz$/ and !$ON_WINDOWS)    {
+        if (external_utility_exists("unxz --version")) {
+            if (external_utility_exists("tar --version")) {
+                $extract_cmd = "unxz -dc '$archive_file' | tar xf -";
+            } else {
+                $missing = "tar";
+            }
+        } else {
+            $missing = "bzip2";
+        }
+    } elsif ($archive_file =~ /\.tar$/ and !$ON_WINDOWS)    {
+        $extract_cmd = "tar xf '$archive_file'";
+    } elsif ($archive_file =~ /\.src\.rpm$/i and !$ON_WINDOWS) {
+        if (external_utility_exists("cpio --version")) {
+            if (external_utility_exists("rpm2cpio")) {
+                $extract_cmd = "rpm2cpio '$archive_file' | cpio -i";
+            } else {
+                $missing = "rpm2cpio";
+            }
+        } else {
+            $missing = "bzip2";
+        }
+    } elsif ($archive_file =~ /\.zip$/i and !$ON_WINDOWS)    {
+        if (external_utility_exists("unzip")) {
+            $extract_cmd = "unzip -qq -d . '$archive_file'";
+        } else {
+            $missing = "unzip";
+        }
+    } elsif ($ON_WINDOWS and $archive_file =~ /\.zip$/i) {
+        # zip on Windows, guess default Winzip install location
+        $extract_cmd = "";
+        my $WinZip = '"C:\\Program Files\\WinZip\\WinZip32.exe"';
+        if (external_utility_exists($WinZip)) {
+            $extract_cmd = "$WinZip -e -o \"$archive_file\" .";
+#print "trace 5 extract_cmd=[$extract_cmd]\n";
+        } else {
+#print "trace 6\n";
+            $missing = $WinZip;
+        }
+    }
+    print "<- uncompress_archive_cmd\n" if $opt_v > 2;
+    if ($missing) {
+        die "Unable to expand $archive_file because external\n",
+            "utility '$missing' is not available.\n",
+            "Another possibility is to use the --extract-with option.\n";
+    } else {
+        return $extract_cmd;
+    }
+}
+# 1}}}
+sub read_list_file {                         # {{{1
+    my ($file, ) = @_;
+
+    print "-> read_list_file($file)\n" if $opt_v > 2;
+    my $IN = new IO::File $file, "r";
+    if (!defined $IN) {
+        warn "Unable to read $file; ignoring.\n";
+        next;
+    }
+    my @entry = ();
+    while (<$IN>) {
+        next if /^\s*$/ or /^\s*#/; # skip empty or commented lines
+        chomp;
+        push @entry, $_;
+    }
+    $IN->close;
+
+    print "<- read_list_file\n" if $opt_v > 2;
+    return @entry;
+}
+# 1}}}
+sub external_utility_exists {                # {{{1
+    my $exe = shift @_;
+
+    my $success      = 0;
+    if ($ON_WINDOWS) {
+        $success = 1 unless system $exe . ' > nul';
+    } else {
+        $success = 1 unless system $exe . ' >/dev/null 2>&1';
+        if (!$success) {
+            $success = 1 unless system "which" . " $exe" . ' >/dev/null 2>&1';
+        }
+    }
+    
+    return $success;
+} # 1}}}
+sub write_xsl_file {                         # {{{1
+    my $OUT = new IO::File $CLOC_XSL, "w";
+    if (!defined $OUT) {
+        warn "Unable to write $CLOC_XSL  $!\n";
+        return;
+    }
+    my $XSL =             # <style>  </style> {{{2
+'<?xml version="1.0" encoding="US-ASCII"?>
+<!-- XLS file by Paul Schwann, January 2009.
+     Fixes for by-file and by-file-by-lang by d_uragan, November 2010.
+     -->
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+  <xsl:output method="html"/>
+  <xsl:template match="/">
+    <html xmlns="http://www.w3.org/1999/xhtml">
+      <head>
+        <title>CLOC Results</title>
+      </head>
+      <style type="text/css">
+        table {
+          table-layout: auto;
+          border-collapse: collapse;
+          empty-cells: show;
+        }
+        td, th {
+          padding: 4px;
+        }
+        th {
+          background-color: #CCCCCC;
+        }
+        td {
+          text-align: center;
+        }
+        table, td, tr, th {
+          border: thin solid #999999;
+        }
+      </style>
+      <body>
+        <h3><xsl:value-of select="results/header"/></h3>
+';
+# 2}}}
+
+    if ($opt_by_file) {
+        $XSL .=             # <table> </table>{{{2
+'        <table>
+          <thead>
+            <tr>
+              <th>File</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>
+              <th>Language</th>
+';
+        $XSL .=
+'             <th>3<sup>rd</sup> Generation Equivalent</th>
+              <th>Scale</th>
+' if $opt_3;
+        $XSL .=
+'           </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="results/files/file">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>
+              <td><xsl:value-of select="@language"/></td>
+';
+        $XSL .=
+'             <td><xsl:value-of select="@factor"/></td>
+              <td><xsl:value-of select="@scaled"/></td>
+' if $opt_3;
+        $XSL .=
+'           </tr>
+          </xsl:for-each>
+            <tr>
+              <th>Total</th>
+              <th><xsl:value-of select="results/files/total/@blank"/></th>
+              <th><xsl:value-of select="results/files/total/@comment"/></th>
+              <th><xsl:value-of select="results/files/total/@code"/></th>
+              <th><xsl:value-of select="results/files/total/@language"/></th>
+';
+        $XSL .=
+'             <th><xsl:value-of select="results/files/total/@factor"/></th>
+              <th><xsl:value-of select="results/files/total/@scaled"/></th>
+' if $opt_3;
+        $XSL .=
+'           </tr>
+          </tbody>
+        </table>
+        <br/>
+';
+# 2}}}
+    }
+
+    if (!$opt_by_file or $opt_by_file_by_lang) {
+        $XSL .=             # <table> </table> {{{2
+'       <table>
+          <thead>
+            <tr>
+              <th>Language</th>
+              <th>Files</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>
+';
+        $XSL .=
+'             <th>Scale</th>
+              <th>3<sup>rd</sup> Generation Equivalent</th>
+' if $opt_3;
+        $XSL .=
+'           </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="results/languages/language">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@files_count"/></td>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>
+';
+        $XSL .=
+'             <td><xsl:value-of select="@factor"/></td>
+              <td><xsl:value-of select="@scaled"/></td>
+' if $opt_3;
+        $XSL .=
+'          </tr>
+          </xsl:for-each>
+            <tr>
+              <th>Total</th>
+              <th><xsl:value-of select="results/languages/total/@sum_files"/></th>
+              <th><xsl:value-of select="results/languages/total/@blank"/></th>
+              <th><xsl:value-of select="results/languages/total/@comment"/></th>
+              <th><xsl:value-of select="results/languages/total/@code"/></th>
+';
+        $XSL .=
+'             <th><xsl:value-of select="results/languages/total/@factor"/></th>
+              <th><xsl:value-of select="results/languages/total/@scaled"/></th>
+' if $opt_3;
+        $XSL .=
+'           </tr>
+          </tbody>
+        </table>
+';
+# 2}}}
+    }
+
+    $XSL.= <<'EO_XSL'; # {{{2
+      </body>
+    </html>
+  </xsl:template>
+</xsl:stylesheet>
+
+EO_XSL
+# 2}}}
+
+    my $XSL_DIFF = <<'EO_DIFF_XSL'; # {{{2
+<?xml version="1.0" encoding="US-ASCII"?>
+<!-- XLS file by Blazej Kroll, November 2010 -->
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+  <xsl:output method="html"/>
+  <xsl:template match="/">
+    <html xmlns="http://www.w3.org/1999/xhtml">
+      <head>
+        <title>CLOC Results</title>
+      </head>
+      <style type="text/css">
+        table {
+          table-layout: auto;
+          border-collapse: collapse;
+          empty-cells: show;
+		  margin: 1em;
+        }
+        td, th {
+          padding: 4px;
+        }
+        th {
+          background-color: #CCCCCC;
+        }
+        td {
+          text-align: center;
+        }
+        table, td, tr, th {
+          border: thin solid #999999;
+        }
+      </style>
+      <body>
+        <h3><xsl:value-of select="results/header"/></h3>
+EO_DIFF_XSL
+# 2}}}
+
+    if ($opt_by_file) {
+        $XSL_DIFF.= <<'EO_DIFF_XSL'; # {{{2
+		<table>
+          <thead>
+		  <tr><th colspan="4">Same</th>
+		  </tr>
+            <tr>
+              <th>File</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/same/file">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="4">Modified</th>
+		  </tr>
+            <tr>
+              <th>File</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/modified/file">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="4">Added</th>
+		  </tr>
+            <tr>
+              <th>File</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/added/file">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="4">Removed</th>
+		  </tr>
+            <tr>
+              <th>File</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/removed/file">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+EO_DIFF_XSL
+# 2}}}
+    }
+
+    if (!$opt_by_file or $opt_by_file_by_lang) {
+        $XSL_DIFF.= <<'EO_DIFF_XSL'; # {{{2
+		<table>
+          <thead>
+		  <tr><th colspan="5">Same</th>
+		  </tr>
+            <tr>
+              <th>Language</th>
+              <th>Files</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/same/language">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@files_count"/></td>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="5">Modified</th>
+		  </tr>
+            <tr>
+              <th>Language</th>
+              <th>Files</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/modified/language">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@files_count"/></td>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="5">Added</th>
+		  </tr>
+            <tr>
+              <th>Language</th>
+              <th>Files</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/added/language">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@files_count"/></td>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+		
+		<table>
+          <thead>
+		  <tr><th colspan="5">Removed</th>
+		  </tr>
+            <tr>
+              <th>Language</th>
+              <th>Files</th>
+              <th>Blank</th>
+              <th>Comment</th>
+              <th>Code</th>              
+            </tr>
+          </thead>
+          <tbody>
+          <xsl:for-each select="diff_results/removed/language">
+            <tr>
+              <th><xsl:value-of select="@name"/></th>
+              <td><xsl:value-of select="@files_count"/></td>
+              <td><xsl:value-of select="@blank"/></td>
+              <td><xsl:value-of select="@comment"/></td>
+              <td><xsl:value-of select="@code"/></td>              
+            </tr>
+          </xsl:for-each>            
+          </tbody>
+        </table>
+EO_DIFF_XSL
+# 2}}}
+
+    }
+    
+    $XSL_DIFF.= <<'EO_DIFF_XSL'; # {{{2
+      </body>
+    </html>
+  </xsl:template>
+</xsl:stylesheet>
+EO_DIFF_XSL
+# 2}}}
+    if ($opt_diff) {
+        print $OUT $XSL_DIFF;
+    } else {
+        print $OUT $XSL;
+    }
+    $OUT->close();
+} # 1}}}
+sub normalize_file_names {                   # {{{1 
+    my (@files, ) = @_;
+
+    # Returns a hash of file names reduced to a canonical form
+    # (fully qualified file names, all path separators changed to /,
+    # Windows file names lowercased).  Hash values are the original
+    # file name.
+
+    my %normalized = ();
+    foreach my $F (@files) {
+        my $F_norm = $F;
+        if ($ON_WINDOWS) {
+            $F_norm = lc $F_norm; # for case insensitive file name comparisons
+            $F_norm =~ s{\\}{/}g; # Windows directory separators to Unix
+            $F_norm =~ s{^\./}{}g;  # remove leading ./
+            if (($F_norm !~ m{^/}) and ($F_norm !~ m{^\w:/})) {
+                # looks like a relative path; prefix with cwd
+                $F_norm = lc "$cwd/$F_norm";
+            }
+        } else {
+            $F_norm =~ s{^\./}{}g;  # remove leading ./
+            if ($F_norm !~ m{^/}) {
+                # looks like a relative path; prefix with cwd
+                $F_norm = lc "$cwd/$F_norm";
+            }
+        }
+        $normalized{ $F_norm } = $F;
+    }
+    return %normalized;
+} # 1}}}
+sub combine_diffs {                          # {{{1
+    # subroutine by Andy (awalshe@sf.net)
+    # https://sourceforge.net/tracker/?func=detail&aid=3261017&group_id=174787&atid=870625
+    my ($ra_files) = @_;
+
+    my $res   = "$URL v $VERSION\n";
+    my $dl    = '-';
+    my $width = 79;
+    # columns are in this order
+    my @cols  = ('files', 'blank', 'comment', 'code');
+    my %HoH   = ();
+  
+    foreach my $file (@{$ra_files}) {
+        my $IN = new IO::File $file, "r";
+        if (!defined $IN) {
+            warn "Unable to read $file; ignoring.\n";
+            next;
+        }
+
+        my $sec;
+        while (<$IN>) {
+            next if /^(http|Language|-----)/;
+            if (/^[A-Za-z0-9]+/) {        # section title
+                $sec = $_;
+                chomp($sec);
+                $HoH{$sec} = () if ! exists $HoH{$sec};
+                next;
+            }
+  
+            if (/^\s(same|modified|added|removed)/) {  # calculated totals row
+                my @ar = grep { $_ ne '' } split(/ /, $_);
+                chomp(@ar);
+                my $ttl = shift @ar;
+                my $i = 0;
+                foreach(@ar) {
+                    my $t = "$ttl$dl$cols[$i]";
+                    $HoH{$sec}{$t} = 0 if ! exists $HoH{$sec}{$t};
+                    $HoH{$sec}{$t} += $_;
+                    $i++;
+                }
+            }
+        }
+        $IN->close;
+    }
+
+    # rows are in this order
+    my @rows = ('same', 'modified', 'added', 'removed');
+  
+    $res .= sprintf("%s\n", "-" x $width);
+    $res .= sprintf("%-19s %14s %14s %14s %14s\n", 'Language', 
+                    $cols[0], $cols[1], $cols[2], $cols[3]);
+    $res .= sprintf("%s\n", "-" x $width);
+  
+    for my $sec ( keys %HoH ) {
+        next if $sec =~ /SUM:/;
+        $res .= "$sec\n";
+        foreach (@rows) {
+            $res .= sprintf(" %-18s %14s %14s %14s %14s\n", 
+                            $_, $HoH{$sec}{"$_$dl$cols[0]"},
+                                $HoH{$sec}{"$_$dl$cols[1]"},
+                                $HoH{$sec}{"$_$dl$cols[2]"},
+                                $HoH{$sec}{"$_$dl$cols[3]"});
+        }
+    }
+    $res .= sprintf("%s\n", "-" x $width);
+    my $sec = 'SUM:';
+    $res .= "$sec\n";
+    foreach (@rows) {
+        $res .= sprintf(" %-18s %14s %14s %14s %14s\n", 
+                        $_, $HoH{$sec}{"$_$dl$cols[0]"},
+                            $HoH{$sec}{"$_$dl$cols[1]"},
+                            $HoH{$sec}{"$_$dl$cols[2]"},
+                            $HoH{$sec}{"$_$dl$cols[3]"});
+    }
+    $res .= sprintf("%s\n", "-" x $width);
+  
+    return $res;
+} # 1}}}
+sub get_time {                               # {{{1
+    if ($HAVE_Time_HiRes) {
+        return Time::HiRes::time();
+    } else {
+        return time();
+    }
+} # 1}}}
+# subroutines copied from SLOCCount
+my %lex_files    = ();  # really_is_lex()
+my %expect_files = ();  # really_is_expect()
+my %php_files    = ();  # really_is_php()
+sub really_is_lex {                          # {{{1
+# Given filename, returns TRUE if its contents really is lex.
+# lex file must have "%%", "%{", and "%}".
+# In theory, a lex file doesn't need "%{" and "%}", but in practice
+# they all have them, and requiring them avoid mislabeling a
+# non-lexfile as a lex file.
+
+ my $filename = shift;
+ chomp($filename);
+
+ my $is_lex = 0;      # Value to determine.
+ my $percent_percent = 0;
+ my $percent_opencurly = 0;
+ my $percent_closecurly = 0;
+
+ # Return cached result, if available:
+ if ($lex_files{$filename}) { return $lex_files{$filename};}
+
+ open(LEX_FILE, "<$filename") ||
+      die "Can't open $filename to determine if it's lex.\n";
+ while(<LEX_FILE>) {
+   $percent_percent++     if (m/^\s*\%\%/);
+   $percent_opencurly++   if (m/^\s*\%\{/);
+   $percent_closecurly++   if (m/^\s*\%\}/);
+ }
+ close(LEX_FILE);
+
+ if ($percent_percent && $percent_opencurly && $percent_closecurly)
+          {$is_lex = 1;}
+
+ $lex_files{$filename} = $is_lex; # Store result in cache.
+
+ return $is_lex;
+} # 1}}}
+sub really_is_expect {                       # {{{1
+# Given filename, returns TRUE if its contents really are Expect.
+# Many "exp" files (such as in Apache and Mesa) are just "export" data,
+# summarizing something else # (e.g., its interface).
+# Sometimes (like in RPM) it's just misc. data.
+# Thus, we need to look at the file to determine
+# if it's really an "expect" file.
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it's Expect _IF_ it:
+# 1. has "load_lib" command and either "#" comments or {}.
+# 2. {, }, and one of: proc, if, [...], expect
+
+ my $is_expect = 0;      # Value to determine.
+
+ my $begin_brace = 0;  # Lines that begin with curly braces.
+ my $end_brace = 0;    # Lines that begin with curly braces.
+ my $load_lib = 0;     # Lines with the Load_lib command.
+ my $found_proc = 0;
+ my $found_if = 0;
+ my $found_brackets = 0;
+ my $found_expect = 0;
+ my $found_pound = 0;
+
+ # Return cached result, if available:
+ if ($expect_files{$filename}) { return expect_files{$filename};}
+
+ open(EXPECT_FILE, "<$filename") ||
+      die "Can't open $filename to determine if it's expect.\n";
+ while(<EXPECT_FILE>) {
+
+   if (m/#/) {$found_pound++; s/#.*//;}
+   if (m/^\s*\{/) { $begin_brace++;}
+   if (m/\{\s*$/) { $begin_brace++;}
+   if (m/^\s*\}/) { $end_brace++;}
+   if (m/\};?\s*$/) { $end_brace++;}
+   if (m/^\s*load_lib\s+\S/) { $load_lib++;}
+   if (m/^\s*proc\s/) { $found_proc++;}
+   if (m/^\s*if\s/) { $found_if++;}
+   if (m/\[.*\]/) { $found_brackets++;}
+   if (m/^\s*expect\s/) { $found_expect++;}
+ }
+ close(EXPECT_FILE);
+
+ if ($load_lib && ($found_pound || ($begin_brace && $end_brace)))
+          {$is_expect = 1;}
+ if ( $begin_brace && $end_brace &&
+      ($found_proc || $found_if || $found_brackets || $found_expect))
+          {$is_expect = 1;}
+
+ $expect_files{$filename} = $is_expect; # Store result in cache.
+
+ return $is_expect;
+} # 1}}}
+sub really_is_pascal {                       # {{{1
+# Given filename, returns TRUE if its contents really are Pascal.
+
+# This isn't as obvious as it seems.
+# Many ".p" files are Perl files
+# (such as /usr/src/redhat/BUILD/ispell-3.1/dicts/czech/glob.p),
+# others are C extractions
+# (such as /usr/src/redhat/BUILD/linux/include/linux/umsdos_fs.p
+# and some files in linuxconf).
+# However, test files in "p2c" really are Pascal, for example.
+
+# Note that /usr/src/redhat/BUILD/ucd-snmp-4.1.1/ov/bitmaps/UCD.20.p
+# is actually C code.  The heuristics determine that they're not Pascal,
+# but because it ends in ".p" it's not counted as C code either.
+# I believe this is actually correct behavior, because frankly it
+# looks like it's automatically generated (it's a bitmap expressed as code).
+# Rather than guess otherwise, we don't include it in a list of
+# source files.  Let's face it, someone who creates C files ending in ".p"
+# and expects them to be counted by default as C files in SLOCCount needs
+# their head examined.  I suggest examining their head
+# with a sucker rod (see syslogd(8) for more on sucker rods).
+
+# This heuristic counts as Pascal such files such as:
+#  /usr/src/redhat/BUILD/teTeX-1.0/texk/web2c/tangleboot.p
+# Which is hand-generated.  We don't count woven documents now anyway,
+# so this is justifiable.
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it's Pascal _IF_ it has all of the following
+# (ignoring {...} and (*...*) comments):
+# 1. "^..program NAME" or "^..unit NAME",
+# 2. "procedure", "function", "^..interface", or "^..implementation",
+# 3. a "begin", and
+# 4. it ends with "end.",
+#
+# Or it has all of the following:
+# 1. "^..module NAME" and
+# 2. it ends with "end.".
+#
+# Or it has all of the following:
+# 1. "^..program NAME",
+# 2. a "begin", and
+# 3. it ends with "end.".
+#
+# The "end." requirements in particular filter out non-Pascal.
+#
+# Note (jgb): this does not detect Pascal main files in fpc, like
+# fpc-1.0.4/api/test/testterminfo.pas, which does not have "program" in
+# it
+
+ my $is_pascal = 0;      # Value to determine.
+
+ my $has_program = 0;
+ my $has_unit = 0;
+ my $has_module = 0;
+ my $has_procedure_or_function = 0;
+ my $found_begin = 0;
+ my $found_terminating_end = 0;
+ my $has_begin = 0;
+
+ open(PASCAL_FILE, "<$filename") ||
+      die "Can't open $filename to determine if it's pascal.\n";
+ while(<PASCAL_FILE>) {
+   s/\{.*?\}//g;  # Ignore {...} comments on this line; imperfect, but effective.
+   s/\(\*.*?\*\)//g;  # Ignore (*...*) comments on this line; imperfect, but effective.
+   if (m/\bprogram\s+[A-Za-z]/i)  {$has_program=1;}
+   if (m/\bunit\s+[A-Za-z]/i)     {$has_unit=1;}
+   if (m/\bmodule\s+[A-Za-z]/i)   {$has_module=1;}
+   if (m/\bprocedure\b/i)         { $has_procedure_or_function = 1; }
+   if (m/\bfunction\b/i)          { $has_procedure_or_function = 1; }
+   if (m/^\s*interface\s+/i)      { $has_procedure_or_function = 1; }
+   if (m/^\s*implementation\s+/i) { $has_procedure_or_function = 1; }
+   if (m/\bbegin\b/i) { $has_begin = 1; }
+   # Originally I said:
+   # "This heuristic fails if there are multi-line comments after
+   # "end."; I haven't seen that in real Pascal programs:"
+   # But jgb found there are a good quantity of them in Debian, specially in 
+   # fpc (at the end of a lot of files there is a multiline comment
+   # with the changelog for the file).
+   # Therefore, assume Pascal if "end." appears anywhere in the file.
+   if (m/end\.\s*$/i) {$found_terminating_end = 1;}
+#   elsif (m/\S/) {$found_terminating_end = 0;}
+ }
+ close(PASCAL_FILE);
+
+ # Okay, we've examined the entire file looking for clues;
+ # let's use those clues to determine if it's really Pascal:
+
+ if ( ( ($has_unit || $has_program) && $has_procedure_or_function &&
+     $has_begin && $found_terminating_end ) ||
+      ( $has_module && $found_terminating_end ) ||
+      ( $has_program && $has_begin && $found_terminating_end ) )
+          {$is_pascal = 1;}
+
+ return $is_pascal;
+} # 1}}}
+sub really_is_incpascal {                    # {{{1
+# Given filename, returns TRUE if its contents really are Pascal.
+# For .inc files (mainly seen in fpc)
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it is Pacal if any of the following:
+# 1. really_is_pascal returns true
+# 2. Any usual reserverd word is found (program, unit, const, begin...)
+
+ # If the general routine for Pascal files works, we have it
+ if (really_is_pascal($filename)) { 
+   return 1;
+ }
+
+ my $is_pascal = 0;      # Value to determine.
+ my $found_begin = 0;
+
+ open(PASCAL_FILE, "<$filename") ||
+      die "Can't open $filename to determine if it's pascal.\n";
+ while(<PASCAL_FILE>) {
+   s/\{.*?\}//g;  # Ignore {...} comments on this line; imperfect, but effective.
+   s/\(\*.*?\*\)//g;  # Ignore (*...*) comments on this line; imperfect, but effective.
+   if (m/\bprogram\s+[A-Za-z]/i)  {$is_pascal=1;}
+   if (m/\bunit\s+[A-Za-z]/i)     {$is_pascal=1;}
+   if (m/\bmodule\s+[A-Za-z]/i)   {$is_pascal=1;}
+   if (m/\bprocedure\b/i)         {$is_pascal = 1; }
+   if (m/\bfunction\b/i)          {$is_pascal = 1; }
+   if (m/^\s*interface\s+/i)      {$is_pascal = 1; }
+   if (m/^\s*implementation\s+/i) {$is_pascal = 1; }
+   if (m/\bconstant\s+/i)         {$is_pascal=1;}
+   if (m/\bbegin\b/i) { $found_begin = 1; }
+   if ((m/end\.\s*$/i) && ($found_begin = 1)) {$is_pascal = 1;}
+   if ($is_pascal) {
+     last;
+   }
+ }
+
+ close(PASCAL_FILE);
+ return $is_pascal;
+} # 1}}}
+sub really_is_php {                          # {{{1
+# Given filename, returns TRUE if its contents really is php.
+
+ my $filename = shift;
+ chomp($filename);
+
+ my $is_php = 0;      # Value to determine.
+ # Need to find a matching pair of surrounds, with ending after beginning:
+ my $normal_surround = 0;  # <?; bit 0 = <?, bit 1 = ?>
+ my $script_surround = 0;  # <script..>; bit 0 = <script language="php">
+ my $asp_surround = 0;     # <%; bit 0 = <%, bit 1 = %>
+
+ # Return cached result, if available:
+ if ($php_files{$filename}) { return $php_files{$filename};}
+
+ open(PHP_FILE, "<$filename") ||
+      die "Can't open $filename to determine if it's php.\n";
+ while(<PHP_FILE>) {
+   if (m/\<\?/)                           { $normal_surround |= 1; }
+   if (m/\?\>/ && ($normal_surround & 1)) { $normal_surround |= 2; }
+   if (m/\<script.*language="?php"?/i)    { $script_surround |= 1; }
+   if (m/\<\/script\>/i && ($script_surround & 1)) { $script_surround |= 2; }
+   if (m/\<\%/)                           { $asp_surround |= 1; }
+   if (m/\%\>/ && ($asp_surround & 1)) { $asp_surround |= 2; }
+ }
+ close(PHP_FILE);
+
+ if ( ($normal_surround == 3) || ($script_surround == 3) ||
+      ($asp_surround == 3)) {
+   $is_php = 1;
+ }
+
+ $php_files{$filename} = $is_php; # Store result in cache.
+
+ return $is_php;
+} # 1}}}
+__END__
+mode values (stat $item)[2]
+       Unix    Windows
+file:  33188   33206
+dir :  16832   16895
+link:  33261   33206
+pipe:   4544    null
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc2html.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc2html.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/cloc2html.py	(revision 18231)
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+# -*- coding: ISO-8859-1 -*-
+#inspired from http://qwiki.stanford.edu/images/d/df/Latex2qwiki.txt
+import sys, re, os
+
+ISSM_DIR=os.getenv('ISSM_DIR');
+if(not ISSM_DIR): raise NameError('ISSM_DIR undefined')
+
+infile  = open('temp','r')
+outfile = open('temp.html','w')
+file_text  = infile.readlines()
+
+#write header
+outfile.write('<table width="600px" rules=none border=0 bordercolor="#000000" cellpadding="3" align="center" style="border-collapse:collapse;">\n')
+style_r='style="text-align:right;"'
+style_c='style="text-align:center;"'
+style_l='style="text-align:left;"'
+color = ' bgcolor=#7AA9DD ' #dark blue
+color1 = ' bgcolor=#C6E2FF ' #light blue
+color2 = ' bgcolor=#FFFFFF ' #white
+
+count = 0 
+toggle = 0
+for i in range(len(file_text)):
+
+	#Get current lines except if first line
+	if(i==0): continue
+	line = file_text[i]
+
+	pattern=r"----------------"
+	if (re.search(pattern,line)):
+		count+=1
+		continue
+
+	if(count==1):
+		mystr = '<tr>\n'
+		column = 1
+		for i in line.split():
+			if(column==1): mystr += '<th '+color+style_l+'>'+i+'</th>'; column+=1
+			else:          mystr += '<th '+color+style_r+'>'+i+'</th>'
+		mystr += '<th '+color+style_r+'>Total</th>\n</th>\n'
+	elif(count==2):
+		total  = 0
+		column = 1
+		if(toggle): mystr = '<tr>\n<th '+color1+style_l+'>'
+		else:       mystr = '<tr>\n<th '+color2+style_l+'>'
+		for i in line.split():
+			if(not i.isdigit() or (i.isdigit and int(i)==77)):
+				mystr += ' '+i+' '
+			else:
+				if(column==1): mystr += '</th>'
+				if(column>=2): total += int(i)
+				if(toggle): mystr += '<td '+color1+style_r+'>'+i+'</td>'
+				else:       mystr += '<td '+color2+style_r+'>'+i+'</td>'
+				column += 1
+		if(toggle): mystr += '<td '+color1+style_r+'>'+str(total)+'</td>\n</tr>\n'
+		else:       mystr += '<td '+color2+style_r+'>'+str(total)+'</td>\n</tr>\n'
+		toggle = 1 - toggle
+	elif(count==3):
+		total  = 0
+		column = 1
+		if(toggle): mystr = '<tr>\n<th '+color1+style_l+'>'
+		else:       mystr = '<tr>\n<th '+color2+style_l+'>'
+		for i in line.split():
+			if(not i.isdigit()):
+				mystr += ' '+i+' '
+			else:
+				if(column==1): mystr += '</th>'
+				if(column>=2): total += int(i)
+				if(toggle): mystr += '<td '+color1+style_r+'>'+i+'</td>'
+				else:       mystr += '<td '+color2+style_r+'>'+i+'</td>'
+				column += 1
+		if(toggle): mystr += '<td '+color1+style_r+'>'+str(total)+'</td>\n</tr>\n'
+		else:       mystr += '<td '+color2+style_r+'>'+str(total)+'</td>\n</tr>\n'
+	else:
+		continue
+
+	outfile.write(mystr)
+
+#write header
+outfile.write('</table>\n')
+
+#close all files
+infile.close()
+outfile.close()
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/convertmatlabclasses.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/convertmatlabclasses.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/convertmatlabclasses.py	(revision 18231)
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+# -*- coding: ISO-8859-1 -*-
+import sys, re, os, shutil
+
+#get names of all directories to process
+ISSM_DIR=os.getenv('ISSM_DIR');
+if(not ISSM_DIR): raise NameError('ISSM_DIR undefined')
+newclassesdir = ISSM_DIR + '/src/m/classes/'
+oldclassesdir = ISSM_DIR + '/src/m/oldclasses/'
+
+#make new directory
+if(os.path.exists(oldclassesdir)):shutil.rmtree(oldclassesdir)
+os.mkdir(oldclassesdir)
+
+#prepare subsref and subsasgn
+#{{{
+subsasgntext = r'''
+function obj = subsasgn(obj,index,val)
+obj=builtin('subsasgn',obj,index,val);
+'''
+subsreftext = r'''
+function obj = subsref(obj,index)
+obj=builtin('subsref',obj,index);
+'''
+#}}}
+
+#copy all files from new classes
+files = os.listdir(newclassesdir)
+for filename in files:
+	newpath = newclassesdir + filename
+	oldpath = oldclassesdir + filename
+	if(filename==".svn"):         continue
+	if(filename.endswith(".m")):  shutil.copy(newpath,oldpath)
+	if(filename.startswith("@")): shutil.copytree(newpath,oldpath)
+	if(filename=="clusters"):
+		files2 = os.listdir(newpath)
+		for filename2 in files2:
+			if(filename2==".svn"): continue
+			newpath = newclassesdir + filename +'/'+ filename2
+			oldpath = oldclassesdir + filename2
+			shutil.copy(newpath,oldpath)
+	if(filename=="model"):
+		shutil.copy(newpath+'/model.m'     ,oldclassesdir+'model.m');
+	if(filename=="qmu"):
+		shutil.copytree(newpath+'/@dakota_method',oldclassesdir+'/@dakota_method')
+		files2 = os.listdir(newpath)
+		for filename2 in files2:
+			if(filename2==".svn"): continue
+			if(filename2=="@dakota_method"): continue
+			newpath = newclassesdir + filename +'/'+ filename2
+			oldpath = oldclassesdir + filename2
+			shutil.copy(newpath,oldpath)
+
+files = os.listdir(oldclassesdir)
+#prepare properties
+#{{{
+propertiesfile = open(oldclassesdir+'/properties.m','w')
+propertiesfile.write("function out=properties(classname)\n");
+#}}}
+for file in files:
+	if(not file.endswith(".m")): continue;
+	print "converting " + file + " from new to old Matlab class definition..."
+	infile     = open(oldclassesdir+file,'r')
+	classname  = (re.compile(r"\.m")).sub("",file)
+	dirname    = oldclassesdir+'/@'+classname
+	step       = 0
+	properties = ""
+
+	#create directory
+	if(not os.path.exists(dirname)):
+		#print "Directory " + dirname + " does not exist, creating...";
+		os.mkdir(dirname)
+
+	#Process file
+	file_text  = infile.readlines()
+	for i in range(len(file_text)-2):
+		mystr  = file_text[i];
+
+		if("properties" in mystr and step==0): step  = 1; continue
+		if("methods"    in mystr and step==1): step  = 2; continue
+		if("function "   in mystr and step==2): step += 1; 
+
+		if(step==1):
+			if("end" in mystr): continue
+			property = mystr.lstrip();
+			property = re.sub(r"%.*$","",property);
+			property = re.sub(r"\n","",property);
+			if(len(property)):
+				properties = properties + 'OBJ' + property + ";\n"
+
+		if("function " in mystr):
+
+			#close previous file
+			if(step>3): outfile.close()
+
+			#get function name
+			mystr2 = (re.compile("=")).sub(" ",mystr); #replaces equal signs by blank space
+			mystr2 = (re.compile("\(")).sub(" ( ",mystr2); #add blank spaces before and after (
+			list=mystr2.split();
+			for j in range(len(list)):
+				word=list[j];
+				if(word=='('): break
+			objectname   = list[1]
+			functionname = list[j-1]
+			objectname = re.sub("\[","",objectname);
+			objectname = re.sub("\]","",objectname);
+			if(functionname == "disp"): functionname = "display"
+			outfile = open(dirname + '/' + functionname + '.m','w')
+
+			#deal with constructor
+			if(functionname==classname):
+
+				properties2 = re.sub("OBJ",objectname + '.',properties);
+				#write function declaration
+				outfile.write(mystr)
+				#write properties
+				outfile.write(properties2)
+				#write set class
+				outfile.write(objectname + "=class(" + objectname + ",'" + classname + "');\n")
+
+				#update properties list
+				properties2=properties2.split('\n')
+				propertiesfile2 = open(dirname + '/properties.m','w')
+				propertiesfile2.write("function out=properties(obj),\n")
+				propertiesfile2.write('\tout=cell('+str(len(properties2)-1)+',1);\n')
+				propertiesfile.write("if strcmp(classname,'"+ classname +"'),\n")
+				propertiesfile.write('\tout=cell('+str(len(properties2)-1)+',1);\n')
+				for j in range(len(properties2)-1):
+					property = re.sub(r"=.*$","",properties2[j]);
+					property = property.strip()
+					property = re.sub(objectname+'.',"",property);
+					propertiesfile.write('\tout{' + str(j+1) + "}='" + property + "';\n")
+					propertiesfile2.write('\tout{' + str(j+1) + "}='" + property + "';\n")
+				propertiesfile.write('end\n')
+				continue
+
+		#write file
+		if(step>2): outfile.write(mystr)
+
+	#close all files and delete m file
+	if(step>3):outfile.close()
+	infile.close()
+	os.remove(oldclassesdir+file)
+
+	#Add subsref and subsasgn
+	outfile = open(dirname+'/subsasgn.m','w')
+	outfile.write(subsasgntext)
+	outfile.close()
+	outfile = open(dirname+'/subsref.m','w')
+	outfile.write(subsreftext)
+	outfile.close()
+
+
+#close all files
+propertiesfile.close()
+#shutil.rmtree(newclassesdir)
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/cppcheck.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/cppcheck.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/cppcheck.sh	(revision 18231)
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+#comprehensive check, except unusedFunction
+#cppcheck -j 32 --include=$ISSM_DIR/config.h -DHAVE_CONFIG_H -D_HAVE_ADOLC_ -D_HAVE_DAKOTA_ --enable=all $ISSM_DIR/src/c 2> CPPCHECK.err
+
+#unused function only (slow)
+cppcheck --include=$ISSM_DIR/config.h -DHAVE_CONFIG_H -D_HAVE_ADOLC_ -D_HAVE_DAKOTA_ --enable=unusedFunction $ISSM_DIR/src 2> CPPCHECK.err
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/getloc.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/getloc.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/getloc.sh	(revision 18231)
@@ -0,0 +1,11 @@
+#!/bin/bash
+#get number of lines of code
+cloc-1.60.pl $ISSM_DIR/src $ISSM_DIR/m4 --exclude-dir=.svn --exclude-dir=ad  --exclude-ext=exp --exclude-lang=make --out=temp
+cat temp
+./cloc2html.py
+rm temp
+
+cat $ISSM_DIR/src/dox/issm.dox | sed '/<table/,//d' > input1
+cat $ISSM_DIR/src/dox/issm.dox | sed '1,/<\/table>/d' > input2
+cat input1 temp.html input2 > $ISSM_DIR/src/dox/issm.dox
+rm input1 input2 temp.html
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/historyISSM.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/historyISSM.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/historyISSM.m	(revision 18231)
@@ -0,0 +1,7 @@
+!vim runme.m
+runme('id',[101]);
+md.mesh.numberofelements
+md=solve(md,TransientSolutionEnum);
+md=solve(md,StressbalanceSolutionEnum);
+plotmodel(md,'data',md.results.StressbalanceSolution.Vel)
+plotmodel(md,'data',)
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/intel-compile.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/intel-compile.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/intel-compile.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+#Why don't we just type make? (shouldn't automake have taken care of this?)
+#The problem is the /Fe option from the intel compiler, which we weren't able to 
+#get automake to recognize. End result is that every file compiled is not named libISSM_a-name, 
+#but just name.  This makes the creation of libISSM.a impossible, as none of its objects 
+#can be found with the correct name. 
+#As a fix, we rename the objects, and then link.
+
+#First compile.
+#make
+
+#Then change the names
+list=`ls *.obj | grep -v libISSM_a`
+for i in `echo $list`
+do
+	mv $i libISSM_a-$i
+done
+
+#Now create the library out the .obj files
+rm -rf libISSM.a
+lib.exe /out:libISSM.a *.obj
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/issmconfiguration.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/issmconfiguration.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/issmconfiguration.sh	(revision 18231)
@@ -0,0 +1,80 @@
+#/bin/bash
+#This script picks up whatever configuration files exists in trunk/configs, 
+#and offers the user the choice to reconfigure the ISSM compilation using
+#a given configuration file: 
+
+#keep track of present directory: 
+presendir=`pwd`
+
+if test -d "$ISSM_DIR/configs" ; then
+	cd $ISSM_DIR/configs
+	LIST=`ls`
+	
+	if test -d "$JPL_SVN/usr/$USER/configs"; then
+		cd $JPL_SVN/usr/$USER/configs 
+		LIST2=`ls`
+	fi
+	
+	#print choices
+	COUNT=0;
+	printf 'ISSM wide configurations\n'
+	for STEP in $LIST
+	do
+		let COUNT=$COUNT+1
+		printf '%3i: %s\n' $COUNT $STEP
+	done
+	printf 'Personal configuration\n'
+	for STEP in $LIST2
+	do
+		let COUNT=$COUNT+1
+		printf '%3i: %s\n' $COUNT $STEP
+	done
+
+	echo -n "Configuration choice: "
+	read choice 
+
+	#Now go backto the list and retrieve the name of the configuration file: 
+	COUNT=0;
+	for STEP in $LIST
+	do
+		let COUNT=$COUNT+1
+		if [[ $COUNT == $choice ]]; then
+			configurename=$STEP
+		fi
+	done
+	for STEP in $LIST2
+	do
+		let COUNT=$COUNT+1
+		if [[ $COUNT == $choice ]]; then
+			configurename=$STEP
+		fi
+	done
+
+	#Now go ahead and configure: 
+	echo ""
+	echo "Configuring ISSM with following configs: $configurename"
+	echo ""
+
+	cd $ISSM_DIR 
+
+	#at this point, was a cleanup of the archive requested? 
+	if [ "$1" == "clean" ]; 
+	then 
+		make uninstall && make distclean
+	fi
+
+	source ./scripts/automakererun.sh 
+	if [ -f configs/$configurename ]; then 
+		source configs/$configurename
+	else 
+		source $JPL_SVN/usr/$USER/configs/$configurename
+	fi
+	
+	#we are done, go back to original directory: 
+	cd $presendir
+else
+	echo "Configuration directory does not exist!"
+	exit
+fi
+
+#alias aut='a=`pwd` && cd $ISSM_DIR && ./scripts/automakererun.sh && ./configs/config-macosx64-larour-nopetsc.sh'
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/jpic2pdf
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/jpic2pdf	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/jpic2pdf	(revision 18231)
@@ -0,0 +1,80 @@
+#!/bin/bash
+#Transform a pst from JPicEdt to a nice pdf
+
+# Generate temporary directory ($$ = process ID)
+TMPDIR=/tmp/jpic2pdf$$
+if [ -e $TMPDIR ] ; then
+	echo "$0: Temporary directory $TMPDIR already exists." 1>&2
+	exit 1
+fi
+mkdir $TMPDIR
+HOMEDIR="`pwd`" || exit 1
+
+#get input files
+if [ $# -eq 0 ]
+then
+	echo "No input file specified, exiting..." >&2
+	exit 1
+else
+	FILES=$*
+fi
+
+#convert files
+for FILE in $FILES
+do
+	#get file name without pst extension
+	NAME=$(echo $FILE | sed -e "s/.pst//g")
+
+	#transform equation only if begin{eqution} is found
+	echo "converting $FILE"
+	#Header
+	(
+	cat << ENDHEADER
+\documentclass[11pt,a0paper,landscape]{article}
+\usepackage{color}
+\usepackage[dvips]{graphicx}
+\usepackage[left=0cm, right=0cm, top=0cm, bottom=0cm]{geometry}  % margins
+\usepackage{array, multirow}
+\usepackage{amsmath,amsfonts,amssymb,mathrsfs,bm}
+\usepackage{pstricks}
+\pagestyle{empty}
+%\pagecolor{white}
+\definecolor{darkblue}{RGB}{0,0,170}
+\definecolor{darkgreen}{RGB}{0,140,0}
+\begin{document}
+ENDHEADER
+	) > $TMPDIR/out.tex
+
+	#File
+	cat $FILE >> $TMPDIR/out.tex
+
+	#Footer
+	(
+	cat << ENDFOOTER
+\end{document}
+ENDFOOTER
+) >> $TMPDIR/out.tex
+
+	cd "$TMPDIR"
+	latex -interaction=batchmode out.tex > /dev/null
+	ls
+
+	#check that the dvi has been generated
+	if [ ! -f "./out.dvi" ]; then
+		latex  -halt-on-error -interaction=errorstopmode out.tex
+		echo "latex compilation failed, See above" 1>&2
+		exit 1
+	fi
+	cd "$HOMEDIR"
+	dvips -o $TMPDIR/out.eps -E $TMPDIR/out.dvi 2> /dev/null
+	dvipdf $TMPDIR/out.dvi $TMPDIR/out.pdf
+	mv $TMPDIR/out.pdf $NAME.pdf
+
+	echo "cropping $FILE"
+	pdfcrop -noverbose $NAME.pdf $NAME.pdf
+done
+
+# Cleanup
+rm -rf $TMPDIR
+#mv $TMPDIR .
+exit 0
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/mToPy.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/mToPy.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/mToPy.py	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/scripts/mail
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/mail	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/mail	(revision 18231)
@@ -0,0 +1,158 @@
+#!/bin/sh
+
+# This is a shell script to emulate the standard mail(1) aka mailx(1)
+# aka Mail(1) tool usage for sending emails. This shell script is not
+# a client for checking or reading mail. Also, this version of mail
+# does not touch any mail boxes.
+
+# Copyright (c) 2003 by Jeremy C. Reed
+# This software is provided "as is" without any warranties. You may
+# redistribute and use this source, with or without modification,
+# as long as you include this copyright and disclaimer.
+
+# To do: some switches to consider:
+# -v  display details of delivery
+# -E  do not send empty messages
+# -c  send carbon copies to users
+# -b  send blind carbon copies
+
+# todo: test if read can read in long enough lines
+# some shells may have limit of 256 characters per read?
+ 
+SENDMAIL=sendmail  # set to path of your sendmail(8) command
+SENDMAIL_ARGS="-t -i" # -i is so dot doesn't terminate message
+                      # -t is to get recipients from headers
+
+unset subject
+unset to_addr
+dontsendempty=0
+
+about ()
+{
+  echo "This is mailx.sh version 0.03. This is simple, shell script"
+  echo "to implement mailx(1) functionality for sending mail. It does"
+  echo "not provide an interface for checking or reading email messages."
+  echo
+
+  # maybe do this without forking a command
+  mailname=$( basename $0 )
+
+  if [ -n "$1" ] ; then
+    echo "$mailname: $1" 1>&2
+  fi
+
+  echo "Usage: $mailname [-s subject] to-addr ..." 1>&2
+
+  if [ -n "$1" ] ; then
+    if [ -n "$2" ] ; then 
+      exit $2
+    fi
+    exit 100
+  fi
+
+  exit 0
+}
+
+if [ $# -eq 0 ] ; then
+  about "Sorry, this is not a mail reader." 1
+fi
+
+while [ -n "$1" ] ; do
+  case "$1" in
+  -*)
+      if [ "$1" = "-s" ] ; then
+        if [ -z "$2" ] ; then
+          about "The \"-s\" option requires an argument." 4
+        fi
+        subject="$2"
+        shift
+      elif [ "$1" = "-u" -o "$1" = "-f" ] ; then
+        about "Sorry, this is not a mail reader." 2
+#      elif [ "$1" = "-E" ] ; then
+# this probably needs to have entire message saved to temp file first
+#        dontsendempty=1
+      else
+#        about "unknown option -- $1" 3
+        about "Switch \"$1\" is not implemented." 3
+      fi
+      ;;
+  *)  if [ -n "$to_addr" ] ; then
+        to_addr="${to_addr}, $1"
+      else
+        to_addr="$1"
+      fi
+      ;;
+  esac
+  shift
+done
+
+
+if [ -t 0 ] ; then   # no piped in standard input
+  if [ -z "$subject" ] ; then
+    echo -n "Subject: "
+    OLD_IFS=$IFS
+    IFS=""
+    read -r subject
+    IFS=$OLD_IFS
+  fi
+fi
+
+if [ -z "$to_addr" ] ; then
+  about "No recipients specified." 6
+#  about "You must specify recipients." 6
+fi
+
+# generate SMTP headers
+
+# mail(1) doesn't seem to set date
+#date +"Date: %a, %e %b %G %T %z"
+## maybe pipe though sed to get rid of extra space
+## before single digit day of month?
+
+{
+# if [ -n "$to_addr" ] ; then
+echo "To: ${to_addr}"
+# fi
+
+if [ -n "$subject" ] ; then
+  echo "Subject: $subject"
+fi
+
+# end of headers
+echo ""
+
+# output
+line_count=0
+OLD_IFS=$IFS
+IFS=""
+while read -r line ; do
+  # finish if manual, non-piped input is a period on a line by itself
+  if [ "$line" = "." -a -t 0 ] ; then
+      break
+  fi
+  echo "$line"
+  line_count=$(( line_count + 1 ))
+done
+
+IFS=$OLD_IFS
+
+if [ -t 0 ] ; then   # no piped in standard input
+  echo "EOT" 1>&2
+fi
+
+# later add switch to not send mail by exiting
+if [ "$line_count" -eq 0 ] ; then
+#  if [ "$dontsendempty" -eq 1 ] ; then
+# todo this, have it save to temp file and then send to sendmail as needed
+#    # No message, so just exit cleanly
+#    exit 0
+#  fi
+  if [ -z "$subject" ] ; then
+    echo "No message, no subject; hope that's ok" 1>&2
+  else
+    echo "Null message body; hope that's ok" 1>&2
+  fi
+fi
+
+} | $SENDMAIL $SENDMAIL_ARGS
+
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/matlabissm.bat
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/matlabissm.bat	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/matlabissm.bat	(revision 18231)
@@ -0,0 +1,2 @@
+@echo off
+matlab 
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/ol
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/ol	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/ol	(revision 18231)
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#Get the runme file, read it, and display steps
+rm -rf orglist_temporary_file
+LIST=$(cat runme.m | grep perform | sed "s/'/ /g" | awk '{print $3}')
+
+COUNT=0;
+echo "Available steps"
+for STEP in $LIST
+do
+	let COUNT=$COUNT+1
+	printf '%3i: %s\n' $COUNT $STEP
+done
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/ol.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/ol.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/ol.m	(revision 18231)
@@ -0,0 +1,1 @@
+system('ol');
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/pdfcrop.pl
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/pdfcrop.pl	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/pdfcrop.pl	(revision 18231)
@@ -0,0 +1,608 @@
+eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
+  if 0;
+use strict;
+$^W=1; # turn warning on
+#
+# pdfcrop.pl
+#
+# Copyright (C) 2002, 2004, 2005, 2008, 2009 Heiko Oberdiek.
+#
+# This program may be distributed and/or modified under the
+# conditions of the LaTeX Project Public License, either version 1.2
+# of this license or (at your option) any later version.
+# The latest version of this license is in
+#   http://www.latex-project.org/lppl.txt
+# and version 1.2 or later is part of all distributions of LaTeX
+# version 1999/12/01 or later.
+#
+# See file "README" for a list of files that belong to this project.
+#
+# This file "pdfcrop.pl" may be renamed to "pdfcrop"
+# for installation purposes.
+#
+my $file        = "pdfcrop.pl";
+my $program     = uc($&) if $file =~ /^\w+/;
+my $version     = "1.18";
+my $date        = "2009/07/18";
+my $author      = "Heiko Oberdiek";
+my $copyright   = "Copyright (c) 2002-2009 by $author.";
+#
+# Reqirements: Perl5, Ghostscript
+# History:
+#   2002/10/30 v1.0:  First release.
+#   2002/10/30 v1.1:  Option --hires added.
+#   2002/11/04 v1.2:  "nul" instead of "/dev/null" for windows.
+#   2002/11/23 v1.3:  Use of File::Spec module's "devnull" call.
+#   2002/11/29 v1.4:  Option --papersize added.
+#   2004/06/24 v1.5:  Clear map file entries so that pdfTeX
+#                     does not touch the fonts.
+#   2004/06/26 v1.6:  Use mgs.exe instead of gswin32c.exe for MIKTEX.
+#   2005/03/11 v1.7:  Support of spaces in file names
+#                     (open("-|") is used for ghostscript call).
+#   2008/01/09 v1.8:  Fix for moving the temporary file to the output
+#                     file across file system boundaries.
+#   2008/04/05 v1.9:  Options --resolution and --bbox added.
+#   2008/07/16 v1.10: Support for XeTeX added with new options
+#                     --pdftex, --xetex, and --xetexcmd.
+#   2008/07/22 v1.11: Workaround for open("-|").
+#   2008/07/23 v1.12: Workarounds for the workaround (error detection, ...).
+#   2008/07/24 v1.13: open("-|")/workaround removed.
+#                     Input files with unsafe file names are linked/copied
+#                     to temporary file with safe file name.
+#   2008/09/12 v1.14: Error detection for invalid Bounding Boxes.
+#   2009/07/14 v1.15: Fix for negative coordinates in Bounding Boxes
+#                     (David Menestrina).
+#   2009/07/16 v1.16: Security fixes:
+#                     * -dSAFER added for Ghostscript,
+#                     * -no-shell-escape added for pdfTeX/XeTeX.
+#   2009/07/17 v1.17: Security fixes:
+#                     * Backticks and whitespace are forbidden
+#                       for options --(gs|pdftex|xetex)cmd.
+#                     * Validation of options --papersize and --resolution.
+#   2009/07/18 v1.18: * Restricted mode added.
+#                     * Option --version added.
+
+### program identification
+my $title = "$program $version, $date - $copyright\n";
+
+### error strings
+my $Error = "!!! Error:"; # error prefix
+
+### string constants for Ghostscript run
+# get Ghostscript command name
+my $GS = "gs";
+$GS = "gs386"    if $^O =~ /dos/i;
+$GS = "gsos2"    if $^O =~ /os2/i;
+$GS = "gswin32c" if $^O =~ /mswin32/i;
+$GS = "gswin32c" if $^O =~ /cygwin/i;
+$GS = "mgs"      if defined($ENV{"TEXSYSTEM"}) and
+                    $ENV{"TEXSYSTEM"} =~ /miktex/i;
+
+# Windows detection (no SIGHUP)
+my $Win = 0;
+$Win = 1 if $^O =~ /mswin32/i;
+$Win = 1 if $^O =~ /cygwin/i;
+
+# restricted mode
+my $restricted = 0;
+if ($0 =~ /rpdfcrop/ or $0 =~ /restricted/) {
+    $restricted = 1;
+}
+
+# "null" device
+use File::Spec::Functions qw(devnull);
+my $null = devnull();
+
+### variables
+my $inputfile   = "";
+my $outputfile  = "";
+my $tmp = "tmp-\L$program\E-$$";
+
+### paper sizes
+
+my @papersizes = qw[
+  11x17 ledger legal letter lettersmall
+  archE archD archC archB archA
+  a0 a1 a2 a3 a4 a4small a5 a6 a7 a8 a9 a10
+  isob0 isob1 isob2 isob3 isob4 isob5 isob6
+  c0 c1 c2 c3 c4 c5 c6
+  jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6
+  b0 b1 b2 b3 b4 b5
+  flsa flse halfletter
+];
+my %papersizes;
+foreach (@papersizes) {
+    $papersizes{$_} = 1;
+}
+
+### option variables
+my @bool = ("false", "true");
+$::opt_version    = 0;
+$::opt_help       = 0;
+$::opt_debug      = 0;
+$::opt_verbose    = 0;
+$::opt_gscmd      = $GS;
+$::opt_pdftexcmd  = "pdftex";
+$::opt_xetexcmd   = "xetex";
+$::opt_tex        = "pdftex";
+$::opt_margins    = "0 0 0 0";
+$::opt_clip       = 0;
+$::opt_hires      = 0;
+$::opt_papersize  = "";
+$::opt_resolution = "";
+$::opt_bbox       = "";
+
+my $usage = <<"END_OF_USAGE";
+${title}Syntax:   \L$program\E [options] <input[.pdf]> [output file]
+Function: Margins are calculated and removed for each page in the file.
+Options:                                                    (defaults:)
+  --help              print usage
+  --version           print version number
+  --(no)verbose       verbose printing                      ($bool[$::opt_verbose])
+  --(no)debug         debug informations                    ($bool[$::opt_debug])
+  --gscmd <name>      call of ghostscript                   ($::opt_gscmd)
+  --pdftex | --xetex  use pdfTeX | use XeTeX                ($::opt_tex)
+  --pdftexcmd <name>  call of pdfTeX                        ($::opt_pdftexcmd)
+  --xetexcmd <name>   call of XeTeX                         ($::opt_xetexcmd)
+  --margins "<left> <top> <right> <bottom>"                 ($::opt_margins)
+                      add extra margins, unit is bp. If only one number is
+                      given, then it is used for all margins, in the case
+                      of two numbers they are also used for right and bottom.
+  --(no)clip          clipping support, if margins are set  ($bool[$::opt_clip])
+                      (not available for --xetex)
+  --(no)hires         using `%%HiResBoundingBox'            ($bool[$::opt_hires])
+                      instead of `%%BoundingBox'
+Expert options:
+  --restricted        turn on restricted mode               ($bool[$restricted])
+  --papersize <foo>   parameter for gs's -sPAPERSIZE=<foo>,
+                      use only with older gs versions <7.32 ($::opt_papersize)
+  --resolution <xres>x<yres>                                ()
+  --resolution <res>  pass argument to ghostscript's option -r
+                      Example: --resolution 72
+  --bbox "<left> <top> <right> <bottom>"                    ()
+                      override bounding box found by ghostscript
+Examples:
+  \L$program\E --margins 10 input.pdf output.pdf
+  \L$program\E --margins '5 10 5 20' --clip input.pdf output.pdf
+In case of errors:
+  Try option --verbose first to get more information.
+In case of bugs:
+  Please, use option --debug for bug reports.
+END_OF_USAGE
+
+### process options
+my @OrgArgv = @ARGV;
+use Getopt::Long;
+GetOptions(
+  "help!",
+  "version!",
+  "debug!",
+  "verbose!",
+  "gscmd=s",
+  "pdftexcmd=s",
+  "xetexcmd=s",
+  "pdftex" => sub { $::opt_tex = 'pdftex'; },
+  "xetex"  => sub { $::opt_tex = 'xetex'; },
+  "margins=s",
+  "clip!",
+  "hires!",
+  "papersize=s",
+  "resolution=s",
+  "bbox=s",
+  "restricted" => sub { $restricted = 1; },
+) or die $usage;
+!$::opt_help or die $usage;
+
+if ($::opt_version) {
+    print "$version\n";
+    exit(0);
+}
+
+$::opt_verbose = 1 if $::opt_debug;
+
+@ARGV >= 1 or die $usage;
+
+print $title;
+
+if ($::opt_bbox) {
+    $::opt_bbox =~ s/^\s+//;
+    $::opt_bbox =~ s/\s+$//;
+    $::opt_bbox =~ s/\s+/ /;
+    if ($::opt_bbox =~ /^-?\d*\.?\d+ -?\d*\.?\d+ -?\d*\.?\d+ -?\d*\.?\d+$/) {
+        print "* Explicite Bounding Box: $::opt_bbox\n" if $::opt_debug;
+    }
+    else {
+        die "$Error Parse error (option --bbox \"$::opt_bbox\")!\n";
+    }
+}
+
+@ARGV <= 2 or die "$Error Too many files!\n";
+
+### input file
+$inputfile = shift @ARGV;
+
+if (! -f $inputfile) {
+    if (-f "$inputfile.pdf") {
+        $inputfile .= ".pdf";
+    }
+    else {
+        die "$Error Input file `$inputfile' not found!\n";
+    }
+}
+
+print "* Input file: $inputfile\n" if $::opt_debug;
+
+### output file
+if (@ARGV) {
+    $outputfile = shift @ARGV;
+}
+else {
+    $outputfile = $inputfile;
+    $outputfile =~ s/\.pdf$//i;
+    $outputfile .= "-crop.pdf";
+}
+
+print "* Output file: $outputfile\n" if $::opt_debug;
+
+if (($::opt_tex eq 'xetex') && $::opt_clip) {
+    die "$Error No clipping support for XeTeX!\n";
+}
+
+### margins
+my ($llx, $lly, $urx, $ury) = (0, 0, 0, 0);
+if ($::opt_margins =~
+        /^\s*([\-\.\d]+)\s+([\-\.\d]+)\s+([\-\.\d]+)\s+([\-\.\d]+)\s*$/) {
+    ($llx, $lly, $urx, $ury) = ($1, $2, $3, $4);
+}
+else {
+    if ($::opt_margins =~ /^\s*([\-\.\d]+)\s+([\-\.\d]+)\s*$/) {
+        ($llx, $lly, $urx, $ury) = ($1, $2, $1, $2);
+    }
+    else {
+        if ($::opt_margins =~ /^\s*([\-\.\d]+)\s*$/) {
+            ($llx, $lly, $urx, $ury) = ($1, $1, $1, $1);
+        }
+        else {
+            die "$Error Parse error (option --margins)!\n";
+        }
+    }
+}
+print "* Margins: $llx $lly $urx $ury\n" if $::opt_debug;
+
+### papersize validation (security)
+if ($::opt_papersize ne '') {
+    $::opt_papersize =~ /^[0-9A-Za-z]+$/
+            or die "$Error Invalid papersize ($::opt_papersize)!\n";
+    $papersizes{$::opt_papersize}
+            or die "$Error Unknown papersize ($::opt_papersize),"
+                   . " see ghostscript's documentation for option `-r'!\n";
+}
+
+### resolution validation (security)
+if ($::opt_resolution ne '') {
+    $::opt_resolution =~ /^\d+(x\d+)?$/
+            or die "$Error Invalid resolution ($::opt_resolution),"
+                   . " see ghostscript's documentation!\n";
+}
+
+### command name validation (security)
+my %cmd = (
+    'gscmd' => \$::opt_gscmd,
+    'pdftexcmd' => \$::opt_pdftexcmd,
+    'xetexcmd' => \$::opt_xetexcmd
+);
+foreach my $cmd (keys %cmd) {
+    my $val = ${$cmd{$cmd}};
+    next unless $val;
+    $val =~ s/^\s+//;
+    $val =~ s/\s+$//;
+    next unless $val;
+    if ($val =~ /`/) {
+        die "$Error Forbidden backtick for option `--$cmd' ($val)!\n";
+    }
+    if ($val =~ /\s/) {
+        die "$Error Forbidden whitespace for option `--$cmd' ($val)!\n";
+    }
+}
+if ($restricted) {
+    if ($::opt_pdftexcmd and $::opt_pdftexcmd ne 'pdftex') {
+        die "$Error pdfTeX program name must not be changed in restricted mode!\n";
+    }
+    if ($::opt_xetexcmd and $::opt_xetexcmd ne 'xetex') {
+        die "$Error XeTeX program name must not be changed in restricted mode!\n";
+    }
+    if ($::opt_gscmd) {
+        $::opt_gscmd =~ /^(gs|mgs|gswin32c|gs386|gsos2)$/
+        or $::opt_gscmd =~ /^gs[\-_]?(\d|\d[\.-_]?\d\d)c?$/
+        or die "$Error: Invalid Ghostscript program name in restricted mode!\n";
+    }
+}
+
+### cleanup system
+my @unlink_files = ();
+my $exit_code = 1;
+sub clean {
+    print "* Cleanup\n" if $::opt_debug;
+    if ($::opt_debug) {
+        print "* Temporary files: @unlink_files\n";
+    }
+    else {
+        for (; @unlink_files>0; ) {
+            unlink shift @unlink_files;
+        }
+    }
+}
+sub cleanup {
+    clean();
+    exit($exit_code);
+}
+$SIG{'INT'} = \&cleanup;
+$SIG{'__DIE__'} = \&clean;
+
+### Calculation of BoundingBoxes
+
+# use safe file name for use within cmd line of gs (unknown shell: space, ...)
+# and pdfTeX (dollar, ...)
+my $inputfilesafe = $inputfile;
+if ($inputfile =~ /[\s\$~'"]/) {
+    $inputfilesafe = "$tmp-img.pdf";
+    push @unlink_files, $inputfilesafe;
+    my $symlink_exists = eval { symlink("", ""); 1 };
+    print "* Input file name `$inputfile' contains special characters.\n"
+          . "* " . ($symlink_exists ? "Link" : "Copy")
+          . " input file to temporary file `$inputfilesafe'.\n"
+            if $::opt_verbose;
+    if ($symlink_exists) {
+        symlink($inputfile, $inputfilesafe)
+            or die "$Error Link from `$inputfile' to"
+                   . " `$inputfilesafe' failed: $!\n";
+    }
+    else {
+        use File::Copy;
+        copy($inputfile, $inputfilesafe)
+                or die "$Error Copy from `$inputfile' to"
+                       . " `$inputfilesafe' failed: $!\n";
+    }
+}
+
+my @gsargs = (
+    "-sDEVICE=bbox",
+    "-dBATCH",
+    "-dNOPAUSE"
+);
+push @gsargs, "-sPAPERSIZE=$::opt_papersize" if $::opt_papersize;
+push @gsargs, "-r$::opt_resolution" if $::opt_resolution;
+push @gsargs,
+    "-c",
+    "save",
+    "pop",
+    "-f",
+    $inputfilesafe
+;
+
+my $tmpfile = "$tmp.tex";
+push @unlink_files, $tmpfile;
+open(TMP, ">$tmpfile") or
+    die "$Error Cannot write tmp file `$tmpfile'!\n";
+print TMP "\\def\\pdffile{$inputfilesafe}\n";
+if ($::opt_tex eq 'pdftex') {
+    print TMP <<'END_TMP_HEAD';
+\csname pdfmapfile\endcsname{}
+\def\page #1 [#2 #3 #4 #5]{%
+  \count0=#1\relax
+  \setbox0=\hbox{%
+    \pdfximage page #1{\pdffile}%
+    \pdfrefximage\pdflastximage
+  }%
+  \pdfhorigin=-#2bp\relax
+  \pdfvorigin=#3bp\relax
+  \pdfpagewidth=#4bp\relax
+  \advance\pdfpagewidth by -#2bp\relax
+  \pdfpageheight=#5bp\relax
+  \advance\pdfpageheight by -#3bp\relax
+  \ht0=\pdfpageheight
+  \shipout\box0\relax
+}
+\def\pageclip #1 [#2 #3 #4 #5][#6 #7 #8 #9]{%
+  \count0=#1\relax
+  \dimen0=#4bp\relax \advance\dimen0 by -#2bp\relax
+  \edef\imagewidth{\the\dimen0}%
+  \dimen0=#5bp\relax \advance\dimen0 by -#3bp\relax
+  \edef\imageheight{\the\dimen0}%
+  \pdfximage page #1{\pdffile}%
+  \setbox0=\hbox{%
+    \kern -#2bp\relax
+    \lower #3bp\hbox{\pdfrefximage\pdflastximage}%
+  }%
+  \wd0=\imagewidth\relax
+  \ht0=\imageheight\relax
+  \dp0=0pt\relax
+  \pdfhorigin=#6pt\relax
+  \pdfvorigin=#7bp\relax
+  \pdfpagewidth=\imagewidth
+  \advance\pdfpagewidth by #6bp\relax
+  \advance\pdfpagewidth by #8bp\relax
+  \pdfpageheight=\imageheight\relax
+  \advance\pdfpageheight by #7bp\relax
+  \advance\pdfpageheight by #9bp\relax
+  \pdfxform0\relax
+  \shipout\hbox{\pdfrefxform\pdflastxform}%
+}%
+\def\pageinclude#1{%
+  \pdfhorigin=0pt\relax
+  \pdfvorigin=0pt\relax
+  \pdfximage page #1{\pdffile}%
+  \setbox0=\hbox{\pdfrefximage\pdflastximage}%
+  \pdfpagewidth=\wd0\relax
+  \pdfpageheight=\ht0\relax
+  \advance\pdfpageheight by \dp0\relax
+  \shipout\hbox{%
+    \raise\dp0\box0\relax
+  }%
+}
+END_TMP_HEAD
+}
+else { # XeTeX
+    print TMP <<'END_TMP_HEAD';
+\expandafter\ifx\csname XeTeXpdffile\endcsname\relax
+  \expandafter\ifx\csname pdffile\endcsname\relax
+    \errmessage{XeTeX not found!}%
+  \else
+    \errmessage{XeTeX is too old!}%
+  \fi
+\fi
+\def\page #1 [#2 #3 #4 #5]{%
+  \count0=#1\relax
+  \setbox0=\hbox{%
+    \XeTeXpdffile "\pdffile" page #1%
+  }%
+  \pdfpagewidth=#4bp\relax
+  \advance\pdfpagewidth by -#2bp\relax
+  \pdfpageheight=#5bp\relax
+  \advance\pdfpageheight by -#3bp\relax
+  \shipout\hbox{%
+    \kern-1in%
+    \kern-#2bp%
+    \vbox{%
+      \kern-1in%
+      \kern#3bp%
+      \ht0=\pdfpageheight
+      \box0 %
+    }%
+  }%
+}
+END_TMP_HEAD
+}
+
+print "* Running ghostscript for BoundingBox calculation ...\n"
+    if $::opt_verbose;
+print "* Ghostscript call: $::opt_gscmd @gsargs\n" if $::opt_debug;
+
+my @bbox;
+if ($::opt_bbox) {
+     $::opt_bbox =~ /([-\d\.]+) ([-\d\.]+) ([-\d\.]+) ([-\d\.]+)/;
+     @bbox = ($1, $2, $3, $4);
+}
+my $page = 0;
+my $gs_pipe = "$::opt_gscmd -dSAFER @gsargs 2>&1";
+$gs_pipe .= " 1>$null" unless $::opt_verbose;
+$gs_pipe .= "|";
+
+open(GS, $gs_pipe) or
+        die "$Error Cannot call ghostscript ($::opt_gscmd)!\n";
+my $bb = ($::opt_hires) ? "%%HiResBoundingBox" : "%%BoundingBox";
+while (<GS>) {
+    print $_ if $::opt_verbose;
+    next unless
+        /^$bb:\s*(-?[\.\d]+) (-?[\.\d]+) (-?[\.\d]+) (-?[\.\d]+)/o;
+    @bbox = ($1, $2, $3, $4) unless $::opt_bbox;
+    $page++;
+
+    my $empty = 0;
+    $empty = 1 if $bbox[0] >= $bbox[2];
+    $empty = 1 if $bbox[1] >= $bbox[3];
+    if ($empty) {
+        print <<"END_WARNING";
+
+!!! Warning: Empty Bounding Box is returned by Ghostscript!
+!!!   Page $page: @bbox
+!!! Either there is a problem with the page or with Ghostscript.
+!!! Recovery is tried by embedding the page in its original size.
+
+END_WARNING
+        print TMP "\\pageinclude{$page}\n";
+        next;
+    }
+
+    print "* Page $page: @bbox\n" if $::opt_verbose;
+
+    my @bb = ($bbox[0] - $llx, $bbox[1] - $ury,
+             $bbox[2] + $urx, $bbox[3] + $lly);
+
+    $empty = 0;
+    $empty = 1 if $bb[0] >= $bb[2];
+    $empty = 1 if $bb[1] >= $bb[3];
+    if ($empty) {
+        print <<"END_WARNING";
+
+!!! Warning: The final Bounding Box is empty!
+!!!   Page: $page: @bb
+!!! Probably caused by too large negative margin values.
+!!! Recovery by ignoring margin values.
+
+END_WARNING
+        print TMP "\\page $page [@bbox]\n";
+        # clipping shouldn't make a difference
+        next;
+    }
+    if ($::opt_clip) {
+        print TMP "\\pageclip $page [@bbox][$llx $lly $urx $ury]\n";
+    }
+    else {
+        print TMP "\\page $page [@bb]\n";
+    }
+}
+close(GS);
+
+if ($? & 127) {
+    die sprintf  "$Error Ghostscript died with signal %d!\n",
+                 ($? & 127);
+}
+elsif ($? != 0) {
+    die sprintf "$Error Ghostscript exited with error code %d!\n",
+                $? >> 8;
+}
+
+print TMP "\\csname \@\@end\\endcsname\n\\end\n";
+close(TMP);
+
+if ($page == 0) {
+    die "$Error Ghostscript does not report bounding boxes!\n";
+}
+
+### Run pdfTeX/XeTeX
+
+push @unlink_files, "$tmp.log";
+my $cmd;
+my $texname;
+if ($::opt_tex eq 'pdftex') {
+    $cmd = $::opt_pdftexcmd;
+    $texname = 'pdfTeX';
+}
+else {
+    $cmd = $::opt_xetexcmd;
+    $texname = 'XeTeX';
+}
+$cmd .= ' -no-shell-escape';
+if ($::opt_verbose) {
+    $cmd .= " -interaction=nonstopmode $tmp";
+}
+else {
+    $cmd .= " -interaction=batchmode $tmp";
+}
+print "* Running $texname ...\n" if $::opt_verbose;
+print "* $texname call: $cmd\n" if $::opt_debug;
+if ($::opt_verbose) {
+    system($cmd);
+}
+else {
+    `$cmd`;
+}
+if ($?) {
+    die "$Error $texname run failed!\n";
+}
+
+### Move temp file to output
+if (!rename("$tmp.pdf", $outputfile)) {
+    use File::Copy;
+    move "$tmp.pdf", $outputfile or
+            die "$Error Cannot move `$tmp.pdf' to `$outputfile'!\n";
+}
+
+print "==> $page page", (($page == 1) ? "" : "s"),
+      " written on `$outputfile'.\n";
+
+$exit_code = 0;
+cleanup();
+
+__END__
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/report.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/report.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/report.sh	(revision 18231)
@@ -0,0 +1,322 @@
+#!/bin/bash
+#generate html report from info.log output file
+
+#style
+#{{{
+TITLE_STYLE='width="700px" cellpadding="10"'
+TITLE_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-weight: bold; font-size:25px;" align="center"'
+SECTION_STYLE='width="700px" cellpadding="5"'
+SECTION_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-size:20px; font-weight: bold;" align="left"'
+TABLE_STYLE='width="680px" rules=none bgcolor="#ffffdd" border=1 bordercolor="#000000" cellpadding="3"'
+TABLE_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px; font-weight: normal;" align="left"'
+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;"'
+BODY_FONTC=$(echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:center; /g")
+BODY_FONTL=$(echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:left; /g")
+FOOTER_STYLE='width="700px"  cellpadding="10"'
+FOOTER_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="center"'
+#}}}
+
+#process info.log
+#{{{
+if [ ! -f info.log ]; then
+	echo "File info.log not found!" >&2   # Error message to stderr.
+	exit 1
+fi 
+NRNAME=$(      cat info.log | grep "name:"           | awk '{$1=""}1')
+TODAY=$(       cat info.log | grep "today"           | awk '{printf("%s %s",$2,$3);}')
+USER=$(        cat info.log | grep "user"            | awk '{print $2}')
+VERSION=$(     cat info.log | grep "version"         | awk '{print $2}')
+HOST_NAME=$(   cat info.log | grep "host"            | awk '{print $2}')
+OS=$(          cat info.log | grep "OS"              | awk '{print $2}')
+RELEASE=$(     cat info.log | grep "release"         | awk '{print $2}')
+EL_INSTALL=$(  cat info.log | grep "elapsed_install" | awk '{print $2}')
+EL_TOTAL=$(    cat info.log | grep "elapsed_total"   | awk '{print $2}')
+IS_MATLAB=$(   cat info.log | grep "is_matlab"       | awk '{print $2}')
+IS_PYTHON=$(   cat info.log | grep "is_python"       | awk '{print $2}')
+EL_MATLAB=$(   cat info.log | grep "elapsed_matlab"  | awk '{print $2}')
+EL_PYTHON=$(   cat info.log | grep "elapsed_python"  | awk '{print $2}')
+CRASH_MATLAB=$(cat info.log | grep "matlab_crash:"   | awk '{print $2}')
+CRASH_PYTHON=$(cat info.log | grep "python_crash:"   | awk '{print $2}')
+
+#Did installation work?
+if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 1 ]; then
+	IS_INSTALL=0
+else
+	IS_INSTALL=1
+fi
+#}}}
+
+#1. summary table 
+#{{{
+rm report.html
+cat << END >> report.html
+<div align="center">
+<table $TITLE_STYLE><tr><td $TITLE_FONT>$NRNAME</td></tr></table>
+
+<table $TABLE_STYLE>
+<tr> 
+<td $TABLE_FONT>host: $HOST_NAME ($OS)</td>
+<td $TABLE_FONT>date: $TODAY</td>
+</tr>
+<tr>
+<td $TABLE_FONT>user: $USER</td>
+<td $TABLE_FONT>release: $RELEASE</td>
+</tr>
+<tr>
+<td $TABLE_FONT>total elapsed time: $EL_TOTAL</td>
+<td $TABLE_FONT>installation elapsed time: $EL_INSTALL</td>
+</tr>
+<tr>
+<td $TABLE_FONT>svn version: $VERSION</td>
+<td $TABLE_FONT></td>
+</tr>
+</table>
+<br><hr width="700px">
+END
+# }}}
+
+#stop if did not install
+#{{{
+if [ $IS_INSTALL -eq 0 ]; then
+	cat << END >> report.html
+	<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+	<tr><td $BODY_FONTC>Status: <span style="color:#ff0000">Installation failed</span></td></tr>
+	</table>
+	<table $FOOTER_STYLE><tr><td $FOOTER_FONT><a href="http://issm.jpl.nasa.gov" title="ISSM website" target="_blank">ISSM</a> nightly run report</td></tr></table>
+	</div>
+END
+exit 0
+fi
+#}}}
+
+#2. matlab report
+if [ $IS_MATLAB -eq 1 ]; then
+#Process matlab_log.log {{{
+cat matlab_log.log        | egrep 'ERROR|SUCCESS|FAILURE' | grep -v "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > matlab.log
+cat matlab.log        | grep -v "SUCCESS" > matlab_short.log
+cat matlab_log.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
+NUM_MATLAB_TOT=$(wc -l matlab.log | awk '{print $1}')
+NUM_MATLAB_ERR=$(cat matlab.log | grep 'ERROR'   | grep -v "PETSC" | wc -l)
+NUM_MATLAB_SUC=$(cat matlab.log | grep 'SUCCESS' | wc -l)
+NUM_MATLAB_FAI=$(cat matlab.log | grep 'FAILURE' | wc -l)
+#}}}
+#write report {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Matlab tests</td></tr></table>
+<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+$(if [ $CRASH_MATLAB -eq 0 ]; then
+echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all tests have been run</span></td></tr>"
+else
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Matlab crashed</span></td></tr>"
+fi)
+<tr><td $BODY_FONTL>Total execution time: $EL_MATLAB</td></tr>
+<tr><td $BODY_FONTL>Number of successes: $NUM_MATLAB_SUC/$NUM_MATLAB_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of errors: $NUM_MATLAB_ERR/$NUM_MATLAB_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of failures: $NUM_MATLAB_FAI/$NUM_MATLAB_TOT</td></tr>
+</table>
+END
+#}}}
+fi
+
+#2. python report
+if [ $IS_PYTHON -eq 1 ]; then
+#Process python_log.log {{{
+cat python_log.log        | egrep 'ERROR|SUCCESS|FAILURE' | grep -v "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > python.log
+cat python.log        | grep -v "SUCCESS" > python_short.log
+cat python_log.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
+NUM_PYTHON_TOT=$(wc -l python.log | awk '{print $1}')
+NUM_PYTHON_ERR=$(cat python.log | grep 'ERROR'   | grep -v "PETSC" | wc -l)
+NUM_PYTHON_SUC=$(cat python.log | grep 'SUCCESS' | wc -l)
+NUM_PYTHON_FAI=$(cat python.log | grep 'FAILURE' | wc -l)
+#}}}
+#write report {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Python tests</td></tr></table>
+<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+$(if [ $CRASH_PYTHON -eq 0 ]; then
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all tests have been run</span></td></tr>"
+else
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Python crashed</span></td></tr>"
+fi)
+<tr><td $BODY_FONTL>Total execution time: $EL_PYTHON</td></tr>
+<tr><td $BODY_FONTL>Number of successes: $NUM_PYTHON_SUC/$NUM_PYTHON_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of errors: $NUM_PYTHON_ERR/$NUM_PYTHON_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of failures: $NUM_PYTHON_FAI/$NUM_PYTHON_TOT</td></tr>
+</table>
+END
+#}}}
+fi
+
+#3. Matlab and python tables
+if [ $IS_MATLAB -eq 1 ]; then
+#Matlab{{{
+#display table ONLY if installation worked and there has been at leat one FAILURE or ERROR
+if [ $IS_INSTALL -eq 1 ] && [ $NUM_MATLAB_TOT -gt 1 ] && [ $NUM_MATLAB_SUC -ne $NUM_MATLAB_TOT ]
+then
+	cat << END >> report.html
+<table $SECTION_STYLE><tr><td $(echo $SECTION_FONT)>List of Matlab tests</td></tr></table>
+<table $BODY_STYLE style="border-collapse:collapse;">
+<tr> 
+<th $BODY_FONT>Result</th> 
+<th $BODY_FONT>Tolerance</th> 
+<th $BODY_FONT>Test id</th>  
+<th $BODY_FONT>Test name</th> 
+<th $BODY_FONT>Field checked</th>
+</tr>
+$(cat matlab_short.log | while read line
+  do
+	  echo "<tr>"
+	  STATUS=`echo $line | awk '{print $1}'`
+	  #FAILURE
+	  if [ "$STATUS" = "FAILURE" ]
+	  then
+		  FONTC=$(echo "$BODY_FONTC bgcolor=#ffff00");
+		  FONTL=$(echo "$BODY_FONTL bgcolor=#ffff00");
+		  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+		  { printf("<td %s id=FAILURE>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTC,$3,FONTC,$6,FONTL,$9,FONTL,$11);}
+		  '; 
+	  else
+		  #SUCCESS
+		  if [ "$STATUS" = "SUCCESS" ]
+		  then
+			  FONTC=$(echo "$BODY_FONTC bgcolor=#ddffdd")
+			  FONTL=$(echo "$BODY_FONTL bgcolor=#ddffdd")
+			  #do not write anything
+		  #ERROR
+		  else
+			  FONTC=$(echo "$BODY_FONTC bgcolor=#ffdddd id=ERROR")
+			  FONTL=$(echo "$BODY_FONTL bgcolor=#ffdddd")
+			  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+			  { printf("<td %s>%s</td>\n<td %s>%s%s%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTL,$3,$4,$5,FONTC,$8,FONTL,$11,FONTL,$13);}
+			  '; 
+		  fi
+
+	  fi
+	  echo "</tr>"
+  done
+	  )
+</table>
+<br>
+END
+fi
+#}}}
+fi
+if [ $IS_PYTHON -eq 1 ]; then
+#python{{{
+#display table ONLY if installation worked and there has been at leat one FAILURE or ERROR
+if [ $IS_INSTALL -eq 1 ] && [ $NUM_PYTHON_TOT -gt 1 ] && [ $NUM_PYTHON_SUC -ne $NUM_PYTHON_TOT ]
+then
+	cat << END >> report.html
+	<table $(echo $SECTION_STYLE)><tr><td $(echo $SECTION_FONT)>List of Python tests</td></tr></table>
+	<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+	<tr> 
+	<th $BODY_FONT>Result</th> 
+	<th $BODY_FONT>Tolerance</th> 
+	<th $BODY_FONT>Test id</th>  
+	<th $BODY_FONT>Test name</th> 
+	<th $BODY_FONT>Field checked</th>
+	</tr>
+	$(cat python_short.log | while read line
+do
+	echo "<tr>"
+	STATUS=`echo $line | awk '{print $1}'`
+
+	#FAILURE
+	if [ "$STATUS" = "FAILURE" ]
+	then
+
+		FONTC=$(echo "$BODY_FONTC bgcolor=#ffff00");
+		FONTL=$(echo "$BODY_FONTL bgcolor=#ffff00");
+		echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+		{ printf("<td %s id=FAILURE>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTC,$3,FONTC,$6,FONTL,$9,FONTL,$11);}
+		'; 
+
+	else
+
+		#SUCCESS
+		if [ "$STATUS" = "SUCCESS" ]
+		then
+			FONTC=$(echo "$BODY_FONTC bgcolor=#ddffdd")
+			FONTL=$(echo "$BODY_FONTL bgcolor=#ddffdd")
+			#do not write anything
+			#ERROR
+		else
+			FONTC=$(echo "$BODY_FONTC bgcolor=#ffdddd id=ERROR")
+			FONTL=$(echo "$BODY_FONTL bgcolor=#ffdddd")
+			echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+			{ printf("<td %s>%s</td>\n<td %s>%s%s%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTL,$3,$4,$5,FONTC,$8,FONTL,$11,FONTL,$13);}
+			'; 
+		fi
+
+	fi
+	echo "</tr>"
+done
+)
+</table>
+<br>
+END
+fi
+#}}}
+fi
+
+#4. Error report
+if [ $IS_MATLAB -eq 1 ] && [ -s matlaberror.log ]; then
+#Matlab {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Matlab errors</td></tr></table>
+<table $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 matlaberror.log)</pre>
+</td></tr></table>
+END
+#}}}
+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 $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 petscerror.log)</pre>
+</td></tr></table>
+END
+#}}}
+fi
+
+#last: footer
+#{{{
+cat << END >> report.html
+<br>
+<table $FOOTER_STYLE><tr><td $FOOTER_FONT><a href="http://issm.jpl.nasa.gov" title="ISSM website" target="_blank">ISSM</a> nightly run report</td></tr></table>
+</div>
+END
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/svnlog
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/svnlog	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/svnlog	(revision 18231)
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+svn log $1 | perl -e 'print reverse<>'
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/svnvimdiff
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/svnvimdiff	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/svnvimdiff	(revision 18231)
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+#get files to check
+if [ $# -eq 0 ]
+then
+	echo "no file specified"
+	return
+fi
+
+#first, check that all files exist
+for FILE in $*
+do
+	if [ ! -f "$FILE" ]
+	then
+		echo "File $FILE not found!" >&2   # Error message to stderr.
+		exit 1
+	fi 
+done
+
+#svn diff all files
+for FILE in $*
+do
+
+	FILENAME=$(basename $FILE);
+	EXT=${FILENAME/*./}
+	RELEASE=$(svn info $FILE | grep "Revision" | awk '{ print $2 }')
+
+	YOUFILE="YOUR_FILE"."$EXT"
+	SVNFILE="SVN_FILE"."$EXT"
+
+	echo "Downloading current $FILENAME in svn repository"
+	mv $FILE $YOUFILE
+	svn update -q $FILE
+	mv $FILE $SVNFILE
+
+	vimdiff $YOUFILE $SVNFILE
+
+	echo "Reverting to local version of $FILENAME"
+	svn update -q -r$RELEASE $FILE
+	wait #wait till svn has downloaded the file otherwise it could be lost!
+	mv $YOUFILE $FILE
+	touch $FILE
+	rm $SVNFILE
+done
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/tai
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/tai	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/tai	(revision 18231)
@@ -0,0 +1,9 @@
+#!/bin/bash
+if [ -z $EXECUTION_DIR ];
+then
+	EXECUTION_DIR=$ISSM_DIR/execution
+fi
+
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
+echo "Execution directory: $DIR"
+tail -f $DIR/*.outlog
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/translateToPy.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/translateToPy.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/translateToPy.py	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/scripts/user_kill
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/user_kill	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/user_kill	(revision 18231)
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+#get jobs to be killed
+if [ $# -eq 0 ]
+then
+	echo "no job specified"
+	return
+fi
+
+#kill jobs
+for JOB in $*
+do
+
+	#if [[ "$HOSTNAME" != "metro.jpl.nasa.gov" ]]
+	#then
+	#	echo "cannot use user_kill for now"
+	#	exit
+	#fi
+
+	#if [[ $1 == "screen" ]]
+	#then
+	#	echo "cannot kill screen for now!"
+	#	exit 1
+	#fi
+
+
+
+	#if [[ $1 == "matlab" ]]
+	#then
+	#	echo "cannot kill matlab for now!"
+	#	exit 1
+	#fi
+
+	if [ "$JOB" = "konsole" ]; then
+		echo "cannot kill konsole for now!"
+		exit 1
+	fi
+
+	echo "killing $JOB"
+
+	for i in `ps aux | grep $JOB | grep -v grep | grep -v user_kill | awk '{printf("%s\n",$2);}'`; 
+	do 
+		kill -9 $i;
+	done;
+done
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/vie
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/vie	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/vie	(revision 18231)
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+if [ -z "$EXECUTION_DIR" ];
+then
+	EXECUTION_DIR="$ISSM_DIR/execution"
+fi
+
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
+vim $DIR/*.errlog
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/vil
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/vil	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/vil	(revision 18231)
@@ -0,0 +1,8 @@
+#!/bin/bash
+if [ -z $EXECUTION_DIR ];
+then
+	EXECUTION_DIR="$ISSM_DIR/execution"
+fi
+
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
+vim $DIR/*.outlog
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/wincron.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/wincron.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/wincron.sh	(revision 18231)
@@ -0,0 +1,5 @@
+#/bin/bash
+#Launch cron as a windows service, using cygrunsrv: 
+
+cygrunsrv --install cron --path /usr/sbin/cron --args -n
+net start cron
Index: /issm/branches/trunk-jpl-ad2-integrated/scripts/windowsbuild.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/scripts/windowsbuild.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/scripts/windowsbuild.sh	(revision 18231)
@@ -0,0 +1,21 @@
+#!/bin/bash
+#build windows archive of binaries.
+
+#Some local script functions 
+function today_date {
+suffix=`date | awk '{printf("%s-%s-%s",$2,$3,$6);}'` 
+echo $suffix;
+}
+
+#Create tar file, with today's date in the title;
+today=`today_date`
+
+cd $ISSM_DIR/bin
+
+#Filter out .svn files
+rm -rf list
+ls *.mexw32 | grep -v "\.svn" > list;
+
+tar zcvf ../issm-1.0-win-$today.tar.gz  `cat list`
+rm -rf list
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/Makefile.am	(revision 18231)
@@ -0,0 +1,2 @@
+EXTRA_DIST =  perl
+SUBDIRS = c m wrappers mobile
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation.sh	(revision 18231)
@@ -0,0 +1,9 @@
+#!/bin/bash
+#This is a quick validation test for new ADIC2 capability development
+#Just run it, it will fire up matlab, which will create a binary file
+#launch issm.exe using the binary file, post-process the output binary 
+#and compare it against an archive result.
+
+cd validation/Validation
+matlab -nojvm -r "addpath $ISSM_TIER/; startup;" < validation.m
+cd ..
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/Square.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/Square.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/Square.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/SquareShelfConstrained.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/SquareShelfConstrained.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/SquareShelfConstrained.par	(revision 18231)
@@ -0,0 +1,51 @@
+%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-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 
+load('SquareShelfConstrained.data','-mat');
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Surface mass balance and basal melting
+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.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Deal with boundary conditions:
+md=SetIceShelfBC(md);
+md.miscellaneous.name='validation';
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/update.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/update.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Update/update.m	(revision 18231)
@@ -0,0 +1,17 @@
+tolerance=1e-13;
+
+md=setmesh(model,'Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.cluster.executionpath=[issmtier() '/src/ad/validation/Validation/'];
+
+md.autodiff.isautodiff=true;
+md.autodiff.forward=true;
+md.verbose=verbose('solution',true);
+
+md=solve(md,MasstransportSolutionEnum);
+
+thickness=md.results.MasstransportSolution.Thickness;
+save ../Validation/Archive.mat thickness;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/Makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/Makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/Makefile	(revision 18231)
@@ -0,0 +1,2 @@
+clean:
+	rm validation.lock validation.outlog validationRose.outlog
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.m	(revision 18231)
@@ -0,0 +1,31 @@
+tolerance=1e-13;
+
+md=model;
+md.cluster=generic('name',oshostname(),'np',3);
+md.miscellaneous.name='validation';
+
+%run all scripts
+for i=1:2,
+
+	%run queuing script
+	if i==1,
+		disp('Checking src/ad/issm.exe ...');
+		!source validation.queue
+	elseif i==2,
+		disp('Checking src/ad/issmROSE.exe ...');
+		!source validationROSE.queue
+	end
+
+	%load solution and remove outbin
+	md=loadresultsfromdisk(md,'validation.outbin');
+	!rm validation.outbin
+
+	s=load('Archive.mat'); h0=s.thickness;
+	h=md.results.MasstransportSolution.Thickness;
+	error_diff=full(max(abs(h-h0))/(max(abs(h0))+eps));
+	if (error_diff>tolerance);
+		disp(sprintf(['\nERROR   difference: %-7.2g > %7.2g \n'],error_diff,tolerance));
+	else
+		disp(sprintf(['\nSUCCESS difference: %-7.2g < %7.2g \n'],error_diff,tolerance));
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.petsc
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.petsc	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.petsc	(revision 18231)
@@ -0,0 +1,17 @@
+%Petsc options file: validation.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/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.queue
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.queue	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validation.queue	(revision 18231)
@@ -0,0 +1,4 @@
+#!/bin/sh
+#mpiexec -np 3 $ISSM_TIER/bin/issm.exe PrognosticSolution ./ validation > validation.outlog
+echo "\n Running issm.exe"
+mpiexec -np 3 $ISSM_TIER/src/ad/issm.exe PrognosticSolution ./ validation > validation.outlog 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validationROSE.queue
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validationROSE.queue	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/ad/validation/Validation/validationROSE.queue	(revision 18231)
@@ -0,0 +1,4 @@
+#!/bin/sh
+#mpiexec -np 3 $ISSM_TIER/bin/issm.exe PrognosticSolution ./ validation > validation.outlog
+echo "\n Running issmRose.exe"
+mpiexec -np 3 $ISSM_TIER/src/ad/issmRose.exe PrognosticSolution ./ validation > validationRose.outlog 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/Makefile.am	(revision 18231)
@@ -0,0 +1,953 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@
+AUTOMAKE_OPTIONS = subdir-objects
+
+EXEEXT=$(ISSMEXT)
+
+#Library declaration {{{
+lib_LIBRARIES = libISSMCore.a libISSMOverload.a
+
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
+endif
+if WRAPPERS
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMModules.la
+endif
+lib_LIBRARIES += libISSMModules.a 
+endif
+#}}}
+
+#Core sources
+#Core sources{{{
+issm_sources = ./datastructures/DataSet.h\
+					./datastructures/DataSet.cpp\
+					./datastructures/Object.h\
+					./datastructures/datastructures.h\
+					./classes/classes.h\
+					./classes/gauss/Gauss.h\
+					./classes/gauss/GaussSeg.h\
+					./classes/gauss/GaussSeg.cpp\
+					./classes/gauss/GaussTria.h\
+					./classes/gauss/GaussTria.cpp\
+					./classes/gauss/GaussTetra.h\
+					./classes/gauss/GaussTetra.cpp\
+					./classes/gauss/GaussPenta.h\
+					./classes/gauss/GaussPenta.cpp\
+					./classes/Update.h\
+					./classes/FemModel.h\
+					./classes/FemModel.cpp\
+					./classes/Material.h\
+					./classes/Load.h\
+					./classes/Contour.h\
+					./classes/Loads/Friction.h\
+					./classes/Loads/Friction.cpp\
+					./classes/Inputs/TransientInput.h\
+					./classes/Inputs/TransientInput.cpp\
+					./classes/Constraints/SpcTransient.cpp\
+					./classes/Constraints/SpcTransient.h\
+					./classes/IndependentObject.h\
+					./classes/IndependentObject.cpp\
+					./classes/DependentObject.h\
+					./classes/DependentObject.cpp\
+					./classes/DofIndexing.h\
+					./classes/DofIndexing.cpp\
+					./classes/IoModel.h\
+					./classes/IoModel.cpp\
+					./classes/Contours.h\
+					./classes/Contours.cpp\
+					./classes/Nodes.h\
+					./classes/Nodes.cpp\
+					./classes/Vertices.h\
+					./classes/Vertices.cpp\
+					./classes/Node.h\
+					./classes/Node.cpp\
+					./classes/Segment.h\
+					./classes/Vertex.h\
+					./classes/Vertex.cpp\
+					./classes/Hook.h\
+					./classes/Hook.cpp\
+					./classes/ExternalResults/Results.h\
+					./classes/ExternalResults/Results.cpp\
+					./classes/ExternalResults/ExternalResult.h\
+					./classes/ExternalResults/GenericExternalResult.h\
+					./classes/Elements/Element.h\
+					./classes/Elements/Element.cpp\
+					./classes/Elements/Elements.h\
+					./classes/Elements/Elements.cpp\
+					./classes/Elements/ElementHook.h\
+					./classes/Elements/ElementHook.cpp\
+					./classes/Elements/Seg.h\
+					./classes/Elements/Seg.cpp\
+					./classes/Elements/SegRef.h\
+					./classes/Elements/SegRef.cpp\
+					./classes/Elements/Tria.h\
+					./classes/Elements/Tria.cpp\
+					./classes/Elements/TriaRef.h\
+					./classes/Elements/TriaRef.cpp\
+					./classes/Elements/Tetra.h\
+					./classes/Elements/Tetra.cpp\
+					./classes/Elements/TetraRef.h\
+					./classes/Elements/TetraRef.cpp\
+					./classes/Elements/Penta.h\
+					./classes/Elements/Penta.cpp\
+					./classes/Elements/PentaRef.h\
+					./classes/Elements/PentaRef.cpp\
+					./classes/Inputs/Inputs.h\
+					./classes/Inputs/Inputs.cpp\
+					./classes/Inputs/Input.h\
+					./classes/Inputs/InputLocal.h\
+					./classes/Inputs/SegInput.h\
+					./classes/Inputs/SegInput.cpp\
+					./classes/Inputs/TriaInput.h\
+					./classes/Inputs/TriaInput.cpp\
+					./classes/Inputs/BoolInput.h\
+					./classes/Inputs/BoolInput.cpp\
+					./classes/Inputs/IntInput.h\
+					./classes/Inputs/IntInput.cpp\
+					./classes/Inputs/DoubleInput.h\
+					./classes/Inputs/DoubleInput.cpp\
+					./classes/Inputs/DatasetInput.h\
+					./classes/Inputs/DatasetInput.cpp\
+					./classes/Materials/Materials.h\
+					./classes/Materials/Materials.cpp\
+					./classes/Materials/Matice.h\
+					./classes/Materials/Matice.cpp\
+					./classes/Materials/Matpar.h\
+					./classes/Materials/Matpar.cpp\
+					./classes/Constraints/Constraints.h\
+					./classes/Constraints/Constraints.cpp\
+					./classes/Constraints/Constraint.h\
+					./classes/Constraints/SpcStatic.cpp\
+					./classes/Constraints/SpcStatic.h\
+					./classes/Constraints/SpcDynamic.cpp\
+					./classes/Constraints/SpcDynamic.h\
+					./classes/Loads/Loads.h\
+					./classes/Loads/Loads.cpp\
+					./classes/Loads/Penpair.cpp\
+					./classes/Loads/Penpair.h\
+					./classes/Loads/Pengrid.cpp\
+					./classes/Loads/Pengrid.h\
+					./classes/Loads/Numericalflux.cpp\
+					./classes/Loads/Numericalflux.h\
+					./classes/matrix/matrixobjects.h\
+					./classes/matrix/ElementMatrix.h\
+					./classes/matrix/ElementMatrix.cpp\
+					./classes/matrix/ElementVector.h\
+					./classes/matrix/ElementVector.cpp\
+					./classes/Params/Parameters.h\
+					./classes/Params/Parameters.cpp\
+					./classes/Params/Param.h\
+					./classes/Params/GenericParam.h\
+					./classes/Params/BoolParam.cpp\
+					./classes/Params/BoolParam.h\
+					./classes/Params/IntParam.cpp\
+					./classes/Params/IntParam.h\
+					./classes/Params/IntVecParam.cpp\
+					./classes/Params/IntVecParam.h\
+					./classes/Params/IntMatParam.cpp\
+					./classes/Params/IntMatParam.h\
+					./classes/Params/DoubleParam.cpp\
+					./classes/Params/DoubleParam.h\
+					./classes/Params/FileParam.cpp\
+					./classes/Params/FileParam.h\
+					./classes/Params/StringArrayParam.cpp\
+					./classes/Params/StringArrayParam.h\
+					./classes/Params/DoubleMatParam.cpp\
+					./classes/Params/DoubleMatParam.h\
+					./classes/Params/DoubleTransientMatParam.cpp\
+					./classes/Params/DoubleTransientMatParam.h\
+					./classes/Params/DoubleMatArrayParam.cpp\
+					./classes/Params/DoubleMatArrayParam.h\
+					./classes/Params/DoubleVecParam.cpp\
+					./classes/Params/DoubleVecParam.h\
+					./classes/Params/StringParam.cpp\
+					./classes/Params/StringParam.h\
+					./classes/Params/MatrixParam.h\
+					./classes/Params/MatrixParam.cpp\
+					./classes/Params/VectorParam.h\
+					./classes/Params/VectorParam.cpp\
+					./classes/Params/TransientParam.h\
+					./classes/Params/TransientParam.cpp\
+					./classes/Params/DataSetParam.h\
+					./classes/Params/DataSetParam.cpp\
+					./classes/Profiler.h\
+					./classes/Profiler.cpp\
+					./shared/shared.h\
+					./shared/MemOps/MemOps.h\
+					./shared/MemOps/MemOps.cpp\
+					./shared/Matrix/matrix.h\
+					./shared/Matrix/MatrixUtils.cpp\
+					./shared/io/io.h\
+					./shared/io/Disk/diskio.h\
+					./shared/io/Disk/pfopen.cpp\
+					./shared/io/Disk/pfclose.cpp\
+					./shared/io/Disk/WriteLockFile.cpp\
+					./shared/io/Print/PrintfFunction.cpp\
+					./shared/io/Print/Print.h\
+					./shared/io/Comm/IssmComm.h\
+					./shared/io/Comm/IssmComm.cpp\
+					./shared/LatLong/Ll2xyx.cpp\
+					./shared/LatLong/Xy2llx.cpp\
+					./shared/FSanalyticals/fsanalyticals.h\
+					./shared/FSanalyticals/fsanalyticals.cpp\
+					./shared/Enum/Enum.h\
+					./shared/Enum/EnumDefinitions.h\
+					./shared/Enum/EnumToStringx.cpp\
+					./shared/Enum/StringToEnumx.cpp\
+					./shared/Numerics/numerics.h\
+					./shared/Numerics/types.h\
+					./shared/Numerics/constants.h\
+					./shared/Numerics/Verbosity.h\
+					./shared/Numerics/Verbosity.cpp\
+					./shared/Numerics/GaussPoints.h\
+					./shared/Numerics/GaussPoints.cpp\
+					./shared/Numerics/cross.cpp\
+					./shared/Numerics/isnan.h\
+					./shared/Numerics/isnan.cpp\
+					./shared/Numerics/cubic.cpp\
+					./shared/Numerics/NewtonSolveDnorm.cpp\
+					./shared/Numerics/extrema.cpp\
+					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
+					./shared/Numerics/OptPars.h\
+					./shared/Exceptions/exceptions.h\
+					./shared/Exceptions/Exceptions.cpp\
+					./shared/Sorting/binary_search.cpp\
+					./shared/Sorting/sorting.h\
+					./shared/Elements/elements.h\
+					./shared/Elements/Cuffey.cpp\
+					./shared/Elements/Paterson.cpp\
+					./shared/Elements/Arrhenius.cpp\
+					./shared/Elements/LliboutryDuval.cpp \
+					./shared/Elements/PrintArrays.cpp\
+					./shared/Elements/PddSurfaceMassBalance.cpp\
+					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
+					./shared/Elements/DrainageFunctionWaterfraction.cpp\
+					./shared/String/sharedstring.h\
+					./shared/String/DescriptorIndex.cpp\
+					./toolkits/metis/metisincludes.h\
+					./toolkits/issm/issmtoolkit.h\
+					./toolkits/issm/IssmToolkitUtils.h\
+					./toolkits/issm/IssmToolkitUtils.cpp\
+					./toolkits/issm/IssmAbsMat.h\
+					./toolkits/issm/IssmAbsVec.h\
+					./toolkits/issm/IssmDenseMat.h\
+					./toolkits/issm/IssmMat.h\
+					./toolkits/issm/IssmSeqVec.h\
+					./toolkits/issm/IssmVec.h\
+					./toolkits/issm/IssmSolver.h\
+					./toolkits/issm/IssmSolver.cpp\
+					./toolkits/issm/SparseRow.h\
+					./toolkits/issm/Bucket.h\
+					./toolkits/mpi/issmmpi.h\
+					./toolkits/mpi/issmmpi.cpp\
+					./toolkits/mpi/commops/commops.h\
+					./toolkits/mpi/commops/DetermineLocalSize.cpp\
+					./toolkits/mpi/commops/DetermineGlobalSize.cpp\
+					./toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp\
+					./toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp\
+					./toolkits/adolc/adolcincludes.h\
+					./toolkits/adolc/AdolcEdf.h\
+					./toolkits/ToolkitOptions.h\
+					./toolkits/ToolkitOptions.cpp\
+					./toolkits/triangle/triangleincludes.h\
+					./toolkits/objects/toolkitobjects.h\
+					./toolkits/objects/Matrix.h\
+					./toolkits/objects/Vector.h\
+					./toolkits/objects/Solver.h\
+					./toolkitsenums.h\
+					./toolkits.h\
+					./modules/ModelProcessorx/ModelProcessorx.h\
+					./modules/ModelProcessorx/ModelProcessorx.cpp\
+					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
+					./modules/ModelProcessorx/NodesPartitioning.cpp\
+					./modules/ModelProcessorx/EdgesPartitioning.cpp\
+					./modules/ModelProcessorx/FacesPartitioning.cpp\
+					./modules/ModelProcessorx/CreateParameters.cpp\
+					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
+					./modules/ModelProcessorx/CreateFaces.cpp\
+					./modules/ModelProcessorx/CreateEdges.cpp\
+					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ModelProcessorx/CreateNodes.cpp\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
+					./modules/NodesDofx/NodesDofx.h\
+					./modules/NodesDofx/NodesDofx.cpp\
+					./modules/NodalValuex/NodalValuex.h\
+					./modules/NodalValuex/NodalValuex.cpp\
+					./modules/VerticesDofx/VerticesDofx.h\
+					./modules/VerticesDofx/VerticesDofx.cpp\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.h\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp\
+					./modules/OutputResultsx/OutputResultsx.h\
+					./modules/OutputResultsx/OutputResultsx.cpp\
+					./modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.h\
+					./modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp\
+					./modules/InputDuplicatex/InputDuplicatex.h\
+					./modules/InputDuplicatex/InputDuplicatex.cpp\
+					./modules/InputExtrudex/InputExtrudex.h\
+					./modules/InputExtrudex/InputExtrudex.cpp\
+					./modules/InputScalex/InputScalex.h\
+					./modules/InputScalex/InputScalex.cpp\
+					./modules/SurfaceAreax/SurfaceAreax.h\
+					./modules/SurfaceAreax/SurfaceAreax.cpp\
+					./modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h\
+					./modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp\
+					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h\
+					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp\
+					./modules/SystemMatricesx/SystemMatricesx.h\
+					./modules/SystemMatricesx/SystemMatricesx.cpp\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.h\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp\
+					./modules/SetActiveNodesLSMx/SetActiveNodesLSMx.h\
+					./modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.h\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
+					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h\
+					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
+					./modules/SpcNodesx/SpcNodesx.h\
+					./modules/SpcNodesx/SpcNodesx.cpp\
+					./modules/SurfaceMassBalancex/SurfaceMassBalancex.h\
+					./modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.h\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
+					./modules/Reduceloadx/Reduceloadx.h\
+					./modules/Reduceloadx/Reduceloadx.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.h\
+					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
+					./modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h\
+					./modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp\
+					./modules/Solverx/Solverx.cpp\
+					./modules/Solverx/Solverx.h\
+					./modules/VecMergex/VecMergex.cpp\
+					./modules/VecMergex/VecMergex.h\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
+					./cores/ProcessArguments.cpp\
+					./cores/ResetBoundaryConditions.cpp\
+					./cores/AnalysisConfiguration.cpp\
+					./cores/WrapperCorePointerFromSolutionEnum.cpp\
+					./cores/CorePointerFromSolutionEnum.cpp\
+					./cores/ad_core.cpp\
+					./main/EnvironmentInit.cpp\
+					./main/EnvironmentFinalize.cpp\
+					./analyses/EnumToAnalysis.h\
+					./analyses/EnumToAnalysis.cpp\
+					./analyses/Analysis.h\
+					./solutionsequences/solutionsequence_la.cpp\
+					./solutionsequences/solutionsequence_la_theta.cpp\
+					./solutionsequences/solutionsequence_linear.cpp\
+					./solutionsequences/solutionsequence_nonlinear.cpp\
+					./solutionsequences/solutionsequence_newton.cpp\
+					./solutionsequences/convergence.cpp\
+					./classes/Options/Options.h\
+					./classes/Options/Options.cpp\
+					./classes/Options/Option.h\
+					./classes/Options/GenericOption.h\
+					./classes/Options/OptionUtilities.cpp\
+					./classes/Options/OptionUtilities.h\
+					./classes/RiftStruct.cpp\
+					./classes/RiftStruct.h\
+					./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
+					./cores/transient_core.cpp\
+					./cores/steadystate_core.cpp\
+					./cores/masstransport_core.cpp\
+					./cores/depthaverage_core.cpp\
+					./cores/extrudefrombase_core.cpp\
+					./cores/extrudefromtop_core.cpp\
+					./cores/thermal_core.cpp\
+					./solutionsequences/solutionsequence_thermal_nonlinear.cpp\
+					./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp\
+					./modules/ControlInputSetGradientx/ControlInputSetGradientx.h\
+					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp\
+					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h\
+					./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp\
+					./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h\
+					./modules/ModelProcessorx/Control/CreateParametersControl.cpp\
+					./modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp\
+					./modules/InputControlUpdatex/InputControlUpdatex.h\
+					./modules/InputControlUpdatex/InputControlUpdatex.cpp\
+					./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h\
+					./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp\
+					./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h\
+					./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp\
+					./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h\
+					./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp\
+					./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h\
+					./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp\
+					./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h\
+					./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp\
+					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
+					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
+					./modules/Gradjx/Gradjx.h\
+					./modules/Gradjx/Gradjx.cpp\
+					./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
+					./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
+					./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
+					./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
+					./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp\
+					./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h\
+					./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
+					./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
+					./classes/Inputs/ControlInput.h\
+					./classes/Inputs/ControlInput.cpp\
+					./shared/Numerics/BrentSearch.cpp\
+					./cores/control_core.cpp\
+					./cores/controltao_core.cpp\
+					./cores/controlm1qn3_core.cpp\
+					./cores/controlvalidation_core.cpp\
+					./cores/adjointstressbalance_core.cpp\
+					./cores/adjointbalancethickness_core.cpp\
+					./cores/adjointbalancethickness2_core.cpp\
+					./cores/AdjointCorePointerFromSolutionEnum.cpp\
+					./solutionsequences/solutionsequence_adjoint_linear.cpp\
+					./cores/hydrology_core.cpp\
+					./solutionsequences/solutionsequence_hydro_nonlinear.cpp\
+					./cores/stressbalance_core.cpp\
+					./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp\
+					./cores/balancethickness_core.cpp \
+					./cores/balancethickness2_core.cpp \
+					./cores/balancevelocity_core.cpp \
+					./cores/dummy_core.cpp\
+					./cores/surfaceslope_core.cpp\
+					./cores/bedslope_core.cpp\
+					./cores/meshdeformation_core.cpp\
+					./cores/damage_core.cpp\
+					./cores/levelsetfunctionslope_core.cpp\
+					./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
+					./classes/Loads/Riftfront.cpp\
+					./modules/ConstraintsStatex/RiftConstraintsState.cpp\
+					./classes/Massfluxatgate.h \
+					./classes/Misfit.h \
+					./modules/ModelProcessorx/CreateOutputDefinitions.cpp\
+					./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h\
+					./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp\
+					./classes/Inputs/PentaInput.h\
+					./classes/Inputs/PentaInput.cpp\
+					./classes/Inputs/TetraInput.h\
+					./classes/Inputs/TetraInput.cpp\
+					#}}}
+#DAKOTA sources  {{{
+if DAKOTA
+issm_sources +=  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
+					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
+					  ./modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp\
+					  ./cores/dakota_core.cpp\
+					  ./cores/DakotaSpawnCore.h\
+					  ./cores/DakotaSpawnCore.cpp
+endif
+#}}}
+#Petsc sources  {{{
+if PETSC
+issm_sources += ./toolkits/petsc\
+					./toolkits/petsc/patches\
+					./toolkits/petsc/patches/SolverEnum.h\
+					./toolkits/petsc/patches/petscpatches.h\
+					./toolkits/petsc/patches/VecToMPISerial.cpp\
+					./toolkits/petsc/patches/MatToSerial.cpp\
+					./toolkits/petsc/patches/VecMerge.cpp\
+					./toolkits/petsc/patches/NewVec.cpp\
+					./toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp\
+					./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp\
+					./toolkits/petsc/patches/NewMat.cpp\
+					./toolkits/petsc/patches/VecFree.cpp\
+					./toolkits/petsc/patches/KSPFree.cpp\
+					./toolkits/petsc/patches/MatFree.cpp\
+					./toolkits/petsc/patches/MatMultPatch.cpp\
+					./toolkits/petsc/patches/ISSMToPetscMatrixType.cpp\
+					./toolkits/petsc/patches/ISSMToPetscInsertMode.cpp\
+					./toolkits/petsc/patches/ISSMToPetscNormMode.cpp\
+					./toolkits/petsc/objects/petscobjects.h\
+					./toolkits/petsc/objects/PetscMat.h\
+					./toolkits/petsc/objects/PetscMat.cpp\
+					./toolkits/petsc/objects/PetscVec.h\
+					./toolkits/petsc/objects/PetscVec.cpp\
+					./toolkits/petsc/objects/PetscSolver.cpp\
+					./toolkits/petsc/objects/PetscSolver.h\
+					./toolkits/petsc/petscincludes.h
+endif
+#}}}
+#Mumps sources  {{{
+if MUMPS
+issm_sources += ./toolkits/mumps\
+					./toolkits/mumps/mumpsincludes.h\
+					./toolkits/mumps/MumpsSolve.cpp
+endif
+#}}}
+#Gsl sources  {{{
+if GSL
+issm_sources += ./toolkits/gsl\
+					./toolkits/gsl/gslincludes.h\
+					./toolkits/gsl/DenseGslSolve.cpp
+endif
+#}}}
+#Analyses{{{
+if ADJOINTBALANCETHICKNESS
+issm_sources += ./analyses/AdjointBalancethicknessAnalysis.cpp
+endif
+if ADJOINTBALANCETHICKNESS2
+issm_sources += ./analyses/AdjointBalancethickness2Analysis.cpp
+endif
+if ADJOINTHORIZ
+issm_sources += ./analyses/AdjointHorizAnalysis.cpp
+endif
+if BALANCETHICKNESS
+issm_sources += ./analyses/BalancethicknessAnalysis.cpp
+endif
+if BALANCETHICKNESS2
+issm_sources += ./analyses/Balancethickness2Analysis.cpp
+endif
+if BALANCETHICKNESSSOFT
+issm_sources += ./analyses/BalancethicknessSoftAnalysis.cpp
+endif
+if BALANCEVELOCITY
+issm_sources += ./analyses/BalancevelocityAnalysis.cpp
+endif
+if L2PROJECTIONBASE
+issm_sources += ./analyses/L2ProjectionBaseAnalysis.cpp
+endif
+if DAMAGEEVOLUTION
+issm_sources += ./analyses/DamageEvolutionAnalysis.cpp
+endif
+if STRESSBALANCE
+issm_sources += ./analyses/StressbalanceAnalysis.cpp
+endif
+if UZAWAPRESSURE
+issm_sources += ./analyses/UzawaPressureAnalysis.cpp
+endif
+if STRESSBALANCESIA
+issm_sources += ./analyses/StressbalanceSIAAnalysis.cpp
+endif
+if STRESSBALANCEVERTICAL
+issm_sources += ./analyses/StressbalanceVerticalAnalysis.cpp
+endif
+if ENTHALPY
+issm_sources += ./analyses/EnthalpyAnalysis.cpp
+endif
+if HYDROLOGYSHREVE
+issm_sources += ./analyses/HydrologyShreveAnalysis.cpp
+endif
+if HYDROLOGYDCINEFFICIENT
+issm_sources += ./analyses/HydrologyDCInefficientAnalysis.cpp
+endif
+if HYDROLOGYDCEFFICIENT
+issm_sources += ./analyses/HydrologyDCEfficientAnalysis.cpp
+endif
+if L2PROJECTIONEPL
+issm_sources += ./analyses/L2ProjectionEPLAnalysis.cpp
+endif
+if MELTING
+issm_sources += ./analyses/MeltingAnalysis.cpp
+endif
+if MASSTRANSPORT
+issm_sources += ./analyses/MasstransportAnalysis.cpp
+endif
+if FREESURFACEBASE
+issm_sources += ./analyses/FreeSurfaceBaseAnalysis.cpp
+endif
+if FREESURFACETOP
+issm_sources += ./analyses/FreeSurfaceTopAnalysis.cpp
+endif
+if EXTRUDEFROMBASE
+issm_sources += ./analyses/ExtrudeFromBaseAnalysis.cpp
+endif
+if EXTRUDEFROMTOP
+issm_sources += ./analyses/ExtrudeFromTopAnalysis.cpp
+endif
+if DEPTHAVERAGE
+issm_sources += ./analyses/DepthAverageAnalysis.cpp
+endif
+if THERMAL
+issm_sources += ./analyses/ThermalAnalysis.cpp
+endif
+if SMOOTHEDSURFACESLOPEX
+issm_sources += ./analyses/SmoothedSurfaceSlopeXAnalysis.cpp
+endif
+if SMOOTHEDSURFACESLOPEY
+issm_sources += ./analyses/SmoothedSurfaceSlopeYAnalysis.cpp
+endif
+if MESHDEFORMATION
+issm_sources += ./analyses/MeshdeformationAnalysis.cpp
+endif
+if LEVELSET
+issm_sources += ./analyses/LevelsetAnalysis.cpp
+endif
+if EXTRAPOLATION
+issm_sources += ./analyses/ExtrapolationAnalysis.cpp
+endif
+if LSFREINITIALIZATION
+issm_sources += ./analyses/LsfReinitializationAnalysis.cpp
+endif
+#}}}
+#Gia sources  {{{
+if GIA
+issm_sources +=  ./cores/gia_core.cpp\
+					./analyses/GiaAnalysis.cpp\
+					./modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp\
+					./modules/GiaDeflectionCorex/distme.f\
+					./modules/GiaDeflectionCorex/freed.f\
+					./modules/GiaDeflectionCorex/ojrule.f\
+					./modules/GiaDeflectionCorex/pwise.f\
+					./modules/GiaDeflectionCorex/qwise.f\
+					./modules/GiaDeflectionCorex/stot.f\
+					./modules/GiaDeflectionCorex/what0.f
+endif
+#}}}
+#Mpi sources  {{{
+if MPI
+issm_sources += ./toolkits/issm/IssmMpiDenseMat.h\
+					 ./toolkits/issm/IssmMpiVec.h
+endif
+#}}}
+#Metis sources  {{{
+if METIS
+issm_sources += ./toolkits/metis/patches/metispatches.h\
+					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
+endif
+#}}}
+
+#Wrapper sources
+#Bamg sources  {{{
+bamg_sources =  ./bamg/bamgobjects.h\
+					 ./bamg/BamgGeom.h\
+					 ./bamg/BamgGeom.cpp\
+					 ./bamg/BamgMesh.h\
+					 ./bamg/BamgMesh.cpp\
+					 ./bamg/BamgOpts.h\
+					 ./bamg/BamgOpts.cpp\
+					 ./bamg/CrackedEdge.h\
+					 ./bamg/CrackedEdge.cpp\
+					 ./bamg/Curve.h\
+					 ./bamg/Curve.cpp\
+					 ./bamg/Direction.h\
+					 ./bamg/Direction.cpp\
+					 ./bamg/DoubleAndInt.h\
+					 ./bamg/Edge.h\
+					 ./bamg/Edge.cpp\
+					 ./bamg/GeomEdge.h\
+					 ./bamg/GeomEdge.cpp\
+					 ./bamg/GeomSubDomain.h\
+					 ./bamg/GeomSubDomain.cpp\
+					 ./bamg/GeomVertex.h\
+					 ./bamg/GeomVertex.cpp\
+					 ./bamg/Geometry.cpp\
+					 ./bamg/Geometry.h\
+					 ./bamg/ListofIntersectionTriangles.cpp\
+					 ./bamg/ListofIntersectionTriangles.h\
+					 ./bamg/EigenMetric.cpp\
+					 ./bamg/Metric.cpp\
+					 ./bamg/Metric.h\
+					 ./bamg/BamgQuadtree.cpp\
+					 ./bamg/BamgQuadtree.h\
+					 ./bamg/R2.h\
+					 ./bamg/SetOfE4.cpp\
+					 ./bamg/SetOfE4.h\
+					 ./bamg/SubDomain.h\
+					 ./bamg/SubDomain.cpp\
+					 ./bamg/AdjacentTriangle.h\
+					 ./bamg/AdjacentTriangle.cpp\
+					 ./bamg/Triangle.cpp\
+					 ./bamg/det.h \
+					 ./bamg/Triangle.h\
+					 ./bamg/BamgVertex.cpp\
+					 ./bamg/BamgVertex.h\
+					 ./bamg/VertexOnEdge.h\
+					 ./bamg/VertexOnEdge.cpp\
+					 ./bamg/VertexOnGeom.h\
+					 ./bamg/VertexOnGeom.cpp\
+					 ./bamg/VertexOnVertex.h\
+					 ./bamg/VertexOnVertex.cpp\
+					 ./bamg/Mesh.cpp\
+					 ./bamg/Mesh.h\
+					 ./shared/Bamg/Abs.h \
+					 ./shared/Bamg/BigPrimeNumber.h\
+					 ./shared/Bamg/BigPrimeNumber.cpp\
+					 ./shared/Bamg/BinaryRand.h \
+					 ./shared/Bamg/Exchange.h \
+					 ./shared/Bamg/extrema.h \
+					 ./shared/Bamg/HeapSort.h \
+					 ./shared/Bamg/OppositeAngle.h \
+					 ./modules/Bamgx/Bamgx.cpp\
+					 ./modules/Bamgx/Bamgx.h\
+					 ./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
+					 ./modules/BamgConvertMeshx/BamgConvertMeshx.h\
+					 ./modules/BamgTriangulatex/BamgTriangulatex.cpp\
+					 ./modules/BamgTriangulatex/BamgTriangulatex.h
+#}}}
+#Kriging sources  {{{
+if KRIGING
+kriging_sources = ./classes/kriging/Observations.h\
+					./classes/kriging/Observations.cpp\
+					./classes/kriging/Variogram.h \
+					./classes/kriging/GaussianVariogram.h\
+					./classes/kriging/GaussianVariogram.cpp\
+					./classes/kriging/ExponentialVariogram.h\
+					./classes/kriging/ExponentialVariogram.cpp\
+					./classes/kriging/SphericalVariogram.h\
+					./classes/kriging/SphericalVariogram.cpp\
+					./classes/kriging/PowerVariogram.h\
+					./classes/kriging/PowerVariogram.cpp\
+					./classes/kriging/Quadtree.h\
+					./classes/kriging/Quadtree.cpp\
+					./classes/kriging/Observation.h\
+					./classes/kriging/Observation.cpp\
+					./modules/Krigingx/Krigingx.cpp\
+					./modules/Krigingx/Krigingx.h
+issm_sources +=$(kriging_sources)
+issm_sources +=./modules/Krigingx/pKrigingx.cpp
+endif
+#}}}
+#Kml sources  {{{
+kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.h\
+				  ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
+				  ./modules/Kml2Expx/Kml2Expx.h\
+				  ./modules/Kml2Expx/Kml2Expx.cpp\
+				  ./modules/Shp2Kmlx/Shp2Kmlx.h\
+				  ./modules/Shp2Kmlx/Shp2Kmlx.cpp\
+				  ./modules/KMLFileReadx/KMLFileReadx.h\
+				  ./modules/KMLFileReadx/KMLFileReadx.cpp\
+				  ./modules/KMLMeshWritex/KMLMeshWritex.h\
+				  ./modules/KMLMeshWritex/KMLMeshWritex.cpp\
+				  ./modules/KMLOverlayx/KMLOverlayx.h\
+				  ./modules/KMLOverlayx/KMLOverlayx.cpp\
+				  ./kml/kmlobjects.h\
+				  ./kml/KML_Attribute.cpp\
+				  ./kml/KML_Attribute.h\
+				  ./kml/KML_Comment.cpp\
+				  ./kml/KML_Comment.h\
+				  ./kml/KML_ColorStyle.cpp\
+				  ./kml/KML_ColorStyle.h\
+				  ./kml/KML_Container.cpp\
+				  ./kml/KML_Container.h\
+				  ./kml/KML_Document.cpp\
+				  ./kml/KML_Document.h\
+				  ./kml/KML_Feature.cpp\
+				  ./kml/KML_Feature.h\
+				  ./kml/KML_File.cpp\
+				  ./kml/KML_File.h\
+				  ./kml/KML_Folder.cpp\
+				  ./kml/KML_Folder.h\
+				  ./kml/KML_Geometry.cpp\
+				  ./kml/KML_Geometry.h\
+				  ./kml/KML_GroundOverlay.cpp\
+				  ./kml/KML_GroundOverlay.h\
+				  ./kml/KML_Icon.cpp\
+				  ./kml/KML_Icon.h\
+				  ./kml/KML_LatLonBox.cpp\
+				  ./kml/KML_LatLonBox.h\
+				  ./kml/KML_LinearRing.cpp\
+				  ./kml/KML_LinearRing.h\
+				  ./kml/KML_LineString.cpp\
+				  ./kml/KML_LineString.h\
+				  ./kml/KML_LineStyle.cpp\
+				  ./kml/KML_LineStyle.h\
+				  ./kml/KML_MultiGeometry.cpp\
+				  ./kml/KML_MultiGeometry.h\
+				  ./kml/KML_Object.cpp\
+				  ./kml/KML_Object.h\
+				  ./kml/KML_Overlay.cpp\
+				  ./kml/KML_Overlay.h\
+				  ./kml/KML_Point.cpp\
+				  ./kml/KML_Point.h\
+				  ./kml/KML_Placemark.cpp\
+				  ./kml/KML_Placemark.h\
+				  ./kml/KML_Polygon.cpp\
+				  ./kml/KML_Polygon.h\
+				  ./kml/KML_PolyStyle.cpp\
+				  ./kml/KML_PolyStyle.h\
+				  ./kml/KML_Style.cpp\
+				  ./kml/KML_Style.h\
+				  ./kml/KML_StyleSelector.cpp\
+				  ./kml/KML_StyleSelector.h\
+				  ./kml/KML_SubStyle.cpp\
+				  ./kml/KML_SubStyle.h\
+				  ./kml/KML_Unknown.cpp\
+				  ./kml/KML_Unknown.h\
+				  ./kml/KMLFileReadUtils.cpp\
+				  ./kml/KMLFileReadUtils.h
+#}}}
+#Modules sources{{{
+modules_sources= ./shared/Threads/issm_threads.h\
+			./shared/Threads/LaunchThread.cpp\
+			./shared/Threads/PartitionRange.cpp\
+			./shared/Exp/exp.h\
+			./shared/Exp/exp.cpp\
+			./shared/TriMesh/trimesh.h\
+			./shared/TriMesh/AssociateSegmentToElement.cpp\
+			./shared/TriMesh/GridInsideHole.cpp\
+			./shared/TriMesh/OrderSegments.cpp\
+			./shared/TriMesh/SplitMeshForRifts.cpp\
+			./shared/TriMesh/TriMeshUtils.cpp\
+			./modules/TriaSearchx/TriaSearchx.h\
+			./modules/TriaSearchx/TriaSearchx.cpp\
+			./modules/TriMeshx/TriMeshx.h\
+			./modules/TriMeshx/TriMeshx.cpp\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.h\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
+			./modules/ContourToMeshx/ContourToMeshx.cpp\
+			./modules/ContourToMeshx/ContourToMeshxt.cpp\
+			./modules/ContourToMeshx/ContourToMeshx.h\
+			./modules/ContourToNodesx/ContourToNodesx.cpp\
+			./modules/ContourToNodesx/ContourToNodesx.h\
+			./modules/NodeConnectivityx/NodeConnectivityx.cpp\
+			./modules/NodeConnectivityx/NodeConnectivityx.h\
+			./modules/ElementConnectivityx/ElementConnectivityx.cpp\
+			./modules/ElementConnectivityx/ElementConnectivityx.h\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
+if CHACO
+modules_sources+= ./modules/Chacox/Chacox.h\
+						./modules/Chacox/Chacox.cpp\
+						./modules/Chacox/input_parse.cpp\
+						./modules/Chacox/chaco_seconds.cpp\
+						./modules/Chacox/user_params.cpp
+endif
+if SCOTCH
+modules_sources+= ./modules/Scotchx/Scotchx.cpp\
+						./modules/Scotchx/Scotchx.h
+endif
+#}}}
+#}}}
+#Library flags and sources {{{
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  $(CXXFLAGS) $(CXXOPTFLAGS) 
+
+libISSMCore_a_SOURCES  = $(issm_sources)
+libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS) $(DAKOTAFLAGS)
+libISSMCore_a_FFLAGS = $(AM_FFLAGS)
+
+if SHAREDLIBS
+libISSM_la_SOURCES = main/issm.cpp
+libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
+
+libISSMCore_la_SOURCES  = $(issm_sources)
+libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(METEOIOLIB) $(SNOWPACKLIB) 
+libISSMCore_la_FFLAGS = $(AM_FFLAGS)
+endif
+
+if WRAPPERS
+libISSMModules_a_SOURCES = $(modules_sources)
+libISSMModules_a_SOURCES += $(bamg_sources)
+if KRIGING
+libISSMModules_a_SOURCES += $(kriging_sources)
+endif
+if KML
+libISSMModules_a_SOURCES += $(kml_sources)
+endif
+libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMModules_a_LIBADD = ./libISSMCore.a
+if SHAREDLIBS
+libISSMModules_la_SOURCES = $(libISSMModules_a_SOURCES)
+endif
+endif
+
+if VERSION
+AM_LDFLAGS =
+else
+AM_LDFLAGS = -avoid-version
+endif
+#}}}
+#Overload library, to overload any non-standard symbols. {{{
+libISSMOverload_a_SOURCES = ./shared/String/ApiPrintf.cpp
+
+libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
+#}}}
+
+#Executable {{{
+if ANDROID
+if ANDROIDEXE
+bin_PROGRAMS = issm 
+else
+bin_PROGRAMS = 
+endif
+else
+bin_PROGRAMS = issm 
+endif
+
+#Standard libraries
+LDADD = ./libISSMCore.a ./libISSMOverload.a
+
+#External packages
+LDADD += $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
+
+if FORTRAN
+LDADD += $(FLIBS) $(FORTRANLIB)
+endif
+
+issm_SOURCES = main/issm.h main/globals.h main/issm.cpp
+issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+
+if KRIGING
+bin_PROGRAMS += kriging
+kriging_SOURCES = main/issm.h main/globals.h main/kriging.cpp
+kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+endif
+#}}}
+#Automatic differentiation (must be done at the end) {{{
+if ADIC2 
+lib_LIBRARIES += libAD.a libISSMRose.a
+
+#ADIC2 library, for automatic differentiation 
+#libAD_a_SOURCES = ./mini1.ad.c
+libAD_a_SOURCES = 
+libAD_a_CFLAGS = -fPIC -D_C_ $(COPTFLAGS)
+
+#test rose preprocessing 
+%.r2cpp.cpp : %.cpp
+	testTranslator -rose:o $@ -rose:skipfinalCompileStep -DHAVE_CONFIG_H -D_C_ -I. -I../.. $(INCLUDES) $<
+libISSMRose_a_SOURCES = $(libISSMCore_a_SOURCES:.cpp=.r2cpp.cpp)
+libISSMRose_a_CXXFLAGS= -fPIC -D_C_ $(CXXOPTFLAGS)
+
+#Automatic differentiation rules: 
+%.ad.c: %.c
+	adic2 -mforward  $< --nary
+
+#Executable
+bin_PROGRAMS +=  issmRose.exe
+issmRose_exe_LDADD = ./libISSMRose.a $(LDADD)
+issmRose_exe_SOURCES = main/issm.cpp
+issmRose_exe_CXXFLAGS= -fPIC $(CXXOPTFLAGS) $(COPTFLAGS) 
+LDADD +=  $(ADIC2LIB) 
+
+endif #}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 18231)
@@ -0,0 +1,215 @@
+#include "./AdjointBalancethickness2Analysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processor*/
+int  AdjointBalancethickness2Analysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void AdjointBalancethickness2Analysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           AdjointBalancethickness2Analysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* AdjointBalancethickness2Analysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* AdjointBalancethickness2Analysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* AdjointBalancethickness2Analysis::CreateKMatrix(Element* element){/*{{{*/
+
+	Balancethickness2Analysis* analysis = new Balancethickness2Analysis();
+	ElementMatrix* Ke = analysis->CreateKMatrix(element);
+	delete analysis;
+
+	return Ke;
+}/*}}}*/
+ElementVector* AdjointBalancethickness2Analysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         num_responses,i;
+	IssmDouble  hobs,hu2,weight,NUMx,NUMy,DEN,Jdet;
+	IssmDouble  vx,vy,vbar2,nux,nuy,phi,dphi[2];
+	int        *responses = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe     = element->NewElementVector(SSAApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* thicknessobs_input = element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	Input* weights_input      = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* potential_input = element->GetInput(PotentialEnum);             _assert_(potential_input);
+	Input* vx_input        = element->GetInput(BalancethicknessVxObsEnum); _assert_(vx_input);
+	Input* vy_input        = element->GetInput(BalancethicknessVyObsEnum); _assert_(vy_input);
+	Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
+	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		nux_input->GetInputValue(&nux,gauss);
+		nuy_input->GetInputValue(&nuy,gauss);
+		potential_input->GetInputValue(&phi,gauss);
+		potential_input->GetInputDerivativeValue(&dphi[0],xyz_list,gauss);
+		thicknessobs_input->GetInputValue(&hobs,gauss);
+
+		vbar2 = (nux*nux*vx*vx + nuy*nuy*vy*vy);
+		hu2 = hobs*hobs*vbar2;
+
+		NUMx = 2.*dbasis[0]*dphi[0]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
+		NUMy = 2.*dbasis[1]*dphi[1]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
+		DEN = vbar2*vbar2+1.e-14;
+
+		/*Loop over all requested responses*/
+		for(int resp=0;resp<num_responses;resp++){
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case Balancethickness2MisfitEnum:
+					//for(i=0;i<numnodes;i++) pe->values[i]+=(NUMx+NUMy)/DEN *weight*Jdet*gauss->weight;
+					for(i=0;i<numnodes;i++) pe->values[i]+= phi*basis[i]*weight*Jdet*gauss->weight;
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void AdjointBalancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=BalancethicknessApparentMassbalanceEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case Balancethickness2MisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case BalancethicknessApparentMassbalanceEnum: GradientJAdot(element,gradient,control_index); break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+
+}/*}}}*/
+void AdjointBalancethickness2Analysis::GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble lambda; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* adjoint_input = element->GetInput(AdjointEnum);                            _assert_(adjoint_input);
+	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+		weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
+		adjoint_input->GetInputValue(&lambda,gauss);
+
+		/*Build gradient vector (actually -dJ/da): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+= - weight*Jdet*gauss->weight*basis[i]*lambda;
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void AdjointBalancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	element->InputUpdateFromSolutionOneDof(solution,AdjointEnum);
+}/*}}}*/
+void AdjointBalancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file AdjointBalancethickness2Analysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AdjointBalancethickness2Analysis_
+#define _AdjointBalancethickness2Analysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AdjointBalancethickness2Analysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 18231)
@@ -0,0 +1,335 @@
+#include "./AdjointBalancethicknessAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processor*/
+int  AdjointBalancethicknessAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           AdjointBalancethicknessAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* AdjointBalancethicknessAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* AdjointBalancethicknessAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* AdjointBalancethicknessAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	BalancethicknessAnalysis* analysis = new BalancethicknessAnalysis();
+	ElementMatrix* Ke = analysis->CreateKMatrix(element);
+	delete analysis;
+
+	/*Transpose and return Ke*/
+	Ke->Transpose();
+	return Ke;
+}/*}}}*/
+ElementVector* AdjointBalancethicknessAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	int         num_responses,i;
+	IssmDouble  dH[2];
+	IssmDouble  vx,vy,vel,Jdet;
+	IssmDouble  thickness,thicknessobs,weight;
+	int        *responses = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe     = basalelement->NewElementVector(SSAApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	basalelement->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* thickness_input    = basalelement->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* thicknessobs_input = basalelement->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	Input* weights_input      = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input           = basalelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input           = basalelement->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		/*Loop over all requested responses*/
+		for(int resp=0;resp<num_responses;resp++){
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case ThicknessAbsMisfitEnum:
+					for(i=0;i<numnodes;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case ThicknessAbsGradientEnum:
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[0]*dbasis[0*numnodes+i]*Jdet*gauss->weight;
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[1]*dbasis[1*numnodes+i]*Jdet*gauss->weight;
+					break;
+				case ThicknessAlongGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numnodes+i]*vx+dbasis[1*numnodes+i]*vy)*Jdet*gauss->weight;
+					break;
+				case ThicknessAcrossGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numnodes+i]*(-vy)+dbasis[1*numnodes+i]*vx)*Jdet*gauss->weight;
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete gauss;
+	return pe;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=VxEnum && 
+		control_type!=VyEnum && 
+		control_type!=BalancethicknessThickeningRateEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case ThicknessAbsMisfitEnum:      /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAbsGradientEnum:    /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAlongGradientEnum:  /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAcrossGradientEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case BalancethicknessThickeningRateEnum: GradientJDhDt(element,gradient,control_index); break;
+		case VxEnum:                             GradientJVx(  element,gradient,control_index); break;
+		case VyEnum:                             GradientJVy(  element,gradient,control_index); break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dvy): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	IssmDouble* lambda        = xNew<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	element->GetInputListOnVertices(lambda,AdjointEnum);
+	for(int i=0;i<numvertices;i++){
+		ge[i]=-lambda[i];
+		_assert_(!xIsNan<IssmDouble>(ge[i]));
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,INS_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(lambda);
+	xDelete<int>(vertexpidlist);
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,AdjointEnum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,AdjointEnum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*! \file AdjointBalancethicknessAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AdjointBalancethicknessAnalysis_
+#define _AdjointBalancethicknessAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AdjointBalancethicknessAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 18231)
@@ -0,0 +1,1660 @@
+#include "./AdjointHorizAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  AdjointHorizAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void AdjointHorizAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           AdjointHorizAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case SSAApproximationEnum: 
+			return CreateKMatrixSSA(element);
+		case HOApproximationEnum: 
+			return CreateKMatrixHO(element);
+		case FSApproximationEnum: 
+			return CreateKMatrixFS(element);
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixSSA(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	bool        incomplete_adjoint;
+	IssmDouble  Jdet,thickness,mu_prime;
+	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij;
+	IssmDouble  eps1[2],eps2[2],epsilon[3];
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Jacobian with regular SSA (first part of the Gateau derivative)*/
+	basalelement->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+	if(incomplete_adjoint){
+		if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+		return Ke;
+	}
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input        = basalelement->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);       _assert_(vy_input);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(2*numnodes);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		basalelement->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		basalelement->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2.*epsilon[0]+epsilon[1]; eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];               eps2[1]=epsilon[0]+2*epsilon[1];
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	basalelement->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixHO(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	bool        incomplete_adjoint;
+	IssmDouble  Jdet,mu_prime;
+	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij;
+	IssmDouble  eps1[3],eps2[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
+	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+	if(incomplete_adjoint) return Ke;
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(3*numnodes);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2.*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                 eps2[1]=epsilon[0]+2.*epsilon[1];
+		eps1[2]=epsilon[3];                 eps2[2]=epsilon[4];
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i]+eps1[2]*dbasis[2*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j]+eps1[2]*dbasis[2*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i]+eps2[2]*dbasis[2*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j]+eps2[2]*dbasis[2*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixFS(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	bool        incomplete_adjoint;
+	int         dim,epssize;
+	IssmDouble  Jdet,mu_prime;
+	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij,eps3dotdphii,eps3dotdphij;
+	IssmDouble  eps1[3],eps2[3],eps3[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Jacobian with regular FS (first part of the Gateau derivative)*/
+	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+	if(incomplete_adjoint) return Ke;
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum);_assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum);_assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){
+		vz_input = element->GetInput(VzEnum);
+	}
+	else{
+		_error_("Not implemented yet");
+	}
+
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(dim*vnumnodes);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(int i=0;i<vnumnodes;i++){
+			for(int j=0;j<vnumnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*vnumnodes+i]+eps1[1]*dbasis[1*vnumnodes+i]+eps1[2]*dbasis[2*vnumnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*vnumnodes+j]+eps1[1]*dbasis[1*vnumnodes+j]+eps1[2]*dbasis[2*vnumnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*vnumnodes+i]+eps2[1]*dbasis[1*vnumnodes+i]+eps2[2]*dbasis[2*vnumnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*vnumnodes+j]+eps2[1]*dbasis[1*vnumnodes+j]+eps2[2]*dbasis[2*vnumnodes+j];
+				eps3dotdphii=eps3[0]*dbasis[0*vnumnodes+i]+eps3[1]*dbasis[1*vnumnodes+i]+eps3[2]*dbasis[2*vnumnodes+i];
+				eps3dotdphij=eps3[0]*dbasis[0*vnumnodes+j]+eps3[1]*dbasis[1*vnumnodes+j]+eps3[2]*dbasis[2*vnumnodes+j];
+
+				Ke->values[numdof*(4*i+0)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(4*i+1)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(4*i+2)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,XYZEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case SSAApproximationEnum: 
+			return CreatePVectorSSA(element);
+		case HOApproximationEnum: 
+			return CreatePVectorHO(element);
+		case FSApproximationEnum: 
+			return CreatePVectorFS(element);
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreatePVectorFS(Element* element){/*{{{*/
+
+	/*Nothing to be done if not on surface*/
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int        num_responses,i,dim;
+	IssmDouble Jdet,obs_velocity_mag,velocity_mag;
+	IssmDouble vx,vy,vxobs,vyobs,dux,duy,weight;
+	IssmDouble scalex,scaley,scale,S;
+	int        *responses    = NULL;
+	IssmDouble *xyz_list_top = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe     = element->NewElementVector(FSApproximationEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list_top);
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input      = element->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
+	Input* vxobs_input   = element->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	IssmDouble epsvel  = 2.220446049250313e-16;
+	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
+
+	/*Get Surface if required by one response*/
+	for(int resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			element->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussTop(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Loop over all requested responses*/
+		for(int resp=0;resp<num_responses;resp++){
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for(i=0;i<vnumnodes;i++){
+						dux=vxobs-vx;
+						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						if(dim==3){
+							duy=vyobs-vy;
+							pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					for(i=0;i<vnumnodes;i++){
+						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+						dux=scalex*(vxobs-vx);
+						duy=scaley*(vyobs-vy);
+						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for(i=0;i<vnumnodes;i++){
+						if(dim==3){
+							velocity_mag    =sqrt(vx*vx+vy*vy)+epsvel;
+							obs_velocity_mag=sqrt(vxobs*vxobs+vyobs*vyobs)+epsvel;
+							scale=-8.*meanvel*meanvel/(velocity_mag*velocity_mag)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							duy=scale*vy;
+							pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+						else{
+							velocity_mag    =fabs(vx)+epsvel;
+							obs_velocity_mag=fabs(vxobs)+epsvel;
+							scale=-8.*meanvel*meanvel/(velocity_mag*velocity_mag)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					for(i=0;i<vnumnodes;i++){
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+						dux=scale*(vxobs-vx);
+						duy=scale*(vyobs-vy);
+						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					for(i=0;i<vnumnodes;i++){
+						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<int>(responses);
+	xDelete<IssmDouble>(xyz_list_top);
+	xDelete<IssmDouble>(vbasis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreatePVectorHO(Element* element){/*{{{*/
+
+	/*Nothing to be done if not on surface*/
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int        num_responses,i;
+	IssmDouble Jdet,obs_velocity_mag,velocity_mag;
+	IssmDouble vx,vy,vxobs,vyobs,dux,duy,weight;
+	IssmDouble scalex,scaley,scale,S;
+	int        *responses    = NULL;
+	IssmDouble *xyz_list_top = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe    = element->NewElementVector(HOApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list_top);
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input      = element->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
+	Input* vxobs_input   = element->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	IssmDouble epsvel  = 2.220446049250313e-16;
+	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
+
+	/*Get Surface if required by one response*/
+	for(int resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			element->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussTop(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
+		element->NodalFunctions(basis, gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Loop over all requested responses*/
+		for(int resp=0;resp<num_responses;resp++){
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for(i=0;i<numnodes;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					for(i=0;i<numnodes;i++){
+						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+						dux=scalex*(vxobs-vx);
+						duy=scaley*(vyobs-vy);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for(i=0;i<numnodes;i++){
+						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+						dux=scale*vx;
+						duy=scale*vy;
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					for(i=0;i<numnodes;i++){
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+						dux=scale*(vxobs-vx);
+						duy=scale*(vyobs-vy);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					for(i=0;i<numnodes;i++){
+						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+	xDelete<IssmDouble>(xyz_list_top);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+
+}/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreatePVectorSSA(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	int         num_responses,i;
+	IssmDouble  Jdet,obs_velocity_mag,velocity_mag;
+	IssmDouble  vx,vy,vxobs,vyobs,dux,duy,weight;
+	IssmDouble scalex,scaley,scale,S;
+	int        *responses = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe    = basalelement->NewElementVector(SSAApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	basalelement->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* weights_input = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input      = basalelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input      = basalelement->GetInput(VyEnum);                                 _assert_(vy_input);
+	Input* vxobs_input   = basalelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vyobs_input   = basalelement->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	IssmDouble epsvel  = 2.220446049250313e-16;
+	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
+
+	/*Get Surface if required by one response*/
+	for(int resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			basalelement->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis, gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Loop over all requested responses*/
+		for(int resp=0;resp<num_responses;resp++){
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for(i=0;i<numnodes;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					for(i=0;i<numnodes;i++){
+						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+						dux=scalex*(vxobs-vx);
+						duy=scaley*(vyobs-vy);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for(i=0;i<numnodes;i++){
+						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+						dux=scale*vx;
+						duy=scale*vy;
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					for(i=0;i<numnodes;i++){
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+						dux=scale*(vxobs-vx);
+						duy=scale*(vyobs-vy);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					for(i=0;i<numnodes;i++){
+						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	basalelement->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete gauss;
+	return pe;
+}/*}}}*/
+void AdjointHorizAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get Approximation*/
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=MaterialsRheologyBbarEnum && 
+		control_type!=FrictionCoefficientEnum   && 
+		control_type!=DamageDbarEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case SurfaceAbsVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceRelVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceLogVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceLogVxVyMisfitEnum:    /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceAverageVelMisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		case DragCoefficientAbsGradientEnum: GradientJDragGradient(element,gradient,control_index); break;
+		case RheologyBbarAbsGradientEnum:    GradientJBGradient(element,gradient,control_index);    break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case FrictionCoefficientEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJDragSSA(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJDragHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJDragFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		case MaterialsRheologyBbarEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJBbarSSA(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJBbarHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJBbarFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		case DamageDbarEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJDSSA(element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                 break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+                         
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating (gradient is 0)*/
+	if(element->IsFloating()) return;
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* dragcoefficient_input = basalelement->GetInput(FrictionCoefficientEnum);                _assert_(dragcoefficient_input);
+	Input* weights_input         = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradient vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(dim==2){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum);              _assert_(rheologyb_input);
+	Input* weights_input   = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		rheologyb_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(dim==2){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating (gradient is 0)*/
+	if(element->IsFloating()) return;
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(basalelement,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* dragcoeff_input = basalelement->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
+
+	/*Intermediaries*/
+	int        dim=3;
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list_base= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
+
+	/*Intermediaries*/
+	int        dim=3;
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk,normal[3];
+	IssmDouble vx,vy,vz,lambda,mu,xi;
+	IssmDouble *xyz_list_base= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* vz_input        = element->GetInput(VzEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* adjointz_input  = element->GetInput(AdjointzEnum);             _assert_(adjointz_input);
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		adjointz_input->GetInputValue(&xi    ,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+		element->NormalBase(&normal[0],xyz_list_base);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dk): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=(
+						-lambda*(2*drag*dalpha2dk*(vx - vz*normal[0]*normal[2]))
+						-mu    *(2*drag*dalpha2dk*(vy - vz*normal[1]*normal[2]))
+						-xi    *(2*drag*dalpha2dk*(-vx*normal[0]*normal[2]-vy*normal[1]*normal[2]))
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudB;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dB): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudB*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudD;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydDSSA(&dmudD,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudD*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+		InputUpdateFromSolutionFS(solution,element);
+	}
+	else{
+		InputUpdateFromSolutionHoriz(solution,element);
+	}
+}/*}}}*/
+void AdjointHorizAnalysis::InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element){/*{{{*/
+	int  i;
+	int* doflist=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*2;
+
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values  = xNew<IssmDouble>(numdof);
+	IssmDouble* lambdax = xNew<IssmDouble>(numnodes);
+	IssmDouble* lambday = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(&values[0],XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(AdjointxEnum,lambdax,element->GetElementType());
+	element->AddInput(AdjointyEnum,lambday,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(lambdax);
+	xDelete<IssmDouble>(lambday);
+	xDelete<int>(doflist);
+}/*}}}*/
+void AdjointHorizAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
+	int          i,dim;
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   FSreconditioning;
+
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*dim;
+	int pnumdof   = pnumnodes*1;
+
+	/*Initialize values*/
+	IssmDouble* values  = xNew<IssmDouble>(vnumdof+pnumdof);
+	IssmDouble* lambdax = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambday = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambdaz = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambdap = xNew<IssmDouble>(pnumnodes);
+
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Get dof list: */
+	element->GetDofListVelocity(&vdoflist,GsetEnum);
+	element->GetDofListPressure(&pdoflist,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<vnumdof;i++) values[i]        =solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) values[vnumdof+i]=solution[pdoflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(values,cs_list);
+
+	/*fill in all arrays: */
+	for(i=0;i<vnumnodes;i++){
+		lambdax[i] = values[i*NDOF3+0]; if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		lambday[i] = values[i*NDOF3+1]; if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+		lambdaz[i] = values[i*NDOF3+2]; if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+	}
+	for(i=0;i<pnumnodes;i++){
+		lambdap[i] = values[vnumdof+i]; if(xIsNan<IssmDouble>(lambdap[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<pnumnodes;i++) lambdap[i]=lambdap[i]*FSreconditioning;
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(AdjointxEnum,lambdax,element->VelocityInterpolation());
+	element->AddInput(AdjointyEnum,lambday,element->VelocityInterpolation());
+	element->AddInput(AdjointzEnum,lambdaz,element->VelocityInterpolation());
+	element->AddInput(AdjointpEnum,lambdap,element->PressureInterpolation());
+
+	/*Free ressources:*/
+	xDelete<int>(vdoflist);
+	xDelete<int>(pdoflist);
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(lambdap);
+	xDelete<IssmDouble>(lambdaz);
+	xDelete<IssmDouble>(lambday);
+	xDelete<IssmDouble>(lambdax);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void AdjointHorizAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/AdjointHorizAnalysis.h	(revision 18231)
@@ -0,0 +1,50 @@
+/*! \file AdjointHorizAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _AdjointHorizAnalysis_
+#define _AdjointHorizAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class AdjointHorizAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixSSA(Element* element);
+		ElementMatrix* CreateKMatrixHO(Element* element);
+		ElementMatrix* CreateKMatrixFS(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorSSA(Element* element);
+		ElementVector* CreatePVectorHO(Element* element);
+		ElementVector* CreatePVectorFS(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+		void InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element);
+		void InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Analysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Analysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Analysis.h	(revision 18231)
@@ -0,0 +1,46 @@
+/*!\file:  Analysis.h
+ * \brief abstract class for Analysis objects
+ */ 
+
+#ifndef _ANALYSIS_H_
+#define _ANALYSIS_H_
+
+#include "../toolkits/objects/toolkitobjects.h"
+class Parameters;
+class IoModel;
+class Elements;
+class Nodes;
+class Constraints;
+class Loads;
+class Element;
+class ElementVector;
+class ElementMatrix;
+class Gauss;
+class FemModel;
+
+class Analysis{
+
+	public: 
+		/*Constructor/Destructor*/
+		virtual      ~Analysis(){};
+
+		/*Model processing*/
+		virtual int  DofsPerNode(int** doflist,int domaintype,int approximation)=0;
+		virtual void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum)=0;
+		virtual void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void CreateNodes(Nodes* nodes,IoModel* iomodel)=0;
+		virtual void CreateConstraints(Constraints* constraints,IoModel* iomodel)=0;
+		virtual void CreateLoads(Loads* loads, IoModel* iomodel)=0;
+
+		/*Finite element Analysis*/
+		virtual void           Core(FemModel* femmodel)=0;
+		virtual ElementVector* CreateDVector(Element* element)=0;
+		virtual ElementMatrix* CreateJacobianMatrix(Element* element)=0;
+		virtual ElementMatrix* CreateKMatrix(Element* element)=0;
+		virtual ElementVector* CreatePVector(Element* element)=0;
+		virtual void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element)=0;
+		virtual void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index)=0;
+		virtual void InputUpdateFromSolution(IssmDouble* solution,Element* element)=0;
+		virtual void UpdateConstraints(FemModel* femmodel)=0;
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.cpp	(revision 18231)
@@ -0,0 +1,277 @@
+#include "./Balancethickness2Analysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  Balancethickness2Analysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void Balancethickness2Analysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void Balancethickness2Analysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Finite element type*/
+	int finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,BalancethicknessApparentMassbalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessNuxEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessNuyEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessVxObsEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessVyObsEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThicknessObsEnum);
+	iomodel->FetchDataToInput(elements,MeshVertexonboundaryEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+}/*}}}*/
+void Balancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	::CreateNodes(nodes,iomodel,Balancethickness2AnalysisEnum,finiteelement);
+}/*}}}*/
+void Balancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+
+	int finiteelement = P1Enum;
+	IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcpotentialEnum,Balancethickness2AnalysisEnum,finiteelement);
+
+}/*}}}*/
+void Balancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           Balancethickness2Analysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+ElementVector* Balancethickness2Analysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* Balancethickness2Analysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* Balancethickness2Analysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble Jdet,D_scalar;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* Balancethickness2Analysis::CreatePVector(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorVolume(element);
+	ElementVector* pe2=CreatePVectorBoundary(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* Balancethickness2Analysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  adot,Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* adot_input   = element->GetInput(BalancethicknessApparentMassbalanceEnum); _assert_(adot_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		adot_input->GetInputValue(&adot,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*adot*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* Balancethickness2Analysis::CreatePVectorBoundary(Element* element){/*{{{*/
+
+	/*If no front, return NULL*/
+	if(!element->IsFaceOnBoundary()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  Jdet,thickness,vx,vy;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble *xyz_list_front = NULL;
+	IssmDouble  normal[2];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* thickness_input = element->GetInput(BalancethicknessThicknessObsEnum); _assert_(thickness_input);
+	Input* vx_input        = element->GetInput(BalancethicknessVxObsEnum);        _assert_(vx_input);
+	Input* vy_input        = element->GetInput(BalancethicknessVyObsEnum);        _assert_(vy_input);
+
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	Gauss* gauss=element->NewGauss(xyz_list,xyz_list_front,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i] += Jdet*gauss->weight*thickness*(vx*normal[0] + vy*normal[1])*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void Balancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void Balancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void Balancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         Hinterpolation;
+	IssmDouble  vx,vy,vbar,nux,nuy,normdphi,dphi[2];
+	IssmDouble* xyz_list = NULL;
+	int       * doflist  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values         = xNew<IssmDouble>(numnodes);
+	IssmDouble* thickness_list = xNew<IssmDouble>(numvertices);
+	IssmDouble* vx_list        = xNew<IssmDouble>(numvertices);
+	IssmDouble* vy_list        = xNew<IssmDouble>(numvertices);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	element->AddInput(PotentialEnum,values,element->GetElementType());
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* potential_input = element->GetInput(PotentialEnum);             _assert_(potential_input);
+	Input* vx_input        = element->GetInput(BalancethicknessVxObsEnum); _assert_(vx_input);
+	Input* vy_input        = element->GetInput(BalancethicknessVyObsEnum); _assert_(vy_input);
+	Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
+	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
+
+	switch(element->GetElementType()){
+		case P1Enum: Hinterpolation = P0Enum; break;
+		default:     _error_("not implemented");
+	}
+
+	Gauss* gauss=element->NewGauss();
+	for (int iv=0;iv<1;iv++){
+		gauss->GaussNode(Hinterpolation,iv);//P0 Only for now
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		nux_input->GetInputValue(&nux,gauss);
+		nuy_input->GetInputValue(&nuy,gauss);
+		potential_input->GetInputDerivativeValue(&dphi[0],xyz_list,gauss);
+
+		vx = vx*nux; vy = vy*nuy;
+		vbar = sqrt(vx*vx + vy*vy) + 1.e-10;
+		normdphi = sqrt(dphi[0]*dphi[0] + dphi[1]*dphi[1]);
+
+		thickness_list[iv] = normdphi/vbar;
+		vx_list[iv]        = -1./thickness_list[iv] * dphi[0];
+		vy_list[iv]        = -1./thickness_list[iv] * dphi[1];
+	}
+	element->AddInput(ThicknessEnum,thickness_list,Hinterpolation);
+	element->AddInput(VxEnum,vx_list,Hinterpolation);
+	element->AddInput(VyEnum,vy_list,Hinterpolation);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(thickness_list);
+	xDelete<IssmDouble>(vx_list);
+	xDelete<IssmDouble>(vy_list);
+}/*}}}*/
+void Balancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/Balancethickness2Analysis.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file Balancethickness2Analysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _Balancethickness2Analysis_
+#define _Balancethickness2Analysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class Balancethickness2Analysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorVolume(Element* element);
+		ElementVector* CreatePVectorBoundary(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 18231)
@@ -0,0 +1,614 @@
+#include "./BalancethicknessAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancethicknessAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void BalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	parameters->AddObject(iomodel->CopyConstantObject(BalancethicknessStabilizationEnum));
+}/*}}}*/
+void BalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int    stabilization,finiteelement;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void BalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int  stabilization;
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void BalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int    stabilization;	
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Do not add constraints in DG*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum,P1Enum);
+	}
+
+}/*}}}*/
+void BalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int element;
+	int stabilization;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,BalancethicknessAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           BalancethicknessAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* BalancethicknessAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* BalancethicknessAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* BalancethicknessAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	ElementMatrix* Ke = NULL;
+	switch(element->FiniteElement()){
+		case P1Enum: case P2Enum:
+			Ke = CreateKMatrixCG(basalelement);
+			break;
+		case P1DGEnum:
+			Ke = CreateKMatrixDG(basalelement);
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(element->FiniteElement()) << " not supported yet");
+	}
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementMatrix* BalancethicknessAnalysis::CreateKMatrixCG(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int        stabilization;
+	int        domaintype;
+	IssmDouble Jdet,D_scalar,h;
+	IssmDouble vel,vx,vy,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&stabilization,BalancethicknessStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+	h = element->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		GetB(B,element,xyz_list,gauss);
+		GetBprime(Bprime,element,xyz_list,gauss);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vyaverage_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		D_scalar=gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==1){
+			/*Streamline upwinding*/
+			vel=sqrt(vx*vx+vy*vy);
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==2){
+			/*SSA*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementMatrix* BalancethicknessAnalysis::CreateKMatrixDG(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int        domaintype;
+	IssmDouble Jdet,D_scalar,vx,vy,dvxdx,dvydy,vel;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vyaverage_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		D_scalar=gauss->weight*Jdet;
+
+		/*WARNING: B and Bprime are inverted compared to CG*/
+		GetB(Bprime,element,xyz_list,gauss);
+		GetBprime(B,element,xyz_list,gauss);
+
+		D_scalar = - gauss->weight*Jdet;
+		D[0][0]  = D_scalar*vx;
+		D[0][1]  = 0.;
+		D[1][0]  = 0.;
+		D[1][1]  = D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* BalancethicknessAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	ElementVector* pe = NULL;
+	switch(element->FiniteElement()){
+		case P1Enum: case P2Enum:
+			pe = CreatePVectorCG(basalelement);
+			break;
+		case P1DGEnum:
+			pe = CreatePVectorDG(basalelement);
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(element->FiniteElement()) << " not supported yet");
+	}
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+ElementVector* BalancethicknessAnalysis::CreatePVectorCG(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  dhdt,mb,ms,Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);       _assert_(mb_input);
+	Input* ms_input   = element->GetInput(SurfaceforcingsMassBalanceEnum);     _assert_(ms_input);
+	Input* dhdt_input = element->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		dhdt_input->GetInputValue(&dhdt,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(ms-mb-dhdt)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* BalancethicknessAnalysis::CreatePVectorDG(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  dhdt,mb,ms,Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);       _assert_(mb_input);
+	Input* ms_input   = element->GetInput(SurfaceforcingsMassBalanceEnum);     _assert_(ms_input);
+	Input* dhdt_input = element->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		dhdt_input->GetInputValue(&dhdt,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(ms-mb-dhdt)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void BalancethicknessAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void BalancethicknessAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void BalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/* WARNING: this gradient is valid for Soft balance thickness only */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,thicknessobs,dH[3],dp[3];
+	IssmDouble  vx,vy,vel,dvx[2],dvy[2],dhdt,basal_melting,surface_mass_balance;
+	IssmDouble *xyz_list= NULL;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int  num_responses,resp,solution;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	element->FindParam(&solution,SolutionTypeEnum);
+	if(solution!=BalancethicknessSoftSolutionEnum) _error_("not implemented yet");
+	if(control_type!=ThicknessEnum)                _error_("Control "<<EnumToStringx(control_type)<<" not supported");
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input            = element->GetInput(ThicknessEnum);                           _assert_(thickness_input);
+	Input* thicknessobs_input         = element->GetInput(InversionThicknessObsEnum);               _assert_(thicknessobs_input);
+	Input* weights_input              = element->GetInput(InversionCostFunctionsCoefficientsEnum);  _assert_(weights_input);
+	Input* vx_input                   = element->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input                   = element->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* surface_mass_balance_input = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(surface_mass_balance_input);
+	Input* basal_melting_input        = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(basal_melting_input);
+	Input* dhdt_input                 = element->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+		element->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+
+		/*Deal with first part (partial derivative a J with respect to k)*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case ThicknessAbsMisfitEnum:
+					for(int i=0;i<numvertices;i++) ge[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case ThicknessAbsGradientEnum:
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*dH[0]*dbasis[0*numvertices+i]*Jdet*gauss->weight;
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*dH[1]*dbasis[1*numvertices+i]*Jdet*gauss->weight;
+					break;
+				case ThicknessAlongGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numvertices+i]*vx+dbasis[1*numvertices+i]*vy)*Jdet*gauss->weight;
+					break;
+				case ThicknessAcrossGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numvertices+i]*(-vy)+dbasis[1*numvertices+i]*vx)*Jdet*gauss->weight;
+					break;
+				case BalancethicknessMisfitEnum:
+					surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+					basal_melting_input->GetInputValue(&basal_melting,gauss);
+					dhdt_input->GetInputValue(&dhdt,gauss);
+					vx_input->GetInputValue(&vx,gauss);
+					vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+					for(int i=0;i<numvertices;i++){
+						ge[i]+= - weight*Jdet*gauss->weight*(
+							(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0*numvertices+i]+ vy*dbasis[1*numvertices+i] + basis[i]*(dvx[0]+dvy[1]))
+							-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0*numvertices+i]+ vy*dbasis[1*numvertices+i] + basis[i]*(dvx[0]+dvy[1]))
+							);
+					}
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	xDelete<int>(responses);
+	delete gauss;
+
+
+}/*}}}*/
+void BalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,ThicknessEnum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void BalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessAnalysis.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file BalancethicknessAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancethicknessAnalysis_
+#define _BalancethicknessAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancethicknessAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixCG(Element* element);
+		ElementMatrix* CreateKMatrixDG(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorCG(Element* element);
+		ElementVector* CreatePVectorDG(Element* element);
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+#include "./BalancethicknessSoftAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancethicknessSoftAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           BalancethicknessSoftAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* BalancethicknessSoftAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* BalancethicknessSoftAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* BalancethicknessSoftAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+ElementVector* BalancethicknessSoftAnalysis::CreatePVector(Element* element){/*{{{*/
+_error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void BalancethicknessSoftAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file BalancethicknessSoftAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancethicknessSoftAnalysis_
+#define _BalancethicknessSoftAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancethicknessSoftAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 18231)
@@ -0,0 +1,263 @@
+#include "./BalancevelocityAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  BalancevelocityAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void BalancevelocityAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void BalancevelocityAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void BalancevelocityAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Check in 3d*/
+	if(iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	::CreateNodes(nodes,iomodel,BalancevelocityAnalysisEnum,P1Enum);
+}/*}}}*/
+void BalancevelocityAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints for now*/
+	//IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancevelocityAnalysisEnum,P1Enum);
+}/*}}}*/
+void BalancevelocityAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           BalancevelocityAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* BalancevelocityAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* BalancevelocityAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* BalancevelocityAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  dhdt,mb,ms,Jdet;
+	IssmDouble  h,gamma,thickness;
+	IssmDouble  hnx,hny,dhnx[2],dhny[2];
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    HNx    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    HNy    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    H      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Nx     = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Ny     = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all Inputs and parameters: */
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* H_input = element->GetInput(ThicknessEnum); _assert_(H_input);
+	h = element->CharacteristicLength();
+
+	/*Get vector N for all nodes and build HNx and HNy*/
+	element->GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
+	element->GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	element->GetInputListOnNodes(H,ThicknessEnum);
+	for(int i=0;i<numnodes;i++){
+		IssmDouble norm=sqrt(Nx[i]*Nx[i]+Ny[i]*Ny[i]+1.e-10);
+		HNx[i] = -H[i]*Nx[i]/norm;
+		HNy[i] = -H[i]*Ny[i]/norm;
+	}
+
+	/*Start looping on the number of gaussian points:*/
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		H_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+		element->ValueP1DerivativesOnGauss(&dhnx[0],HNx,xyz_list,gauss);
+		element->ValueP1DerivativesOnGauss(&dhny[0],HNy,xyz_list,gauss);
+		element->ValueP1OnGauss(&hnx,HNx,gauss);
+		element->ValueP1OnGauss(&hny,HNy,gauss);
+
+		gamma=h/(2.*thickness+1.e-10);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							(basis[i]+gamma*(basis[i]*(dhnx[0]+dhny[1]) + dbasis[0*numnodes+i]*hnx + dbasis[1*numnodes+i]*hny))*
+							(basis[j]*(dhnx[0]+dhny[1])  + dbasis[0*numnodes+j]*hnx + dbasis[1*numnodes+j]*hny)
+							);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(H);
+	xDelete<IssmDouble>(Nx);
+	xDelete<IssmDouble>(Ny);
+	xDelete<IssmDouble>(HNx);
+	xDelete<IssmDouble>(HNy);
+	xDelete<IssmDouble>(B);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* BalancevelocityAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	IssmDouble dhdt,mb,ms,Jdet;
+	IssmDouble gamma,thickness;
+	IssmDouble hnx,hny,dhnx[2],dhny[2];
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(numnodes*2);
+	IssmDouble*    H      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Nx     = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Ny     = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	Input* ms_input   = basalelement->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(ms_input);
+	Input* mb_input   = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(mb_input);
+	Input* dhdt_input = basalelement->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
+	Input* H_input    = basalelement->GetInput(ThicknessEnum);                           _assert_(H_input);
+	IssmDouble h = basalelement->CharacteristicLength();
+
+	/*Get vector N for all nodes*/
+	basalelement->GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
+	basalelement->GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	basalelement->GetInputListOnNodes(H,ThicknessEnum);
+	for(int i=0;i<numnodes;i++){
+		IssmDouble norm=sqrt(Nx[i]*Nx[i]+Ny[i]*Ny[i]+1.e-10);
+		Nx[i] = -H[i]*Nx[i]/norm;
+		Ny[i] = -H[i]*Ny[i]/norm;
+	}
+
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->ValueP1DerivativesOnGauss(&dhnx[0],Nx,xyz_list,gauss);
+		element->ValueP1DerivativesOnGauss(&dhny[0],Ny,xyz_list,gauss);
+		element->ValueP1OnGauss(&hnx,Nx,gauss);
+		element->ValueP1OnGauss(&hny,Ny,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		dhdt_input->GetInputValue(&dhdt,gauss);
+		H_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		gamma=h/(2.*thickness+1.e-10);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i]+=Jdet*gauss->weight*(ms-mb-dhdt)*( basis[i] + gamma*(basis[i]*(dhnx[0]+dhny[1])+hnx*dbasis[0*numnodes+i] + hny*dbasis[1*numnodes+i]));
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(H);
+	xDelete<IssmDouble>(Nx);
+	xDelete<IssmDouble>(Ny);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void BalancevelocityAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void BalancevelocityAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void BalancevelocityAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,VelEnum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,VelEnum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void BalancevelocityAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/BalancevelocityAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file BalancevelocityAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _BalancevelocityAnalysis_
+#define _BalancevelocityAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class BalancevelocityAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 18231)
@@ -0,0 +1,606 @@
+#include "./DamageEvolutionAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  DamageEvolutionAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*Intermediaries*/
+	int         numoutputs;
+	char**      requestedoutputs = NULL;
+
+	/*retrieve some parameters: */
+	parameters->AddObject(iomodel->CopyConstantObject(DamageLawEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyLockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamagePenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxDamageEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageElementinterpEnum));
+
+	/*Requested outputs*/
+	iomodel->FetchData(&requestedoutputs,&numoutputs,DamageEvolutionRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(DamageEvolutionNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(DamageEvolutionRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,DamageEvolutionRequestedOutputsEnum);
+
+	/*Retrieve law dependent parameters: */
+	int law;
+	iomodel->Constant(&law,DamageLawEnum);
+	if (law>0){
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC1Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC2Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC3Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC4Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageStressThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageHealingEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageEquivStressEnum));
+	}
+
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int finiteelement;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	/*What input do I need to run my damage evolution model?*/
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchDataToInput(elements,VzEnum);
+	iomodel->FetchDataToInput(elements,DamageDEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(DamageDEnum, QmuDamageDEnum);
+	}
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
+	::CreateNodes(nodes,iomodel,DamageEvolutionAnalysisEnum,finiteelement);
+	iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	int finiteelement;
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+
+	IoModelToConstraintsx(constraints,iomodel,DamageSpcdamageEnum,DamageEvolutionAnalysisEnum,finiteelement);
+
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Nothing for now*/
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           DamageEvolutionAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* DamageEvolutionAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* DamageEvolutionAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* DamageEvolutionAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	Element*    basalelement;
+	int         domaintype,dim;
+	int         stabilization;
+	IssmDouble  Jdet,dt,D_scalar,h;
+	IssmDouble  vel,vx,vy,dvxdx,dvydy,dvx[2],dvy[2];
+	IssmDouble *xyz_list  = NULL;
+
+	/*Get problem dimension and basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim = 2;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			dim = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement->FindParam(&stabilization,DamageStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vxaverage_input=basalelement->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=basalelement->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		if(dim==1){
+			vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		}
+		if(dim==2){
+			vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+			vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+		}
+	}
+	h=basalelement->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		if(dim==2){
+			vyaverage_input->GetInputValue(&vy,gauss);
+			vyaverage_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		}
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetB(B,basalelement,dim,xyz_list,gauss);
+		GetBprime(Bprime,basalelement,dim,xyz_list,gauss);
+
+		dvxdx=dvx[0];
+		if(dim==2) dvydy=dvy[1];
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0*dim+0]=D_scalar*dvxdx;
+		if(dim==2) D[1*dim+1]=D_scalar*dvydy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					B,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0*dim+0]=D_scalar*vx;
+		if(dim==2) D[1*dim+1]=D_scalar*vy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			if(dim==1){
+				vel=fabs(vx)+1.e-8;
+				D[0]=h/(2.0*vel)*vx*vx;
+			}
+			else{
+				/*Streamline upwinding*/
+				vel=sqrt(vx*vx+vy*vy)+1.e-8;
+				D[0*dim+0]=h/(2.0*vel)*vx*vx;
+				D[1*dim+0]=h/(2.0*vel)*vy*vx;
+				D[0*dim+1]=h/(2.0*vel)*vx*vy;
+				D[1*dim+1]=h/(2.0*vel)*vy*vy;
+			}
+		}
+		else if(stabilization==1){
+			vxaverage_input->GetInputAverage(&vx);
+			if(dim==2) vyaverage_input->GetInputAverage(&vy);
+			D[0*dim+0]=h/2.0*fabs(vx);
+			if(dim==2) D[1*dim+1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			if(dim==1) D[0]=D_scalar*D[0];
+			else{
+				D[0*dim+0]=D_scalar*D[0*dim+0];
+				D[1*dim+0]=D_scalar*D[1*dim+0];
+				D[0*dim+1]=D_scalar*D[0*dim+1];
+				D[1*dim+1]=D_scalar*D[1*dim+1];
+			}
+
+			TripleMultiply(Bprime,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+		}
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* DamageEvolutionAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int      domaintype,damagelaw;
+	Element* basalelement;
+	IssmDouble  Jdet,dt;
+	IssmDouble  f,damage;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement->FindParam(&damagelaw,DamageLawEnum);
+	if(damagelaw==1 | damagelaw==2){
+		this->CreateDamageFInputPralong(basalelement);
+	}
+	else if(damagelaw==3){
+		this->CreateDamageFInputExp(basalelement);
+	}
+	Input* damaged_input = basalelement->GetInput(DamageDEnum); _assert_(damaged_input);
+	Input* damagef_input = basalelement->GetInput(DamageFEnum); _assert_(damagef_input);
+
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		damaged_input->GetInputValue(&damage,gauss);
+		damagef_input->GetInputValue(&f,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i]+=Jdet*gauss->weight*(damage+dt*f)*basis[i];
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete gauss;
+	return pe;
+}/*}}}*/
+void DamageEvolutionAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			B[numnodes*j+i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void DamageEvolutionAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void DamageEvolutionAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void DamageEvolutionAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void DamageEvolutionAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	IssmDouble  max_damage;
+	int			*doflist = NULL;
+	Element*   basalelement=NULL;
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){
+		if(!element->IsOnBase()) return;
+		basalelement=element->SpawnBasalElement();
+	}
+	else{
+		basalelement = element;
+	}
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* newdamage = xNew<IssmDouble>(numnodes);
+
+	/*Get user-supplied max_damage: */
+	basalelement->FindParam(&max_damage,DamageMaxDamageEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		newdamage[i]=solution[doflist[i]];
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(newdamage[i])) _error_("NaN found in solution vector");
+		/*Enforce D < max_damage and D > 0 */
+		if(newdamage[i]>max_damage) newdamage[i]=max_damage;
+		else if(newdamage[i]<0.)    newdamage[i]=0.;
+	}
+
+	/*Get all inputs and parameters*/
+	if(domaintype==Domain2DhorizontalEnum){
+		basalelement->AddInput(DamageDbarEnum,newdamage,element->GetElementType());
+	}
+	else{
+		basalelement->AddBasalInput(DamageDEnum,newdamage,element->GetElementType());
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(newdamage);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
+/*Intermediaries*/
+void DamageEvolutionAnalysis::CreateDamageFInputPralong(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble c1,c2,c3,healing,stress_threshold;
+	IssmDouble s_xx,s_xy,s_yy,s1,s2,stmp;
+	IssmDouble J2s,Chi,Psi,PosPsi,NegPsi;
+	IssmDouble damage,tau_xx,tau_xy,tau_yy;
+	int equivstress,domaintype,damagelaw;
+
+	/*Fetch number of vertices and allocate output*/
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* f   = xNew<IssmDouble>(numnodes);
+
+	/*retrieve parameters:*/
+	element->FindParam(&c1,DamageC1Enum);
+	element->FindParam(&c2,DamageC2Enum);
+	element->FindParam(&c3,DamageC3Enum);
+	element->FindParam(&healing,DamageHealingEnum);
+	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
+
+	/*Compute stress tensor: */
+	element->ComputeDeviatoricStressTensor();
+
+	/*retrieve what we need: */
+	Input* tau_xx_input  = element->GetInput(DeviatoricStressxxEnum);     _assert_(tau_xx_input);
+	Input* tau_xy_input  = element->GetInput(DeviatoricStressxyEnum);     _assert_(tau_xy_input);
+	Input* tau_yy_input  = element->GetInput(DeviatoricStressyyEnum);     _assert_(tau_yy_input);
+	Input* damage_input = NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		damage_input = element->GetInput(DamageDbarEnum); 	_assert_(damage_input);
+	}
+	else{
+		damage_input = element->GetInput(DamageDEnum);   _assert_(damage_input);
+	}
+
+	/*retrieve the desired type of equivalent stress*/
+	element->FindParam(&equivstress,DamageEquivStressEnum);
+
+	/*Calculate damage evolution source term: */
+	Gauss* gauss=element->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
+		
+		damage_input->GetInputValue(&damage,gauss);
+		tau_xx_input->GetInputValue(&tau_xx,gauss);
+		tau_xy_input->GetInputValue(&tau_xy,gauss);
+		tau_yy_input->GetInputValue(&tau_yy,gauss);
+	
+		/*Calculate effective stress components*/
+		s_xx=tau_xx/(1.-damage);
+		s_xy=tau_xy/(1.-damage);
+		s_yy=tau_yy/(1.-damage);
+
+		/*Calculate principal effective stresses*/
+		s1=(s_xx+s_yy)/2.+sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+		s2=(s_xx+s_yy)/2.-sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+		if(fabs(s2)>fabs(s1)){stmp=s2; s2=s1; s1=stmp;}
+
+		if(equivstress==0){ /* von Mises */
+			Chi=sqrt(s1*s1-s1*s2+s2*s2);
+		}
+		else if(equivstress==1){ /* max principal stress */
+			Chi=s1;
+		}
+		Psi=Chi-stress_threshold;
+		NegPsi=max(-Chi,0.); /* healing only for compressive stresses */
+
+		if(damagelaw==1){
+			PosPsi=max(Psi,0.);
+			f[i]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+		}
+		else if(damagelaw==2){
+			PosPsi=max(Psi,1.);
+			f[i]= c1*(pow(log10(PosPsi),c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+		}
+		else _error_("damage law not supported");
+	}
+
+	/*Add input*/
+	element->AddInput(DamageFEnum,f,element->GetElementType());
+	
+	/*Clean up and return*/
+	xDelete<IssmDouble>(f);
+	delete gauss;
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateDamageFInputExp(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble epsf,stress_threshold,eps0;
+	IssmDouble damage,B,n,epseff;
+	IssmDouble eps_xx,eps_yy,eps_xy,eps1,eps2,epstmp;
+	int domaintype,damagelaw;
+
+	/*Fetch number of vertices and allocate output*/
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* f   = xNew<IssmDouble>(numnodes);
+
+	/*retrieve parameters:*/
+	element->FindParam(&epsf,DamageC1Enum);
+	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
+
+	/*Compute stress tensor: */
+	element->ComputeDeviatoricStressTensor();
+
+	/*retrieve what we need: */
+	Input* eps_xx_input  = element->GetInput(StrainRatexxEnum);     _assert_(eps_xx_input);
+	Input* eps_xy_input  = element->GetInput(StrainRatexyEnum);     _assert_(eps_xy_input);
+	Input* eps_yy_input  = element->GetInput(StrainRateyyEnum);     _assert_(eps_yy_input);
+	Input*  n_input=element->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
+	Input* damage_input = NULL;
+	Input* B_input = NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		damage_input = element->GetInput(DamageDbarEnum); 	_assert_(damage_input);
+		B_input=element->GetInput(MaterialsRheologyBbarEnum); _assert_(B_input);
+	}
+	else{
+		damage_input = element->GetInput(DamageDEnum);   _assert_(damage_input);
+		B_input=element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+	}
+
+	/*Calculate damage evolution source term: */
+	Gauss* gauss=element->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
+		
+		eps_xx_input->GetInputValue(&eps_xx,gauss);
+		eps_xy_input->GetInputValue(&eps_xy,gauss);
+		eps_yy_input->GetInputValue(&eps_yy,gauss);
+		B_input->GetInputValue(&B,gauss);
+		n_input->GetInputValue(&n,gauss);
+		damage_input->GetInputValue(&damage,gauss);
+	
+		/*Calculate principal effective strain rates*/
+		eps1=(eps_xx+eps_yy)/2.+sqrt(pow((eps_xx-eps_yy)/2.,2)+pow(eps_xy,2));
+		eps2=(eps_xx+eps_yy)/2.-sqrt(pow((eps_xx-eps_yy)/2.,2)+pow(eps_xy,2));
+		if(fabs(eps2)>fabs(eps1)){epstmp=eps2; eps2=eps1; eps1=epstmp;}
+
+		/*Calculate effective strain rate and threshold strain rate*/
+		epseff=1./sqrt(2.)*sqrt(eps1*eps1-eps1*eps2+eps2*eps2);
+		eps0=pow(stress_threshold/B,n);
+
+		if(epseff>eps0){
+			f[i]=1.-pow(eps0/epseff,1./n)*exp(-(epseff-eps0)/(epsf-eps0))-damage;
+		}
+		else f[i]=0;
+	}
+
+	/*Add input*/
+	element->AddInput(DamageFEnum,f,element->GetElementType());
+	
+	/*Clean up and return*/
+	xDelete<IssmDouble>(f);
+	delete gauss;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DamageEvolutionAnalysis.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file DamageEvolutionAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _DamageEvolutionAnalysis_
+#define _DamageEvolutionAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class DamageEvolutionAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*Intermediaries*/
+		void CreateDamageFInputPralong(Element* element);
+		void CreateDamageFInputExp(Element* element);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.cpp	(revision 18231)
@@ -0,0 +1,174 @@
+#include "./DepthAverageAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  DepthAverageAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void DepthAverageAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void DepthAverageAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+	}
+}/*}}}*/
+void DepthAverageAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,DepthAverageAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void DepthAverageAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void DepthAverageAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           DepthAverageAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* DepthAverageAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* DepthAverageAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* DepthAverageAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,dt=1.e+9;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		GetB(B,element,dim,xyz_list,gauss);
+		D=gauss->weight*Jdet*dt;
+
+		/*vertical diffusion*/
+		TripleMultiply(B,1,numnodes,1,
+					&D,1,1,0,
+					B,1,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Next value*/
+		D=gauss->weight*Jdet;
+		element->NodalFunctions(B,gauss);
+		TripleMultiply(B,numnodes,1,0,
+					&D,1,1,0,
+					B,1,numnodes,0,
+					&Ke->values[0],1);
+	} 
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* DepthAverageAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         input_enum;
+	IssmDouble  Jdet,scalar,value;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe     = element->NewElementVector();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&input_enum,InputToDepthaverageEnum);
+	Input* input = element->GetInput(input_enum); _assert_(input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		/* Build transient now */
+		input->GetInputValue(&value, gauss);
+		scalar=value*Jdet*gauss->weight;
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void DepthAverageAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[(dim-1)*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+void DepthAverageAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void DepthAverageAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void DepthAverageAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int inputenum;
+	element->FindParam(&inputenum,InputToDepthaverageEnum);
+	element->InputUpdateFromSolutionOneDof(solution,inputenum);
+}/*}}}*/
+void DepthAverageAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/DepthAverageAnalysis.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file DepthAverageAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _DepthAverageAnalysis_
+#define _DepthAverageAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class DepthAverageAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.cpp	(revision 18231)
@@ -0,0 +1,1317 @@
+#include "./EnthalpyAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  EnthalpyAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void EnthalpyAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
+}/*}}}*/
+void EnthalpyAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool dakota_analysis,islevelset,isenthalpy;
+	int frictionlaw;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Is enthalpy requested?*/
+	iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+	if(!isenthalpy) return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	iomodel->FetchDataToInput(elements,TemperatureEnum);
+	iomodel->FetchDataToInput(elements,WaterfractionEnum);
+	iomodel->FetchDataToInput(elements,EnthalpyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	InputUpdateFromConstantx(elements,0.,VxMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(BasalforcingsGroundediceMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
+	}
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum); // required for updating active nodes
+	}
+	
+	/*Friction law variables*/
+	switch(frictionlaw){
+		case 1:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			break;
+		case 2:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+	/*Free data: */
+	iomodel->DeleteData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
+}/*}}}*/
+void EnthalpyAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,EnthalpyAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void EnthalpyAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        count;
+	int        M,N;
+	bool       spcpresent = false;
+	IssmDouble heatcapacity;
+	IssmDouble referencetemperature;
+
+	/*Output*/
+	IssmDouble *spcvector  = NULL;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+
+	/*return if 2d mesh*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(&spcvector,&M,&N,ThermalSpctemperatureEnum);
+
+	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
+	/*Transient or static?:*/
+	if(M==iomodel->numberofvertices){
+		/*static: just create Constraints objects*/
+		count=0;
+
+		for(int i=0;i<iomodel->numberofvertices;i++){
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				if (!xIsNan<IssmDouble>(spcvector[i])){
+
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,heatcapacity*(spcvector[i]-referencetemperature),EnthalpyAnalysisEnum));
+					count++;
+
+				}
+			}
+		}
+	}
+	else if (M==(iomodel->numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+		count=0;
+
+		/*figure out times: */
+		times=xNew<IssmDouble>(N);
+		for(int j=0;j<N;j++){
+			times[j]=spcvector[(M-1)*N+j];
+		}
+
+		/*Create constraints from x,y,z: */
+		for(int i=0;i<iomodel->numberofvertices;i++){
+
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				/*figure out times and values: */
+				values=xNew<IssmDouble>(N);
+				spcpresent=false;
+				for(int j=0;j<N;j++){
+					values[j]=heatcapacity*(spcvector[i*N+j]-referencetemperature);
+					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+				}
+
+				if(spcpresent){
+					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,N,times,values,EnthalpyAnalysisEnum));
+					count++;
+				}
+				xDelete<IssmDouble>(values);
+			}
+		}
+	}
+	else{
+		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+	}
+
+	/*Free ressources:*/
+	iomodel->DeleteData(spcvector,ThermalSpctemperatureEnum);
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void EnthalpyAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads */
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void EnthalpyAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* EnthalpyAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* EnthalpyAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* EnthalpyAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixShelf(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* EnthalpyAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         stabilization;
+	IssmDouble  Jdet,dt,u,v,w,um,vm,wm,vel;
+	IssmDouble  h,hx,hy,hz,vx,vy,vz;
+	IssmDouble  tau_parameter,diameter;
+	IssmDouble  D_scalar;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke       = element->NewElementMatrix();
+	IssmDouble*    basis    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis   = xNew<IssmDouble>(3*numnodes);
+	IssmDouble*    B        = xNew<IssmDouble>(3*numnodes);
+	IssmDouble*    Bprime   = xNew<IssmDouble>(3*numnodes);
+	IssmDouble     D[3][3]  = {0.};
+	IssmDouble     K[3][3];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,ThermalStabilizationEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+	Input* vx_input  = element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input  = element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input  = element->GetInput(VzEnum);     _assert_(vz_input);
+	Input* vxm_input = element->GetInput(VxMeshEnum); _assert_(vxm_input);
+	Input* vym_input = element->GetInput(VyMeshEnum); _assert_(vym_input);
+	Input* vzm_input = element->GetInput(VzMeshEnum); _assert_(vzm_input);
+	if(stabilization==2) diameter=element->MinEdgeLength(xyz_list);
+
+	/*Enthalpy diffusion parameter*/
+	IssmDouble kappa=this->EnthalpyDiffusionParameterVolume(element,EnthalpyPicardEnum); _assert_(kappa>=0.);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		D_scalar=gauss->weight*Jdet;
+		if(dt!=0.) D_scalar=D_scalar*dt;
+
+		/*Conduction: */
+		GetBConduct(B,element,xyz_list,gauss); 
+		D[0][0]=D_scalar*kappa/rho_ice;
+		D[1][1]=D_scalar*kappa/rho_ice;
+		D[2][2]=D_scalar*kappa/rho_ice;
+		TripleMultiply(B,3,numnodes,1,
+					&D[0][0],3,3,0,
+					B,3,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+		GetBAdvec(B,element,xyz_list,gauss); 
+		GetBAdvecprime(Bprime,element,xyz_list,gauss); 
+		vx_input->GetInputValue(&u,gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v,gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w,gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		D[2][2]=D_scalar*vz;
+		TripleMultiply(B,3,numnodes,1,
+					&D[0][0],3,3,0,
+					Bprime,3,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(dt!=0.){
+			D_scalar=gauss->weight*Jdet;
+			element->NodalFunctions(basis,gauss);
+			TripleMultiply(basis,numnodes,1,0,
+						&D_scalar,1,1,0,
+						basis,1,numnodes,0,
+						&Ke->values[0],1);
+			D_scalar=D_scalar*dt;
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			element->ElementSizes(&hx,&hy,&hz);
+			vel=sqrt(vx*vx + vy*vy + vz*vz)+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2) + pow(hy*vy/vel,2) + pow(hz*vz/vel,2));
+			K[0][0]=h/(2.*vel)*vx*vx;  K[0][1]=h/(2.*vel)*vx*vy; K[0][2]=h/(2.*vel)*vx*vz;
+			K[1][0]=h/(2.*vel)*vy*vx;  K[1][1]=h/(2.*vel)*vy*vy; K[1][2]=h/(2.*vel)*vy*vz;
+			K[2][0]=h/(2.*vel)*vz*vx;  K[2][1]=h/(2.*vel)*vz*vy; K[2][2]=h/(2.*vel)*vz*vz;
+			for(int i=0;i<3;i++) for(int j=0;j<3;j++) K[i][j] = D_scalar*K[i][j];
+
+			GetBAdvecprime(Bprime,element,xyz_list,gauss); 
+			TripleMultiply(Bprime,3,numnodes,1,
+						&K[0][0],3,3,0,
+						Bprime,3,numnodes,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			tau_parameter=element->StabilizationParameter(u-um,v-vm,w-wm,diameter,kappa/rho_ice);
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*
+					  ((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i])*((u-um)*dbasis[0*numnodes+j]+(v-vm)*dbasis[1*numnodes+j]+(w-wm)*dbasis[2*numnodes+j]);
+				}
+			}
+			if(dt!=0.){
+				D_scalar=gauss->weight*Jdet;
+				for(int i=0;i<numnodes;i++){
+					for(int j=0;j<numnodes;j++){
+						Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*basis[j]*((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementMatrix* EnthalpyAnalysis::CreateKMatrixShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  dt,Jdet,D;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		D=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) D=dt*D;
+		TripleMultiply(basis,numnodes,1,0,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return Ke;
+}/*}}}*/
+ElementVector* EnthalpyAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorVolume(element);
+	ElementVector* pe2=CreatePVectorSheet(element);
+	ElementVector* pe3=CreatePVectorShelf(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}/*}}}*/
+ElementVector* EnthalpyAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         i, stabilization;
+	IssmDouble  Jdet,phi,dt;
+	IssmDouble  enthalpy, Hpmp;
+	IssmDouble  enthalpypicard, d1enthalpypicard[3];
+	IssmDouble  pressure, d1pressure[3], d2pressure;
+	IssmDouble  waterfractionpicard;
+	IssmDouble  kappa,tau_parameter,diameter,kappa_w;
+	IssmDouble  u,v,w;
+	IssmDouble  scalar_def, scalar_sens ,scalar_transient;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  d1H_d1P, d1P2;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize Element vector*/
+	ElementVector* pe             = element->NewElementVector();
+	IssmDouble*    basis          = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis         = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+	IssmDouble  temperateiceconductivity = element->GetMaterialParameter(MaterialsTemperateiceconductivityEnum);
+	IssmDouble  beta                = element->GetMaterialParameter(MaterialsBetaEnum);
+	IssmDouble  latentheat          = element->GetMaterialParameter(MaterialsLatentheatEnum);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+	Input* enthalpypicard_input=element->GetInput(EnthalpyPicardEnum); _assert_(enthalpypicard_input);
+	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* enthalpy_input=NULL;
+	if(reCast<bool,IssmDouble>(dt)){enthalpy_input = element->GetInput(EnthalpyEnum); _assert_(enthalpy_input);}
+	if(stabilization==2){
+		diameter=element->MinEdgeLength(xyz_list);
+		kappa=this->EnthalpyDiffusionParameterVolume(element,EnthalpyPicardEnum); _assert_(kappa>=0.);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		
+		/*viscous dissipation*/
+		element->ViscousHeating(&phi,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		scalar_def=phi/rho_ice*Jdet*gauss->weight;
+		if(dt!=0.) scalar_def=scalar_def*dt;
+
+		for(i=0;i<numnodes;i++) pe->values[i]+=scalar_def*basis[i];
+
+		/*sensible heat flux in temperate ice*/
+		enthalpypicard_input->GetInputValue(&enthalpypicard,gauss);
+		pressure_input->GetInputValue(&pressure,gauss);
+		Hpmp=this->PureIceEnthalpy(element, pressure);
+
+		if(enthalpypicard>=Hpmp){
+			enthalpypicard_input->GetInputDerivativeValue(&d1enthalpypicard[0],xyz_list,gauss);
+			pressure_input->GetInputDerivativeValue(&d1pressure[0],xyz_list,gauss);
+			d2pressure=0.; // for linear elements, 2nd derivative is zero
+			
+			d1H_d1P=0.;
+			for(i=0;i<3;i++) d1H_d1P+=d1enthalpypicard[i]*d1pressure[i];
+			d1P2=0.;
+			for(i=0;i<3;i++) d1P2+=pow(d1pressure[i],2.);
+
+			scalar_sens=-beta*((temperateiceconductivity - thermalconductivity)/latentheat*(d1H_d1P + beta*heatcapacity*d1P2))/rho_ice;
+			if(dt!=0.) scalar_sens=scalar_sens*dt;
+			for(i=0;i<numnodes;i++) pe->values[i]+=scalar_sens*basis[i];
+		}		
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			enthalpy_input->GetInputValue(&enthalpy, gauss);
+			scalar_transient=enthalpy*Jdet*gauss->weight;
+			for(i=0;i<numnodes;i++) pe->values[i]+=scalar_transient*basis[i];
+		}
+
+		if(stabilization==2){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+			vx_input->GetInputValue(&u,gauss);
+			vy_input->GetInputValue(&v,gauss);
+			vz_input->GetInputValue(&w,gauss);
+			tau_parameter=element->StabilizationParameter(u,v,w,diameter,kappa/rho_ice);
+
+			for(i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+
+			if(dt!=0.){
+				for(i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+
+}/*}}}*/
+ElementVector* EnthalpyAnalysis::CreatePVectorSheet(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/* implementation of the basal condition decision chart of Aschwanden 2012, Fig.5 */
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,enthalpy,pressure,watercolumn,geothermalflux,vx,vy,vz;
+	IssmDouble  enthalpyup,pressureup,alpha2,scalar,basalfriction,heatflux;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input             = element->GetInput(VxEnum);                          _assert_(vx_input);
+	Input* vy_input             = element->GetInput(VyEnum);                          _assert_(vy_input);
+	Input* vz_input             = element->GetInput(VzEnum);                          _assert_(vz_input);
+	Input* enthalpy_input       = element->GetInput(EnthalpyPicardEnum);              _assert_(enthalpy_input);
+	Input* pressure_input       = element->GetInput(PressureEnum);                    _assert_(pressure_input);
+	Input* geothermalflux_input = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+	Input* watercolumn_input    = element->GetInput(WatercolumnEnum);                 _assert_(watercolumn_input);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss   = element->NewGaussBase(2);
+	Gauss* gaussup = element->NewGaussTop(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		enthalpy_input->GetInputValue(&enthalpy,gauss);
+		pressure_input->GetInputValue(&pressure,gauss);
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+
+		if((watercolumn<=0.) && (enthalpy<PureIceEnthalpy(element,pressure))){
+			/* the above check is equivalent to 
+			 NOT [(watercolumn>0.) AND (enthalpy<PIE)] AND (enthalpy<PIE)*/
+			geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+
+			friction->GetAlpha2(&alpha2,gauss);
+			vx_input->GetInputValue(&vx,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			vz_input->GetInputValue(&vz,gauss);
+			basalfriction = alpha2*(vx*vx + vy*vy + vz*vz);
+			heatflux      = (basalfriction+geothermalflux)/(rho_ice);
+
+			scalar = gauss->weight*Jdet*heatflux;
+			if(dt!=0.) scalar=dt*scalar;
+
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
+		}
+		else if(enthalpy >= PureIceEnthalpy(element,pressure)){
+			/* check positive thickness of temperate basal ice layer */
+			enthalpy_input->GetInputValue(&enthalpyup,gaussup);
+			pressure_input->GetInputValue(&pressureup,gaussup);
+			if(enthalpyup >= PureIceEnthalpy(element,pressureup)){
+				// do nothing, set grad enthalpy*n=0.
+			}
+			else{
+				// only base temperate, set Dirichlet BCs in Penta::UpdateBasalConstraintsEnthalpy()
+			}
+		}
+		else{
+			// base cold, but watercolumn positive. Set base to pressure melting point enthalpy
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete gaussup;
+	delete friction;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+
+}/*}}}*/
+ElementVector* EnthalpyAnalysis::CreatePVectorShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	IssmDouble  h_pmp,dt,Jdet,scalar_ocean,pressure;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input*      pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		h_pmp=element->PureIceEnthalpy(pressure);
+
+		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel*h_pmp/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+void EnthalpyAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_conduct=[ dh/dx ]
+	 *                  [ dh/dy ]
+	 *                  [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void EnthalpyAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+		B[numnodes*2+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void EnthalpyAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void EnthalpyAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,EnthalpyEnum);
+}/*}}}*/
+void EnthalpyAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void EnthalpyAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	bool        converged;
+	int         i,rheology_law;
+	IssmDouble  B_average,s_average,T_average=0.,P_average=0.;
+	int        *doflist   = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values        = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure      = xNew<IssmDouble>(numnodes);
+	IssmDouble* surface       = xNew<IssmDouble>(numnodes);
+	IssmDouble* B             = xNew<IssmDouble>(numnodes);
+	IssmDouble* temperature   = xNew<IssmDouble>(numnodes);
+	IssmDouble* waterfraction = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	element->GetInputValue(&converged,ConvergedEnum);
+	element->GetInputListOnNodes(&pressure[0],PressureEnum);
+	if(converged){
+		for(i=0;i<numnodes;i++){
+			element->EnthalpyToThermal(&temperature[i],&waterfraction[i],values[i],pressure[i]);
+			if(waterfraction[i]<0.) _error_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1.) _error_("Water fraction >1 found in solution vector");
+		}
+		element->AddInput(EnthalpyEnum,values,element->GetElementType());
+		element->AddInput(WaterfractionEnum,waterfraction,element->GetElementType());
+		element->AddInput(TemperatureEnum,temperature,element->GetElementType());
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case CuffeyEnum:
+				for(i=0;i<numnodes;i++) B[i]=Cuffey(temperature[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case PatersonEnum:
+				for(i=0;i<numnodes;i++) B[i]=Paterson(temperature[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case ArrheniusEnum:
+				element->GetVerticesCoordinates(&xyz_list);
+				for(i=0;i<numnodes;i++) B[i]=Arrhenius(temperature[i],surface[i]-xyz_list[i*3+2],element->GetMaterialParameter(MaterialsRheologyNEnum));
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case LliboutryDuvalEnum:
+				for(i=0;i<numnodes;i++) B[i]=LliboutryDuval(values[i],pressure[i],element->GetMaterialParameter(MaterialsRheologyNEnum),element->GetMaterialParameter(MaterialsBetaEnum),element->GetMaterialParameter(ConstantsReferencetemperatureEnum),element->GetMaterialParameter(MaterialsHeatcapacityEnum),element->GetMaterialParameter(MaterialsLatentheatEnum)); 
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType()); 
+				break; 
+			default: _error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+		}
+	}
+	else{
+		element->AddInput(EnthalpyPicardEnum,values,element->GetElementType());
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(temperature);
+	xDelete<IssmDouble>(waterfraction);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+void EnthalpyAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
+
+/*Modules*/
+void EnthalpyAnalysis::PostProcessing(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	int solution_type, i;
+	bool computebasalmeltingrates=true;
+	bool isdrainage=true;
+	bool updatebasalconstraints=true;
+
+	if(isdrainage){
+		/*Drain excess water fraction in ice column: */
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			DrainWaterfractionIcecolumn(element);
+		}
+	}
+
+	if(computebasalmeltingrates){
+		/*Compute basal melting rates: */
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			ComputeBasalMeltingrate(element);
+		}
+	}
+
+	if(updatebasalconstraints){
+		/*Update basal dirichlet BCs for enthalpy in transient runs: */
+		femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+		if(solution_type==TransientSolutionEnum){
+			for(i=0;i<femmodel->elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+				UpdateBasalConstraints(element);
+			}
+		}
+	}
+}/*}}}*/
+void EnthalpyAnalysis::ComputeBasalMeltingrate(Element* element){/*{{{*/
+	/*Calculate the basal melt rates of the enthalpy model after Aschwanden 2012*/
+	/* melting rate is positive when melting, negative when refreezing*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only compute melt rates at the base of grounded ice*/
+	if(!element->IsOnBase() || element->IsFloating()) return;
+
+	/* Intermediaries */
+	const int   dim=3;
+	int         i,is,vertexdown,vertexup,numvertices,numsegments;
+	IssmDouble  heatflux;
+	IssmDouble  vec_heatflux[dim],normal_base[dim],d1enthalpy[dim];
+	IssmDouble  basalfriction,alpha2;
+	IssmDouble  dt,yts;
+	IssmDouble  melting_overshoot,lambda;
+	IssmDouble  geothermalflux;
+	IssmDouble  vx,vy,vz;
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_base = NULL;
+	int        *pairindices   = NULL;
+
+	/*Fetch parameters and inputs */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	IssmDouble latentheat = element->GetMaterialParameter(MaterialsLatentheatEnum);
+	IssmDouble rho_ice    = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble rho_water  = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	Input* enthalpy_input         = element->GetInput(EnthalpyEnum);                    _assert_(enthalpy_input);
+	Input* geothermalflux_input   = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+	Input* vx_input               = element->GetInput(VxEnum);                          _assert_(vx_input);
+	Input* vy_input               = element->GetInput(VyEnum);                          _assert_(vy_input);
+	Input* vz_input               = element->GetInput(VzEnum);                          _assert_(vz_input);
+	IssmDouble kappa=EnthalpyDiffusionParameterVolume(element,EnthalpyEnum);     _assert_(kappa>=0.);
+	element->NormalBase(&normal_base[0],xyz_list_base);
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+	IssmDouble* meltingrate_enthalpy = xNew<IssmDouble>(numsegments);
+	IssmDouble* heating = xNew<IssmDouble>(numsegments);	
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/******** MELTING RATES  ************************************/
+	numvertices=element->GetNumberOfVertices();
+	IssmDouble* enthalpy = xNew<IssmDouble>(numvertices);
+	IssmDouble* pressure = xNew<IssmDouble>(numvertices);
+	IssmDouble* watercolumn = xNew<IssmDouble>(numvertices);
+	IssmDouble* basalmeltingrate = xNew<IssmDouble>(numvertices);
+	element->GetInputListOnVertices(enthalpy,EnthalpyEnum);
+	element->GetInputListOnVertices(pressure,PressureEnum);
+	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
+	element->GetInputListOnVertices(basalmeltingrate,BasalforcingsGroundediceMeltingRateEnum);
+
+	Gauss* gauss=element->NewGauss();
+	
+	for(int is=0;is<numsegments;is++){
+		vertexdown = pairindices[is*2+0];
+		vertexup   = pairindices[is*2+1];
+		gauss->GaussVertex(vertexdown);
+		
+		bool checkpositivethickness=true;
+		_assert_(watercolumn[vertexdown]>=0.);
+
+		/*Calculate basal meltingrate after Fig.5 of A.Aschwanden 2012*/
+		meltingrate_enthalpy[is]=0.;
+		heating[is]=0.;
+		if((watercolumn[vertexdown]>0.) && (enthalpy[vertexdown]<PureIceEnthalpy(element,pressure[vertexdown]))){
+			/*ensure that no ice is at T<Tm(p), if water layer present*/
+			enthalpy[vertexdown]=element->PureIceEnthalpy(pressure[vertexdown]); 
+		}
+		else if(enthalpy[vertexdown]<element->PureIceEnthalpy(pressure[vertexdown])){
+			/*cold base: set q*n=q_geo*n+frictionheating as Neumann BC in Penta::CreatePVectorEnthalpySheet*/
+			checkpositivethickness=false; // cold base, skip next test
+		}
+		else{/*we have a temperate base, go to next test*/}
+
+		if(checkpositivethickness){
+			/*From here on all basal ice is temperate. Check for positive thickness of layer of temperate ice. */
+			bool istemperatelayer=false;
+			if(enthalpy[vertexup]>=element->PureIceEnthalpy(pressure[vertexup])) istemperatelayer=true;
+			if(istemperatelayer) for(i=0;i<dim;i++) vec_heatflux[i]=0.; // TODO: add -k*nabla T_pmp
+			else{
+				enthalpy_input->GetInputDerivativeValue(&d1enthalpy[0],xyz_list,gauss);
+				for(i=0;i<3;i++) vec_heatflux[i]=-kappa*d1enthalpy[i];
+			}
+
+			/*heat flux along normal*/
+			heatflux=0.;
+			for(i=0;i<3;i++) heatflux+=(vec_heatflux[i])*normal_base[i];
+
+			/*basal friction*/
+			friction->GetAlpha2(&alpha2,gauss);
+			vx_input->GetInputValue(&vx,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			vz_input->GetInputValue(&vz,gauss);
+			basalfriction=alpha2*(vx*vx + vy*vy + vz*vz);
+
+			geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+			/* -Mb= Fb-(q-q_geo)/((1-w)*L*rho), and (1-w)*rho=rho_ice, cf Aschwanden 2012, eqs.1, 2, 66*/
+			heating[is]=(heatflux+basalfriction+geothermalflux);
+			meltingrate_enthalpy[is]=heating[is]/(latentheat*rho_ice); // m/s water equivalent
+		}
+	}
+	/******** UPDATE MELTINGRATES AND WATERCOLUMN **************/
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	for(is=0;is<numsegments;is++){
+		vertexdown = pairindices[is*2+0];
+		vertexup   = pairindices[is*2+1];
+		if(dt!=0.){
+			if(watercolumn[vertexdown]+meltingrate_enthalpy[is]*dt<0.){	// prevent too much freeze on			
+				lambda = -watercolumn[vertexdown]/(dt*meltingrate_enthalpy[is]); _assert_(lambda>=0.); _assert_(lambda<1.);
+				watercolumn[vertexdown]=0.;
+				basalmeltingrate[vertexdown]=lambda*meltingrate_enthalpy[is]; // restrict freeze on only to size of watercolumn
+				enthalpy[vertexdown]+=(1.-lambda)*meltingrate_enthalpy[is]*dt*latentheat; // use rest of energy to cool down base
+			}
+			else{
+				basalmeltingrate[vertexdown]=meltingrate_enthalpy[is];
+				watercolumn[vertexdown]+=dt*meltingrate_enthalpy[is]; 
+			}
+		}
+		else{
+			basalmeltingrate[vertexdown]=meltingrate_enthalpy[is];
+			watercolumn[vertexdown]+=meltingrate_enthalpy[is];
+		}	
+		basalmeltingrate[vertexdown]*=rho_water/rho_ice; // convert meltingrate from water to ice equivalent
+		_assert_(watercolumn[vertexdown]>=0.);
+	}
+
+	/*feed updated variables back into model*/
+	element->AddInput(EnthalpyEnum,enthalpy,P1Enum);
+	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
+	element->AddInput(BasalforcingsGroundediceMeltingRateEnum,basalmeltingrate,P1Enum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(enthalpy);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(watercolumn);
+	xDelete<IssmDouble>(basalmeltingrate);
+	xDelete<IssmDouble>(meltingrate_enthalpy);
+	xDelete<IssmDouble>(heating);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_base);
+}/*}}}*/
+void EnthalpyAnalysis::DrainWaterfractionIcecolumn(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only drain waterfraction of ice column from element at base*/
+	if(!element->IsOnBase()) return; //FIXME: allow freeze on for floating elements
+
+	/* Intermediaries*/
+	int is, numvertices, numsegments;
+	int *pairindices   = NULL;
+
+	numvertices=element->GetNumberOfVertices();
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+
+	IssmDouble* watercolumn = xNew<IssmDouble>(numvertices);
+	IssmDouble* drainrate_column  = xNew<IssmDouble>(numsegments);
+	IssmDouble* drainrate_element = xNew<IssmDouble>(numsegments);
+
+	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
+
+	for(is=0;is<numsegments;is++)	drainrate_column[is]=0.;
+	Element* elementi = element;
+	for(;;){
+		for(is=0;is<numsegments;is++)	drainrate_element[is]=0.;
+		DrainWaterfraction(elementi,drainrate_element); // TODO: make sure every vertex is only drained once
+		for(is=0;is<numsegments;is++)	drainrate_column[is]+=drainrate_element[is];
+
+		if(elementi->IsOnSurface()) break;
+		elementi=elementi->GetUpperElement();			
+	}
+	/* add drained water to water column*/
+	for(is=0;is<numsegments;is++) watercolumn[is]+=drainrate_column[is];
+	/* Feed updated water column back into model */
+	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
+
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(drainrate_column);
+	xDelete<IssmDouble>(drainrate_element);
+	xDelete<IssmDouble>(watercolumn);
+}/*}}}*/
+void EnthalpyAnalysis::DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/*Intermediaries*/
+	int iv,is,vertexdown,vertexup,numsegments;	
+	IssmDouble dt, height_element;
+	IssmDouble rho_water, rho_ice;
+	int numvertices = element->GetNumberOfVertices();
+
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* enthalpies = xNew<IssmDouble>(numvertices);
+	IssmDouble* pressures = xNew<IssmDouble>(numvertices);
+	IssmDouble* temperatures = xNew<IssmDouble>(numvertices);
+	IssmDouble* waterfractions = xNew<IssmDouble>(numvertices);
+	IssmDouble* deltawaterfractions = xNew<IssmDouble>(numvertices);
+	int        *pairindices   = NULL;
+	
+	rho_ice=element->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_water=element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnVertices(enthalpies,EnthalpyEnum);
+	element->GetInputListOnVertices(pressures,PressureEnum);
+
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	for(iv=0;iv<numvertices;iv++){ 
+		element->EnthalpyToThermal(&temperatures[iv],&waterfractions[iv], enthalpies[iv],pressures[iv]); 
+		deltawaterfractions[iv]=DrainageFunctionWaterfraction(waterfractions[iv], dt);
+	}
+	
+	/*drain waterfraction, feed updated variables back into model*/
+	for(iv=0;iv<numvertices;iv++){
+		if(reCast<bool,IssmDouble>(dt))
+			waterfractions[iv]-=deltawaterfractions[iv]*dt;
+		else
+			waterfractions[iv]-=deltawaterfractions[iv];
+		element->ThermalToEnthalpy(&enthalpies[iv], temperatures[iv], waterfractions[iv], pressures[iv]);
+	}
+	element->AddInput(EnthalpyEnum,enthalpies,P1Enum);
+  	element->AddInput(WaterfractionEnum,waterfractions,P1Enum);
+
+	/*return meltwater column equivalent to drained water*/
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+	for(is=0;is<numsegments;is++){
+		vertexdown = pairindices[is*2+0];
+		vertexup   = pairindices[is*2+1];
+		height_element=fabs(xyz_list[vertexup*3+2]-xyz_list[vertexdown*3+2]);
+		pdrainrate_element[is]=(deltawaterfractions[vertexdown]+deltawaterfractions[vertexup])/2.*height_element; // return water equivalent of drainage
+		_assert_(pdrainrate_element[is]>=0.);
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(enthalpies);
+	xDelete<IssmDouble>(pressures);
+	xDelete<IssmDouble>(temperatures);
+	xDelete<IssmDouble>(waterfractions);
+	xDelete<IssmDouble>(deltawaterfractions);
+}/*}}}*/
+void EnthalpyAnalysis::UpdateBasalConstraints(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase()) || element->IsFloating()) return;
+
+	/*Intermediary*/
+	bool        isdynamicbasalspc,setspc;
+	int         numindices, numindicesup;
+	IssmDouble  pressure, pressureup;
+	IssmDouble  h_pmp, enthalpy, enthalpyup;
+	IssmDouble  watercolumn;
+	int        *indices = NULL, *indicesup = NULL;
+	Node*       node = NULL;
+
+	/*Check wether dynamic basal boundary conditions are activated */
+	element->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+	if(!isdynamicbasalspc) return;
+
+	/*Fetch indices of basal & surface nodes for this finite element*/
+	Penta *penta =  (Penta *) element; // TODO: add Basal-/SurfaceNodeIndices to element.h, and change this to Element*
+	penta->BasalNodeIndices(&numindices,&indices,element->GetElementType());
+	penta->SurfaceNodeIndices(&numindicesup,&indicesup,element->GetElementType());
+	_assert_(numindices==numindicesup);
+
+	/*Get parameters and inputs: */
+	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* enthalpy_input=element->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+	Input* watercolumn_input=element->GetInput(WatercolumnEnum); _assert_(watercolumn_input);
+
+	/*if there is a temperate layer of zero thickness, set spc enthalpy=h_pmp at that node*/
+	GaussPenta* gauss=new GaussPenta();
+	GaussPenta* gaussup=new GaussPenta();
+	for(int i=0;i<numindices;i++){
+		gauss->GaussNode(element->GetElementType(),indices[i]);
+		gaussup->GaussNode(element->GetElementType(),indicesup[i]);
+
+		/*Check wether there is a temperate layer at the base or not */
+		/*check if node is temperate, else continue*/
+		enthalpy_input->GetInputValue(&enthalpy, gauss);
+		pressure_input->GetInputValue(&pressure, gauss);
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		h_pmp=PureIceEnthalpy(element,pressure);
+		if (enthalpy>=h_pmp){
+			/*check if upper node is temperate, too.
+				if yes, then we have a temperate layer of positive thickness and reset the spc.
+				if not, apply dirichlet BC.*/
+			enthalpy_input->GetInputValue(&enthalpyup, gaussup);
+			pressure_input->GetInputValue(&pressureup, gaussup);
+			setspc=((enthalpyup<PureIceEnthalpy(element,pressureup)) && (watercolumn>=0.))?true:false;
+		}
+		else
+			setspc = false;
+
+		node=element->GetNode(indices[i]);
+		if(setspc) 
+			node->ApplyConstraint(0,h_pmp); /*apply spc*/ 
+		else			
+			node->DofInFSet(0); /*remove spc*/ 
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(indices);
+	xDelete<int>(indicesup);
+	delete gauss;
+	delete gaussup;
+}/*}}}*/
+
+/*Intermediaries*/
+IssmDouble EnthalpyAnalysis::EnthalpyDiffusionParameter(Element* element,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+
+	IssmDouble heatcapacity             = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble temperateiceconductivity = element->GetMaterialParameter(MaterialsTemperateiceconductivityEnum);
+	IssmDouble thermalconductivity      = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+
+	if(enthalpy < PureIceEnthalpy(element,pressure)){
+		return thermalconductivity/heatcapacity;
+	}
+	else{
+		return temperateiceconductivity/heatcapacity;
+	}
+}/*}}}*/
+IssmDouble EnthalpyAnalysis::EnthalpyDiffusionParameterVolume(Element* element,int enthalpy_enum){/*{{{*/
+
+	int         iv;
+	IssmDouble  lambda;                   /* fraction of cold ice    */
+	IssmDouble  kappa,kappa_c,kappa_t; /* enthalpy conductivities */
+	IssmDouble  Hc,Ht;
+
+	/*Get pressures and enthalpies on vertices*/
+	int         numvertices = element->GetNumberOfVertices();
+	IssmDouble* pressures   = xNew<IssmDouble>(numvertices);
+	IssmDouble* enthalpies  = xNew<IssmDouble>(numvertices);
+	IssmDouble* PIE         = xNew<IssmDouble>(numvertices);
+	IssmDouble* dHpmp       = xNew<IssmDouble>(numvertices);
+	element->GetInputListOnVertices(pressures,PressureEnum);
+	element->GetInputListOnVertices(enthalpies,enthalpy_enum);
+	for(iv=0;iv<numvertices;iv++){
+		PIE[iv]   = PureIceEnthalpy(element,pressures[iv]);
+		dHpmp[iv] = enthalpies[iv]-PIE[iv];
+	}
+
+	bool allequalsign = true;
+	if(dHpmp[0]<0.){
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]<0.));
+	}
+	else{
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]>=0.));
+	}
+
+	if(allequalsign){
+		kappa = EnthalpyDiffusionParameter(element,enthalpies[0],pressures[0]);
+	}
+	else{
+		/* return harmonic mean of thermal conductivities, weighted by fraction of cold/temperate ice,
+			cf Patankar 1980, pp44 */
+		kappa_c = EnthalpyDiffusionParameter(element,PureIceEnthalpy(element,0.)-1.,0.);
+		kappa_t = EnthalpyDiffusionParameter(element,PureIceEnthalpy(element,0.)+1.,0.);
+		Hc=0.; Ht=0.;
+		for(iv=0; iv<numvertices;iv++){
+			if(enthalpies[iv]<PIE[iv])
+			 Hc+=(PIE[iv]-enthalpies[iv]);
+			else
+			 Ht+=(enthalpies[iv]-PIE[iv]);
+		}
+		_assert_((Hc+Ht)>0.);
+		lambda = Hc/(Hc+Ht);
+		kappa  = kappa_c*kappa_t/(lambda*kappa_t+(1.-lambda)*kappa_c); // ==(lambda/kappa_c + (1.-lambda)/kappa_t)^-1
+	}	
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(PIE);
+	xDelete<IssmDouble>(dHpmp);
+	xDelete<IssmDouble>(pressures);
+	xDelete<IssmDouble>(enthalpies);
+	return kappa;
+}/*}}}*/
+IssmDouble EnthalpyAnalysis::PureIceEnthalpy(Element* element,IssmDouble pressure){/*{{{*/
+
+	IssmDouble heatcapacity         = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble referencetemperature = element->GetMaterialParameter(ConstantsReferencetemperatureEnum);
+
+	return heatcapacity*(TMeltingPoint(element,pressure)-referencetemperature);
+}/*}}}*/
+IssmDouble EnthalpyAnalysis::TMeltingPoint(Element* element,IssmDouble pressure){/*{{{*/
+
+	IssmDouble meltingpoint = element->GetMaterialParameter(MaterialsMeltingpointEnum);
+	IssmDouble beta         = element->GetMaterialParameter(MaterialsBetaEnum);
+
+	return meltingpoint-beta*pressure;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnthalpyAnalysis.h	(revision 18231)
@@ -0,0 +1,54 @@
+/*! \file EnthalpyAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _EnthalpyAnalysis_
+#define _EnthalpyAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class EnthalpyAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementMatrix* CreateKMatrixShelf(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorVolume(Element* element);
+		ElementVector* CreatePVectorSheet(Element* element);
+		ElementVector* CreatePVectorShelf(Element* element);
+		void GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*Modules*/
+		static void PostProcessing(FemModel* femmodel);
+		static void ComputeBasalMeltingrate(Element* element);
+		static void DrainWaterfractionIcecolumn(Element* element);
+		static void DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element);
+		static void UpdateBasalConstraints(Element* element);
+
+		/*Intermediaries*/
+		static IssmDouble EnthalpyDiffusionParameter(Element* element,IssmDouble enthalpy,IssmDouble pressure);
+		static IssmDouble EnthalpyDiffusionParameterVolume(Element* element,int enthalpy_enum);
+		static IssmDouble PureIceEnthalpy(Element* element,IssmDouble pressure);
+		static IssmDouble TMeltingPoint(Element* element,IssmDouble pressure);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.cpp	(revision 18231)
@@ -0,0 +1,117 @@
+/*
+* \file EnumToAnalysis.cpp
+* \brief: output class depending on enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include "./analyses.h"
+#include "../shared/shared.h"
+
+Analysis* EnumToAnalysis(int analysis_enum){
+
+	switch(analysis_enum){
+		#ifdef _HAVE_ADJOINTBALANCETHICKNESS_
+		case AdjointBalancethicknessAnalysisEnum : return new AdjointBalancethicknessAnalysis();
+		#endif
+		#ifdef _HAVE_ADJOINTBALANCETHICKNESS2_
+		case AdjointBalancethickness2AnalysisEnum : return new AdjointBalancethickness2Analysis();
+		#endif
+		#ifdef _HAVE_ADJOINTHORIZ_
+		case AdjointHorizAnalysisEnum : return new AdjointHorizAnalysis();
+		#endif
+		#ifdef _HAVE_BALANCETHICKNESS_
+		case BalancethicknessAnalysisEnum : return new BalancethicknessAnalysis();
+		#endif
+		#ifdef _HAVE_BALANCETHICKNESS2_
+		case Balancethickness2AnalysisEnum : return new Balancethickness2Analysis();
+		#endif
+		#ifdef _HAVE_BALANCETHICKNESSSOFT_
+		case BalancethicknessSoftAnalysisEnum : return new BalancethicknessSoftAnalysis();
+		#endif
+		#ifdef _HAVE_BALANCEVELOCITY_
+		case BalancevelocityAnalysisEnum : return new BalancevelocityAnalysis();
+		#endif
+		#ifdef _HAVE_L2PROJECTIONEPL_
+		case L2ProjectionEPLAnalysisEnum : return new L2ProjectionEPLAnalysis();
+		#endif
+		#ifdef _HAVE_L2PROJECTIONBASE_
+		case L2ProjectionBaseAnalysisEnum : return new L2ProjectionBaseAnalysis();
+		#endif
+		#ifdef _HAVE_DAMAGEEVOLUTION_
+		case DamageEvolutionAnalysisEnum : return new DamageEvolutionAnalysis();
+		#endif
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum : return new StressbalanceAnalysis();
+		#endif
+		#ifdef _HAVE_STRESSBALANCESIA_
+		case StressbalanceSIAAnalysisEnum : return new StressbalanceSIAAnalysis();
+		#endif
+		#ifdef _HAVE_STRESSBALANCEVERTICAL_
+		case StressbalanceVerticalAnalysisEnum : return new StressbalanceVerticalAnalysis();
+		#endif
+		#ifdef _HAVE_ENTHALPY_
+		case EnthalpyAnalysisEnum : return new EnthalpyAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYSHREVE_
+		case HydrologyShreveAnalysisEnum : return new HydrologyShreveAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYDCINEFFICIENT_
+		case HydrologyDCInefficientAnalysisEnum : return new HydrologyDCInefficientAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYDCEFFICIENT_
+		case HydrologyDCEfficientAnalysisEnum : return new HydrologyDCEfficientAnalysis();
+		#endif
+		#ifdef _HAVE_MELTING_
+		case MeltingAnalysisEnum : return new MeltingAnalysis();
+		#endif
+		#ifdef _HAVE_MASSTRANSPORT_
+		case MasstransportAnalysisEnum : return new MasstransportAnalysis();
+		#endif
+		#ifdef _HAVE_FREESURFACEBASE_
+		case FreeSurfaceBaseAnalysisEnum : return new FreeSurfaceBaseAnalysis();
+		#endif
+		#ifdef _HAVE_FREESURFACETOP_
+		case FreeSurfaceTopAnalysisEnum : return new FreeSurfaceTopAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRUDEFROMBASE_
+		case ExtrudeFromBaseAnalysisEnum : return new ExtrudeFromBaseAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRUDEFROMTOP_
+		case ExtrudeFromTopAnalysisEnum : return new ExtrudeFromTopAnalysis();
+		#endif
+		#ifdef _HAVE_DEPTHAVERAGE_
+		case DepthAverageAnalysisEnum : return new DepthAverageAnalysis();
+		#endif
+		#ifdef _HAVE_SMOOTHEDSURFACESLOPEX_
+		case SmoothedSurfaceSlopeXAnalysisEnum : return new SmoothedSurfaceSlopeXAnalysis();
+		#endif
+		#ifdef _HAVE_SMOOTHEDSURFACESLOPEY_
+		case SmoothedSurfaceSlopeYAnalysisEnum : return new SmoothedSurfaceSlopeYAnalysis();
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum : return new ThermalAnalysis();
+		#endif
+		#ifdef _HAVE_UZAWAPRESSURE_
+		case UzawaPressureAnalysisEnum : return new UzawaPressureAnalysis();
+		#endif
+		#ifdef _HAVE_GIA_
+		case GiaAnalysisEnum : return new GiaAnalysis();
+		#endif
+		#ifdef _HAVE_MESHDEFORMATION_
+		case MeshdeformationAnalysisEnum : return new MeshdeformationAnalysis();
+		#endif
+		#ifdef _HAVE_LEVELSET_
+		case LevelsetAnalysisEnum : return new LevelsetAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRAPOLATION_
+		case ExtrapolationAnalysisEnum : return new ExtrapolationAnalysis();
+		#endif
+		#ifdef _HAVE_LSFREINITIALIZATION_
+		case LsfReinitializationAnalysisEnum : return new LsfReinitializationAnalysis();
+		#endif
+		default : _error_("enum provided not supported ("<<EnumToStringx(analysis_enum)<<")");
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/EnumToAnalysis.h	(revision 18231)
@@ -0,0 +1,26 @@
+#ifndef _ENUMTOANALYSIS_
+#define _ENUMTOANALYSIS_
+
+class Analysis;
+
+Analysis* EnumToAnalysis(int analysis_enum);
+
+#endif
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 18231)
@@ -0,0 +1,355 @@
+#include "./ExtrapolationAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+int ExtrapolationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}
+/*}}}*/
+void ExtrapolationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	//do nothing for now
+	return;
+}
+/*}}}*/
+void ExtrapolationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	int    finiteelement;
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}
+/*}}}*/
+void ExtrapolationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	int finiteelement=P1Enum;
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,ExtrapolationAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}
+/*}}}*/
+void ExtrapolationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	// do nothing for now
+	return;
+}
+/*}}}*/
+void ExtrapolationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	//	do nothing for now
+	return;
+}/*}}}*/
+
+/*Finite element Analysis*/
+void ExtrapolationAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+	/* Intermediaries */
+	bool save_results;
+	int extvar_enum; 
+   femmodel->parameters->FindParam(&extvar_enum, ExtrapolationVariableEnum);
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(ExtrapolationAnalysisEnum);
+
+	if(VerboseSolution()) _printf0_("extrapolation of " << EnumToStringx(extvar_enum) << ": call computational core:\n");
+	solutionsequence_linear(femmodel);
+
+	save_results=true;
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[2] = {VxEnum,VyEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+	}
+}/*}}}*/
+ElementVector* ExtrapolationAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* ExtrapolationAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+	/* Jacobian required for the Newton solver */
+	_error_("not implemented yet");
+}/*}}}*/
+ElementMatrix* ExtrapolationAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	/*Intermediaries */
+	int		   domaintype,dim;
+	int        i,row,col,stabilization;
+	bool	   extrapolatebydiffusion = true;
+	IssmDouble Jdet,D_scalar,h;
+	IssmDouble norm_dlsf;
+	IssmDouble hx,hy,hz,kappa;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	basalelement->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1; break;
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 2; break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*		D	  = xNew<IssmDouble>(dim*dim);
+	IssmDouble*		dlsf  = xNew<IssmDouble>(dim);
+	IssmDouble*		normal= xNew<IssmDouble>(dim);
+
+	/*Retrieve all inputs and parameters*/
+	Input* lsf_slopex_input=basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+	Input* lsf_slopey_input=basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	h = basalelement->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){/*{{{*/
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		GetB(B,basalelement,xyz_list,gauss);
+		GetBprime(Bprime,basalelement,xyz_list,gauss);
+		
+		D_scalar=gauss->weight*Jdet;
+
+		if(extrapolatebydiffusion){
+			/* diffuse values outward */
+			for(row=0;row<dim;row++)
+				for(col=0;col<dim;col++)
+					if(row==col)
+						D[row*dim+col] = D_scalar;
+					else
+						D[row*dim+col] = 0.;
+
+			TripleMultiply(Bprime,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+		}
+		else{
+			/* extrapolate values along normal */
+			/* Get normal on ice boundary */
+			lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+			lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+			norm_dlsf=0.;
+			for(i=0;i<dim;i++)	norm_dlsf+=dlsf[i]*dlsf[i]; 
+			norm_dlsf=sqrt(norm_dlsf); _assert_(norm_dlsf>0.);
+
+			if(norm_dlsf>0.)
+				for(i=0;i<dim;i++)	normal[i]=dlsf[i]/norm_dlsf;
+			else
+				for(i=0;i<dim;i++)	normal[i]=0.;
+			
+			for(row=0;row<dim;row++)
+				for(col=0;col<dim;col++)
+					if(row==col)
+						D[row*dim+col]=D_scalar*normal[row];
+					else
+						D[row*dim+col]=0.;
+			TripleMultiply(B,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+
+			/* Stabilization *//*{{{*/
+			stabilization=1;
+			if (stabilization==0){/* no stabilization, do nothing*/}
+			else if(stabilization==1){
+				/* Artificial Diffusion */
+				basalelement->ElementSizes(&hx,&hy,&hz);
+				h=sqrt( pow(hx*normal[0],2) + pow(hy*normal[1],2));
+				kappa=h/2.+1.e-14; 
+				for(row=0;row<dim;row++)
+					for(col=0;col<dim;col++)
+						if(row==col)
+							D[row*dim+col]=D_scalar*kappa;
+						else
+							D[row*dim+col]=0.;
+				TripleMultiply(Bprime,dim,numnodes,1,
+							D,dim,dim,0,
+							Bprime,dim,numnodes,0,
+							&Ke->values[0],1);
+			}
+			else if(stabilization==2){
+				/*Streamline upwinding - do not use this for extrapolation: yields oscillating results due to smoothing along normal, not across */
+				for(row=0;row<dim;row++)
+					for(col=0;col<dim;col++)
+						D[row*dim+col]=h/(2.*1.)*normal[row]*normal[col];
+
+				TripleMultiply(Bprime,dim,numnodes,1,
+							D,dim,dim,0,
+							Bprime,dim,numnodes,0,
+							&Ke->values[0],1);
+			}/*}}}*/
+		}
+	}/*}}}*/
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(dlsf);
+	xDelete<IssmDouble>(normal);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+
+}/*}}}*/
+ElementVector* ExtrapolationAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	/*Intermediaries */
+	int i, domaintype;
+	
+	/*Fetch number of nodes */
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe = basalelement->NewElementVector();
+	for(i=0;i<numnodes;i++) 
+		pe->values[i]=0.; 
+
+	basalelement->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void ExtrapolationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void ExtrapolationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void ExtrapolationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype, extrapolationvariable;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&extrapolationvariable, ExtrapolationVariableEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,extrapolationvariable);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,extrapolationvariable);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void ExtrapolationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void ExtrapolationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void ExtrapolationAnalysis::SetConstraintsOnIce(Element* element){/*{{{*/
+
+	int numnodes=element->GetNumberOfNodes();	
+
+	/* Intermediaries */
+	int extvar_enum;
+	IssmDouble phi,value;
+	Node* node = NULL;
+
+	/* Get parameters */
+	element->FindParam(&extvar_enum, ExtrapolationVariableEnum);
+	
+	Input* levelset_input=element->GetInput(MaskIceLevelsetEnum); _assert_(levelset_input);
+	Input* extvar_input=element->GetInput(extvar_enum); _assert_(extvar_input);
+
+	Gauss* gauss=element->NewGauss();
+	for(int in=0;in<numnodes;in++){
+		gauss->GaussNode(element->GetElementType(),in);
+		node=element->GetNode(in);
+		levelset_input->GetInputValue(&phi,gauss);
+		if(node->IsActive()){
+			if(phi<=0.){
+				/* if ice, set dirichlet BC */
+				extvar_input->GetInputValue(&value,gauss);
+				node->ApplyConstraint(0,value);
+			}
+			else {
+				/* no ice, set no spc */
+				node->DofInFSet(0); 
+			}
+		}
+	}
+	delete gauss;
+}/*}}}*/
+void ExtrapolationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		this->SetConstraintsOnIce(element);
+	}
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrapolationAnalysis.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*! \file ExtrapolationAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _ExtrapolationAnalysis_
+#define _ExtrapolationAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ExtrapolationAnalysis: public Analysis{
+	
+ public:
+	/*Model processing*/
+	int  DofsPerNode(int** doflist,int domaintype,int approximation);
+	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+	void CreateNodes(Nodes* nodes,IoModel* iomodel);
+	void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+	void CreateLoads(Loads* loads, IoModel* iomodel);
+
+	/*Finite element Analysis*/
+	void           Core(FemModel* femmodel);
+	ElementVector* CreateDVector(Element* element);
+	ElementMatrix* CreateJacobianMatrix(Element* element);
+	ElementMatrix* CreateKMatrix(Element* element);
+	ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+	void UpdateConstraints(FemModel* femmodel);
+	void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void SetConstraintsOnIce(Element* element);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 18231)
@@ -0,0 +1,236 @@
+#include "./ExtrudeFromBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ExtrudeFromBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+	}
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromBaseAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           ExtrudeFromBaseAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* ExtrudeFromBaseAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixSurface(element);
+	ElementMatrix* Ke3=CreateKMatrixBed(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  Jdet,D;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get dimension*/
+	int dim;
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(Bprime,gauss);
+		GetB(B,element,dim,xyz_list,gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(B,1,numnodes,1,
+					&D,1,1,0,
+					Bprime,1,numnodes,0,
+					&Ke->values[0],1);
+	} 
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
+
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[3];
+	IssmDouble *xyz_list_top = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list_top);
+	element->NormalTop(&normal[0],xyz_list_top);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussTop(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_top);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixBed(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[3];
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->NormalBase(&normal[0],xyz_list_base);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementVector* ExtrudeFromBaseAnalysis::CreatePVector(Element* element){/*{{{*/
+	return NULL;
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[(dim-1)*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+void ExtrudeFromBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int inputenum;
+	element->FindParam(&inputenum,InputToExtrudeEnum);
+	element->InputUpdateFromSolutionOneDof(solution,inputenum);
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file ExtrudeFromBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _ExtrudeFromBaseAnalysis_
+#define _ExtrudeFromBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ExtrudeFromBaseAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
+		ElementMatrix* CreateKMatrixBed(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 18231)
@@ -0,0 +1,236 @@
+#include "./ExtrudeFromTopAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ExtrudeFromTopAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ExtrudeFromTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+	}
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromTopAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           ExtrudeFromTopAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* ExtrudeFromTopAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* ExtrudeFromTopAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* ExtrudeFromTopAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixSurface(element);
+	ElementMatrix* Ke3=CreateKMatrixBed(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* ExtrudeFromTopAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(Bprime,gauss);
+		GetB(B,element,dim,xyz_list,gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(B,1,numnodes,1,
+					&D,1,1,0,
+					Bprime,1,numnodes,0,
+					&Ke->values[0],1);
+	} 
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* ExtrudeFromTopAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
+
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[2];
+	IssmDouble *xyz_list_top = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list_top);
+	element->NormalTop(&normal[0],xyz_list_top);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussTop(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_top);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* ExtrudeFromTopAnalysis::CreateKMatrixBed(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[3];
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->NormalBase(&normal[0],xyz_list_base);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementVector* ExtrudeFromTopAnalysis::CreatePVector(Element* element){/*{{{*/
+	return NULL;
+}/*}}}*/
+void ExtrudeFromTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[(dim-1)*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+void ExtrudeFromTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void ExtrudeFromTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void ExtrudeFromTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int inputenum;
+	element->FindParam(&inputenum,InputToExtrudeEnum);
+	element->InputUpdateFromSolutionOneDof(solution,inputenum);
+}/*}}}*/
+void ExtrudeFromTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file ExtrudeFromTopAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _ExtrudeFromTopAnalysis_
+#define _ExtrudeFromTopAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ExtrudeFromTopAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
+		ElementMatrix* CreateKMatrixBed(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 18231)
@@ -0,0 +1,404 @@
+#include "./FreeSurfaceBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  FreeSurfaceBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Finite element type*/
+	int finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	if(iomodel->domaindim==3){
+		iomodel->FetchDataToInput(elements,VzEnum);
+	}
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbase=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceBaseAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           FreeSurfaceBaseAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* FreeSurfaceBaseAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* FreeSurfaceBaseAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* FreeSurfaceBaseAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         domaintype,dim,stabilization;
+	Element*    basalelement = NULL;
+	IssmDouble *xyz_list  = NULL;
+	IssmDouble  Jdet,D_scalar,dt,h;
+	IssmDouble  vel,vx,vy;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			dim = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			dim = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNew<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=basalelement->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=NULL;
+	if(dim>1){vy_input = basalelement->GetInput(VyEnum); _assert_(vy_input);}
+	h = basalelement->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		if(dim==2) vy_input->GetInputValue(&vy,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetB(B,basalelement,dim,xyz_list,gauss);
+		GetBprime(Bprime,basalelement,dim,xyz_list,gauss);
+
+		D_scalar=dt*gauss->weight*Jdet;
+		for(int i=0;i<dim*dim;i++) D[i]=0.;
+		D[0] = D_scalar*vx;
+		if(dim==2) D[1*dim+1] = D_scalar*vy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			if(dim==1){
+			 vel=fabs(vx)+1.e-8;
+			 D[0] = h/(2.*vel)*vx*vx;
+			}
+			else{
+			 vel=sqrt(vx*vx+vy*vy)+1.e-8;
+			 D[0*dim+0]=h/(2*vel)*vx*vx;
+			 D[1*dim+0]=h/(2*vel)*vy*vx;
+			 D[0*dim+1]=h/(2*vel)*vx*vy;
+			 D[1*dim+1]=h/(2*vel)*vy*vy;
+			}
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			if(dim==1){
+				vx_input->GetInputAverage(&vx);
+				D[0]=h/2.*fabs(vx);
+			}
+			else{
+				vx_input->GetInputAverage(&vx);
+				vy_input->GetInputAverage(&vy);
+				D[0*dim+0]=h/2.0*fabs(vx);
+				D[1*dim+1]=h/2.0*fabs(vy);
+			}
+		}
+		if(stabilization==1 || stabilization==2){
+			for(int i=0;i<dim*dim;i++) D[i]=D_scalar*D[i];
+			TripleMultiply(Bprime,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* FreeSurfaceBaseAnalysis::CreatePVector(Element* element){/*{{{*/
+	/*Intermediaries*/
+	int         domaintype,dim;
+	IssmDouble  Jdet,dt;
+	IssmDouble  gmb,fmb,mb,bed,phi,vz;
+	Element*    basalelement = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			dim = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			dim = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* groundedice_input   = basalelement->GetInput(MaskGroundediceLevelsetEnum);              _assert_(groundedice_input);
+	Input* gmb_input           = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
+	Input* fmb_input           = basalelement->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
+	Input* base_input          = basalelement->GetInput(BaseEnum);                                 _assert_(base_input);
+	Input* vz_input      = NULL;
+	switch(dim){
+		case 1: vz_input = basalelement->GetInput(VyEnum); _assert_(vz_input); break;
+		case 2: vz_input = basalelement->GetInput(VzEnum); _assert_(vz_input); break;
+		default: _error_("not implemented");
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		vz_input->GetInputValue(&vz,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
+		base_input->GetInputValue(&bed,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
+		if(phi>0) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb) + dt*vz)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			B[numnodes*j+i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	element->InputUpdateFromSolutionOneDof(solution,BaseEnum);
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	/*Intermediary*/
+	IssmDouble phi,isonbase,base;
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(!element->IsOnBase()) continue;
+
+		int             numnodes = element->GetNumberOfNodes();
+		Input* groundedice_input = element->GetInput(MaskGroundediceLevelsetEnum);  _assert_(groundedice_input);
+		Input* onbase_input       = element->GetInput(MeshVertexonbaseEnum);          _assert_(onbase_input);
+		Input* base_input        = element->GetInput(BaseEnum);                     _assert_(base_input);
+
+		Gauss* gauss=element->NewGauss();
+		for(int iv=0;iv<numnodes;iv++){
+			gauss->GaussNode(element->GetElementType(),iv);
+			onbase_input->GetInputValue(&isonbase,gauss);
+			if(isonbase==1.){
+				groundedice_input->GetInputValue(&phi,gauss);
+				if(phi>=0.){
+					base_input->GetInputValue(&base,gauss);
+					element->nodes[iv]->ApplyConstraint(0,base);
+				}
+				else{
+					element->nodes[iv]->DofInFSet(0);
+				}
+			}
+		}
+		delete gauss;
+	}
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file FreeSurfaceBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _FreeSurfaceBaseAnalysis_
+#define _FreeSurfaceBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class FreeSurfaceBaseAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 18231)
@@ -0,0 +1,379 @@
+#include "./FreeSurfaceTopAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  FreeSurfaceTopAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void FreeSurfaceTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void FreeSurfaceTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	int smb_model;
+	int finiteelement = P1Enum;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&smb_model,SurfaceforcingsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+	}
+	if(iomodel->domaindim==3){
+		iomodel->FetchDataToInput(elements,VzEnum);
+	}
+	switch(smb_model){
+		case SMBEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum,0.);
+			break;
+		default:
+			/*Nothing for now*/
+			;
+	}
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceTopAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonsurface=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonsurface,NULL,NULL,MeshVertexonsurfaceEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceTopAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonsurface,MeshVertexonsurfaceEnum);
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           FreeSurfaceTopAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* FreeSurfaceTopAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* FreeSurfaceTopAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* FreeSurfaceTopAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         domaintype,dim,stabilization;
+	Element*    topelement = NULL;
+	IssmDouble *xyz_list  = NULL;
+	IssmDouble  Jdet,D_scalar,dt,h;
+	IssmDouble  vel,vx,vy;
+
+	/*Get top element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			topelement = element;
+			dim = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnSurface()) return NULL;
+			topelement = element->SpawnTopElement();
+			dim = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnSurface()) return NULL;
+			topelement = element->SpawnTopElement();
+			dim = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = topelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = topelement->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNew<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+	topelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	topelement->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=topelement->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=NULL;
+	if(dim>1){vy_input = topelement->GetInput(VyEnum); _assert_(vy_input);}
+	h = topelement->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		topelement->NodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		if(dim==2) vy_input->GetInputValue(&vy,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetB(B,topelement,dim,xyz_list,gauss);
+		GetBprime(Bprime,topelement,dim,xyz_list,gauss);
+
+		D_scalar=dt*gauss->weight*Jdet;
+		for(int i=0;i<dim*dim;i++) D[i]=0.;
+		D[0] = D_scalar*vx;
+		if(dim==2) D[1*dim+1]=D_scalar*vy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			if(dim==1){
+				vel=fabs(vx)+1.e-8;
+				D[0] = h/(2.*vel)*vx*vx;
+			}
+			else{
+				vel=sqrt(vx*vx+vy*vy)+1.e-8;
+				D[0*dim+0]=h/(2*vel)*vx*vx;
+				D[1*dim+0]=h/(2*vel)*vy*vx;
+				D[0*dim+1]=h/(2*vel)*vx*vy;
+				D[1*dim+1]=h/(2*vel)*vy*vy;
+			}
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			if(dim==1){
+				vx_input->GetInputAverage(&vx);
+				D[0]=h/2.*fabs(vx);
+			}
+			else{
+				vx_input->GetInputAverage(&vx);
+				vy_input->GetInputAverage(&vy);
+				D[0*dim+0]=h/2.0*fabs(vx);
+				D[1*dim+1]=h/2.0*fabs(vy);
+			}
+		}
+		if(stabilization==1 || stabilization==2){
+			for(int i=0;i<dim*dim;i++) D[i]=D_scalar*D[i];
+			TripleMultiply(Bprime,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* FreeSurfaceTopAnalysis::CreatePVector(Element* element){/*{{{*/
+	/*Intermediaries*/
+	int         domaintype,dim;
+	IssmDouble  Jdet,dt;
+	IssmDouble  ms,surface,vz;
+	Element*    topelement = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Get top element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			topelement = element;
+			dim = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnSurface()) return NULL;
+			topelement = element->SpawnTopElement();
+			dim = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnSurface()) return NULL;
+			topelement = element->SpawnTopElement();
+			dim = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = topelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = topelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+	topelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* ms_input      = topelement->GetInput(SurfaceforcingsMassBalanceEnum);  _assert_(ms_input);
+	Input* surface_input = topelement->GetInput(SurfaceEnum);                     _assert_(surface_input);
+	Input* vz_input      = NULL;
+	switch(dim){
+		case 1: vz_input = topelement->GetInput(VyEnum); _assert_(vz_input); break;
+		case 2: vz_input = topelement->GetInput(VzEnum); _assert_(vz_input); break;
+		default: _error_("not implemented");
+	}
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		topelement->NodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(surface + dt*ms + dt*vz)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	return pe;
+
+}/*}}}*/
+void FreeSurfaceTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			B[numnodes*j+i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void FreeSurfaceTopAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void FreeSurfaceTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void FreeSurfaceTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void FreeSurfaceTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	element->InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
+}/*}}}*/
+void FreeSurfaceTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file FreeSurfaceTopAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _FreeSurfaceTopAnalysis_
+#define _FreeSurfaceTopAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class FreeSurfaceTopAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.cpp	(revision 18231)
@@ -0,0 +1,68 @@
+#include "./GiaAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  GiaAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void GiaAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void GiaAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GiaMantleViscosityEnum);
+	iomodel->FetchDataToInput(elements,GiaLithosphereThicknessEnum);
+}/*}}}*/
+void GiaAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	::CreateNodes(nodes,iomodel,GiaAnalysisEnum,P1Enum);
+}/*}}}*/
+void GiaAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/*No constraints*/
+}/*}}}*/
+void GiaAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           GiaAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* GiaAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* GiaAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* GiaAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+ElementVector* GiaAnalysis::CreatePVector(Element* element){/*{{{*/
+_error_("not implemented yet");
+}/*}}}*/
+void GiaAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void GiaAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void GiaAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void GiaAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/GiaAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file GiaAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _GiaAnalysis_
+#define _GiaAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class GiaAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 18231)
@@ -0,0 +1,766 @@
+#include "./HydrologyDCEfficientAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyDCEfficientAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int         hydrology_model;
+	bool        isefficientlayer;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Nothing for now*/
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+
+	/*Now, do we really want DC?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,EplHeadEnum);
+	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcEplInitialThicknessEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcEplMaxThicknessEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcSedimentTransmitivityEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcEplThicknessEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Now, do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyDCEfficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*Nothing for now*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void HydrologyDCEfficientAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* HydrologyDCEfficientAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* HydrologyDCEfficientAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* HydrologyDCEfficientAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	bool     active_element;
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	Input* active_element_input = basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
+
+	/*Check that all nodes are active, else return empty matrix*/
+	if(!active_element) {
+	if(domaintype!=Domain2DhorizontalEnum){
+			basalelement->DeleteMaterials(); 
+			delete basalelement;
+		}
+		return NULL;
+	}
+	/* Intermediaries */
+	IssmDouble  D_scalar,Jdet,dt;
+	IssmDouble  epl_thickness;
+	IssmDouble  transfer;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble     D[2][2]={0.};
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* thickness_input = basalelement->GetInput(HydrologydcEplThicknessEnum);          _assert_(thickness_input);
+	Input* sed_head_input  = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input  = basalelement->GetInput(EplHeadEnum);
+	Input* sed_trans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
+	Input* residual_input  = basalelement->GetInput(SedimentHeadResidualEnum);
+
+	IssmDouble epl_specificstoring   = EplSpecificStoring(basalelement);
+	IssmDouble epl_conductivity      = basalelement->GetMaterialParameter(HydrologydcEplConductivityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss           ->GaussPoint(ig);
+		basalelement    ->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		thickness_input ->GetInputValue(&epl_thickness,gauss);
+
+		/*Diffusivity*/
+		D_scalar=epl_conductivity*epl_thickness*gauss->weight*Jdet;
+		if(dt!=0.) D_scalar=D_scalar*dt;
+		D[0][0]=D_scalar;
+		D[1][1]=D_scalar;
+		GetB(B,basalelement,xyz_list,gauss); 
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Transient*/
+		if(dt!=0.){
+			basalelement->NodalFunctions(&basis[0],gauss);
+			D_scalar=epl_specificstoring*epl_thickness*gauss->weight*Jdet;
+			TripleMultiply(basis,numnodes,1,0,
+						&D_scalar,1,1,0,
+						basis,1,numnodes,0,
+						&Ke->values[0],1);
+			
+			/*Transfer EPL part*/
+			transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,thickness_input,sed_head_input,epl_head_input,sed_trans_input,residual_input);
+			D_scalar=transfer*gauss->weight*Jdet*dt;
+			TripleMultiply(basis,numnodes,1,0,
+										 &D_scalar,1,1,0,
+										 basis,1,numnodes,0,
+										 &Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+
+}/*}}}*/
+ElementVector* HydrologyDCEfficientAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	bool     active_element;
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	Input* active_element_input = basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
+
+	/*Check that all nodes are active, else return empty matrix*/
+	if(!active_element) {
+	if(domaintype!=Domain2DhorizontalEnum){
+			basalelement->DeleteMaterials(); 
+			delete basalelement;
+		}
+		return NULL;
+	}
+	/*Intermediaries */
+	IssmDouble dt,scalar,water_head;
+	IssmDouble transfer;
+	IssmDouble epl_thickness;
+	IssmDouble Jdet;
+	IssmDouble residual,connectivity;
+
+	IssmDouble *xyz_list     = NULL;
+	Input*      old_wh_input = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = basalelement->GetNumberOfNodes();
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);	
+
+	Input* thickness_input = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(thickness_input);
+	Input* sed_head_input  = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input  = basalelement->GetInput(EplHeadEnum);
+	Input* sed_trans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
+	Input* residual_input  = basalelement->GetInput(SedimentHeadResidualEnum);    _assert_(residual_input);
+	if(dt!= 0.){old_wh_input = basalelement->GetInput(EplHeadOldEnum);            _assert_(old_wh_input);}
+
+	IssmDouble epl_specificstoring = EplSpecificStoring(basalelement);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement ->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement ->NodalFunctions(basis,gauss);
+
+		/*Transient and transfer terms*/
+		if(dt!=0.){
+			old_wh_input    ->GetInputValue(&water_head,gauss);
+			thickness_input ->GetInputValue(&epl_thickness,gauss);
+			
+			/*Dealing with the epl part of the transfer term*/
+			transfer=GetHydrologyPVectorTransfer(basalelement,gauss,thickness_input,sed_head_input,epl_head_input,sed_trans_input,residual_input);
+			scalar = Jdet*gauss->weight*((water_head*epl_specificstoring*epl_thickness)+(transfer*dt));
+			for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
+		}
+	}
+	delete gauss;
+
+	/*	Add residual if necessary*/
+	gauss=basalelement->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		connectivity = IssmDouble(basalelement->VertexConnectivity(iv));
+		residual_input->GetInputValue(&residual,gauss);
+		pe->values[iv]+=residual/connectivity;
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,EplHeadEnum);
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype,i;
+	Element*   basalelement=NULL;
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	if(domaintype!=Domain2DhorizontalEnum){
+		if(!element->IsOnBase()) return;
+		basalelement=element->SpawnBasalElement();
+	}
+	else{
+		basalelement = element;
+	}
+	
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* eplHeads    = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numnodes;i++){
+		eplHeads[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(eplHeads[i])) _error_("NaN found in solution vector");
+	}
+	/*Add input to the element: */
+	element->AddBasalInput(EplHeadEnum,eplHeads,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(eplHeads);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+} /*}}}*/
+void HydrologyDCEfficientAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
+/*Intermediaries*/
+IssmDouble HydrologyDCEfficientAnalysis::EplSpecificStoring(Element* element){/*{{{*/
+	IssmDouble rho_freshwater        = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble g                     = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble epl_porosity          = element->GetMaterialParameter(HydrologydcEplPorosityEnum);
+	IssmDouble epl_compressibility   = element->GetMaterialParameter(HydrologydcEplCompressibilityEnum);
+	IssmDouble water_compressibility = element->GetMaterialParameter(HydrologydcWaterCompressibilityEnum);
+	return rho_freshwater*g*epl_porosity*(water_compressibility+(epl_compressibility/epl_porosity));		 
+}/*}}}*/
+IssmDouble HydrologyDCEfficientAnalysis::SedimentStoring(Element* element){/*{{{*/
+	IssmDouble rho_freshwater           = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble g                        = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble sediment_porosity        = element->GetMaterialParameter(HydrologydcSedimentPorosityEnum);
+	IssmDouble sediment_thickness       = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_compressibility = element->GetMaterialParameter(HydrologydcSedimentCompressibilityEnum);
+	IssmDouble water_compressibility    = element->GetMaterialParameter(HydrologydcWaterCompressibilityEnum);
+	return rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));		 
+}/*}}}*/
+IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input){/*{{{*/
+	
+	int transfermethod;
+	IssmDouble epl_thickness;
+	IssmDouble epl_head,sed_head;
+	IssmDouble sediment_transmitivity;
+	IssmDouble leakage,residual,transfer;
+
+	IssmDouble sediment_thickness  = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_storing    = SedimentStoring(element);
+ 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+
+	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+	/*Switch between the different transfer methods cases*/
+	switch(transfermethod){
+	case 0:
+		/*Just keepping the transfer to zero*/
+		transfer=0.0;
+		break;
+	case 1:
+		_assert_(epl_thick_input); 
+		_assert_(sed_head_input); 
+		_assert_(epl_head_input); 
+		_assert_(sed_trans_input); 
+		_assert_(residual_input); 
+		/* get input */
+		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		sed_head_input->GetInputValue(&sed_head,gauss);
+		epl_head_input->GetInputValue(&epl_head,gauss);
+		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
+		residual_input->GetInputValue(&residual,gauss);
+		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
+		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); 
+		/* if(epl_head>sed_head){ */
+		/* 	if(residual>0.0){	 */
+		/* 		transfer=0.0; */
+		/* 	} */
+		/* 	else{ */
+		/* 		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 	} */
+		/* } */
+		/* else{ */
+		/* 	transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 	//transfer=(sediment_storing*sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* } */
+		break;
+	default:
+		_error_("no case higher than 1 for the Transfer method");
+	}
+	
+	return transfer;
+}/*}}}*/
+IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input){/*{{{*/
+
+	int transfermethod;
+	IssmDouble epl_thickness;
+	IssmDouble epl_head,sediment_head;
+	IssmDouble sediment_transmitivity;
+	IssmDouble leakage,residual,transfer;
+
+	IssmDouble sediment_thickness = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_storing   = SedimentStoring(element);
+ 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+
+	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+	/*Switch between the different transfer methods cases*/
+	switch(transfermethod){
+	case 0:
+		/*Just keepping the transfer to zero*/
+		transfer=0.0;
+		break;
+	case 1:
+		_assert_(epl_thick_input); 
+		_assert_(sed_head_input); 
+		_assert_(epl_head_input); 
+		_assert_(sed_trans_input); 
+		_assert_(residual_input); 
+		/* get input */
+		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		sed_head_input->GetInputValue(&sediment_head,gauss);
+		epl_head_input->GetInputValue(&epl_head,gauss);
+		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
+		residual_input->GetInputValue(&residual,gauss);
+		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
+		transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage);
+		/* if(epl_head>sediment_head){ */
+		/* 	if(residual>0.0){	 */
+		/* 		transfer=0.0; */
+		/* 	} */
+		/* 	else{ */
+		/* 		transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
+		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
+		/* 	} */
+		/* } */
+		/* else{ */
+		/* 	transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
+		/* 	//transfer=(sediment_storing*sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
+		/* } */
+		break;
+	default:
+		_error_("no case higher than 1 for the Transfer method");
+	}
+	return transfer;
+}/*}}}*/
+
+void HydrologyDCEfficientAnalysis::ComputeEPLThickness(FemModel* femmodel){/*{{{*/
+
+	bool        active_element;
+	int         domaintype;
+	IssmDouble  dt,A,B;
+	IssmDouble  EPLgrad2;
+	IssmDouble  EPL_N;
+
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	for(int j=0;j<femmodel->elements->Size();j++){
+		
+		Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
+		
+		switch(domaintype){
+		case Domain2DhorizontalEnum:
+			if(!element->IsOnBase()) return;			
+			B = element->GetMaterialParameter(MaterialsRheologyBbarEnum);
+			break;
+		case Domain3DEnum:
+			B = element->GetMaterialParameter(MaterialsRheologyBEnum);
+			break;
+		default:
+		_error_("not Implemented Yet");
+		}
+			
+		int         numnodes      = element->GetNumberOfNodes();
+		IssmDouble* thickness     = xNew<IssmDouble>(numnodes);
+		IssmDouble* eplhead       = xNew<IssmDouble>(numnodes);
+		IssmDouble* epl_slopeX    = xNew<IssmDouble>(numnodes);
+		IssmDouble* epl_slopeY    = xNew<IssmDouble>(numnodes);
+		IssmDouble* old_thickness = xNew<IssmDouble>(numnodes);
+		IssmDouble* ice_thickness = xNew<IssmDouble>(numnodes);
+		IssmDouble* bed           = xNew<IssmDouble>(numnodes);
+
+		Input* 	active_element_input=element->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);		
+		active_element_input->GetInputValue(&active_element);
+		element->FindParam(&dt,TimesteppingTimeStepEnum);
+	
+		/*For now, assuming just one way to compute EPL thickness*/
+		IssmDouble gravity          = element->GetMaterialParameter(ConstantsGEnum);
+		IssmDouble rho_water        = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+		IssmDouble rho_ice          = element->GetMaterialParameter(MaterialsRhoIceEnum);
+		IssmDouble n                =	element->GetMaterialParameter(MaterialsRheologyNEnum);
+		IssmDouble latentheat       = element->GetMaterialParameter(MaterialsLatentheatEnum);
+		IssmDouble epl_conductivity = element->GetMaterialParameter(HydrologydcEplConductivityEnum);
+		IssmDouble init_thick       =	element->GetMaterialParameter(HydrologydcEplInitialThicknessEnum);
+		IssmDouble max_thick        =	element->GetMaterialParameter(HydrologydcEplMaxThicknessEnum);
+		
+		A=pow(B,-n);
+		
+		element->GetInputListOnVertices(&eplhead[0],EplHeadEnum);
+		element->GetInputListOnVertices(&epl_slopeX[0],EplHeadSlopeXEnum); 
+		element->GetInputListOnVertices(&epl_slopeY[0],EplHeadSlopeYEnum);
+		element->GetInputListOnVertices(&old_thickness[0],HydrologydcEplThicknessOldEnum);
+		element->GetInputListOnVertices(&ice_thickness[0],ThicknessEnum);
+		element->GetInputListOnVertices(&bed[0],BaseEnum);
+			
+		if(!active_element){
+			
+			/*Keeping thickness to initial value if EPL is not active*/
+			for(int i=0;i<numnodes;i++){
+				thickness[i]=init_thick;
+			}
+		}
+		else{
+			for(int i=0;i<numnodes;i++){
+				
+				/*Compute first the effective pressure in the EPL*/
+				EPL_N=gravity*((rho_ice*ice_thickness[i])-(rho_water*(eplhead[i]-bed[i])));
+				if(EPL_N<0.0)EPL_N=0.0;
+				/*Get then the square of the gradient of EPL heads*/
+				EPLgrad2 = (epl_slopeX[i]+epl_slopeY[i])*(epl_slopeX[i]+epl_slopeY[i]);
+				
+				/*And proceed to the real thing*/
+				thickness[i] = old_thickness[i]*(1+((rho_water*gravity*dt)/(rho_ice*latentheat))*epl_conductivity*EPLgrad2-2.0*(A*dt/(pow(n,n)))*(pow(EPL_N,n)));
+				
+				/*Take care of otherthikening*/
+				if(thickness[i]>max_thick){
+					thickness[i] = max_thick;
+				}
+			}
+		}
+		element->AddInput(HydrologydcEplThicknessEnum,thickness,element->GetElementType());
+		xDelete<IssmDouble>(thickness);
+		xDelete<IssmDouble>(eplhead);
+		xDelete<IssmDouble>(epl_slopeX);
+		xDelete<IssmDouble>(epl_slopeY);
+		xDelete<IssmDouble>(old_thickness);
+		xDelete<IssmDouble>(ice_thickness);
+		xDelete<IssmDouble>(bed);
+	}
+}
+/*}}}*/
+void HydrologyDCEfficientAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dN/dx ]
+	 *          [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void  HydrologyDCEfficientAnalysis::HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask,Element* element){
+
+	bool        active_element;
+	int         i,j;
+	int         domaintype;
+	IssmDouble  h_max;
+	IssmDouble  sedheadmin;
+	Element*   basalelement=NULL;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+
+	int         numnodes      =basalelement->GetNumberOfNodes();
+	IssmDouble* epl_thickness =xNew<IssmDouble>(numnodes);
+	IssmDouble* old_active    =xNew<IssmDouble>(numnodes);
+	IssmDouble* sedhead       =xNew<IssmDouble>(numnodes);
+	IssmDouble* eplhead       =xNew<IssmDouble>(numnodes);
+	IssmDouble* residual      =xNew<IssmDouble>(numnodes);
+
+	IssmDouble init_thick =	basalelement->GetMaterialParameter(HydrologydcEplInitialThicknessEnum);
+
+	Input* active_element_input=basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
+
+	basalelement-> GetInputListOnVertices(&old_active[0],HydrologydcMaskEplactiveNodeEnum);	
+	basalelement-> GetInputListOnVertices(&epl_thickness[0],HydrologydcEplThicknessEnum);	
+	basalelement-> GetInputListOnVertices(&sedhead[0],SedimentHeadEnum);
+	basalelement-> GetInputListOnVertices(&eplhead[0],EplHeadEnum);
+	basalelement-> GetInputListOnVertices(&residual[0],SedimentHeadResidualEnum);
+
+	/*Get minimum sediment head of the element*/
+	sedheadmin=sedhead[0];
+	for(i=1;i<numnodes;i++) if(sedhead[i]<=sedheadmin)sedheadmin=sedhead[i];
+
+	for(i=0;i<numnodes;i++){
+		/*Activate EPL if residual is >0 */
+		if(residual[i]>0.){
+			vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+		}
+
+		/*If mask was already one, keep one*/
+		else if(old_active[i]>0.){
+			vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+			/*If epl thickness gets under 10-3 initial thickness, close the layer*/
+			if(epl_thickness[i]<0.001*init_thick){
+				vec_mask->SetValue(basalelement->nodes[i]->Sid(),0.,INS_VAL);
+				epl_thickness[i]=init_thick;
+			}
+		}
+		/*Increase of the efficient system is needed if the epl head reach the maximum value (sediment max value for now)*/
+		GetHydrologyDCInefficientHmax(&h_max,basalelement,basalelement->nodes[i]);
+		if(eplhead[i]>=h_max && active_element){
+			for(j=0;j<numnodes;j++){
+				if(old_active[j]>0.){
+					vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+				}
+				/*Increase of the domain is on the downstream node in term of sediment head*/
+				if(sedhead[j] == sedheadmin){
+					vec_mask->SetValue(basalelement->nodes[j]->Sid(),1.,INS_VAL);
+				}
+			}
+		}
+	}
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	xDelete<IssmDouble>(epl_thickness);
+	xDelete<IssmDouble>(old_active);
+	xDelete<IssmDouble>(sedhead);
+	xDelete<IssmDouble>(eplhead);
+	xDelete<IssmDouble>(residual);
+}
+/*}}}*/
+void HydrologyDCEfficientAnalysis::HydrologyEPLGetActive(Vector<IssmDouble>* active_vec, Element* element){
+	/*Constants*/
+
+	int      domaintype;
+	Element*   basalelement=NULL;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+	
+	const int   numnodes = basalelement->GetNumberOfNodes();
+	IssmDouble  flag     = 0.;
+	IssmDouble* active   = xNew<IssmDouble>(numnodes);
+		
+	basalelement->GetInputListOnVertices(&active[0],HydrologydcMaskEplactiveNodeEnum);
+	
+	for(int i=0;i<numnodes;i++) flag+=active[i];
+
+	if(flag>0.){
+		for(int i=0;i<numnodes;i++){
+			active_vec->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+		}
+	}
+	else{
+		/*Do not do anything: at least one node is active for this element but this element is not solved for*/
+	}
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	xDelete<IssmDouble>(active);
+}
+
+void HydrologyDCEfficientAnalysis::GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode){/*{{{*/
+	
+	int        hmax_flag;
+	IssmDouble h_max;
+	IssmDouble rho_ice,rho_water;
+	IssmDouble thickness,bed;
+	/*Get the flag to the limitation method*/
+	element->FindParam(&hmax_flag,HydrologydcSedimentlimitFlagEnum);
+	
+	/*Switch between the different cases*/
+	switch(hmax_flag){
+	case 0:
+		h_max=1.0e+10;
+		break;
+	case 1:
+		element->FindParam(&h_max,HydrologydcSedimentlimitEnum);
+		break;
+	case 2:
+		/*Compute max*/
+		rho_water = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+		rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+		element-> GetInputValue(&thickness,innode,ThicknessEnum);
+		element-> GetInputValue(&bed,innode,BaseEnum);
+		h_max=((rho_ice*thickness)/rho_water)+bed;
+		break;
+	case 3:
+		_error_("Using normal stress  not supported yet");
+		break;
+	default:
+		_error_("no case higher than 3 for SedimentlimitFlag");
+	}
+	/*Assign output pointer*/
+	*ph_max=h_max;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 18231)
@@ -0,0 +1,45 @@
+/*! \file HydrologyDCEfficientAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyDCEfficientAnalysis_
+#define _HydrologyDCEfficientAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+class Node;
+class Input;
+class HydrologyDCEfficientAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*Intermediaries*/
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble EplSpecificStoring(Element* element);
+		IssmDouble SedimentStoring(Element* element);
+		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input);
+		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input);
+		void HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask,Element* element);
+		void HydrologyEPLGetActive(Vector<IssmDouble>* active_vec, Element* element);
+		void GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode);
+		void ComputeEPLThickness(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 18231)
@@ -0,0 +1,707 @@
+#include "./HydrologyDCInefficientAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../classes/Node.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyDCInefficientAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int         hydrology_model;
+	int         sedimentlimit_flag;
+	int         transfer_flag;
+	int         penalty_lock;
+	int         hydro_maxiter;
+	bool        isefficientlayer;
+	IssmDouble  sedimentlimit;
+	IssmDouble  penalty_factor;
+	IssmDouble  leakagefactor;
+	IssmDouble  rel_tol;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	iomodel->FetchData(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	iomodel->FetchData(&sedimentlimit_flag,HydrologydcSedimentlimitFlagEnum);
+	iomodel->FetchData(&transfer_flag,HydrologydcTransferFlagEnum);
+	iomodel->FetchData(&penalty_factor,HydrologydcPenaltyFactorEnum);
+	iomodel->FetchData(&rel_tol,HydrologydcRelTolEnum);
+	iomodel->FetchData(&penalty_lock,HydrologydcPenaltyLockEnum);
+	iomodel->FetchData(&hydro_maxiter,HydrologydcMaxIterEnum);
+
+	if(sedimentlimit_flag==1){
+		iomodel->FetchData(&sedimentlimit,HydrologydcSedimentlimitEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcSedimentlimitEnum,sedimentlimit));
+	}
+
+	if(transfer_flag==1){
+		iomodel->FetchData(&leakagefactor,HydrologydcLeakageFactorEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcLeakageFactorEnum,leakagefactor));
+	}
+
+	parameters->AddObject(new DoubleParam(HydrologydcPenaltyFactorEnum,penalty_factor));
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(new BoolParam(HydrologydcIsefficientlayerEnum,isefficientlayer));
+	parameters->AddObject(new IntParam(HydrologydcSedimentlimitFlagEnum,sedimentlimit_flag));
+	parameters->AddObject(new IntParam(HydrologydcTransferFlagEnum,transfer_flag));
+	parameters->AddObject(new DoubleParam(HydrologydcRelTolEnum,rel_tol));
+	parameters->AddObject(new IntParam(HydrologydcPenaltyLockEnum,penalty_lock));
+	parameters->AddObject(new IntParam(HydrologydcMaxIterEnum,hydro_maxiter));
+
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcBasalMoulinInputEnum);
+	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
+	iomodel->FetchDataToInput(elements,HydrologydcSedimentTransmitivityEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+
+	if(isefficientlayer)iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveNodeEnum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyDCInefficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*retrieve some parameters: */
+	int hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpcsedimentHeadEnum,HydrologyDCInefficientAnalysisEnum,P1Enum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
+
+	//create penalties for nodes: no node can have water above the max
+	CreateSingleNodeToElementConnectivity(iomodel);
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if (iomodel->domaintype!=Domain3DEnum){
+			/*keep only this partition's nodes:*/
+			if(iomodel->my_vertices[i]){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}
+		}
+		else if(reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[i])){
+			if(iomodel->my_vertices[i]){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}	
+		}
+	}
+	iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           HydrologyDCInefficientAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* HydrologyDCInefficientAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* HydrologyDCInefficientAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* HydrologyDCInefficientAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	bool        active_element,isefficientlayer;
+	IssmDouble  D_scalar,Jdet,dt;
+	IssmDouble  sediment_transmitivity;
+	IssmDouble  transfer;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Define transfer related variables*/
+	Input* active_element_input =NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble     D[2][2]= {0.};
+
+	/*Retrieve all inputs and parameters*/
+	basalelement ->GetVerticesCoordinates(&xyz_list);
+	basalelement ->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement ->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+	Input* epl_thick_input   = basalelement->GetInput(HydrologydcEplThicknessEnum);
+	Input* sed_head_input    = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input    = basalelement->GetInput(EplHeadEnum);
+	Input* thickness_input   = basalelement->GetInput(ThicknessEnum);
+	Input* base_input         = basalelement->GetInput(BaseEnum);
+	Input* SedTrans_input    = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
+	IssmDouble sediment_storing = SedimentStoring(basalelement);
+	/*Transfer related Inputs*/
+	if(isefficientlayer){
+		active_element_input = basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	}
+	
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss -> begin();ig<gauss->end();ig++){
+		gauss          -> GaussPoint(ig);
+		basalelement   -> JacobianDeterminant(&Jdet,xyz_list,gauss);
+		SedTrans_input -> GetInputValue(&sediment_transmitivity,gauss);
+		/*Diffusivity*/
+		D_scalar=sediment_transmitivity*gauss->weight*Jdet;
+		if(dt!=0.) D_scalar=D_scalar*dt;
+		D[0][0]=D_scalar;
+		D[1][1]=D_scalar;
+		GetB(B,basalelement,xyz_list,gauss); 
+		TripleMultiply(B,2,numnodes,1,
+									 &D[0][0],2,2,0,
+									 B,2,numnodes,0,
+									 &Ke->values[0],1);
+
+		/*Transient*/
+		if(dt!=0.){
+			basalelement->NodalFunctions(&basis[0],gauss);
+			D_scalar=sediment_storing*gauss->weight*Jdet;
+			TripleMultiply(basis,numnodes,1,0,
+										 &D_scalar,1,1,0,
+										 basis,1,numnodes,0,
+										 &Ke->values[0],1);
+			
+			/*Transfer EPL part*/
+			if(isefficientlayer){
+				active_element_input->GetInputValue(&active_element);
+				if(active_element){
+					transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,epl_thick_input,sed_head_input,epl_head_input,SedTrans_input,thickness_input,base_input);
+					basalelement->NodalFunctions(&basis[0],gauss);
+					D_scalar=transfer*gauss->weight*Jdet*dt;
+					TripleMultiply(basis,numnodes,1,0,
+												 &D_scalar,1,1,0,
+												 basis,1,numnodes,0,
+												 &Ke->values[0],1);
+				}
+			}
+		}
+	}
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* HydrologyDCInefficientAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	bool       active_element,isefficientlayer;
+	IssmDouble dt,scalar;
+	IssmDouble water_head;
+	IssmDouble water_load,transfer;
+	IssmDouble Jdet;
+
+	IssmDouble *xyz_list             = NULL;
+	Input*      old_wh_input         = NULL;
+	Input*      active_element_input = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+	Input* epl_thick_input   = basalelement->GetInput(HydrologydcEplThicknessEnum);
+	Input* sed_head_input    = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input    = basalelement->GetInput(EplHeadEnum);
+	Input* sed_trans_input   = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
+	Input* thickness_input   = basalelement->GetInput(ThicknessEnum);
+	Input* base_input        = basalelement->GetInput(BaseEnum);
+	Input* water_input       = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
+	if(dt!= 0.){old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                     _assert_(old_wh_input);}
+
+	IssmDouble sediment_storing    = SedimentStoring(basalelement);
+
+	/*Transfer related Inputs*/
+	if(isefficientlayer){
+		active_element_input = basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+	
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		/*Loading term*/
+		water_input->GetInputValue(&water_load,gauss);
+
+		scalar = Jdet*gauss->weight*(water_load);
+
+		if(dt!=0.) scalar = scalar*dt;
+		for(int i=0;i<numnodes;i++){
+			pe->values[i]+=scalar*basis[i];
+		}
+			
+		/*Transient and transfer terms*/
+		if(dt!=0.){
+			old_wh_input    ->GetInputValue(&water_head,gauss);
+			if(isefficientlayer){
+				/*Dealing with the sediment part of the transfer term*/
+				active_element_input->GetInputValue(&active_element);
+				if(active_element){
+					transfer=GetHydrologyPVectorTransfer(basalelement,gauss,epl_thick_input,sed_head_input,epl_head_input,sed_trans_input,thickness_input,base_input);
+				}
+				else{
+					transfer=0.0;
+				}
+				scalar = Jdet*gauss->weight*((water_head*sediment_storing)+(dt*transfer));
+				for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
+			}
+			else{
+				scalar = Jdet*gauss->weight*(water_head*sediment_storing);
+				for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
+			}
+		}
+	}
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dN/dx ]
+	 *          [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,SedimentHeadEnum);
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int        domaintype;
+	bool       converged;
+	int*       doflist=NULL;
+	Element*   basalelement=NULL;
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){
+		if(!element->IsOnBase()) return;
+		basalelement=element->SpawnBasalElement();
+	}
+	else{
+		basalelement = element;
+	}
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values   = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(numnodes);
+	IssmDouble* residual = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i] =solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*If converged keep the residual in mind, also compute effective pressure*/
+	basalelement->GetInputValue(&converged,ConvergedEnum);
+
+	/*Get inputs*/
+	if(converged){
+		IssmDouble  penalty_factor,kmax,kappa,h_max;
+		IssmDouble* thickness = xNew<IssmDouble>(numnodes);
+		IssmDouble* base      = xNew<IssmDouble>(numnodes);
+
+		basalelement->FindParam(&kmax,HydrologySedimentKmaxEnum);
+		basalelement->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+		IssmDouble rho_freshwater = basalelement->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+		IssmDouble rho_ice        = basalelement->GetMaterialParameter(MaterialsRhoIceEnum);
+		IssmDouble g              = basalelement->GetMaterialParameter(ConstantsGEnum);
+		
+		basalelement->GetInputListOnVertices(thickness,ThicknessEnum);
+		basalelement->GetInputListOnVertices(base,BaseEnum);
+
+		kappa=kmax*pow(10.,penalty_factor);
+
+		for(int i=0;i<numnodes;i++){
+
+			GetHydrologyDCInefficientHmax(&h_max,basalelement,basalelement->GetNode(i));
+			if(values[i]>h_max) {
+				residual[i] = kappa*(values[i]-h_max);
+			}
+			else{
+				residual[i] = 0.;
+			}
+			pressure[i]=(rho_ice*g*thickness[i])-(rho_freshwater*g*(min(h_max,values[i])-base[i]));
+		}
+		xDelete<IssmDouble>(thickness);
+		xDelete<IssmDouble>(base);
+	}
+
+	/*Add input to the element: */
+	element->AddBasalInput(SedimentHeadEnum,values,P1Enum);
+	element->AddBasalInput(SedimentHeadResidualEnum,residual,P1Enum);
+	element->AddBasalInput(EffectivePressureEnum,pressure,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(residual);
+	xDelete<IssmDouble>(pressure);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void HydrologyDCInefficientAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
+/*Intermediaries*/
+IssmDouble HydrologyDCInefficientAnalysis::SedimentStoring(Element* element){/*{{{*/
+	IssmDouble rho_freshwater           = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble g                        = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble sediment_porosity        = element->GetMaterialParameter(HydrologydcSedimentPorosityEnum);
+	IssmDouble sediment_thickness       = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_compressibility = element->GetMaterialParameter(HydrologydcSedimentCompressibilityEnum);
+	IssmDouble water_compressibility    = element->GetMaterialParameter(HydrologydcWaterCompressibilityEnum);
+	return rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));		 
+}/*}}}*/
+
+IssmDouble HydrologyDCInefficientAnalysis::EplSpecificStoring(Element* element){/*{{{*/
+	IssmDouble rho_freshwater        = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble g                     = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble epl_porosity          = element->GetMaterialParameter(HydrologydcEplPorosityEnum);
+	IssmDouble epl_compressibility   = element->GetMaterialParameter(HydrologydcEplCompressibilityEnum);
+	IssmDouble water_compressibility = element->GetMaterialParameter(HydrologydcWaterCompressibilityEnum);
+	return rho_freshwater*g*epl_porosity*(water_compressibility+(epl_compressibility/epl_porosity));		 
+}/*}}}*/
+
+IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyDCInefficientHmax(Element* element, Gauss* gauss, Input* thick_input, Input* base_input){/*{{{*/
+	int        hmax_flag;
+	IssmDouble h_max;
+	IssmDouble rho_ice,rho_water;
+	IssmDouble thickness,bed;
+	/*Get the flag to the limitation method*/
+	element->FindParam(&hmax_flag,HydrologydcSedimentlimitFlagEnum);
+	
+	/*Switch between the different cases*/
+	switch(hmax_flag){
+	case 0:
+		h_max=1.0e+10;
+		break;
+	case 1:
+		element->FindParam(&h_max,HydrologydcSedimentlimitEnum);
+		break;
+	case 2:
+	
+		rho_water = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+		rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+
+		_assert_(thick_input);
+		_assert_(base_input);
+
+		/*Compute max*/
+		thick_input->GetInputValue(&thickness,gauss);
+		base_input->GetInputValue(&bed,gauss);
+		h_max=((rho_ice*thickness)/rho_water)+bed;
+		break;
+	case 3:
+		_error_("Using normal stress  not supported yet");
+		break;
+	default:
+		_error_("no case higher than 3 for SedimentlimitFlag");
+	}
+	return h_max;
+}/*}}}*/
+void  HydrologyDCInefficientAnalysis::GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode){/*{{{*/
+	
+	int        hmax_flag;
+	IssmDouble h_max;
+	IssmDouble rho_ice,rho_water;
+	IssmDouble thickness,bed;
+	/*Get the flag to the limitation method*/
+	element->FindParam(&hmax_flag,HydrologydcSedimentlimitFlagEnum);
+	
+	/*Switch between the different cases*/
+	switch(hmax_flag){
+	case 0:
+		h_max=1.0e+10;
+		break;
+	case 1:
+		element->FindParam(&h_max,HydrologydcSedimentlimitEnum);
+		break;
+	case 2:
+		/*Compute max*/
+		rho_water = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+		rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+		element->GetInputValue(&thickness,innode,ThicknessEnum);
+		element->GetInputValue(&bed,innode,BaseEnum);
+		h_max=((rho_ice*thickness)/rho_water)+bed;
+		break;
+	case 3:
+		_error_("Using normal stress  not supported yet");
+		break;
+	default:
+		_error_("no case higher than 3 for SedimentlimitFlag");
+	}
+	/*Assign output pointer*/
+	*ph_max=h_max;
+}
+/*}}}*/
+IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input){/*{{{*/
+
+	int transfermethod;
+	IssmDouble epl_thickness;
+	IssmDouble epl_head,sed_head;
+	IssmDouble sediment_transmitivity;
+	IssmDouble leakage,h_max,transfer;
+
+	IssmDouble sediment_thickness  = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_storing    = SedimentStoring(element);
+ 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+
+	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+	/*Switch between the different transfer methods cases*/
+	switch(transfermethod){
+	case 0:
+		/*Just keepping the transfer to zero*/
+		transfer=0.0;
+		break;
+	case 1:
+		
+		_assert_(epl_thick_input);
+		_assert_(sed_head_input);
+		_assert_(epl_head_input);
+		_assert_(sed_trans_input);
+		_assert_(thickness_input);
+		_assert_(base_input);
+
+		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		sed_head_input->GetInputValue(&sed_head,gauss);
+		epl_head_input->GetInputValue(&epl_head,gauss);
+		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
+		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
+		
+		transfer=(sediment_transmitivity)/(sediment_thickness*leakage);
+		
+		/* if(epl_head>sed_head){ */
+		/* 	h_max=GetHydrologyDCInefficientHmax(element,gauss,thickness_input,base_input); */
+		/* 	if(sed_head>=h_max){ */
+		/* 		transfer=0.0; */
+		/* 	} */
+		/* 	else{ */
+		/* 		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 	} */
+		/* } */
+		/* else{ */
+		/* 	transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* 	//transfer=(sediment_storing*sediment_transmitivity)/(sediment_thickness*leakage); */
+		/* } */
+		
+		break;
+	default:
+		_error_("no case higher than 1 for the Transfer method");
+	}
+	
+	return transfer;
+}/*}}}*/
+
+IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input){/*{{{*/
+
+	int transfermethod;
+	IssmDouble epl_thickness;
+	IssmDouble epl_head,sediment_head;
+	IssmDouble sediment_transmitivity;
+	IssmDouble leakage,h_max,transfer;
+
+	IssmDouble sediment_thickness = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
+	IssmDouble sediment_storing   = SedimentStoring(element);
+ 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+
+	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+	/*Switch between the different transfer methods cases*/
+	switch(transfermethod){
+	case 0:
+		/*Just keepping the transfer to zero*/
+		transfer=0.0;
+		break;
+	case 1:
+		
+		_assert_(epl_thick_input);
+		_assert_(sed_head_input);
+		_assert_(epl_head_input);
+		_assert_(sed_trans_input);
+		_assert_(thickness_input);
+		_assert_(base_input);
+
+		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		sed_head_input->GetInputValue(&sediment_head,gauss);
+		epl_head_input->GetInputValue(&epl_head,gauss);
+		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
+
+		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
+ 		transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage);
+		/* if(epl_head>sediment_head){ */
+		/* 	h_max=GetHydrologyDCInefficientHmax(element,gauss,thickness_input,base_input); */
+ 		/* 	if(sediment_head>=h_max){ */
+		/* 		transfer=0.0; */
+		/* 	} */
+		/* 	else{ */
+		/* 		transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
+		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
+		/* 	} */
+		/* } */
+		/* else{ */
+		/* 	transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
+		/* 	//transfer=(sediment_storing*sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
+		/* } */
+		break;
+	default:
+		_error_("no case higher than 1 for the Transfer method");
+	}
+	return transfer;
+}/*}}}*/
+
+void HydrologyDCInefficientAnalysis::ElementizeEplMask(FemModel* femmodel){/*{{{*/
+
+	bool     element_active;
+	Element* element=NULL;
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		int numvertices = element->GetNumberOfVertices();
+		Input* node_mask_input = element->GetInput(HydrologydcMaskEplactiveNodeEnum);
+		if(node_mask_input->Max()>0.) {
+			element_active = true;
+		}
+		else{
+			element_active = false;
+		}
+		element->AddInput(new BoolInput(HydrologydcMaskEplactiveEltEnum,element_active));
+	}
+}/*}}}*/
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 18231)
@@ -0,0 +1,44 @@
+/*! \file HydrologyDCInefficientAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyDCInefficientAnalysis_
+#define _HydrologyDCInefficientAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+class Node; 
+class Input;
+class HydrologyDCInefficientAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*Intermediaries*/
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble SedimentStoring(Element* element);
+		IssmDouble EplSpecificStoring(Element* element);
+		IssmDouble GetHydrologyDCInefficientHmax(Element* element, Gauss* gauss, Input* thickness_input, Input* base_input);
+		void GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode);
+		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input);
+		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input);
+		void ElementizeEplMask(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 18231)
@@ -0,0 +1,395 @@
+#include "./HydrologyShreveAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  HydrologyShreveAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void HydrologyShreveAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*retrieve some parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(iomodel->CopyConstantObject(HydrologyshreveStabilizationEnum));
+
+}/*}}}*/
+void HydrologyShreveAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Fetch data needed: */
+	int    hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+
+	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyShreveAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*retrieve some parameters: */
+	int          hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           HydrologyShreveAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* HydrologyShreveAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* HydrologyShreveAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* HydrologyShreveAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble diffusivity;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vx,vy,vel,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2]={0.};
+
+	/*Create water velocity vx and vy from current inputs*/
+	CreateHydrologyWaterVelocityInput(element);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&diffusivity,HydrologyshreveStabilizationEnum);
+	Input* vx_input=element->GetInput(HydrologyWaterVxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(HydrologyWaterVyEnum); _assert_(vy_input);
+	h = element->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					Ke->values,1);
+
+		GetB(B,element,xyz_list,gauss);
+		GetBprime(Bprime,element,xyz_list,gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Artificial diffusivity*/
+		vel=sqrt(vx*vx+vy*vy);
+		D[0][0]=D_scalar*diffusivity*h/(2*vel)*vx*vx;
+		D[1][0]=D_scalar*diffusivity*h/(2*vel)*vy*vx;
+		D[0][1]=D_scalar*diffusivity*h/(2*vel)*vx*vy;
+		D[1][1]=D_scalar*diffusivity*h/(2*vel)*vy*vy;
+		TripleMultiply(Bprime,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* HydrologyShreveAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Skip if water or ice shelf element*/
+	if(element->IsFloating()) return NULL;
+
+	/*Intermediaries */
+	IssmDouble  Jdet,dt;
+	IssmDouble  mb,oldw;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(mb_input);
+	Input* oldw_input = element->GetInput(WaterColumnOldEnum);                      _assert_(oldw_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		mb_input->GetInputValue(&mb,gauss);
+		oldw_input->GetInputValue(&oldw,gauss);
+
+		if(dt!=0.){
+			for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(oldw+dt*mb)*basis[i];
+		}
+		else{
+			for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*mb*basis[i];
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void HydrologyShreveAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void HydrologyShreveAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void HydrologyShreveAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,WatercolumnEnum);
+}/*}}}*/
+void HydrologyShreveAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void HydrologyShreveAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		if (values[i]<10e-10) values[i]=10e-10; //correcting the water column to positive values
+	}
+
+	/*Add input to the element: */
+	element->AddInput(WatercolumnEnum,values,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}/*}}}*/
+void HydrologyShreveAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
+/*Intermediaries*/
+void HydrologyShreveAnalysis::CreateHydrologyWaterVelocityInput(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dsdx,dsdy,dbdx,dbdy,w;
+
+	/*Retrieve all inputs and parameters*/
+	IssmDouble  rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  g         = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  mu_water  = element->GetMaterialParameter(MaterialsMuWaterEnum);
+	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
+	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
+	Input* bedslopex_input     = element->GetInput(BedSlopeXEnum);     _assert_(bedslopex_input);
+	Input* bedslopey_input     = element->GetInput(BedSlopeYEnum);     _assert_(bedslopey_input);
+	Input* watercolumn_input   = element->GetInput(WatercolumnEnum);   _assert_(watercolumn_input);
+
+	/*Fetch number of vertices and allocate output*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* vx  = xNew<IssmDouble>(numvertices);
+	IssmDouble* vy  = xNew<IssmDouble>(numvertices);
+
+	Gauss* gauss=element->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+		surfaceslopex_input->GetInputValue(&dsdx,gauss);
+		surfaceslopey_input->GetInputValue(&dsdy,gauss);
+		bedslopex_input->GetInputValue(&dbdx,gauss);
+		bedslopey_input->GetInputValue(&dbdy,gauss);
+		watercolumn_input->GetInputValue(&w,gauss);
+
+		/* Water velocity x and y components */
+		vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	element->AddInput(HydrologyWaterVxEnum,vx,P1Enum);
+	element->AddInput(HydrologyWaterVyEnum,vy,P1Enum);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(vy);
+}/*}}}*/
+
+
+
+/*Needed changes to switch to the Johnson formulation*//*{{{*/
+/*All the changes are to be done in the velocity computation.
+	The new velocity needs some new parameter that should be introduce in the hydrologyshreve class:
+	'p' and 'q' which are the exponent of the Manning formula for laminar (p=2,q=1) or turbulent (p=2/3,q=1/2) flow
+	'R' the hydraulic radius
+	'n' the manning roughness coeficient
+
+	With these, the velocity reads ;
+
+	v= - (1/n)* pow(R,p)*pow((grad phi(rho_water*g)),q)
+
+	you should also redefine the water pressure potential 'phi' with respect to the effective pressure deffinition given in Johson:
+	phi=(rho_ice*g*( surface + ((rho_water/rho_ice)-1)*base - k_n*((thickness* grad(base))/omega) )
+
+	where 
+	'omega' is the fractional area of the base occupied by the water film
+	'k_n' is a parameter
+	This last equation derives from the effective pressure definition developped in Alley 1989
+*/
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/HydrologyShreveAnalysis.h	(revision 18231)
@@ -0,0 +1,38 @@
+/*! \file HydrologyShreveAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _HydrologyShreveAnalysis_
+#define _HydrologyShreveAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class HydrologyShreveAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*Intermediaries*/
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void CreateHydrologyWaterVelocityInput(Element* element);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 18231)
@@ -0,0 +1,230 @@
+#include "./L2ProjectionBaseAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  L2ProjectionBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void L2ProjectionBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	}
+	else if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	::CreateNodes(nodes,iomodel,L2ProjectionBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           L2ProjectionBaseAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* L2ProjectionBaseAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* L2ProjectionBaseAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* L2ProjectionBaseAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	IssmDouble  D,Jdet;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke    = basalelement->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* L2ProjectionBaseAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	int         input_enum;
+	IssmDouble  Jdet,value,slopes[2];
+	Input      *input     = NULL;
+	Input      *input2    = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&input_enum,InputToL2ProjectEnum);
+	switch(input_enum){
+		case SurfaceSlopeXEnum: input2 = basalelement->GetInput(SurfaceEnum); _assert_(input2); break;
+		case SurfaceSlopeYEnum: input2 = basalelement->GetInput(SurfaceEnum); _assert_(input2); break;
+		case BedSlopeXEnum:     input2 = basalelement->GetInput(BaseEnum);     _assert_(input2); break;
+		case BedSlopeYEnum:     input2 = basalelement->GetInput(BaseEnum);     _assert_(input2); break;
+		case LevelsetfunctionSlopeXEnum: input2 = basalelement->GetInput(MaskIceLevelsetEnum);     _assert_(input2); break;
+		case LevelsetfunctionSlopeYEnum: input2 = basalelement->GetInput(MaskIceLevelsetEnum);     _assert_(input2); break;
+		default: input = element->GetInput(input_enum);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		if(input2) input2->GetInputDerivativeValue(&slopes[0],xyz_list,gauss);
+		switch(input_enum){
+			case SurfaceSlopeXEnum: case BedSlopeXEnum: case LevelsetfunctionSlopeXEnum: value = slopes[0]; break;
+			case SurfaceSlopeYEnum: case BedSlopeYEnum: case LevelsetfunctionSlopeYEnum: value = slopes[1]; break;
+			default: input->GetInputValue(&value,gauss);
+		}
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*value*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void L2ProjectionBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void L2ProjectionBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void L2ProjectionBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int inputenum,domaintype,elementtype;
+
+	element->FindParam(&inputenum,InputToL2ProjectEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&elementtype,MeshElementtypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			break;
+		case Domain2DverticalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			break;
+		case Domain3DEnum:
+			if(elementtype==TetraEnum)
+			 element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			else
+			 element->InputUpdateFromSolutionOneDofCollapsed(solution,inputenum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void L2ProjectionBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file L2ProjectionBaseAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _L2ProjectionBaseAnalysis_
+#define _L2ProjectionBaseAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class L2ProjectionBaseAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 18231)
@@ -0,0 +1,256 @@
+#include "./L2ProjectionEPLAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  L2ProjectionEPLAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void L2ProjectionEPLAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void L2ProjectionEPLAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+
+	/*Now, do we really want DC?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,EplHeadEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void L2ProjectionEPLAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	/*Now, do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	else if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	::CreateNodes(nodes,iomodel,L2ProjectionEPLAnalysisEnum,P1Enum);
+	iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
+void L2ProjectionEPLAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints*/
+}/*}}}*/
+void L2ProjectionEPLAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           L2ProjectionEPLAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* L2ProjectionEPLAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* L2ProjectionEPLAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* L2ProjectionEPLAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	bool     active_element;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	Input* active_element_input=basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
+
+	/* Check that all nodes are active, else return empty matrix */
+	if(!active_element){
+		if(domaintype!=Domain2DhorizontalEnum){
+			basalelement->DeleteMaterials();
+			delete basalelement;
+		}
+		return NULL;
+	}
+
+	/*Intermediaries */
+	IssmDouble  D,Jdet;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke    = basalelement->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* L2ProjectionEPLAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	bool     active_element;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	Input* active_element_input = basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
+
+	/*Check that all nodes are active, else return empty matrix*/
+	if(!active_element) {
+		if(domaintype!=Domain2DhorizontalEnum){
+			basalelement->DeleteMaterials();
+			delete basalelement;
+		}
+		return NULL;
+	}
+	
+	/*Intermediaries */
+	int         input_enum,index;
+	IssmDouble  Jdet,slopes[2];
+	Input      *input     = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&input_enum,InputToL2ProjectEnum);
+	switch(input_enum){
+		case EplHeadSlopeXEnum: input = basalelement->GetInput(EplHeadEnum); index = 0; _assert_(input); break;
+		case EplHeadSlopeYEnum: input = basalelement->GetInput(EplHeadEnum); index = 1; _assert_(input); break;
+		default: _error_("not implemented");
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		input->GetInputDerivativeValue(&slopes[0],xyz_list,gauss);
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*slopes[index]*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void L2ProjectionEPLAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void L2ProjectionEPLAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void L2ProjectionEPLAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	int inputenum,domaintype;
+
+	element->FindParam(&inputenum,InputToL2ProjectEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			break;
+		case Domain2DverticalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,inputenum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void L2ProjectionEPLAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file L2ProjectionEPLAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _L2ProjectionEPLAnalysis_
+#define _L2ProjectionEPLAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class L2ProjectionEPLAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.cpp	(revision 18231)
@@ -0,0 +1,518 @@
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./LevelsetAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+int LevelsetAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}
+/*}}}*/
+void LevelsetAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	return;
+}
+/*}}}*/
+void LevelsetAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	int  finiteelement;
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+	
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,MasstransportCalvingrateEnum);
+}
+/*}}}*/
+void LevelsetAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	int finiteelement=P1Enum;
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,LevelsetAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}
+/*}}}*/
+void LevelsetAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	return;
+}
+/*}}}*/
+void LevelsetAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+
+/*Finite element Analysis*/
+void LevelsetAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+	#if !defined(_DEVELOPMENT_)
+	_error_("Not implemented yet");
+	#endif
+
+	/*parameters: */
+	bool save_results;
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(LevelsetAnalysisEnum);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs = MaskIceLevelsetEnum;
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+	}
+}/*}}}*/
+ElementVector* LevelsetAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* LevelsetAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+	/* Jacobian required for the Newton solver */
+	_error_("not implemented yet");
+}/*}}}*/
+ElementMatrix* LevelsetAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	/*Intermediaries */
+	int  dim, domaintype;
+	int i, row, col;
+	IssmDouble kappa;
+	IssmDouble Jdet, dt, D_scalar;
+	IssmDouble h,hx,hy,hz;
+	IssmDouble vel, calvingrate;
+	IssmDouble norm_dlsf;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	basalelement->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1; break;
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 2; break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke       = basalelement->NewElementMatrix();
+	IssmDouble*    basis    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B        = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime   = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D        = xNew<IssmDouble>(dim*dim);
+	IssmDouble*    v        = xNew<IssmDouble>(dim);
+	IssmDouble*    w        = xNew<IssmDouble>(dim);
+	IssmDouble*    c        = xNew<IssmDouble>(dim);
+	IssmDouble*    dlsf     = xNew<IssmDouble>(dim);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vx_input=basalelement->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=basalelement->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		if(dim==1){
+			vx_input=basalelement->GetInput(VxEnum); _assert_(vx_input);
+		}
+		if(dim==2){
+			vx_input=basalelement->GetInput(VxAverageEnum); _assert_(vx_input);
+			vy_input=basalelement->GetInput(VyAverageEnum); _assert_(vy_input);
+		}
+	}
+
+	Input* lsf_slopex_input  = basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+	Input* lsf_slopey_input  = basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+	Input* calvingrate_input  = basalelement->GetInput(MasstransportCalvingrateEnum);     _assert_(calvingrate_input);
+	
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		D_scalar=gauss->weight*Jdet;
+
+		/* Transient */
+		if(dt!=0.){
+			basalelement->NodalFunctions(basis,gauss);
+			TripleMultiply(basis,numnodes,1,0,
+						&D_scalar,1,1,0,
+						basis,1,numnodes,0,
+						&Ke->values[0],1);
+			D_scalar*=dt;
+		}
+
+		/* Advection */
+		GetB(B,basalelement,xyz_list,gauss); 
+		GetBprime(Bprime,basalelement,xyz_list,gauss); 
+		vx_input->GetInputValue(&v[0],gauss); // in 3D case, add mesh velocity 
+		vy_input->GetInputValue(&v[1],gauss); 
+		lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+		lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+		calvingrate_input->GetInputValue(&calvingrate,gauss);
+
+		norm_dlsf=0.;
+		for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
+		norm_dlsf=sqrt(norm_dlsf);
+
+		if(norm_dlsf>1.e-10)
+			for(i=0;i<dim;i++) c[i]=calvingrate*dlsf[i]/norm_dlsf;
+		else
+			for(i=0;i<dim;i++) c[i]=0.;
+		
+		for(i=0;i<dim;i++) w[i]=v[i]-c[i];
+
+		for(row=0;row<dim;row++)
+			for(col=0;col<dim;col++)
+				if(row==col)
+					D[row*dim+col]=D_scalar*w[row];
+				else
+				   D[row*dim+col]=0.;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		/* Stabilization */
+		int stabilization=2;
+		vel=0.;
+		for(i=0;i<dim;i++) vel+=v[i]*v[i];
+		vel=sqrt(vel)+1.e-14;
+		switch(stabilization){
+			case 0:
+				// no stabilization, do nothing
+				break;
+			case 1:
+				/* Artificial Diffusion */
+				basalelement->ElementSizes(&hx,&hy,&hz);
+				h=sqrt( pow(hx*v[0]/vel,2) + pow(hy*v[1]/vel,2) ); 
+				kappa=h*vel/2.;
+				for(row=0;row<dim;row++)
+					for(col=0;col<dim;col++)
+					if(row==col)
+						D[row*dim+col]=D_scalar*kappa;
+					else
+						D[row*dim+col]=0.;
+
+				TripleMultiply(Bprime,dim,numnodes,1,
+							D,dim,dim,0,
+							Bprime,dim,numnodes,0,
+							&Ke->values[0],1);
+				break;	
+			case 2:
+				/* Streamline Upwinding */
+				basalelement->ElementSizes(&hx,&hy,&hz);
+				h=sqrt( pow(hx*v[0]/vel,2) + pow(hy*v[1]/vel,2) );
+				for(row=0;row<dim;row++) 
+					for(col=0;col<dim;col++) 
+						D[row*dim+col] = D_scalar*h/(2.*vel)*v[row]*v[col];
+
+				TripleMultiply(Bprime,dim,numnodes,1,
+							D,dim,dim,0,
+							Bprime,dim,numnodes,0,
+							&Ke->values[0],1);
+				break;
+			default:
+				_error_("unknown type of stabilization in LevelsetAnalysis.cpp");
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(v);
+	xDelete<IssmDouble>(w);
+	xDelete<IssmDouble>(c);
+	xDelete<IssmDouble>(dlsf);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementVector* LevelsetAnalysis::CreatePVector(Element* element){/*{{{*/
+	
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	/*Intermediaries */
+	int i, ig, domaintype;
+	IssmDouble  Jdet,dt;
+	IssmDouble  lsf;
+	IssmDouble* xyz_list = NULL;
+	
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe = basalelement->NewElementVector();
+	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	
+	if(dt!=0.){
+		/*Initialize basis vector*/
+		IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+		/*Retrieve all inputs and parameters*/
+		basalelement->GetVerticesCoordinates(&xyz_list);
+		Input* levelset_input     = basalelement->GetInput(MaskIceLevelsetEnum);                    _assert_(levelset_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=basalelement->NewGauss(2);
+		for(ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+			basalelement->NodalFunctions(basis,gauss);
+
+			/* old function value */
+			levelset_input->GetInputValue(&lsf,gauss);
+			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*lsf*basis[i];
+		}
+
+		/*Clean up and return*/
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(basis);
+		basalelement->FindParam(&domaintype,DomainTypeEnum);
+		if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+		delete gauss;
+	}
+
+	return pe;
+}/*}}}*/
+void LevelsetAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void LevelsetAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void LevelsetAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,MaskIceLevelsetEnum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,MaskIceLevelsetEnum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void LevelsetAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+void LevelsetAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void LevelsetAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void LevelsetAnalysis::SetDistanceOnIntersectedElements(FemModel* femmodel){/*{{{*/
+
+	/* Intermediaries */
+	int i,k;
+	IssmDouble dmaxp=0.,dmaxm=0,val=0.;
+
+	/*Initialize vector with number of vertices*/
+	int numvertices=femmodel->vertices->NumberOfVertices();
+	Element* element;
+
+	Vector<IssmDouble>* vec_dist_zerolevelset = NULL;
+	GetVectorFromInputsx(&vec_dist_zerolevelset, femmodel, MaskIceLevelsetEnum, VertexEnum);
+	
+	/* set NaN on elements intersected by zero levelset */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(element->IsZeroLevelset(MaskIceLevelsetEnum))
+			for(k=0;k<element->GetNumberOfVertices();k++)
+				vec_dist_zerolevelset->SetValue(element->vertices[k]->Sid(),NAN,INS_VAL); 
+	}
+
+	/* set distance on elements intersected by zero levelset */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
+			SetDistanceToZeroLevelsetElement(vec_dist_zerolevelset, element);
+
+			/* Get maximum distance to interface along vertices */
+			for(k=0;k<element->GetNumberOfVertices();k++){
+					vec_dist_zerolevelset->GetValue(&val,element->vertices[k]->Sid()); 
+					if((val>0.) && (val>dmaxp))
+						 dmaxp=val;
+					else if((val<0.) && (val<dmaxm))
+						 dmaxm=val;
+			}
+		}
+	}
+
+	/* set all none intersected vertices to max/min distance */
+	for(i=0;i<numvertices;i++){
+		vec_dist_zerolevelset->GetValue(&val,i);
+		if(val==1.) //FIXME: improve check
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxp,INS_VAL);
+		else if(val==-1.)
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxm,INS_VAL);
+	}
+
+	/*Assemble vector and serialize */
+	vec_dist_zerolevelset->Assemble();
+	IssmDouble* dist_zerolevelset=vec_dist_zerolevelset->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,dist_zerolevelset,MaskIceLevelsetEnum,VertexSIdEnum);
+
+	/*Clean up and return*/
+	delete vec_dist_zerolevelset;
+	delete dist_zerolevelset;
+}/*}}}*/
+void LevelsetAnalysis::SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element){/*{{{*/
+
+	if(!element->IsZeroLevelset(MaskIceLevelsetEnum))
+		return;
+
+	/* Intermediaries */
+	const int dim=3;
+	int i,d;
+	int numvertices=element->GetNumberOfVertices();
+	IssmDouble s0[dim], s1[dim], v[dim];
+	IssmDouble dist,lsf_old;
+
+	IssmDouble* lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* sign_lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* signed_dist = xNew<IssmDouble>(numvertices);
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* xyz_list_zero = NULL;
+
+	/* retrieve inputs and parameters */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnVertices(lsf,MaskIceLevelsetEnum);
+
+	/* get sign of levelset function */
+	for(i=0;i<numvertices;i++)
+		sign_lsf[i]=(lsf[i]>=0.?1.:-1.);
+
+	element->ZeroLevelsetCoordinates(&xyz_list_zero, xyz_list, MaskIceLevelsetEnum);
+	for(d=0;d<dim;d++){
+		s0[d]=xyz_list_zero[0+d];
+		s1[d]=xyz_list_zero[3+d];
+	}
+
+	/* get signed_distance of vertices to zero levelset straight */
+	for(i=0;i<numvertices;i++){
+		for(d=0;d<dim;d++)
+			v[d]=xyz_list[3*i+d];
+		dist=GetDistanceToStraight(&v[0],&s0[0],&s1[0]);
+		signed_dist[i]=sign_lsf[i]*dist;
+	}
+	
+	/* insert signed_distance into vec_signed_dist, if computed distance is smaller */
+	for(i=0;i<numvertices;i++){
+		vec_signed_dist->GetValue(&lsf_old, element->vertices[i]->Sid());
+		if(xIsNan<IssmDouble>(lsf_old) || fabs(signed_dist[i])<fabs(lsf_old))
+			vec_signed_dist->SetValue(element->vertices[i]->Sid(),signed_dist[i],INS_VAL);
+	}
+
+	xDelete<IssmDouble>(lsf);
+	xDelete<IssmDouble>(sign_lsf);
+	xDelete<IssmDouble>(signed_dist);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_zero);
+}/*}}}*/
+IssmDouble LevelsetAnalysis::GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1){/*{{{*/
+	// returns distance d of point q to straight going through points s0, s1
+	// d=|a x b|/|b|
+	// with a=q-s0, b=s1-s0
+	
+	/* Intermediaries */
+	const int dim=2;
+	int i;
+	IssmDouble a[dim], b[dim];
+	IssmDouble norm_b;
+
+	for(i=0;i<dim;i++){
+		a[i]=q[i]-s0[i];
+		b[i]=s1[i]-s0[i];
+	}
+	
+	norm_b=0.;
+	for(i=0;i<dim;i++)
+		norm_b+=b[i]*b[i];
+	norm_b=sqrt(norm_b);
+	_assert_(norm_b>0.);
+
+	return fabs(a[0]*b[1]-a[1]*b[0])/norm_b;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LevelsetAnalysis.h	(revision 18231)
@@ -0,0 +1,38 @@
+/*! \file LevelsetAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _LevelsetAnalysis_
+#define _LevelsetAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class LevelsetAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void SetDistanceOnIntersectedElements(FemModel* femmodel);
+		void SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element);
+		IssmDouble GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 18231)
@@ -0,0 +1,561 @@
+#include "./LsfReinitializationAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../cores/cores.h"
+
+#include "../modules/GetVectorFromInputsx/GetVectorFromInputsx.h"
+
+/*Model processing*/
+int  LsfReinitializationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void LsfReinitializationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+void LsfReinitializationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	int    finiteelement;
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+}/*}}}*/
+void LsfReinitializationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	int finiteelement=P1Enum;
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,LsfReinitializationAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void LsfReinitializationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+void LsfReinitializationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+
+/*Finite element Analysis*/
+void  LsfReinitializationAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+	/*parameters: */
+	bool save_results;
+	int maxiter = 3;
+	int step;
+	IssmDouble reltol = 0.05;
+
+	Vector<IssmDouble>* lsfg     = NULL;
+	Vector<IssmDouble>* lsfg_old = NULL;
+
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(LsfReinitializationAnalysisEnum);
+
+	/* set spcs for reinitialization */
+	if(VerboseSolution()) _printf0_("Update spcs for reinitialization:\n");
+	SetReinitSPCs(femmodel);
+
+	step = 1;
+	for(;;){
+
+		_printf_("smoothing lsf slope\n");
+		/* smoothen slope of lsf for computation of normal on ice domain*/
+		levelsetfunctionslope_core(femmodel);
+
+		//solve current artificial time step
+		if(VerboseSolution()) _printf0_("call computational core for reinitialization in step " << step << ":\n");
+		solutionsequence_linear(femmodel);
+		GetSolutionFromInputsx(&lsfg,femmodel);
+
+		if(step>1){
+			if(VerboseSolution()) _printf0_("   checking reinitialization convergence\n");
+			if(ReinitConvergence(lsfg,lsfg_old,reltol)) break;
+		}
+		if(step>maxiter){
+			if(VerboseSolution()) _printf0_("   maximum number reinitialization iterations " << maxiter << " reached\n");
+			break;
+		}
+
+		/*update results and increase counter*/
+		delete lsfg_old;lsfg_old=lsfg;
+		step++;
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[1] = {MaskIceLevelsetEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+	}
+
+}/*}}}*/
+ElementVector* LsfReinitializationAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* LsfReinitializationAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+ElementMatrix* LsfReinitializationAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	
+	/*Intermediaries */
+	const int dim = 2;
+	int        row,col,stabilization;
+	IssmDouble Jdet,D_scalar;
+	IssmDouble dtau = 1.;
+	IssmDouble mu = 1.;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D		= xNew<IssmDouble>(dim*dim);
+	IssmDouble*    dlsf	= xNew<IssmDouble>(dim);
+	IssmDouble*    normal= xNew<IssmDouble>(dim);
+
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){/*{{{*/
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		D_scalar=gauss->weight*Jdet;
+
+		if(dtau!=0.){
+			element->NodalFunctions(basis,gauss);
+			TripleMultiply(basis,numnodes,1,0,
+						&D_scalar,1,1,0,
+						basis,1,numnodes,0,
+						&Ke->values[0],1);
+			D_scalar*=dtau;
+		}
+
+		GetBprime(Bprime,element,xyz_list,gauss);
+
+		for(row=0;row<dim;row++)
+			for(col=0;col<dim;col++)
+				if(row==col)
+					D[row*dim+col]=mu*D_scalar;
+				else
+					D[row*dim+col]=0.;
+		TripleMultiply(Bprime,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		/* Stabilization */
+		stabilization=0;
+		if (stabilization==0){/* no stabilization, do nothing*/}
+		
+	}/*}}}*/
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* LsfReinitializationAnalysis::CreatePVector(Element* element){/*{{{*/
+	
+	/*Intermediaries */
+	int i,k;
+	int dim = 2;
+	IssmDouble dtau = 1.;
+	IssmDouble mu = 1.;
+	IssmDouble Jdet, D_scalar;
+	IssmDouble lsf;
+	IssmDouble norm_dlsf;
+	IssmDouble dbasis_normal;
+
+	/*Fetch number of nodes */
+	int numnodes = element->GetNumberOfNodes();
+
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* basis = xNew<IssmDouble>(numnodes);
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	IssmDouble* dlsf = xNew<IssmDouble>(dim);
+	IssmDouble* normal = xNew<IssmDouble>(dim);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Initialize Element vector*/
+	ElementVector* pe = element->NewElementVector();
+
+	/*Retrieve all inputs and parameters*/
+	Input* lsf_input = element->GetInput(MaskIceLevelsetEnum); _assert_(lsf_input);
+	Input* lsf_slopex_input=element->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+	Input* lsf_slopey_input=element->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		D_scalar=Jdet*gauss->weight;
+
+		if(dtau!=0.){
+			/* old function value */
+			lsf_input->GetInputValue(&lsf,gauss);
+			for(i=0;i<numnodes;i++) pe->values[i]+=D_scalar*lsf*basis[i];
+			D_scalar*=dtau;
+		}
+
+		lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+		lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+
+		/*get normal*/
+		norm_dlsf=0.;
+		for(i=0;i<dim;i++) norm_dlsf+=dlsf[i]*dlsf[i]; 
+		norm_dlsf=sqrt(norm_dlsf);
+		if(norm_dlsf>0.)
+			for(i=0;i<dim;i++)	normal[i]=dlsf[i]/norm_dlsf;
+		else
+			for(i=0;i<dim;i++)	normal[i]=0.;
+
+		/* multiply normal and dbasis */
+		for(i=0;i<numnodes;i++){
+			dbasis_normal=0.;
+			for(k=0;k<dim;k++) dbasis_normal+=dbasis[k*numnodes+i]*normal[k];
+			pe->values[i]+=D_scalar*mu*dbasis_normal; 
+		}
+	}
+
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dlsf);
+	xDelete<IssmDouble>(normal);
+	return pe;
+	}/*}}}*/
+void LsfReinitializationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+
+	IssmDouble   lsf;
+	int          dim;
+	int*         doflist = NULL;
+
+	/*Get some parameters*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
+
+	/*Get inputs*/
+	Input* lsf_input=element->GetInput(MaskIceLevelsetEnum); _assert_(lsf_input);
+
+	Gauss* gauss=element->NewGauss();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->FiniteElement(),i);
+
+		lsf_input->GetInputValue(&lsf,gauss);
+		values[i]=lsf;
+	}
+
+	solution->SetValues(numnodes,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+
+}/*}}}*/
+void LsfReinitializationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void LsfReinitializationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,MaskIceLevelsetEnum);
+			break;
+		case Domain3DEnum:
+			element->InputUpdateFromSolutionOneDofCollapsed(solution,MaskIceLevelsetEnum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void LsfReinitializationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+void LsfReinitializationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void LsfReinitializationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+
+/* Other */
+void LsfReinitializationAnalysis::SetReinitSPCs(FemModel* femmodel){/*{{{*/
+
+	int i,k, numnodes;
+	Element* element;
+	Node* node;
+
+	/* deactivate all spcs */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		for(k=0;k<element->GetNumberOfNodes();k++){
+			node=element->GetNode(k);
+			if(node->IsActive()){
+				node->DofInFSet(0); 
+			}
+		}
+	}
+
+	SetDistanceOnIntersectedElements(femmodel);
+
+	/* reactivate spcs on elements intersected by zero levelset */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
+			/*iterate over nodes and set spc */
+			numnodes=element->GetNumberOfNodes();
+			IssmDouble* lsf = xNew<IssmDouble>(numnodes);
+			element->GetInputListOnNodes(&lsf[0],MaskIceLevelsetEnum);
+			for(k=0;k<numnodes;k++){
+				node=element->GetNode(k);
+				if(node->IsActive()){
+					node->ApplyConstraint(0,lsf[k]);
+				}
+			}
+			xDelete<IssmDouble>(lsf);
+		}
+	}
+
+}/*}}}*/
+void LsfReinitializationAnalysis::SetDistanceOnIntersectedElements(FemModel* femmodel){/*{{{*/
+
+	/* Intermediaries */
+	int i;
+	IssmDouble dmaxp,dmaxm,val;
+	Element* element;
+
+	/*Initialize vector with number of vertices*/
+	int numvertices=femmodel->vertices->NumberOfVertices();
+
+	Vector<IssmDouble>* vec_dist_zerolevelset = NULL;
+	GetVectorFromInputsx(&vec_dist_zerolevelset, femmodel, MaskIceLevelsetEnum, VertexEnum);
+	
+	/* set distance on elements intersected by zero levelset */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
+			SetDistanceToZeroLevelsetElement(vec_dist_zerolevelset, element);
+		}
+	}
+	vec_dist_zerolevelset->Assemble();
+
+	/* Get maximum distance to interface along vertices */
+	dmaxp=0.; dmaxm=0.;
+	for(i=0;i<numvertices;i++){
+		vec_dist_zerolevelset->GetValue(&val,i); 
+		if((val>0.) && (val>dmaxp))
+			 dmaxp=val;
+		else if((val<0.) && (val<dmaxm))
+			 dmaxm=val;
+	}
+	//wait until all values are computed
+
+	/* set all none intersected vertices to max/min distance */
+	for(i=0;i<numvertices;i++){
+		vec_dist_zerolevelset->GetValue(&val,i);
+		if(val==1.) //FIXME: improve check
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxp,INS_VAL);
+		else if(val==-1.)
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxm,INS_VAL);
+	}
+
+	/*Assemble vector and serialize */
+	vec_dist_zerolevelset->Assemble();
+	IssmDouble* dist_zerolevelset=vec_dist_zerolevelset->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,dist_zerolevelset,MaskIceLevelsetEnum,VertexSIdEnum);
+
+	/*Clean up and return*/
+	delete vec_dist_zerolevelset;
+	delete dist_zerolevelset;
+
+}/*}}}*/
+void LsfReinitializationAnalysis::SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element){/*{{{*/
+
+	if(!element->IsZeroLevelset(MaskIceLevelsetEnum))
+		return;
+
+	/* Intermediaries */
+	int dim=3;
+	int i,d;
+	IssmDouble dist,lsf_old;
+
+	int numvertices=element->GetNumberOfVertices();
+
+	IssmDouble* lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* sign_lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* signed_dist = xNew<IssmDouble>(numvertices);
+	IssmDouble* s0 = xNew<IssmDouble>(dim);
+	IssmDouble* s1 = xNew<IssmDouble>(dim);
+	IssmDouble* v = xNew<IssmDouble>(dim);
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* xyz_list_zero = NULL;
+
+	/* retrieve inputs and parameters */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnVertices(lsf,MaskIceLevelsetEnum);
+
+	/* get sign of levelset function */
+	for(i=0;i<numvertices;i++)
+		sign_lsf[i]=(lsf[i]>=0.?1.:-1.);
+
+	element->ZeroLevelsetCoordinates(&xyz_list_zero, xyz_list, MaskIceLevelsetEnum);
+	for(i=0;i<dim;i++){
+		s0[i]=xyz_list_zero[0+i];
+		s1[i]=xyz_list_zero[3+i];
+	}
+
+	/* get signed_distance of vertices to zero levelset straight */
+	for(i=0;i<numvertices;i++){
+		for(d=0;d<dim;d++)
+			v[d]=xyz_list[dim*i+d];
+		dist=GetDistanceToStraight(&v[0],&s0[0],&s1[0]);
+		signed_dist[i]=sign_lsf[i]*dist;
+	}
+	
+	/* insert signed_distance into vec_signed_dist, if computed distance is smaller */
+	for(i=0;i<numvertices;i++){
+		vec_signed_dist->GetValue(&lsf_old, element->vertices[i]->Sid());
+		/* initial lsf values are +-1. Update those fields or if distance to interface smaller.*/
+		if(fabs(lsf_old)==1. || fabs(signed_dist[i])<fabs(lsf_old))
+			vec_signed_dist->SetValue(element->vertices[i]->Sid(),signed_dist[i],INS_VAL);
+	}
+
+	xDelete<IssmDouble>(lsf);
+	xDelete<IssmDouble>(sign_lsf);
+	xDelete<IssmDouble>(signed_dist);
+	xDelete<IssmDouble>(s0);
+	xDelete<IssmDouble>(s1);
+	xDelete<IssmDouble>(v);
+
+}/*}}}*/
+IssmDouble LsfReinitializationAnalysis::GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1){/*{{{*/
+	// returns distance d of point q to straight going through points s0, s1
+	// d=|a x b|/|b|
+	// with a=q-s0, b=s1-s0
+	
+	/* Intermediaries */
+	const int dim=2;
+	int i;
+	IssmDouble a[dim], b[dim];
+	IssmDouble norm_b;
+
+	for(i=0;i<dim;i++){
+		a[i]=q[i]-s0[i];
+		b[i]=s1[i]-s0[i];
+	}
+	
+	norm_b=0.;
+	for(i=0;i<dim;i++)
+		norm_b+=b[i]*b[i];
+	norm_b=sqrt(norm_b);
+	_assert_(norm_b>0.);
+
+	return fabs(a[0]*b[1]-a[1]*b[0])/norm_b;
+}/*}}}*/
+bool LsfReinitializationAnalysis::ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol){/*{{{*/
+
+	/*Output*/
+	bool converged = true;
+
+	/*Intermediary*/
+	Vector<IssmDouble>* dlsfg    = NULL;
+	IssmDouble          norm_dlsf,norm_lsf;
+
+	/*compute norm(du)/norm(u)*/
+	dlsfg=lsfg_old->Duplicate(); lsfg_old->Copy(dlsfg); dlsfg->AYPX(lsfg,-1.0);
+	norm_dlsf=dlsfg->Norm(NORM_TWO); norm_lsf=lsfg_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(norm_dlsf) || xIsNan<IssmDouble>(norm_lsf)) _error_("convergence criterion is NaN!");
+	if((norm_dlsf/norm_lsf)<reltol){
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*Cleanup*/
+	delete dlsfg;
+
+	return converged;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/LsfReinitializationAnalysis.h	(revision 18231)
@@ -0,0 +1,42 @@
+/*! \file LsfReinitializationAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _LsfReinitializationAnalysis_
+#define _LsfReinitializationAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class LsfReinitializationAnalysis: public Analysis{
+	
+public:
+	/*Model processing*/
+	int  DofsPerNode(int** doflist,int domaintype,int approximation);
+	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+	void CreateNodes(Nodes* nodes,IoModel* iomodel);
+	void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+	void CreateLoads(Loads* loads, IoModel* iomodel);
+
+	/*Finite element Analysis*/
+	void           Core(FemModel* femmodel);
+	ElementVector* CreateDVector(Element* element);
+	ElementMatrix* CreateJacobianMatrix(Element* element);
+	ElementMatrix* CreateKMatrix(Element* element);
+	ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+	void UpdateConstraints(FemModel* femmodel);
+	void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	
+	/* Other */
+	void SetReinitSPCs(FemModel* femmodel);
+	void SetDistanceOnIntersectedElements(FemModel* femmodel);
+	void SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_dist, Element* element);
+	IssmDouble GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
+	bool ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.cpp	(revision 18231)
@@ -0,0 +1,776 @@
+#include "./MasstransportAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MasstransportAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void MasstransportAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportIsfreesurfaceEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportHydrostaticAdjustmentEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportMinThicknessEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportPenaltyFactorEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,MasstransportRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(MasstransportNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,MasstransportRequestedOutputsEnum);
+
+}/*}}}*/
+void MasstransportAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int    stabilization,finiteelement,smb_model;
+	bool   dakota_analysis;
+	bool   isdelta18o;
+	bool   isgroundingline;
+	bool   islevelset;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&smb_model,SurfaceforcingsEnum);
+	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	if(stabilization==3){
+		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for DG, we need the spc in the element
+	}
+
+	if(dakota_analysis){
+		elements->InputDuplicate(BaseEnum,QmuBaseEnum);
+		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
+		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
+		elements->InputDuplicate(MaskIceLevelsetEnum,QmuMaskIceLevelsetEnum);
+		if(isgroundingline) elements->InputDuplicate(MaskGroundediceLevelsetEnum,QmuMaskGroundediceLevelsetEnum);
+	}
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+	}
+
+	switch(smb_model){
+		case SMBEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum,0.);
+			break;
+		case SMBpddEnum:
+			iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
+			if(isdelta18o){
+				iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesLgmEnum);
+				iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesPresentdayEnum);
+				iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsPresentdayEnum);
+			}
+			else{
+				iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
+				iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
+			}
+			break;
+		case SMBgradientsEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsHrefEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsBPosEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsBNegEnum);
+			break;
+		case SMBhenningEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum,0.);
+			break;
+		case SMBcomponentsEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsEvaporationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsRunoffEnum,0.);
+			break;
+		case SMBmeltcomponentsEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsEvaporationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMeltEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsRefreezeEnum,0.);
+			break;
+		default:
+			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+
+}/*}}}*/
+void MasstransportAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void MasstransportAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Do not add constraints in DG, they are weakly imposed*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,MasstransportSpcthicknessEnum,MasstransportAnalysisEnum,P1Enum);
+	}
+}/*}}}*/
+void MasstransportAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int stabilization;
+	int numvertex_pairing;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,MasstransportAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbase=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							MasstransportAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           MasstransportAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* MasstransportAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* MasstransportAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* MasstransportAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	ElementMatrix* Ke = NULL;
+	switch(element->FiniteElement()){
+		case P1Enum: case P2Enum:
+			Ke = CreateKMatrixCG(basalelement);
+			break;
+		case P1DGEnum:
+			Ke = CreateKMatrixDG(basalelement);
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(element->FiniteElement()) << " not supported yet");
+	}
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+}/*}}}*/
+ElementMatrix* MasstransportAnalysis::CreateKMatrixCG(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        domaintype,dim;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vel,vx,vy,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1; break;
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 2; break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		if(dim==1){
+			vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		}
+		if(dim==2){
+			vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+			vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+		}
+
+	}
+	h = element->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		if(dim==2){
+			vyaverage_input->GetInputValue(&vy,gauss);
+			vyaverage_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		}
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetB(B,element,dim,xyz_list,gauss);
+		GetBprime(Bprime,element,dim,xyz_list,gauss);
+
+		dvxdx=dvx[0];
+		if(dim==2) dvydy=dvy[1];
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0*dim+0]=D_scalar*dvxdx;
+		if(dim==2) D[1*dim+1]=D_scalar*dvydy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					B,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0*dim+0]=D_scalar*vx;
+		if(dim==2) D[1*dim+1]=D_scalar*vy;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			if(dim==1){
+				vel=fabs(vx)+1.e-8;
+				D[0]=h/(2*vel)*vx*vx;
+			}
+			else{
+				/*Streamline upwinding*/
+				vel=sqrt(vx*vx+vy*vy)+1.e-8;
+				D[0*dim+0]=h/(2*vel)*vx*vx;
+				D[1*dim+0]=h/(2*vel)*vy*vx;
+				D[0*dim+1]=h/(2*vel)*vx*vy;
+				D[1*dim+1]=h/(2*vel)*vy*vy;
+			}
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vxaverage_input->GetInputAverage(&vx);
+			if(dim==2) vyaverage_input->GetInputAverage(&vy);
+			D[0*dim+0]=h/2.0*fabs(vx);
+			if(dim==2) D[1*dim+1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			if(dim==1) D[0]=D_scalar*D[0];
+			else{
+				D[0*dim+0]=D_scalar*D[0*dim+0];
+				D[1*dim+0]=D_scalar*D[1*dim+0];
+				D[0*dim+1]=D_scalar*D[0*dim+1];
+				D[1*dim+1]=D_scalar*D[1*dim+1];
+			}
+
+			TripleMultiply(Bprime,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementMatrix* MasstransportAnalysis::CreateKMatrixDG(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int        domaintype;
+	IssmDouble Jdet,D_scalar,dt,vx,vy;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		/*WARNING: B and Bprime are inverted compared to CG*/
+		GetB(Bprime,element,2,xyz_list,gauss);
+		GetBprime(B,element,2,xyz_list,gauss);
+
+		D_scalar = - dt*gauss->weight*Jdet;
+		D[0][0]  = D_scalar*vx;
+		D[0][1]  = 0.;
+		D[1][0]  = 0.;
+		D[1][1]  = D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* MasstransportAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	ElementVector* pe = NULL;
+	switch(element->FiniteElement()){
+		case P1Enum: case P2Enum:
+			pe = CreatePVectorCG(basalelement);
+			break;
+		case P1DGEnum:
+			pe = CreatePVectorDG(basalelement);
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(element->FiniteElement()) << " not supported yet");
+	}
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+ElementVector* MasstransportAnalysis::CreatePVectorCG(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	IssmDouble  Jdet,dt;
+	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* gmb_input           = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
+	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
+	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);              _assert_(groundedice_input);
+	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);           _assert_(ms_input);
+	Input* thickness_input     = element->GetInput(ThicknessEnum);                            _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(phi>0.) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* MasstransportAnalysis::CreatePVectorDG(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	IssmDouble  Jdet,dt;
+	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* gmb_input           = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(gmb_input);
+	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(fmb_input);
+	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(ms_input);
+	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);             _assert_(groundedice_input);
+	Input* thickness_input     = element->GetInput(ThicknessEnum);                           _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(phi>0) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void MasstransportAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			B[numnodes*j+i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void MasstransportAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void MasstransportAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MasstransportAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void MasstransportAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int        i,hydroadjustment,domaintype;
+	int*       doflist=NULL;
+	IssmDouble rho_ice,rho_water,minthickness;
+	Element*   basalelement=NULL;
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum){
+		if(!element->IsOnBase()) return;
+		basalelement=element->SpawnBasalElement();
+	}
+	else{
+		basalelement = element;
+	}
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* newthickness = xNew<IssmDouble>(numnodes);
+	IssmDouble* newbed       = xNew<IssmDouble>(numnodes);
+	IssmDouble* newsurface   = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldthickness = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldbed       = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldsurface   = xNew<IssmDouble>(numnodes);
+	IssmDouble* phi          = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	basalelement->FindParam(&minthickness,MasstransportMinThicknessEnum);
+	for(i=0;i<numnodes;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+	}
+
+	/*Get previous bed, thickness and surface*/
+	basalelement->GetInputListOnNodes(&oldbed[0],BaseEnum);
+	basalelement->GetInputListOnNodes(&oldsurface[0],SurfaceEnum);
+	basalelement->GetInputListOnNodes(&oldthickness[0],ThicknessEnum);
+	basalelement->GetInputListOnNodes(&phi[0],MaskGroundediceLevelsetEnum);
+
+	/*Find MasstransportHydrostaticAdjustment to figure out how to update the geometry:*/
+	basalelement->FindParam(&hydroadjustment,MasstransportHydrostaticAdjustmentEnum);
+	rho_ice   = basalelement->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_water = basalelement->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+
+	for(i=0;i<numnodes;i++) {
+		/*If shelf: hydrostatic equilibrium*/
+		if (phi[i]>0.){
+			newsurface[i] = oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]     = oldbed[i];                 //same bed: do nothing
+		}
+		else{ //this is an ice shelf
+			if(hydroadjustment==AbsoluteEnum){
+				newsurface[i] = newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]     = newthickness[i]*(-rho_ice/rho_water);
+			}
+			else if(hydroadjustment==IncrementalEnum){
+				newsurface[i] = oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH
+				newbed[i]     = oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed               = oldbed + di * dH
+			}
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Add input to the element: */
+	element->AddBasalInput(ThicknessEnum,newthickness,P1Enum);
+	element->AddBasalInput(SurfaceEnum,newsurface,P1Enum);
+	element->AddBasalInput(BaseEnum,newbed,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(newthickness);
+	xDelete<IssmDouble>(newbed);
+	xDelete<IssmDouble>(newsurface);
+	xDelete<IssmDouble>(oldthickness);
+	xDelete<IssmDouble>(oldbed);
+	xDelete<IssmDouble>(oldsurface);
+	xDelete<IssmDouble>(phi);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void MasstransportAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MasstransportAnalysis.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file MasstransportAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MasstransportAnalysis_
+#define _MasstransportAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MasstransportAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixCG(Element* element);
+		ElementMatrix* CreateKMatrixDG(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorCG(Element* element);
+		ElementVector* CreatePVectorDG(Element* element);
+		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.cpp	(revision 18231)
@@ -0,0 +1,162 @@
+#include "./MeltingAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MeltingAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void MeltingAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+}/*}}}*/
+void MeltingAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int frictionlaw;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	
+	/*Friction law variables*/
+	switch(frictionlaw){
+		case 1:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			break;
+		case 2:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+}/*}}}*/
+void MeltingAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,MeltingAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void MeltingAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/*No Constraints*/
+}/*}}}*/
+void MeltingAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*if 2d: Error*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+	//create penalties for nodes: no node can have a temperature over the melting point
+	iomodel->FetchData(1,MeshVertexonbaseEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+			if (reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[i])){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,MeltingAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,MeshVertexonbaseEnum);
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           MeltingAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* MeltingAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* MeltingAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* MeltingAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Get basal element*/
+	if(!element->IsOnBase()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+
+	/*Intermediaries */
+	IssmDouble  D,Jdet;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke    = basalelement->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	IssmDouble latentheat   = element->GetMaterialParameter(MaterialsLatentheatEnum);
+	IssmDouble heatcapacity = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		D=latentheat/heatcapacity*gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	basalelement->DeleteMaterials(); delete basalelement;
+	return Ke;
+}/*}}}*/
+ElementVector* MeltingAnalysis::CreatePVector(Element* element){/*{{{*/
+	return NULL;
+}/*}}}*/
+void MeltingAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeltingAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void MeltingAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	element->InputUpdateFromSolutionOneDof(solution,BasalforcingsGroundediceMeltingRateEnum);
+}/*}}}*/
+void MeltingAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeltingAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file MeltingAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MeltingAnalysis_
+#define _MeltingAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MeltingAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+#include "./MeshdeformationAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  MeshdeformationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           MeshdeformationAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* MeshdeformationAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* MeshdeformationAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* MeshdeformationAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+ElementVector* MeshdeformationAnalysis::CreatePVector(Element* element){/*{{{*/
+_error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/MeshdeformationAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file MeshdeformationAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _MeshdeformationAnalysis_
+#define _MeshdeformationAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class MeshdeformationAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 18231)
@@ -0,0 +1,183 @@
+#include "./SmoothedSurfaceSlopeXAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  SmoothedSurfaceSlopeXAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
+	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeXAnalysisEnum,P1Enum);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           SmoothedSurfaceSlopeXAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* SmoothedSurfaceSlopeXAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* SmoothedSurfaceSlopeXAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* SmoothedSurfaceSlopeXAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Intermediaries */
+	IssmDouble  Jdet,thickness,l=8.;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							basis[i]*basis[j]
+							+(l*thickness)*(l*thickness)*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j])
+							);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementVector* SmoothedSurfaceSlopeXAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	int         input_enum;
+	IssmDouble  Jdet,thickness,slope[2];
+	IssmDouble  taud_x,norms,normv,vx,vy;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	IssmDouble rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
+	Input* H_input       = basalelement->GetInput(ThicknessEnum); _assert_(H_input);
+	Input* surface_input = basalelement->GetInput(SurfaceEnum);   _assert_(surface_input);
+	Input* vx_input      = basalelement->GetInput(VxEnum);
+	Input* vy_input      = basalelement->GetInput(VyEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		H_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+		if(vx_input && vy_input){
+			vx_input->GetInputValue(&vx,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			norms = sqrt(slope[0]*slope[0]+slope[1]*slope[1]+1.e-10);
+			normv = sqrt(vx*vx + vy*vy);
+			if(normv>15./(365.*24.*3600.)) slope[0] = -vx/normv*norms;
+		}
+		taud_x = rho_ice*gravity*thickness*slope[0];
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_x*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file SmoothedSurfaceSlopeXAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _SmoothedSurfaceSlopeXAnalysis_
+#define _SmoothedSurfaceSlopeXAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class SmoothedSurfaceSlopeXAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 18231)
@@ -0,0 +1,182 @@
+#include "./SmoothedSurfaceSlopeYAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  SmoothedSurfaceSlopeYAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
+	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeYAnalysisEnum,P1Enum);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           SmoothedSurfaceSlopeYAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* SmoothedSurfaceSlopeYAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* SmoothedSurfaceSlopeYAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* SmoothedSurfaceSlopeYAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Intermediaries */
+	IssmDouble  Jdet,thickness,l=8.;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							basis[i]*basis[j]
+							+(l*thickness)*(l*thickness)*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j])
+							);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementVector* SmoothedSurfaceSlopeYAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	IssmDouble  Jdet,thickness,slope[2];
+	IssmDouble  taud_y,norms,normv,vx,vy;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = basalelement->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	IssmDouble rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
+	Input* H_input       = basalelement->GetInput(ThicknessEnum); _assert_(H_input);
+	Input* surface_input = basalelement->GetInput(SurfaceEnum);   _assert_(surface_input);
+	Input* vx_input      = basalelement->GetInput(VxEnum);
+	Input* vy_input      = basalelement->GetInput(VyEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+
+		H_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+		if(vx_input && vy_input){
+			vx_input->GetInputValue(&vx,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			norms = sqrt(slope[0]*slope[0]+slope[1]*slope[1]+1.e-10);
+			normv = sqrt(vx*vx + vy*vy);
+			if(normv>15./(365.*24.*3600.)) slope[1] = -vy/normv*norms;
+		}
+		taud_y = rho_ice*gravity*thickness*slope[1];
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_y*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return pe;
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
+}/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*! \file SmoothedSurfaceSlopeYAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _SmoothedSurfaceSlopeYAnalysis_
+#define _SmoothedSurfaceSlopeYAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class SmoothedSurfaceSlopeYAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.cpp	(revision 18231)
@@ -0,0 +1,6702 @@
+#include "./StressbalanceAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../cores/cores.h"
+
+//#define FSANALYTICAL 2
+
+/*Model processing*/
+int  StressbalanceAnalysis::DofsPerNode(int** pdoftype,int domaintype,int approximation){/*{{{*/
+
+	/*output*/
+	int *doftype = NULL;
+	int  numdofs;
+
+	switch(approximation){
+		case SSAApproximationEnum:
+			 switch(domaintype){
+				 case Domain3DEnum:           numdofs=2; break;
+				 case Domain2DhorizontalEnum: numdofs=2; break;
+				 case Domain2DverticalEnum:   numdofs=1; break;
+				 default: _error_("mesh type not supported yet");
+			 }
+			 break;
+		case L1L2ApproximationEnum: numdofs =2; break;
+		case HOApproximationEnum:   
+			 switch(domaintype){
+				 case Domain3DEnum:         numdofs=2; break;
+				 case Domain2DverticalEnum: numdofs=1; break;
+				 default: _error_("mesh type not supported yet");
+			 }
+			 break;
+		case SIAApproximationEnum:  numdofs =2; break;
+		case FSvelocityEnum:
+			 switch(domaintype){
+				 case Domain3DEnum:         numdofs=3; break;
+				 case Domain2DverticalEnum: numdofs=2; break;
+				 default: _error_("mesh type not supported yet");
+			}
+			break;
+		case FSpressureEnum: numdofs=1; break;
+		case NoneApproximationEnum:
+			 switch(domaintype){
+				 case Domain3DEnum:         numdofs=4; break;
+				 case Domain2DverticalEnum: numdofs=3; break;
+				 default: _error_("mesh type not supported yet");
+			}
+			break;
+		case SSAHOApproximationEnum:
+			numdofs=4;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=SSAApproximationEnum;
+			doftype[1]=SSAApproximationEnum;
+			doftype[2]=HOApproximationEnum;
+			doftype[3]=HOApproximationEnum;
+			break;
+		case HOFSApproximationEnum:
+			numdofs=5;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=HOApproximationEnum;
+			doftype[1]=HOApproximationEnum;
+			doftype[2]=FSvelocityEnum;
+			doftype[3]=FSvelocityEnum;
+			doftype[4]=FSvelocityEnum;
+			break;
+		case SSAFSApproximationEnum:
+			numdofs=5;
+			doftype=xNew<int>(numdofs);
+			doftype[0]=SSAApproximationEnum;
+			doftype[1]=SSAApproximationEnum;
+			doftype[2]=FSvelocityEnum;
+			doftype[3]=FSvelocityEnum;
+			doftype[4]=FSvelocityEnum;
+			break;
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not implemented yet");
+	}
+
+	/*Assign output pointer and return*/
+	*pdoftype = doftype;
+	return numdofs;
+}/*}}}*/
+void StressbalanceAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*Intermediaries*/
+	int     fe_FS;
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSIAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSSAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsL1L2Enum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsHOEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationFeFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceIsnewtonEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalancePenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceFSreconditioningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceShelfDampeningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceViscosityOvershootEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+
+	/*XTH LATH parameters*/
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==XTaylorHoodEnum || fe_FS==LATaylorHoodEnum){
+		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianREnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianThetaEnum));
+	}
+
+	/*Requested outputs*/
+	iomodel->FetchData(&requestedoutputs,&numoutputs,StressbalanceRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(StressbalanceNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(StressbalanceRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,StressbalanceRequestedOutputsEnum);
+
+}/*}}}*/
+void StressbalanceAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Intermediaries*/
+	int    materials_type,finiteelement,fe_FS;
+	int    approximation,frictionlaw;
+	int*   finiteelement_list=NULL;
+	bool   isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool   control_analysis;
+	bool   dakota_analysis;
+	bool   islevelset;
+	bool   isdamage;
+
+	/*Fetch constants needed: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+
+	/*return if no processing required*/
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Fetch data needed and allocate vectors: */
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+	finiteelement_list=xNewZeroInit<int>(iomodel->numberofelements);
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*is damage mechanics being used?*/
+	if(materials_type==MaticeEnum) isdamage = false;
+	else if(materials_type==MatdamageiceEnum) isdamage = true;
+	else _error_("Material type not recognized");
+
+	/*Get finite element type*/
+	if(!iscoupling){
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS)   iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		for(int i=0;i<iomodel->numberofelements;i++){
+			finiteelement_list[i]=finiteelement;
+		}
+	}
+	else{
+		if(isFS){
+			for(int i=0;i<iomodel->numberofelements;i++){
+				approximation=reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[i]);
+				if(approximation==FSApproximationEnum || approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+					finiteelement_list[i]=MINIcondensedEnum;
+				}
+				else{
+					finiteelement_list[i]=P1Enum;
+				}
+			}
+		}
+		else{
+			finiteelement = P1Enum;
+			for(int i=0;i<iomodel->numberofelements;i++){
+				finiteelement_list[i]=finiteelement;
+			}
+		}
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement_list[i]);
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
+	if(isdamage)iomodel->FetchDataToInput(elements,DamageDEnum);
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchDataToInput(elements,FlowequationBorderFSEnum);
+		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
+		iomodel->FetchDataToInput(elements,VzEnum,0.);
+		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
+	}
+	if(isFS){
+		iomodel->FetchDataToInput(elements,PressureEnum,0.);
+		iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum,0.);
+		if(dakota_analysis)elements->InputDuplicate(PressureEnum,QmuPressureEnum);
+	}
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+	}
+	/*LATH parameters*/
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==LATaylorHoodEnum){
+		iomodel->FetchDataToInput(elements,PressureEnum);
+	}
+
+	/*Friction law variables*/
+	switch(frictionlaw){
+		case 1:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			break;
+		case 2:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+#ifdef _HAVE_ANDROID_
+	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
+#endif
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+	xDelete<int>(finiteelement_list);
+}/*}}}*/
+void StressbalanceAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	bool isSSA,isL1L2,isHO,isFS,iscoupling;
+	int  finiteelement=-1,approximation=-1;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, check that we have non SIA elements */
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular CreateNodes, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA){
+			approximation=SSAApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		}
+		else if(isL1L2){
+			approximation = L1L2ApproximationEnum;
+			finiteelement = P1Enum;
+		}
+		else if(isHO){
+			approximation = HOApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		}
+		else if(isFS){
+			approximation = FSApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		}
+		iomodel->FetchData(3,FlowequationBorderSSAEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderFSEnum);
+		::CreateNodes(nodes,iomodel,StressbalanceAnalysisEnum,finiteelement,approximation);
+		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+	else{
+		/*Coupling: we are going to create P1 Elements only*/
+
+		Node*  node  = NULL;
+		int    lid=0;
+		if(!nodes) nodes = new Nodes();
+
+		iomodel->FetchData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(isFS){
+			/*P1+ velocity*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					if(approximation==FSApproximationEnum)  approximation=FSvelocityEnum;
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,approximation));
+				}
+			}
+			for(int i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,StressbalanceAnalysisEnum,FSvelocityEnum);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			/*P1 pressure*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,StressbalanceAnalysisEnum,FSpressureEnum);
+					if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum){
+						node->Deactivate();
+					}
+					nodes->AddObject(node);
+				}
+			}
+		}
+		else{
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])));
+				}
+			}
+		}
+		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+}/*}}}*/
+void StressbalanceAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        i,j;
+	int        count,finiteelement;
+	IssmDouble g;
+	IssmDouble rho_ice;
+	IssmDouble FSreconditioning;
+	bool       isSIA,isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool       spcpresent = false;
+	int        Mx,Nx;
+	int        My,Ny;
+	int        Mz,Nz;
+	IssmDouble *spcvx          = NULL;
+	IssmDouble *spcvy          = NULL;
+	IssmDouble *spcvz          = NULL;
+	IssmDouble *nodeonSSA = NULL;
+	IssmDouble *nodeonHO   = NULL;
+	IssmDouble *nodeonFS   = NULL;
+	IssmDouble *nodeonbase      = NULL;
+	IssmDouble *groundedice_ls = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *surface        = NULL;
+	IssmDouble *z              = NULL;
+	IssmDouble *timesx=NULL;
+	IssmDouble *timesy=NULL;
+	IssmDouble *timesz=NULL;
+   IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&g,ConstantsGEnum);
+	iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Do we have coupling*/
+	if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular IoModelToConstraintsx, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS){  iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+			/*Deduce velocity interpolation from finite element*/
+			switch(finiteelement){
+				case P1P1Enum            : finiteelement = P1Enum;       break;
+				case P1P1GLSEnum         : finiteelement = P1Enum;       break;
+				case MINIcondensedEnum   : finiteelement = P1bubbleEnum; break;
+				case MINIEnum            : finiteelement = P1bubbleEnum; break;
+				case TaylorHoodEnum      : finiteelement = P2Enum;       break;
+				case XTaylorHoodEnum     : finiteelement = P2Enum;       break;
+				case LATaylorHoodEnum    : finiteelement = P2Enum;       break;
+				case OneLayerP4zEnum     : finiteelement = P2xP4Enum;    break;
+				case CrouzeixRaviartEnum : finiteelement = P2bubbleEnum; break;
+				default: _error_("finite element "<<EnumToStringx(finiteelement)<<" not supported");
+			}
+		}
+		else{
+			_error_("model not supported yet");
+		}
+
+		if(isFS){
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+			iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+			iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+			if(iomodel->domaintype==Domain3DEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->domaintype==Domain2DverticalEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			if(iomodel->domaintype==Domain3DEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,2);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->domaintype==Domain2DverticalEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,1);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+			iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+			iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+
+			/*Pressure spc*/
+			count = constraints->Size();
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+			iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+			switch(finiteelement){
+				case P1Enum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P1bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2Enum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+iomodel->numberoffaces+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2xP4Enum:
+					//Nothing yet
+					break;
+				default:
+					_error_("not implemented yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(surface,SurfaceEnum);
+			iomodel->DeleteData(z,MeshZEnum);
+		}
+		else{
+			IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+			if(iomodel->domaintype!=Domain2DverticalEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
+			}
+		}
+
+		return;
+	}
+
+	/*Constraints: fetch data: */
+	iomodel->FetchData(&spcvx,&Mx,&Nx,StressbalanceSpcvxEnum);
+	iomodel->FetchData(&spcvy,&My,&Ny,StressbalanceSpcvyEnum);
+	iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+	iomodel->FetchData(&nodeonSSA,NULL,NULL,FlowequationBorderSSAEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonHO,NULL,NULL,FlowequationBorderHOEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+	iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+	iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+	iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+
+	/*Initialize counter: */
+	count=0;
+
+	/*figure out times: */
+	timesx=xNew<IssmDouble>(Nx);
+	for(j=0;j<Nx;j++){
+		timesx[j]=spcvx[(Mx-1)*Nx+j];
+	}
+	/*figure out times: */
+	timesy=xNew<IssmDouble>(Ny);
+	for(j=0;j<Ny;j++){
+		timesy[j]=spcvy[(My-1)*Ny+j];
+	}
+	/*figure out times: */
+	timesz=xNew<IssmDouble>(Nz);
+	for(j=0;j<Nz;j++){
+		timesz[j]=spcvz[(Mz-1)*Nz+j];
+	}
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Start with adding spcs of coupling: zero at the border SSA/HO for the appropriate dofs*/
+			if(reCast<int,IssmDouble>(vertices_type[i]==SSAHOApproximationEnum)){
+				/*If grionSSA, spc HO dofs: 3 & 4*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else _error_("if vertices_type is SSAHO, you shoud have nodeonHO or nodeonSSA");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==HOFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc HO nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is HOFS, you shoud have nodeonHO or nodeonFS");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==SSAFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc SSA nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is SSAFS, you shoud have nodeonSSA or nodeonFS");
+			}
+			/*Now add the regular spcs*/
+			else{
+				if (Mx==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvx[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+
+				}
+				else if (Mx==iomodel->numberofvertices+1) {
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Nx);
+					spcpresent=false;
+					for(j=0;j<Nx;j++){
+						values[j]=spcvx[i*Nx+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,Nx,timesx,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (My==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
+					count++;
+				}
+				else if (My==iomodel->numberofvertices+1){
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Ny);
+					spcpresent=false;
+					for(j=0;j<Ny;j++){
+						values[j]=spcvy[i*Ny+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,Ny,timesy,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (reCast<int,IssmDouble>(vertices_type[i])==FSApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
+					if (Mz==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+						count++;
+					}
+					else if (Mz==iomodel->numberofvertices+1){
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(Nz);
+						spcpresent=false;
+						for(j=0;j<Nz;j++){
+							values[j]=spcvz[i*Nz+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,Nz,timesz,values,StressbalanceAnalysisEnum));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+
+				}
+				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(spcvx,StressbalanceSpcvxEnum);
+	iomodel->DeleteData(spcvy,StressbalanceSpcvyEnum);
+	iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+	iomodel->DeleteData(nodeonSSA,FlowequationBorderSSAEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonHO,FlowequationBorderHOEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+	iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+	iomodel->DeleteData(surface,SurfaceEnum);
+	iomodel->DeleteData(z,MeshZEnum);
+
+	/*Free resources:*/
+	xDelete<IssmDouble>(timesx);
+	xDelete<IssmDouble>(timesy);
+	xDelete<IssmDouble>(timesz);
+	xDelete<IssmDouble>(values);
+
+}/*}}}*/
+void StressbalanceAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	const int   RIFTINFOSIZE = 12;
+	int         i;
+	int         count;
+	int         penpair_ids[2];
+	bool        isSSA,isL1L2,isHO,isFS;
+	int         numpenalties,numrifts,numriftsegments;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *penalties      = NULL;
+	int         assert_int;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Initialize counter: */
+	count=0;
+
+	/*Create Penpair for penalties: */
+	iomodel->FetchData(&penalties,&numpenalties,NULL,StressbalanceVertexPairingEnum);
+
+	for(i=0;i<numpenalties;i++){
+
+		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			assert_int=iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+1]-1)]; _assert_(assert_int);
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(iomodel->loadcounter+count+1,&penpair_ids[0],StressbalanceAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(penalties,StressbalanceVertexPairingEnum);
+
+	/*Create Riffront loads for rifts: */
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
+		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		for(i=0;i<numriftsegments;i++){
+			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
+				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,StressbalanceAnalysisEnum));
+				count++;
+			}
+		}
+		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		xDelete<IssmDouble>(riftinfo);
+	}
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           StressbalanceAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool isSSA,isL1L2,isHO,isFS;
+	bool conserve_loads = true;
+	int  newton,domaintype,fe_FS;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+	femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
+	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&fe_FS,FlowequationFeFSEnum);
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
+
+	if(isFS && !(isSSA || isHO || isL1L2)){
+		if(VerboseSolution()) _printf0_("   computing velocities\n");
+
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		if (fe_FS==XTaylorHoodEnum)
+		 solutionsequence_la_theta(femmodel);
+		else if (fe_FS==LATaylorHoodEnum)
+		 solutionsequence_la(femmodel);
+		else if(newton>0)
+		 solutionsequence_newton(femmodel);
+		else
+		 solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+	else if(!isFS && (isSSA || isHO || isL1L2)){ 
+		if(VerboseSolution()) _printf0_("   computing velocities\n");
+
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		if(newton>0)
+		 solutionsequence_newton(femmodel);
+		else
+		 solutionsequence_nonlinear(femmodel,conserve_loads); 
+
+		if(domaintype==Domain2DverticalEnum && isSSA){
+			femmodel->parameters->SetParam(VxEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+			femmodel->parameters->SetParam(VelEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+		}
+	}
+	else if ((isSSA || isL1L2 || isHO) && isFS){
+		if(VerboseSolution()) _printf0_("   computing coupling between lower order models and FS\n");
+		solutionsequence_FScoupling_nonlinear(femmodel,conserve_loads);
+	}
+	else{
+		_error_("not supported");
+	}
+
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreateDVector(Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case FSApproximationEnum: 
+			return CreateDVectorFS(element);
+		default:
+			return NULL; //no need for doftypes outside of FS approximation
+	}
+	return NULL;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case SSAApproximationEnum: 
+			return CreateJacobianMatrixSSA(element);
+		case HOApproximationEnum: 
+			return CreateJacobianMatrixHO(element);
+		case FSApproximationEnum: 
+			return CreateJacobianMatrixFS(element);
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case SIAApproximationEnum:
+			return NULL;
+		case SSAApproximationEnum: 
+			return CreateKMatrixSSA(element);
+		case L1L2ApproximationEnum: 
+			return CreateKMatrixL1L2(element);
+		case HOApproximationEnum: 
+			return CreateKMatrixHO(element);
+		case FSApproximationEnum: 
+			return CreateKMatrixFS(element);
+		case SSAHOApproximationEnum: 
+			return CreateKMatrixSSAHO(element);
+		case HOFSApproximationEnum: 
+			return CreateKMatrixHOFS(element);
+		case SSAFSApproximationEnum: 
+			return CreateKMatrixSSAFS(element);
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case SIAApproximationEnum:
+			return NULL;
+		case SSAApproximationEnum: 
+			return CreatePVectorSSA(element);
+		case L1L2ApproximationEnum: 
+			return CreatePVectorL1L2(element);
+		case HOApproximationEnum: 
+			return CreatePVectorHO(element);
+		case FSApproximationEnum: 
+			return CreatePVectorFS(element);
+		case SSAHOApproximationEnum: 
+			return CreatePVectorSSAHO(element);
+		case HOFSApproximationEnum: 
+			return CreatePVectorHOFS(element);
+		case SSAFSApproximationEnum: 
+			return CreatePVectorSSAFS(element);
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case FSApproximationEnum: case NoneApproximationEnum:
+			GetSolutionFromInputsFS(solution,element);
+			return;
+		case SSAApproximationEnum: case HOApproximationEnum: case SIAApproximationEnum:
+			GetSolutionFromInputsHoriz(solution,element);
+			return;
+		case L1L2ApproximationEnum:
+			GetSolutionFromInputsHoriz(solution,element);
+			return;
+		case SSAHOApproximationEnum: case HOFSApproximationEnum: case SSAFSApproximationEnum:
+			/*the elements around will create the solution*/
+			return;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+
+	IssmDouble   vx,vy;
+	int          domaintype,dim,approximation,dofpernode;
+	int*         doflist = NULL;
+
+	/*Get some parameters*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum: dim = 2; dofpernode = 2; break;
+		case Domain2DverticalEnum:   dim = 2; dofpernode = 1; break;
+		case Domain3DEnum:           dim = 3; dofpernode = 2; break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*dofpernode;
+	element->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,approximation,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numdof);
+
+	/*Get inputs*/
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=NULL;
+	if(domaintype!=Domain2DverticalEnum){vy_input=element->GetInput(VyEnum); _assert_(vy_input);}
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	Gauss* gauss=element->NewGauss();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->FiniteElement(),i);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		values[i*dofpernode+0]=vx;
+		if(dofpernode==2){
+			vy_input->GetInputValue(&vy,gauss);
+			values[i*dofpernode+1]=vy;
+		}
+	}
+
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}/*}}}*/
+void StressbalanceAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	switch(approximation){
+		case FSApproximationEnum: case NoneApproximationEnum:
+			InputUpdateFromSolutionFS(solution,element);
+			return;
+		case SIAApproximationEnum: 
+			return;
+		case SSAApproximationEnum: 
+			InputUpdateFromSolutionSSA(solution,element);
+			return;
+		case HOApproximationEnum: 
+			InputUpdateFromSolutionHO(solution,element);
+			return;
+		case L1L2ApproximationEnum:
+			InputUpdateFromSolutionL1L2(solution,element);
+			return;
+		case SSAHOApproximationEnum:
+			InputUpdateFromSolutionSSAHO(solution,element);
+			return;
+		case HOFSApproximationEnum:
+			InputUpdateFromSolutionHOFS(solution,element);
+			return;
+		case SSAFSApproximationEnum:
+			InputUpdateFromSolutionSSAFS(solution,element);
+			return;
+		default:
+			_error_("Approximation "<<EnumToStringx(approximation)<<" not supported");
+	}
+}/*}}}*/
+void StressbalanceAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
+
+/*SSA*/
+ElementMatrix* StressbalanceAnalysis::CreateJacobianMatrixSSA(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	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 *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+
+	/*Initialize Element matrix, vectors and Gaussian points*/
+	ElementMatrix* Ke=this->CreateKMatrixSSA(element); //Initialize Jacobian with regular SSA (first part of the Gateau derivative)
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);_assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);       _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		basalelement->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		basalelement->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2.*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2.*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2.*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2.*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	basalelement->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+
+	/*clean-up and return*/
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum: case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixSSAViscous(basalelement);
+	ElementMatrix* Ke2=CreateKMatrixSSAFriction(basalelement);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAFriction(Element* element){/*{{{*/
+
+	/*Return if element is inactive*/
+	if(element->IsFloating() || !element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         dim,domaintype;
+	bool        mainlyfloating;
+	int         migration_style,point1;
+	IssmDouble  alpha2,Jdet,fraction1,fraction2;
+	IssmDouble  gllevelset,phi=1.;
+	IssmDouble *xyz_list  = NULL;
+	Gauss*      gauss     = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1;break;
+		case Domain2DhorizontalEnum: dim = 2;break;
+		case Domain3DEnum:           dim = 2;break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*dim;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(SSAApproximationEnum);
+	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&migration_style,GroundinglineMigrationEnum);
+	Input* surface_input    = element->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* gllevelset_input = NULL;
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,1);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=element->GetGroundedPortion(xyz_list);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+	   gauss = element->NewGauss(point1,fraction1,fraction2,mainlyfloating,2);
+	}
+	else{
+		gauss = element->NewGauss(2);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss);
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0.) alpha2=0.;
+		}
+
+		this->GetBSSAFriction(B,element,dim,xyz_list,gauss);
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		for(int i=0;i<dim;i++) D[i*dim+i]=alpha2*gauss->weight*Jdet;
+
+		TripleMultiply(B,dim,numdof,1,
+					D,dim,dim,0,
+					B,dim,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==2) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAViscous(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         dim,domaintype,bsize;
+	IssmDouble  viscosity,newviscosity,oldviscosity;
+	IssmDouble  viscosity_overshoot,thickness,Jdet;
+	IssmDouble  D_scalar;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1; bsize = 1; break;
+		case Domain2DhorizontalEnum: dim = 2; bsize = 3; break;
+		case Domain3DEnum:           dim = 2; bsize = 3; break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*dim;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(SSAApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* thickness_input=element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* vx_input=element->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vxold_input=element->GetInput(VxPicardEnum);      _assert_(vxold_input);
+	Input* vy_input    = NULL;
+	Input* vyold_input = NULL;
+	if(dim==2){
+		vy_input    = element->GetInput(VyEnum);       _assert_(vy_input);
+		vyold_input = element->GetInput(VyPicardEnum); _assert_(vyold_input);
+	}
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBSSA(B,element,dim,xyz_list,gauss);
+		this->GetBSSAprime(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscositySSA(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
+		element->ViscositySSA(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
+		thickness_input->GetInputValue(&thickness, gauss);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2.*newviscosity*thickness*gauss->weight*Jdet;
+		for(int i=0;i<bsize;i++) D[i*bsize+i]=D_scalar;
+
+		TripleMultiply(B,bsize,numdof,1,
+					D,bsize,bsize,0,
+					Bprime,bsize,numdof,0,
+					&Ke->values[0],1);
+
+		for(int i=0;i<bsize*numdof;i++) if(B[i]==1.) _error_("STREAM");
+		for(int i=0;i<bsize*numdof;i++) if(Bprime[i]==1.) _error_("STREAM");
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==2) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSA(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum: case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorSSADrivingStress(basalelement);
+	ElementVector* pe2=CreatePVectorSSAFront(basalelement);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSADrivingStress(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         dim,domaintype;
+	IssmDouble  thickness,Jdet,slope[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1;break;
+		case Domain2DhorizontalEnum: dim = 2;break;
+		case Domain3DEnum:           dim = 2;break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe    = element->NewElementVector(SSAApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input*     thickness_input=element->GetInput(ThicknessEnum); _assert_(thickness_input); 
+	Input*     surface_input  =element->GetInput(SurfaceEnum);   _assert_(surface_input);
+	IssmDouble rhog = element->GetMaterialParameter(MaterialsRhoIceEnum)*element->GetMaterialParameter(ConstantsGEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i*dim+0]+=-rhog*thickness*slope[0]*Jdet*gauss->weight*basis[i];
+			if(dim==2) pe->values[i*dim+1]+=-rhog*thickness*slope[1]*Jdet*gauss->weight*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	if(dim==2) element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSAFront(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*If no front, return NULL*/
+	if(!element->IsIcefront()) return NULL;
+
+	/*Intermediaries*/
+	int         dim,domaintype;
+	IssmDouble  Jdet,thickness,bed,water_pressure,ice_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble *xyz_list_front = NULL;
+	IssmDouble  normal[2];
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   dim = 1;break;
+		case Domain2DhorizontalEnum: dim = 2;break;
+		case Domain3DEnum:           dim = 2;break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector(SSAApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* base_input       = element->GetInput(BaseEnum);       _assert_(base_input);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+	//element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	Gauss* gauss=element->NewGauss(xyz_list,xyz_list_front,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		thickness_input->GetInputValue(&thickness,gauss);
+		base_input->GetInputValue(&bed,gauss);
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		surface_under_water = min(0.,thickness+bed); // 0 if the top of the glacier is above water level
+		base_under_water    = min(0.,bed);           // 0 if the bottom of the glacier is above water level
+		water_pressure = 1.0/2.0*gravity*rho_water*(surface_under_water*surface_under_water - base_under_water*base_under_water);
+		ice_pressure   = 1.0/2.0*gravity*rho_ice*thickness*thickness;
+		pressure = ice_pressure + water_pressure;
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[dim*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
+			if(dim==2) pe->values[dim*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	if(dim==2) element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *                   2D                      1D
+	 *       Bi=[ dN/dx           0    ]   Bi=[ dN/dx ]
+	 *          [   0           dN/dy  ]      
+	 *          [ 1/2*dN/dy  1/2*dN/dx ]     
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	if(dim==2){
+		for(int i=0;i<numnodes;i++){
+			B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+			B[2*numnodes*0+2*i+1] = 0.;
+			B[2*numnodes*1+2*i+0] = 0.;
+			B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+			B[2*numnodes*2+2*i+0] = .5*dbasis[1*numnodes+i];
+			B[2*numnodes*2+2*i+1] = .5*dbasis[0*numnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			B[i] = dbasis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *                       2D             1D
+	 *                 Bi=[ N   0 ]    Bi = N
+	 *                    [ 0   N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build L: */
+	if(dim==2){
+		for(int i=0;i<numnodes;i++){
+			B[2*numnodes*0+2*i+0] = basis[i];
+			B[2*numnodes*0+2*i+1] = 0.;
+			B[2*numnodes*1+2*i+0] = 0.;
+			B[2*numnodes*1+2*i+1] = basis[i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			B[i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSAprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *                         2D                        1D
+	 *       Bi_prime=[ 2*dN/dx    dN/dy ]     Bi_prime=[ 2*dN/dx ]
+	 *                [   dN/dx  2*dN/dy ]
+	 *                [   dN/dy    dN/dx ]
+	 * where hNis the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	if(dim==2){
+		for(int i=0;i<numnodes;i++){
+			Bprime[2*numnodes*0+2*i+0] = 2.*dbasis[0*numnodes+i];
+			Bprime[2*numnodes*0+2*i+1] =    dbasis[1*numnodes+i];
+			Bprime[2*numnodes*1+2*i+0] =    dbasis[0*numnodes+i];
+			Bprime[2*numnodes*1+2*i+1] = 2.*dbasis[1*numnodes+i];
+			Bprime[2*numnodes*2+2*i+0] =    dbasis[1*numnodes+i];
+			Bprime[2*numnodes*2+2*i+1] =    dbasis[0*numnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			Bprime[i] = 2.*dbasis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i,dim,domaintype;
+	IssmDouble  rho_ice,g;
+	int*        doflist=NULL;
+	IssmDouble* xyz_list=NULL;
+	Element*    basalelement=NULL;
+
+	/*Deal with pressure first*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* pressure  = xNew<IssmDouble>(numvertices);
+	IssmDouble* thickness = xNew<IssmDouble>(numvertices);
+	IssmDouble* surface   = xNew<IssmDouble>(numvertices);
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+	rho_ice =element->GetMaterialParameter(MaterialsRhoIceEnum);
+	g       =element->GetMaterialParameter(ConstantsGEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->GetInputListOnVertices(thickness,ThicknessEnum);
+			for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*thickness[i];
+			dim=2;
+			break;
+		case Domain3DEnum:
+			element->GetVerticesCoordinates(&xyz_list);
+			element->GetInputListOnVertices(surface,SurfaceEnum);
+			for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+			dim=2;
+			break;
+		case Domain2DverticalEnum:
+			element->GetVerticesCoordinates(&xyz_list);
+			element->GetInputListOnVertices(surface,SurfaceEnum);
+			for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+			dim=1;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+	element->AddInput(PressureEnum,pressure,P1Enum);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(surface);
+
+	/*Get basal element*/
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum: case Domain2DverticalEnum:
+			if(!element->IsOnBase()){xDelete<IssmDouble>(xyz_list); return;}
+			basalelement=element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+	int numdof   = numnodes*dim;
+
+	/*Fetch dof list and allocate solution vectors*/
+	basalelement->GetDofList(&doflist,SSAApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	if(dim==2) basalelement->TransformSolutionCoord(&values[0],XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*dim+0];
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+
+		if(dim==2){
+			vy[i]=values[i*dim+1];
+			if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+		}
+	}
+
+	/*Get Vz and compute vel*/
+	if(dim==2){
+		basalelement->GetInputListOnNodes(&vz[0],VzEnum,0.);
+		for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+	}
+	else{
+		basalelement->GetInputListOnNodes(&vy[0],VyEnum,0.);
+		for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	if(dim==2)element->InputChangeName(VyEnum,VyPicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddBasalInput(VxEnum,vx,element->GetElementType());
+	if(dim==2)element->AddBasalInput(VyEnum,vy,element->GetElementType());
+	element->AddBasalInput(VelEnum,vel,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+
+/*L1L2*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixL1L2(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixL1L2Viscous(element);
+	ElementMatrix* Ke2=CreateKMatrixL1L2Friction(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixL1L2Friction(Element* element){/*{{{*/
+
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+	Element* basalelement = element->SpawnBasalElement();
+	ElementMatrix* Ke = CreateKMatrixSSAFriction(basalelement);
+
+	/*clean-up and return*/
+	basalelement->DeleteMaterials(); delete basalelement;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixL1L2Viscous(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble  viscosity,Jdet;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get element on base*/
+	Element* basalelement = element->GetBasalElement()->SpawnBasalElement();
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+	int numdof   = numnodes*2;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = basalelement->NewElementMatrix(L1L2ApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(3*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(3*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(3*3);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* vx_input      = element->GetInput(VxEnum);      _assert_(vx_input);
+	Input* vy_input      = element->GetInput(VyEnum);      _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss      = element->NewGauss(5);
+	Gauss* gauss_base = basalelement->NewGauss();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_base);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBSSA(B,basalelement,2,xyz_list,gauss_base);
+		this->GetBSSAprime(Bprime,basalelement,2,xyz_list,gauss_base);
+
+		element->ViscosityL1L2(&viscosity,xyz_list,gauss,vx_input,vy_input,surface_input);
+
+		for(int i=0;i<3;i++) D[i*3+i]=2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply(B,3,numdof,1,
+					D,3,3,0,
+					Bprime,3,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	basalelement->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete gauss_base;
+	basalelement->DeleteMaterials(); delete basalelement;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorL1L2(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum: case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorL1L2DrivingStress(basalelement);
+	ElementVector* pe2=CreatePVectorL1L2Front(basalelement);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorL1L2DrivingStress(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble  thickness,Jdet,slope[2];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe    = element->NewElementVector(L1L2ApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input*     thickness_input=element->GetInput(ThicknessEnum); _assert_(thickness_input); 
+	Input*     surface_input  =element->GetInput(SurfaceEnum);   _assert_(surface_input);
+	IssmDouble rhog = element->GetMaterialParameter(MaterialsRhoIceEnum)*element->GetMaterialParameter(ConstantsGEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i*2+0]+=-rhog*thickness*slope[0]*Jdet*gauss->weight*basis[i];
+			pe->values[i*2+1]+=-rhog*thickness*slope[1]*Jdet*gauss->weight*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorL1L2Front(Element* element){/*{{{*/
+
+	/*If no front, return NULL*/
+	if(!element->IsIcefront()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  Jdet,thickness,bed,water_pressure,ice_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble *xyz_list_front = NULL;
+	IssmDouble  normal[2];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector(L1L2ApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* base_input       = element->GetInput(BaseEnum);       _assert_(base_input);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	Gauss* gauss=element->NewGauss(xyz_list,xyz_list_front,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		thickness_input->GetInputValue(&thickness,gauss);
+		base_input->GetInputValue(&bed,gauss);
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		surface_under_water = min(0.,thickness+bed); // 0 if the top of the glacier is above water level
+		base_under_water    = min(0.,bed);           // 0 if the bottom of the glacier is above water level
+		water_pressure = 1.0/2.0*gravity*rho_water*(surface_under_water*surface_under_water - base_under_water*base_under_water);
+		ice_pressure   = 1.0/2.0*gravity*rho_ice*thickness*thickness;
+		pressure = ice_pressure + water_pressure;
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i,dim,domaintype;
+	IssmDouble  rho_ice,g;
+	int*        doflist=NULL;
+	IssmDouble* xyz_list=NULL;
+	Element*    basalelement=NULL;
+
+	/*Deal with pressure first*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* pressure  = xNew<IssmDouble>(numvertices);
+	IssmDouble* thickness = xNew<IssmDouble>(numvertices);
+	IssmDouble* surface   = xNew<IssmDouble>(numvertices);
+
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	rho_ice =element->GetMaterialParameter(MaterialsRhoIceEnum);
+	g       =element->GetMaterialParameter(ConstantsGEnum);
+	if(dim==2){
+		element->GetInputListOnVertices(thickness,ThicknessEnum);
+		for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*thickness[i];
+	}
+	else{
+		element->GetVerticesCoordinates(&xyz_list);
+		element->GetInputListOnVertices(surface,SurfaceEnum);
+		for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+	}
+	element->AddInput(PressureEnum,pressure,P1Enum);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(surface);
+
+	/*Get basal element*/
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()){xDelete<IssmDouble>(xyz_list); return;}
+			basalelement=element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = basalelement->GetNumberOfNodes();
+	int numdof   = numnodes*2;
+
+	/*Fetch dof list and allocate solution vectors*/
+	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	basalelement->TransformSolutionCoord(&values[0],XYEnum);
+	basalelement->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*2+0];
+		vy[i]=values[i*2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	basalelement->GetInputListOnNodes(&vz[0],VzEnum,0.);
+	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddBasalInput(VxEnum,vx,element->GetElementType());
+	element->AddBasalInput(VyEnum,vy,element->GetElementType());
+	element->AddBasalInput(VelEnum,vel,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+
+/*HO*/
+ElementMatrix* StressbalanceAnalysis::CreateJacobianMatrixHO(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	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 *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix, vectors and Gaussian points*/
+	ElementMatrix* Ke=this->CreateKMatrixHO(element); //Initialize Jacobian with regular HO (first part of the Gateau derivative)
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+		eps1[2]=epsilon[3];                eps2[2]=epsilon[4];
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i]+eps1[2]*dbasis[2*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j]+eps1[2]*dbasis[2*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i]+eps2[2]*dbasis[2*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j]+eps2[2]*dbasis[2*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2.*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2.*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2.*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2.*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHO(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixHOViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixHOFriction(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOViscous(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         dim,bsize;
+	IssmDouble  viscosity,newviscosity,oldviscosity;
+	IssmDouble  viscosity_overshoot,thickness,Jdet;
+	IssmDouble  D_scalar;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) bsize = 2;
+	else       bsize = 5;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*(dim-1);
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(HOApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input    = element->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vxold_input = element->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vy_input    = NULL;
+	Input* vyold_input = NULL;
+	if(dim==3){
+		vy_input=element->GetInput(VyEnum);          _assert_(vy_input);
+		vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
+	}
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBHO(B,element,dim,xyz_list,gauss);
+		this->GetBHOprime(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2.*newviscosity*gauss->weight*Jdet;
+		for(int i=0;i<bsize;i++) D[i*bsize+i]=D_scalar;
+
+		TripleMultiply(B,bsize,numdof,1,
+					D,bsize,bsize,0,
+					Bprime,bsize,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==3) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFriction(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	bool        mainlyfloating;
+	int         migration_style,point1;
+	IssmDouble  alpha2,Jdet,fraction1,fraction2;
+	IssmDouble  gllevelset,phi=1.;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*(dim-1);
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(HOApproximationEnum);
+	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&migration_style,GroundinglineMigrationEnum);
+	Input* gllevelset_input = NULL;
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,2);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=element->GetGroundedPortion(xyz_list_base);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+		//gauss = element->NewGauss(point1,fraction1,fraction2,mainlyfloating,2);
+		gauss=element->NewGaussBase(2);
+	}
+	else{
+		gauss=element->NewGaussBase(2);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss);
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0.) alpha2=0.;
+		}
+
+		this->GetBHOFriction(B,element,dim,xyz_list_base,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i]=alpha2*gauss->weight*Jdet;
+
+		TripleMultiply(B,dim-1,numdof,1,
+					D,dim-1,dim-1,0,
+					B,dim-1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==3) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
+#ifdef FSANALYTICAL
+ElementVector* StressbalanceAnalysis::CreatePVectorHO(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  x_coord,y_coord,z_coord;
+	IssmDouble  Jdet,forcex,forcey,forcez;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe=element->NewElementVector(HOApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+
+		x_coord=element->GetXcoord(xyz_list,gauss);
+		y_coord=element->GetYcoord(xyz_list,gauss);
+		if(dim==3) z_coord=element->GetZcoord(xyz_list,gauss);
+		else z_coord=0.;
+
+		forcex=fx(x_coord,y_coord,z_coord,FSANALYTICAL);
+		forcey=fy(x_coord,y_coord,z_coord,FSANALYTICAL);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i*(dim-1)+0]+=forcex*Jdet*gauss->weight*basis[i];
+			pe->values[i*(dim-1)+1]+=forcey*Jdet*gauss->weight*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	if(dim==3) element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+#else
+ElementVector* StressbalanceAnalysis::CreatePVectorHO(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorHODrivingStress(element);
+	ElementVector* pe2=CreatePVectorHOFront(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+#endif
+ElementVector* StressbalanceAnalysis::CreatePVectorHODrivingStress(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,slope[3];
+	IssmDouble* xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe=element->NewElementVector(HOApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input*     surface_input = element->GetInput(SurfaceEnum);   _assert_(surface_input);
+	IssmDouble rhog = element->GetMaterialParameter(MaterialsRhoIceEnum)*element->GetMaterialParameter(ConstantsGEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i*(dim-1)+0]+=-rhog*slope[0]*Jdet*gauss->weight*basis[i];
+			if(dim==3) pe->values[i*(dim-1)+1]+=-rhog*slope[1]*Jdet*gauss->weight*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	if(dim==3) element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorHOFront(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*If no front, return NULL*/
+	if(!element->IsIcefront()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	IssmDouble  Jdet,surface,z,water_pressure,ice_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble* xyz_list       = NULL;
+	IssmDouble* xyz_list_front = NULL;
+	IssmDouble  normal[3];
+	Gauss*      gauss = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector(HOApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input);
+	IssmDouble rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+
+	/*Initialize gauss points*/
+	IssmDouble zmax=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]>zmax) zmax=xyz_list[i*3+(dim-1)];
+	IssmDouble zmin=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]<zmin) zmin=xyz_list[i*3+(dim-1)];
+	if(zmax>0. && zmin<0.) gauss=element->NewGauss(xyz_list,xyz_list_front,3,10);//refined in vertical because of the sea level discontinuity
+	else                   gauss=element->NewGauss(xyz_list,xyz_list_front,3,3);
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		surface_input->GetInputValue(&surface,gauss);
+		if(dim==3) z=element->GetZcoord(xyz_list,gauss);
+		else       z=element->GetYcoord(xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+
+		water_pressure = rho_water*gravity*min(0.,z);//0 if the gaussian point is above water level
+		ice_pressure   = rho_ice*gravity*(surface-z);
+		pressure       = ice_pressure + water_pressure;
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[(dim-1)*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
+			if(dim==3) pe->values[(dim-1)*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	if(dim==3)element->TransformLoadVectorCoord(pe,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void StressbalanceAnalysis::GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *                   3D                        2D
+	 *
+	 *       Bi=[ dh/dx          0      ]  Bi=[ dh/dx]
+	 *          [   0           dh/dy   ]     [ dh/dy]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]     
+	 *          [ 1/2*dh/dz      0      ]    
+	 *          [  0         1/2*dh/dz  ]   
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	if(dim==2){
+		for(int i=0;i<numnodes;i++){
+			B[numnodes*0+i] = dbasis[0*numnodes+i];
+			B[numnodes*1+i] = .5*dbasis[1*numnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+			B[2*numnodes*0+2*i+1] = 0.;
+			B[2*numnodes*1+2*i+0] = 0.;
+			B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+			B[2*numnodes*2+2*i+0] = .5*dbasis[1*numnodes+i];
+			B[2*numnodes*2+2*i+1] = .5*dbasis[0*numnodes+i];
+			B[2*numnodes*3+2*i+0] = .5*dbasis[2*numnodes+i];
+			B[2*numnodes*3+2*i+1] = 0.;
+			B[2*numnodes*4+2*i+0] = 0.;
+			B[2*numnodes*4+2*i+1] = .5*dbasis[2*numnodes+i];
+		}
+	}
+
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBHOprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *                          3D                      2D
+	 *       Bi_prime=[ 2*dN/dx    dN/dy ] Bi_prime=[ 2*dN/dx ]
+	 *                [   dN/dx  2*dN/dy ]          [   dN/dy ]
+	 *                [   dN/dy    dN/dx ]  
+	 * where hNis the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	if(dim==3){
+		for(int i=0;i<numnodes;i++){
+			Bprime[2*numnodes*0+2*i+0] = 2.*dbasis[0*numnodes+i];
+			Bprime[2*numnodes*0+2*i+1] = dbasis[1*numnodes+i];
+			Bprime[2*numnodes*1+2*i+0] = dbasis[0*numnodes+i];
+			Bprime[2*numnodes*1+2*i+1] = 2.*dbasis[1*numnodes+i];
+			Bprime[2*numnodes*2+2*i+0] = dbasis[1*numnodes+i];
+			Bprime[2*numnodes*2+2*i+1] = dbasis[0*numnodes+i];
+			Bprime[2*numnodes*3+2*i+0] = dbasis[2*numnodes+i];
+			Bprime[2*numnodes*3+2*i+1] = 0.;
+			Bprime[2*numnodes*4+2*i+0] = 0.;
+			Bprime[2*numnodes*4+2*i+1] = dbasis[2*numnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			Bprime[numnodes*0+i] = 2.*dbasis[0*numnodes+i];
+			Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *                       3D           2D
+	 *                 Bi=[ N   0 ]    Bi=N
+	 *                    [ 0   N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build L: */
+	if(dim==3){
+		for(int i=0;i<numnodes;i++){
+			B[2*numnodes*0+2*i+0] = basis[i];
+			B[2*numnodes*0+2*i+1] = 0.;
+			B[2*numnodes*1+2*i+0] = 0.;
+			B[2*numnodes*1+2*i+1] = basis[i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			B[i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionHO(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i,dim;
+	int*        doflist=NULL;
+	IssmDouble* xyz_list=NULL;
+
+	/*Get mesh dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Deal with pressure first*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* pressure  = xNew<IssmDouble>(numvertices);
+	IssmDouble* surface   = xNew<IssmDouble>(numvertices);
+	IssmDouble  rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  g         = element->GetMaterialParameter(ConstantsGEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnVertices(surface,SurfaceEnum);
+	for(i=0;i<numvertices;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+	element->AddInput(PressureEnum,pressure,P1Enum);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(surface);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*(dim-1);
+
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflist,HOApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numdof);
+	IssmDouble* vx     = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy     = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz     = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel    = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	if(dim==3) element->TransformSolutionCoord(&values[0],XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*(dim-1)+0];
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(dim==3){
+			vy[i]=values[i*(dim-1)+1];
+			if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+		}
+	}
+
+	/*Get Vz and compute vel*/
+	if(dim==3){
+		element->GetInputListOnNodes(&vz[0],VzEnum,0.);
+		for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+	}
+	else{
+		element->GetInputListOnNodes(&vy[0],VyEnum,0.);
+		for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	if(dim==3)element->InputChangeName(VyEnum,VyPicardEnum);
+
+	/*Add vx and vy as inputs to the element: */
+	//element->AddInput(VxEnum,  vx,element->GetElementType());
+	//element->AddInput(VyEnum,  vy,element->GetElementType());
+	//element->AddInput(VelEnum,vel,element->GetElementType());
+	element->AddInput(VxEnum,vx,element->GetElementType());
+	if(dim==3)element->AddInput(VyEnum,vy,element->GetElementType());
+	element->AddInput(VelEnum,vel,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+
+/*FS*/
+ElementVector* StressbalanceAnalysis::CreateDVectorFS(Element* element){/*{{{*/
+
+	int dim;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Initialize output vector*/
+	ElementVector* de = element->NewElementVector(FSvelocityEnum);
+
+	for(int i=0;i<vnumnodes;i++){
+		for(int j=0;j<dim;j++) de->values[i*dim+j]=VelocityEnum;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		de->values[vnumnodes*dim+i]=PressureEnum;
+	}
+
+	return de;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateJacobianMatrixFS(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble eps3dotdphii,eps3dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3],eps3[3];
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*NDOF3 + pnumnodes*NDOF1;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix, vectors and Gaussian points*/
+	ElementMatrix* Ke=this->CreateKMatrixFS(element); //Initialize Jacobian with regular FS (first part of the Gateau derivative)
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input = element->GetInput(VzEnum); _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivativesVelocity(dbasis,xyz_list,gauss);
+
+		//element->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		//eps1[0]=epsilon[0];   eps2[0]=epsilon[3];   eps3[0]=epsilon[4];
+		//eps1[1]=epsilon[3];   eps2[1]=epsilon[1];   eps3[1]=epsilon[5];
+		//eps1[2]=epsilon[4];   eps2[2]=epsilon[5];   eps3[2]=epsilon[2];
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+		element->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+
+		for(i=0;i<vnumnodes;i++){
+			for(j=0;j<vnumnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*vnumnodes+i]+eps1[1]*dbasis[1*vnumnodes+i]+eps1[2]*dbasis[2*vnumnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*vnumnodes+j]+eps1[1]*dbasis[1*vnumnodes+j]+eps1[2]*dbasis[2*vnumnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*vnumnodes+i]+eps2[1]*dbasis[1*vnumnodes+i]+eps2[2]*dbasis[2*vnumnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*vnumnodes+j]+eps2[1]*dbasis[1*vnumnodes+j]+eps2[2]*dbasis[2*vnumnodes+j];
+				eps3dotdphii=eps3[0]*dbasis[0*vnumnodes+i]+eps3[1]*dbasis[1*vnumnodes+i]+eps3[2]*dbasis[2*vnumnodes+i];
+				eps3dotdphij=eps3[0]*dbasis[0*vnumnodes+j]+eps3[1]*dbasis[1*vnumnodes+j]+eps3[2]*dbasis[2*vnumnodes+j];
+
+				Ke->values[numdof*(3*i+0)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(3*i+0)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(3*i+0)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(3*i+1)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(3*i+1)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(3*i+1)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(3*i+2)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(3*i+2)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(3*i+2)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<int>(cs_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFS(Element* element){/*{{{*/
+
+	/*Get type of algorithm*/
+	int fe_FS;
+	element->FindParam(&fe_FS,FlowequationFeFSEnum);
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=NULL;
+	if(fe_FS==XTaylorHoodEnum)
+	 Ke1=CreateKMatrixFSViscousXTH(element);
+	else if(fe_FS==LATaylorHoodEnum)
+	 Ke1=CreateKMatrixFSViscousLATH(element);
+	else
+	 Ke1=CreateKMatrixFSViscous(element);
+
+	ElementMatrix* Ke2=CreateKMatrixFSFriction(element);
+	ElementMatrix* Ke3=CreateKMatrixFSShelf(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousLATH(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,dim,epssize;
+	IssmDouble  r,Jdet,viscosity,DU;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes;
+	if(dim==2) pnumnodes=3;
+	else pnumnodes=6;
+	//int pnumnodes = element->NumberofNodes(P1Enum);
+	int numdof    = vnumnodes*dim;
+	int pnumdof   = pnumnodes;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke       = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B        = xNew<IssmDouble>(epssize*numdof);
+	IssmDouble*    Bprime   = xNew<IssmDouble>(epssize*numdof);
+	IssmDouble*    BtBUzawa = xNewZeroInit<IssmDouble>(numdof*pnumdof);
+	IssmDouble*    BU       = xNew<IssmDouble>(pnumdof);
+	IssmDouble*    BprimeU  = xNew<IssmDouble>(numdof);
+	IssmDouble*    D        = xNewZeroInit<IssmDouble>(epssize*epssize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBFSvel(B,element,dim,xyz_list,gauss);
+		this->GetBFSprimevel(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		for(i=0;i<epssize;i++)   D[i*epssize+i] = 2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply(B,epssize,numdof,1,
+					D,epssize,epssize,0,
+					Bprime,epssize,numdof,0,
+					&Ke->values[0],1);
+
+		this->GetBFSUzawa(BU,element,dim,xyz_list,gauss);
+		this->GetBFSprimeUzawa(BprimeU,element,dim,xyz_list,gauss);
+
+		DU = gauss->weight*Jdet*sqrt(r);
+
+		TripleMultiply(BU,1,pnumdof,1,
+					&DU,1,1,0,
+					BprimeU,1,numdof,0,
+					BtBUzawa,1);
+
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*The pressure augmentation should not be transformed*/
+	MatrixMultiply(BtBUzawa,pnumdof,numdof,1,
+				BtBUzawa,pnumdof,numdof,0,
+				&Ke->values[0],1);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(BprimeU);
+	xDelete<IssmDouble>(BU);
+	xDelete<IssmDouble>(BtBUzawa);
+	xDelete<int>(cs_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousXTH(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,dim,epssize;
+	IssmDouble  r,FSreconditioning,Jdet;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+	int bsize     = epssize + 2;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBFS(B,element,dim,xyz_list,gauss);
+		this->GetBFSprime(Bprime,element,dim,xyz_list,gauss);
+
+		for(i=0;i<epssize;i++)     D[i*bsize+i] = + r*gauss->weight*Jdet;
+		for(i=epssize;i<bsize;i++) D[i*bsize+i] = - FSreconditioning*gauss->weight*Jdet;
+
+		TripleMultiply(B,bsize,numdof,1,
+					D,bsize,bsize,0,
+					Bprime,bsize,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	xDelete<int>(cs_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,dim,epssize;
+	IssmDouble  viscosity,FSreconditioning,Jdet;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+	int bsize     = epssize + 2;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBFS(B,element,dim,xyz_list,gauss);
+		this->GetBFSprime(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		for(i=0;i<epssize;i++)     D[i*bsize+i] = + 2.*viscosity*gauss->weight*Jdet;
+		for(i=epssize;i<bsize;i++) D[i*bsize+i] = - FSreconditioning*gauss->weight*Jdet;
+
+		TripleMultiply(B,bsize,numdof,1,
+					D,bsize,bsize,0,
+					Bprime,bsize,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	xDelete<int>(cs_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSShelf(Element* element){/*{{{*/
+
+	if(!element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*If on not water or not FS, skip stiffness: */
+	int approximation,shelf_dampening;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
+	if(shelf_dampening==0) return NULL;
+
+	/*Intermediaries*/
+	bool        mainlyfloating;
+	int         j,i,dim;
+	IssmDouble  Jdet,slope2,scalar,dt;
+	IssmDouble  slope[3];
+	IssmDouble *xyz_list_base = NULL;
+	IssmDouble *xyz_list      = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	if(dt==0)   dt=1.e+5;
+	IssmDouble  rho_water     = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity       = element->GetMaterialParameter(ConstantsGEnum);
+	Input*      surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		if(dim==2) slope2=slope[0]*slope[0];
+		else if(dim==3) slope2=slope[0]*slope[0]+slope[1]*slope[1];
+		scalar  = rho_water*gravity*sqrt(1+slope2)*gauss->weight*Jdet*dt; 
+		for(i=0;i<vnumnodes;i++){
+			for(j=0;j<vnumnodes;j++){
+				Ke->values[numdof*((i+1)*dim-1)+(j+1)*dim-1] += scalar*vbasis[i]*vbasis[j];
+			}
+		}
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(vbasis);
+	return Ke;
+}/*}}}*/
+#ifdef FSANALYTICAL
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSFriction(Element* element){/*{{{*/
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*If on water or not FS, skip stiffness: */
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Intermediaries*/
+	int         i,dim;
+	IssmDouble  alpha2,Jdet;
+	IssmDouble  x_coord,y_coord,z_coord;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input* vx_input         = element->GetInput(VxEnum);      _assert_(vx_input);
+	Input* vy_input         = element->GetInput(VyEnum);      _assert_(vy_input);
+	Input* vz_input         = NULL;
+	if(dim==3){    vz_input = element->GetInput(VzEnum);      _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(10);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		x_coord=element->GetXcoord(xyz_list_base,gauss);
+		y_coord=element->GetYcoord(xyz_list_base,gauss);
+		if(dim==3) z_coord=element->GetZcoord(xyz_list_base,gauss);
+		else z_coord=0.;
+
+		alpha2=alpha(x_coord,y_coord,z_coord,FSANALYTICAL);
+
+		this->GetBFSFriction(B,element,dim,xyz_list_base,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i] = alpha2*gauss->weight*Jdet; //taub_x = -alpha2 v_x (same for y)
+
+		TripleMultiply(B,dim-1,numdof,1,
+					D,dim-1,dim-1,0,
+					B,dim-1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFS(Element* element){/*{{{*/
+
+	int         i,dim,fe_FS;
+	IssmDouble  x_coord,y_coord,z_coord;
+	IssmDouble  Jdet,forcex,forcey,forcez;
+	IssmDouble *xyz_list = NULL;
+
+	element->FindParam(&fe_FS,FlowequationFeFSEnum);
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		x_coord=element->GetXcoord(xyz_list,gauss);
+		y_coord=element->GetYcoord(xyz_list,gauss);
+		if(dim==3) z_coord=element->GetZcoord(xyz_list,gauss);
+		else z_coord=0.;
+
+		forcex=fx(x_coord,y_coord,z_coord,FSANALYTICAL);
+		forcey=fy(x_coord,y_coord,z_coord,FSANALYTICAL);
+		forcez=fz(x_coord,y_coord,z_coord,FSANALYTICAL);
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += forcex *Jdet*gauss->weight*vbasis[i];
+			pe->values[i*dim+1] += forcey *Jdet*gauss->weight*vbasis[i];
+			if(dim==3) pe->values[i*dim+2] += forcez *Jdet*gauss->weight*vbasis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list);
+	if(fe_FS==XTaylorHoodEnum){
+		ElementVector* pe2=CreatePVectorFSViscousXTH(element);
+		ElementVector* pe3 = new ElementVector(pe,pe2);
+		delete pe;
+		delete pe2;
+		return pe3;
+	}
+	else if(fe_FS==LATaylorHoodEnum){
+		ElementVector* pe2=CreatePVectorFSViscousLATH(element);
+		ElementVector* pe3 = new ElementVector(pe,pe2);
+		delete pe;
+		delete pe2;
+		return pe3;
+	}
+	return pe;
+}/*}}}*/
+#else
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSFriction(Element* element){/*{{{*/
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*If on water or not FS, skip stiffness: */
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Intermediaries*/
+	bool        mainlyfloating;
+	int         dim,domaintype;
+	int         migration_style,point1;
+	IssmDouble  alpha2,Jdet,fraction1,fraction2;
+	IssmDouble  gllevelset,phi=1.;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&migration_style,GroundinglineMigrationEnum);
+	Input* gllevelset_input = NULL;
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,dim==3?3:1);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=element->GetGroundedPortion(xyz_list_base);
+	if(migration_style==SubelementMigration2Enum){
+		if(domaintype==Domain2DverticalEnum) _error_("Subelement Migration 2 not implemented yet for Flowline");
+		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+		//gauss = element->NewGauss(point1,fraction1,fraction2,mainlyfloating,2);
+		gauss=element->NewGaussBase(3);
+	}
+	else{
+		gauss=element->NewGaussBase(3);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss);
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0.) alpha2=0.;
+		}
+
+		this->GetBFSFriction(B,element,dim,xyz_list_base,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i] = alpha2*gauss->weight*Jdet; //taub_x = -alpha2 v_x (same for y)
+
+		TripleMultiply(B,dim-1,numdof,1,
+					D,dim-1,dim-1,0,
+					B,dim-1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFS(Element* element){/*{{{*/
+
+	ElementVector* pe = NULL;
+
+	int fe_FS;
+	element->FindParam(&fe_FS,FlowequationFeFSEnum);
+
+	if(fe_FS==XTaylorHoodEnum){
+		ElementVector* pe1=CreatePVectorFSViscous(element);
+		ElementVector* pe2=CreatePVectorFSShelf(element);
+		ElementVector* pe3=CreatePVectorFSFront(element);
+		ElementVector* petemp =new ElementVector(pe1,pe2,pe3);
+		ElementVector* pe4=CreatePVectorFSViscousXTH(element);
+		pe = new ElementVector(petemp,pe4);
+		delete pe1;
+		delete pe2;
+		delete pe3;
+		delete petemp;
+		delete pe4;
+	}
+	else if(fe_FS==LATaylorHoodEnum){
+		ElementVector* pe1=CreatePVectorFSViscous(element);
+		ElementVector* pe2=CreatePVectorFSShelf(element);
+		ElementVector* pe3=CreatePVectorFSFront(element);
+		ElementVector* petemp =new ElementVector(pe1,pe2,pe3);
+		ElementVector* pe4=CreatePVectorFSViscousLATH(element);
+		pe = new ElementVector(petemp,pe4);
+		delete pe1;
+		delete pe2;
+		delete pe3;
+		delete petemp;
+		delete pe4;
+	}
+	else{
+		ElementVector* pe1=CreatePVectorFSViscous(element);
+		ElementVector* pe2=CreatePVectorFSShelf(element);
+		ElementVector* pe3=CreatePVectorFSFront(element);
+		pe =new ElementVector(pe1,pe2,pe3);
+		delete pe1;
+		delete pe2;
+		delete pe3;
+	}
+
+	/*clean-up and return*/
+	return pe;
+}/*}}}*/
+#endif
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscous(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,forcex,forcey,forcez;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	IssmDouble  rho_ice =element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  gravity =element->GetMaterialParameter(ConstantsGEnum);
+	Input*      loadingforcex_input=element->GetInput(LoadingforceXEnum);  _assert_(loadingforcex_input);
+	Input*      loadingforcey_input=element->GetInput(LoadingforceYEnum);  _assert_(loadingforcey_input);
+	Input*      loadingforcez_input=NULL;
+	if(dim==3){
+		loadingforcez_input=element->GetInput(LoadingforceZEnum);  _assert_(loadingforcez_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		loadingforcex_input->GetInputValue(&forcex,gauss);
+		loadingforcey_input->GetInputValue(&forcey,gauss);
+		if(dim==3) loadingforcez_input->GetInputValue(&forcez,gauss);
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += +rho_ice*forcex *Jdet*gauss->weight*vbasis[i];
+			pe->values[i*dim+1] += +rho_ice*forcey *Jdet*gauss->weight*vbasis[i];
+			if(dim==3){
+				pe->values[i*dim+2] += +rho_ice*forcez*Jdet*gauss->weight*vbasis[i];
+				pe->values[i*dim+2] += -rho_ice*gravity*Jdet*gauss->weight*vbasis[i];
+			}
+			else{
+				pe->values[i*dim+1] += -rho_ice*gravity*Jdet*gauss->weight*vbasis[i];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousXTH(Element* element){/*{{{*/
+
+	int         i,tausize,dim;
+	IssmDouble  Jdet,r;
+	IssmDouble  epsxx,epsyy,epszz,epsxy,epsxz,epsyz;
+	IssmDouble  sigmapxx,sigmapyy,sigmapzz,sigmapxy,sigmapxz,sigmapyz;
+	IssmDouble *xyz_list = NULL;
+	Gauss*      gauss    = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) tausize = 3;
+	else       tausize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int tnumnodes = element->GetNumberOfVertices();      //Tensors, P1 DG
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i]  = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe      = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    Dstar   = xNewZeroInit<IssmDouble>((dim*vnumnodes)*(tausize*tnumnodes));
+	IssmDouble*    tau     = xNew<IssmDouble>(tausize*tnumnodes);
+	IssmDouble*    d       = xNew<IssmDouble>(tausize*tnumnodes);
+	IssmDouble*    vdbasis = xNew<IssmDouble>(dim*vnumnodes);
+	IssmDouble*    tbasis  = xNew<IssmDouble>(tnumnodes);
+	IssmDouble*    D       = xNewZeroInit<IssmDouble>(tausize*tnumnodes*tausize*tnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Get d and tau*/
+	Input* epsxx_input=element->GetInput(StrainRatexxEnum); _assert_(epsxx_input);
+	Input* epsyy_input=element->GetInput(StrainRateyyEnum); _assert_(epsyy_input);
+	Input* epsxy_input=element->GetInput(StrainRatexyEnum); _assert_(epsxy_input);
+	Input* epszz_input=NULL; Input* epsxz_input=NULL; Input* epsyz_input=NULL;
+	Input* sigmapxx_input=element->GetInput(DeviatoricStressxxEnum); _assert_(sigmapxx_input);
+	Input* sigmapyy_input=element->GetInput(DeviatoricStressyyEnum); _assert_(sigmapyy_input);
+	Input* sigmapxy_input=element->GetInput(DeviatoricStressxyEnum); _assert_(sigmapxy_input);
+	Input* sigmapzz_input=NULL; Input* sigmapxz_input=NULL; Input* sigmapyz_input=NULL;
+	if(dim==3){
+		epszz_input=element->GetInput(StrainRatezzEnum); _assert_(epszz_input);
+		epsxz_input=element->GetInput(StrainRatexzEnum); _assert_(epsxz_input);
+		epsyz_input=element->GetInput(StrainRateyzEnum); _assert_(epsyz_input);
+		sigmapzz_input=element->GetInput(DeviatoricStresszzEnum); _assert_(sigmapzz_input);
+		sigmapxz_input=element->GetInput(DeviatoricStressxzEnum); _assert_(sigmapxz_input);
+		sigmapyz_input=element->GetInput(DeviatoricStressyzEnum); _assert_(sigmapyz_input);
+	}
+
+	gauss = element->NewGauss();
+	for(int i=0;i<tnumnodes;i++){
+		gauss->GaussNode(P1DGEnum,i);
+
+		epsxx_input->GetInputValue(&epsxx,gauss); sigmapxx_input->GetInputValue(&sigmapxx,gauss);
+		epsyy_input->GetInputValue(&epsyy,gauss); sigmapyy_input->GetInputValue(&sigmapyy,gauss);
+		epsxy_input->GetInputValue(&epsxy,gauss); sigmapxy_input->GetInputValue(&sigmapxy,gauss);
+		if(dim==2){
+			d[i*tausize+0]=epsxx;  tau[i*tausize+0]=sigmapxx;
+			d[i*tausize+1]=epsyy;  tau[i*tausize+1]=sigmapyy;
+			d[i*tausize+2]=epsxy;  tau[i*tausize+2]=sigmapxy;
+		}
+		else{
+			epszz_input->GetInputValue(&epszz,gauss); sigmapzz_input->GetInputValue(&sigmapzz,gauss);
+			epsxz_input->GetInputValue(&epsxz,gauss); sigmapxz_input->GetInputValue(&sigmapxz,gauss);
+			epsyz_input->GetInputValue(&epsyz,gauss); sigmapyz_input->GetInputValue(&sigmapyz,gauss);
+			d[i*tausize+0]=epsxx;  tau[i*tausize+0]=sigmapxx;
+			d[i*tausize+1]=epsyy;  tau[i*tausize+1]=sigmapyy;
+			d[i*tausize+2]=epszz;  tau[i*tausize+2]=sigmapzz;
+			d[i*tausize+3]=epsxy;  tau[i*tausize+3]=sigmapxy;
+			d[i*tausize+4]=epsxz;  tau[i*tausize+4]=sigmapxz;
+			d[i*tausize+5]=epsyz;  tau[i*tausize+5]=sigmapyz;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	delete gauss;
+	gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Create Dstar*/
+		/*In dim = 2
+		 *
+		 *       <----------------- tausize ---------------> x tnumnodes
+		 *       |  gamma_ij^x         0       gamma_ij^y  | ^
+		 * Dij = |                                         | dim
+		 *       |     0          gamma_ij^y   gamma_ij^x  | v
+		 *                                                   x
+		 *                                                   vnumnodes
+		 *
+		 *In dim = 3
+		 *
+		 *       |  gamma_ij^x         0          0         gamma_ij^y  gamma_ij^z      0      |
+		 *       |                                                                             |
+		 * Dij = |     0          gamma_ij^y      0         gamma_ij^x     0        gamma_ij^z |
+		 *       |                                                                             |
+		 *       |     0               0      gamma_ij^z        0       gamma_ij^x  gamma_ij^y |
+		 *
+		 * gamma_ij^x = zeta_j dphi_i/dx
+		 *
+		 * where:
+		 *   - zeta_j is the nodal function for the j^th node of the tensor (P1DG)
+		 *   - phi_i  is the nodal function for the i^th node of the velocity (P2)*/
+		element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+		element->NodalFunctionsTensor(tbasis,gauss);
+		if(dim==2){
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<tnumnodes;j++){
+					Dstar[(i*dim+0)*tausize*tnumnodes + j*tausize+0] += gauss->weight*Jdet*tbasis[j]*vdbasis[0*vnumnodes+i];
+					Dstar[(i*dim+0)*tausize*tnumnodes + j*tausize+2] += gauss->weight*Jdet*tbasis[j]*vdbasis[1*vnumnodes+i];
+
+					Dstar[(i*dim+1)*tausize*tnumnodes + j*tausize+1] += gauss->weight*Jdet*tbasis[j]*vdbasis[1*vnumnodes+i];
+					Dstar[(i*dim+1)*tausize*tnumnodes + j*tausize+2] += gauss->weight*Jdet*tbasis[j]*vdbasis[0*vnumnodes+i];
+				}
+			}
+		}
+		else{
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<tnumnodes;j++){
+					Dstar[(i*dim+0)*tausize*tnumnodes + j*tausize+0] += gauss->weight*Jdet*tbasis[j]*vdbasis[0*vnumnodes+i];
+					Dstar[(i*dim+0)*tausize*tnumnodes + j*tausize+3] += gauss->weight*Jdet*tbasis[j]*vdbasis[1*vnumnodes+i];
+					Dstar[(i*dim+0)*tausize*tnumnodes + j*tausize+4] += gauss->weight*Jdet*tbasis[j]*vdbasis[2*vnumnodes+i];
+
+					Dstar[(i*dim+1)*tausize*tnumnodes + j*tausize+1] += gauss->weight*Jdet*tbasis[j]*vdbasis[1*vnumnodes+i];
+					Dstar[(i*dim+1)*tausize*tnumnodes + j*tausize+3] += gauss->weight*Jdet*tbasis[j]*vdbasis[0*vnumnodes+i];
+					Dstar[(i*dim+1)*tausize*tnumnodes + j*tausize+5] += gauss->weight*Jdet*tbasis[j]*vdbasis[2*vnumnodes+i];
+
+					Dstar[(i*dim+2)*tausize*tnumnodes + j*tausize+2] += gauss->weight*Jdet*tbasis[j]*vdbasis[2*vnumnodes+i];
+					Dstar[(i*dim+2)*tausize*tnumnodes + j*tausize+4] += gauss->weight*Jdet*tbasis[j]*vdbasis[0*vnumnodes+i];
+					Dstar[(i*dim+2)*tausize*tnumnodes + j*tausize+5] += gauss->weight*Jdet*tbasis[j]*vdbasis[1*vnumnodes+i];
+				}
+			}
+		}
+	}
+
+	/*contribution -Dstar tau*/
+	for(i=0;i<tausize*tnumnodes;i++) D[i*(tausize*tnumnodes)+i] = -1.;
+	TripleMultiply(Dstar,dim*vnumnodes,tausize*tnumnodes,0,
+				D,tausize*tnumnodes,tausize*tnumnodes,0,
+				tau,tausize*tnumnodes,1,0,
+				&pe->values[0],1);
+
+	/*contribution + r Dstar d*/
+	for(i=0;i<tausize*tnumnodes;i++) D[i*(tausize*tnumnodes)+i] = +r;
+	TripleMultiply(Dstar,dim*vnumnodes,tausize*tnumnodes,0,
+				D,tausize*tnumnodes,tausize*tnumnodes,0,
+				d,tausize*tnumnodes,1,0,
+				&pe->values[0],1);
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(Dstar);
+	xDelete<IssmDouble>(d);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(tau);
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(tbasis);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousLATH(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,r,pressure;
+	IssmDouble *xyz_list = NULL;
+	Gauss*      gauss    = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(numnodes);
+	if(dim==2) for(i=0;i<numnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<numnodes;i++) cs_list[i] = XYZEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe      = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    dbasis  = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Get d and tau*/
+	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+
+	gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		
+		pressure_input->GetInputValue(&pressure, gauss);
+		element->NodalFunctionsDerivativesVelocity(dbasis,xyz_list,gauss);
+
+		for(i=0;i<numnodes;i++){
+			pe->values[i*dim+0] += pressure*gauss->weight*Jdet*dbasis[0*numnodes+i];
+			pe->values[i*dim+1] += pressure*gauss->weight*Jdet*dbasis[1*numnodes+i];
+			if(dim==3){
+				pe->values[i*dim+2]+= pressure*gauss->weight*Jdet*dbasis[2*numnodes+i];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	//element->TransformLoadVectorCoord(pe,cs_list); Do not transform pressure augmentation
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSShelf(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,water_pressure,bed;
+	IssmDouble	normal[3];
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*      base_input=element->GetInput(BaseEnum); _assert_(base_input);
+	IssmDouble  rho_water=element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity  =element->GetMaterialParameter(ConstantsGEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		element->NormalBase(&normal[0],xyz_list_base);
+		_assert_(normal[dim-1]<0.);
+		base_input->GetInputValue(&bed, gauss);
+		water_pressure=gravity*rho_water*bed;
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[0];
+			pe->values[i*dim+1] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[1];
+			if(dim==3){
+				pe->values[i*dim+2]+=water_pressure*gauss->weight*Jdet*vbasis[i]*normal[2];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/* shelf dampening*/
+	int shelf_dampening;
+	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
+	if(shelf_dampening) {
+		Input*      mb_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(mb_input);
+		IssmDouble dt,mb,normal_b;
+		element->FindParam(&dt,TimesteppingTimeStepEnum);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			element->NodalFunctionsVelocity(vbasis,gauss);
+			element->NormalBase(&normal[0],xyz_list_base);
+			if (dim==2) normal_b=normal[1];
+			else if (dim==3) normal_b=sqrt(normal[0]*normal[0]+normal[1]*normal[1]);
+			mb_input->GetInputValue(&mb, gauss);
+			for(i=0;i<vnumnodes;i++){
+				pe->values[i*dim+1] += dt*rho_water*gravity*mb*gauss->weight*Jdet*vbasis[i]*normal_b;
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSFront(Element* element){/*{{{*/
+
+	/*If no front, return NULL*/
+	if(!element->IsIcefront()) return NULL;
+
+	/*Intermediaries*/
+	int         i,dim;
+	IssmDouble  Jdet,pressure,surface,z;
+	IssmDouble	normal[3];
+	IssmDouble *xyz_list       = NULL;
+	IssmDouble *xyz_list_front = NULL;
+	Gauss      *gauss          = NULL;
+
+	/*Make sure current element is floating*/
+	if(!element->IsFloating()) return NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes   = element->NumberofNodesVelocity();
+	int pnumnodes   = element->NumberofNodesPressure();
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+	Input* surface_input  = element->GetInput(SurfaceEnum); _assert_(surface_input);
+	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity   = element->GetMaterialParameter(ConstantsGEnum);
+
+	/*Initialize gauss points*/
+	IssmDouble zmax=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]>zmax) zmax=xyz_list[i*3+(dim-1)];
+	IssmDouble zmin=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]<zmin) zmin=xyz_list[i*3+(dim-1)];
+	if(zmax>0. && zmin<0.) gauss=element->NewGauss(xyz_list,xyz_list_front,3,30);//refined in vertical because of the sea level discontinuity
+	else                   gauss=element->NewGauss(xyz_list,xyz_list_front,3,3);
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+		if(dim==3) z=element->GetZcoord(xyz_list,gauss);
+		else       z=element->GetYcoord(xyz_list,gauss);
+		pressure = rho_water*gravity*min(0.,z);//0 if the gaussian point is above water level
+
+		for (int i=0;i<vnumnodes;i++){
+			pe->values[dim*i+0]+= pressure*Jdet*gauss->weight*normal[0]*vbasis[i];
+			pe->values[dim*i+1]+= pressure*Jdet*gauss->weight*normal[1]*vbasis[i];
+			if(dim==3) pe->values[dim*i+2]+= pressure*Jdet*gauss->weight*normal[2]*vbasis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	return pe;
+}/*}}}*/
+void StressbalanceAnalysis::GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
+	 * For node i, Bvi can be expressed in the actual coordinate system
+	 * by: 	   Bvi=[ dphi/dx          0        ]
+	 *					 [   0           dphi/dy     ]
+	 *					 [ 1/2*dphi/dy    1/2*dphi/dx]
+	 *					 [   0             0         ]
+	 *					 [ dphi/dx         dphi/dy   ]
+	 *
+	 *         Bpi=[  0    ]
+	 *					[  0    ]
+	 *					[  0    ]
+	 *					[ phi_p ]
+	 *					[  0    ]
+	 *
+	 *	In 3d:
+	 *     	   Bvi=[ dh/dx          0             0      ]
+	 *					[   0           dh/dy           0      ]
+	 *					[   0             0           dh/dz    ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0      ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy  ]
+	 *					[   0             0             0      ]
+	 *					[ dh/dx         dh/dy         dh/dz    ]
+	 *
+	 *         Bpi=[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ h ]
+	 *					[ 0 ]
+	 *	where phi is the finiteelement function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	element->NodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes+pnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*2+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*2+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*3+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*3+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*4+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*4+dim*i+1] = vdbasis[1*vnumnodes+i];
+		}
+		for(int i=0;i<pnumnodes;i++){
+			B[(dim*vnumnodes+pnumnodes)*0+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*2+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*3+(dim*vnumnodes)+i] = pbasis[i];
+			B[(dim*vnumnodes+pnumnodes)*4+(dim*vnumnodes)+i] = 0.;
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes+pnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*0+dim*i+2] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*1+dim*i+2] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*2+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*2+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*3+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*3+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*3+dim*i+2] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*4+dim*i+0] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*4+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*4+dim*i+2] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*5+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*5+dim*i+1] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*5+dim*i+2] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*6+dim*i+0] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*6+dim*i+1] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*6+dim*i+2] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*7+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*7+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes+pnumnodes)*7+dim*i+2] = vdbasis[2*vnumnodes+i];
+		}
+		for(int i=0;i<pnumnodes;i++){
+			B[(dim*vnumnodes+pnumnodes)*0+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*1+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*2+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*3+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*4+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*5+(dim*vnumnodes)+i] = 0.;
+			B[(dim*vnumnodes+pnumnodes)*6+(dim*vnumnodes)+i] = pbasis[i];
+			B[(dim*vnumnodes+pnumnodes)*7+(dim*vnumnodes)+i] = 0.;
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx     0     ]
+	 *					 [     0      dphi/dy ]
+	 *					 [  dphi/dy   dphi/dx ]
+	 *					 [  dphi/dx   dphi/dy ]
+	 *					 [     0      0       ]
+	 *
+	 * by: 	  Bpi=[  0  ]
+	 *					[  0  ]
+	 *					[  0  ]
+	 *					[  0  ]
+	 *					[ phi ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx     0        0    ]
+	 *					[   0      dh/dy      0    ]
+	 *					[   0        0      dh/dz  ]
+	 *					[ dh/dy    dh/dx      0    ]
+	 *					[ dh/dz      0      dh/dx  ]
+	 *					[   0      dh/dz    dh/dy  ]
+	 *					[ dh/dx    dh/dy    dh/dz  ]
+	 *					[   0        0        0    ]
+	 *
+	 *         Bpi=[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ h ]
+	 *	where phi is the finiteelement function for node i.
+	 *	In 3d:
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	element->NodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes+pnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*2+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*2+dim*i+1] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*3+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*3+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*4+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*4+dim*i+1] = 0.;
+		}
+		for(int i=0;i<pnumnodes;i++){
+			Bprime[(dim*vnumnodes+pnumnodes)*0+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*2+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*3+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*4+(dim*vnumnodes)+i] = pbasis[i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes+pnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*0+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*1+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*2+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*2+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*3+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*3+dim*i+1] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*3+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*4+dim*i+0] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*4+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*4+dim*i+2] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*5+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*5+dim*i+1] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*5+dim*i+2] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*6+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*6+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*6+dim*i+2] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes+pnumnodes)*7+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*7+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*7+dim*i+2] = 0.;
+		}
+		for(int i=0;i<pnumnodes;i++){
+			Bprime[(dim*vnumnodes+pnumnodes)*0+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*1+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*2+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*3+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*4+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*5+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*6+(dim*vnumnodes)+i] = 0.;
+			Bprime[(dim*vnumnodes+pnumnodes)*7+(dim*vnumnodes)+i] = pbasis[i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
+	 * For node i, Bvi can be expressed in the actual coordinate system
+	 * by: 	   Bvi=[ dphi/dx          0        ]
+	 *					 [   0           dphi/dy     ]
+	 *					 [ 1/2*dphi/dy    1/2*dphi/dx]
+	 *
+	 *
+	 *	In 3d:
+	 *     	   Bvi=[ dh/dx          0             0      ]
+	 *					[   0           dh/dy           0      ]
+	 *					[   0             0           dh/dz    ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0      ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy  ]
+	 *
+	 *	where phi is the finiteelement function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*2+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*2+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*0+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*1+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*4+dim*i+0] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*4+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*4+dim*i+2] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*5+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*5+dim*i+1] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*5+dim*i+2] = .5*vdbasis[1*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSprimevel(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx     0     ]
+	 *					 [     0      dphi/dy ]
+	 *					 [  dphi/dy   dphi/dx ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx     0        0    ]
+	 *					[   0      dh/dy      0    ]
+	 *					[   0        0      dh/dz  ]
+	 *					[ dh/dy    dh/dx      0    ]
+	 *					[ dh/dz      0      dh/dx  ]
+	 *					[   0      dh/dz    dh/dy  ]
+	 *	where phi is the finiteelement function for node i.
+	 *	In 3d:
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = vdbasis[0*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*0+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*1+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+1] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+0] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*4+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+2] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*5+dim*i+1] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+2] = vdbasis[1*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bp1 Bp2 ...] where Bpi=phi_pi. 
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes;
+	if(dim==2) pnumnodes=3;
+	else pnumnodes=6;
+	//int pnumnodes = element->NumberofNodes(P1Enum);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis =xNew<IssmDouble>(pnumnodes);
+	element->NodalFunctionsP1(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<pnumnodes;i++){
+		B[i] = basis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSprimeUzawa(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx   dphi/dy ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx   dh/dy    dh/dz  ]
+	 *	where phi is the finiteelement function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[dim*i+2] = vdbasis[2*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by in 3d 
+	 *       Li=[ h 0 0 0 ]
+	 *	 	      [ 0 h 0 0 ]
+	 *	in 2d:
+	 *       Li=[ h 0 0 ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumdof   = pnumnodes;
+	int vnumdof   = vnumnodes*dim;
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
+	element->NodalFunctionsVelocity(vbasis,gauss);
+
+	/*Build B: */
+	if(dim==3){
+		for(int i=0;i<vnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+3*i+0] = vbasis[i];
+			B[(vnumdof+pnumdof)*0+3*i+1] = 0.;
+			B[(vnumdof+pnumdof)*0+3*i+2] = 0.;
+
+			B[(vnumdof+pnumdof)*1+3*i+0] = 0.;
+			B[(vnumdof+pnumdof)*1+3*i+1] = vbasis[i];
+			B[(vnumdof+pnumdof)*1+3*i+2] = 0.;
+		}
+		for(int i=0;i<pnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			B[2*i+0] = vbasis[i];
+			B[2*i+1] = 0.;
+		}
+
+		for(int i=0;i<pnumnodes;i++){
+			B[i+vnumdof+0] = 0.;
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(vbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	Input*       vz_input=NULL;
+	int          dim;
+	IssmDouble   vx,vy,vz,p;
+	IssmDouble   FSreconditioning;
+
+	/*Get some parameters*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*dim;
+	int pnumdof   = pnumnodes*1;
+
+	/*Initialize values*/
+	IssmDouble* vvalues = xNew<IssmDouble>(vnumdof);
+	IssmDouble* pvalues = xNew<IssmDouble>(pnumdof);
+
+	/*Get dof list: */
+	element->GetDofListVelocity(&vdoflist,GsetEnum);
+	element->GetDofListPressure(&pdoflist,GsetEnum);
+	Input*     vx_input=element->GetInput(VxEnum);       _assert_(vx_input);
+	Input*     vy_input=element->GetInput(VyEnum);       _assert_(vy_input);
+	if(dim==3){vz_input=element->GetInput(VzEnum);       _assert_(vz_input);}
+	Input*     p_input =element->GetInput(PressureEnum); _assert_(p_input);
+
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	/*Ok, we have the velocities in inputs, fill in solution */
+	Gauss* gauss = element->NewGauss();
+	for(int i=0;i<vnumnodes;i++){
+		gauss->GaussNode(element->VelocityInterpolation(),i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vvalues[i*dim+0]=vx;
+		vvalues[i*dim+1]=vy;
+		if(dim==3){
+			vz_input->GetInputValue(&vz,gauss);
+			vvalues[i*dim+2]=vz;
+		}
+	}
+	for(int i=0;i<pnumnodes;i++){
+		gauss->GaussNode(element->PressureInterpolation(),i);
+		p_input->GetInputValue(&p ,gauss);
+		pvalues[i]=p/FSreconditioning;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(vnumdof,vdoflist,vvalues,INS_VAL);
+	if(pnumdof>0) solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(pdoflist);
+	xDelete<int>(vdoflist);
+	xDelete<IssmDouble>(pvalues);
+	xDelete<IssmDouble>(vvalues);
+}/*}}}*/
+void StressbalanceAnalysis::InitializeXTH(Elements* elements,Parameters* parameters){/*{{{*/
+
+	/*Intermediaries*/
+	int        dim;
+	IssmDouble dvx[3],dvy[3],dvz[3];
+	IssmDouble viscosity;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	parameters->FindParam(&dim,DomainDimensionEnum);
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*Get inputs and parameters*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+		Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+		Input* vz_input;
+		if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+		/*Allocate new inputs*/
+		int tnumnodes = element->GetNumberOfVertices();      //Tensors, P1 DG
+		IssmDouble* epsxx = xNew<IssmDouble>(tnumnodes); IssmDouble* sigmapxx = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* epsyy = xNew<IssmDouble>(tnumnodes); IssmDouble* sigmapyy = xNew<IssmDouble>(tnumnodes); 
+		IssmDouble* epsxy = xNew<IssmDouble>(tnumnodes); IssmDouble* sigmapxy = xNew<IssmDouble>(tnumnodes); 
+		IssmDouble* epszz = NULL;                        IssmDouble* sigmapzz = NULL;  
+		IssmDouble* epsxz = NULL;                        IssmDouble* sigmapxz = NULL;  
+		IssmDouble* epsyz = NULL;                        IssmDouble* sigmapyz = NULL;  
+		if(dim==3){
+			epszz = xNew<IssmDouble>(tnumnodes); sigmapzz = xNew<IssmDouble>(tnumnodes);
+			epsxz = xNew<IssmDouble>(tnumnodes); sigmapxz = xNew<IssmDouble>(tnumnodes); 
+			epsyz = xNew<IssmDouble>(tnumnodes); sigmapyz = xNew<IssmDouble>(tnumnodes); 
+		}
+
+		/*Get d and tau*/
+		Gauss* gauss = element->NewGauss();
+		for(int i=0;i<tnumnodes;i++){
+			gauss->GaussNode(P1DGEnum,i);
+
+			vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+			vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+			if(dim==3){
+				vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+			}
+
+			element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+			epsxx[i] = dvx[0];                sigmapxx[i] = 2.*viscosity*epsxx[i];
+			epsyy[i] = dvy[1];                sigmapyy[i] = 2.*viscosity*epsyy[i];
+			epsxy[i] = 0.5*(dvx[1] + dvy[0]); sigmapxy[i] = 2.*viscosity*epsxy[i];
+			if(dim==3){
+				epszz[i] = dvz[2];                sigmapzz[i] = 2.*viscosity*epszz[i];
+				epsxz[i] = 0.5*(dvx[2] + dvz[0]); sigmapxz[i] = 2.*viscosity*epsxz[i];
+				epsyz[i] = 0.5*(dvy[2] + dvz[1]); sigmapyz[i] = 2.*viscosity*epsyz[i];
+			}
+		}
+
+		/*Add inputs*/
+		element->AddInput(StrainRatexxEnum,epsxx,P1DGEnum); element->AddInput(DeviatoricStressxxEnum,sigmapxx,P1DGEnum);
+		element->AddInput(StrainRateyyEnum,epsyy,P1DGEnum); element->AddInput(DeviatoricStressyyEnum,sigmapyy,P1DGEnum);
+		element->AddInput(StrainRatexyEnum,epsxy,P1DGEnum); element->AddInput(DeviatoricStressxyEnum,sigmapxy,P1DGEnum);
+		if(dim==3){
+			element->AddInput(StrainRatezzEnum,epszz,P1DGEnum); element->AddInput(DeviatoricStresszzEnum,sigmapzz,P1DGEnum);
+			element->AddInput(StrainRatexzEnum,epsxz,P1DGEnum); element->AddInput(DeviatoricStressxzEnum,sigmapxz,P1DGEnum);
+			element->AddInput(StrainRateyzEnum,epsyz,P1DGEnum); element->AddInput(DeviatoricStressyzEnum,sigmapyz,P1DGEnum);
+		}
+
+		/*Clean up*/
+		delete gauss;
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(epsxx); xDelete<IssmDouble>(sigmapxx);
+		xDelete<IssmDouble>(epsyy); xDelete<IssmDouble>(sigmapyy);
+		xDelete<IssmDouble>(epszz); xDelete<IssmDouble>(sigmapzz);
+		xDelete<IssmDouble>(epsxy); xDelete<IssmDouble>(sigmapxy);
+		xDelete<IssmDouble>(epsxz); xDelete<IssmDouble>(sigmapxz);
+		xDelete<IssmDouble>(epsyz); xDelete<IssmDouble>(sigmapyz);
+	}
+
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
+
+	bool         results_on_nodes;
+	int          i,dim;
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   FSreconditioning;
+
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	element->FindParam(&results_on_nodes,SettingsResultsOnNodesEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*dim;
+	int pnumdof   = pnumnodes*1;
+
+	/*Initialize values*/
+	IssmDouble* values   = xNew<IssmDouble>(vnumdof+pnumdof);
+	IssmDouble* vx       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vy       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vz       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vel      = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(pnumnodes);
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Get dof list: */
+	element->GetDofListVelocity(&vdoflist,GsetEnum);
+	element->GetDofListPressure(&pdoflist,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<vnumdof;i++) values[i]        =solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) values[vnumdof+i]=solution[pdoflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(values,cs_list);
+
+	/*Ok, we have vx and vy in values, fill in all arrays: */
+	for(i=0;i<vnumnodes;i++){
+		vx[i] = values[i*dim+0];
+		vy[i] = values[i*dim+1];
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+
+		if(dim==3){
+			vz[i] = values[i*dim+2];
+			if(xIsNan<IssmDouble>(vz[i])) _error_("NaN found in solution vector");
+		}
+	}
+	for(i=0;i<pnumnodes;i++){
+		pressure[i] = values[vnumdof+i];
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	for(i=0;i<pnumnodes;i++) pressure[i] = pressure[i]*FSreconditioning;
+	if(dim==3) for(i=0;i<vnumnodes;i++) vel[i] = sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+	else       for(i=0;i<vnumnodes;i++) vel[i] = sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
+
+	/*Now, we have to move the previous inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+	if(pnumdof>0) element->InputChangeName(PressureEnum,PressurePicardEnum);
+	if(dim==3) element->InputChangeName(VzEnum,VzPicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(VxEnum,      vx,      element->VelocityInterpolation());
+	element->AddInput(VyEnum,      vy,      element->VelocityInterpolation());
+	element->AddInput(VelEnum,     vel,     element->VelocityInterpolation());
+	if(pnumdof>0) element->AddInput(PressureEnum,pressure,element->PressureInterpolation());
+	if(dim==3) element->AddInput(VzEnum,vz, element->VelocityInterpolation());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<int>(vdoflist);
+	xDelete<int>(pdoflist);
+	xDelete<int>(cs_list);
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters){/*{{{*/
+
+	/*Intermediaries*/
+	int         dim,tausize;
+	IssmDouble  epsxx,epsyy,epszz,epsxy,epsxz,epsyz,D_scalar;
+	IssmDouble  epsxx_old,epsyy_old,epszz_old,epsxy_old,epsxz_old,epsyz_old;
+	IssmDouble  sigmapxx,sigmapyy,sigmapzz,sigmapxy,sigmapxz,sigmapyz;
+	IssmDouble  dvx[3],dvy[3],dvz[3],B,n;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  Jdet,r;
+
+	parameters->FindParam(&r,AugmentedLagrangianREnum);
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) tausize = 3;
+	else       tausize = 6;
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*Get inputs and parameters*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input*  B_input=element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+		Input*  n_input=element->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
+		Input* vx_input=element->GetInput(VxEnum);                 _assert_(vx_input);
+		Input* vy_input=element->GetInput(VyEnum);                 _assert_(vy_input);
+		Input* vz_input;
+		if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+		/*Fetch number of nodes and dof for this finite element*/
+		int tnumnodes = element->GetNumberOfVertices();      //Tensors, P1 DG
+
+		/*Initialize vectors*/
+		IssmDouble* tbasis = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* Ke     = xNewZeroInit<IssmDouble>(tnumnodes*tnumnodes);
+		IssmDouble* pe_xx  = xNewZeroInit<IssmDouble>(tnumnodes);
+		IssmDouble* pe_yy  = xNewZeroInit<IssmDouble>(tnumnodes);
+		IssmDouble* pe_xy  = xNewZeroInit<IssmDouble>(tnumnodes);
+		IssmDouble* pe_zz  = NULL; IssmDouble* pe_xz  = NULL; IssmDouble* pe_yz  = NULL;
+		if(dim==3){
+			pe_zz = xNewZeroInit<IssmDouble>(tnumnodes);
+			pe_xz = xNewZeroInit<IssmDouble>(tnumnodes);
+			pe_yz = xNewZeroInit<IssmDouble>(tnumnodes);
+		}
+
+		/*Get previous d*/
+		Input* epsxx_input=element->GetInput(StrainRatexxEnum); _assert_(epsxx_input);
+		Input* epsyy_input=element->GetInput(StrainRateyyEnum); _assert_(epsyy_input);
+		Input* epsxy_input=element->GetInput(StrainRatexyEnum); _assert_(epsxy_input);
+		Input* epszz_input=NULL; Input* epsxz_input=NULL; Input* epsyz_input=NULL;
+		if(dim==3){
+			epszz_input=element->GetInput(StrainRatezzEnum); _assert_(epszz_input);
+			epsxz_input=element->GetInput(StrainRatexzEnum); _assert_(epsxz_input);
+			epsyz_input=element->GetInput(StrainRateyzEnum); _assert_(epsyz_input);
+		}
+
+		/*Get tau*/
+		Input* sigmapxx_input=element->GetInput(DeviatoricStressxxEnum); _assert_(sigmapxx_input);
+		Input* sigmapyy_input=element->GetInput(DeviatoricStressyyEnum); _assert_(sigmapyy_input);
+		Input* sigmapxy_input=element->GetInput(DeviatoricStressxyEnum); _assert_(sigmapxy_input);
+		Input* sigmapzz_input=NULL; Input* sigmapxz_input=NULL; Input* sigmapyz_input=NULL;
+		if(dim==3){
+			sigmapzz_input=element->GetInput(DeviatoricStresszzEnum); _assert_(sigmapzz_input);
+			sigmapxz_input=element->GetInput(DeviatoricStressxzEnum); _assert_(sigmapxz_input);
+			sigmapyz_input=element->GetInput(DeviatoricStressyzEnum); _assert_(sigmapyz_input);
+		}
+
+		Gauss* gauss=element->NewGauss(5);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+			element->NodalFunctionsTensor(tbasis,gauss);
+
+			/*Get tau from inputs*/
+			sigmapxx_input->GetInputValue(&sigmapxx,gauss);
+			sigmapyy_input->GetInputValue(&sigmapyy,gauss);
+			sigmapxy_input->GetInputValue(&sigmapxy,gauss);
+			if(dim==3){
+				sigmapzz_input->GetInputValue(&sigmapzz,gauss);
+				sigmapxz_input->GetInputValue(&sigmapxz,gauss);
+				sigmapyz_input->GetInputValue(&sigmapyz,gauss);
+			}
+
+			/*Get previous d*/
+			epsxx_input->GetInputValue(&epsxx_old,gauss);
+			epsyy_input->GetInputValue(&epsyy_old,gauss);
+			epsxy_input->GetInputValue(&epsxy_old,gauss);
+			if(dim==3){
+				epszz_input->GetInputValue(&epszz_old,gauss);
+				epsxz_input->GetInputValue(&epsxz_old,gauss);
+				epsyz_input->GetInputValue(&epsyz_old,gauss);
+			}
+
+			/*Calculate d from previous results*/
+			vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+			vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+			if(dim==3){
+				vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+			}
+			epsxx = dvx[0];
+			epsyy = dvy[1];
+			epsxy = 0.5*(dvx[1] + dvy[0]); 
+			if(dim==3){
+				epszz = dvz[2];               
+				epsxz = 0.5*(dvx[2] + dvz[0]);
+				epsyz = 0.5*(dvy[2] + dvz[1]);
+			}
+
+			/*Solve 2 eta_0 |d|^s-1 + r |d| = |rD(u) + tau|*/
+			IssmDouble coef1,coef2,coef3;
+			B_input->GetInputValue(&B,gauss);
+			n_input->GetInputValue(&n,gauss);
+			coef1 = B*pow(1./sqrt(2.),(1.-n)/n); //2 eta_0 = 2 * B/(2* (1/sqrt(2)  )^(n-1)/n ) 
+			coef2 = r;
+			if(dim==2){
+				coef3 = sqrt(
+							  (r*epsxx + sigmapxx)*(r*epsxx + sigmapxx)
+							+ (r*epsyy + sigmapyy)*(r*epsyy + sigmapyy)
+							+ 2*(r*epsxy + sigmapxy)*(r*epsxy + sigmapxy)
+							);
+			}
+			else{
+				coef3 = sqrt(
+					  		  (r*epsxx + sigmapxx)*(r*epsxx + sigmapxx)
+							+ (r*epsyy + sigmapyy)*(r*epsyy + sigmapyy)
+							+ (r*epszz + sigmapzz)*(r*epszz + sigmapzz)
+							+ 2*(r*epsxy + sigmapxy)*(r*epsxy + sigmapxy)
+							+ 2*(r*epsxz + sigmapxz)*(r*epsxz + sigmapxz)
+							+ 2*(r*epsyz + sigmapyz)*(r*epsyz + sigmapyz)
+							);
+			}
+			IssmDouble dnorm;
+			if(dim==2){
+				dnorm = sqrt( epsxx_old*epsxx_old + epsyy_old*epsyy_old + 2.*epsxy_old*epsxy_old );
+			}
+			else{
+				dnorm = sqrt( epsxx_old*epsxx_old + epsyy_old*epsyy_old + epszz_old*epszz_old 
+							+2.*(epsxy_old*epsxy_old + epsxz_old*epsxz_old + epsyz_old*epsyz_old));
+			}
+			/*Initial guess cannot be 0 otherwise log(0)  - inf*/
+			if(dnorm==0.) dnorm=1.;
+			NewtonSolveDnorm(&dnorm,coef1,coef2,coef3,n,dnorm);
+			_assert_(dnorm>=0.);
+			_assert_(!xIsNan<IssmDouble>(dnorm));
+
+			/*Create Ke*/
+			D_scalar=(coef1*pow(dnorm,(1.-n)/n)+r)*gauss->weight*Jdet;
+			TripleMultiply(tbasis,tnumnodes,1,0,
+						&D_scalar,1,1,0,
+						tbasis,1,tnumnodes,0,
+						Ke,1);
+
+			/*Create Right hand sides*/
+			for(int ii=0;ii<tnumnodes;ii++) pe_xx[ii] += (r*epsxx+sigmapxx)*tbasis[ii]*gauss->weight*Jdet;
+			for(int ii=0;ii<tnumnodes;ii++) pe_yy[ii] += (r*epsyy+sigmapyy)*tbasis[ii]*gauss->weight*Jdet;
+			for(int ii=0;ii<tnumnodes;ii++) pe_xy[ii] += (r*epsxy+sigmapxy)*tbasis[ii]*gauss->weight*Jdet;
+			if(dim==3){
+				for(int ii=0;ii<tnumnodes;ii++) pe_zz[ii] += (r*epszz+sigmapzz)*tbasis[ii]*gauss->weight*Jdet;
+				for(int ii=0;ii<tnumnodes;ii++) pe_xz[ii] += (r*epsxz+sigmapxz)*tbasis[ii]*gauss->weight*Jdet;
+				for(int ii=0;ii<tnumnodes;ii++) pe_yz[ii] += (r*epsyz+sigmapyz)*tbasis[ii]*gauss->weight*Jdet;
+			}
+		}
+
+		/*Solve the systems*/
+		IssmDouble* d_xx = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* d_yy = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* d_xy = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* d_zz = NULL;
+		IssmDouble* d_xz = NULL;
+		IssmDouble* d_yz = NULL;
+		if(dim==2){
+			_assert_(tnumnodes==3);
+			Matrix3x3Solve(&d_xx[0],Ke,pe_xx);
+			Matrix3x3Solve(&d_yy[0],Ke,pe_yy);
+			Matrix3x3Solve(&d_xy[0],Ke,pe_xy);
+			for(int i=0;i<3;i++) _assert_(!xIsNan<IssmDouble>(d_xx[i]));
+			for(int i=0;i<3;i++) _assert_(!xIsNan<IssmDouble>(d_yy[i]));
+			for(int i=0;i<3;i++) _assert_(!xIsNan<IssmDouble>(d_xx[i]));
+			element->AddInput(StrainRatexxEnum,d_xx,P1DGEnum);
+			element->AddInput(StrainRateyyEnum,d_yy,P1DGEnum);
+			element->AddInput(StrainRatexyEnum,d_xy,P1DGEnum);
+		}
+		else{
+			_assert_(tnumnodes==4);
+			d_zz = xNew<IssmDouble>(tnumnodes);
+			d_xz = xNew<IssmDouble>(tnumnodes);
+			d_yz = xNew<IssmDouble>(tnumnodes);
+			Matrix4x4Solve(&d_xx[0],Ke,pe_xx);
+			Matrix4x4Solve(&d_yy[0],Ke,pe_yy);
+			Matrix4x4Solve(&d_xy[0],Ke,pe_xy);
+			Matrix4x4Solve(&d_zz[0],Ke,pe_zz);
+			Matrix4x4Solve(&d_xz[0],Ke,pe_xz);
+			Matrix4x4Solve(&d_yz[0],Ke,pe_yz);
+			element->AddInput(StrainRatexxEnum,d_xx,P1DGEnum);
+			element->AddInput(StrainRateyyEnum,d_yy,P1DGEnum);
+			element->AddInput(StrainRatexyEnum,d_xy,P1DGEnum);
+			element->AddInput(StrainRatezzEnum,d_zz,P1DGEnum);
+			element->AddInput(StrainRatexzEnum,d_xz,P1DGEnum);
+			element->AddInput(StrainRateyzEnum,d_yz,P1DGEnum);
+		}
+
+		/*Clean up*/
+		delete gauss;
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(tbasis);
+		xDelete<IssmDouble>(Ke);
+		xDelete<IssmDouble>(pe_xx); xDelete<IssmDouble>(d_xx);
+		xDelete<IssmDouble>(pe_yy); xDelete<IssmDouble>(d_yy);
+		xDelete<IssmDouble>(pe_zz); xDelete<IssmDouble>(d_zz);
+		xDelete<IssmDouble>(pe_xy); xDelete<IssmDouble>(d_xy);
+		xDelete<IssmDouble>(pe_xz); xDelete<IssmDouble>(d_xz);
+		xDelete<IssmDouble>(pe_yz); xDelete<IssmDouble>(d_yz);
+	}
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters){/*{{{*/
+
+	/*Intermediaries*/
+	int         dim,tausize;
+	IssmDouble  epsxx,epsyy,epszz,epsxy,epsxz,epsyz,D_scalar;
+	IssmDouble  d_xx,d_yy,d_zz,d_xy,d_xz,d_yz;
+	IssmDouble  sigmapxx,sigmapyy,sigmapzz,sigmapxy,sigmapxz,sigmapyz;
+	IssmDouble  dvx[3],dvy[3],dvz[3];
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  Jdet,r;
+
+	parameters->FindParam(&r,AugmentedLagrangianREnum);
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) tausize = 3;
+	else       tausize = 6;
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*Get inputs and parameters*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input* vx_input=element->GetInput(VxEnum);                 _assert_(vx_input);
+		Input* vy_input=element->GetInput(VyEnum);                 _assert_(vy_input);
+		Input* vz_input=NULL;
+		if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+		/*Get previous tau*/
+		Input* sigmapxx_input=element->GetInput(DeviatoricStressxxEnum); _assert_(sigmapxx_input);
+		Input* sigmapyy_input=element->GetInput(DeviatoricStressyyEnum); _assert_(sigmapyy_input);
+		Input* sigmapxy_input=element->GetInput(DeviatoricStressxyEnum); _assert_(sigmapxy_input);
+		Input* sigmapzz_input=NULL; Input* sigmapxz_input=NULL; Input* sigmapyz_input=NULL;
+		if(dim==3){
+			sigmapzz_input=element->GetInput(DeviatoricStresszzEnum); _assert_(sigmapzz_input);
+			sigmapxz_input=element->GetInput(DeviatoricStressxzEnum); _assert_(sigmapxz_input);
+			sigmapyz_input=element->GetInput(DeviatoricStressyzEnum); _assert_(sigmapyz_input);
+		}
+
+		/*Get NEW d*/
+		Input* epsxx_input=element->GetInput(StrainRatexxEnum); _assert_(epsxx_input);
+		Input* epsyy_input=element->GetInput(StrainRateyyEnum); _assert_(epsyy_input);
+		Input* epsxy_input=element->GetInput(StrainRatexyEnum); _assert_(epsxy_input);
+		Input* epszz_input=NULL; Input* epsxz_input=NULL; Input* epsyz_input=NULL;
+		if(dim==3){
+			epszz_input=element->GetInput(StrainRatezzEnum); _assert_(epszz_input);
+			epsxz_input=element->GetInput(StrainRatexzEnum); _assert_(epsxz_input);
+			epsyz_input=element->GetInput(StrainRateyzEnum); _assert_(epsyz_input);
+		}
+
+		/*Fetch number of nodes and dof for this finite element*/
+		int tnumnodes = element->GetNumberOfVertices();      //Tensors, P1 DG
+
+		/*Update tau accordingly*/
+		IssmDouble* tau_xx = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* tau_yy = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* tau_xy = xNew<IssmDouble>(tnumnodes);
+		IssmDouble* tau_zz = NULL;
+		IssmDouble* tau_xz = NULL;
+		IssmDouble* tau_yz = NULL;
+		if(dim==3){
+			tau_zz = xNew<IssmDouble>(tnumnodes);
+			tau_xz = xNew<IssmDouble>(tnumnodes);
+			tau_yz = xNew<IssmDouble>(tnumnodes);
+		}
+		Gauss* gauss = element->NewGauss();
+		for(int ig=0;ig<tnumnodes;ig++){
+			gauss->GaussNode(P1DGEnum,ig);
+
+			/*Get D(u)*/
+			vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+			vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+			if(dim==3){
+				vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+			}
+			epsxx = dvx[0];
+			epsyy = dvy[1];
+			epsxy = 0.5*(dvx[1] + dvy[0]); 
+			if(dim==3){
+				epszz = dvz[2]; 
+				epsxz = 0.5*(dvx[2] + dvz[0]);
+				epsyz = 0.5*(dvy[2] + dvz[1]);
+			}
+
+			/*Get tau^(n-1) from inputs*/
+			sigmapxx_input->GetInputValue(&sigmapxx,gauss);
+			sigmapyy_input->GetInputValue(&sigmapyy,gauss);
+			sigmapxy_input->GetInputValue(&sigmapxy,gauss);
+			if(dim==3){
+				sigmapzz_input->GetInputValue(&sigmapzz,gauss);
+				sigmapxz_input->GetInputValue(&sigmapxz,gauss);
+				sigmapyz_input->GetInputValue(&sigmapyz,gauss);
+			}
+
+			/*Get new d*/
+			epsxx_input->GetInputValue(&d_xx,gauss);
+			epsyy_input->GetInputValue(&d_yy,gauss);
+			epsxy_input->GetInputValue(&d_xy,gauss);
+			if(dim==3){
+				epszz_input->GetInputValue(&d_zz,gauss);
+				epsxz_input->GetInputValue(&d_xz,gauss);
+				epsyz_input->GetInputValue(&d_yz,gauss);
+			}
+
+			/*Get d and update tau accordingly*/
+			tau_xx[ig] = sigmapxx + r*(epsxx - d_xx);
+			tau_yy[ig] = sigmapyy + r*(epsyy - d_yy);
+			tau_xy[ig] = sigmapxy + r*(epsxy - d_xy);
+			if(dim==3){
+				tau_zz[ig] = sigmapzz + r*(epszz - d_zz);
+				tau_xz[ig] = sigmapxz + r*(epsxz - d_xz);
+				tau_yz[ig] = sigmapyz + r*(epsyz - d_yz);
+			}
+		}
+
+		/*Add inputs*/
+		element->AddInput(DeviatoricStressxxEnum,tau_xx,P1DGEnum);
+		element->AddInput(DeviatoricStressyyEnum,tau_yy,P1DGEnum);
+		element->AddInput(DeviatoricStressxyEnum,tau_xy,P1DGEnum);
+		if(dim==3){
+			element->AddInput(DeviatoricStresszzEnum,tau_zz,P1DGEnum);
+			element->AddInput(DeviatoricStressxzEnum,tau_xz,P1DGEnum);
+			element->AddInput(DeviatoricStressyzEnum,tau_yz,P1DGEnum);
+		}
+
+		/*Clean up and */
+		delete gauss;
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(tau_xx);
+		xDelete<IssmDouble>(tau_yy);
+		xDelete<IssmDouble>(tau_zz);
+		xDelete<IssmDouble>(tau_xy);
+		xDelete<IssmDouble>(tau_xz);
+		xDelete<IssmDouble>(tau_yz);
+	}
+}/*}}}*/
+
+/*Coupling (Tiling)*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3d(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixSSA3dViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixSSA3dFriction(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dFriction(Element* element){/*{{{*/
+
+	/*Initialize Element matrix and return if necessary*/
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Element* basalelement = element->SpawnBasalElement();
+	ElementMatrix* Ke=CreateKMatrixSSAFriction(basalelement);
+	basalelement->DeleteMaterials(); delete basalelement;
+
+	/*clean-up and return*/
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dViscous(Element* element){/*{{{*/
+
+	/*Constants*/
+	const int    numdof2d=2*3;
+
+	/*Intermediaries */
+	int         i,j,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot;
+	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  epsilons[6];                    //6 for FS
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg[numdof2d][numdof2d]={0.0};
+	IssmDouble  *xyz_list  = NULL;
+
+	/*Find penta on bed as this is a SSA elements: */
+	Element* pentabase=element->GetBasalElement();
+	Element* basaltria=pentabase->SpawnBasalElement();
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=basaltria->NewElementMatrix(SSAApproximationEnum);
+	element->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
+	Input* vz_input   =element->GetInput(VzEnum);       _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	Gauss* gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_tria);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		this->GetBSSA(&B[0][0],basaltria,2,xyz_list, gauss_tria);
+		this->GetBSSAprime(&Bprime[0][0],basaltria,2,xyz_list, gauss_tria);
+
+		if(approximation==SSAHOApproximationEnum){
+			element->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
+			element->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
+			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		}
+		else if (approximation==SSAFSApproximationEnum){
+			element->ViscosityFS(&newviscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		}
+		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg[0][0],1);
+
+	}
+	for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg[i][j];
+
+	/*Transform Coordinate System*/
+	basaltria->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	delete basaltria->material;
+	delete basaltria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFS(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixFS(element);
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum); // P1 needed for HO
+	ElementMatrix* Ke2=CreateKMatrixHO(element);
+	element->SetTemporaryElementType(init); // P1 needed for HO
+	ElementMatrix* Ke3=CreateKMatrixCouplingHOFS(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAHO(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixSSA3d(element);
+	ElementMatrix* Ke2=CreateKMatrixHO(element);
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAHO(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAFS(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixFS(element);
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum); 
+	ElementMatrix* Ke2=CreateKMatrixSSA3d(element);
+	element->SetTemporaryElementType(init); 
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAFS(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingHOFS(Element* element){/*{{{*/
+
+	/*Constants*/
+	int numnodes       = 3*6+1;
+	int numdofp        = 2*6;
+	int numdofs        = 4*6 + 3;
+	int numdoftotal    = (2+4)*6+ 3;
+
+	/*Intermediaries*/
+	int   i,j,init;
+	int*   cs_list     = xNew<int>(6*3+1);
+	int*   cs_list2    = xNew<int>(6*2+1);
+	Node  **node_list  = xNew<Node*>(6*3+1);
+
+	/*Some parameters needed*/
+	init = element->FiniteElement();
+
+	/*prepare node list*/
+	for(i=0;i<6+1;i++){
+		node_list[i+6] = element->GetNode(i);
+		cs_list[i+6]   = XYZEnum;
+		cs_list2[i]    = XYZEnum;
+	}
+	for(i=0;i<6;i++){
+		node_list[i]       = element->GetNode(i);
+		node_list[i+2*6+1] = element->GetNode(i+6*1);
+		cs_list[i]         = XYEnum;
+		cs_list[i+2*6+1]   = PressureEnum;
+		cs_list2[i+6+1]    = PressureEnum;
+	}
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=element->NewElementMatrixCoupling(6,HOApproximationEnum);
+	ElementMatrix* Ke2=element->NewElementMatrix(FSvelocityEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Compute HO Matrix with P1 element type\n");*/
+	Ke1=CreateKMatrixFS(element); element->TransformInvStiffnessMatrixCoord(Ke1,node_list,2*6+1,cs_list2);
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	element->SetTemporaryElementType(P1Enum); // P1 needed for HO
+	Ke2=CreateKMatrixHO(element); element->TransformInvStiffnessMatrixCoord(Ke2,XYEnum);
+	element->SetTemporaryElementType(init); // P1 needed for HO
+	/*Compute FS Matrix and condense it \n");*/
+
+	for(i=0;i<numdofs;i++) for(j=0;j<6;j++){
+		Ke->values[(i+numdofp)*numdoftotal+2*j+0]+=Ke1->values[i*numdofs+3*j+0];
+		Ke->values[(i+numdofp)*numdoftotal+2*j+1]+=Ke1->values[i*numdofs+3*j+1];
+	}
+	for(i=0;i<numdofp;i++) for(j=0;j<6;j++){
+		Ke->values[i*numdoftotal+numdofp+3*j+0]+=Ke2->values[i*numdofp+2*j+0];
+		Ke->values[i*numdoftotal+numdofp+3*j+1]+=Ke2->values[i*numdofp+2*j+1];
+	}
+
+	/*Transform Coordinate System*/ //Do not transform, already done in the matrices
+	element->TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*clean-up and return*/
+	xDelete<int>(cs_list);
+	xDelete<int>(cs_list2);
+	xDelete<Node*>(node_list);
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHO(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingSSAHOViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixCouplingSSAHOFriction(element);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOFriction(Element* element){/*{{{*/
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Constants*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numdof      = 2*numnodes;
+	int numdoftotal = 4*numnodes;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet2d,alpha2;
+	IssmDouble *xyz_list_tria = NULL;
+	IssmDouble* L             = xNewZeroInit<IssmDouble>(2*numdof);
+	IssmDouble  DL[2][2]      = {{ 0,0 },{0,0}}; //for basal drag
+	IssmDouble  DL_scalar;
+	IssmDouble* Ke_gg         = xNewZeroInit<IssmDouble>(numdof*numdof);
+	Node      **node_list     = xNew<Node*>(2*numnodes);
+	int*        cs_list       = xNew<int>(2*numnodes);
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke1=element->NewElementMatrix(SSAApproximationEnum);
+	ElementMatrix* Ke2=element->NewElementMatrix(HOApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Prepare node list*/
+	for(i=0;i<numnodes;i++){
+		node_list[i+0*numnodes] = element->GetNode(i);
+		node_list[i+1*numnodes] = element->GetNode(i);
+		cs_list[i+0*numnodes] = XYEnum;
+		cs_list[i+1*numnodes] = XYEnum;
+	}
+
+	/*retrieve inputs :*/
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,2);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Friction: */
+		friction->GetAlpha2(&alpha2,gauss);
+		element->JacobianDeterminantBase(&Jdet2d, xyz_list_tria,gauss);
+		this->GetBHOFriction(L,element,3,xyz_list_tria,gauss);
+
+		DL_scalar=alpha2*gauss->weight*Jdet2d;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar; 
+
+		/*  Do the triple producte tL*D*L: */
+		TripleMultiply( L,2,numdof,1,
+					&DL[0][0],2,2,0,
+					L,2,numdof,0,
+					Ke_gg,1);
+	}
+
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdoftotal+(numdof+j)]+=Ke_gg[i*numdof+j];
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[(i+numdof)*numdoftotal+j]+=Ke_gg[i*numdof+j];
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	xDelete<IssmDouble>(Ke_gg);
+	xDelete<IssmDouble>(L);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOViscous(Element* element){/*{{{*/
+
+	/*Constants*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numdofm     = 1 *numnodes; //*2/2
+	int numdofp     = 2 *numnodes;
+	int numdoftotal = 2 *2 *numnodes;//2 dof per nodes and 2 sets of nodes for HO and SSA
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  *xyz_list      = NULL;
+	IssmDouble* B              = xNew<IssmDouble>(3*numdofp);
+	IssmDouble* Bprime         = xNew<IssmDouble>(3*numdofm);
+	IssmDouble  D[3][3]={0.0}; // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble* Ke_gg          = xNewZeroInit<IssmDouble>(numdofp*numdofm);
+	Node       **node_list     = xNew<Node*>(2*numnodes);
+	int*         cs_list= xNew<int>(2*numnodes);
+
+	/*Find penta on bed as HO must be coupled to the dofs on the bed: */
+	Element* pentabase=element->GetBasalElement();
+	Element* basaltria=pentabase->SpawnBasalElement();
+
+	/*prepare node list*/
+	for(i=0;i<numnodes;i++){
+		node_list[i+0*numnodes] = pentabase->GetNode(i);
+		node_list[i+1*numnodes] = element  ->GetNode(i);
+		cs_list[i+0*numnodes] = XYEnum;
+		cs_list[i+1*numnodes] = XYEnum;
+	}
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke1= pentabase->NewElementMatrix(SSAApproximationEnum);
+	ElementMatrix* Ke2= element  ->NewElementMatrix(HOApproximationEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	Gauss* gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_tria);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		this->GetBSSAHO(B, element,xyz_list, gauss);
+		this->GetBSSAprime(Bprime,basaltria,2,xyz_list, gauss_tria); 
+		element->ViscosityHO(&viscosity,3,xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHO(&oldviscosity,3,xyz_list,gauss,vxold_input,vyold_input);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( B,3,numdofp,1,
+					&D[0][0],3,3,0,
+					Bprime,3,numdofm,0,
+					Ke_gg,1);
+	} 
+	for(i=0;i<numdofp;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i*numdofm+j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j*numdofm+i];
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
+
+	/*Clean-up and return*/
+	basaltria->DeleteMaterials(); delete basaltria;
+	
+	delete gauss;
+	delete gauss_tria;
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(Ke_gg);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<Node*>(node_list);
+	xDelete<int>(cs_list);
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFS(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingSSAFSViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixCouplingSSAFSFriction(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFSFriction(Element* element){/*{{{*/
+
+	/*Constants*/
+	const int numdofs   = (6+1)*3 + 6*1;
+	const int numdofm   = 6 *2;
+	const int numdof2d  = 3 *3;
+	const int numdof2dm = 3 *2;
+	const int numdoftot = 6*2 + (6+1)*3 +6; // HO + FS vel + FS Pressure
+
+	/*Intermediaries */
+	int        i,j,approximation;
+	int        dim=3;
+	IssmDouble FSreconditioning,viscosity,alpha2_gauss,Jdet2d;
+	IssmDouble bed_normal[3];
+	IssmDouble LSSAFS[8][numdof2dm];
+	IssmDouble LprimeSSAFS[8][numdofs];
+	IssmDouble DLSSAFS[8][8]={0.0};
+	IssmDouble LFSSSA[4][numdof2d];
+	IssmDouble LprimeFSSSA[4][numdof2dm];
+	IssmDouble DLFSSSA[4][4]={0.0};
+	IssmDouble Ke_drag[numdof2dm][numdofs]={0.0};
+	IssmDouble Ke_drag2[numdof2d][numdof2dm]={0.0};
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_tria = NULL;
+
+	/*If on water or not FS, skip stiffness: */
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numnodes  = 2*vnumnodes-1+pnumnodes;
+
+	/*Prepare node list*/
+	int* cs_list = xNew<int>(2*vnumnodes-1+pnumnodes);
+	Node **node_list = xNew<Node*>(2*vnumnodes-1+pnumnodes);
+	for(i=0;i<vnumnodes-1;i++){
+		node_list[i] = element->GetNode(i);
+		cs_list[i]   = XYEnum;
+	}
+	for(i=0;i<vnumnodes;i++){
+		node_list[i+vnumnodes-1] = element->GetNode(i);
+		cs_list[i+vnumnodes-1]   = XYZEnum;
+	}
+	for(i=0;i<pnumnodes;i++){
+		node_list[2*vnumnodes-1+i] = element->GetNode(vnumnodes+i);
+		cs_list[2*vnumnodes-1+i]   = PressureEnum;
+	}
+
+	ElementMatrix* Ke1=element->NewElementMatrixCoupling(6,SSAApproximationEnum);
+	ElementMatrix* Ke2=element->NewElementMatrix(FSvelocityEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
+		this->GetLSSAFS(&LSSAFS[0][0], element,gauss);
+		this->GetLprimeSSAFS(&LprimeSSAFS[0][0], element,xyz_list, gauss);
+		this->GetLFSSSA(&LFSSSA[0][0],element, gauss);
+		this->GetLprimeFSSSA(&LprimeFSSSA[0][0], element,xyz_list, gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		element->NormalBase(&bed_normal[0],xyz_list_tria);
+		friction->GetAlpha2(&alpha2_gauss,gauss);
+
+		DLSSAFS[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLSSAFS[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLSSAFS[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLSSAFS[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		DLSSAFS[4][4]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[0];
+		DLSSAFS[5][5]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[1];
+		DLSSAFS[6][6]=FSreconditioning*gauss->weight*Jdet2d*bed_normal[0];
+		DLSSAFS[7][7]=FSreconditioning*gauss->weight*Jdet2d*bed_normal[1];
+
+		DLFSSSA[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLFSSSA[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLFSSSA[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLFSSSA[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+
+		TripleMultiply( &LSSAFS[0][0],8,numdof2dm,1,
+					&DLSSAFS[0][0],8,8,0,
+					&LprimeSSAFS[0][0],8,numdofs,0,
+					&Ke_drag[0][0],1);
+
+		TripleMultiply( &LFSSSA[0][0],4,numdof2d,1,
+					&DLFSSSA[0][0],4,4,0,
+					&LprimeFSSSA[0][0],4,numdof2dm,0,
+					&Ke_drag2[0][0],1);
+	}
+
+	for(i=0;i<numdof2dm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftot+j+numdofm]+=Ke_drag[i][j];
+	for(i=0;i<numdof2d;i++) for(j=0;j<numdof2dm;j++) Ke->values[(i+numdofm)*numdoftot+j]+=Ke_drag2[i][j];
+		
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	delete gauss;
+	delete friction;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFSViscous(Element* element){/*{{{*/
+
+	/*Constants*/
+	const int numdofm     = 2 *3;
+	const int numdofs     = 4 *6+ 3;
+	const int numdoftotal = 2 *numdofm+numdofs;
+
+	/*Intermediaries */
+	int        i,j;
+	int        dim=3;
+	IssmDouble Jdet,viscosity,FSreconditioning,D_scalar;
+	IssmDouble B[4][numdofs];
+	IssmDouble Bprime[4][numdofm];
+	IssmDouble B2[3][numdofm];
+	IssmDouble Bprime2[3][numdofs];
+	IssmDouble D[4][4]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble D2[3][3]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix 
+	IssmDouble Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix 
+	IssmDouble *xyz_list    = NULL;
+
+	/*Find penta on bed as FS must be coupled to the dofs on the bed: */
+	Element* pentabase=element->GetBasalElement();
+	Element* basaltria=pentabase->SpawnBasalElement();
+
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numnodes  = 2*vnumnodes-1+pnumnodes;
+
+	/*Prepare node list*/
+	int* cs_list     = xNew<int>(2*vnumnodes-1+pnumnodes);
+	Node **node_list = xNew<Node*>(2*vnumnodes-1+pnumnodes);
+	for(i=0;i<vnumnodes-1;i++){
+		node_list[i] = pentabase->GetNode(i);
+		cs_list[i]   = XYEnum;
+	}
+	for(i=0;i<vnumnodes;i++){
+		node_list[i+vnumnodes-1] = element->GetNode(i);
+		cs_list[i+vnumnodes-1]   = XYZEnum;
+	}
+	for(i=0;i<pnumnodes;i++){
+		node_list[2*vnumnodes-1+i] = element->GetNode(vnumnodes+i);
+		cs_list[2*vnumnodes-1+i]   = PressureEnum;
+	}
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke1=pentabase->NewElementMatrixCoupling(6,SSAApproximationEnum);
+	ElementMatrix* Ke2=element->NewElementMatrix(FSvelocityEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	Gauss* gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_tria);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		this->GetBSSAFS(&B[0][0],element,xyz_list, gauss);
+		this->GetBprimeSSAFSTria(&Bprime[0][0], basaltria,xyz_list, gauss_tria);
+		this->GetBSSAFSTria(&B2[0][0], basaltria,xyz_list, gauss_tria);
+		this->GetBprimeSSAFS(&Bprime2[0][0], element,xyz_list, gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		D_scalar=2*viscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+		D[3][3]=-gauss->weight*Jdet*FSreconditioning;
+		for (i=0;i<3;i++) D2[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],4,numdofs,1,
+					&D[0][0],4,4,0,
+					&Bprime[0][0],4,numdofm,0,
+					&Ke_gg[0][0],1);
+
+		TripleMultiply( &B2[0][0],3,numdofm,1,
+					&D2[0][0],3,3,0,
+					&Bprime2[0][0],3,numdofs,0,
+					&Ke_gg2[0][0],1);
+
+	} 
+	for(i=0;i<numdofs;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg2[i][j];
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	delete basaltria->material; delete basaltria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSAHO(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorSSA(element);
+	ElementVector* pe2=CreatePVectorHO(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSAFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum); // P1 needed for HO
+	ElementVector* pe1=CreatePVectorSSA(element);
+	element->SetTemporaryElementType(init); // P1 needed for HO
+	ElementVector* pe2=CreatePVectorFS(element);
+	int indices[3]={18,19,20};
+	element->SetTemporaryElementType(MINIcondensedEnum); // P1 needed for HO
+	ElementMatrix* Ke = CreateKMatrixFS(element);
+	element->SetTemporaryElementType(init); // P1 needed for HO
+	pe2->StaticCondensation(Ke,3,&indices[0]);
+	delete Ke;
+	ElementVector* pe3=CreatePVectorCouplingSSAFS(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorHOFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum);
+	ElementVector* pe1=CreatePVectorHO(element);
+	element->SetTemporaryElementType(init);
+	ElementVector* pe2=CreatePVectorFS(element);
+	int indices[3]={18,19,20};
+	element->SetTemporaryElementType(MINIcondensedEnum);
+	ElementMatrix* Ke = CreateKMatrixFS(element);
+	element->SetTemporaryElementType(init);
+	pe2->StaticCondensation(Ke,3,&indices[0]);
+	delete Ke;
+	ElementVector* pe3=CreatePVectorCouplingHOFS(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingHOFSViscous(element);
+	ElementVector* pe2=CreatePVectorCouplingHOFSFriction(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSFriction(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,Jdet2d,FSreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble	*xyz_list_tria = NULL;
+	IssmDouble  *xyz_list      = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numnodes  = vnumnodes+pnumnodes;
+
+	/*Prepare coordinate system list*/
+	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]           = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i] = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=  element->GetInput(VxEnum);   _assert_(vx_input);
+	Input* vy_input=  element->GetInput(VyEnum);   _assert_(vy_input);
+	Input* vz_input=  element->GetInput(VzEnum);   _assert_(vz_input);
+	Input* vzHO_input=element->GetInput(VzHOEnum); _assert_(vzHO_input);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
+		element->NodalFunctionsP1(basis, gauss);
+
+		vzHO_input->GetInputValue(&w, gauss);
+		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		element->NormalBase(&bed_normal[0],xyz_list_tria);
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		friction->GetAlpha2(&alpha2_gauss,gauss);
+
+		for(i=0;i<3;i++){
+			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	delete gauss;
+	delete friction;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         i,approximation;
+	int         dim=3;
+	IssmDouble  viscosity,Jdet,FSreconditioning;
+	IssmDouble  dw[3];
+	IssmDouble  *xyz_list = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+	int   vnumnodes = element->NumberofNodesVelocity();
+	int   pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input   =element->GetInput(VxEnum);   _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);   _assert_(vy_input);
+	Input* vz_input   =element->GetInput(VzEnum);   _assert_(vz_input);
+	Input* vzHO_input=element->GetInput(VzHOEnum);  _assert_(vzHO_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		element->NodalFunctionsP1(&basis[0],gauss);
+		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+		
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		for(i=0;i<6;i++){
+			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingSSAFSViscous(element);
+	ElementVector* pe2=CreatePVectorCouplingSSAFSFriction(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSFriction(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,j,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,Jdet2d,FSreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble	*xyz_list_tria = NULL;
+	IssmDouble  *xyz_list      = NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list     = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=   element->GetInput(VxEnum);    _assert_(vx_input);
+	Input* vy_input=   element->GetInput(VyEnum);    _assert_(vy_input);
+	Input* vz_input=   element->GetInput(VzEnum);    _assert_(vz_input);
+	Input* vzSSA_input=element->GetInput(VzSSAEnum); _assert_(vzSSA_input);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
+		element->NodalFunctionsP1(basis, gauss);
+
+		vzSSA_input->GetInputValue(&w, gauss);
+		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		element->NormalBase(&bed_normal[0],xyz_list_tria);
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		friction->GetAlpha2(&alpha2_gauss,gauss);
+
+		for(i=0;i<3;i++){
+			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	xDelete<Node*>(node_list);
+	delete gauss;
+	delete friction;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         i,approximation;
+	IssmDouble  viscosity,Jdet,FSreconditioning;
+	IssmDouble  dw[3];
+	IssmDouble  *xyz_list = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input   =element->GetInput(VxEnum);      _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);      _assert_(vy_input);
+	Input* vz_input   =element->GetInput(VzEnum);      _assert_(vz_input);
+	Input* vzSSA_input=element->GetInput(VzSSAEnum);   _assert_(vzSSA_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(&basis[0], gauss);
+		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+
+		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+		element->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		for(i=0;i<6;i++){
+			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+
+	/*Get dbasis in actual coordinate system: */
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+		B[2*numnodes*0+2*i+1] = 0.;
+		B[2*numnodes*1+2*i+0] = 0.;
+		B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+0] = .5*dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+1] = .5*dbasis[0*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx          0       0   0 ]
+	 *          [   0           dh/dy    0   0 ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx   0   0 ]
+	 *          [   0            0       0   h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int i;
+	IssmDouble dbasismini[3][7];
+	IssmDouble basis[6];
+
+	/*Get dbasis in actual coordinate system: */
+	element->NodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
+	element->NodalFunctionsP1(basis,gauss);
+
+	/*Build B: */
+	for(i=0;i<6;i++){
+		B[(3*7+6)*0+3*i+0] = dbasismini[0][i];
+		B[(3*7+6)*0+3*i+1] = 0.;
+		B[(3*7+6)*0+3*i+2] = 0.;
+		B[(3*7+6)*1+3*i+0] = 0.;
+		B[(3*7+6)*1+3*i+1] = dbasismini[1][i];
+		B[(3*7+6)*1+3*i+2] = 0.;
+		B[(3*7+6)*2+3*i+0] = 0.5*dbasismini[1][i];
+		B[(3*7+6)*2+3*i+1] = 0.5*dbasismini[0][i];
+		B[(3*7+6)*2+3*i+2] = 0.;
+		B[(3*7+6)*3+3*i+0] = 0.;
+		B[(3*7+6)*3+3*i+1] = 0.;
+		B[(3*7+6)*3+3*i+2] = 0.;
+	}
+	for(i=0;i<1;i++){
+		B[(3*7+6)*0+3*(6+i)+0] = 0.;
+		B[(3*7+6)*0+3*(6+i)+1] = 0.;
+		B[(3*7+6)*0+3*(6+i)+2] = 0.;
+		B[(3*7+6)*1+3*(6+i)+0] = 0.;
+		B[(3*7+6)*1+3*(6+i)+1] = 0.;
+		B[(3*7+6)*1+3*(6+i)+2] = 0.;
+		B[(3*7+6)*2+3*(6+i)+0] = 0.;
+		B[(3*7+6)*2+3*(6+i)+1] = 0.;
+		B[(3*7+6)*2+3*(6+i)+2] = 0.;
+		B[(3*7+6)*3+3*(6+i)+0] = 0.;
+		B[(3*7+6)*3+3*(6+i)+1] = 0.;
+		B[(3*7+6)*3+3*(6+i)+2] = 0.;
+	}
+
+	for(i=0;i<6;i++){ //last column not for the bubble function
+		B[(3*7+6)*0+7*3+i] = 0;
+		B[(3*7+6)*1+7*3+i] = 0;
+		B[(3*7+6)*2+7*3+i] = 0;
+		B[(3*7+6)*3+7*3+i] = basis[i];
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3 Bprime4 Bprime5 Bprime6] where Bprimei is of size 5*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[ 2*dh/dx    dh/dy   0   0 ]
+	 *               [  dh/dx    2*dh/dy  0   0 ]
+	 *               [  dh/dy     dh/dx   0   0 ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int    i;
+	IssmDouble dbasismini[3][7];
+
+	/*Get dbasis in actual coordinate system: */
+	element->NodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
+
+	/*Build Bprime: */
+	for(i=0;i<6;i++){
+		Bprime[(3*7+6)*0+3*i+0] = 2.*dbasismini[0][i];
+		Bprime[(3*7+6)*0+3*i+1] = dbasismini[1][i];
+		Bprime[(3*7+6)*0+3*i+2] = 0.;
+		Bprime[(3*7+6)*1+3*i+0] = dbasismini[0][i];
+		Bprime[(3*7+6)*1+3*i+1] = 2.*dbasismini[1][i];
+		Bprime[(3*7+6)*1+3*i+2] = 0.;
+		Bprime[(3*7+6)*2+3*i+0] = dbasismini[1][i];
+		Bprime[(3*7+6)*2+3*i+1] = dbasismini[0][i];
+		Bprime[(3*7+6)*2+3*i+2] = 0.;
+	}
+
+	for(i=0;i<1;i++){ //Add zeros for the bubble function
+		Bprime[(3*7+6)*0+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*0+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*0+3*(6+i)+2] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+2] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+2] = 0.;
+	}
+
+	for(i=0;i<6;i++){ //last column not for the bubble function
+		Bprime[(3*7+6)*0+7*3+i] = 0.;
+		Bprime[(3*7+6)*1+7*3+i] = 0.;
+		Bprime[(3*7+6)*2+7*3+i] = 0.;
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[   dN/dx         0     ]
+	 *          [       0       dN/dy   ]
+	 *          [  1/2*dN/dy  1/2*dN/dx ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+		B[2*numnodes*0+2*i+1] = 0.;
+		B[2*numnodes*1+2*i+0] = 0.;
+		B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+0] = 0.5*dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+1] = 0.5*dbasis[0*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3] where Bprimei is of size 3*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[  dN/dx    0   ]
+	 *               [    0    dN/dy ]
+	 *               [  dN/dy  dN/dx ]
+	 N               [  dN/dx  dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build Bprime: */
+	for(int i=0;i<numnodes;i++){
+		Bprime[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*0+2*i+1] = 0.;
+		Bprime[2*numnodes*1+2*i+0] = 0.;
+		Bprime[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+		Bprime[2*numnodes*2+2*i+0] = dbasis[1*numnodes+i];
+		Bprime[2*numnodes*2+2*i+1] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*3+2*i+0] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*3+2*i+1] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetLSSAFS(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
+	/*
+	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	int num_dof=2;
+	IssmDouble basis[3];
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LFS: */
+	for(int i=0;i<3;i++){
+		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*0+num_dof*i+1] = 0;
+		LFS[num_dof*3*1+num_dof*i+0] = 0;
+		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*2+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*2+num_dof*i+1] = 0;
+		LFS[num_dof*3*3+num_dof*i+0] = 0;
+		LFS[num_dof*3*3+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*4+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*4+num_dof*i+1] = 0;
+		LFS[num_dof*3*5+num_dof*i+0] = 0;
+		LFS[num_dof*3*5+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*6+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*6+num_dof*i+1] = 0;
+		LFS[num_dof*3*7+num_dof*i+0] = 0;
+		LFS[num_dof*3*7+num_dof*i+1] = basis[i];
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetLprimeSSAFS(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
+	/* Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0    0   0]
+	 *		       [ 0    h    0   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0  dh/dz 0]
+	 *		       [ 0    0  dh/dz 0]
+	 *           [ 0    0    0   h]
+	 *           [ 0    0    0   h]
+	 * where h is the interpolation function for node i.
+	 */
+	int num_dof=3;
+	int num_dof_vel=3*7;
+	int num_dof_total=3*7+1*6;
+	IssmDouble basis[3];
+	IssmDouble dbasis[3][6];
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build LprimeFS: */
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof_total*0+num_dof*i+0] = basis[i];
+		LprimeFS[num_dof_total*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+1] = basis[i];
+		LprimeFS[num_dof_total*1+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+2] = basis[i];
+		LprimeFS[num_dof_total*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+2] = basis[i];
+		LprimeFS[num_dof_total*4+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+2] = dbasis[2][i];
+		LprimeFS[num_dof_total*5+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+2] = dbasis[2][i];
+		LprimeFS[num_dof_total*6+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+2] = 0.;
+	}
+	for(int i=3;i<7;i++){
+		LprimeFS[num_dof_total*0+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+2] = 0.;
+	}
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof_total*0+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*1+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*2+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*3+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*4+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*5+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*6+num_dof_vel+i] = basis[i];
+		LprimeFS[num_dof_total*7+num_dof_vel+i] = basis[i];
+	}
+	for(int i=3;i<6;i++){
+		LprimeFS[num_dof_total*0+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*1+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*2+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*3+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*4+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*5+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*6+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*7+num_dof_vel+i] = 0.;
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetLFSSSA(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
+	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h    0    0 ]
+	 *	 	      [ 0    h    0 ]
+	 *		      [ 0    0    h ]
+	 *		      [ 0    0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	int num_dof=3;
+	IssmDouble basis[3];
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LFS: */
+	for(int i=0;i<3;i++){
+		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*0+num_dof*i+1] = 0.;
+		LFS[num_dof*3*0+num_dof*i+2] = 0.;
+		LFS[num_dof*3*1+num_dof*i+0] = 0.;
+		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*1+num_dof*i+2] = 0.;
+		LFS[num_dof*3*2+num_dof*i+0] = 0.;
+		LFS[num_dof*3*2+num_dof*i+1] = 0.;
+		LFS[num_dof*3*2+num_dof*i+2] = basis[i];
+		LFS[num_dof*3*3+num_dof*i+0] = 0.;
+		LFS[num_dof*3*3+num_dof*i+1] = 0.;
+		LFS[num_dof*3*3+num_dof*i+2] = basis[i];
+	}
+}/*}}}*/
+void StressbalanceAnalysis::GetLprimeFSSSA(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
+	/* Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0 ]
+	 *		       [ 0    h ]
+	 *		       [ h    0 ]
+	 *		       [ 0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+	int num_dof=2;
+	IssmDouble basis[3];
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LprimeFS: */
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof*3*0+num_dof*i+0] = basis[i];
+		LprimeFS[num_dof*3*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*3*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LprimeFS[num_dof*3*2+num_dof*i+0] = basis[i];
+		LprimeFS[num_dof*3*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*3*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*3*3+num_dof*i+1] = basis[i];
+	}
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i;
+	IssmDouble  rho_ice,g,FSreconditioning;
+	int*        doflistHO  = NULL;
+	int*        doflistFSv = NULL;
+	int*        doflistFSp = NULL;
+
+	/*Only works with Penta for now*/
+	if(element->ObjectEnum()!=PentaEnum) _error_("Coupling not supported for "<<EnumToStringx(element->ObjectEnum()));
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes  = 6;
+	int numdofHO  = 6*2;
+	int numdofFSv = 6*3;
+	int numdofFSp = 6;
+
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflistFSv,FSvelocityEnum,GsetEnum);
+	element->GetDofList(&doflistHO, HOApproximationEnum, GsetEnum);
+	element->GetDofListPressure(&doflistFSp,GsetEnum);
+	IssmDouble* HOvalues  = xNew<IssmDouble>(numdofHO);
+	IssmDouble* FSvalues  = xNew<IssmDouble>(numdofFSv+numdofFSp);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vzHO      = xNew<IssmDouble>(numnodes);
+	IssmDouble* vzFS      = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure  = xNew<IssmDouble>(numnodes);
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(2*numnodes);
+	for(i=0;i<numnodes;i++) cs_list[i]          = XYZEnum;
+	for(i=0;i<numnodes;i++) cs_list[numnodes+i] = PressureEnum;
+
+	/*Use the dof list to index into the solution vector: */
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<numdofHO ;i++) HOvalues[i]=solution[doflistHO[i]];
+	for(i=0;i<numdofFSv;i++) FSvalues[i]=solution[doflistFSv[i]];
+	for(i=0;i<numdofFSp;i++) FSvalues[numdofFSv+i]=solution[doflistFSp[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(FSvalues,2*numnodes,cs_list);
+	element->TransformSolutionCoord(HOvalues,numnodes,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]       = FSvalues[i*3+0]+HOvalues[i*2+0];
+		vy[i]       = FSvalues[i*3+1]+HOvalues[i*2+1];
+		vzFS[i]     = FSvalues[i*3+2];
+		pressure[i] = FSvalues[numnodes*3+i]*FSreconditioning;
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i]))     _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	element->GetInputListOnVertices(vzHO,VzHOEnum);
+	for(i=0;i<numnodes;i++){
+		vz[i] = vzHO[i]+vzFS[i];
+		vel[i]= sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+	element->InputChangeName(VzEnum,VzPicardEnum);
+	element->InputChangeName(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to element: */
+	element->AddInput(VxEnum,vx,P1Enum);
+	element->AddInput(VyEnum,vy,P1Enum);
+	element->AddInput(VzEnum,vz,P1Enum);
+	element->AddInput(VzFSEnum,vzFS,P1Enum);
+	element->AddInput(VelEnum,vel,P1Enum);
+	element->AddInput(PressureEnum,pressure,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vzHO);
+	xDelete<IssmDouble>(vzFS);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(FSvalues);
+	xDelete<IssmDouble>(HOvalues);
+	xDelete<int>(doflistFSp);
+	xDelete<int>(doflistFSv);
+	xDelete<int>(doflistHO);
+	xDelete<int>(cs_list);
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i;
+	IssmDouble  rho_ice,g,FSreconditioning;
+	int*        doflistSSA  = NULL;
+	int*        doflistFSv = NULL;
+	int*        doflistFSp = NULL;
+
+	/*we have to add results of this element for FS and results from the element
+	 * at base for SSA, so we need to have the pointer toward the basal element*/
+	Element* basalelement=element->GetBasalElement();
+	if(basalelement->ObjectEnum()!=PentaEnum){
+		_error_("Coupling not supported for "<<EnumToStringx(basalelement->ObjectEnum()));
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes  = 6;
+	int numdof2d  = numnodes;
+	int numdofSSA = 6*2;
+	int numdofFSv = 6*3;
+	int numdofFSp = 6;
+
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflistFSv,FSvelocityEnum,GsetEnum);
+	element->GetDofListPressure(&doflistFSp,GsetEnum);
+	basalelement->GetDofList(&doflistSSA, SSAApproximationEnum, GsetEnum);
+	IssmDouble* SSAvalues  = xNew<IssmDouble>(numdofSSA);
+	IssmDouble* FSvalues  = xNew<IssmDouble>(numdofFSv+numdofFSp);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vzSSA      = xNew<IssmDouble>(numnodes);
+	IssmDouble* vzFS      = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure  = xNew<IssmDouble>(numnodes);
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(2*numnodes);
+	for(i=0;i<numnodes;i++) cs_list[i]          = XYZEnum;
+	for(i=0;i<numnodes;i++) cs_list[numnodes+i] = PressureEnum;
+
+	/*Use the dof list to index into the solution vector: */
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<numdof2d;i++){
+		SSAvalues[i]          = solution[doflistSSA[i]];
+		SSAvalues[i+numdof2d] = solution[doflistSSA[i]];
+	}
+	for(i=0;i<numdofFSv;i++) FSvalues[i]=solution[doflistFSv[i]];
+	for(i=0;i<numdofFSp;i++) FSvalues[numdofFSv+i]=solution[doflistFSp[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(FSvalues,2*numnodes,cs_list);
+	element->TransformSolutionCoord(SSAvalues,numnodes,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+
+	for(i=0;i<numnodes;i++){
+		vx[i]       = FSvalues[i*3+0]+SSAvalues[i*2+0];
+		vy[i]       = FSvalues[i*3+1]+SSAvalues[i*2+1];
+		vzFS[i]     = FSvalues[i*3+2];
+		pressure[i] = FSvalues[numnodes*3+i]*FSreconditioning;
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i]))     _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	element->GetInputListOnVertices(vzSSA,VzSSAEnum);
+	for(i=0;i<numnodes;i++){
+		vz[i] = vzSSA[i]+vzFS[i];
+		vel[i]= sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+	element->InputChangeName(VzEnum,VzPicardEnum);
+	element->InputChangeName(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to element: */
+	element->AddInput(VxEnum,vx,P1Enum);
+	element->AddInput(VyEnum,vy,P1Enum);
+	element->AddInput(VzEnum,vz,P1Enum);
+	element->AddInput(VzFSEnum,vzFS,P1Enum);
+	element->AddInput(VelEnum,vel,P1Enum);
+	element->AddInput(PressureEnum,pressure,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vzSSA);
+	xDelete<IssmDouble>(vzFS);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(FSvalues);
+	xDelete<IssmDouble>(SSAvalues);
+	xDelete<int>(doflistFSp);
+	xDelete<int>(doflistFSv);
+	xDelete<int>(doflistSSA);
+	xDelete<int>(cs_list);
+}/*}}}*/
+void StressbalanceAnalysis::InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i,domaintype;
+	IssmDouble  rho_ice,g;
+	int*        SSAdoflist = NULL;
+	int*        HOdoflist  = NULL;
+	IssmDouble* xyz_list   = NULL;
+
+	/*we have to add results of this element for HO and results from the element
+	 * at base for SSA, so we need to have the pointer toward the basal element*/
+	Element* basalelement=element->GetBasalElement();
+	if(basalelement->ObjectEnum()!=PentaEnum){
+		_error_("Coupling not supported for "<<EnumToStringx(basalelement->ObjectEnum()));
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*2;
+	int numdof2d = numnodes;
+
+	/*Fetch dof list and allocate solution vectors*/
+	basalelement->GetDofList(&SSAdoflist,SSAApproximationEnum,GsetEnum);
+	element     ->GetDofList(&HOdoflist, HOApproximationEnum, GsetEnum);
+	IssmDouble* HOvalues  = xNew<IssmDouble>(numdof);
+	IssmDouble* SSAvalues = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure  = xNew<IssmDouble>(numnodes);
+	IssmDouble* surface   = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof2d;i++){
+		HOvalues[i]  = solution[HOdoflist[i]];
+		SSAvalues[i] = solution[SSAdoflist[i]];
+	}
+	for(i=numdof2d;i<numdof;i++){
+		HOvalues[i]  = solution[HOdoflist[i]];
+		SSAvalues[i] = SSAvalues[i-numdof2d];
+	}
+
+	/*Transform solution in Cartesian Space*/
+	basalelement->TransformSolutionCoord(SSAvalues,XYEnum);
+	element->TransformSolutionCoord(HOvalues,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=SSAvalues[i*2+0]+HOvalues[i*2+0];
+		vy[i]=SSAvalues[i*2+1]+HOvalues[i*2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	element->GetInputListOnNodes(&vz[0],VzEnum,0.);
+	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	g       = element->GetMaterialParameter(ConstantsGEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnNodes(&surface[0],SurfaceEnum);
+	for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+	element->InputChangeName(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to element: */
+	element->AddInput(VxEnum,vx,P1Enum);
+	element->AddInput(VyEnum,vy,P1Enum);
+	element->AddInput(VelEnum,vel,P1Enum);
+	element->AddInput(PressureEnum,pressure,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(SSAvalues);
+	xDelete<IssmDouble>(HOvalues);
+	xDelete<int>(SSAdoflist);
+	xDelete<int>(HOdoflist);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceAnalysis.h	(revision 18231)
@@ -0,0 +1,129 @@
+/*! \file StressbalanceAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceAnalysis_
+#define _StressbalanceAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceAnalysis: public Analysis{
+
+  public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+
+		/*SSA*/
+		ElementMatrix* CreateJacobianMatrixSSA(Element* element);
+		ElementMatrix* CreateKMatrixSSA(Element* element);
+		ElementMatrix* CreateKMatrixSSAViscous(Element* element);
+		ElementMatrix* CreateKMatrixSSAFriction(Element* element);
+		ElementVector* CreatePVectorSSA(Element* element);
+		ElementVector* CreatePVectorSSADrivingStress(Element* element);
+		ElementVector* CreatePVectorSSAFront(Element* element);
+		void GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBSSAprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element);
+		/*L1L2*/
+		ElementMatrix* CreateKMatrixL1L2(Element* element);
+		ElementMatrix* CreateKMatrixL1L2Viscous(Element* element);
+		ElementMatrix* CreateKMatrixL1L2Friction(Element* element);
+		ElementVector* CreatePVectorL1L2(Element* element);
+		ElementVector* CreatePVectorL1L2DrivingStress(Element* element);
+		ElementVector* CreatePVectorL1L2Front(Element* element);
+		void InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element);
+		/*HO*/
+		ElementMatrix* CreateJacobianMatrixHO(Element* element);
+		ElementMatrix* CreateKMatrixHO(Element* element);
+		ElementMatrix* CreateKMatrixHOViscous(Element* element);
+		ElementMatrix* CreateKMatrixHOFriction(Element* element);
+		ElementVector* CreatePVectorHO(Element* element);
+		ElementVector* CreatePVectorHODrivingStress(Element* element);
+		ElementVector* CreatePVectorHOFront(Element* element);
+		void GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBHOprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void InputUpdateFromSolutionHO(IssmDouble* solution,Element* element);
+		/*FS*/
+		ElementVector* CreateDVectorFS(Element* element);
+		ElementMatrix* CreateJacobianMatrixFS(Element* element);
+		ElementMatrix* CreateKMatrixFS(Element* element);
+		ElementMatrix* CreateKMatrixFSViscousLATH(Element* element);
+		ElementMatrix* CreateKMatrixFSViscousXTH(Element* element);
+		ElementMatrix* CreateKMatrixFSViscous(Element* element);
+		ElementMatrix* CreateKMatrixFSFriction(Element* element);
+		ElementMatrix* CreateKMatrixFSShelf(Element* element);
+		ElementVector* CreatePVectorFS(Element* element);
+		ElementVector* CreatePVectorFSViscous(Element* element);
+		ElementVector* CreatePVectorFSViscousLATH(Element* element);
+		ElementVector* CreatePVectorFSViscousXTH(Element* element);
+		ElementVector* CreatePVectorFSShelf(Element* element);
+		ElementVector* CreatePVectorFSFront(Element* element);
+		void GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSprimevel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSprimeUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element);
+		void InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
+		void InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters);
+		void InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters);
+		void InitializeXTH(Elements* elements,Parameters* parameters);
+		/*Coupling*/
+		ElementMatrix* CreateKMatrixSSA3d(Element* element);
+		ElementMatrix* CreateKMatrixSSA3dFriction(Element* element);
+		ElementMatrix* CreateKMatrixSSA3dViscous(Element* element);
+		ElementMatrix* CreateKMatrixHOFS(Element* element);
+		ElementMatrix* CreateKMatrixSSAHO(Element* element);
+		ElementMatrix* CreateKMatrixSSAFS(Element* element);
+		ElementMatrix* CreateKMatrixCouplingHOFS(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHO(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHOFriction(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHOViscous(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFS(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFSFriction(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFSViscous(Element* element);
+		ElementVector* CreatePVectorSSAHO(Element* element);
+		ElementVector* CreatePVectorSSAFS(Element* element);
+		ElementVector* CreatePVectorCouplingSSAFS(Element* element);
+		ElementVector* CreatePVectorCouplingSSAFSFriction(Element* element);
+		ElementVector* CreatePVectorCouplingSSAFSViscous(Element* element);
+		ElementVector* CreatePVectorHOFS(Element* element);
+		ElementVector* CreatePVectorCouplingHOFS(Element* element);
+		ElementVector* CreatePVectorCouplingHOFSFriction(Element* element);
+		ElementVector* CreatePVectorCouplingHOFSViscous(Element* element);
+		void GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetLFSSSA(IssmDouble* L,Element* element,Gauss* gauss);
+		void GetLSSAFS(IssmDouble* L,Element* element,Gauss* gauss);
+		void GetLprimeFSSSA(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetLprimeSSAFS(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element);
+		void InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element);
+		void InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 18231)
@@ -0,0 +1,591 @@
+#include "./StressbalanceSIAAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Model processing*/
+int  StressbalanceSIAAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 2;
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Fetch data needed: */
+	bool   isSIA;
+	bool   islevelset;
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+
+	/*Now, is the flag SIA on? otherwise, do nothing: */
+	if (!isSIA)return;
+
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+		if(iomodel->domaintype!=Domain2DhorizontalEnum)
+			iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum); // required for updating active nodes
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool  isSIA;
+	Node* node = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if(!isSIA) return;
+
+	/*First create nodes*/
+	int    lid=0;
+	iomodel->FetchData(4,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	}
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Create new node if is in this processor's partition*/
+			node = new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceSIAAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]));
+
+			/*Deactivate node if not SIA*/
+			if(reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
+				node->Deactivate();
+			}
+
+			/*Add to Nodes dataset*/
+			nodes->AddObject(node);
+		}
+	}
+
+	iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        count;
+	IssmDouble yts;
+	bool       isSIA;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if (!isSIA) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+	/*Initialize conunter*/
+	count=0;
+
+	/*vx and vy are spc'd if we are not on nodeonSIA: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i])){
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceSIAAnalysisEnum));
+				count++;
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceSIAAnalysisEnum));
+				count++;
+			}
+			else{
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvxEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,iomodel->Data(StressbalanceSpcvxEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+				}
+
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvyEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,iomodel->Data(StressbalanceSpcvyEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           StressbalanceSIAAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+		if(VerboseSolution()) _printf0_("   computing SIA velocities\n");
+		femmodel->SetCurrentConfiguration(StressbalanceSIAAnalysisEnum);
+		solutionsequence_linear(femmodel);
+}/*}}}*/
+ElementVector* StressbalanceSIAAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* StressbalanceSIAAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* StressbalanceSIAAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			return CreateKMatrix2D(element);
+		case Domain3DEnum:
+			return CreateKMatrix3D(element);
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+ElementMatrix* StressbalanceSIAAnalysis::CreateKMatrix2D(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	IssmDouble connectivity;
+
+	/*Fetch number vertices for this element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke=element->NewElementMatrix();
+	for(int iv=0;iv<numvertices;iv++){
+		connectivity=(IssmDouble)element->VertexConnectivity(iv);
+		Ke->values[(2*iv+0)*2*numvertices+(2*iv+0)]=1./connectivity;
+		Ke->values[(2*iv+1)*2*numvertices+(2*iv+1)]=1./connectivity;
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceSIAAnalysis::CreateKMatrix3D(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         i0,i1,j0,j1,nodeup,nodedown,numsegments;
+	IssmDouble  slope[2],connectivity[2],one0,one1;
+	int        *pairindices = NULL;
+
+	/*Fetch number vertices for this element*/
+	int numvertices = element->GetNumberOfVertices();
+	int numdof      = 2*numvertices;
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke=element->NewElementMatrix();
+
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+	for(int is=0;is<numsegments;is++){
+		nodedown = pairindices[is*2+0];
+		nodeup   = pairindices[is*2+1];
+		connectivity[0]=(IssmDouble)element->VertexConnectivity(nodedown);
+		connectivity[1]=(IssmDouble)element->VertexConnectivity(nodeup);
+		one0=1./connectivity[0];
+		one1=1./connectivity[1];
+
+		/*2 dofs of first node*/
+		i0=2*nodedown;  i1=2*nodedown+1;
+		/*2 dofs of second node*/
+		j0=2*nodeup;    j1=2*nodeup+1;
+
+		/*Create matrix for these two nodes*/
+		if(element->IsOnBase() && element->IsOnSurface()){
+			Ke->values[i0*numdof+i0] = +one0;
+			Ke->values[i1*numdof+i1] = +one0;
+			Ke->values[j0*numdof+i0] = -one1;
+			Ke->values[j0*numdof+j0] = +one1;
+			Ke->values[j1*numdof+i1] = -one1;
+			Ke->values[j1*numdof+j1] = +one1;
+		}
+		else if(element->IsOnBase()){
+			Ke->values[i0*numdof+i0] = one0;
+			Ke->values[i1*numdof+i1] = one0;
+			Ke->values[j0*numdof+i0] = -2.*one1;
+			Ke->values[j0*numdof+j0] = +2.*one1;
+			Ke->values[j1*numdof+i1] = -2.*one1;
+			Ke->values[j1*numdof+j1] = +2.*one1;
+		}
+		else if(element->IsOnSurface()){
+			Ke->values[j0*numdof+i0] = -one1;
+			Ke->values[j0*numdof+j0] = +one1;
+			Ke->values[j1*numdof+i1] = -one1;
+			Ke->values[j1*numdof+j1] = +one1;
+		}
+		else{ //node is on two horizontal layers and beams include the values only once, so the have to use half of the connectivity
+			Ke->values[j0*numdof+i0] = -2.*one1;
+			Ke->values[j0*numdof+j0] = +2.*one1;
+			Ke->values[j1*numdof+i1] = -2.*one1;
+			Ke->values[j1*numdof+j1] = +2.*one1;
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(pairindices);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceSIAAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			return CreatePVector2D(element);
+		case Domain3DEnum:
+			return CreatePVector3D(element);
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+ElementVector* StressbalanceSIAAnalysis::CreatePVector2D(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int        frictionlaw = 1;
+	IssmDouble ub,vb,slope2,drag,thickness,surface,connectivity;
+	IssmDouble slope[2];
+
+	/*Fetch number vertices for this element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize Element vector*/
+	ElementVector* pe=element->NewElementVector();
+
+	/*Retrieve all inputs and parameters*/
+	IssmDouble  rho_ice    = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  gravity    = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  n          = element->GetMaterialParameter(MaterialsRheologyNEnum);
+	IssmDouble  B          = element->GetMaterialParameter(MaterialsRheologyBbarEnum);
+	Input* slopex_input    = element->GetInput(SurfaceSlopeXEnum);        _assert_(slopex_input);
+	Input* slopey_input    = element->GetInput(SurfaceSlopeYEnum);        _assert_(slopey_input);
+	Input* thickness_input = element->GetInput(ThicknessEnum);            _assert_(thickness_input);
+	Input* surface_input   = element->GetInput(SurfaceEnum);              _assert_(surface_input);
+	Input* drag_input      = element->GetInput(FrictionCoefficientEnum);  _assert_(drag_input);
+
+	Gauss* gauss=element->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		connectivity=(IssmDouble)element->VertexConnectivity(iv);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+		drag_input->GetInputValue(&drag,gauss);
+		slopex_input->GetInputValue(&slope[0],gauss);
+		slopey_input->GetInputValue(&slope[1],gauss);
+		slope2=slope[0]*slope[0]+slope[1]*slope[1];
+
+		switch(frictionlaw){
+			case 1:
+				/*Payne 1995 (m = 1, B = 5e-3/yts = 1.58e-10  m/s/Pa*/
+				ub=-1.58*1.e-10*rho_ice*gravity*thickness*slope[0];
+				vb=-1.58*1.e-10*rho_ice*gravity*thickness*slope[1];
+				break;
+			case 2:
+				/*Ritz et al. 1996*/
+				ub=drag*(rho_ice*gravity*thickness)*(rho_ice*gravity*thickness)*slope[0]/sqrt(slope2);
+				vb=drag*(rho_ice*gravity*thickness)*(rho_ice*gravity*thickness)*slope[1]/sqrt(slope2);
+				break;
+			case 3:
+				/*Rutt et al. 2009*/
+				ub=-drag*rho_ice*gravity*thickness*slope[0];
+				vb=-drag*rho_ice*gravity*thickness*slope[1];
+				break;
+			case 4:
+				/*Henning Akesson*/
+				drag = -4e-15 * surface + 8.6e-12;
+				ub=-drag*rho_ice*gravity*thickness*slope[0];
+				vb=-drag*rho_ice*gravity*thickness*slope[1];
+				break;
+			default:
+				_error_("Not supported yet");
+		}
+
+		pe->values[2*iv+0]=(ub-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[0])/connectivity;
+		pe->values[2*iv+1]=(vb-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[1])/connectivity;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceSIAAnalysis::CreatePVector3D(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         frictionlaw = 1;
+	int         nodeup,nodedown,numsegments;
+	IssmDouble  ub,vb,slope2,drag,surface,thickness,constant_part,z,Jdet;
+	IssmDouble  slope[2],connectivity[2],xyz_list_line[2][3];
+	IssmDouble *xyz_list = NULL;
+	int        *pairindices = NULL;
+
+	/*Fetch number vertices for this element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize Element vector*/
+	ElementVector* pe=element->NewElementVector();
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	IssmDouble  rho_ice    = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  gravity    = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  n          = element->GetMaterialParameter(MaterialsRheologyNEnum);
+	IssmDouble  B          = element->GetMaterialParameter(MaterialsRheologyBEnum);
+	Input* surface_input   = element->GetInput(SurfaceEnum);              _assert_(surface_input);
+	Input* slopex_input    = element->GetInput(SurfaceSlopeXEnum);        _assert_(slopex_input);
+	Input* slopey_input    = element->GetInput(SurfaceSlopeYEnum);        _assert_(slopey_input);
+	Input* thickness_input = element->GetInput(ThicknessEnum);            _assert_(thickness_input);
+	Input* drag_input      = element->GetInput(FrictionCoefficientEnum);  _assert_(drag_input);
+
+	/*Get Vertical segment indices*/
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+	for(int is=0;is<numsegments;is++){
+		nodedown = pairindices[is*2+0];
+		nodeup   = pairindices[is*2+1];
+		connectivity[0]=(IssmDouble)element->VertexConnectivity(nodedown);
+		connectivity[1]=(IssmDouble)element->VertexConnectivity(nodeup);
+		for(int i=0;i<3;i++){
+			xyz_list_line[0][i]=xyz_list[nodedown*3+i];
+			xyz_list_line[1][i]=xyz_list[nodeup*3+i];
+		}
+
+		Gauss* gauss=element->NewGaussLine(nodedown,nodeup,3);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			slopex_input->GetInputValue(&slope[0],gauss);
+			slopey_input->GetInputValue(&slope[1],gauss);
+			surface_input->GetInputValue(&surface,gauss);
+			thickness_input->GetInputValue(&thickness,gauss);
+
+			slope2=slope[0]*slope[0]+slope[1]*slope[1];
+			constant_part=-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.));
+
+			z = element->GetZcoord(xyz_list,gauss);
+			element->JacobianDeterminantLine(&Jdet,&xyz_list_line[0][0],gauss);
+
+			if(element->IsOnSurface()){
+				pe->values[2*nodeup+0]+=constant_part*pow((surface-z)/B,n)*slope[0]*Jdet*gauss->weight/connectivity[1];
+				pe->values[2*nodeup+1]+=constant_part*pow((surface-z)/B,n)*slope[1]*Jdet*gauss->weight/connectivity[1];
+			}
+			else{/*connectivity is too large, should take only half on it*/
+				pe->values[2*nodeup+0]+=constant_part*pow((surface-z)/B,n)*slope[0]*Jdet*gauss->weight*2./connectivity[1];
+				pe->values[2*nodeup+1]+=constant_part*pow((surface-z)/B,n)*slope[1]*Jdet*gauss->weight*2./connectivity[1];
+			}
+		}
+
+		/*Deal with basal velocities*/
+		if(element->IsOnBase()){
+			drag_input->GetInputValue(&drag,gauss);
+
+			switch(frictionlaw){
+				case 1:
+					/*Payne 1995 (m = 1, B = 5e-3/yts = 1.58e-10  m/s/Pa*/
+					ub=-1.58*1.e-10*rho_ice*gravity*thickness*slope[0];
+					vb=-1.58*1.e-10*rho_ice*gravity*thickness*slope[1];
+					break;
+				case 2:
+					/*Ritz et al. 1996*/
+					ub=drag*(rho_ice*gravity*thickness)*(rho_ice*gravity*thickness)*slope[0]/sqrt(slope2);
+					vb=drag*(rho_ice*gravity*thickness)*(rho_ice*gravity*thickness)*slope[1]/sqrt(slope2);
+					break;
+				case 3:
+					/*Rutt et al. 2009*/
+					ub=-drag*rho_ice*gravity*thickness*slope[0];
+					vb=-drag*rho_ice*gravity*thickness*slope[1];
+					break;
+				case 4:
+					/*Henning Akesson*/
+					drag = -4e-15 * surface + 8.6e-12;
+					ub=-drag*rho_ice*gravity*thickness*slope[0];
+					vb=-drag*rho_ice*gravity*thickness*slope[1];
+					break;
+				default:
+					_error_("Not supported yet");
+			}
+
+			pe->values[2*nodedown+0]+=ub/connectivity[0];
+			pe->values[2*nodedown+1]+=vb/connectivity[0];
+		}
+		delete gauss;
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(xyz_list);
+	return pe;
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+
+	IssmDouble vx,vy;
+	int       *doflist = NULL;
+
+	/*Fetch number of nodes and initialize values*/
+	int         numnodes = element->GetNumberOfNodes();
+	int         numdof   = numnodes*2;
+	IssmDouble* values   = xNew<IssmDouble>(numdof);
+
+	/*Get dof list and inputs */
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have the velocities in inputs, fill in solution */
+	Gauss* gauss=element->NewGauss();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*2+0]=vx;
+		values[i*2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void StressbalanceSIAAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void StressbalanceSIAAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int         i,domaintype;
+	IssmDouble  rho_ice,g;
+	int*        doflist=NULL;
+	IssmDouble* xyz_list=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*2;
+
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numdof);
+	IssmDouble* vy        = xNew<IssmDouble>(numdof);
+	IssmDouble* vz        = xNew<IssmDouble>(numdof);
+	IssmDouble* vel       = xNew<IssmDouble>(numdof);
+	IssmDouble* pressure  = xNew<IssmDouble>(numdof);
+	IssmDouble* thickness = xNew<IssmDouble>(numdof);
+	IssmDouble* surface   = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	element->TransformSolutionCoord(&values[0],XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	element->GetInputListOnNodes(&vz[0],VzEnum,0.);
+	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice  = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	g        = element->GetMaterialParameter(ConstantsGEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->GetInputListOnNodes(&thickness[0],ThicknessEnum);
+			for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*thickness[i];
+			break;
+		case Domain3DEnum:   
+			element->GetVerticesCoordinates(&xyz_list);
+			element->GetInputListOnNodes(&surface[0],SurfaceEnum);
+			for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	element->InputChangeName(VxEnum,VxPicardEnum);
+	element->InputChangeName(VyEnum,VyPicardEnum);
+	element->InputChangeName(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(VxEnum,vx,P1Enum);
+	element->AddInput(VyEnum,vy,P1Enum);
+	element->AddInput(VelEnum,vel,P1Enum);
+	element->AddInput(PressureEnum,pressure,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file StressbalanceSIAAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceSIAAnalysis_
+#define _StressbalanceSIAAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceSIAAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrix2D(Element* element);
+		ElementMatrix* CreateKMatrix3D(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVector2D(Element* element);
+		ElementVector* CreatePVector3D(Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 18231)
@@ -0,0 +1,486 @@
+#include "./StressbalanceVerticalAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Model processing*/
+int  StressbalanceVerticalAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
+
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->domaintype!=Domain3DEnum) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->domaintype!=Domain3DEnum) return;
+
+	iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	::CreateNodes(nodes,iomodel,StressbalanceVerticalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int count;
+	IssmDouble yts;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*return if not 3d mesh*/
+	if(iomodel->domaintype!=Domain3DEnum) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+	/*Initialize counter*/
+	count=0;
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationBorderFSEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceVerticalAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for FS
+				count++;
+			}
+			else if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvzEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,
+								iomodel->Data(StressbalanceSpcvzEnum)[i],StressbalanceVerticalAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+				count++;
+
+			}
+		} 
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+}/*}}}*/
+void StressbalanceVerticalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           StressbalanceVerticalAnalysis::Core(FemModel* femmodel){/*{{{*/
+
+		if(VerboseSolution()) _printf0_("   computing vertical velocities\n");
+		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
+		solutionsequence_linear(femmodel);
+}/*}}}*/
+ElementVector* StressbalanceVerticalAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* StressbalanceVerticalAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixSurface(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble  D,Jdet;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetB(B,element,xyz_list,gauss);
+		this->GetBprime(Bprime,element,xyz_list,gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(B,1,numnodes,1,
+					&D,1,1,0,
+					Bprime,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
+
+
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  D,Jdet,normal[3];
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGaussTop(2);
+	element->NormalTop(&normal[0],xyz_list);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = -gauss->weight*Jdet*normal[2];
+
+		TripleMultiply( basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	return Ke;
+}/*}}}*/
+ElementVector* StressbalanceVerticalAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorVolume(element);
+	ElementVector* pe2=CreatePVectorBase(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceVerticalAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         approximation;
+	IssmDouble  Jdet,dudx,dvdy,dwdz;
+	IssmDouble  du[3],dv[3],dw[3];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and basis functions*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vzFS_input=NULL;
+	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+		vzFS_input=element->GetInput(VzFSEnum); _assert_(vzFS_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		vx_input->GetInputDerivativeValue(&du[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dv[0],xyz_list,gauss);
+		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+			vzFS_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+			dwdz=dw[2];
+		}
+		else dwdz=0;
+		dudx=du[0];
+		dvdy=dv[1];
+
+		for(int i=0;i<numnodes;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceVerticalAnalysis::CreatePVectorBase(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         approximation;
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_base = NULL;
+	IssmDouble  Jdet,slope[3];
+	IssmDouble  vx,vy,vz=0.,dbdx,dbdy;
+	IssmDouble  gmb,fmb,phi,basalmeltingvalue;
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GetInputValue(&approximation,ApproximationEnum);
+	Input* base_input=element->GetInput(BaseEnum);                                               _assert_(base_input);
+	Input* groundedice_input=element->GetInput(MaskGroundediceLevelsetEnum);                     _assert_(groundedice_input);
+	Input* groundedice_melting_input=element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedice_melting_input);
+	Input* floatingice_melting_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(floatingice_melting_input);
+	Input* vx_input=element->GetInput(VxEnum);                                                   _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);                                                   _assert_(vy_input);
+	Input* vzFS_input=NULL;
+	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+		vzFS_input=element->GetInput(VzFSEnum);       _assert_(vzFS_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		groundedice_melting_input->GetInputValue(&gmb,gauss);
+		floatingice_melting_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
+		base_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+			vzFS_input->GetInputValue(&vz,gauss);
+		}
+		dbdx=slope[0];
+		dbdy=slope[1];
+		if(phi>0.) basalmeltingvalue=gmb;
+		else basalmeltingvalue=fmb;
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=-Jdet*gauss->weight*(vx*dbdx+vy*dbdy-vz-basalmeltingvalue)*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+void StressbalanceVerticalAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[2*numnodes+i];  
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	element->NodalFunctions(Bprime,gauss);
+
+}/*}}}*/
+void StressbalanceVerticalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,VzEnum);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void StressbalanceVerticalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int          numnodes = element->GetNumberOfNodes();
+	int          numdof=numnodes*1;
+
+	int          i;
+	int          approximation;
+	int*         doflist  = NULL;
+	IssmDouble*  xyz_list = NULL;
+	IssmDouble   rho_ice,g;
+
+	/*Get the approximation and do nothing if the element in FS or None*/
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+		return;
+	}
+
+	/*Get dof list and vertices coordinates: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble*  values    = xNew<IssmDouble>(numdof);
+	IssmDouble*  vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vzSSA     = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vzHO      = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vzFS      = xNew<IssmDouble>(numnodes);
+	IssmDouble*  vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble*  pressure  = xNew<IssmDouble>(numnodes);
+	IssmDouble*  surface   = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector vz: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+	for(i=0;i<numdof;i++){
+		vz[i]=values[i*1+0];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vz[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vx and Vy*/
+	element->GetInputListOnNodes(&vx[0],VxEnum,0.0); //default is 0
+	element->GetInputListOnNodes(&vy[0],VyEnum,0.0); //default is 0
+
+	/*Do some modifications if we actually have a HOFS or SSAFS element*/
+	if(approximation==HOFSApproximationEnum){
+		Input* vzFS_input=element->GetInput(VzFSEnum);
+		if (vzFS_input){
+			if (vzFS_input->ObjectEnum()!=PentaInputEnum) _error_("Cannot compute Vel as VzFS is of type " << EnumToStringx(vzFS_input->ObjectEnum()));
+			element->GetInputListOnNodes(&vzFS[0],VzFSEnum,0.);
+		}
+		else _error_("Cannot compute Vz as VzFS in not present in HOFS element");
+		for(i=0;i<numnodes;i++){
+			vzHO[i]=vz[i];
+			vz[i]=vzHO[i]+vzFS[i];
+		}
+	}
+	else if(approximation==SSAFSApproximationEnum){
+		Input* vzFS_input=element->GetInput(VzFSEnum);
+		if (vzFS_input){
+			if (vzFS_input->ObjectEnum()!=PentaInputEnum) _error_("Cannot compute Vel as VzFS is of type " << EnumToStringx(vzFS_input->ObjectEnum()));
+			element->GetInputListOnNodes(&vzFS[0],VzFSEnum,0.);
+		}
+		else _error_("Cannot compute Vz as VzFS in not present in SSAFS element");
+		for(i=0;i<numnodes;i++){
+			vzSSA[i]=vz[i];
+			vz[i]=vzSSA[i]+vzFS[i];
+		}
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<numnodes;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: except it this is a HOFS element */
+	if(approximation!=HOFSApproximationEnum &&  approximation!=SSAFSApproximationEnum){
+		rho_ice = element->GetMaterialParameter(MaterialsRhoIceEnum);
+		g       = element->GetMaterialParameter(ConstantsGEnum);
+		element->GetInputListOnNodes(&surface[0],SurfaceEnum,0.);
+		for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
+	}
+
+	/*Now, we have to move the previous Vz inputs to old 
+	 * status, otherwise, we'll wipe them off and add the new inputs: */
+	element->InputChangeName(VzEnum,VzPicardEnum);
+
+	if(approximation!=HOFSApproximationEnum && approximation!=SSAFSApproximationEnum){
+		element->InputChangeName(PressureEnum,PressurePicardEnum);
+		element->AddInput(PressureEnum,pressure,element->GetElementType());
+	}
+	else if(approximation==HOFSApproximationEnum){
+		element->AddInput(VzHOEnum,vzHO,P1Enum);
+	}
+	else if(approximation==SSAFSApproximationEnum){
+		element->AddInput(VzSSAEnum,vzSSA,P1Enum);
+	}
+	element->AddInput(VzEnum,vz,P1Enum);
+	element->AddInput(VelEnum,vel,P1Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vzSSA);
+	xDelete<IssmDouble>(vzHO);
+	xDelete<IssmDouble>(vzFS);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file StressbalanceVerticalAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _StressbalanceVerticalAnalysis_
+#define _StressbalanceVerticalAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class StressbalanceVerticalAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorVolume(Element* element);
+		ElementVector* CreatePVectorBase(Element* element);
+		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.cpp	(revision 18231)
@@ -0,0 +1,747 @@
+#include "./ThermalAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  ThermalAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void ThermalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
+
+}/*}}}*/
+void ThermalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int frictionlaw;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int finiteelement = P1Enum;
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	bool dakota_analysis, islevelset;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+	iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	iomodel->FetchDataToInput(elements,TemperatureEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	InputUpdateFromConstantx(elements,0.,VxMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
+	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
+	if(dakota_analysis){
+		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(BasalforcingsGroundediceMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
+		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
+	}
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum); // required for updating active nodes
+	}
+	/*Friction law variables*/
+	switch(frictionlaw){
+		case 1:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			break;
+		case 2:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+}/*}}}*/
+void ThermalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,ThermalAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void ThermalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Only 3d mesh supported*/
+	int finiteelement = P1Enum;
+	if(iomodel->domaintype==Domain3DEnum){
+		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum,finiteelement);
+	}
+
+}/*}}}*/
+void ThermalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+	/*create penalties for nodes: no node can have a temperature over the melting point*/
+	iomodel->FetchData(1,ThermalSpctemperatureEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+			if (xIsNan<IssmDouble>(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,ThermalSpctemperatureEnum);
+
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           ThermalAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* ThermalAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* ThermalAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* ThermalAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixVolume(element);
+	ElementMatrix* Ke2=CreateKMatrixShelf(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* ThermalAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	int         stabilization;
+	IssmDouble  Jdet,dt,u,v,w,um,vm,wm,vel;
+	IssmDouble  h,hx,hy,hz,vx,vy,vz;
+	IssmDouble  tau_parameter,diameter;
+	IssmDouble  D_scalar;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(3*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(3*numnodes);
+	IssmDouble     D[3][3]={0.};
+	IssmDouble     K[3][3];
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,ThermalStabilizationEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+	IssmDouble  kappa = thermalconductivity/(rho_ice*heatcapacity);
+	Input* vx_input  = element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input  = element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input  = element->GetInput(VzEnum);     _assert_(vz_input);
+	Input* vxm_input = element->GetInput(VxMeshEnum); _assert_(vxm_input);
+	Input* vym_input = element->GetInput(VyMeshEnum); _assert_(vym_input);
+	Input* vzm_input = element->GetInput(VzMeshEnum); _assert_(vzm_input);
+	if(stabilization==2) diameter=element->MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		D_scalar=gauss->weight*Jdet;
+		if(dt!=0.) D_scalar=D_scalar*dt;
+
+		/*Conduction: */
+		GetBConduct(B,element,xyz_list,gauss); 
+		D[0][0]=D_scalar*kappa;
+		D[1][1]=D_scalar*kappa;
+		D[2][2]=D_scalar*kappa;
+		TripleMultiply(B,3,numnodes,1,
+					&D[0][0],3,3,0,
+					B,3,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+		GetBAdvec(B,element,xyz_list,gauss); 
+		GetBAdvecprime(Bprime,element,xyz_list,gauss); 
+		vx_input->GetInputValue(&u,gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v,gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w,gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		D[2][2]=D_scalar*vz;
+		TripleMultiply(B,3,numnodes,1,
+					&D[0][0],3,3,0,
+					Bprime,3,numnodes,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(dt!=0.){
+			D_scalar=gauss->weight*Jdet;
+			element->NodalFunctions(basis,gauss);
+			TripleMultiply(basis,numnodes,1,0,
+						&D_scalar,1,1,0,
+						basis,1,numnodes,0,
+						&Ke->values[0],1);
+			D_scalar=D_scalar*dt;
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			element->ElementSizes(&hx,&hy,&hz);
+			vel=sqrt(vx*vx + vy*vy + vz*vz)+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2) + pow(hy*vy/vel,2) + pow(hz*vz/vel,2));
+			K[0][0]=h/(2.*vel)*fabs(vx*vx);  K[0][1]=h/(2.*vel)*fabs(vx*vy); K[0][2]=h/(2.*vel)*fabs(vx*vz);
+			K[1][0]=h/(2.*vel)*fabs(vy*vx);  K[1][1]=h/(2.*vel)*fabs(vy*vy); K[1][2]=h/(2.*vel)*fabs(vy*vz);
+			K[2][0]=h/(2.*vel)*fabs(vz*vx);  K[2][1]=h/(2.*vel)*fabs(vz*vy); K[2][2]=h/(2.*vel)*fabs(vz*vz);
+			for(int i=0;i<3;i++) for(int j=0;j<3;j++) K[i][j] = D_scalar*K[i][j];
+
+			GetBAdvecprime(Bprime,element,xyz_list,gauss); 
+
+			TripleMultiply(Bprime,3,numnodes,1,
+						&K[0][0],3,3,0,
+						Bprime,3,numnodes,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			tau_parameter=element->StabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*
+					  ((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i])*((u-um)*dbasis[0*numnodes+j]+(v-vm)*dbasis[1*numnodes+j]+(w-wm)*dbasis[2*numnodes+j]);
+				}
+			}
+			if(dt!=0.){
+				D_scalar=gauss->weight*Jdet;
+				for(int i=0;i<numnodes;i++){
+					for(int j=0;j<numnodes;j++){
+						Ke->values[i*numnodes+j]+=tau_parameter*D_scalar*basis[j]*((u-um)*dbasis[0*numnodes+i]+(v-vm)*dbasis[1*numnodes+i]+(w-wm)*dbasis[2*numnodes+i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementMatrix* ThermalAnalysis::CreateKMatrixShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,D;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		D=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) D=dt*D;
+		TripleMultiply(basis,numnodes,1,0,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return Ke;
+}/*}}}*/
+ElementVector* ThermalAnalysis::CreatePVector(Element* element){/*{{{*/
+	
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorVolume(element);
+	ElementVector* pe2=CreatePVectorSheet(element);
+	ElementVector* pe3=CreatePVectorShelf(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}/*}}}*/
+ElementVector* ThermalAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int         stabilization;
+	IssmDouble  Jdet,phi,dt;
+	IssmDouble  temperature;
+	IssmDouble  tau_parameter,diameter;
+	IssmDouble  u,v,w;
+	IssmDouble  scalar_def,scalar_transient;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe     = element->NewElementVector();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  thermalconductivity = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+	IssmDouble  kappa = thermalconductivity/(rho_ice*heatcapacity);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+	Input* temperature_input = NULL;
+	if(reCast<bool,IssmDouble>(dt)){temperature_input = element->GetInput(TemperatureEnum); _assert_(temperature_input);}
+	if(stabilization==2) diameter=element->MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->ViscousHeating(&phi,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_def*basis[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			temperature_input->GetInputValue(&temperature, gauss);
+			scalar_transient=temperature*Jdet*gauss->weight;
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_transient*basis[i];
+		}
+
+		if(stabilization==2){
+			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+			vx_input->GetInputValue(&u,gauss);
+			vy_input->GetInputValue(&v,gauss);
+			vz_input->GetInputValue(&w,gauss);
+
+			tau_parameter=element->StabilizationParameter(u,v,w,diameter,kappa);
+
+			for(int i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(int i=0;i<numnodes;i++) pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0*numnodes+i]+v*dbasis[1*numnodes+i]+w*dbasis[2*numnodes+i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+
+}/*}}}*/
+ElementVector* ThermalAnalysis::CreatePVectorSheet(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,geothermalflux,vx,vy,vz;
+	IssmDouble  alpha2,scalar,basalfriction,heatflux;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input             = element->GetInput(VxEnum);                          _assert_(vx_input);
+	Input* vy_input             = element->GetInput(VyEnum);                          _assert_(vy_input);
+	Input* vz_input             = element->GetInput(VzEnum);                          _assert_(vz_input);
+	Input* geothermalflux_input = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss   = element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+		friction->GetAlpha2(&alpha2,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		vz = 0.;//FIXME
+		basalfriction = alpha2*(vx*vx + vy*vy + vz*vz);
+		heatflux      = (basalfriction+geothermalflux)/(rho_ice*heatcapacity);
+
+		scalar = gauss->weight*Jdet*heatflux;
+		if(dt!=0.) scalar=dt*scalar;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+ElementVector* ThermalAnalysis::CreatePVectorShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	IssmDouble  t_pmp,dt,Jdet,scalar_ocean,pressure;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input*      pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	IssmDouble  gravity             = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		t_pmp=element->TMeltingPoint(pressure);
+
+		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel*(t_pmp)/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+void ThermalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,TemperatureEnum);
+}/*}}}*/
+void ThermalAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_conduct=[ dh/dx ]
+	 *                  [ dh/dy ]
+	 *                  [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void ThermalAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+		B[numnodes*2+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void ThermalAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void ThermalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void ThermalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	bool        converged;
+	int         i,rheology_law;
+	int        *doflist   = NULL;
+	IssmDouble *xyz_list  = NULL;
+	bool        hack      = false;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
+	IssmDouble* surface   = xNew<IssmDouble>(numnodes);
+	IssmDouble* B         = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		//if(values[i]<0)      _printf_("temperature < 0°K found in solution vector\n");
+		//if(values[i]>275)    _printf_("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)\n");
+	}
+
+	/*Force temperature between [Tpmp-50 Tpmp] to disable penalties*/
+	if(hack){
+		IssmDouble* pressure = xNew<IssmDouble>(numnodes);
+		element->GetInputListOnNodes(&pressure[0],PressureEnum);
+		for(i=0;i<numnodes;i++){
+			if(values[i]>element->TMeltingPoint(pressure[i]))     values[i]=element->TMeltingPoint(pressure[i]);
+			if(values[i]<element->TMeltingPoint(pressure[i])-50.) values[i]=element->TMeltingPoint(pressure[i])-50.;
+		}
+		xDelete<IssmDouble>(pressure);
+	}
+
+	/*Get all inputs and parameters*/
+	element->GetInputValue(&converged,ConvergedEnum);
+	if(converged){
+		element->AddInput(TemperatureEnum,values,element->GetElementType());
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case CuffeyEnum:
+				for(i=0;i<numnodes;i++) B[i]=Cuffey(values[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case PatersonEnum:
+				for(i=0;i<numnodes;i++) B[i]=Paterson(values[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case ArrheniusEnum:{
+				element->GetVerticesCoordinates(&xyz_list);
+				for(i=0;i<numnodes;i++) B[i]=Arrhenius(values[i],surface[i]-xyz_list[i*3+2],element->GetMaterialParameter(MaterialsRheologyNEnum));
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+				}
+			default:
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+		}
+	}
+	else{
+		element->AddInput(TemperaturePicardEnum,values,element->GetElementType());
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+void ThermalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/ThermalAnalysis.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file ThermalAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _THERMALANALYSIS_
+#define _THERMALANALYSIS_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class ThermalAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixVolume(Element* element);
+		ElementMatrix* CreateKMatrixShelf(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorVolume(Element* element);
+		ElementVector* CreatePVectorSheet(Element* element);
+		ElementVector* CreatePVectorShelf(Element* element);
+		void GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 18231)
@@ -0,0 +1,195 @@
+#include "./UzawaPressureAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  UzawaPressureAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRhopEnum));
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int finiteelement = P1Enum;
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchDataToInput(elements,VzEnum,0.);
+	iomodel->FetchDataToInput(elements,PressureEnum,0.);
+}/*}}}*/
+void UzawaPressureAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	::CreateNodes(nodes,iomodel,UzawaPressureAnalysisEnum,finiteelement);
+}/*}}}*/
+void UzawaPressureAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+void UzawaPressureAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           UzawaPressureAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* UzawaPressureAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* UzawaPressureAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* UzawaPressureAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble  D_scalar,Jdet;
+	IssmDouble *xyz_list = NULL;
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke   = element->NewElementMatrix();
+	IssmDouble*    M    = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetM(M,element,gauss);
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(M,1,numnodes,1,
+					&D_scalar,1,1,0,
+					M,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(M);
+	return Ke;
+}/*}}}*/
+ElementVector* UzawaPressureAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int          dim;
+	IssmDouble   Jdet,rhop,divu;
+	IssmDouble   *xyz_list = NULL;
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&rhop,AugmentedLagrangianRhopEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dvx   = xNew<IssmDouble>(dim);
+	IssmDouble*    dvy   = xNew<IssmDouble>(dim);
+	IssmDouble*    dvz   = xNew<IssmDouble>(dim);
+
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		if(dim==3){
+			vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+		}
+
+		divu=dvx[0]+dvy[1];
+		if (dim==3) divu=divu+dvz[2];
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i] += - rhop * divu * Jdet * gauss->weight * basis[i];
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dvx);
+	xDelete<IssmDouble>(dvy);
+	xDelete<IssmDouble>(dvz);
+	return pe;
+}/*}}}*/
+void UzawaPressureAnalysis::GetM(IssmDouble* M,Element* element,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. M=[M1 M2 M3] */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		M[i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void UzawaPressureAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void UzawaPressureAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void UzawaPressureAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int        *doflist   = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(numnodes);
+	element->GetInputListOnNodes(&pressure[0],PressureEnum);
+
+	for(int i=0;i<numnodes;i++){
+		values[i]   = pressure[i] + solution[doflist[i]];
+	}
+
+	element->AddInput(PressureEnum,values,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(pressure);
+	xDelete<int>(doflist);
+
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/UzawaPressureAnalysis.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file UzawaPressureAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _UzawaPressureAnalysis_
+#define _UzawaPressureAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class UzawaPressureAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetM(IssmDouble* M,Element* element,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/analyses.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/analyses.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/analyses/analyses.h	(revision 18231)
@@ -0,0 +1,44 @@
+/*
+ * analyses.h: 
+ */
+
+#ifndef _ANALYSES_H_
+#define _ANALYSES_H_
+
+#include "./Analysis.h"
+
+#include "./AdjointBalancethicknessAnalysis.h"
+#include "./AdjointBalancethickness2Analysis.h"
+#include "./AdjointHorizAnalysis.h"
+#include "./BalancethicknessAnalysis.h"
+#include "./Balancethickness2Analysis.h"
+#include "./BalancethicknessSoftAnalysis.h"
+#include "./BalancevelocityAnalysis.h"
+#include "./DamageEvolutionAnalysis.h"
+#include "./DepthAverageAnalysis.h"
+#include "./EnthalpyAnalysis.h"
+#include "./ExtrudeFromBaseAnalysis.h"
+#include "./ExtrudeFromTopAnalysis.h"
+#include "./ExtrapolationAnalysis.h"
+#include "./FreeSurfaceBaseAnalysis.h"
+#include "./FreeSurfaceTopAnalysis.h"
+#include "./GiaAnalysis.h"
+#include "./HydrologyDCEfficientAnalysis.h"
+#include "./HydrologyDCInefficientAnalysis.h"
+#include "./HydrologyShreveAnalysis.h"
+#include "./LevelsetAnalysis.h"
+#include "./LsfReinitializationAnalysis.h"
+#include "./MasstransportAnalysis.h"
+#include "./MeltingAnalysis.h"
+#include "./MeshdeformationAnalysis.h"
+#include "./SmoothedSurfaceSlopeXAnalysis.h"
+#include "./SmoothedSurfaceSlopeYAnalysis.h"
+#include "./StressbalanceAnalysis.h"
+#include "./StressbalanceSIAAnalysis.h"
+#include "./StressbalanceVerticalAnalysis.h"
+#include "./UzawaPressureAnalysis.h"
+#include "./L2ProjectionBaseAnalysis.h"
+#include "./L2ProjectionEPLAnalysis.h"
+#include "./ThermalAnalysis.h"
+#include "./EnumToAnalysis.h"
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.cpp	(revision 18231)
@@ -0,0 +1,57 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "AdjacentTriangle.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	int  AdjacentTriangle::Locked() const {/*{{{*/
+		return t->AdjEdgeIndex[a] & 4;
+	}
+	/*}}}*/
+	int  AdjacentTriangle::GetAllFlag_UnSwap() const {/*{{{*/
+		// take all flag except MarkUnSwap
+		return t->AdjEdgeIndex[a] & 1012;
+	}
+	/*}}}*/
+	void AdjacentTriangle::SetLock(){/*{{{*/
+		t->SetLocked(a);
+	}
+	/*}}}*/
+	AdjacentTriangle AdjacentTriangle::Adj() const {/*{{{*/
+		return  t->Adj(a);
+	}
+	/*}}}*/
+	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {/*{{{*/
+		return t->vertices[VerticesOfTriangularEdge[a][i]];
+	}
+	/*}}}*/
+	Icoor2 & AdjacentTriangle::det() const {/*{{{*/
+		return t->det;
+	}
+	/*}}}*/
+	int AdjacentTriangle::swap(){/*{{{*/
+		return  t->swap(a);
+	}
+	/*}}}*/
+	void AdjacentTriangle::SetAdj2(const AdjacentTriangle & ta, int l  ){/*{{{*/
+		//set Adjacent Triangle of a triangle
+		if(t) {
+			t->adj[a]=ta.t;
+			t->AdjEdgeIndex[a]=ta.a|l;
+		}
+		if(ta.t) {
+			ta.t->adj[ta.a] = t ;
+			ta.t->AdjEdgeIndex[ta.a] = a| l ;
+		}
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/AdjacentTriangle.h	(revision 18231)
@@ -0,0 +1,42 @@
+#ifndef _TRIANGLEADJACENT_H_
+#define _TRIANGLEADJACENT_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Triangle;
+
+	class AdjacentTriangle {
+
+		public:
+			Triangle* t; //pointer toward the triangle
+			int  a;      //Edge number
+
+			//Constructors
+			AdjacentTriangle():a(0),t(NULL) {};
+			AdjacentTriangle(Triangle* tt,int  aa): t(tt),a(aa &3) {};
+
+			//Operators
+			operator Triangle * () const {return t;}
+			operator Triangle & () const {return *t;}
+			operator int() const {return a;}
+			AdjacentTriangle & operator++(){ a= NextEdge[a]; return *this; }
+			AdjacentTriangle operator--(){ a= PreviousEdge[a]; return *this; }
+
+			//Methods
+
+			//Methods
+			int  Locked() const;
+			int  GetAllFlag_UnSwap() const;
+			void SetLock();
+			void SetAdj2(const AdjacentTriangle &ta, int l=0);
+			int  swap();
+			AdjacentTriangle Adj() const;
+			BamgVertex* EdgeVertex(const int & i) const;
+			Icoor2& det() const;
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.cpp	(revision 18231)
@@ -0,0 +1,30 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+BamgGeom::BamgGeom(){/*{{{*/
+
+	this->VerticesSize[0]=0,          this->VerticesSize[1]=0;          this->Vertices=NULL;
+	this->EdgesSize[0]=0,             this->EdgesSize[1]=0;             this->Edges=NULL;
+	this->TangentAtEdgesSize[0]=0,    this->TangentAtEdgesSize[1]=0;    this->TangentAtEdges=NULL;
+	this->CornersSize[0]=0,           this->CornersSize[1]=0;           this->Corners=NULL;
+	this->RequiredVerticesSize[0]=0,  this->RequiredVerticesSize[1]=0;  this->RequiredVertices=NULL;
+	this->RequiredEdgesSize[0]=0,     this->RequiredEdgesSize[1]=0;     this->RequiredEdges=NULL;
+	this->CrackedEdgesSize[0]=0,      this->CrackedEdgesSize[1]=0;      this->CrackedEdges=NULL;
+	this->SubDomainsSize[0]=0,        this->SubDomainsSize[1]=0;        this->SubDomains=NULL;
+
+}
+/*}}}*/
+BamgGeom::~BamgGeom(){/*{{{*/
+
+	xDelete<double>(this->Vertices);
+	xDelete<double>(this->Edges);
+	xDelete<double>(this->TangentAtEdges);
+	xDelete<double>(this->Corners);
+	xDelete<double>(this->RequiredVertices);
+	xDelete<double>(this->RequiredEdges);
+	xDelete<double>(this->CrackedEdges);
+	xDelete<double>(this->SubDomains);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgGeom.h	(revision 18231)
@@ -0,0 +1,31 @@
+/*!\file:  BamgGeom.h
+ */ 
+
+#ifndef _BAMGGEOM_H_
+#define _BAMGGEOM_H_
+
+class BamgGeom{
+
+	public:
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TangentAtEdgesSize[2];
+		double* TangentAtEdges;
+		int     CornersSize[2];
+		double* Corners;
+		int     RequiredVerticesSize[2];
+		double* RequiredVertices;
+		int     RequiredEdgesSize[2];
+		double* RequiredEdges;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+		int     SubDomainsSize[2];
+		double* SubDomains;
+
+		BamgGeom();
+		~BamgGeom();
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.cpp	(revision 18231)
@@ -0,0 +1,52 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+BamgMesh::BamgMesh(){/*{{{*/
+
+	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;
+	this->EdgesSize[0]=0,                     this->EdgesSize[1]=0;                    this->Edges=NULL;
+	this->TrianglesSize[0]=0,                 this->TrianglesSize[1]=0;                this->Triangles=NULL;
+	this->QuadrilateralsSize[0]=0,            this->QuadrilateralsSize[1]=0;           this->Quadrilaterals=NULL;
+
+	this->SubDomainsSize[0]=0,                this->SubDomainsSize[1]=0;               this->SubDomains=NULL;
+	this->SubDomainsFromGeomSize[0]=0,        this->SubDomainsFromGeomSize[1]=0;       this->SubDomainsFromGeom=NULL;
+	this->CrackedVerticesSize[0]=0,           this->CrackedVerticesSize[1]=0;          this->CrackedVertices=NULL;
+	this->CrackedEdgesSize[0]=0,              this->CrackedEdgesSize[1]=0;             this->CrackedEdges=NULL;
+
+	this->VerticesOnGeomVertexSize[0]=0,      this->VerticesOnGeomVertexSize[1]=0;     this->VerticesOnGeomVertex=NULL;
+	this->VerticesOnGeomEdgeSize[0]=0,        this->VerticesOnGeomEdgeSize[1]=0;       this->VerticesOnGeomEdge=NULL;
+	this->EdgesOnGeomEdgeSize[0]=0,           this->EdgesOnGeomEdgeSize[1]=0;          this->EdgesOnGeomEdge=NULL;
+
+	this->IssmEdgesSize[0]=0,                 this->IssmEdgesSize[1]=0;                this->IssmEdges=NULL;
+	this->IssmSegmentsSize[0]=0,              this->IssmSegmentsSize[1]=0;             this->IssmSegments=NULL;
+
+	this->ElementConnectivitySize[0]=0,       this->ElementConnectivitySize[1]=0;      this->ElementConnectivity=NULL;
+	this->NodalConnectivitySize[0]=0,         this->NodalConnectivitySize[1]=0;        this->NodalConnectivity=NULL;
+	this->NodalElementConnectivitySize[0]=0,  this->NodalElementConnectivitySize[1]=0; this->NodalElementConnectivity=NULL;
+}
+/*}}}*/
+BamgMesh::~BamgMesh(){/*{{{*/
+
+	xDelete<double>(this->Vertices);
+	xDelete<double>(this->Edges);
+	xDelete<double>(this->Triangles);
+	xDelete<double>(this->Quadrilaterals);
+
+	xDelete<double>(this->SubDomains);
+	xDelete<double>(this->SubDomainsFromGeom);
+	xDelete<double>(this->CrackedVertices);
+	xDelete<double>(this->CrackedEdges);
+
+	xDelete<double>(this->VerticesOnGeomVertex);
+	xDelete<double>(this->VerticesOnGeomEdge);
+	xDelete<double>(this->EdgesOnGeomEdge);
+
+	xDelete<double>(this->IssmEdges);
+	xDelete<double>(this->IssmSegments);
+
+	xDelete<double>(this->ElementConnectivity);
+	xDelete<double>(this->NodalConnectivity);
+	xDelete<double>(this->NodalElementConnectivity);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgMesh.h	(revision 18231)
@@ -0,0 +1,52 @@
+/*!\file:  BamgMesh.h
+ */ 
+
+#ifndef _BAMGMESH_H_
+#define _BAMGMESH_H_
+
+class BamgMesh{
+
+	public:
+
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TrianglesSize[2];
+		double* Triangles;
+		int     QuadrilateralsSize[2];
+		double* Quadrilaterals;
+
+		int     VerticesOnGeomVertexSize[2];
+		double* VerticesOnGeomVertex;
+		int     VerticesOnGeomEdgeSize[2];
+		double* VerticesOnGeomEdge;
+		int     EdgesOnGeomEdgeSize[2];
+		double* EdgesOnGeomEdge;
+
+		int     SubDomainsSize[2];
+		double* SubDomains;
+		int     SubDomainsFromGeomSize[2];
+		double* SubDomainsFromGeom;
+		int     CrackedVerticesSize[2];
+		double* CrackedVertices;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+
+		/*Output for ISSM*/
+		int     IssmEdgesSize[2];
+		double* IssmEdges;
+		int     IssmSegmentsSize[2];
+		double* IssmSegments;
+		int     ElementConnectivitySize[2];
+		double* ElementConnectivity;
+		int     NodalConnectivitySize[2];
+		double* NodalConnectivity;
+		int     NodalElementConnectivitySize[2];
+		double* NodalElementConnectivity;
+
+		BamgMesh();
+		~BamgMesh();
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.cpp	(revision 18231)
@@ -0,0 +1,84 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+BamgOpts::BamgOpts(){/*{{{*/
+
+	this->anisomax=0;
+	this->cutoff=0;
+	this->coeff=0;
+	this->errg=0;
+	this->gradation=0;
+	this->Hessiantype=0;
+	this->MaxCornerAngle=0;
+	this->maxnbv=0;
+	this->maxsubdiv=0;
+	this->Metrictype=0;
+	this->nbjacobi=0;
+	this->nbsmooth=0;
+	this->omega=0;
+	this->power=0;
+	this->random=0;
+	this->verbose=0;
+
+	this->Crack=0;
+	this->geometricalmetric=0;
+	this->KeepVertices=0;
+	this->splitcorners=0;
+
+	this->hmin=0;
+	this->hmax=0;
+	this->hminVertices=NULL; this->hminVerticesSize[0]=this->hminVerticesSize[1]=0;
+	this->hmaxVertices=NULL; this->hmaxVerticesSize[0]=this->hmaxVerticesSize[1]=0;
+	this->hVertices=NULL;    this->hVerticesSize[0]=this->hVerticesSize[1]=0;
+	this->metric=NULL;       this->metricSize[0]=this->metricSize[1]=0;
+	this->field=NULL;        this->fieldSize[0]=this->fieldSize[1]=0;
+	this->err=NULL;          this->errSize[0]=this->errSize[1]=0;
+
+}
+/*}}}*/
+BamgOpts::~BamgOpts(){/*{{{*/
+
+	xDelete<double>(this->hminVertices);
+	xDelete<double>(this->hmaxVertices);
+	xDelete<double>(this->hVertices);
+	xDelete<double>(this->metric);
+	xDelete<double>(this->field);
+	xDelete<double>(this->err);
+
+}
+/*}}}*/
+
+/*Methods*/
+void BamgOpts::Check(void){/*{{{*/
+
+	int i;
+
+	if (this->anisomax<1) _error_("'anisomax' option should be >=1");
+	if (this->coeff==0) _error_("'coeff' should be positive");
+	if (this->errg<0) _error_("'errg' option should be >0");
+	if (this->gradation<1) _error_("'gradation' option should be >=1");
+	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error_("'Hessiantype' supported options are 0 and 1");
+	if (this->maxnbv<3) _error_("'maxnbv' option should be >3");
+	if (this->maxsubdiv<=1) _error_("'maxsubdiv' should be >1");
+	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error_("'Metrictype' supported options are 0, 1 and 2");
+	if (this->nbjacobi<=0) _error_("'nbjacobi' option should be >0");
+	if (this->nbsmooth<=0) _error_("'nbsmooth' option should be >0");
+
+	if (this->Crack!=0  && this->Crack!=1) _error_("'Crack' supported options are 0 and 1");
+	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error_("'KeepVertices' supported options are 0 and 1");
+	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error_("'geometricalmetric' supported options are 0 and 1");
+
+	if (this->hmin<=0) _error_("'hmin' option should be >0");
+	if (this->hmax<=0 || this->hmax<this->hmin) _error_("'hmax' option should be between 0 and hmin=" << this->hmin);
+	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error_("'hminVertices' should be a column");
+	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error_("'hmaxVertices' should be a column");
+	if (this->hVertices && this->hVerticesSize[1]!=1) _error_("'hVertices' should be a column");
+	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
+	if (this->field){
+		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error_("'err' option should be >0");};
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgOpts.h	(revision 18231)
@@ -0,0 +1,58 @@
+/*!\file:  BamgOpts.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _BAMGOPTS_H_
+#define _BAMGOPTS_H_
+
+class BamgOpts{
+
+	public:
+
+		/*Parameters*/
+		double  anisomax;
+		double  cutoff;
+		double  coeff;
+		double  errg;
+		double  gradation;
+		int     Hessiantype;
+		double  MaxCornerAngle;
+		int     maxnbv;
+		double  maxsubdiv;
+		int     Metrictype;
+		int     nbjacobi;
+		int     nbsmooth;
+		double  omega;
+		double  power;
+		bool    random;
+		int     verbose;
+
+		/*Flags*/
+		int     Crack;
+		int     geometricalmetric;
+		int     KeepVertices;
+		int     splitcorners;
+
+		/*Metric related*/
+		double  hmin;
+		double  hmax;
+		int     hminVerticesSize[2];
+		double* hminVertices;
+		int     hmaxVerticesSize[2];
+		double* hmaxVertices;
+		int     hVerticesSize[2];
+		double* hVertices;
+		int     metricSize[2];
+		double* metric;
+		int     fieldSize[2];
+		double* field;
+		int     errSize[2];
+		double* err;
+
+		BamgOpts();
+		~BamgOpts();
+
+		void Check(void);
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.cpp	(revision 18231)
@@ -0,0 +1,481 @@
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "./bamgobjects.h"
+#include "../datastructures/datastructures.h"
+
+namespace bamg {
+
+	/*MACROS {{{*/
+	/* 
+	 * 
+	 *    J    j
+	 *    ^    ^
+	 *    |    | +--------+--------+
+	 *    |    | |        |        |
+	 * 1X |    | |   2    |   3    |
+	 *    |    | |        |        |
+	 *    |    | +--------+--------+
+	 *    |    | |        |        |
+	 * 0X |    | |   0    |   1    |
+	 *    |    | |        |        |
+	 *    |    | +--------+--------+
+	 *    |    +-----------------------> i
+	 *    |         
+	 *    |----------------------------> I
+	 *              X0        X1  
+	 *
+	 * box 0 -> I=0 J=0 IJ=00  = 0
+	 * box 1 -> I=1 J=0 IJ=01  = 1
+	 * box 2 -> I=0 J=1 IJ=10  = 2
+	 * box 3 -> I=1 J=1 IJ=11  = 3
+	 */
+#define INTER_SEG(a,b,x,y) (((y) > (a)) && ((x) <(b)))
+#define ABS(i) ((i)<0 ?-(i) :(i))
+#define MAX1(i,j) ((i)>(j) ?(i) :(j))
+#define NORM(i1,j1,i2,j2) MAX1(ABS((i1)-(j1)),ABS((i2)-(j2)))
+
+	//IJ(i,j,l) returns the box number of i and j with respect to l
+	//if !j&l and !i&l -> 0 (box zero: lower left )
+	//if !j&l and  i&l -> 1 (box one:  lower right)
+	//if  j&l and !i&l -> 2 (box two:  upper left )
+	//if  j&l and  i&l -> 3 (box three:upper right)
+#define IJ(i,j,l)  ((j&l) ? ((i&l) ? 3:2 ) :((i&l) ? 1:0 ))
+
+	//I_IJ(k,l) returns l if first  bit of k is 1, else 0
+#define I_IJ(k,l)  ((k&1) ? l:0)
+	//J_IJ(k,l) returns l if second bit of k is 1, else 0
+#define J_IJ(k,l)  ((k&2) ? l:0)
+	/*}}}*/
+	/*DOCUMENTATION What is a BamgQuadtree? {{{
+	 * A Quadtree is a very simple way to group vertices according
+	 * to their locations. A square that holds all the points of the mesh
+	 * (or the geometry) is divided into 4 boxes. As soon as one box
+	 * hold more than 4 vertices, it is divided into 4 new boxes, etc...
+	 * There cannot be more than MAXDEEP (=30) subdivision.
+	 * This process is like a Dichotomy in dimension 2
+	 *
+	 *  + - -  -    - -    -    - - + -   - + - + - + - -     - - +
+	 *  |                           |       |   | X |             |
+	 *                                      + - + - +
+	 *  |                           |       |   |   |             |
+	 *                              + -   - + - + - +             +
+	 *  |                           |       |       |             |
+	 *                         
+	 *  |                           |       |       |             |
+	 *  + - -  -    - -    -    - - + -   - + -   - + - -     - - +
+	 *  |                           |               |             |
+	 *                         
+	 *  |                           |               |             |
+	 *                         
+	 *  |                           |               |             |
+	 *  |                           |               |             |
+	 *  + - -  -    - -    -    - - + -   -   -   - + - -     - - +
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  + - -  -    - -    -    - - + -   -   -   -   - -     - - +
+	 *
+	 * The coordinate system used in a quadtree are integers to avoid
+	 * round-off errors. The vertex in the lower left box has the coordinates
+	 * (0 0) 
+	 * The upper right vertex has the follwing coordinates:
+	 * 2^30 -1           2^30 -1        in decimal
+	 * 0 1 1 1 .... 1    0 1 1 1 .... 1 in binary
+	 *  \--   29  --/     \--   29  --/
+	 * Using binaries is therefore very easy to locate a vertex in a box:
+	 * we just need to look at the bits from the left to the right (See ::Add)
+	 }}}*/
+
+	/*Constructors/Destructors*/
+	BamgQuadtree::BamgQuadtree(){/*{{{*/
+
+		/*Number of boxes and vertices*/
+		NbBamgQuadtreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewBamgQuadtreeBox();
+
+		}
+	/*}}}*/
+	BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){ /*{{{*/
+
+		/*Number of boxes and vertices*/
+		NbBamgQuadtreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewBamgQuadtreeBox();
+
+		/*Check Sizes*/
+		_assert_(MaxISize>MaxICoor);
+
+		/*Add all vertices of the mesh*/
+		if (nbv==-1) nbv=t->nbv;
+		for (int i=0;i<nbv;i++) Add(t->vertices[i]);
+
+	}
+	/*}}}*/
+	BamgQuadtree::~BamgQuadtree() {/*{{{*/
+		delete boxcontainer;
+		root=NULL;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	void  BamgQuadtree::Add(BamgVertex &w){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/Add)*/
+		BamgQuadtreeBox** pb=NULL;
+		BamgQuadtreeBox*  b=NULL;
+
+		/*Get integer coodinate of current point w*/
+		long i=w.i.x, j=w.i.y;
+
+		/*Initialize level*/
+		long level=MaxISize;
+
+		/*Get inital box (the largest)*/
+		pb = &root;
+
+		/*Find the smallest box where w is located*/
+		while((b=*pb) && (b->nbitems<0)){ 
+
+			//shift b->nbitems by -1
+			b->nbitems--;
+
+			//shifted righ by one bit: level=00000010 -> 00000001
+			level >>= 1;
+
+			//Get next subbox according to the bit value (level)
+			pb = &b->b[IJ(i,j,level)];
+		}
+
+		/*OK, we have found b, a Subbox holding vertices (might be full)
+		  check that the vertex is not already in the box*/
+		if (b){      
+			if (b->nbitems > 3 &&  b->v[3] == &w) return;
+			if (b->nbitems > 2 &&  b->v[2] == &w) return;
+			if (b->nbitems > 1 &&  b->v[1] == &w) return;
+			if (b->nbitems > 0 &&  b->v[0] == &w) return;
+		}
+
+		/*check that l is not 0 (this should not happen as MaxDepth = 30)*/
+		_assert_(level>0);
+
+		/*Now, try to add the vertex, if the subbox is full (nbitems=4), we have to divide it
+		  in 4 new subboxes*/
+		while ((b= *pb) && (b->nbitems == 4)){ // the BamgQuadtreeBox is full
+
+			/*Copy the 4 vertices in the current BamgQuadtreebox*/
+			BamgVertex* v4[4];
+			v4[0]= b->v[0];
+			v4[1]= b->v[1];
+			v4[2]= b->v[2];
+			v4[3]= b->v[3];
+
+			/*set nbitems as negative 
+			 * (box full -> holds 4 pointers toward subboxes and not 4 vertices)*/
+			b->nbitems = -b->nbitems;
+
+			/*Initialize the 4 pointers toward the 4 subboxes*/
+			b->b[0]=b->b[1]=b->b[2]=b->b[3]=NULL;
+
+			/*level = 0010000 -> 0001000*/
+			level >>= 1;
+
+			/*Put the four vertices in the new boxes*/
+			for (int k=0;k<4;k++){
+
+				int          ij;
+				/*bb is the new "sub"box of b where v4[k] is located*/
+				BamgQuadtreeBox *bb = b->b[ij=IJ(v4[k]->i.x,v4[k]->i.y,level)];
+
+				// alloc the BamgQuadtreeBox
+				if (!bb) bb=b->b[ij]=NewBamgQuadtreeBox(); 
+
+				/*Copy the current vertex*/
+				bb->v[bb->nbitems++] = v4[k];
+			}
+
+			/*Get the subbox where w (i,j) is located*/
+			pb = &b->b[IJ(i,j,level)];
+		}
+
+		/*alloc the BamgQuadtreeBox if necessary*/
+		if (!(b=*pb)) b=*pb= NewBamgQuadtreeBox();
+
+		/*Add w*/
+		b->v[b->nbitems++]=&w;
+
+		//Increase NbVertices by one (we have one new vertex)
+		NbVertices++;
+	}
+	/*}}}*/
+	BamgVertex*  BamgQuadtree::NearestVertex(Icoor1 i,Icoor1 j) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/NearestVertex)*/
+
+		/*Intermediaries*/
+		BamgQuadtreeBox *pb[MaxDepth];
+		int          pi[MaxDepth];
+		Icoor1       ii[MaxDepth];
+		Icoor1       jj[MaxDepth];
+		int          level;
+		long         n0;
+		BamgQuadtreeBox *b;
+		long         h0;
+		long         h = MaxISize;
+		long         hb= MaxISize;
+		Icoor1       i0=0,j0=0;
+
+		/*initial output as NULL (no vertex found)*/
+		BamgVertex*  nearest_v=NULL;
+
+		/*Project w coordinates (i,j) onto [0,MaxISize-1] x [0,MaxISize-1] -> (iplus,jplus)*/
+		Icoor1 iplus( i<MaxISize ? (i<0?0:i) : MaxISize-1);
+		Icoor1 jplus( j<MaxISize ? (j<0?0:j) : MaxISize-1);
+
+		/*Get initial Quadtree box (largest)*/
+		b = root;
+
+		/*if the tree is empty, return NULL pointer*/
+		if (!root->nbitems) return nearest_v; 
+
+		/*else, find the smallest non-empty BamgQuadtreeBox containing  the point (i,j)*/
+		while((n0=b->nbitems)<0){
+
+			Icoor1       hb2 = hb >> 1;             //size of the current box
+			int          k   = IJ(iplus,jplus,hb2); //box number (0,1,2 or 3)
+			BamgQuadtreeBox *b0  = b->b[k];             //pointer toward current box
+
+			/* break if NULL box or empty (Keep previous box b)*/
+			if (( b0 == NULL) || (b0->nbitems == 0)) break;
+
+			/*Get next Quadtree box*/
+			b=b0;	
+			i0 += I_IJ(k,hb2); // i orign of BamgQuadtreeBox (macro)
+			j0 += J_IJ(k,hb2); // j orign of BamgQuadtreeBox 
+			hb = hb2;          // size of the box (in Int)
+		}
+
+		/*The box b, is the smallest box containing the point (i,j) and
+		 * has the following properties:
+		 * - n0: number of items (>0 if vertices, else boxes)
+		 * - hb: box size (int)
+		 * - i0: x coordinate of the lower left corner
+		 * - j0: y coordinate of the lower left corner*/
+
+		/* if the current subbox is holding vertices, we are almost done*/
+		if (n0>0){  
+			//loop over the vertices of the box and find the closest vertex
+			for(int k=0;k<n0;k++){
+
+				/*get integer coordinates of current vertex*/
+				I2 i2=b->v[k]->i;
+
+				/*Compute norm with w*/
+				h0=NORM(iplus,i2.x,jplus,i2.y);
+
+				/*is it smaller than previous value*/
+				if (h0<h){
+					h = h0;
+					nearest_v = b->v[k];
+				}
+			}
+			/*return closest vertex*/
+			return nearest_v;
+		}
+
+		/* general case: the current box is empty, we have to go backwards
+			and find the closest not-empty box and find the closest vertex*/
+
+		/*Initialize search variables*/
+		pb[0]=b;                             //pointer toward the box b
+		pi[0]=b->nbitems>0?(int)b->nbitems:4;//number of boxes in b
+		ii[0]=i0;                            //i coordinate of the box lowest left corner
+		jj[0]=j0;                            //j coordinate of the box lowest left corner
+
+		/*initialize h: smallest box size, containing a vertex close to w*/
+		h=hb;
+
+		/*Main loop*/
+		level=0;
+		do {
+
+			/*get current box*/
+			b= pb[level];
+
+			/*Loop over the items in current box (if not empty!)*/
+			while (pi[level]){
+
+				/*We are looping now over the items of b. k is the current index (in [0 3])*/
+				pi[level]--;
+				int k=pi[level];
+
+				/*if the current subbox is holding vertices (b->nbitems<0 is subboxes)*/
+				if (b->nbitems>0){
+					I2 i2=b->v[k]->i;
+					h0 = NORM(iplus,i2.x,jplus,i2.y);
+					if (h0<h){
+						h=h0;
+						nearest_v=b->v[k];
+					}
+				}
+				/*else: current box b is pointing toward 4 boxes
+				 * test sub-box k and go deeper into the tree if it is non empty
+				 * and contains the point w modulo a size h that is either the size of the smallest
+				 * non empty box containing w, or the closest point to w (so far) */
+				else{
+					BamgQuadtreeBox* b0=b;
+
+					/*if the next box exists:*/
+					if((b=b->b[k])){
+
+						/*Get size (hb) and coordinates of the current sub-box lowest left corner*/
+						hb>>=1;
+						Icoor1 iii = ii[level]+I_IJ(k,hb);
+						Icoor1 jjj = jj[level]+J_IJ(k,hb);
+
+						/*if the current point (iplus,jplus) is in b (modulo h), this box is good:
+						 * it is holding vertices that are close to w */
+						if (INTER_SEG(iii,iii+hb,iplus-h,iplus+h) && INTER_SEG(jjj,jjj+hb,jplus-h,jplus+h)){
+							level++;
+							pb[level]= b;
+							pi[level]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[level]= iii;
+							jj[level]= jjj;
+						}
+
+						//else go backwards
+						else{
+							//shifted righ by one bit: hb=001000000 -> 01000000
+							b=b0;
+							hb<<=1;
+						}
+					}
+					else{
+						/*Current box is NULL, go to next subbox of b (k=k-1)*/
+						b=b0;
+					}
+				}
+			}
+
+			/*We have found a vertex, now, let's try the other boxes of the previous level
+			 * in case there is a vertex closest to w that has not yet been tested*/
+			hb <<= 1;
+		} while (level--);
+
+		/*return nearest_v, nearest vertex*/
+		return nearest_v;
+
+	}
+	/*}}}*/
+	BamgQuadtree::BamgQuadtreeBox* BamgQuadtree::NewBamgQuadtreeBox(void){/*{{{*/
+
+		/*Output*/
+		BamgQuadtreeBox* newbox=NULL;
+
+		/*Create and initialize a new box*/
+		newbox=new BamgQuadtreeBox;
+		newbox->nbitems=0;
+		newbox->b[0]=NULL;
+		newbox->b[1]=NULL;
+		newbox->b[2]=NULL;
+		newbox->b[3]=NULL;
+
+		/*Add root to the container*/
+		boxcontainer->AddObject(newbox);
+
+		/*Increase counter*/
+		NbBamgQuadtreeBox++;
+
+		/*currentbox now points toward next quadtree box*/
+		return newbox;
+	}/*}}}*/
+	BamgVertex*   BamgQuadtree::ToClose(BamgVertex & v,double seuil,Icoor1 hx,Icoor1 hy){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/ToClose)*/
+
+		const Icoor1 i=v.i.x;
+		const Icoor1 j=v.i.y;
+		const R2 X(v.r);
+		const Metric  Mx(v.m);
+
+		BamgQuadtreeBox * pb[ MaxDepth ];
+		int  pi[ MaxDepth  ];
+		Icoor1 ii[  MaxDepth ], jj [ MaxDepth];
+		int l=0; // level
+		BamgQuadtreeBox * b;
+		Icoor1 hb =  MaxISize;
+		Icoor1 i0=0,j0=0;
+
+		//  BamgVertex *vn=0;
+
+		if (!root->nbitems)
+		 return 0; // empty tree 
+
+		// general case -----
+		pb[0]=root;
+		pi[0]=root->nbitems>0 ?(int)  root->nbitems : 4  ;
+		ii[0]=i0;
+		jj[0]=j0;
+		do {    
+			b= pb[l];
+			while (pi[l]--){ 	      
+				int k = pi[l];
+
+				if (b->nbitems>0){ // BamgVertex BamgQuadtreeBox none empty
+					I2 i2 =  b->v[k]->i;
+					if ( ABS(i-i2.x) <hx && ABS(j-i2.y) <hy )
+					  {
+						R2 XY(X,b->v[k]->r);
+						if(LengthInterpole(Mx(XY), b->v[k]->m(XY)) < seuil){
+							return b->v[k]; 
+						}
+					  }
+				}
+				else{ // Pointer BamgQuadtreeBox 
+					BamgQuadtreeBox *b0=b;
+					if ((b=b->b[k])){
+						hb >>=1 ; // div by 2
+						long iii = ii[l]+I_IJ(k,hb);
+						long jjj = jj[l]+J_IJ(k,hb);
+
+						if  (INTER_SEG(iii,iii+hb,i-hx,i+hx) && INTER_SEG(jjj,jjj+hb,j-hy,j+hy)){
+							pb[++l]=  b;
+							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[l]= iii;
+							jj[l]= jjj;
+
+						}
+						else{
+							b=b0;
+							hb <<=1 ;
+						}
+					}
+					else{
+						b=b0;
+					}
+				}
+			}
+			hb <<= 1; // mul by 2 
+		} while (l--);
+
+		return 0;
+	}
+	/*}}}*/
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgQuadtree.h	(revision 18231)
@@ -0,0 +1,59 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.h)*/
+#ifndef _BAMGQUADTREE_H
+#define _BAMGQUADTREE_H
+
+#include "./include.h"
+#include "../datastructures/datastructures.h"
+
+namespace bamg {
+
+	const int  MaxDepth = 30;
+	const long MaxISize = ( 1L << MaxDepth);  // = 2^30 : 010000000000..000 (bitwise operation)
+
+	class BamgVertex;
+
+	class BamgQuadtree{
+
+		private:
+
+			/*A quadtree box contains a maximum of 4 vertices. 4 other quadtree boxes are
+			 * created if a fifth vertex is added to the same box. A Quadtree box is therefore
+			 * composed of EITHER:
+			 * - up to 4 vertices
+			 * - 4 "sub" quadtree boxes*/
+			class BamgQuadtreeBox: public Object{ 
+				public:
+					int nbitems; // number of current vertices in the box
+					union{
+						BamgQuadtreeBox* b[4];
+						BamgVertex*  v[4];
+					};
+					/*Object functions*/
+					void    Echo()       {_error_("not implemented yet"); };
+					void    DeepEcho()   {_error_("not implemented yet"); };
+					int     Id()         {_error_("not implemented yet"); };
+					int     ObjectEnum() {_error_("not implemented yet"); };
+					Object *copy()       {_error_("not implemented yet"); };
+			};
+
+			/*BamgQuadtree private Fields*/
+			DataSet* boxcontainer;
+
+		public:
+
+			/*BamgQuadtree public Fields*/
+			BamgQuadtreeBox* root;
+			long         NbBamgQuadtreeBox;
+			long         NbVertices;
+
+			BamgQuadtree();
+			BamgQuadtree(Mesh *t,long nbv=-1);
+			~BamgQuadtree();
+
+			BamgVertex      *NearestVertex(Icoor1 i,Icoor1 j);
+			BamgQuadtreeBox *NewBamgQuadtreeBox(void);
+			BamgVertex      *ToClose(BamgVertex &,double ,Icoor1,Icoor1);
+			void             Add(BamgVertex &w);
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.cpp	(revision 18231)
@@ -0,0 +1,251 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Methods*/
+	void BamgVertex::Echo(void){/*{{{*/
+
+		_printf_("Vertex:\n");
+		_printf_("  integer   coordinates i.x: " << i.x << ", i.y: " << i.y << "\n");
+		_printf_("  Euclidean coordinates r.x: " << r.x << ", r.y: " << r.y << "\n");
+		_printf_("  ReferenceNumber = " << ReferenceNumber << "\n");
+		m.Echo();
+
+		return;
+	}
+	/*}}}*/
+	int  BamgVertex::GetReferenceNumber() const { /*{{{*/
+		return ReferenceNumber;
+	}
+	/*}}}*/
+	void BamgVertex::MetricFromHessian(const double Hxx,const double Hyx, const double Hyy,const double smin,const double smax,const double s,double err,BamgOpts* bamgopts){/*{{{*/
+		/*Compute Metric from Hessian*/
+
+		/*get options*/
+		double power=(bamgopts->power);
+		double anisomax=(bamgopts->anisomax);
+		double CutOff=bamgopts->cutoff;
+		double hmin=(bamgopts->hmin);
+		double hmax=(bamgopts->hmax);
+		double coef=bamgopts->coeff;
+		int    Metrictype=(bamgopts->Metrictype);
+
+		/*Intermediary*/
+		double ci;
+
+		/*compute multiplicative coefficient depending on Metric Type (2/9 because it is 2d)*/
+
+		//Absolute Error
+		/*
+		 *            2         1       
+		 *Metric M = ---  ------------   Abs(Hessian)
+		 *            9   err * coeff^2  
+		 */
+		if (Metrictype==0){
+			ci= 2.0/9.0 * 1/(err*coef*coef);
+		}
+
+		//Relative Error
+		/*
+		 *            2         1            Abs(Hessian)
+		 *Metric M = ---  ------------  ----------------------
+		 *            9   err * coeff^2  max( |s| , cutoff*max(|s|) )
+		 *
+		 */
+		else if (Metrictype==1){
+			ci= 2.0/9.0 * 1/(err*coef*coef) * 1/Max( Abs(s), CutOff*(Max(Abs(smin),Abs(smax))));
+		}
+
+		//Rescaled absolute error
+		/*
+		 *            2         1            Abs(Hessian)
+		 *Metric M = ---  ------------  ---------------------- 
+		 *            9   err * coeff^2       (smax-smin)
+		 */
+		else if (Metrictype==2){
+			ci= 2.0/9.0 * 1/(err*coef*coef) * 1/(smax-smin);
+		}
+		else{
+			_error_("Metrictype " << Metrictype << " not supported yet (use 0,1 or 2(default))");
+		}
+
+		//initialize metric Miv with ci*H
+		Metric Miv(Hxx*ci,Hyx*ci,Hyy*ci);
+
+		//Get eigen values and vectors of Miv
+		EigenMetric Vp(Miv);
+
+		//move eigen valuse to their absolute values
+		Vp.Abs();
+
+		//Apply a power if requested by user
+		if(power!=1.0) Vp.pow(power);
+
+		//modify eigen values according to hmin and hmax
+		Vp.Maxh(hmax);
+		Vp.Minh(hmin);
+
+		//Bound anisotropy by 1/(anisomax)^2
+		Vp.BoundAniso2(1/(anisomax*anisomax));
+
+		//rebuild Metric from Vp
+		Metric MVp(Vp);
+
+		//Apply Metric to vertex
+		m.IntersectWith(MVp);
+
+	}
+	/*}}}*/
+	long BamgVertex::Optim(int i,int koption){ /*{{{*/
+		long ret=0;
+		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
+			ret = t->Optim(IndexInTriangle,koption);
+			if(!i){
+				t =0; // for no future optime 
+				IndexInTriangle= 0;
+			}
+		}
+		return ret;
+	}
+	/*}}}*/
+	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
+
+		BamgVertex* s=this;
+		BamgVertex &vP = *s,vPsave=vP;
+
+		Triangle* tbegin= t , *tria = t , *ttc;
+
+		int k=0,kk=0,j = EdgesVertexTriangle[IndexInTriangle][0],jc;
+		R2 P(s->r),PNew(0,0);
+		do {
+			k++; 
+
+			if (!tria->Hidden(j)){
+				BamgVertex &vQ = (*tria)[VerticesOfTriangularEdge[j][0]]; 
+
+				R2 Q = vQ,QP(P-Q);
+				double lQP = LengthInterpole(vP,vQ,QP);
+				PNew += Q+QP/Max(lQP,1e-20);
+				kk ++;
+			}
+			ttc =  tria->TriangleAdj(j);
+			jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+			tria = ttc;
+			j = NextEdge[jc];
+			if (k>=2000){
+				_error_("k>=2000 (Maximum number of iterations reached)");
+			}
+		} while ( tbegin != tria); 
+		if (kk<4) return 0;
+		PNew = PNew/(double)kk;
+		R2 Xmove((PNew-P)*omega);
+		PNew = P+Xmove;
+		double delta=Norme2_2(Xmove); 
+
+		Icoor2 deta[3];
+		I2 IBTh  = BTh.R2ToI2(PNew);
+
+		tstart=BTh.TriangleFindFromCoord(IBTh,deta,tstart);  
+
+		if (tstart->det <0){ // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(IBTh,tstart,ba,bb) ;
+			tstart = edge;
+			vP.m= Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));
+		}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			vP.m = Metric(aa,(*tstart)[0],(*tstart)[1],(*tstart)[2]);
+		}
+
+		// recompute the det of the triangle
+		vP.r = PNew;
+
+		vP.i = Th.R2ToI2(PNew);
+
+		BamgVertex vPnew = vP;
+
+		int ok=1;
+		int loop=1;
+		k=0;
+		while (ok){
+			ok =0;
+			do {
+				k++; 
+				double detold = tria->det;
+				tria->det =  bamg::det( (*tria)[0],(*tria)[1]  ,(*tria)[2]);
+				if (loop) {
+					BamgVertex *v0,*v1,*v2,*v3;
+					if (tria->det<0) ok =1;			       
+					else if (tria->Quadrangle(v0,v1,v2,v3))
+					  {
+						vP = vPsave;
+						double qold =QuadQuality(*v0,*v1,*v2,*v3);
+						vP = vPnew;
+						double qnew =QuadQuality(*v0,*v1,*v2,*v3);
+						if (qnew<qold) ok = 1;
+					  }
+					else if ( (double)tria->det < detold/2 ) ok=1;
+
+				}
+				tria->SetUnMarkUnSwap(0);
+				tria->SetUnMarkUnSwap(1);
+				tria->SetUnMarkUnSwap(2);
+				ttc =  tria->TriangleAdj(j);
+				jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+				tria = ttc;
+				j = NextEdge[jc];
+				if (k>=2000){
+					_error_("k>=2000");
+				}
+			}while ( tbegin != tria); 
+
+			if (ok && loop) vP=vPsave; // no move 
+			loop=0;
+		}
+		return delta;
+	}
+	/*}}}*/
+
+	/*Intermediary*/
+	double QuadQuality(const BamgVertex & a,const BamgVertex &b,const BamgVertex &c,const BamgVertex &d) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/QuadQuality)*/
+
+		// calcul de 4 angles --
+		R2 A((R2)a),B((R2)b),C((R2)c),D((R2)d);
+		R2 AB(B-A),BC(C-B),CD(D-C),DA(A-D);
+		//  Move(A),Line(B),Line(C),Line(D),Line(A);
+		const Metric & Ma  = a;
+		const Metric & Mb  = b;
+		const Metric & Mc  = c;
+		const Metric & Md  = d;
+
+		double lAB=Norme2(AB);
+		double lBC=Norme2(BC);
+		double lCD=Norme2(CD);
+		double lDA=Norme2(DA);
+		AB /= lAB;  BC /= lBC;  CD /= lCD;  DA /= lDA;
+		// version aniso 
+		double cosDAB= Ma(DA,AB)/(Ma(DA)*Ma(AB)),sinDAB= Det(DA,AB);
+		double cosABC= Mb(AB,BC)/(Mb(AB)*Mb(BC)),sinABC= Det(AB,BC);
+		double cosBCD= Mc(BC,CD)/(Mc(BC)*Mc(CD)),sinBCD= Det(BC,CD);
+		double cosCDA= Md(CD,DA)/(Md(CD)*Md(DA)),sinCDA= Det(CD,DA);
+		double sinmin=Min(Min(sinDAB,sinABC),Min(sinBCD,sinCDA));
+		if (sinmin<=0) return sinmin;
+		return 1.0-Max(Max(Abs(cosDAB),Abs(cosABC)),Max(Abs(cosBCD),Abs(cosCDA)));
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/BamgVertex.h	(revision 18231)
@@ -0,0 +1,57 @@
+#ifndef _BAMGVERTEX_H_
+#define _BAMGVERTEX_H_
+
+#include "./include.h"
+#include "./Metric.h"
+#include "./Direction.h"
+#include "./BamgOpts.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Mesh;
+	class VertexOnGeom;
+	class VertexOnEdge;
+
+	class BamgVertex {
+
+		public:
+
+			/*Fields*/
+			I2        i;                 // integer coordinates
+			R2        r;                 // real coordinates
+			Metric    m;
+			long      ReferenceNumber;
+			Direction DirOfSearch;
+			short     IndexInTriangle;              // the vertex number in triangle; varies between 0 and 2 in t
+
+			union {
+				Triangle     *t;                      // one triangle which is containing the vertex
+				long          color;
+				BamgVertex   *MeshVertexHook;         // used in geometry BamgVertex to know the Mesh Vertex associated
+				VertexOnGeom *GeomEdgeHook;    // if IndexInTriangle == 8; // set with Mesh::SetVertexFieldOn()
+				BamgVertex   *BackgroundVertexHook;   // if IndexInTriangle == 16 on Background vertex Mesh::SetVertexFieldOnBTh()
+				VertexOnEdge *BackgroundEdgeHook;     // if IndexInTriangle == 32 on Background edge
+			};
+
+			/*Operators*/
+			operator I2() const {return i;}             // Cast operator
+			operator const R2 & () const {return r;}    // Cast operator
+			operator Metric () const {return m;}        // Cast operator
+			double operator()(R2 x) const { return m(x);} // Get x in the metric m
+
+			/*methods (No constructor and no destructors...)*/
+			double Smoothing(Mesh & ,const Mesh & ,Triangle  * & ,double =1);
+			void   MetricFromHessian(const double Hxx,const double Hyx, const double Hyy, const double smin,const double smax,const double s,const double err,BamgOpts* bamgopts);
+			void   Echo();
+			int    GetReferenceNumber() const;
+			long   Optim(int =1,int =0); 
+
+			//inline functions
+			inline void Set(const BamgVertex &rec,const Mesh & ,Mesh & ){*this=rec;}
+	};
+
+	//Intermediary
+	double QuadQuality(const BamgVertex &,const BamgVertex &,const BamgVertex &,const BamgVertex &);
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.cpp	(revision 18231)
@@ -0,0 +1,32 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "CrackedEdge.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	CrackedEdge::CrackedEdge() {/*{{{*/
+		a=NULL;
+		b=NULL;
+		E=NULL;
+		e1=NULL;
+		e2=NULL;
+		indexa[0]=-1;
+		indexa[1]=-1;
+		indexa[2]=-1;
+		indexb[0]=-1;
+		indexb[1]=-1;
+		indexb[2]=-1;
+		length=0;
+		normal.x=0;
+		normal.y=0;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/CrackedEdge.h	(revision 18231)
@@ -0,0 +1,30 @@
+#ifndef _CRACKEDEDGE_H_
+#define _CRACKEDEDGE_H_
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	class Triangle;
+	class GeomEdge;
+	class Edge;
+
+	class CrackedEdge {
+
+		public:
+			Triangle* a;
+			Triangle* b; 
+			GeomEdge* E;
+			Edge* e1;
+			Edge* e2;
+			double length;
+			R2     normal;
+			long   indexa[3];
+			long   indexb[3];
+
+			//Constructors
+			CrackedEdge();
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.cpp	(revision 18231)
@@ -0,0 +1,28 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Curve.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	Curve::Curve(){/*{{{*/
+		FirstEdge=NULL;
+		LastEdge=NULL;
+		FirstVertexIndex=0;
+		LastVertexIndex=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){/*{{{*/
+		*this = rec;
+		FirstEdge = GhNew.edges + Gh.GetId(FirstEdge);    
+		LastEdge = GhNew.edges + Gh.GetId(LastEdge); 
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Curve.h	(revision 18231)
@@ -0,0 +1,25 @@
+#ifndef _CURVE_H_
+#define _CURVE_H_
+
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	class GeomEdge;
+	class Curve;
+	class Geometry;
+
+	class Curve {
+		public:
+			GeomEdge *FirstEdge; //First edge of the curve
+			GeomEdge *LastEdge;  //Last edge of the curve
+			int FirstVertexIndex;       //Last vertex index in the last edge
+			int LastVertexIndex;        //First Vertex index in the first edge
+
+			//Methods
+			Curve();
+			void Set(const Curve & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Direction.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	Direction::Direction():/*{{{*/
+		dir(MaxICoor){
+
+	}/*}}}*/
+	Direction::Direction(Icoor1 i,Icoor1 j) {/*{{{*/
+		Icoor2 n2 = 2*(Abs(i)+Abs(j));  
+		Icoor2 r  = MaxICoor* (Icoor2) i;
+		Icoor1 r1 = (Icoor1) (2*(r/ n2)); // odd number 
+		dir = (j>0) ? r1 : r1+1;          // odd-> j>0 even-> j<0
+	}/*}}}*/
+
+	/*Methods*/
+	int Direction::direction(Icoor1 i,Icoor1 j) {/*{{{*/
+		int r =1; 
+		if (dir!= MaxICoor) {
+			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y((dir%2)?-y1:y1);
+			r = (x*i + y*j) >=0;
+		}
+		return r;
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Direction.h	(revision 18231)
@@ -0,0 +1,20 @@
+#ifndef _DIRECTION_H_
+#define _DIRECTION_H_
+
+#include "./include.h"
+#include "../shared/Bamg/shared.h"
+
+namespace bamg {
+
+	class Direction {
+		private:
+			Icoor1 dir;
+
+		public:
+			//Methods
+			Direction();
+			Direction(Icoor1 i,Icoor1 j);
+			int direction(Icoor1 i,Icoor1 j);
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/DoubleAndInt.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/DoubleAndInt.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/DoubleAndInt.h	(revision 18231)
@@ -0,0 +1,19 @@
+#ifndef _DOUBLEANDINT_H_
+#define _DOUBLEANDINT_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class DoubleAndInt {
+		//class used by Mesh::MakeQuadrangles
+
+		public:
+			double q;
+			long i3j;
+
+			//Operators
+			int operator<(DoubleAndInt a){return q > a.q;}
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Edge.h"
+#include "Mesh.h"
+#include "Geometry.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	void Edge::Set(const Mesh & Th ,long i,Mesh & ThNew){ /*{{{*/
+		*this = Th.edges[i];
+		v[0] = ThNew.vertices + Th.GetId(v[0]);    
+		v[1] = ThNew.vertices + Th.GetId(v[1]);
+		if (GeomEdgeHook) 
+		 GeomEdgeHook =  ThNew.Gh.edges+Th.Gh.GetId(GeomEdgeHook);
+		if (adj[0]) adj[0] =   ThNew.edges +   Th.GetId(adj[0]);
+		if (adj[1]) adj[1] =   ThNew.edges +   Th.GetId(adj[1]);
+	}
+	/*}}}*/
+	void Edge::Echo(void){ /*{{{*/
+		_printf_("Edge:\n");
+		_printf_("   pointers towards two vertices: " << v[0] << " " << v[1] << "\n");
+		_printf_("   ReferenceNumber = " << ReferenceNumber << "\n");
+		_printf_("   GeomEdgeHook = " << GeomEdgeHook << "\n");
+		_printf_("   two adjacent edges on the same curve: " << adj[0] << " " << adj[1] << "\n");
+	}
+	/*}}}*/
+	void Edge::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){/*{{{*/
+
+		if (v[0] >=vb && v[0] <ve) v[0] = vb + renu[v[0]-vb];
+		if (v[1] >=vb && v[1] <ve) v[1] = vb + renu[v[1]-vb];
+
+	}
+	/*}}}*/
+	int Edge::Intersection(const  Edge & e){ /*{{{*/
+
+		/*some shecks*/
+		if (!(adj[0]==&e || adj[1]==&e)){ _error_("Intersection bug"); }
+		_assert_(adj[0]==&e || adj[1]==&e);
+
+		return adj[0]==&e?0:1;
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Edge.h	(revision 18231)
@@ -0,0 +1,34 @@
+#ifndef _EDGE_H_
+#define _EDGE_H_
+
+#include "./BamgVertex.h"
+#include "../shared/shared.h"
+#include "./GeomEdge.h"
+
+namespace bamg {
+
+	class Mesh;
+
+	class Edge {
+
+		public:
+			BamgVertex      *v[2];
+			long             ReferenceNumber;
+			GeomEdge *GeomEdgeHook;
+			Edge            *adj[2];       // the 2 adj edges if on the same curve
+
+			//Operators
+			BamgVertex       &operator[](int i){return *v[i];   };
+			BamgVertex       *operator()(int     i){return v[i];};
+			R2                operator()(double  t) const;// return the point
+			const BamgVertex &operator[](int i) const{return *v[i];};
+
+			//Methods
+			void Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			int  Intersection(const  Edge & e);
+			void Set(const Mesh &,long,Mesh &);
+			void Echo(void);
+
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/EigenMetric.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/EigenMetric.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/EigenMetric.cpp	(revision 18231)
@@ -0,0 +1,142 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Metric.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructor*/
+	EigenMetric::EigenMetric(const Metric& M){/*{{{*/
+		/*From a metric (a11,a21,a22), get eigen values lambda1 and lambda2 and one eigen vector v*/
+
+		/*Intermediaries*/
+		double a11=M.a11,a21=M.a21,a22=M.a22;
+		double normM;
+		double delta,b;
+
+		/*To get the eigen values, we must solve the following equation:
+		 *     | a11 - lambda    a21        |
+		 * det |                            | = 0
+		 *     | a21             a22-lambda |
+		 *
+		 * We have to solve the following polynom:
+		 *  lamda^2 + ( -a11 -a22)*lambda + (a11*a22-a21*a21) = 0*/
+
+		/*Compute polynom determinant*/
+		b=-a11-a22;
+		delta=b*b - 4*(a11*a22-a21*a21);
+
+		/*Compute norm of M to avoid round off errors*/
+		normM=a11*a11 + a22*a22 + a21*a21;
+
+		/*1: normM too small: eigen values = 0*/
+		if(normM<1.e-30){
+			lambda1=0;
+			lambda2=0;
+			v.x=1;
+			v.y=0;
+		}
+		/*2: delta is small -> double root*/
+		else if (delta < 1.e-5*normM){
+			lambda1=-b/2;
+			lambda2=-b/2;
+			v.x=1;
+			v.y=0;
+		}
+		/*3: general case -> two roots*/
+		else{
+			delta     = sqrt(delta);
+			lambda1   = (-b-delta)/2.0;
+			lambda2   = (-b+delta)/2.0;
+
+			/*Now, one must find the eigen vectors. For that we use the following property of the inner product
+			 *    <Ax,y> = <x,tAy>
+			 * Here, M'(M-lambda*Id) is symmetrical, which gives:
+			 *    ∀(x,y)∈R²xR² <M'x,y> = <M'y,x>
+			 * And we have the following:
+			 *    if y∈Ker(M'), ∀x∈R² <M'x,y> = <x,M'y> = 0
+			 * We have shown that
+			 *    Im(M') ⊥ Ker(M')
+			 *
+			 * To find the eigen vectors of M, we only have to find two vectors
+			 * of the image of M' and take their perpendicular as long as they are
+			 * not 0.
+			 * To do that, we take the images (1,0) and (0,1):
+			 *  x1 = (a11 - lambda)      x2 = a21
+			 *  y1 = a21                 y2 = (a22-lambda)
+			 *
+			 * We take the vector that has the larger norm and take its perpendicular.*/
+
+			double norm1 = (a11-lambda1)*(a11-lambda1) + a21*a21; 
+			double norm2 = a21*a21 + (a22-lambda1)*(a22-lambda1);
+
+			if (norm2<norm1){
+				norm1=sqrt(norm1);
+				v.x = - a21/norm1;
+				v.y = (a11-lambda1)/norm1;
+			}
+			else{
+				norm2=sqrt(norm2);
+				v.x = - (a22-lambda1)/norm2;
+				v.y = a21/norm2;
+			}
+		}
+
+	}
+	/*}}}*/
+	EigenMetric::EigenMetric(double r1,double r2,const D2& vp1): lambda1(r1),lambda2(r2),v(vp1){/*{{{*/
+
+	}/*}}}*/
+
+	/*Methods*/
+	void   EigenMetric::Abs(){/*{{{*/
+		lambda1=bamg::Abs(lambda1),lambda2=bamg::Abs(lambda2);
+	}/*}}}*/
+	double EigenMetric::Aniso2() const  { /*{{{*/
+		return lmax()/lmin();
+	}/*}}}*/
+	void EigenMetric::Echo(void){/*{{{*/
+
+		_printf_("EigenMetric:\n");
+		_printf_("   lambda1: " << lambda1 << "\n");
+		_printf_("   lambda2: " << lambda2 << "\n");
+		_printf_("   v.x: " << v.x << "\n");
+		_printf_("   v.y: " << v.y << "\n");
+
+		return;
+	}
+	/*}}}*/
+	double EigenMetric::hmin() const {/*{{{*/
+		return sqrt(1/bamg::Max3(lambda1,lambda2,1e-30));
+	}/*}}}*/
+	double EigenMetric::hmax() const {/*{{{*/
+		return sqrt(1/bamg::Max(bamg::Min(lambda1,lambda2),1e-30));
+	}/*}}}*/
+	double EigenMetric::lmax() const {/*{{{*/
+		return bamg::Max3(lambda1,lambda2,1e-30);
+	}/*}}}*/
+	double EigenMetric::lmin() const {/*{{{*/
+		return bamg::Max(bamg::Min(lambda1,lambda2),1e-30);
+	}/*}}}*/
+	void   EigenMetric::Min(double a) { /*{{{*/
+		lambda1=bamg::Min(a,lambda1); lambda2=bamg::Min(a,lambda2) ;
+	}/*}}}*/
+	void   EigenMetric::Max(double a) { /*{{{*/
+		//change eigen values
+		lambda1=bamg::Max(a,lambda1); lambda2=bamg::Max(a,lambda2) ;
+	}/*}}}*/
+	void   EigenMetric::Minh(double h) {/*{{{*/
+		Min(1.0/(h*h));
+	}/*}}}*/
+	void   EigenMetric::Maxh(double h) {/*{{{*/
+		//Call Max function
+		Max(1.0/(h*h));
+	}/*}}}*/
+	void   EigenMetric::pow(double p){/*{{{*/
+		lambda1=::pow(lambda1,p);lambda2=::pow(lambda2,p);
+	}/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.cpp	(revision 18231)
@@ -0,0 +1,171 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "../shared/shared.h"
+
+#include "GeomEdge.h"
+#include "Geometry.h"
+
+using namespace std;
+
+namespace bamg {
+
+	/*Constructor/Destructor*/
+
+	/*Methods*/
+	int    GeomEdge::Cracked() const  {/*{{{*/
+		return type &1;  
+	}/*}}}*/
+	R2 GeomEdge::F(double theta) const{/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/F)*/
+		// parametrization of the curve edge
+
+	   R2 A=v[0]->r,B=v[1]->r;
+		double ca,cb,cta,ctb;
+
+		//Check that theta is in [0 1]
+		_assert_(theta>-1e-12 && theta<1+1e-12);
+
+		if (TgA()){ 
+			if (TgB()){ //Hermite interpolation
+				cb =  theta*theta*(3-2*theta);
+				ca =  1-cb;     
+				cta = (1-theta)*(1-theta)*theta;
+				ctb = (theta-1)*theta*theta ;
+			}
+			else {
+				double t = theta;
+				cb = t*t;
+				ca = 1-cb;
+				cta= t-cb;
+				ctb=0;    
+			}
+		}
+		else{
+			if (TgB()){
+				double t = 1-theta;
+				ca = t*t;
+				cb = 1-ca;
+				ctb= -t+ca;
+				cta=0;    
+			}
+			else { // lagrange P1
+				ca =(1-theta);
+				cb = theta;
+				cta=ctb=0;
+			}
+		}
+		return A*ca + B*cb + tg[0]*cta + tg[1]*ctb;
+	  }
+	/*}}}*/
+	int    GeomEdge::Mark()    const  {/*{{{*/
+		return type &16; 
+	}/*}}}*/
+	double GeomEdge::R1tg(double theta,R2 & t) const{/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/R1tg)*/
+		// 1/R of radius of cuvature
+
+		R2 A=v[0]->r,B=v[1]->r;
+		double dca,dcb,dcta,dctb;
+		double ddca,ddcb,ddcta,ddctb;
+		double tt = theta*theta;
+
+		//check theta
+		_assert_(theta>=0 && theta<=1);
+
+		if (TgA()){ 
+			if (TgB()){
+				// Tangent A and B provided:
+				// interpolation d'hermite
+				dcb = 6*theta*(1-theta);
+				ddcb = 6*(1-2*theta);
+				dca = -dcb;
+				ddca = -ddcb;
+				dcta =  (3*theta - 4)*theta + 1;
+				ddcta=6*theta-4;
+				dctb = 3*tt - 2*theta;
+				ddctb = 6*theta-2;
+			}
+			else {
+				//Tangent A provided but tangent B not provided
+				// 1-t*t, t-t*t, t*t
+				double t = theta;
+				dcb = 2*t;
+				ddcb = 2;
+				dca = -dcb;
+				ddca = -2;
+				dcta = 1-dcb;
+				ddcta = -ddcb;
+				dctb=0;    
+				ddctb=0;    
+			}
+		}
+		else{
+			if (TgB()){
+				//Tangent B provided but tangent A not provided
+				double t = 1-theta;
+				dca = -2*t;
+				ddca = 2;
+				dcb = -dca;
+				ddcb = -2;
+				dctb = 1+dca;
+				ddctb= ddca;
+				dcta =0;
+				ddcta =0;
+			}
+			else {
+				//Neither thangent A nor tangent B provided
+				// lagrange P1
+				t=B-A;
+				return 0;
+			} 
+		}
+		R2 d  =  A*dca  + B*dcb  + tg[0]* dcta  + tg[1] * dctb;
+		R2 dd =  A*ddca + B*ddcb + tg[0]* ddcta + tg[1] * ddctb;
+		double d2=(d,d);
+		double sd2 = sqrt(d2);
+		t=d;
+		if(d2>1.0e-20){
+			t/=sd2;
+			return Abs(Det(d,dd))/(d2*sd2);
+		}
+		else return 0;
+	}
+	/*}}}*/
+	int    GeomEdge::Required()       {/*{{{*/
+		return type &64; 
+	}/*}}}*/
+	void GeomEdge::Set(const GeomEdge & rec,const Geometry & Gh ,Geometry & GhNew){ /*{{{*/
+		*this = rec;
+		v[0] = GhNew.vertices + Gh.GetId(v[0]);    
+		v[1] = GhNew.vertices + Gh.GetId(v[1]); 
+		if (Adj[0]) Adj[0] =  GhNew.edges + Gh.GetId(Adj[0]);     
+		if (Adj[1]) Adj[1] =  GhNew.edges + Gh.GetId(Adj[1]);     
+	}
+	/*}}}*/
+	void   GeomEdge::SetCracked()     { /*{{{*/
+		type |= 1;/*=>1st digit to 1*/
+	}/*}}}*/
+	void   GeomEdge::SetTgA()         { /*{{{*/
+		type |=4; /*=>2d digit to 1*/
+	}/*}}}*/
+	void   GeomEdge::SetTgB()         { /*{{{*/
+		type |=8; /*=> 3d digit to 1*/
+	}/*}}}*/
+	void   GeomEdge::SetMark()        { /*{{{*/
+		type |=16;/*=> 4th digiy to 1*/
+	}/*}}}*/
+	void   GeomEdge::SetUnMark()      { /*{{{*/
+		type &= 1007 /* 1023-16 = 000111110111 => 4th digit to 0*/;
+	}/*}}}*/
+	void   GeomEdge::SetRequired()    { /*{{{*/
+		type |= 64;/*=>6th digit to 1*/ 
+	}/*}}}*/
+	int    GeomEdge::TgA()     const  {/*{{{*/
+		return type &4;  
+	}/*}}}*/
+	int    GeomEdge::TgB()     const  {/*{{{*/
+		return type &8;  
+	}/*}}}*/
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomEdge.h	(revision 18231)
@@ -0,0 +1,45 @@
+#ifndef _GEOMETRICALEDGE_H_
+#define _GEOMETRICALEDGE_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class GeomVertex;
+	class Geometry;
+
+	class GeomEdge {
+
+		public:
+			GeomVertex *v[2];
+			long               ReferenceNumber;
+			long               CurveNumber;
+			R2                 tg[2];              // the 2 tangentes (tg[0] =0 => no continuity)
+			GeomEdge   *Adj[2];
+			int                AdjVertexIndex[2]; // for a given vertex, this gives the index of the vertex in the adjacent edge (0 or 1)
+			int                type;
+
+			//Operators
+			GeomVertex       & operator[](int i){return *v[i];};
+			const GeomVertex & operator[](int i) const { return *v[i];};
+			GeomVertex       * operator()(int i){return v[i];};  
+
+			//Methods
+			R2     F(double theta) const ; // parametrization of the curve edge
+			double R1tg(double theta,R2 &t) const ; // 1/radius of curvature + tangente
+			int    Cracked() const;
+			int    TgA()     const;
+			int    TgB()     const;
+			int    Mark()    const;
+			int    Required();
+			void   SetCracked();
+			void   SetTgA();
+			void   SetTgB();
+			void   SetMark();
+			void   SetUnMark();
+			void   SetRequired();
+			void   Set(const GeomEdge & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.cpp	(revision 18231)
@@ -0,0 +1,19 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomSubDomain.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){/*{{{*/
+		*this = rec;
+		edge = Gh.GetId(edge) + GhNew.edges;
+	}/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomSubDomain.h	(revision 18231)
@@ -0,0 +1,22 @@
+#ifndef _GEOMETRICALSUBDOMAIN_H_
+#define _GEOMETRICALSUBDOMAIN_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class GeomEdge;
+	class Geometry;
+
+	class GeomSubDomain {
+		public:
+			GeomEdge *edge;
+			int              direction;   // -1 or 1
+			long             ReferenceNumber;
+
+			//Methods
+			void Set(const GeomSubDomain &,const Geometry & ,const Geometry &);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomVertex.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	int  GeomVertex::Corner() const {/*{{{*/
+		return type & 4;
+	}
+	/*}}}*/
+	int  GeomVertex::Required()const {/*{{{*/
+		// a corner is required
+		return type & 6;
+	}
+	/*}}}*/
+	void GeomVertex::SetCorner(){/*{{{*/
+		type |= 4;
+	}
+	/*}}}*/
+	void GeomVertex::SetRequired(){/*{{{*/
+		type |= 2;
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/GeomVertex.h	(revision 18231)
@@ -0,0 +1,30 @@
+#ifndef _GEOMETRICALVERTEX_H_
+#define _GEOMETRICALVERTEX_H_
+
+#include "./include.h"
+#include "BamgVertex.h"
+
+namespace bamg {
+
+	class Geometry;
+
+	class GeomVertex : public BamgVertex { 
+
+		public:
+			friend class Geometry;
+
+			int type;
+
+			//Constructors
+			GeomVertex():type(0){};
+
+			//Methods
+			int  Corner() const;
+			int  Required()const;
+			void SetCorner();
+			void SetRequired();
+
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.cpp	(revision 18231)
@@ -0,0 +1,918 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	Geometry::Geometry(){/*{{{*/
+		Init();
+	}
+	/*}}}*/
+	Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){/*{{{*/
+		Init();
+		ReadGeometry(bamggeom,bamgopts);
+		PostRead();
+	}
+	/*}}}*/
+	Geometry::Geometry(const Geometry & Gh) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Geometry)*/
+
+		long i;
+		*this = Gh;
+		NbRef =0;
+		quadtree=0;
+		vertices = nbv ? new GeomVertex[nbv] : NULL;
+		edges = nbe ? new GeomEdge[nbe]:NULL;
+		curves= nbcurves ? new Curve[nbcurves]:NULL;
+		subdomains = nbsubdomains ? new GeomSubDomain[nbsubdomains]:NULL;
+		for (i=0;i<nbe;i++)
+		 edges[i].Set(Gh.edges[i],Gh,*this);
+		for (i=0;i<nbcurves;i++)
+		 curves[i].Set(Gh.curves[i],Gh,*this);
+		for (i=0;i<nbsubdomains;i++)
+		 subdomains[i].Set(Gh.subdomains[i],Gh,*this);
+	}
+	/*}}}*/
+	Geometry::~Geometry() {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/~Geometry)*/
+		if(NbRef>0){   _printf_("Trying to delete geometry and NbRef>0, probably due to an error"); return;}
+		if(vertices)   delete [] vertices;  vertices=0;
+		if(edges)      delete [] edges;     edges=0;
+		if(quadtree)   delete    quadtree;  quadtree=0;
+		if(curves)     delete [] curves;    curves=0;nbcurves=0;
+		if(subdomains) delete [] subdomains;subdomains=0;
+		Init();
+	}
+	/*}}}*/
+
+	/*IO*/
+	void Geometry::ReadGeometry(BamgGeom* bamggeom,BamgOpts* bamgopts){/*{{{*/
+
+		int verbose;
+		nbcurves=0;
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		int i,j,n,i0,i1,i2,i3;
+
+		/*initialize some variables*/
+		verbose= bamgopts->verbose;
+		nbv    = bamggeom->VerticesSize[0];
+		nbe    = bamggeom->EdgesSize[0];
+
+		//some checks
+		if (bamggeom->Vertices==NULL) _error_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error_("the domain provided does not contain any edge");
+
+		//Vertices
+		if (bamggeom->Vertices){
+			if(verbose>5) _printf_("      processing Vertices\n");
+			if (bamggeom->VerticesSize[1]!=3) _error_("Vertices should have 3 columns");
+			vertices = new GeomVertex[nbv];
+			for (i=0;i<nbv;i++) {
+				vertices[i].r.x=(double)bamggeom->Vertices[i*3+0];
+				vertices[i].r.y=(double)bamggeom->Vertices[i*3+1];
+				vertices[i].ReferenceNumber=(long)bamggeom->Vertices[i*3+2];
+				vertices[i].DirOfSearch=NoDirOfSearch;
+				vertices[i].color =0;
+				vertices[i].type=0;
+			}
+			/*find domain extrema (pmin,pmax) that will define the square box used for by the quadtree*/
+			pmin =  vertices[0].r;
+			pmax =  vertices[0].r;
+			for (i=0;i<nbv;i++) {
+				pmin.x = Min(pmin.x,vertices[i].r.x);
+				pmin.y = Min(pmin.y,vertices[i].r.y);
+				pmax.x = Max(pmax.x,vertices[i].r.x);
+				pmax.y = Max(pmax.y,vertices[i].r.y);
+			}
+			/*Offset pmin and pmax to avoid round-off errors*/
+			R2 offset = (pmax-pmin)*0.05;
+			pmin -= offset;
+			pmax += offset;
+			/*coefIcoor is the coefficient used for integer coordinates:
+			 *                       (x-pmin.x)
+			 * Icoor x = (2^30 -1) ------------ 
+			 *                          D
+			 * where D is the longest side of the domain (direction x or y)
+			 * so that (x-pmin.x)/D is in ]0 1[
+			 *
+			 * coefIcoor = (2^30 -1)/D
+			 */
+			coefIcoor=(MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+			if(coefIcoor<=0) _error_("coefIcoor should be positive");
+		}
+		else{
+			_error_("No BamgVertex provided");
+		}
+
+		//Edges
+		if (bamggeom->Edges){
+			R2      zerovector(0,0);
+			double* verticeslength=NULL;
+
+			if(verbose>5) _printf_("      processing Edges\n");
+			if (bamggeom->EdgesSize[1]!=3) _error_("Edges should have 3 columns");
+			edges = new GeomEdge[nbe];
+
+			//initialize verticeslength (sum of the lengths of the edges holding vertex)
+			verticeslength = new double[nbv];
+			for(i=0;i<nbv;i++) verticeslength[i]=0;
+
+			/*Loop over the edges*/
+			for (i=0;i<nbe;i++){
+
+				i1=(int)bamggeom->Edges[i*3+0]-1; //-1 for C indexing
+				i2=(int)bamggeom->Edges[i*3+1]-1; //-1 for C indexing
+				edges[i].v[0]= vertices + i1;     //pointer toward vertex i1 (=&vertices[i1])
+				edges[i].v[1]= vertices + i2;     //pointer toward vertex i2
+				edges[i].ReferenceNumber=(long)bamggeom->Edges[i*3+2];
+
+				//get length of edge
+				R2     x12=vertices[i2].r-vertices[i1].r;
+				double l12=sqrt((x12,x12));
+				Hmin=Min(Hmin,l12);
+
+				//initialize other fields
+				edges[i].tg[0]=zerovector;
+				edges[i].tg[1]=zerovector;
+				edges[i].AdjVertexIndex[0] = edges[i].AdjVertexIndex[1] = -1;
+				edges[i].Adj[0] = edges[i].Adj[1] = NULL;
+				edges[i].type = 0;
+
+				//Cracked?
+				if (edges[i].ReferenceNumber!=1) edges[i].SetCracked();
+
+				//prepare metric
+				vertices[i1].color++;
+				vertices[i2].color++;
+				verticeslength[i1] += l12;
+				verticeslength[i2] += l12;
+			}
+
+			// definition the default of the given mesh size 
+			for (i=0;i<nbv;i++) {
+				if (vertices[i].color > 0) 
+				 vertices[i].m=Metric(verticeslength[i] /(double) vertices[i].color);
+				else 
+				 vertices[i].m=Metric(Hmin);
+			}
+			delete [] verticeslength;
+
+		}
+		else{
+			_error_("No edges provided");
+		}
+
+		//hVertices
+		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==nbv){
+			if(verbose>5) _printf_("      processing hVertices\n");
+			for (i=0;i< nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
+					vertices[i].m=Metric((double)bamgopts->hVertices[i]);
+				}
+			}
+		}
+
+		//MetricVertices
+		if(bamgopts->metric && bamgopts->metric[0]==nbv){
+			if(verbose>5) _printf_("      processing MetricVertices\n");
+			for (i=0;i< nbv;i++) {
+				vertices[i].m = Metric((double)bamgopts->metric[i*3+0],(double)bamgopts->metric[i*3+1],(double)bamgopts->metric[i*3+2]);
+			}
+		}
+
+		//MaxCornerAngle
+		if (bamgopts->MaxCornerAngle){
+			if(verbose>5) _printf_("      processing MaxCornerAngle\n");
+			MaxCornerAngle=bamgopts->MaxCornerAngle*Pi/180;
+		}
+
+		//TangentAtEdges
+		if (bamggeom->TangentAtEdges){
+			if(verbose>5) _printf_("      processing TangentAtEdges");
+			if (bamggeom->TangentAtEdgesSize[1]!=4) _error_("TangentAtEdges should have 4 columns");
+			int n,i,j,k;
+			R2 tg;
+
+			n=bamggeom->TangentAtEdgesSize[0];
+			for (k=0;k<n;k++) {
+				i=(int)bamggeom->TangentAtEdges[k*4+0]-1; //for C indexing
+				j=(int)bamggeom->TangentAtEdges[k*4+1]-1; //for C indexing
+				tg.x=bamggeom->TangentAtEdges[k*4+2];
+				tg.y=bamggeom->TangentAtEdges[k*4+3];
+				if (i<0 || i>=nbe) _error_("TangentAtEdges first index exceeds matrix dimension");
+				if (j!=0 && j!=1)  _error_("TangentAtEdges second index should be 1 or 2 only");
+				edges[i].tg[j] = tg;
+			}
+		}
+
+		//Corners
+		if(bamggeom->Corners){
+			if(verbose>5) _printf_("      processing Corners");
+			if (bamggeom->CornersSize[1]!=1) _error_("Corners should have 1 column");
+			n=bamggeom->CornersSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->Corners[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad corner definition: should in [0 " << nbv << "]");
+				/*Required => at the same time SetRequired and SetCorner*/
+				vertices[j].SetCorner();
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredVertices
+		if(bamggeom->RequiredVertices){
+			if(verbose>5) _printf_("      processing RequiredVertices\n");
+			if (bamggeom->RequiredVerticesSize[1]!=1) _error_("RequiredVertices should have 1 column");
+			n=bamggeom->RequiredVerticesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredVertices[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredEdges
+		if(bamggeom->RequiredEdges){
+			if(verbose>5) _printf_("      processing RequiredEdges\n");
+			if (bamggeom->RequiredEdgesSize[1]!=1) _error_("RequiredEdges should have 1 column");
+			n=bamggeom->RequiredEdgesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredEdges[i]-1; //for C indexing
+				if (j>nbe-1 || j<0) _error_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
+				edges[j].SetRequired();  
+			}
+		}
+
+		//SubDomain
+		if(bamggeom->SubDomains){
+			if(verbose>5) _printf_("      processing SubDomains\n");
+			if (bamggeom->SubDomainsSize[1]!=4) _error_("SubDomains should have 4 columns");
+			nbsubdomains=bamggeom->SubDomainsSize[0];
+			subdomains = new GeomSubDomain[nbsubdomains];
+			for (i=0;i<nbsubdomains;i++){
+				i0=(int)bamggeom->SubDomains[i*4+0];
+				i1=(int)bamggeom->SubDomains[i*4+1];
+				i2=(int)bamggeom->SubDomains[i*4+2];
+				i3=(int)bamggeom->SubDomains[i*4+3];
+				if (i0!=2) _error_("Bad Subdomain definition: first number should be 2 (for Edges)");
+				if (i1>nbe || i1<=0) _error_("Bad Subdomain definition: second number should in [1 " << nbe << "] (edge number)");
+				subdomains[i].edge=edges + (i1-1);
+				subdomains[i].direction = (int) i2;
+				subdomains[i].ReferenceNumber = i3;
+			}
+		}
+	}
+	/*}}}*/
+	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){/*{{{*/
+
+		int verbose;
+		int nbreq=0;
+		int nbreqv=0;
+		int nbtan=0;
+		int i,count;
+
+		/*Get options*/
+		verbose=bamgopts->verbose;
+
+		/*Vertices*/
+		if(verbose>5) _printf_("      writing Vertices\n");
+		bamggeom->VerticesSize[0]=nbv;
+		bamggeom->VerticesSize[1]=3;
+		if (nbv){
+			bamggeom->Vertices=xNew<double>(3*nbv);
+			for (i=0;i<nbv;i++){
+				bamggeom->Vertices[i*3+0]=vertices[i].r.x;
+				bamggeom->Vertices[i*3+1]=vertices[i].r.y;
+				bamggeom->Vertices[i*3+2]=vertices[i].GetReferenceNumber();
+
+				//update counters
+				if (vertices[i].Required()) nbreqv++;
+			}
+		}
+
+		/*Edges*/
+		if(verbose>5) _printf_("      writing Edges\n");
+		bamggeom->EdgesSize[0]=nbe;
+		bamggeom->EdgesSize[1]=3;
+		if (nbe){
+			bamggeom->Edges=xNew<double>(3*nbe);
+			for (i=0;i<nbe;i++){
+				bamggeom->Edges[i*3+0]=GetId(edges[i][0])+1; //back to Matlab indexing
+				bamggeom->Edges[i*3+1]=GetId(edges[i][1])+1; //back to Matlab indexing
+				bamggeom->Edges[i*3+2]=(double)edges[i].ReferenceNumber;
+
+				//update counters
+				if (edges[i].Required()) nbreq++;
+				if (edges[i].TgA() && edges[i][0].Corner()) nbtan++;
+				if (edges[i].TgB() && edges[i][1].Corner()) nbtan++;
+			}
+		}
+
+		/*RequiredEdges*/
+		if(verbose>5) _printf_("      writing " << nbreq << " RequiredEdges\n");
+		bamggeom->RequiredEdgesSize[0]=nbreq;
+		bamggeom->RequiredEdgesSize[1]=1;
+		if (nbreq){
+			bamggeom->RequiredEdges=xNew<double>(1*nbreq);
+			count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].Required()){
+					bamggeom->RequiredEdges[count]=i+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		//No corners
+
+		/*RequiredVertices*/
+		if(verbose>5) _printf_("      writing " << nbreqv << " RequiredVertices\n");
+		bamggeom->RequiredVerticesSize[0]=nbreqv;
+		bamggeom->RequiredVerticesSize[1]=1;
+		if (nbreqv){
+			bamggeom->RequiredVertices=xNew<double>(1*nbreqv);
+			count=0;
+			for (i=0;i<nbv;i++){
+				if (vertices[i].Required()){
+					bamggeom->RequiredVertices[count]=i+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		/*SubDomains*/
+		if(verbose>5) _printf_("      writing SubDomains\n");
+		bamggeom->SubDomainsSize[0]=nbsubdomains;
+		bamggeom->SubDomainsSize[1]=4;
+		if (nbsubdomains){
+			bamggeom->SubDomains=xNew<double>(4*nbsubdomains);
+			for (i=0;i<nbsubdomains;i++){
+				bamggeom->SubDomains[4*i+0]=2;
+				bamggeom->SubDomains[4*i+1]=GetId(subdomains[i].edge)+1; //back to Matlab indexing
+				bamggeom->SubDomains[4*i+2]=subdomains[i].direction;
+				bamggeom->SubDomains[4*i+3]=subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*TangentAtEdges*/
+		if(verbose>5) _printf_("      writing TangentAtEdges\n");
+		bamggeom->TangentAtEdgesSize[0]=nbtan;
+		bamggeom->TangentAtEdgesSize[1]=4;
+		if (nbtan){
+			bamggeom->TangentAtEdges=xNew<double>(4*nbtan);
+			for (i=0;i<nbe;i++){
+				if (edges[i].TgA() && edges[i][0].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=1;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[0].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[0].y;
+				}
+				if (edges[i].TgB() && edges[i][1].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=2;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[1].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[1].y;
+				}
+			}
+		}
+	}
+	/*}}}*/
+
+	/*Methods*/
+	void Geometry::Echo(void){/*{{{*/
+
+		_printf_("Geometry:\n");
+		_printf_("   nbv  (number of vertices) : " << nbv << "\n");
+		_printf_("   nbe  (number of edges)    : " << nbe << "\n");
+		_printf_("   nbsubdomains: " << nbsubdomains << "\n");
+		_printf_("   nbcurves: " << nbcurves << "\n");
+		_printf_("   vertices: " << vertices << "\n");
+		_printf_("   edges: " << edges << "\n");
+		_printf_("   quadtree: " << quadtree << "\n");
+		_printf_("   subdomains: " << subdomains << "\n");
+		_printf_("   curves: " << curves << "\n");
+		_printf_("   pmin (x,y): (" << pmin.x << " " << pmin.y << ")\n");
+		_printf_("   pmax (x,y): (" << pmax.x << " " << pmax.y << ")\n");
+		_printf_("   coefIcoor: " << coefIcoor << "\n");
+		_printf_("   MaxCornerAngle: " << MaxCornerAngle << "\n");
+
+		return;
+	}
+	/*}}}*/
+	void Geometry::Init(void){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/EmptyGeometry)*/
+
+		NbRef=0;
+		nbv=0;
+		nbe=0;
+		quadtree=NULL;
+		curves=NULL;
+		edges=NULL;
+		vertices=NULL;
+		nbsubdomains=0;
+		nbcurves=0;
+		subdomains=NULL;
+		MaxCornerAngle = 10*Pi/180; //default is 10 degres
+	}
+	/*}}}*/
+	double Geometry::MinimalHmin() {/*{{{*/
+		/* coeffIcoor = (2^30-1)/D
+		 * We cannot go beyond hmin = D/2^30 because of the quadtree
+		 * hmin is therefore approximately 2/coeffIcoor */
+		return 2.0/coefIcoor;
+	}/*}}}*/
+	double Geometry::MaximalHmax() {/*{{{*/
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}/*}}}*/
+	long Geometry::GetId(const GeomVertex & t) const  {/*{{{*/
+		return &t - vertices;
+	}/*}}}*/
+	long Geometry::GetId(const GeomVertex * t) const  {/*{{{*/
+		return t - vertices;
+	}/*}}}*/
+	long Geometry::GetId(const GeomEdge & t) const  {/*{{{*/
+		return &t - edges;
+	}/*}}}*/
+	long Geometry::GetId(const GeomEdge * t) const  {/*{{{*/
+		return t - edges;
+	}/*}}}*/
+	long Geometry::GetId(const Curve * c) const  {/*{{{*/
+		return c - curves;
+	}/*}}}*/
+	void Geometry::PostRead(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
+
+		long          i          ,j,k;
+		long         *head_v   = new long[nbv];
+		long         *next_p   = new long[2 *nbe];
+		float        *eangle   = new float[nbe];
+		double        eps      = 1e-20;
+		BamgQuadtree  quadtree;                            // build quadtree to find duplicates
+
+		k=0;
+
+		//build quadtree for this geometry
+		for (i=0;i<nbv;i++){
+
+			/*build integer coordinates (non unique)
+			  these coordinates are used by the quadtree to group
+			  the vertices by groups of 5:
+			  All the coordinates are transformed to ]0,1[^2
+			  then, the integer coordinates are computed using 
+			  the transformation ]0,1[^2 -> [0 2^30-1[^2 for a quadtree of depth 30*/
+			vertices[i].i=R2ToI2(vertices[i].r); 
+
+			/*find nearest vertex already present in the quadtree (NULL if empty)*/
+			BamgVertex* v=quadtree.NearestVertex(vertices[i].i.x,vertices[i].i.y); 
+
+			/*if there is a vertex found that is to close to vertices[i] -> error*/
+			if( v && Norme1(v->r - vertices[i].r) < eps ){
+				_printf_("reference numbers: " << v->ReferenceNumber << " " << vertices[i].ReferenceNumber << "\n");
+				_printf_("Id: " << i+1 << "\n");
+				_printf_("Coords: ["<<v->r.x<<" "<<v->r.y<<"] ["<<vertices[i].r.x<<" "<<vertices[i].r.y<<"]\n");
+
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("two points of the geometry are very closed to each other (see reference numbers above)");
+			}
+
+			/*Add vertices[i] to the quadtree*/
+			quadtree.Add(vertices[i]);
+		}
+
+		/* Here we use a powerful chaining algorithm
+		 *
+		 * 1. What is a chaining algorithm?
+		 *
+		 * If F is a function that goes from i in [0 n] to j in [0 m]
+		 * and we want to compute the reciprocal function F-1 of F
+		 * (what are the antecedents of a given j in Im(F) )
+		 * We use 2 lists:
+		 *    head_F[j] that holds the head of lists
+		 *    next_F[i] that holds the list of elements that have the same image
+		 *
+		 * Example:
+		 *    i1, i2, ..., ip in [0,n] are all antecedents of a given j in [0 m]
+		 *    head_F[j] = ip
+		 *    next_F[ip]= ip-1
+		 *    ....
+		 *    next_F[i2]= i1
+		 *    next_F[i1]= -1  //end of the list
+		 *
+		 * Algorithm:
+		 *    for(j=0;j<m;j++)  head_F[j] = -1 //initialization
+		 *    for(i=0;i<n;i++){
+		 *       j=F[i];
+		 *       next_F[i]= head_F[j];
+		 *       head_F[j]=i;
+		 *    }
+		 * 
+		 *    Then, we can go through all the elements that have for image j:
+		 *    for(i=head_F[j]; i!=-1; i=next_F[i])
+		 *    initialization of i by i=head_F[j]
+		 *    stop the loop when i=-1 (end of the chain)
+		 *    iterate using i=next_F[i] (next element that have for image j)
+		 * 
+		 * 2. How to use this algorithm here?
+		 * 
+		 * Here F is a function that associates two vertices v0 and v1 for a given edge E
+		 * We want to build the reciprocal function: what are the edges that contains
+		 * a vertex v?
+		 * To do so, we use the same chaining algorithm but there is a difficulty
+		 * coming from the fact that for F we have a couple of vertices and not one 
+		 * vertex.
+		 * To overcome this difficulty, we use a global indexing exactly like in 
+		 * C/C++ so that
+		 * a member of a 2-column-table can be described by one index p=i*2+j
+		 * i=(int)p/2 line number of p
+		 * j=p%2      column number of p
+		 *
+		 * Algorithm:
+		 *    for(i=0;i<nbv;i++)  head_v[i] = -1 //initialization
+		 *    for(i=0;i<nbe;i++){
+		 *       for(j=0;j<2;j++){
+		 *          p=2*i+j;
+		 *          v=edges(i,j);
+		 *          next_p[p]= head_v[v];
+		 *          head_v[v]=p;
+		 *       }
+		 *    }
+		 */
+
+		//initialize head_v as -1
+		for (i=0;i<nbv;i++) head_v[i]=-1;
+		k=0;
+		for (i=0;i<nbe;i++) {
+			//compute vector of edge i that goes from vertex 0 to vertex 1
+			R2 v10=edges[i].v[1]->r - edges[i].v[0]->r;
+			double lv10=Norme2(v10);
+			//check that its length is not 0
+			if(lv10==0){
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("Length of edge " << i << " is 0");
+			}
+			//compute angle in [-Pi Pi]
+			eangle[i] = atan2(v10.y,v10.x);
+			//build chains head_v and next_p
+			for (j=0;j<2;j++){
+				long v=GetId(edges[i].v[j]);
+				next_p[k]=head_v[v];
+				head_v[v]=k++; //post increment: head_v[v]=k; and then k=k+1;
+			}
+		}
+
+		//sort head_v by order of increasing edges angle
+		for (i=0;i<nbv;i++) {
+			int exch=1,ord=0;      
+
+			//exchange vertices position in head_v and next_p till tey are sorted
+			while (exch){
+				long *p=head_v+i;               
+				long *po=p;                     
+				long  n=*p;                     
+				float angleold=-1000 ; // angle = - infinity
+				ord=0; exch=0;
+
+				// loop over the edges that contain the vertex i (till -1)
+				while (n >=0){
+					ord++;
+					long  i1=n/2;       // i1 = floor (n/2)      -> Edge number
+					long  j1=n%2;       // j1 = 1 if n is odd    -> Vertex index for this edge (0 or 1)
+					long* pn=next_p+n;
+
+					//Next vertex index
+					n=*pn;                       
+
+					//compute angle between horizontal axis and v0->v1
+					float angle = j1 ? OppositeAngle(eangle[i1]):  eangle[i1]; 
+
+					//exchange if the current edge angle is smaller than the previous one
+					if (angleold > angle){
+						exch=1;
+						*pn=*po;  // next_p[n] = n + 1
+						*po=*p;   // 
+						*p=n;     // next_p[n+1] = n
+						po=pn;    // po now point toward pn (invert next and current)
+					}
+
+					//else, continue going to the next edge position
+					else{                        //  to have : po -> p -> pn
+						angleold=angle; // update maximum angle
+						po=p;           // po now point toward p  (current position)
+						p=pn;           // p  now point toward pn (next position)
+					}
+				}
+			}
+
+			// angular test on current vertex to guess whether it is a corner (ord = number of edges holding i)
+			if(ord==2) { 
+				long  n1 = head_v[i];
+				long  n2 = next_p[n1];
+				long  i1 = n1/2, i2 = n2/2; // edge number
+				long  j1 = n1%2, j2 = n2%2; // vertex in the edge 
+				float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
+				float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
+				float da12 = Abs(angle2-angle1);
+				if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
+					vertices[i].SetCorner() ; 
+				}
+				// if the edge type/referencenumber a changing then is SetRequired();
+				if (edges[i1].type != edges[i2].type || edges[i1].Required()){
+					vertices[i].SetRequired();
+				}
+				if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+					vertices[i].SetRequired();
+				}
+			}
+			if(ord != 2) {
+				vertices[i].SetCorner();
+			}
+
+			/*close the list around the vertex to have a circular loop*/
+			long no=-1, ne = head_v[i];
+			while (ne >=0) ne = next_p[no=ne];        
+			if(no>=0) next_p[no] = head_v[i];
+		}
+
+		/*Check that the list makes sense (we have all the time the same vertex)
+		 * and build adjacent edges*/
+		k =0;
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){
+
+				long n1 = next_p[k++]; 
+				long i1 = n1/2 ,j1=n1%2;
+
+				if( edges[i1].v[j1] != edges[i].v[j]) _error_("Problem while processing edges: check the edge list");
+
+				edges[i1].Adj[j1] = edges + i;
+				edges[i1].AdjVertexIndex[j1] = j;
+			}
+		}
+
+		/* generation of  all the tangents*/
+		for (i=0;i<nbe;i++) {
+			R2    AB =edges[i].v[1]->r -edges[i].v[0]->r;// AB = vertex0 -> vertex1
+			double lAB=Norme2(AB);                       // Get length of AB
+			double ltg2[2]={0.0};                        // initialize tangent
+
+			//loop over the 2 vertices of the edge
+			for (j=0;j<2;j++) {
+				R2     tg =edges[i].tg[j];
+				double ltg=Norme2(tg);
+
+				//by default, tangent=[0 0]
+				if(ltg==0){
+					//if the current vertex of the edge is not a corner
+					if(!edges[i].v[j]->Corner()){
+						/*The tangent is set as the vector between the
+						 * previous and next vertices connected to current vertex
+						 * normed by the edge length*/
+						tg = edges[i].v[1-j]->r - edges[i].Adj[j]->v[1-edges[i].AdjVertexIndex[j]]->r;
+						ltg= Norme2(tg);
+						tg = tg *(lAB/ltg);
+						ltg= lAB;
+					}
+					//else:  a Corner no tangent => nothing to do    
+				}
+				else{
+					//tangent has already been computed
+					tg = tg*(lAB/ltg),ltg=lAB;
+				}
+
+				ltg2[j] = ltg;
+
+				if ((tg,AB)<0) tg = -tg;
+
+				edges[i].tg[j]=tg;
+			}
+			if (ltg2[0]!=0) edges[i].SetTgA();
+			if (ltg2[1]!=0) edges[i].SetTgB();
+		} 
+
+		/* generation of  all curves (from corner to corner)*/
+		/*We proceed in 2 steps: first allocate, second build*/
+		for (int step=0;step<2;step++){
+
+			//unmark all edges
+			for (i=0;i<nbe;i++) edges[i].SetUnMark();
+			long  nb_marked_edges=0;
+
+			//initialize number of curves
+			nbcurves = 0;
+
+			for (int level=0;level<2 && nb_marked_edges!=nbe;level++){
+				for (i=0;i<nbe;i++){
+
+					GeomEdge & ei=edges[i];   
+					for(j=0;j<2;j++){
+						/*If current edge ei is unmarked and (level=1 or vertex i is required (corner)):
+						 * we do have the first edge of a new curve*/
+						if (!ei.Mark() && (level || ei[j].Required())) { 
+							int k0=j,k1;
+							GeomEdge   *e=&ei;
+							GeomVertex *a=(*e)(k0); // begin 
+							if(curves){
+								curves[nbcurves].FirstEdge=e;
+								curves[nbcurves].FirstVertexIndex=k0;
+							}
+							int nee=0;
+							for(;;){ 
+								nee++;
+								k1 = 1-k0; // next vertex of the edge 
+								e->SetMark();
+								nb_marked_edges++;
+								e->CurveNumber=nbcurves;
+								GeomVertex *b=(*e)(k1);
+
+								//break if we have reached the other end of the curve
+								if (a==b || b->Required()){
+									if(curves){
+										curves[nbcurves].LastEdge=e;
+										curves[nbcurves].LastVertexIndex=k1;
+									}
+									break;
+								}
+								//else: go to next edge (adjacent)
+								else{
+									k0 = e->AdjVertexIndex[k1];//  vertex in next edge
+									e  = e->Adj[k1]; // next edge
+								}
+							}
+							nbcurves++;
+							if(level) a->SetRequired();
+						}
+					}
+				} 
+			}
+			_assert_(nb_marked_edges && nbe);
+			//allocate if first step
+			if(step==0) curves=new Curve[nbcurves];
+		} 
+
+		/*clean up*/
+		delete [] next_p;
+		delete [] head_v;
+		delete [] eangle;
+
+	}
+	/*}}}*/
+	GeomEdge* Geometry::ProjectOnCurve(const Edge &e,double s,BamgVertex &V,VertexOnGeom &GV) const {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ProjectOnCurve)*/
+		/*Add a vertex on an existing geometrical edge according to the metrics of the two vertices constituting the edge*/
+
+		double save_s=s;
+		int NbTry=0;
+
+retry:
+
+		s=save_s;
+		GeomEdge* on=e.GeomEdgeHook;
+		if (!on){
+			_error_("ProjectOnCurve error message: edge provided should be on geometry");
+		}
+		if (!e[0].GeomEdgeHook ||  !e[1].GeomEdgeHook){
+			_error_("ProjectOnCurve error message: at least one of the vertex of the edge provided is not on geometry");
+		}
+
+		//Get the two vertices of the edge
+		const BamgVertex &v0=e[0];
+		const BamgVertex &v1=e[1];
+
+		//Get position of V0, V1 and vector v0->v1
+		R2 V0=v0,V1=v1,V01=V1-V0;
+
+		//Get geometrical vertices corresponding to v0 and v1
+		VertexOnGeom  vg0=*v0.GeomEdgeHook,  vg1=*v1.GeomEdgeHook;
+
+		//build two pointers towrad current geometrical edge
+		GeomEdge *eg0=on, *eg1=on;
+
+		//Get edge direction and swap v0 and v1 if necessary
+		R2 Ag=(R2)(*on)[0],Bg=(R2)(*on)[1],AB=Bg-Ag; 
+		int OppositeSens = (V01,AB)<0;
+		int direction0=0,direction1=1;
+		if (OppositeSens) s=1-s,Exchange(vg0,vg1),Exchange(V0,V1);
+
+		//Compute metric of new vertex as a linear interpolation of the two others
+		V.m=Metric(1.0-s,v0,s,v1);
+
+		const int mxe=100;
+		GeomEdge* ge[mxe+1];
+		int     directionge[mxe+1];
+		double  lge[mxe+1];
+		int bge=mxe/2,tge=bge;
+		ge[bge] = e.GeomEdgeHook;
+		directionge[bge]=1;
+
+		while(eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){ 
+			if (bge<=0) {
+				if(NbTry) {
+					_printf_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve\n");
+					_printf_("That bug might come from:\n");
+					_printf_(" 1)  a mesh edge  containing more than " << mxe/2 << " geometrical edges\n");
+					_printf_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before\n");
+					_printf_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)\n");
+					_error_("see above");
+				}
+				NbTry++;
+				goto retry;
+			}
+			GeomEdge* tmpge = eg0;
+			ge[--bge] =eg0 = eg0->Adj[direction0];
+			_assert_(bge>=0 && bge<=mxe);
+			direction0 = 1-( directionge[bge] = tmpge->AdjVertexIndex[direction0]);
+		}
+		while (eg1 != (GeomEdge*) vg1  &&  (*eg1)(direction1) != (GeomVertex*) vg1) { 
+			if(tge>=mxe ) { 
+				_printf_("WARNING: on the class Mesh before call Geometry::ProjectOnCurve is having issues (isn't it Eric?)\n");
+				NbTry++;
+				if (NbTry<2) goto retry;
+				_printf_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve\n");
+				_printf_("That bug might come from:\n");
+				_printf_(" 1)  a mesh edge  contening more than " << mxe/2 << " geometrical edges\n");
+				_printf_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before\n");
+				_printf_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)\n");
+				_error_("see above");
+			}
+			GeomEdge* tmpge = eg1;
+			ge[++tge] =eg1 = eg1->Adj[direction1];
+			directionge[tge]= direction1 = 1-tmpge->AdjVertexIndex[direction1];
+			_assert_(tge>=0 && tge<=mxe);
+		}
+
+		if ((*eg0)(direction0)==(GeomVertex*)vg0)
+		 vg0=VertexOnGeom(*(BamgVertex*) vg0,*eg0,direction0); //vg0 = absisce
+
+		if ((*eg1)(direction1)==(GeomVertex*)vg1)
+		 vg1=VertexOnGeom(*(BamgVertex*) vg1,*eg1,direction1);
+
+		double sg;
+		if (eg0 == eg1) { 
+			double s0=vg0,s1=vg1;
+			sg =  s0*(1.0-s) +  s*s1;
+			on=eg0;
+		}
+		else {
+			R2 AA=V0,BB;
+			double s0,s1;
+			int i=bge;
+			double ll=0;
+			for(i=bge;i<tge;i++){
+				_assert_(i>=0 && i<=mxe);
+				BB =  (*ge[i])[directionge[i]];
+				lge[i]=ll += Norme2(AA-BB);
+				AA=BB ;}
+				lge[tge]=ll+=Norme2(AA-V1); 
+				// search the geometrical edge
+				_assert_(s<=1.0);
+				double ls= s*ll;
+				on =0;
+				s0 = vg0;
+				s1= directionge[bge];
+				double l0=0,l1;
+				i=bge;
+				while (  (l1=lge[i]) < ls ) {
+					_assert_(i>=0 && i<=mxe);
+					i++,s0=1-(s1=directionge[i]),l0=l1;
+				}
+				on=ge[i];
+				if (i==tge) 
+				 s1=vg1;
+
+				s  =(ls-l0)/(l1-l0);
+				sg =s0*(1.0-s)+s*s1;    
+		} 
+		_assert_(on);
+		V.r= on->F(sg);
+		GV=VertexOnGeom(V,*on,sg);
+		return on;
+	}
+	/*}}}*/
+	I2 Geometry::R2ToI2(const R2 & P) const {/*{{{*/
+		/*coefIcoor is the coefficient used for integer coordinates:
+		 *                       (x-pmin.x)
+		 * Icoor x = (2^30 -1) ------------ 
+		 *                          D
+		 * where D is the longest side of the domain (direction x or y)
+		 * so that (x-pmin.x)/D is in ]0 1[
+		 *
+		 * coefIcoor = (2^30 -1)/D
+		 */
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)) ,(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}/*}}}*/
+	void Geometry::UnMarkEdges() {/*{{{*/
+		for (int i=0;i<nbe;i++) edges[i].SetUnMark();
+	}/*}}}*/
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Geometry.h	(revision 18231)
@@ -0,0 +1,67 @@
+#ifndef _GEOMETRY_H_
+#define _GEOMETRY_H_
+
+#include "./include.h"
+#include "./BamgGeom.h"
+#include "./BamgOpts.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+
+namespace bamg {
+
+	class Triangle;
+	class BamgQuadtree;
+	class GeomSubDomain;
+	class Edge;
+
+	class Geometry { 
+
+		public:
+
+			long           NbRef;                 // counter of ref on the this class if 0 we can delete
+			long           nbv;                   // number of vertices
+			long           nbe;                   // number of edges
+			long           nbsubdomains;
+			long           nbcurves;
+			GeomVertex    *vertices;
+			GeomEdge      *edges;
+			BamgQuadtree  *quadtree;
+			GeomSubDomain *subdomains;
+			Curve         *curves;
+			R2             pmin,pmax;             // domain extrema coordinates
+			double         coefIcoor;             // coef to integer Icoor1;
+			double         MaxCornerAngle;
+
+			//Constructor/Destructors
+			~Geometry(); 
+			Geometry();
+			Geometry(const Geometry & Gh);
+			Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts);
+
+			//Operators
+			const GeomVertex &operator[](long i) const { return vertices[i]; };
+			GeomVertex       &operator[](long i) { return vertices[i];       };
+			const GeomEdge   &operator()(long i) const { return edges[i];    };
+			GeomEdge         &operator()(long  i) { return edges[i];         };
+
+			//Methods
+			void             Echo();
+			I2               R2ToI2(const R2 &P) const;
+			double           MinimalHmin();
+			double           MaximalHmax();
+			void             ReadGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+			void             Init(void);
+			void             PostRead();
+			long             GetId(const GeomVertex &t) const;
+			long             GetId(const GeomVertex *t) const;
+			long             GetId(const GeomEdge &t) const;
+			long             GetId(const GeomEdge *t) const;
+			long             GetId(const Curve *c) const;
+			void             UnMarkEdges();
+			GeomEdge        *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
+			void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 18231)
@@ -0,0 +1,390 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Constructors Destructors*/
+	ListofIntersectionTriangles::ListofIntersectionTriangles(int n,int m)/*{{{*/
+	  : MaxSize(n), Size(0), len(-1),state(-1),lIntTria(new IntersectionTriangles[n]) ,
+	  NbSeg(0), MaxNbSeg(m), lSegsI(new SegInterpolation[m]){
+	  }
+	/*}}}*/
+	ListofIntersectionTriangles::~ListofIntersectionTriangles(){/*{{{*/
+		if (lIntTria) delete [] lIntTria,lIntTria=0;
+		if (lSegsI) delete [] lSegsI,lSegsI=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	void ListofIntersectionTriangles::Init(void){/*{{{*/
+		state=0;
+		len=0;
+		Size=0;
+	}
+	/*}}}*/
+	double  ListofIntersectionTriangles::Length(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Length)*/
+
+		// computation of the length
+
+		// check Size
+		if (Size<=0){
+			_error_("Size<=0");
+		}
+
+		Metric Mx,My;
+		int ii,jj;
+		R2 x,y,xy;
+
+		SegInterpolation* SegI=lSegsI;
+		lSegsI[NbSeg].last=Size;
+		int EndSeg=Size;
+
+		y = lIntTria[0].x;
+		double sxy, s = 0;
+		lIntTria[0].s =0;
+		SegI->lBegin=s;
+
+		for (jj=0,ii=1;ii<Size;jj=ii++) {  
+			// seg jj,ii
+			x  = y;
+			y  = lIntTria[ii].x;
+			xy = y-x;
+			Mx = lIntTria[ii].m;
+			My = lIntTria[jj].m;
+			sxy= LengthInterpole(Mx,My,xy);
+			s += sxy;
+			lIntTria[ii].s = s;
+			if (ii == EndSeg){
+				SegI->lEnd=s;
+				SegI++;
+				EndSeg=SegI->last;
+				SegI->lBegin=s;
+			}
+		}
+		len = s;
+		SegI->lEnd=s;
+
+		return s;
+	}
+	/*}}}*/
+	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		int n;
+		R2 x(0,0);
+		if ( d0) x =      (*tt)[0].r * d0;
+		if ( d1) x = x +  (*tt)[1].r * d1;
+		if ( d2) x = x +  (*tt)[2].r * d2;
+		// newer add same point 
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-x)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=tt;
+			lIntTria[Size].bary[0]=d0;
+			lIntTria[Size].bary[1]=d1;
+			lIntTria[Size].bary[2]=d2;
+			lIntTria[Size].x = x;
+			Metric m0,m1,m2;
+			BamgVertex * v;
+			if ((v=(*tt)(0))) m0    = v->m;
+			if ((v=(*tt)(1))) m1    = v->m;
+			if ((v=(*tt)(2))) m2    = v->m;
+			lIntTria[Size].m =  Metric(lIntTria[Size].bary,m0,m1,m2);
+			n=Size++;}
+		else n=Size-1;
+		return n;
+	}
+	/*}}}*/
+	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		int n;
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-A)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=0;
+			lIntTria[Size].x=A;
+			lIntTria[Size].m=mm;
+			n=Size++;
+		}
+		else  n=Size-1;
+		return  n; 
+	}
+	/*}}}*/
+	long ListofIntersectionTriangles::NewPoints(BamgVertex* vertices,long &nbv,long maxnbv){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		//If length<1.5, do nothing
+		double s=Length();
+		if (s<1.5) return 0;
+
+		const long nbvold=nbv;
+		int ii = 1 ;
+		R2 y,x;
+		Metric My,Mx ;
+		double sx =0,sy;
+		int nbi=Max(2,(int) (s+0.5));
+		double sint=s/nbi;
+		double si  =sint;
+
+		int EndSeg=Size;
+		SegInterpolation* SegI=NULL;
+		if (NbSeg) SegI=lSegsI,EndSeg=SegI->last;
+
+		for (int k=1;k<nbi;k++){
+			while ((ii < Size) && ( lIntTria[ii].s <= si )){
+				if (ii++ == EndSeg){
+					SegI++;
+					EndSeg=SegI->last;
+				}
+			}
+
+			int ii1=ii-1;
+			x  =lIntTria[ii1].x;
+			sx =lIntTria[ii1].s;
+			Metric Mx=lIntTria[ii1].m;
+			y  =lIntTria[ii].x;
+			sy =lIntTria[ii].s;
+			Metric My=lIntTria[ii].m;
+			double lxy = sy-sx;
+			double cy = abscisseInterpole(Mx,My,y-x,(si-sx)/lxy);
+
+			R2 C;
+			double cx = 1-cy;
+			C = SegI ? SegI->F(si): x * cx + y *cy;
+			//C.Echo();
+			//x.Echo();
+			//y.Echo();
+			//_printf_("cx = " << cx << ", cy=" << cy << "\n");
+
+			si += sint;
+			if ( nbv<maxnbv) {
+				vertices[nbv].r = C;
+				vertices[nbv++].m = Metric(cx,lIntTria[ii-1].m,cy,lIntTria[ii].m);
+			}
+			else return nbv-nbvold;
+		  }
+		return nbv-nbvold;
+	}
+	/*}}}*/
+	void ListofIntersectionTriangles::ReShape(){ /*{{{*/
+
+		int newsize = MaxSize*2;
+		IntersectionTriangles* nw = new IntersectionTriangles[newsize];
+		_assert_(nw);
+
+		// recopy
+		for (int i=0;i<MaxSize;i++) nw[i] = lIntTria[i];       
+		long int verbosity=0;
+		if(verbosity>3) _printf_("   ListofIntersectionTriangles  ReShape Maxsize " << MaxSize << " -> " << MaxNbSeg << "\n");
+		MaxSize = newsize; 
+		delete [] lIntTria;// remove old
+		lIntTria = nw; // copy pointer
+	}
+	/*}}}*/
+	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ListofIntersectionTriangles)*/
+
+		Triangle *tbegin, *t;
+
+		Icoor2 deta[3], deti,detj;
+		double ba[3];
+		int ifirst=-1,ilast;
+		int i0,i1,i2;
+		int ocut,i,j,k=-1;
+		//  int OnAVertices =0;
+		Icoor2 dt[3];
+		I2 a = Bh.R2ToI2(A) ,b= Bh.R2ToI2(B);// compute  the Icoor a,b
+		I2 vi,vj;  
+		int iedge =-1;// not a edge
+
+		if(nbegin)  {// optimisation 
+			// we suppose  knowing the starting  triangle
+			t=tbegin=lIntTria[ilast=(Size-1)].t;
+			if (tbegin->det>=0) 
+			 ifirst = ilast;}  
+		else {// not optimisation 
+			Init();
+			t=tbegin = Bh.TriangleFindFromCoord(a,deta);
+			if( t->det>=0)
+			 ilast=NewItem(t,double(deta[0])/t->det,double(deta[1])/t->det,double(deta[2])/t->det);
+			else 
+			  {// find the nearest boundary edge  of the vertex A
+				// find a edge or such normal projection a the edge IJ is on the edge
+				//   <=> IJ.IA >=0 && IJ.AJ >=0
+				ilast=ifirst;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+				BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+				NewItem(A,Metric(ba,v0,bb,v1));
+				t=edge;
+				// test if the point b is in the same side
+				if (det(v0.i,v1.i,b)>=0) {
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			  } // find the nearest boundary edge  of the vertex A
+		} // end not optimisation 
+		if (t->det<0) {  // outside departure
+			while (t->det <0) { // intersection boundary edge and a,b,
+				k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
+				if (k<0){
+					_error_("k<0");
+				}
+				ocut = OppositeEdge[k];
+				i=VerticesOfTriangularEdge[ocut][0];
+				j=VerticesOfTriangularEdge[ocut][1];
+				vi=(*t)[i];
+				vj=(*t)[j];
+				deti = bamg::det(a,b,vi);
+				detj = bamg::det(a,b,vj);
+				if (deti>0) // go to  i direction on gamma
+				 ocut = PreviousEdge[ocut];      
+				else if (detj<=0) // go to j direction on gamma
+				 ocut = NextEdge[ocut];         
+				AdjacentTriangle tadj =t->Adj(ocut);
+				t = tadj;
+				iedge= tadj; 
+				if (t == tbegin) { // 
+					double ba,bb;
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			} //  end while (t->det <0)
+			// theoriticaly we have: deti =<0 and detj>0
+
+			// computation of barycentric coor
+			// test if the point b is on size on t
+			// we revert vi,vj because vi,vj is def in Adj triangle
+			if ( det(vi,vj,b)>=0) {
+				t=tbegin;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+				NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+				return;
+			}
+			else
+			  {
+				k = OppositeVertex[iedge];
+				i=VerticesOfTriangularEdge[iedge][0];
+				j=VerticesOfTriangularEdge[iedge][1];
+				double dij = detj-deti;
+				if (i+j+k != 0 + 1 +2){
+					_error_("i+j+k != 0 + 1 +2");
+				}
+				ba[j] =  detj/dij;
+				ba[i] = -deti/dij;
+				ba[k] = 0;
+				ilast=NewItem(t,ba[0],ba[1],ba[2]); }
+		}  //  outside departure
+
+		// recherche the intersection of [a,b] with Bh Mesh.
+		// we know  a triangle ta contening the vertex a
+		// we have 2 case for intersection [a,b] with a edge [A,B] of Bh
+		// 1) the intersection point is in ]A,B[
+		// 2)                        is A or B
+		// first version --- 
+		for (;;) {
+			//    t->Draw();
+			if (iedge < 0) {
+				i0 =0;i1=1;i2=2;
+				dt[0] =bamg::det(a,b,(*t)[0]);
+				dt[1] =bamg::det(a,b,(*t)[1]);
+				dt[2] =bamg::det(a,b,(*t)[2]);}
+			else {
+				i2 = iedge;
+				i0 = NextEdge[i2];
+				i1 = NextEdge[i0]; 
+				dt[VerticesOfTriangularEdge[iedge][0]] = detj;// we revert i,j because
+				dt[VerticesOfTriangularEdge[iedge][1]] = deti;// we take the Triangle by the other side
+				dt[iedge] = det(a,b,(*t)[OppositeVertex[iedge]]);}
+
+				// so we have just to see the transition from - to + of the det0..2 on edge of t
+				// because we are going from a to b
+				if       ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] > 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] == 0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] >  0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] == 0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] == 0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] == 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] == 0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] == 0))
+				 ocut =i2;
+				else { //  On a edge (2 zero)
+					k =0;
+					if (dt[0]) ocut=0,k++; 
+					if (dt[1]) ocut=1,k++; 
+					if (dt[2]) ocut=2,k++;
+					if(k == 1) {
+						if (dt[ocut] >0) // triangle upper AB
+						 ocut = NextEdge[ocut];
+						i= VerticesOfTriangularEdge[ocut][0];
+						j= VerticesOfTriangularEdge[ocut][1];
+					}
+					else {
+						_error_("Bug Split Edge");
+					}
+				}
+
+				k = OppositeVertex[ocut];
+
+				Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
+
+				if (detbij >= 0) { //we find the triangle contening b
+					dt[0]=bamg::det((*t)[1],(*t)[2],b);
+					dt[1]=bamg::det((*t)[2],(*t)[0],b);
+					dt[2]=bamg::det((*t)[0],(*t)[1],b);
+					double dd = t->det;
+					NewItem(t,dt[0]/dd,dt[1]/dd,dt[2]/dd);      
+					return ;}
+				else { // next triangle by  adjacent by edge ocut 
+					deti = dt[i];
+					detj = dt[j];
+					double dij = detj-deti;
+					ba[i] =  detj/dij;
+					ba[j] = -deti/dij;
+					ba[3-i-j ] = 0;
+					ilast=NewItem(t, ba[0],ba[1],ba[2]);      
+
+					AdjacentTriangle ta =t->Adj(ocut);
+					t = ta;
+					iedge= ta; 
+					if (t->det <= 0)  {
+						double ba,bb;
+						AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+						NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+						return;
+					}
+				}// we  go outside of omega 
+		} // for(;;)
+	}
+	/*}}}*/
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/ListofIntersectionTriangles.h	(revision 18231)
@@ -0,0 +1,72 @@
+#ifndef _LISTOFINTERSECTIONTRIANGLES_H_
+#define _LISTOFINTERSECTIONTRIANGLES_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class Triangle;
+
+	class ListofIntersectionTriangles {
+
+		class IntersectionTriangles {
+
+			public: 
+				Triangle *t;
+				double    bary[3];   // use if t != 0
+				R2        x;
+				Metric    m;
+				double    s;         // curvilinear coordinate
+				double    sp;        // length of the previous segment in m
+				double    sn;        // length of the next segment in m
+		};
+
+		class SegInterpolation {
+
+			public:
+				GeomEdge *e;
+				double           sBegin  ,sEnd; // abscisse of the seg on edge parameter
+				double           lBegin  ,lEnd; // length abscisse set in ListofIntersectionTriangles::Length
+				int              last;          // last index in ListofIntersectionTriangles for this Sub seg of edge
+
+				//Methods
+				R2 F(double s){ 
+					double c01=lEnd-lBegin, c0=(lEnd-s)/c01, c1=(s-lBegin)/c01;
+					if (lBegin>s || s>lEnd){
+						_error_("lBegin>s || s>lEnd");
+					}
+					return e->F(sBegin*c0+sEnd*c1);
+				}
+		};
+
+		public:
+
+			int                    MaxSize;
+			int                    Size;
+			double                 len;
+			int                    state;
+			IntersectionTriangles *lIntTria;
+			int                    NbSeg;
+			int                    MaxNbSeg;
+			SegInterpolation      *lSegsI;
+
+			//Constructors/Destructors
+			ListofIntersectionTriangles(int n=256,int m=16);
+			~ListofIntersectionTriangles();
+
+			//Operators
+			IntersectionTriangles & operator[](int i) {return lIntTria[i];}
+			operator int&() {return Size;}
+
+			//Methods
+			void   Init();
+			int    NewItem(Triangle *tt,double d0,double d1,double d2);
+			int    NewItem(R2 ,const Metric &);
+			void   SplitEdge(const Mesh &,const R2 &,const R2 &,int nbegin=0);
+			double Length();
+			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
+			void   ReShape();
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.cpp	(revision 18231)
@@ -0,0 +1,5050 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../shared/shared.h"
+#include "./bamgobjects.h"
+#include "./det.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){ /*{{{*/
+
+		/*Initialize fields*/
+		Init(0);
+
+		/*Read Geometry if provided*/
+		if(bamggeom->Edges) {
+			Gh.ReadGeometry(bamggeom,bamgopts);
+			Gh.PostRead();
+		}
+
+		/*Read background mesh*/
+		ReadMesh(bamgmesh,bamgopts);
+
+		/*Build Geometry if not provided*/
+		if(bamggeom->Edges==NULL) {
+			/*Recreate geometry if needed*/
+			_printf_("WARNING: mesh present but no geometry found. Reconstructing...\n");
+			BuildGeometryFromMesh(bamgopts);
+			Gh.PostRead();
+		}
+
+		/*Set integer coordinates*/
+		SetIntCoor();
+
+		/*Fill holes and generate mesh properties*/
+		ReconstructExistingMesh();
+	}
+	/*}}}*/
+	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){/*{{{*/
+
+		Init(0);
+		ReadMesh(index,x,y,nods,nels);
+		SetIntCoor();
+		ReconstructExistingMesh();
+	}
+	/*}}}*/
+	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){/*{{{*/
+		Triangulate(x,y,nods);
+	}
+	/*}}}*/
+	Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb,BamgOpts* bamgopts) : Gh(*(new Geometry())), BTh(*this) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+
+		  int i,k,itadj;
+		  int kt=0;
+		  int * kk    = new int [Tho.nbv];
+		  long * reft = new long[Tho.nbt];
+		  long nbInT =    Tho.TriangleReferenceList(reft);
+		  long * refv = new long[Tho.nbv];
+
+		  for (i=0;i<Tho.nbv;i++)
+			kk[i]=-1;
+		  for (i=0;i<Tho.nbv;i++)
+			refv[i]=0;
+		  int nbNewBedge =0;
+		  //  int nbOldBedge =0;  
+		  for (i=0;i<Tho.nbt;i++)
+			if(  reft[i] >=0 && flag[i]) 
+			  {
+				const Triangle & t = Tho.triangles[i];
+				kt++;
+				kk[Tho.GetId(t[0])]=1;
+				kk[Tho.GetId(t[1])]=1;
+				kk[Tho.GetId(t[2])]=1;
+				itadj=Tho.GetId(t.TriangleAdj(0));
+				if (  reft[itadj] >=0 && !flag[itadj])
+				  { nbNewBedge++;
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[0][0]])]=bb[i];
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[0][1]])]=bb[i];
+				  }
+				itadj=Tho.GetId(t.TriangleAdj(1));
+				if (  reft[itadj] >=0 && !flag[itadj])
+				  { nbNewBedge++;
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[1][0]])]=bb[i];
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[1][1]])]=bb[i];}
+					itadj=Tho.GetId(t.TriangleAdj(2));
+					if (  reft[itadj] >=0 && !flag[itadj])
+					  { nbNewBedge++;
+						refv[Tho.GetId(t[VerticesOfTriangularEdge[2][0]])]=bb[i];
+						refv[Tho.GetId(t[VerticesOfTriangularEdge[2][1]])]=bb[i];}
+			  }
+		  k=0;
+		  for (i=0;i<Tho.nbv;i++){
+			  if (kk[i]>=0) kk[i]=k++;
+			}
+		  _printf_("   number of vertices " << k << ", remove = " << Tho.nbv - k << "\n");
+		  _printf_("   number of triangles " << kt << ", remove = " << nbInT-kt << "\n");
+		  _printf_("   number of New boundary edge " << nbNewBedge << "\n");
+		  long imaxnbv =k;
+		  Init(imaxnbv);
+		  for (i=0;i<Tho.nbv;i++)
+			if (kk[i]>=0) 
+			  {
+				vertices[nbv] = Tho.vertices[i];
+				if (!vertices[nbv].GetReferenceNumber())
+				 vertices[nbv].ReferenceNumber = refv[i];
+				nbv++;
+			  }
+		  if (imaxnbv != nbv){
+			  delete [] kk;
+			  delete [] refv;
+			  _error_("imaxnbv != nbv");
+		  }
+		  for (i=0;i<Tho.nbt;i++)
+			if(reft[i] >=0 && flag[i]){
+				const Triangle & t = Tho.triangles[i];
+				int i0 = Tho.GetId(t[0]);
+				int i1 = Tho.GetId(t[1]);
+				int i2 = Tho.GetId(t[2]);
+				if(i0<0 || i1<0 || i2<0){
+					delete [] refv;
+					_error_("i0<0 || i1<0 || i2< 0");
+				}
+				if(i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					delete [] refv;
+					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
+				}
+				triangles[nbt] = Triangle(this,kk[i0],kk[i1],kk[i2]);
+				triangles[nbt].color = Tho.subdomains[reft[i]].ReferenceNumber; 
+				nbt++;           
+			  }
+		  if (nbt==0 && nbv==0) {
+			  _error_("All triangles have been removed");
+		  }
+		  delete [] kk;
+		  delete [] reft;
+		  delete [] refv;
+		  BuildGeometryFromMesh(bamgopts);
+		  Gh.PostRead(); 
+		  SetIntCoor();
+		  ReconstructExistingMesh();
+
+		  /*Final checks*/
+		  _assert_(kt==nbt);
+		  _assert_(nbsubdomains);
+		  _assert_(subdomains[0].head && subdomains[0].head->link); 
+	  }
+	/*}}}*/
+	Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in)/*{{{*/
+	  : Gh(*(pGh?pGh:&Th.Gh)), BTh(*(pBth?pBth:this)) {
+		  /*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+		  Gh.NbRef++;
+		  maxnbv_in = Max(maxnbv_in,Th.nbv); 
+		  long i;
+		  // do all the allocation to be sure all the pointer existe
+
+		  Init(maxnbv_in);// to make the allocation 
+		  // copy of triangles
+		  nbv = Th.nbv;
+		  nbt = Th.nbt;
+		  nbe = Th.nbe;
+		  nbsubdomains = Th.nbsubdomains;
+		  nbtout = Th.nbtout;
+		  nbq =  Th.nbq ;
+		  NbVerticesOnGeomVertex = Th.NbVerticesOnGeomVertex;
+		  if(NbVerticesOnGeomVertex)
+			VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		  NbVerticesOnGeomEdge = Th.NbVerticesOnGeomEdge;
+		  if (NbVerticesOnGeomEdge)
+			VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge] ;
+		  if (& BTh == & Th.BTh){ // same background 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex = Th.NbVertexOnBThVertex;
+			  if(NbVertexOnBThVertex)
+				VertexOnBThVertex = new VertexOnVertex[NbVertexOnBThVertex];
+			  NbVertexOnBThEdge = Th.NbVertexOnBThEdge;
+			  if(NbVertexOnBThEdge)
+				VertexOnBThEdge = new VertexOnEdge[NbVertexOnBThEdge];
+			 }
+		  else { // no add on background mesh 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex=0;
+			  VertexOnBThVertex=0;
+			  NbVertexOnBThEdge=0;
+			  VertexOnBThEdge=0;
+			 }
+
+		  if(nbe)
+			edges = new Edge[nbe];
+		  if(nbsubdomains)
+			subdomains = new SubDomain[nbsubdomains];
+		  pmin = Th.pmin;
+		  pmax = Th.pmax;
+		  coefIcoor = Th.coefIcoor;
+		  for(i=0;i<nbt;i++)
+			triangles[i].Set(Th.triangles[i],Th,*this);
+		  for(i=0;i<nbe;i++)
+			edges[i].Set(Th,i,*this);
+		  for(i=0;i<nbv;i++)
+			vertices[i].Set(Th.vertices[i],Th,*this);
+		  for(i=0;i<nbsubdomains;i++)  
+			subdomains[i].Set(Th,i,*this);
+		  for (i=0;i<NbVerticesOnGeomVertex;i++)
+			VerticesOnGeomVertex[i].Set(Th.VerticesOnGeomVertex[i],Th,*this);
+		  for (i=0;i<NbVerticesOnGeomEdge;i++)
+			VerticesOnGeomEdge[i].Set(Th.VerticesOnGeomEdge[i],Th,*this);
+		  quadtree=0;
+
+	  }
+	/*}}}*/
+	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {/*{{{*/
+		this->Init(imaxnbv);
+		TriangulateFromGeom1(bamgopts,keepBackVertices);
+	}
+	/*}}}*/
+	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){/*{{{*/
+		Init(imaxnbv);
+		TriangulateFromGeom0(bamgopts);
+	}
+	/*}}}*/
+	Mesh::~Mesh() {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+
+		//if (vertices)             delete [] vertices;
+		if (edges)                delete [] edges;
+		if (triangles)            delete [] triangles;
+		if (quadtree)             delete    quadtree;
+		//if (orderedvertices)                delete [] orderedvertices;
+		if (subdomains)           delete []  subdomains;
+		if (VerticesOnGeomEdge)   delete [] VerticesOnGeomEdge;
+		if (VerticesOnGeomVertex) delete [] VerticesOnGeomVertex;
+		if (VertexOnBThVertex)    delete [] VertexOnBThVertex;
+		if (VertexOnBThEdge)      delete [] VertexOnBThEdge;
+
+		if (&Gh) {
+			if (Gh.NbRef>0) Gh.NbRef--;
+			else if (Gh.NbRef==0) delete &Gh;
+		}
+		if (&BTh && (&BTh != this)) {
+			if (BTh.NbRef>0) BTh.NbRef--;
+			else if (BTh.NbRef==0) delete &BTh;
+		}
+		Init(0); // set all to zero 
+	}
+	/*}}}*/
+
+	/*IO*/
+	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){/*{{{*/
+
+		long i1,i2,i3;
+		long i;
+		Metric M1(1);
+		int verbose=0;
+		bool* nodeflags=NULL;
+
+		nbv=nods;
+		maxnbv=nbv;
+		nbt=nels;
+
+		//Vertices
+		if (verbose) _printf_("Reading vertices (" << nbv << ")\n");
+		vertices=xNew<BamgVertex>(nbv);
+		orderedvertices=xNew<BamgVertex*>(nbv);
+		for (i=0;i<nbv;i++){
+			vertices[i].r.x=x[i];
+			vertices[i].r.y=y[i];
+			vertices[i].ReferenceNumber=1;
+			vertices[i].DirOfSearch =NoDirOfSearch;
+			vertices[i].m=M1;
+			vertices[i].color=0;
+		}
+		maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+		//Triangles
+		if (verbose) _printf_("Reading triangles (" << nbt << ")\n");
+		triangles =new Triangle[maxnbt]; //we cannot allocate only nbt triangles since 
+		nodeflags=xNew<bool>(nbv);
+		for(i=0;i<nbv;i++) nodeflags[i]=false;
+		//other triangles will be added for each edge
+		for (i=0;i<nbt;i++){
+			Triangle & t = triangles[i];
+			i1=(long)index[i*3+0]-1; //for C indexing
+			i2=(long)index[i*3+1]-1; //for C indexing
+			i3=(long)index[i*3+2]-1; //for C indexing
+			t=Triangle(this,i1,i2,i3);
+			t.color=1;
+			nodeflags[i1]=nodeflags[i2]=nodeflags[i3]=true;
+		}
+
+		/*Recreate geometry: */
+		if (verbose) _printf_("Building Geometry\n");
+		BuildGeometryFromMesh();
+		if (verbose) _printf_("Completing geometry\n");
+		Gh.PostRead();
+
+		/*Check that there is no orphan*/
+		bool isorphan=false;
+		for(i=0;i<nbv;i++){
+			if(!nodeflags[i]){
+				_printf_("Vertex " << i+1 << " does not belong to any element\n");
+				isorphan=true;
+			}
+		}
+		if(isorphan) _error_("Orphan found in mesh, see ids above");
+
+		/*Clean up*/
+		xDelete<bool>(nodeflags);
+	}
+	/*}}}*/
+	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){/*{{{*/
+
+		int    verbose;
+		double Hmin = HUGE_VAL;    // the infinie value
+		long   i1,i2,i3;
+		long   i,j;
+		Metric M1(1);
+
+		verbose=bamgopts->verbose;
+
+		nbv=bamgmesh->VerticesSize[0];
+		maxnbv=nbv;
+		nbt=bamgmesh->TrianglesSize[0];
+
+		//Vertices
+		if(bamgmesh->Vertices){
+			if(verbose>5) _printf_("      processing Vertices\n");
+
+			vertices=xNew<BamgVertex>(nbv);
+			orderedvertices=xNew<BamgVertex*>(nbv);
+
+			for (i=0;i<nbv;i++){
+				vertices[i].r.x=bamgmesh->Vertices[i*3+0];
+				vertices[i].r.y=bamgmesh->Vertices[i*3+1];
+				vertices[i].ReferenceNumber=(long)bamgmesh->Vertices[i*3+2];
+				vertices[i].DirOfSearch =NoDirOfSearch;
+				vertices[i].m=M1;
+				vertices[i].color=0;
+			}
+			maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+		}
+		else{
+			if(verbose>5) _error_("no Vertices found in the initial mesh");
+		}
+
+		//Triangles
+		if(bamgmesh->Triangles){
+			if(verbose>5) _printf_("      processing Triangles\n");
+			triangles =new Triangle[maxnbt]; //we cannot allocate only nbt triangles since 
+			//other triangles will be added for each edge
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				i1=(long)bamgmesh->Triangles[i*4+0]-1; //for C indexing
+				i2=(long)bamgmesh->Triangles[i*4+1]-1; //for C indexing
+				i3=(long)bamgmesh->Triangles[i*4+2]-1; //for C indexing
+				t=Triangle(this,i1,i2,i3);
+				t.color=(long)bamgmesh->Triangles[i*4+3];
+			}
+		}
+		else{
+			if(verbose>5) _error_("no Triangles found in the initial mesh");
+		}
+
+		//Quadrilaterals
+		if(bamgmesh->Quadrilaterals){
+			if(verbose>5) _printf_("      processing Quadrilaterals\n");
+			long i1,i2,i3,i4;
+			triangles =new Triangle[nbt];
+			for (i=0;i<bamgmesh->QuadrilateralsSize[0];i++){
+				//divide the quad into two triangles
+				Triangle & t1 = triangles[2*i];
+				Triangle & t2 = triangles[2*i+1];
+				i1=(long)bamgmesh->Quadrilaterals[i*5+0]-1; //for C indexing
+				i2=(long)bamgmesh->Quadrilaterals[i*5+1]-1; //for C indexing
+				i3=(long)bamgmesh->Quadrilaterals[i*5+2]-1; //for C indexing
+				i4=(long)bamgmesh->Quadrilaterals[i*5+3]-1; //for C indexing
+				t1=Triangle(this,i1,i2,i3);
+				t2=Triangle(this,i3,i4,i1);
+				t1.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t2.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t1.SetHidden(OppositeEdge[1]); // two times  because the adj was not created 
+				t2.SetHidden(OppositeEdge[1]); 
+			}
+		}
+
+		//VerticesOnGeomEdge
+		if(bamgmesh->VerticesOnGeomEdge){
+			if(verbose>5) _printf_("      processing VerticesOnGeomEdge\n");
+			NbVerticesOnGeomEdge=bamgmesh->VerticesOnGeomEdgeSize[0];
+			VerticesOnGeomEdge= new  VertexOnGeom[NbVerticesOnGeomEdge] ;
+			for (i=0;i<NbVerticesOnGeomEdge;i++){
+				long  i1,i2;
+				double s;
+				i1=(long)  bamgmesh->VerticesOnGeomEdge[i*3+0]-1; //for C indexing
+				i2=(long)  bamgmesh->VerticesOnGeomEdge[i*3+1]-1; //for C indexing
+				s =(double)bamgmesh->VerticesOnGeomEdge[i*3+2];
+				VerticesOnGeomEdge[i]=VertexOnGeom(vertices[i1],Gh.edges[i2],s);
+			}
+		}
+
+		//VerticesOnGeomVertex
+		if(bamgmesh->VerticesOnGeomVertexSize[0]){
+			if(verbose>5) _printf_("      processing VerticesOnGeomVertex\n");
+			NbVerticesOnGeomVertex=bamgmesh->VerticesOnGeomVertexSize[0];
+			VerticesOnGeomVertex  = new  VertexOnGeom[NbVerticesOnGeomVertex] ;
+			for (i=0;i<NbVerticesOnGeomVertex;i++){
+				long  i1,i2;
+				i1=(long)bamgmesh->VerticesOnGeomVertex[i*2+0]-1; //for C indexing
+				i2=(long)bamgmesh->VerticesOnGeomVertex[i*2+1]-1; //for C indexing
+				VerticesOnGeomVertex[i]=VertexOnGeom(vertices[i1],Gh.vertices[i2]);
+			}
+		}
+
+		//Edges
+		if (bamgmesh->Edges){
+			int i1,i2;
+			double* len=NULL;
+
+			if(verbose>5) _printf_("      processing Edges\n");
+			nbe=bamgmesh->EdgesSize[0];
+			edges= new Edge[nbe];
+			//initialize length of each edge (used to provided metric)
+			len= new double[nbv];
+			for(i=0;i<nbv;i++) len[i]=0;
+
+			for (i=0;i<nbe;i++){
+				i1=(int)bamgmesh->Edges[i*3+0]-1; //-1 for C indexing
+				i2=(int)bamgmesh->Edges[i*3+1]-1; //-1 for C indexing
+				edges[i].ReferenceNumber=(long)bamgmesh->Edges[i*3+2];
+				edges[i].v[0]= vertices +i1;
+				edges[i].v[1]= vertices +i2;
+				edges[i].adj[0]=NULL;
+				edges[i].adj[1]=NULL;
+				R2 x12=vertices[i2].r-vertices[i1].r;
+				double l12=sqrt((x12,x12));
+
+				//prepare metric
+				vertices[i1].color++;
+				vertices[i2].color++;
+				len[i1]+=l12;
+				len[i2]+=l12;
+				Hmin = Min(Hmin,l12);
+			}
+
+			// definition  the default of the given mesh size 
+			for (i=0;i<nbv;i++){
+				if (vertices[i].color>0) 
+				 vertices[i].m=Metric(len[i]/(double)vertices[i].color);
+				else 
+				 vertices[i].m=Metric(Hmin);
+			}
+			delete [] len;
+
+			// construction of edges[].adj 
+			for (i=0;i<nbv;i++){ 
+				vertices[i].color=(vertices[i].color ==2) ?-1:-2;
+			}
+			for (i=0;i<nbe;i++){
+				for (j=0;j<2;j++) { 
+					BamgVertex *v=edges[i].v[j];
+					long i0=v->color,j0;
+					if(i0==-1){
+						v->color=i*2+j;
+					}
+					else if (i0>=0) {// i and i0 edge are adjacent by the vertex v
+						j0 = i0%2;
+						i0 = i0/2;
+						_assert_(v==edges[i0 ].v[j0]);
+						edges[i ].adj[j ] =edges +i0;
+						edges[i0].adj[j0] =edges +i ;
+						v->color = -3;
+					}
+				}
+			}
+		}
+
+		//EdgeOnGeomEdge
+		if(bamgmesh->EdgesOnGeomEdge){
+			if(verbose>5) _printf_("      processing EdgesOnGeomEdge\n");
+			int i1,i2,i,j;
+			i2=bamgmesh->EdgesOnGeomEdgeSize[0];
+			for (i1=0;i1<i2;i1++) {
+				i=(int)bamgmesh->EdgesOnGeomEdge[i1*2+0]-1; //C indexing
+				j=(int)bamgmesh->EdgesOnGeomEdge[i1*2+1]-1; //C indexing
+				//Check value
+				if(!(i>=0 && j>=0 && i<nbe && j<Gh.nbe)) {
+					_error_("ReadMesh error: EdgesOnGeomEdge edge provided (line " << i1+1 << ": [" << i+1 << " " << j+1 << "]) is incorrect (must be positive, [0<i<nbe=" << nbe << " 0<j<Gh.nbe=" << Gh.nbe << "]");
+				}
+				edges[i].GeomEdgeHook=Gh.edges+j;
+			}
+		}
+
+		//SubDomain
+		if(bamgmesh->SubDomains){
+			long i3,head,direction;
+			if(verbose>5) _printf_("      processing SubDomains\n");
+			nbsubdomains=bamgmesh->SubDomainsSize[0];
+			subdomains = new SubDomain [ nbsubdomains ];
+			for (i=0;i<nbsubdomains;i++) {
+				i3  =(int)bamgmesh->SubDomains[i*3+0];
+				head=(int)bamgmesh->SubDomains[i*3+1]-1;//C indexing
+				direction=(int)bamgmesh->SubDomains[i*3+2];
+				if (i3!=3) _error_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
+				subdomains[i].head = triangles+head;
+				subdomains[i].direction = direction;
+				subdomains[i].ReferenceNumber = i3;
+			}
+		}
+
+	}
+	/*}}}*/
+	void Mesh::WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts){/*{{{*/
+
+		/*Intermediary*/
+		int i,j,k,num,i1,i2;
+		long n;
+		int* head_1=NULL;
+		int* next_1=NULL;
+		int* connectivitysize_1=NULL;
+		int  connectivitymax_1=0;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		/*Build reft that holds the number the subdomain number of each triangle, and the real numbering of the elements*/
+		long* reft = new long[nbt];
+		long* numt = new long[nbt];
+		long nbInT = TriangleReferenceList(reft);
+		TriangleIntNumbering(numt);
+
+		/*Chaining algorithm used to generate connectivity tables and other outputs*/
+
+		//Memory Allocation
+		head_1=xNew<int>(nbv);
+		next_1=xNew<int>(3*nbt);
+		connectivitysize_1=xNew<int>(nbv);
+
+		//Initialization
+		for (i=0;i<nbv;i++) head_1[i]=-1;
+		for (i=0;i<nbv;i++) connectivitysize_1[i]=0;
+		k=0;
+		//Chains generation
+		for (i=0;i<nbt;i++) {
+			//Do not take into account outside triangles (reft<0)
+			if (reft[i]>=0){
+				for (j=0;j<3;j++){
+					int v=GetId(triangles[i][j]); //jth vertex of the ith triangle
+					if (k>3*nbt-1 || k<0) _error_("k = " << k << ", nbt = " << nbt);
+					next_1[k]=head_1[v];
+					if (v>nbv-1 || v<0)   _error_("v = " << v << ", nbv = " << nbv);
+					head_1[v]=k++;
+					connectivitysize_1[v]+=1;
+				}
+			}
+		}
+		//Get maximum connectivity
+		connectivitymax_1=0;
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_1[i]>connectivitymax_1) connectivitymax_1=connectivitysize_1[i];
+		}
+
+		/*OK, now build outputs*/
+
+		/*Vertices*/
+		if(verbose>5) _printf_("      writing Vertices\n");
+		bamgmesh->VerticesSize[0]=nbv;
+		bamgmesh->VerticesSize[1]=3;
+		if (nbv){
+			bamgmesh->Vertices=xNew<double>(3*nbv);
+			for (i=0;i<nbv;i++){
+				bamgmesh->Vertices[i*3+0]=vertices[i].r.x;
+				bamgmesh->Vertices[i*3+1]=vertices[i].r.y;
+				bamgmesh->Vertices[i*3+2]=vertices[i].GetReferenceNumber();
+			}
+		}
+
+		/*Edges*/
+		if(verbose>5) _printf_("      writing Edges\n");
+		bamgmesh->EdgesSize[0]=nbe;
+		bamgmesh->EdgesSize[1]=3;
+		int NumIssmSegments=0;
+		if (nbe){
+			bamgmesh->Edges=xNew<double>(3*nbe);
+			for (i=0;i<nbe;i++){
+				bamgmesh->Edges[i*3+0]=GetId(edges[i][0])+1; //back to M indexing
+				bamgmesh->Edges[i*3+1]=GetId(edges[i][1])+1; //back to M indexing
+				bamgmesh->Edges[i*3+2]=edges[i].ReferenceNumber;
+				if(edges[i].GeomEdgeHook){
+					NumIssmSegments++;
+				}
+			}
+		}
+
+		/*Element edges*/
+		if(verbose>5) _printf_("      writing element edges\n");
+		SetOfEdges4* edge4=new SetOfEdges4(nbt*3,nbv);
+		double* elemedge=NULL;
+		elemedge=xNew<double>(3*nbt);
+		for (i=0;i<3*nbt;i++) elemedge[i]=-2.;//will become -1
+		k=0;
+		for (i=0;i<nbt;i++){
+			//Do not take into account outside triangles (reft<0)
+			if (reft[i]>=0){
+				for  (j=0;j<3;j++) {
+					i1=GetId(triangles[i][VerticesOfTriangularEdge[j][0]]);
+					i2=GetId(triangles[i][VerticesOfTriangularEdge[j][1]]);
+					n =edge4->SortAndFind(i1,i2);
+					if (n==-1){
+						//first time
+						n=edge4->SortAndAdd(i1,i2);
+						elemedge[n*2+0]=double(k);
+					}
+					else{
+						//second time
+						elemedge[n*2+1]=double(k);
+					}
+				}
+				k++;
+			}
+		}
+		bamgmesh->IssmEdgesSize[0]=edge4->nb();
+		bamgmesh->IssmEdgesSize[1]=4;
+		bamgmesh->IssmEdges=xNew<double>(4*edge4->nb());
+		for (i=0;i<edge4->nb();i++){
+			/*Invert first two vertices if necessary*/
+			bool found=false;
+			for (j=0;j<3;j++){
+				if (triangles[(int)elemedge[2*i+0]](j)==vertices+edge4->i(i)){
+					if (triangles[(int)elemedge[2*i+0]]((j+1)%3)==vertices+edge4->j(i)){
+						//trigonometric direction
+						bamgmesh->IssmEdges[i*4+0]=edge4->i(i)+1;// back to M indexing
+						bamgmesh->IssmEdges[i*4+1]=edge4->j(i)+1;// back to M indexing
+					}
+					else{
+						bamgmesh->IssmEdges[i*4+0]=edge4->j(i)+1;// back to M indexing
+						bamgmesh->IssmEdges[i*4+1]=edge4->i(i)+1;// back to M indexing
+					}
+					found=true;
+					break;
+				}
+			}
+			_assert_(found);
+			bamgmesh->IssmEdges[i*4+2]=elemedge[2*i+0]+1; // back to M indexing
+			bamgmesh->IssmEdges[i*4+3]=elemedge[2*i+1]+1; // back to M indexing
+		}
+		//clean up
+		delete edge4;
+		xDelete<double>(elemedge);
+
+		/*IssmSegments*/
+		if(verbose>5) _printf_("      writing IssmSegments\n");
+		bamgmesh->IssmSegmentsSize[0]=NumIssmSegments;
+		bamgmesh->IssmSegmentsSize[1]=4;
+		bamgmesh->IssmSegments=xNew<double>(4*NumIssmSegments);
+		num=0;
+		for (i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook){
+				//build segment
+				int i1=GetId(edges[i][0]);
+				int i2=GetId(edges[i][1]);
+				bool stop=false;
+				for(j=head_1[i1];j!=-1;j=next_1[j]){
+					for(k=0;k<3;k++){
+						if (GetId(triangles[(int)j/3][k])==i1){
+							if (GetId(triangles[(int)j/3][(int)((k+1)%3)])==i2){
+								bamgmesh->IssmSegments[num*4+0]=GetId(edges[i][0])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+1]=GetId(edges[i][1])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+2]=(int)j/3+1;            //back to M indexing
+								bamgmesh->IssmSegments[num*4+3]=edges[i].ReferenceNumber;
+								num+=1;
+								stop=true;
+								break;
+							}
+							if (GetId(triangles[(int)j/3][(int)((k+2)%3)])==i2){
+								bamgmesh->IssmSegments[num*4+0]=GetId(edges[i][1])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+1]=GetId(edges[i][0])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+2]=(int)j/3+1;            //back to M indexing
+								bamgmesh->IssmSegments[num*4+3]=edges[i].ReferenceNumber;
+								num+=1;
+								stop=true;
+								break;
+							}
+						}
+					}
+					if(stop) break;
+				}
+				if (!stop){
+					_error_("Element holding segment [" << i1+1 << " " << i2+1 << "] not found...");
+				}
+			}
+		}
+
+		/*Triangles*/
+		if(verbose>5) _printf_("      writing Triangles\n");
+		k=nbInT-nbq*2;
+		num=0;
+		bamgmesh->TrianglesSize[0]=k;
+		bamgmesh->TrianglesSize[1]=4;
+		if (k){
+			bamgmesh->Triangles=xNew<double>(4*k);
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				//reft[i]=-1 for outside triangle
+				if (reft[i]>=0 && !( t.Hidden(0) || t.Hidden(1) || t.Hidden(2) )){
+					bamgmesh->Triangles[num*4+0]=GetId(t[0])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+1]=GetId(t[1])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+2]=GetId(t[2])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+3]=subdomains[reft[i]].ReferenceNumber;
+					num=num+1;
+				}
+			}
+		}
+
+		/*Quadrilaterals*/
+		if(verbose>5) _printf_("      writing Quadrilaterals\n");
+		bamgmesh->QuadrilateralsSize[0]=nbq;
+		bamgmesh->QuadrilateralsSize[1]=5;
+		if (nbq){
+			bamgmesh->Quadrilaterals=xNew<double>(5*nbq);
+			for (i=0;i<nbt;i++){
+				Triangle &t =triangles[i];
+				Triangle* ta;
+				BamgVertex *v0,*v1,*v2,*v3;
+				if (reft[i]<0) continue;
+				if ((ta=t.Quadrangle(v0,v1,v2,v3)) !=0 && &t<ta) { 
+					bamgmesh->Quadrilaterals[i*5+0]=GetId(v0)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+1]=GetId(v1)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+2]=GetId(v2)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+3]=GetId(v3)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+4]=subdomains[reft[i]].ReferenceNumber;
+				}
+			}
+		}
+
+		/*SubDomains*/
+		if(verbose>5) _printf_("      writing SubDomains\n");
+		bamgmesh->SubDomainsSize[0]=nbsubdomains;
+		bamgmesh->SubDomainsSize[1]=4;
+		if (nbsubdomains){
+			bamgmesh->SubDomains=xNew<double>(4*nbsubdomains);
+			for (i=0;i<nbsubdomains;i++){
+				bamgmesh->SubDomains[i*4+0]=3;
+				bamgmesh->SubDomains[i*4+1]=reft[GetId(subdomains[i].head)];
+				bamgmesh->SubDomains[i*4+2]=1;
+				bamgmesh->SubDomains[i*4+3]=subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*SubDomainsFromGeom*/
+		if(verbose>5) _printf_("      writing SubDomainsFromGeom\n");
+		bamgmesh->SubDomainsFromGeomSize[0]=Gh.nbsubdomains;
+		bamgmesh->SubDomainsFromGeomSize[1]=4;
+		if (Gh.nbsubdomains){
+			bamgmesh->SubDomainsFromGeom=xNew<double>(4*Gh.nbsubdomains);
+			for (i=0;i<Gh.nbsubdomains;i++){
+				bamgmesh->SubDomainsFromGeom[i*4+0]=2;
+				bamgmesh->SubDomainsFromGeom[i*4+1]=GetId(subdomains[i].edge)+1; //back to Matlab indexing
+				bamgmesh->SubDomainsFromGeom[i*4+2]=subdomains[i].direction;
+				bamgmesh->SubDomainsFromGeom[i*4+3]=Gh.subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*VerticesOnGeomVertex*/
+		if(verbose>5) _printf_("      writing VerticesOnGeomVertex\n");
+		bamgmesh->VerticesOnGeomVertexSize[0]=NbVerticesOnGeomVertex;
+		bamgmesh->VerticesOnGeomVertexSize[1]=2;
+		if (NbVerticesOnGeomVertex){
+			bamgmesh->VerticesOnGeomVertex=xNew<double>(2*NbVerticesOnGeomVertex);
+			for (i=0;i<NbVerticesOnGeomVertex;i++){
+				VertexOnGeom &v=VerticesOnGeomVertex[i];
+				_assert_(v.OnGeomVertex());
+				bamgmesh->VerticesOnGeomVertex[i*2+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomVertex[i*2+1]=Gh.GetId((GeomVertex*)v)+1; //back to Matlab indexing
+			}
+		}
+
+		/*VertexOnGeomEdge*/
+		if(verbose>5) _printf_("      writing VerticesOnGeomEdge\n");
+		bamgmesh->VerticesOnGeomEdgeSize[0]=NbVerticesOnGeomEdge;
+		bamgmesh->VerticesOnGeomEdgeSize[1]=3;
+		if (NbVerticesOnGeomEdge){
+			bamgmesh->VerticesOnGeomEdge=xNew<double>(3*NbVerticesOnGeomEdge);
+			for (i=0;i<NbVerticesOnGeomEdge;i++){
+				const VertexOnGeom &v=VerticesOnGeomEdge[i];
+				if (!v.OnGeomEdge()){
+					_error_("A vertices supposed to be OnGeomEdge is actually not");
+				}
+				bamgmesh->VerticesOnGeomEdge[i*3+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+1]=Gh.GetId((const GeomEdge*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+2]=(double)v; //absisce
+			}
+		}
+
+		/*EdgesOnGeomEdge*/
+		if(verbose>5) _printf_("      writing EdgesOnGeomEdge\n");
+		k=0;
+		for (i=0;i<nbe;i++){
+			if (edges[i].GeomEdgeHook) k=k+1;
+		}
+		bamgmesh->EdgesOnGeomEdgeSize[0]=k;
+		bamgmesh->EdgesOnGeomEdgeSize[1]=2;
+		if (k){
+			bamgmesh->EdgesOnGeomEdge=xNew<double>(2*(int)k);
+			int count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].GeomEdgeHook){
+					bamgmesh->EdgesOnGeomEdge[count*2+0]=(double)i+1; //back to Matlab indexing
+					bamgmesh->EdgesOnGeomEdge[count*2+1]=(double)Gh.GetId(edges[i].GeomEdgeHook)+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		/*Element Connectivity*/
+		if(verbose>5) _printf_("      writing Element connectivity\n");
+		bamgmesh->ElementConnectivitySize[0]=nbt-nbtout;
+		bamgmesh->ElementConnectivitySize[1]=3;
+		bamgmesh->ElementConnectivity=xNew<double>(3*(nbt-nbtout));
+		for (i=0;i<3*(nbt-nbtout);i++) bamgmesh->ElementConnectivity[i]=NAN;
+		num=0;
+		for (i=0;i<nbt;i++){
+			if (reft[i]>=0){
+				for (j=0;j<3;j++){
+					k=GetId(triangles[i].TriangleAdj(j));
+					if (reft[k]>=0){
+						_assert_(3*num+j<3*(nbt-nbtout));
+						bamgmesh->ElementConnectivity[3*num+j]=k+1; // back to Matlab indexing
+					}
+				}
+				num+=1;
+			}
+		}
+
+		/*ElementNodal Connectivity*/
+		if(verbose>5) _printf_("      writing Nodal element connectivity\n");
+		bamgmesh->NodalElementConnectivitySize[0]=nbv;
+		bamgmesh->NodalElementConnectivitySize[1]=connectivitymax_1;
+		bamgmesh->NodalElementConnectivity=xNew<double>(connectivitymax_1*nbv);
+		for (i=0;i<connectivitymax_1*nbv;i++) bamgmesh->NodalElementConnectivity[i]=NAN;
+		for (i=0;i<nbv;i++){
+			k=0;
+			for(j=head_1[i];j!=-1;j=next_1[j]){
+				_assert_(connectivitymax_1*i+k < connectivitymax_1*nbv);
+				bamgmesh->NodalElementConnectivity[connectivitymax_1*i+k]=floor((double)j/3)+1;
+				k++;
+			}
+		}
+
+		/*Nodal Connectivity*/
+		if(verbose>5) _printf_("      writing Nodal connectivity\n");
+		//chaining algorithm (again...)
+		int* head_2=NULL;
+		int* next_2=NULL;
+		int* connectivitysize_2=NULL;
+		int  connectivitymax_2=0;
+		i1=bamgmesh->IssmEdgesSize[0];
+		i2=bamgmesh->IssmEdgesSize[1];
+		head_2=xNew<int>(nbv);
+		next_2=xNew<int>(2*i1);
+		connectivitysize_2=xNew<int>(nbv);
+		//Initialization
+		for (i=0;i<nbv;i++) head_2[i]=-1;
+		for (i=0;i<nbv;i++) connectivitysize_2[i]=0;
+		k=0;
+		//Chains generation
+		for (i=0;i<i1;i++) {
+			for (j=0;j<2;j++){
+				int v=(int)bamgmesh->IssmEdges[i*i2+j]-1; //back to C indexing
+				if (k>2*i1-1 || k<0) _error_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
+				next_2[k]=head_2[v];
+				if (v>nbv-1 || v<0)   _error_("Index exceed matrix dimensions (v=" << v << " not in [0 " << nbv-1 << "])");
+				head_2[v]=k++;
+				connectivitysize_2[v]+=1;
+			}
+		}
+		//Get maximum connectivity
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_2[i]>connectivitymax_2) connectivitymax_2=connectivitysize_2[i];
+		}
+		//Build output
+		connectivitymax_2++;//add last column for size
+		bamgmesh->NodalConnectivitySize[0]=nbv;
+		bamgmesh->NodalConnectivitySize[1]=connectivitymax_2;
+		bamgmesh->NodalConnectivity=xNew<double>(connectivitymax_2*nbv);
+		for (i=0;i<connectivitymax_2*nbv;i++) bamgmesh->NodalConnectivity[i]=0;
+		for (i=0;i<nbv;i++){
+			k=0;
+			for(j=head_2[i];j!=-1;j=next_2[j]){
+				_assert_(connectivitymax_2*i+k < connectivitymax_2*nbv);
+				num=(int)bamgmesh->IssmEdges[int(j/2)*i2+0];
+				if (i+1==num){ //carefull, ElementEdge is in M indexing
+					//i is the first vertex of the edge, it is therefore connected to the second vertex
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=bamgmesh->IssmEdges[int(j/2)*i2+1];
+				}
+				else{
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=num;
+				}
+				k++;
+			}
+			bamgmesh->NodalConnectivity[connectivitymax_2*(i+1)-1]=k;
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) _printf_("      writing Cracked vertices\n");
+		bamgmesh->CrackedVerticesSize[0]=NbCrackedVertices;
+		bamgmesh->CrackedVerticesSize[1]=2;
+		if (NbCrackedVertices){
+			bamgmesh->CrackedVertices=xNew<double>(2*NbCrackedVertices);
+			for (i=0;i<NbCrackedVertices;i++){
+				bamgmesh->CrackedVertices[i*2+0]=CrackedVertices[i*2+0]+1; //M indexing
+				bamgmesh->CrackedVertices[i*2+1]=CrackedVertices[i*2+1]+1; //M indexing
+			}
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) _printf_("      writing Cracked vertices\n");
+		bamgmesh->CrackedEdgesSize[0]=NbCrackedEdges;
+		bamgmesh->CrackedEdgesSize[1]=4;
+		if (NbCrackedEdges){
+			bamgmesh->CrackedEdges=xNew<double>(2*NbCrackedEdges);
+			for (i=0;i<NbCrackedEdges;i++){
+				bamgmesh->CrackedEdges[i*2+0]=0;//CrackedEdges[i]->+1; //M indexing
+				bamgmesh->CrackedEdges[i*2+1]=0;//CrackedEdges[i]-]->+1; //M indexing
+			}
+		}
+
+		//clean up
+		xDelete<int>(connectivitysize_1);
+		xDelete<int>(head_1);
+		xDelete<int>(next_1);
+		xDelete<int>(connectivitysize_2);
+		xDelete<int>(head_2);
+		xDelete<int>(next_2);
+		delete [] reft;
+		delete [] numt;
+	}
+	/*}}}*/
+	void Mesh::ReadMetric(const BamgOpts* bamgopts) {/*{{{*/
+
+		/*Intermediary*/
+		int  i,j;
+
+		if(bamgopts->verbose>3) _printf_("      processing metric\n");
+		double hmin = Max(bamgopts->hmin,MinimalHmin());
+		double hmax = Min(bamgopts->hmax,MaximalHmax());
+		double coef = bamgopts->coeff;
+
+		//for now we only use j==3
+		j=3;
+
+		for (i=0;i<nbv;i++){
+			double h;
+			if (j == 1){
+				h=bamgopts->metric[i];
+				vertices[i].m=Metric(Max(hmin,Min(hmax, h*coef)));
+			}
+			else if (j==3){
+				//do not erase metric computed by hVertices
+				if (vertices[i].m.a11==1 && vertices[i].m.a21==0 && vertices[i].m.a22==1){
+					double a,b,c;	     
+					a=bamgopts->metric[i*3+0];
+					b=bamgopts->metric[i*3+1];
+					c=bamgopts->metric[i*3+2];
+					Metric M(a,b,c);
+					EigenMetric Vp(M/coef);
+
+					Vp.Maxh(hmax);
+					Vp.Minh(hmin);
+					vertices[i].m = Vp;
+				}
+			}
+		}
+	}
+	/*}}}*/
+	void Mesh::WriteMetric(BamgOpts* bamgopts) {/*{{{*/
+		int i;
+		xDelete<double>(bamgopts->metric);
+		bamgopts->metric=xNew<double>(3*nbv);
+		for (i=0;i<nbv;i++){
+			bamgopts->metric[i*3+0]=vertices[i].m.a11;
+			bamgopts->metric[i*3+1]=vertices[i].m.a21;
+			bamgopts->metric[i*3+2]=vertices[i].m.a22;
+		}
+	}
+	/*}}}*/
+	void Mesh::WriteIndex(int** pindex,int* pnels){/*{{{*/
+
+		/*Intermediary*/
+		int i,k;
+
+		/*output*/
+		int* index=NULL;
+		int  num=0;
+
+		/*Get number of triangles*/
+		k=0;
+		for (i=0;i<nbt;i++){
+			Triangle &t=triangles[i];
+			if(t.det>0) k++;
+		}
+
+		if (k){
+			index=xNew<int>(3*k);
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				if (t.det>0 && !(t.Hidden(0)||t.Hidden(1) || t.Hidden(2) )){
+					/*Remove triangles that have a bad aspect ratio*/
+					//if(t.Anisotropy()<2 & t.Length()<1.e+5){
+						index[num*3+0]=GetId(t[0])+1; //back to M indexing
+						index[num*3+1]=GetId(t[1])+1; //back to M indexing
+						index[num*3+2]=GetId(t[2])+1; //back to M indexing
+						num=num+1;
+					//}
+				}
+			}
+		}
+
+		/*Assign output pointers*/
+		*pindex=index;
+		*pnels=num;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectGeomMetric)*/
+
+		/*Get options*/
+		double anisomax = bamgopts->anisomax;
+		double errg     = bamgopts->errg;
+
+		double ss[2]={0.00001,0.99999};
+		double errC = 2*sqrt(2*errg);
+		double hmax = Gh.MaximalHmax();
+		double hmin = Gh.MinimalHmin();
+
+		//check that hmax is positive
+		_assert_(hmax>0); 
+
+		//errC cannot be higher than 1
+		if(errC>1) errC=1;
+
+		//Set all vertices to "on"
+		SetVertexFieldOn();
+
+		//loop over all the vertices on edges
+		for(int  i=0;i<nbe;i++){
+			for (int j=0;j<2;j++){
+
+				BamgVertex V;
+				VertexOnGeom GV;
+				Gh.ProjectOnCurve(edges[i],ss[j],V,GV);
+
+				GeomEdge* eg = GV;
+				double s = GV;
+				R2 tg;
+				double  R1= eg->R1tg(s,tg);
+				double  ht=hmax;
+				// err relative to the length of the edge
+				if (R1>1.0e-20) {  
+					ht = Min(Max(errC/R1,hmin),hmax);
+				}
+				double hn=Min(hmax,ht*anisomax);
+
+				if (ht<=0 || hn<=0){
+					_error_("ht<=0 || hn<=0");
+				}
+				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
+				Metric MVp(Vp);
+				edges[i][j].m.IntersectWith(MVp);
+			}
+		}
+		// the problem is for the vertex on vertex 
+	}
+	/*}}}*/
+	void Mesh::AddMetric(BamgOpts* bamgopts){/*{{{*/
+		//  Hessiantype = 0 =>  H is computed using double L2 projection
+		//  Hessiantype = 1 =>  H is computed with green formula
+
+		/*Options*/
+		int Hessiantype=bamgopts->Hessiantype;
+
+		if (Hessiantype==0){
+			BuildMetric0(bamgopts);
+		}
+		else if (Hessiantype==1){
+			BuildMetric1(bamgopts);
+		}
+		else{
+			_error_("Hessiantype " << Hessiantype << " not supported yet (1->use Green formula, 0-> double L2 projection)");
+		}
+	}
+	/*}}}*/
+	void Mesh::AddVertex( BamgVertex &s,Triangle* t, Icoor2* det3) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Add)*/
+		// -------------------------------
+		//             s2
+		//                               !
+		//             /|\               !
+		//            / | \              !
+		//           /  |  \             !
+		//    tt1   /   |   \ tt0        !
+		//         /    |s   \           !
+		//        /     .     \          !
+		//       /  .      `   \         !
+		//      / .           ` \        !
+		//      ----------------         !
+		//   s0       tt2       s1
+		//-------------------------------
+
+		/*Intermediaries*/
+		Triangle* tt[3];       //the three triangles
+		Icoor2 det3local[3];   //three determinants (integer)
+		int nbzerodet =0;      //number of zeros in det3
+		int izerodet=-1;       //egde containing the vertex s
+		int iedge; 
+
+		/*three vertices of t*/
+		BamgVertex &s0=(*t)[0];
+		BamgVertex &s1=(*t)[1];
+		BamgVertex &s2=(*t)[2];
+
+		//determinant of t
+		Icoor2 detOld=t->det;
+
+		/* infvertexindex = index of the infinite vertex (NULL)
+			if no infinite vertex (NULL) infvertexindex=-1
+			else if v_i is infinite, infvertexindex=i*/
+		int infvertexindex = &s0 ?  ((  &s1 ? ( &s2  ? -1 : 2) : 1  )) : 0;
+
+		//some checks
+		if(((infvertexindex <0 ) && (detOld <0)) ||  ((infvertexindex >=0) && (detOld >0)) ){
+			_error_("inconsistent configuration (Contact ISSM developers)");
+		}
+
+		// if det3 does not exist, build it 
+		if (!det3){ 
+			//allocate
+			det3 = det3local;
+			//if no infinite vertex
+			if (infvertexindex<0 ) {
+				det3[0]=bamg::det(s ,s1,s2);
+				det3[1]=bamg::det(s0,s ,s2);
+				det3[2]=bamg::det(s0,s1,s );}
+			else { 
+				// one of &s1  &s2  &s0 is NULL
+				det3[0]= &s0 ? -1 : bamg::det(s ,s1,s2) ;
+				det3[1]= &s1 ? -1 : bamg::det(s0,s ,s2) ;
+				det3[2]= &s2 ? -1 : bamg::det(s0,s1,s ) ;
+			}
+		}
+
+		if (!det3[0]) izerodet=0,nbzerodet++;
+		if (!det3[1]) izerodet=1,nbzerodet++;
+		if (!det3[2]) izerodet=2,nbzerodet++;
+
+		//if nbzerodet>0, point s is on an egde or on a vertex 
+		if  (nbzerodet>0){ 
+			/*s is on an edge*/
+			if (nbzerodet==1) {
+				iedge = OppositeEdge[izerodet];
+				AdjacentTriangle ta = t->Adj(iedge);
+
+				/*if the point is one the boundary 
+				  add the point in outside part */
+				if (t->det>=0){ // inside triangle
+					if (((Triangle*)ta)->det<0 ) {
+						// add in outside triangle 
+						AddVertex(s,( Triangle *)ta);
+						return;
+					}
+				}
+			}
+			else{
+				_error_("Cannot add a vertex more than once. Check duplicates");
+			}
+		}
+
+		// remove de MarkUnSwap edge
+		t->SetUnMarkUnSwap(0);
+		t->SetUnMarkUnSwap(1);
+		t->SetUnMarkUnSwap(2);
+
+		tt[0]= t;
+		tt[1]= &triangles[nbt++];
+		tt[2]= &triangles[nbt++];
+
+		if (nbt>maxnbt) _error_("Not enough triangles");
+
+		*tt[1]=*tt[2]=*t;
+		tt[0]->link=tt[1];
+		tt[1]->link=tt[2]; 
+
+		(*tt[0])(OppositeVertex[0])=&s;
+		(*tt[1])(OppositeVertex[1])=&s;
+		(*tt[2])(OppositeVertex[2])=&s;
+
+		tt[0]->det=det3[0];
+		tt[1]->det=det3[1];
+		tt[2]->det=det3[2];         
+
+		//  update adj des triangles externe 
+		tt[0]->SetAdjAdj(0);
+		tt[1]->SetAdjAdj(1);
+		tt[2]->SetAdjAdj(2);
+		//  update des adj des 3 triangle interne
+		const int i0 = 0;
+		const int i1= NextEdge[i0];
+		const int i2 = PreviousEdge[i0];
+
+		tt[i0]->SetAdj2(i2,tt[i2],i0);
+		tt[i1]->SetAdj2(i0,tt[i0],i1);
+		tt[i2]->SetAdj2(i1,tt[i1],i2);
+
+		tt[0]->SetSingleVertexToTriangleConnectivity();
+		tt[1]->SetSingleVertexToTriangleConnectivity();
+		tt[2]->SetSingleVertexToTriangleConnectivity();
+
+		// swap if the point s is on a edge
+		if(izerodet>=0) {
+			int rswap=tt[izerodet]->swap(iedge);
+
+			if (!rswap) {
+				_error_("swap the point s is on a edge");
+			}
+		}
+	}
+	/*}}}*/
+	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/BoundAnisotropy)*/
+
+		long int verbose=0;
+		double lminaniso = 1/ (Max(hminaniso*hminaniso,1e-100));
+
+		//display info
+		if (verbose > 1)  _printf_("   BoundAnisotropy by " << anisomax << "\n");
+
+		double h1=1.e30,h2=1e-30;
+		double coef = 1./(anisomax*anisomax);
+		double hn1=1.e30,hn2=1e-30,rnx =1.e-30,rx=0;  
+
+		//loop over all vertices
+		for (int i=0;i<nbv;i++){
+			EigenMetric Vp(vertices[i]);
+			double lmax=Vp.lmax();
+			Vp*=Min(lminaniso,lmax)/lmax;
+			Vp.BoundAniso2(coef);
+			vertices[i].m = Vp;
+
+			//info to be displayed
+			if (verbose>2){
+				h1 =Min(h1,Vp.lmin());
+				h2 =Max(h2,Vp.lmax());
+				hn1=Min(hn1,Vp.lmin());
+				hn2=Max(hn2,Vp.lmax());
+				rx =Max(rx,Vp.Aniso2());
+				rnx= Max(rnx,Vp.Aniso2());
+			}
+		}
+
+		//display info
+		if (verbose>2){
+			_printf_("      input:  Hmin = " << pow(h2,-0.5)  << ", Hmax = " << pow(h1,-0.5) << ", factor of anisotropy max  = " << pow(rx,0.5) << "\n");
+			_printf_("      output: Hmin = " << pow(hn2,-0.5) << ", Hmax = " << pow(hn1,-0.5)<< ", factor of anisotropy max  = " <<pow(rnx,0.5) << "\n");
+		}
+	}
+	/*}}}*/
+	void Mesh::BuildGeometryFromMesh(BamgOpts* bamgopts){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ConsGeometry)*/
+
+		/*Reconstruct Geometry from Mesh*/
+
+		/*Intermediary*/
+		int i,j,k,kk,it,jt;
+		int    verbose=0;
+		double cutoffradian=10*Pi/180;
+
+		/*Recover options*/
+		if (bamgopts){
+			verbose=bamgopts->verbose;
+			cutoffradian=bamgopts->MaxCornerAngle*Pi/180;
+		}
+
+		//display info
+		if (verbose>1) _printf_("   construction of the geometry from the 2d mesh\n");
+
+		//check that the mesh is not empty
+		if (nbt<=0 || nbv <=0 ) {
+			_error_("nbt or nbv is negative (Mesh empty?)");
+		}
+
+		//Gh is the geometry of the mesh (this), initialize MaxCornerAngle
+		if (cutoffradian>=0) Gh.MaxCornerAngle = cutoffradian;
+
+		/*Construction of the edges*/
+
+		//initialize st and edge4
+		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+		long*        st   = new long[nbt*3];
+
+		//initialize st as -1 (chaining algorithm)
+		for (i=0;i<nbt*3;i++) st[i]=-1;
+
+		//build edge4 (chain)
+		for (i=0;i<nbe;i++){
+			edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1]));
+		}
+		//check that there is no double edge
+		if (nbe !=  edge4->nb()){ 
+			delete [] st;
+			_error_("Some Double edge in the mesh, the number is " << nbe << ", nbe4=" << edge4->nb()); 
+		}
+		//keep nbe in nbeold
+		long nbeold = nbe;
+
+		//Go through the triangles and ass the edges in edge4 if they are not there yet
+		for (i=0;i<nbt;i++){
+			//3 edges per triangle
+			for  (j=0;j<3;j++) {
+				//Add Edge to edge4 (k=numberofedges in edge4)
+				long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]), GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+				long invisible = triangles[i].Hidden(j);
+
+				//if st[k] has not been changed yet, add 3*i+j (= vertex position in the index)
+				if(st[k]==-1) st[k]=3*i+j;
+
+				//else st[k]>=0 -> the edge already exist, check
+				else if(st[k]>=0) {
+					//check that it is not an edge on boundary (should not already exist)
+					if (triangles[i].TriangleAdj(j) || triangles[st[k]/3].TriangleAdj((int) (st[k]%3))){
+						_error_("problem in Geometry reconstruction: an edge on boundary is duplicated (double element?)");
+					}
+					//OK, the element is not on boundary, is belongs to 2 triangles -> build Adjacent triangles list
+					triangles[i].SetAdj2(j,triangles + st[k] / 3,(int) (st[k]%3));
+					if (invisible)  triangles[i].SetHidden(j);
+					// if k < nbe mark the edge as on Boundary (Locked)
+					if (k<nbe) {
+						triangles[i].SetLocked(j);
+					}
+					//set st[k] as negative so that the edge should not be called again
+					st[k]=-2-st[k]; 
+				}
+				//else (see 3 lines above), the edge has been called more than twice: return error
+				else {
+					_printf_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << "," << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles (" << k << ")\n");
+					_printf_("Edge " << j << " of triangle " << i << "\n");
+					_printf_("Edge " << (-st[k]+2)%3 << " of triangle " << (-st[k]+2)/3 << "\n");
+					_printf_("Edge " << triangles[(-st[k]+2)/3].NuEdgeTriangleAdj((int)((-st[k]+2)%3)) << " of triangle " << GetId(triangles[(-st[k]+2)/3].TriangleAdj((int)((-st[k]+2)%3))) << "\n");
+					_error_("An edge belongs to more than 2 triangles");
+				}	
+			}
+		}
+
+		//delete edge4
+		long nbedges = edge4->nb(); // the total number of edges 
+		delete edge4; edge4=NULL;
+
+		//display info
+		if(verbose>5) {
+			_printf_("         info on Mesh:\n");
+			_printf_("            - number of vertices    = " << nbv << "\n"); 
+			_printf_("            - number of triangles   = " << nbt << "\n"); 
+			_printf_("            - number of given edges = " << nbe << "\n"); 
+			_printf_("            - number of all edges   = " << nbedges << "\n"); 
+			_printf_("            - Euler number 1 - nb of holes = " << nbt-nbedges+nbv << "\n"); 
+		}
+
+		// check consistency of edge[].adj and geometrical required  vertices
+		k=0; kk=0;
+		for (i=0;i<nbedges;i++){
+			//internal edge
+			if (st[i] <-1) {
+				//get triangle number back
+				it =  (-2-st[i])/3;
+				//get edge position back
+				j  =  (int) ((-2-st[i])%3);
+				Triangle &tt=*triangles[it].TriangleAdj(j);
+				if (triangles[it].color != tt.color|| i < nbeold) k++;
+			}
+			//boundary edge (alone)
+			else if (st[i] >=0) 
+			 kk++;
+		}
+
+		/*Constructions of edges*/
+
+		k += kk;
+		kk=0;
+		if (k) {
+			nbe = k;
+			Edge* edgessave=edges;
+			edges = new Edge[nbe];
+			k =0;
+
+			//display info
+			if(verbose>4) _printf_("   Construction of the edges " << nbe << "\n");
+
+			for (i=0;i<nbedges;i++){ 
+				long  add= -1;
+
+				//internal edge (belongs to two triangles)
+				if (st[i] <-1){ 
+					it =  (-2-st[i])/3;
+					j  =  (int) ((-2-st[i])%3);
+					Triangle & tt = * triangles[it].TriangleAdj(j);
+					if (triangles[it].color !=  tt.color || i < nbeold) add=k++;
+				}
+				//boundary edge
+				else if (st[i] >=0){
+					it = st[i]/3;
+					j  = (int) (st[i]%3);
+					add=k++;
+				}
+				if (add>=0 && add < nbe){
+					edges[add].v[0] = &triangles[it][VerticesOfTriangularEdge[j][0]];
+					edges[add].v[1] = &triangles[it][VerticesOfTriangularEdge[j][1]];
+					edges[add].GeomEdgeHook=NULL; 
+					//if already existed
+					if (i<nbeold){
+						edges[add].ReferenceNumber=edgessave[i].ReferenceNumber; 		      
+						edges[add].GeomEdgeHook=edgessave[i].GeomEdgeHook; //  HACK to get required edges
+						_printf_("oh no...\n");
+					}
+					else
+					 edges[add].ReferenceNumber=Min(edges[add].v[0]->GetReferenceNumber(),edges[add].v[1]->GetReferenceNumber());
+				  }
+			}
+
+			//check that we have been through all edges
+			if (k!=nbe){
+				_error_("problem in edge construction process: k!=nbe (should not happen)");
+			}
+			//delete edgessave
+			if (edgessave) delete [] edgessave;
+		}
+
+		/*Color the vertices*/
+
+		//initialize color of all vertices as 0
+		for (i=0;i<nbv;i++) vertices[i].color =0;
+
+		//go through the edges and add a color to corresponding vertices
+		//(A vertex in 4 edges will have a color 4)
+		for (i=0;i<nbe;i++){
+		 for (j=0;j<2;j++) edges[i].v[j]->color++;
+		}
+
+		//change the color: if a vertex belongs to 2 edges -1, else -2
+		for (i=0;i<nbv;i++) {
+			vertices[i].color=(vertices[i].color ==2)? -1 : -2;
+		}
+
+		/*Build edges[i].adj: adjacency of each edge (if on the same curve)*/
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){ 
+				//get current vertex
+				BamgVertex* v=edges[i].v[j];
+				//get vertex color (i0)
+				long i0=v->color;
+				long j0;
+
+				//if color<0 (first time), no adjacent edge
+				if(i0<0) edges[i].adj[j]=NULL;
+
+				//if color=-1 (corner),change the vertex color as 2*i+j (position of the vertex in edges)
+				if(i0==-1) v->color=i*2+j;
+
+				//if color>=0 (i and i0 edge are adjacent by the vertex v)
+				else if (i0>=0) {
+					//get position of v in edges back
+					j0 =  i0%2; //column in edges
+					i0 =  i0/2; //line in edges
+
+					//check that we have the correct vertex
+					if (v!=edges[i0 ].v[j0]){
+						_error_("v!=edges[i0 ].v[j0]: this should not happen as the vertex belongs to this edge");
+					}
+
+					//Add adjacence
+					edges[i ].adj[j ]=edges +i0;
+					edges[i0].adj[j0]=edges +i ;
+
+					//change color to -3
+					v->color = -3;
+				}
+			}
+		}
+
+		/*Reconstruct subdomains info*/
+
+		//check that nbsubdomains is empty
+		if (nbsubdomains){
+			_error_("nbsubdomains should be 0");
+		}
+		nbsubdomains=0;
+
+		//color the subdomains
+		long* colorT= new long[nbt];
+		Triangle *tt,*t;
+
+		//initialize the color of each triangle as -1
+		for (it=0;it<nbt;it++) colorT[it]=-1;
+
+		//loop over the triangles
+		for (it=0;it<nbt;it++){
+
+			//if the triangle has not been colored yet:
+			if (colorT[it]<0){
+
+				//color = number of subdomains
+				colorT[it]=nbsubdomains;
+
+				//color all the adjacent triangles of T that share a non marked edge
+				int level =1;
+				int kolor=triangles[it].color;
+				st[0]=it; // stack 
+				st[1]=0;
+				k=1;
+				while (level>0){
+					if( (j=st[level]++)<3 ){ 
+						t = &triangles[st[level-1]];
+						tt=t->TriangleAdj((int)j);
+
+						//color the adjacent triangle
+						if ( ! t->Locked(j) && tt && (colorT[jt = GetId(tt)] == -1) && ( tt->color==kolor)) {
+							colorT[jt]=nbsubdomains;
+							st[++level]=jt;
+							st[++level]=0;
+							k++;
+						}
+					}
+					else level-=2;
+				}
+				nbsubdomains++;
+			}
+		}
+		if (verbose> 3) _printf_("      The Number of sub domain = " << nbsubdomains << "\n"); 
+
+		//build subdomains
+		long isd;
+		subdomains = new SubDomain[nbsubdomains];
+
+		//initialize subdomains[isd].head as 0
+		for (isd=0;isd<nbsubdomains;isd++) subdomains[isd].head =0;
+
+		k=0;
+		for (it=0;it<nbt;it++){
+			for (int j=0;j<3;j++){
+				tt=triangles[it].TriangleAdj(j);
+				if ((!tt || tt->color != triangles[it].color) && !subdomains[isd=colorT[it]].head){
+					subdomains[isd].head = triangles+it;
+					subdomains[isd].ReferenceNumber =  triangles[it].color;
+					subdomains[isd].direction = j; // hack
+					subdomains[isd].edge = 0;
+					k++;
+				}
+			}
+		}
+		//check that we have been through all subdomains
+		if (k!= nbsubdomains){
+			delete [] colorT;
+			_error_("k!= nbsubdomains");
+		}
+		//delete colorT and st
+		delete [] colorT;
+		delete [] st;
+
+		/*Reconstruct Geometry Gh*/
+
+		//build colorV -1 for all vertex and 0 for the vertices belonging to edges
+		long* colorV = new long[nbv];
+		for (i=0;i<nbv;i++) colorV[i]=-1;
+		for (i=0;i<nbe;i++){
+		 for ( j=0;j<2;j++) colorV[GetId(edges[i][j])]=0;
+		}
+		//number the vertices belonging to edges
+		k=0;
+		for (i=0;i<nbv;i++){
+		 if(!colorV[i]) colorV[i]=k++;
+		}
+
+		//Build Gh
+		Gh.nbv=k;
+		Gh.nbe = nbe;
+		Gh.vertices = new GeomVertex[k];
+		Gh.edges = new GeomEdge[nbe];
+		Gh.nbsubdomains = nbsubdomains;
+		Gh.subdomains = new GeomSubDomain[nbsubdomains];
+		if (verbose>3) _printf_("   number of vertices = " << Gh.nbv << "\n   number of edges = " << Gh.nbe << "\n");
+		NbVerticesOnGeomVertex = Gh.nbv;
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		NbVerticesOnGeomEdge =0;
+		VerticesOnGeomEdge =0;
+
+		//Build VertexOnGeom
+		for (i=0;i<nbv;i++){
+			if((j=colorV[i])>=0){
+				BamgVertex & v = Gh.vertices[j];
+				v = vertices[i];
+				v.color =0;
+				VerticesOnGeomVertex[j] = VertexOnGeom(vertices[i], Gh.vertices[j]);
+			}
+		}
+
+		//Buid pmin and pmax of Gh (extrema coordinates)
+		Gh.pmin =  Gh.vertices[0].r;
+		Gh.pmax =  Gh.vertices[0].r;
+		// recherche des extrema des vertices pmin,pmax
+		for (i=0;i<Gh.nbv;i++) {
+			Gh.pmin.x = Min(Gh.pmin.x,Gh.vertices[i].r.x);
+			Gh.pmin.y = Min(Gh.pmin.y,Gh.vertices[i].r.y);
+			Gh.pmax.x = Max(Gh.pmax.x,Gh.vertices[i].r.x);
+			Gh.pmax.y = Max(Gh.pmax.y,Gh.vertices[i].r.y);
+		}
+		R2 DD05 = (Gh.pmax-Gh.pmin)*0.05;
+		Gh.pmin -=  DD05;
+		Gh.pmax +=  DD05;
+
+		//Build Gh.coefIcoor
+		Gh.coefIcoor= (MaxICoor)/(Max(Gh.pmax.x-Gh.pmin.x,Gh.pmax.y-Gh.pmin.y));
+		if (Gh.coefIcoor<=0){
+			delete [] colorV;
+			_error_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
+		}
+
+		/*Build Gh.edges*/
+
+		//initialize len as 0
+		double * len = new double[Gh.nbv];
+		for(i=0;i<Gh.nbv;i++) len[i]=0;
+
+		//initialize edge4 again
+		edge4= new SetOfEdges4(nbe,nbv);  
+		double hmin = HUGE_VAL;
+		int kreq=0;
+		for (i=0;i<nbe;i++){
+
+			long i0 = GetId(edges[i][0]);
+			long i1 = GetId(edges[i][1]);
+			long j0 = colorV[i0];
+			long j1 = colorV[i1];
+
+			Gh.edges[i].v[0] = Gh.vertices +  j0;
+			Gh.edges[i].v[1] = Gh.vertices +  j1;
+
+			Gh.edges[i].type = 0;
+
+			Gh.edges[i].tg[0]=R2();
+			Gh.edges[i].tg[1]=R2();
+
+			bool required= edges[i].GeomEdgeHook; 
+			if(required) kreq++;
+			edges[i].GeomEdgeHook =  Gh.edges + i;
+			if(required){
+				Gh.edges[i].v[0]->SetRequired();
+				Gh.edges[i].v[1]->SetRequired();
+				Gh.edges[i].SetRequired();
+			}
+
+			R2 x12 = Gh.vertices[j0].r-Gh.vertices[j1].r;
+			double l12=Norme2(x12);        
+			hmin = Min(hmin,l12);
+
+			Gh.vertices[j1].color++;
+			Gh.vertices[j0].color++;
+
+			len[j0]+= l12;
+			len[j1] += l12;
+			hmin = Min(hmin,l12);
+			Gh.edges[i].ReferenceNumber  = edges[i].ReferenceNumber;
+
+			k = edge4->SortAndAdd(i0,i1);
+			if (k != i){
+				delete [] len;
+				delete [] colorV;
+				_error_("problem in Edge4 construction: k != i");
+			}
+		}
+
+		//Build metric for all vertices of Gh
+		for (i=0;i<Gh.nbv;i++){
+		 if (Gh.vertices[i].color > 0) 
+		  Gh.vertices[i].m=  Metric(len[i] /(double) Gh.vertices[i].color);
+		 else 
+		  Gh.vertices[i].m=  Metric(hmin);
+		}
+		//delete len
+		delete [] len;
+
+		//Build Gh.subdomains
+		for (i=0;i<nbsubdomains;i++){
+			it = GetId(subdomains[i].head);
+			j = subdomains[i].direction;
+			long i0 = GetId(triangles[it][VerticesOfTriangularEdge[j][0]]);
+			long i1 = GetId(triangles[it][VerticesOfTriangularEdge[j][1]]);
+			k = edge4->SortAndFind(i0,i1);
+			_assert_(k>=0);
+			subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
+			subdomains[i].edge = edges+k;
+			Gh.subdomains[i].edge = Gh.edges + k;
+			Gh.subdomains[i].direction  =  subdomains[i].direction;
+			Gh.subdomains[i].ReferenceNumber =  subdomains[i].ReferenceNumber;
+		}
+
+		delete edge4;
+		delete [] colorV;
+
+		//unset adj
+		for (i=0;i<nbt;i++){
+			for ( j=0;j<3;j++){
+				triangles[i].SetAdj2(j,0,triangles[i].GetAllflag(j));
+			}
+		}
+
+	}
+	/*}}}*/
+	void Mesh::BuildMetric0(BamgOpts* bamgopts){/*{{{*/
+
+		/*Options*/
+		double* s=NULL;
+		long    nbsol;
+		int     verbose;
+
+		int   i,j,k,iA,iB,iC;
+		int   iv;
+
+		/*Recover options*/
+		verbose=bamgopts->verbose;
+
+		/*Get and process fields*/
+		s=bamgopts->field;
+		nbsol=bamgopts->fieldSize[1];
+
+		/*Check size*/
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  sumareas = new double[nbv];
+		double*  alpha= new double[nbt*3];
+		double*  beta = new double[nbt*3];
+		double*  dx_elem    = new double[nbt];
+		double*  dy_elem    = new double[nbt];
+		double*  dx_vertex  = new double[nbv];
+		double*  dy_vertex  = new double[nbv];
+		double*  dxdx_elem  = new double[nbt];
+		double*  dxdy_elem  = new double[nbt];
+		double*  dydy_elem  = new double[nbt];
+		double*  dxdx_vertex= new double[nbv];
+		double*  dxdy_vertex= new double[nbv];
+		double*  dydy_vertex= new double[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_printf_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")\n");
+		}
+
+		//first, build the chains that will be used for the Hessian computation, as weel as the area of each element
+		int* head_s=NULL;
+		head_s=xNew<int>(nbv);
+		int* next_p=NULL;
+		next_p=xNew<int>(3*nbt);
+		int  p=0;
+		//initialization
+		for(i=0;i<nbv;i++){
+			sumareas[i]=0;
+			head_s[i]=-1;
+		}
+		for(i=0;i<nbt;i++){
+
+			//lopp over the real triangles (no boundary elements)
+			if(triangles[i].link){ 
+
+				//get current triangle t
+				const Triangle &t=triangles[i];
+
+				// coor of 3 vertices 
+				R2 A=t[0];
+				R2 B=t[1];
+				R2 C=t[2];
+
+				//compute triangle determinant (2*Area)
+				double dett = bamg::Area2(A,B,C);
+				detT[i]=dett;
+
+				/*The nodal functions are such that for a vertex A:
+				 *    N_A(x,y)=alphaA x + beta_A y +gamma_A
+				 *    N_A(A) = 1,   N_A(B) = 0,   N_A(C) = 0
+				 * solving this system of equation (determinant = 2Area(T) != 0 if A,B and C are not inlined)
+				 * leads to:
+				 *    N_A = (xB yC - xC yB + x(yB-yC) +y(xC-xB))/(2*Area(T))
+				 * and this gives:
+				 *    alpha_A = (yB-yC)/(2*Area(T))*/
+				alpha[i*3+0]=(B.y-C.y)/dett;
+				alpha[i*3+1]=(C.y-A.y)/dett;
+				alpha[i*3+2]=(A.y-B.y)/dett;
+				beta[ i*3+0]=(C.x-B.x)/dett;
+				beta[ i*3+1]=(A.x-C.x)/dett;
+				beta[ i*3+2]=(B.x-A.x)/dett;
+
+				//compute chains
+				for(j=0;j<3;j++){
+					k=GetId(triangles[i][j]);
+					next_p[p]=head_s[k];
+					head_s[k]=p++;
+
+					//add area to sumareas
+					sumareas[k]+=dett;
+				}
+
+			}
+		}
+
+		//for all Solutions
+		for (int nusol=0;nusol<nbsol;nusol++) {
+			double smin=ss[nusol],smax=ss[nusol];
+
+			//get min(s), max(s) and initialize Hessian (dxdx,dxdy,dydy)
+			for ( iv=0,k=0; iv<nbv; iv++){
+				smin=Min(smin,ss[iv*nbsol+nusol]);
+				smax=Max(smax,ss[iv*nbsol+nusol]);
+			}
+			double sdelta=smax-smin;
+			double absmax=Max(Abs(smin),Abs(smax));
+
+			//display info
+			if(verbose>2) _printf_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta << "\n");
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20)){
+				_printf_("      Solution " << nusol << " is constant, skipping...\n");
+				continue;
+			}
+
+			//initialize the hessian and gradient matrices
+			for ( iv=0,k=0; iv<nbv; iv++) dxdx_vertex[iv]=dxdy_vertex[iv]=dydy_vertex[iv]=dx_vertex[iv]=dy_vertex[iv]=0;
+
+			//1: Compute gradient for each element (exact)
+			for (i=0;i<nbt;i++){
+				if(triangles[i].link){
+					// number of the 3 vertices
+					iA = GetId(triangles[i][0]);
+					iB = GetId(triangles[i][1]);
+					iC = GetId(triangles[i][2]);
+
+					// value of the P1 fonction on 3 vertices 
+					sA = ss[iA*nbsol+nusol];
+					sB = ss[iB*nbsol+nusol];
+					sC = ss[iC*nbsol+nusol];
+
+					//gradient = (sum alpha_i s_i, sum_i beta_i s_i)
+					dx_elem[i]=sA*alpha[3*i+0]+sB*alpha[3*i+1]+sC*alpha[3*i+2];
+					dy_elem[i]=sA*beta[ 3*i+0]+sB*beta[ 3*i+1]+sC*beta[ 3*i+2];
+				}
+			}
+
+			//2: then compute a gradient for each vertex using a P2 projection
+			for(i=0;i<nbv;i++){
+				for(p=head_s[i];p!=-1;p=next_p[p]){
+					//Get triangle number
+					k=(long)(p/3);
+					dx_vertex[i]+=dx_elem[k]*detT[k]/sumareas[i];
+					dy_vertex[i]+=dy_elem[k]*detT[k]/sumareas[i];
+				}
+			}
+
+			//3: compute Hessian matrix on each element
+			for (i=0;i<nbt;i++){
+				if(triangles[i].link){
+					// number of the 3 vertices
+					iA = GetId(triangles[i][0]);
+					iB = GetId(triangles[i][1]);
+					iC = GetId(triangles[i][2]);
+
+					//Hessian
+					dxdx_elem[i]=dx_vertex[iA]*alpha[3*i+0]+dx_vertex[iB]*alpha[3*i+1]+dx_vertex[iC]*alpha[3*i+2];
+					dxdy_elem[i]=dy_vertex[iA]*alpha[3*i+0]+dy_vertex[iB]*alpha[3*i+1]+dy_vertex[iC]*alpha[3*i+2];
+					dydy_elem[i]=dy_vertex[iA]*beta[3*i+0]+dy_vertex[iB]*beta[3*i+1]+dy_vertex[iC]*beta[3*i+2];
+				}
+			}
+
+			//4: finaly compute Hessian on each vertex using the second P2 projection
+			for(i=0;i<nbv;i++){
+				for(p=head_s[i];p!=-1;p=next_p[p]){
+					//Get triangle number
+					k=(long)(p/3);
+					dxdx_vertex[i]+=dxdx_elem[k]*detT[k]/sumareas[i];
+					dxdy_vertex[i]+=dxdy_elem[k]*detT[k]/sumareas[i];
+					dydy_vertex[i]+=dydy_elem[k]*detT[k]/sumareas[i];
+				}
+			}
+
+			/*Compute Metric from Hessian*/
+			for ( iv=0;iv<nbv;iv++){
+				vertices[iv].MetricFromHessian(dxdx_vertex[iv],dxdy_vertex[iv],dydy_vertex[iv],smin,smax,ss[iv*nbsol+nusol],bamgopts->err[nusol],bamgopts);
+			}
+
+		}//for all solutions
+
+		//clean up
+		xDelete<int>(head_s);
+		xDelete<int>(next_p);
+		delete [] detT;
+		delete [] alpha;
+		delete [] beta;
+		delete [] sumareas;
+		delete [] dx_elem;
+		delete [] dy_elem;
+		delete [] dx_vertex;
+		delete [] dy_vertex;
+		delete [] dxdx_elem;
+		delete [] dxdy_elem;
+		delete [] dydy_elem;
+		delete [] dxdx_vertex;
+		delete [] dxdy_vertex;
+		delete [] dydy_vertex;
+	}
+	/*}}}*/
+	void Mesh::BuildMetric1(BamgOpts* bamgopts){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectConsMetric)*/
+
+		/*Options*/
+		double* s=NULL;
+		long nbsol;
+		int NbJacobi;
+		int verbose;
+
+		/*Recover options*/
+		verbose=bamgopts->verbose;
+		NbJacobi=bamgopts->nbjacobi;
+
+		/*Get and process fields*/
+		s=bamgopts->field;
+		nbsol=bamgopts->fieldSize[1];
+
+		/*Check size*/
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		long    i,k,iA,iB,iC,iv;
+		R2      O(0,0);
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  Mmass= new double[nbv];
+		double*  Mmassxx= new double[nbv];
+		double*  dxdx= new double[nbv];
+		double*  dxdy= new double[nbv];
+		double*  dydy= new double[nbv];
+		double*  workT= new double[nbt];
+		double*  workV= new double[nbv];
+		int*    OnBoundary = new int[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_printf_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")\n");
+		}
+
+		//initialize Mmass, OnBoundary and Massxx by zero
+		for (iv=0;iv<nbv;iv++){
+			Mmass[iv]=0;
+			OnBoundary[iv]=0;
+			Mmassxx[iv]=0;
+		}
+
+		//Build detT Mmas Mmassxx workT and OnBoundary
+		for (i=0;i<nbt;i++){ 
+
+			//lopp over the real triangles (no boundary elements)
+			if(triangles[i].link){ 
+
+				//get current triangle t
+				const Triangle &t=triangles[i];
+
+				// coor of 3 vertices 
+				R2 A=t[0];
+				R2 B=t[1];
+				R2 C=t[2];
+
+				// number of the 3 vertices
+				iA = GetId(t[0]);
+				iB = GetId(t[1]);
+				iC = GetId(t[2]);
+
+				//compute triangle determinant (2*Area)
+				double dett = bamg::Area2(A,B,C);
+				detT[i]=dett;
+				dett /= 6;
+
+				// construction of OnBoundary (flag=1 if on boundary, else 0)
+				int nbb=0;
+				for(int j=0;j<3;j++){
+					//get adjacent triangle
+					Triangle *ta=t.Adj(j);
+					//if there is no adjacent triangle, the edge of the triangle t is on boundary
+					if ( !ta || !ta->link){
+						//mark the two vertices of the edge as OnBoundary
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][0]])]=1;
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][1]])]=1;
+						nbb++;
+					}
+				}
+
+				//number of vertices on boundary for current triangle t
+				workT[i] = nbb;
+
+				//Build Mmass Mmass[i] = Mmass[i] + Area/3
+				Mmass[iA] += dett;
+				Mmass[iB] += dett;
+				Mmass[iC] += dett;
+
+				//Build Massxx = Mmass
+				Mmassxx[iA] += dett;
+				Mmassxx[iB] += dett;
+				Mmassxx[iC] += dett;
+			}
+
+			//else: the triangle is a boundary triangle -> workT=-1
+			else workT[i]=-1;
+		}
+
+		//for all Solution  
+		for (int nusol=0;nusol<nbsol;nusol++) {
+
+			double smin=ss[nusol],smax=ss[nusol];
+			double h1=1.e30,h2=1e-30,rx=0;
+			double hn1=1.e30,hn2=1e-30,rnx =1.e-30;  
+
+			//get min(s), max(s) and initialize Hessian (dxdx,dxdy,dydy)
+			for ( iv=0,k=0; iv<nbv; iv++ ){
+				dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+				smin=Min(smin,ss[iv*nbsol+nusol]);
+				smax=Max(smax,ss[iv*nbsol+nusol]);
+			}
+			double sdelta=smax-smin;
+			double absmax=Max(Abs(smin),Abs(smax));
+
+			//display info
+			if(verbose>2) _printf_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta << ", number of fields = " << nbsol << "\n");
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20) ){
+				if (verbose>2) _printf_("      Solution " << nusol << " is constant, skipping...\n");
+				continue;
+			}
+
+			//pointer toward ss that is also a pointer toward s (solutions)
+			double* sf=ss; 
+
+				//initialize the hessian matrix
+				for ( iv=0,k=0; iv<nbv; iv++) dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+
+				//loop over the triangles
+				for (i=0;i<nbt;i++){
+
+					//for real all triangles 
+					if(triangles[i].link){
+
+						// coor of 3 vertices 
+						R2 A=triangles[i][0];
+						R2 B=triangles[i][1];
+						R2 C=triangles[i][2];
+
+						//warning: the normal is internal and the size is the length of the edge
+						R2 nAB = Orthogonal(B-A);
+						R2 nBC = Orthogonal(C-B);
+						R2 nCA = Orthogonal(A-C);
+						//note that :  nAB + nBC + nCA == 0 
+
+						// number of the 3 vertices
+						iA = GetId(triangles[i][0]);
+						iB = GetId(triangles[i][1]);
+						iC = GetId(triangles[i][2]);
+
+						// for the test of  boundary edge
+						// the 3 adj triangles 
+						Triangle *tBC = triangles[i].TriangleAdj(OppositeEdge[0]);
+						Triangle *tCA = triangles[i].TriangleAdj(OppositeEdge[1]);
+						Triangle *tAB = triangles[i].TriangleAdj(OppositeEdge[2]);
+
+						// value of the P1 fonction on 3 vertices 
+						sA = ss[iA*nbsol+nusol];
+						sB = ss[iB*nbsol+nusol];
+						sC = ss[iC*nbsol+nusol];
+
+						/*The nodal functions are such that for a vertex A:
+						  N_A(x,y)=alphaA x + beta_A y +gamma_A
+						  N_A(A) = 1,   N_A(B) = 0,   N_A(C) = 0
+						  solving this system of equation (determinant = 2Area(T) != 0 if A,B and C are not inlined)
+						  leads to:
+						  N_A = (xB yC - xC yB + x(yB-yC) +y(xC-xB))/(2*Area(T))
+						  and this gives:
+						  alpha_A = (yB-yC)/(2*Area(T))
+						  beta_A = (xC-xB)/(2*Area(T))
+						  and therefore:
+						  grad N_A = nA / detT
+						  for an interpolation of a solution s:
+						  grad(s) = s * sum_{i=A,B,C} grad(N_i) */
+
+						R2 Grads=(nAB*sC+nBC*sA+nCA*sB)/detT[i];
+
+						//Use Green to compute Hessian Matrix
+
+						// if edge on boundary no contribution  => normal = 0
+						if ( !tBC || !tBC->link ) nBC=O;
+						if ( !tCA || !tCA->link ) nCA=O;
+						if ( !tAB || !tAB->link ) nAB=O;
+
+						// remark we forgot a 1/2 because
+						//       int_{edge} w_i = 1/2 if i is in edge 
+						//                         0  if not
+						// if we don't take the  boundary 
+						dxdx[iA] += ( nCA.x + nAB.x ) *Grads.x;
+						dxdx[iB] += ( nAB.x + nBC.x ) *Grads.x;
+						dxdx[iC] += ( nBC.x + nCA.x ) *Grads.x;
+
+						//warning optimization (1) the division by 2 is done on the metric construction
+						dxdy[iA] += (( nCA.y + nAB.y ) *Grads.x + ( nCA.x + nAB.x ) *Grads.y) ;
+						dxdy[iB] += (( nAB.y + nBC.y ) *Grads.x + ( nAB.x + nBC.x ) *Grads.y) ;
+						dxdy[iC] += (( nBC.y + nCA.y ) *Grads.x + ( nBC.x + nCA.x ) *Grads.y) ; 
+
+						dydy[iA] += ( nCA.y + nAB.y ) *Grads.y;
+						dydy[iB] += ( nAB.y + nBC.y ) *Grads.y;
+						dydy[iC] += ( nBC.y + nCA.y ) *Grads.y;
+
+					} // for real all triangles 
+				}
+
+				long kk=0;
+				for ( iv=0,k=0 ; iv<nbv; iv++){
+					if(Mmassxx[iv]>0){
+						dxdx[iv] /= 2*Mmassxx[iv];
+						// warning optimization (1) on term dxdy[iv]*ci/2 
+						dxdy[iv] /= 4*Mmassxx[iv];
+						dydy[iv] /= 2*Mmassxx[iv];
+						// Compute the matrix with abs(eigen value)
+						Metric M(dxdx[iv], dxdy[iv], dydy[iv]);
+						EigenMetric Vp(M);
+						Vp.Abs();
+						M = Vp;
+						dxdx[iv] = M.a11;
+						dxdy[iv] = M.a21;
+						dydy[iv] = M.a22;
+					}
+					else kk++;
+				}
+
+				// correction of second derivative
+				// by a laplacien
+				double* dd;
+				for (int xy = 0;xy<3;xy++) {
+					if      (xy==0) dd=dxdx;
+					else if (xy==1) dd=dxdy;
+					else if (xy==2) dd=dydy;
+					else    _error_("not supported yet");
+					// do leat 2 iteration for boundary problem
+					for (int ijacobi=0;ijacobi<Max(NbJacobi,2);ijacobi++){
+						for (i=0;i<nbt;i++) 
+						 if(triangles[i].link){// the real triangles 
+							 // number of the 3 vertices
+							 iA = GetId(triangles[i][0]);
+							 iB = GetId(triangles[i][1]);
+							 iC = GetId(triangles[i][2]);
+							 double cc=3;
+							 if(ijacobi==0)
+							  cc = Max((double) ((Mmassxx[iA]>0)+(Mmassxx[iB]>0)+(Mmassxx[iC]>0)),1.);
+							 workT[i] = (dd[iA]+dd[iB]+dd[iC])/cc;
+						 }
+						for (iv=0;iv<nbv;iv++) workV[iv]=0;
+
+						for (i=0;i<nbt;i++){ 
+							if(triangles[i].link){ // the real triangles 
+								// number of the 3 vertices
+								iA = GetId(triangles[i][0]);
+								iB = GetId(triangles[i][1]);
+								iC = GetId(triangles[i][2]);
+								double cc =  workT[i]*detT[i];
+								workV[iA] += cc;
+								workV[iB] += cc;
+								workV[iC] += cc;
+							}
+						}
+
+						for (iv=0;iv<nbv;iv++){
+							if( ijacobi<NbJacobi || OnBoundary[iv]){
+								dd[iv] = workV[iv]/(Mmass[iv]*6);
+							}
+						}
+					}
+				}
+
+				/*Compute Metric from Hessian*/
+				for ( iv=0;iv<nbv;iv++){
+					vertices[iv].MetricFromHessian(dxdx[iv],dxdy[iv],dydy[iv],smin,smax,ss[iv*nbsol+nusol],bamgopts->err[nusol],bamgopts);
+				}
+
+		}// end for all solution 
+
+		delete [] detT;
+		delete [] Mmass;
+		delete [] dxdx;
+		delete [] dxdy;
+		delete [] dydy;
+		delete []  workT;
+		delete [] workV;
+		delete [] Mmassxx;
+		delete []  OnBoundary;
+
+	}
+	/*}}}*/
+	void Mesh::CrackMesh(BamgOpts* bamgopts) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CrackMesh)*/
+
+		/*Intermediary*/
+		int i,j,k,num,count;
+		int i1,i2;
+		int j1,j2;
+
+		/*Options*/
+		int verbose=bamgopts->verbose;
+
+		//  computed the number of cracked edge
+		for (k=i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook->Cracked()) k++;
+		}
+
+		//Return if no edge is cracked
+		if(k==0) return;
+		if (verbose>4) _printf_("      number of Cracked Edges = " << k << "\n");
+
+		//Initialize Cracked edge
+		NbCrackedEdges=k;
+		CrackedEdges=new CrackedEdge[k];
+
+		//Compute number of Cracked Vertices
+		k=0;
+		NbCrackedVertices=0;
+
+		int* splitvertex=new int[nbv];
+		for (i=0;i<nbv;i++) splitvertex[i]=0;
+
+		for (i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook->Cracked()){
+
+				//Fill edges fields of CrackedEdges
+				CrackedEdges[k  ].E =edges[i].GeomEdgeHook;
+				CrackedEdges[k++].e1=&edges[i];
+
+				//Get number of the two vertices on the edge
+				i1=GetId(edges[i][0]);
+				i2=GetId(edges[i][1]);
+				_assert_(i1>=0 && i1<nbv && i2>=0 && i2<nbv);
+				splitvertex[i1]++;
+				splitvertex[i2]++;
+
+				//If the vertex has already been flagged once, it is a cracked vertex (tip otherwise)
+				if (splitvertex[i1]==2) NbCrackedVertices++;
+				if (splitvertex[i2]==2) NbCrackedVertices++;
+
+				//The vertex cannot be marked more than twice
+				if (splitvertex[i1]==3 || splitvertex[i2]==3){
+					delete [] splitvertex;
+					_error_("Crossing rifts not supported yet");
+				}
+			}
+		}
+		_assert_(k==NbCrackedEdges);
+
+		//Add new vertices
+		if (verbose>4) _printf_("      number of Cracked Vertices = " << NbCrackedVertices << "\n");
+		if (NbCrackedVertices){
+			CrackedVertices=xNew<long>(2*NbCrackedVertices);
+			num=0;
+			for (i=0;i<nbv;i++){
+				if (splitvertex[i]==2){
+					CrackedVertices[num*2+0]=i;      //index of first vertex
+					CrackedVertices[num*2+1]=nbv+num;//index of new vertex
+					num++;
+				}
+			}
+			_assert_(num==NbCrackedVertices);
+		}
+		delete [] splitvertex;
+
+		//Now, find the triangles that hold a cracked edge
+		CreateSingleVertexToTriangleConnectivity();
+
+		long* Edgeflags=new long[NbCrackedEdges];
+		for(i=0;i<NbCrackedEdges;i++) Edgeflags[i]=0;
+
+		for(i=0;i<NbCrackedEdges;i++){
+			//Get the numbers of the 2 vertices of the crren cracked edge
+			i1=GetId((*CrackedEdges[i].e1)[0]);
+			i2=GetId((*CrackedEdges[i].e1)[1]);
+
+			//find a triangle holding the vertex i1 (first vertex of the ith cracked edge)
+			Triangle* tbegin=vertices[i1].t;
+			k=vertices[i1].IndexInTriangle;//local number of i in triangle tbegin
+			_assert_(GetId((*tbegin)[k])==GetId(vertices[i1]));
+
+			//Now, we are going to go through the adjacent triangle that hold i1 till
+			//we find one that has the cracked edge
+			AdjacentTriangle ta(tbegin,EdgesVertexTriangle[k][0]);
+			count=0;
+			do {
+				for(j=0;j<3;j++){
+					//Find the position of i1 in the triangle index
+					if (GetId((*ta.t)[j])==i1){
+						j1=j;
+						break;
+					}
+				}
+				for(j=0;j<3;j++){
+					//Check wether i2 is also in the triangle index
+					if (GetId((*ta.t)[j])==i2){
+						j2=j;
+						//Invert j1 and j2 if necessary
+						if ((j1+1)%3==j2){
+							int j3=j1;
+							j1=j2;
+							j2=j3;
+						}
+						if (Edgeflags[i]==0){
+							//first element
+							CrackedEdges[i].a=ta.t;
+							CrackedEdges[i].length=Norme2((*ta.t)[j1].r-(*ta.t)[j2].r);
+							CrackedEdges[i].normal=Orthogonal((*ta.t)[j1].r-(*ta.t)[j2].r);
+						}
+						else{
+							//Second element -> to renumber
+							CrackedEdges[i].b=ta.t;
+							CrackedEdges[i].length=Norme2((*ta.t)[j1].r-(*ta.t)[j2].r);
+							CrackedEdges[i].normal=Orthogonal((*ta.t)[j1].r-(*ta.t)[j2].r);
+						}
+						Edgeflags[i]++;
+						break;
+					}
+				}
+				//_printf_(element_renu[GetId(ta.t)] << " -> " << GetId((*ta.t)[0])+1 << " " << GetId((*ta.t)[1])+1 << " " << GetId((*ta.t)[2])+1 << ", edge [" << i1 << "->" << j1 << " " << i2 << "->" << j2 << "]\n");
+				ta = Next(ta).Adj(); 
+				if (count++>50) _error_("Maximum number of iteration exceeded");
+			}while ((tbegin != ta)); 
+		}
+
+		//Check EdgeFlag
+		for(i=0;i<NbCrackedEdges;i++){
+			if (Edgeflags[i]!=2){
+				_error_("A problem occured: at least one crack edge (number " << i+1 << ") does not belong to 2 elements");
+			}
+		}
+		delete [] Edgeflags;
+
+		//Reset BamgVertex to On
+		SetVertexFieldOn();
+
+	}
+	/*}}}*/
+	void Mesh::Echo(void) {/*{{{*/
+
+		int i;
+
+		_printf_("Mesh Echo:\n");
+		_printf_("   nbv = " << nbv << "\n");
+		_printf_("   nbt = " << nbt << "\n");
+		_printf_("   nbe = " << nbe << "\n");
+		_printf_("   nbq = " << nbq << "\n");
+		_printf_("   index:\n");
+		for (i=0;i<nbt;i++){
+			_printf_("   " << setw(4) << i+1 << ": [" 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][0])+1:0) << " " 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][1])+1:0) << " " 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][2])+1:0) << "]");
+		}
+		_printf_("   coordinates:\n");
+		for (i=0;i<nbv;i++){
+			_printf_("   " << setw(4) << i+1 << ": [" << vertices[i].r.x << " " << vertices[i].r.y << "]\n");
+		}
+
+	}
+	/*}}}*/
+	void Mesh::ForceBoundary() {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceBoundary)*/
+
+		long int verbose=2;
+		int k=0;
+		int nbfe=0,nbswp=0,Nbswap=0;
+
+		//display
+		if (verbose > 2) _printf_("   ForceBoundary  nb of edge: " << nbe << "\n");
+
+		//check that there is no triangle with 0 determinant
+		for (int t = 0; t < nbt; t++){
+			if (!triangles[t].det) k++;
+		}
+		if (k!=0) {
+			_error_("there is " << k << " triangles of mes = 0");
+		}
+
+		//Force Edges
+		AdjacentTriangle ta(0,0);
+		for (int i = 0; i < nbe; i++){
+
+			//Force edge i
+			nbswp =  ForceEdge(edges[i][0],edges[i][1],ta);
+			if (nbswp<0) k++;
+			else Nbswap += nbswp;
+
+			if (nbswp) nbfe++;
+			if ( nbswp < 0 && k < 5){
+				_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+			}
+		}
+
+		if (k!=0) {
+			_error_("There are " << k << " lost edges, the boundary might be crossing");
+		}
+		for (int j=0;j<nbv;j++){
+			Nbswap +=  vertices[j].Optim(1,0);
+		}
+		if (verbose > 3) _printf_("      number of inforced edge = " << nbfe << ", number of swap= " << Nbswap << "\n"); 
+	}
+	/*}}}*/
+	void Mesh::FindSubDomain(int OutSide) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindSubDomain)*/
+
+		long int verbose=0;
+
+		if (verbose >2){
+			if (OutSide) _printf_("   Find all external sub-domain\n"); 
+			else _printf_("   Find all internal sub-domain\n");
+		  }
+		short * HeapArete = new short[nbt];
+		Triangle  **  HeapTriangle = new Triangle*  [nbt];
+		Triangle *t,*t1;
+		long k,it;
+
+		for (int itt=0;itt<nbt;itt++) 
+		 triangles[itt].link=0; // par defaut pas de couleur
+
+		long  NbSubDomTot =0;
+		for ( it=0;it<nbt;it++)  { 
+			if ( ! triangles[it].link  ) {
+				t = triangles + it;
+				NbSubDomTot++;; // new composante connexe
+				long i = 0; // niveau de la pile 
+				t->link = t ; // sd forme d'un triangle cicular link
+
+				HeapTriangle[i] =t ; 
+				HeapArete[i] = 3;
+
+				while (i >= 0) // boucle sur la pile
+				  { while ( HeapArete[i]--) // boucle sur les 3 aretes 
+					  { 
+						int na =  HeapArete[i];
+						Triangle * tc =  HeapTriangle[i]; // triangle courant
+						if( ! tc->Locked(na)) // arete non frontiere
+						  {
+							Triangle * ta = tc->TriangleAdj(na) ; // næ triangle adjacent
+							if (ta->link == 0 ) // non deja chainer => on enpile
+							  { 
+								i++;
+								ta->link = t->link ;  // on chaine les triangles
+								t->link = ta ;  // d'un meme sous domaine          
+								HeapArete[i] = 3; // pour les 3 triangles adjacents
+								HeapTriangle[i] = ta;
+							  }}
+					  } // deplie fin de boucle sur les 3 adjacences
+					i--;
+				  }          
+			}      
+		}
+
+		// supression de tous les sous domaine infini <=>  contient le sommet NULL
+		it =0;
+		nbtout = 0;
+		while (it<nbt) {
+			if (triangles[it].link) 
+			  { 
+				if (!( triangles[it](0) &&  triangles[it](1) &&  triangles[it](2) )) 
+				  {
+					// infini triangle 
+					NbSubDomTot --;
+					t=&triangles[it];
+					nbtout--;  // on fait un coup de trop. 
+					while  (t){
+						nbtout++;
+						t1=t;
+						t=t->link;
+						t1->link=0;
+					}
+				  }
+			  }   
+			it++;} // end while (it<nbt)
+			if (nbt == nbtout ||  !NbSubDomTot) {
+				delete [] HeapArete;
+				_error_("The boundary is not close: all triangles are outside");
+			}
+
+			delete [] HeapArete;
+			delete [] HeapTriangle;
+
+			if (OutSide|| !Gh.subdomains || !Gh.nbsubdomains ) 
+			  { // No geom sub domain
+				long i;
+				if (subdomains) delete [] subdomains;
+				subdomains = new SubDomain[ NbSubDomTot];
+				nbsubdomains=  NbSubDomTot;
+				for ( i=0;i<nbsubdomains;i++) {
+					subdomains[i].head=NULL;
+					subdomains[i].ReferenceNumber=i+1;
+				}
+				long * mark = new long[nbt];
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+
+				it =0;
+				k = 0;
+				while (it<nbt) {
+					if (mark[it] == -1) {
+						t1 = & triangles[it];
+						t = t1->link;
+						mark[it]=k;
+						subdomains[k].head = t1;
+						do {
+							mark[GetId(t)]=k;
+							t=t->link;
+						} while (t!=t1);
+						mark[it]=k++;}
+						//    else if(mark[it] == -2 ) triangles[it].Draw(999);
+						it++;} // end white (it<nbt)
+						if (k!=nbsubdomains){
+							delete [] mark;
+							_error_("k!=nbsubdomains");
+						}
+						if(OutSide) 
+						  {
+							//  to remove all the sub domain by parity adjacents
+							//  because in this case we have only the true boundary edge
+							// so teh boundary is manifold
+							long nbk = nbsubdomains;
+							while (nbk)
+							 for (it=0;it<nbt && nbk ;it++)
+							  for (int na=0;na<3 && nbk ;na++)
+								 {
+								  Triangle *ta = triangles[it].TriangleAdj(na);
+								  long kl = ta ? mark[GetId(ta)] : -2;
+								  long kr = mark[it];
+								  if(kr !=kl) {
+									  if (kl >=0 && subdomains[kl].ReferenceNumber <0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=subdomains[kl].ReferenceNumber-1;
+									  if (kr >=0 && subdomains[kr].ReferenceNumber <0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=subdomains[kr].ReferenceNumber-1;
+									  if(kr<0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=-1;
+									  if(kl<0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=-1;
+								  }
+								 }
+							long  j=0;
+							for ( i=0;i<nbsubdomains;i++)
+							 if((-subdomains[i].ReferenceNumber) %2) { // good 
+								 if(i != j) 
+								  Exchange(subdomains[i],subdomains[j]);
+								 j++;}
+							 else{ 
+								 t= subdomains[i].head;
+								 while (t){
+									 nbtout++;
+									 t1=t;
+									 t=t->link;
+									 t1->link=0;
+								 }//while (t)
+								}
+							if(verbose>4) _printf_("      Number of removes subdomains (OutSideMesh) = " << nbsubdomains-j << "\n");
+							nbsubdomains=j;
+						  }
+
+						delete []  mark; 
+
+			  }
+			else{ // find the head for all subdomains
+				if (Gh.nbsubdomains != nbsubdomains && subdomains)
+				 delete [] subdomains, subdomains=0;
+				if (! subdomains  ) 
+				 subdomains = new SubDomain[ Gh.nbsubdomains];
+				nbsubdomains =Gh.nbsubdomains;
+				CreateSingleVertexToTriangleConnectivity();
+				long * mark = new long[nbt];
+				Edge **GeomEdgetoEdge = MakeGeomEdgeToEdge();
+
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+				long inew =0;
+				for (int i=0;i<nbsubdomains;i++) {
+					GeomEdge &eg = *Gh.subdomains[i].edge;
+					subdomains[i].ReferenceNumber = Gh.subdomains[i].ReferenceNumber;
+					// by carefull is not easy to find a edge create from a GeomEdge 
+					// see routine MakeGeomEdgeToEdge
+					Edge &e = *GeomEdgetoEdge[Gh.GetId(eg)];
+					_assert_(&e);
+					BamgVertex * v0 =  e(0),*v1 = e(1);
+					Triangle *t  = v0->t;
+					int direction = Gh.subdomains[i].direction;
+					// test if ge and e is in the same direction 
+					if (((eg[0].r-eg[1].r),(e[0].r-e[1].r))<0) direction = -direction ;
+					subdomains[i].direction = direction;
+					subdomains[i].edge = &e;
+					_assert_(t && direction);
+
+					AdjacentTriangle  ta(t,EdgesVertexTriangle[v0->IndexInTriangle][0]);// previous edges
+
+					while (1) {
+						_assert_(v0==ta.EdgeVertex(1));
+						if (ta.EdgeVertex(0) == v1) { // ok we find the edge
+							if (direction>0)  
+							 subdomains[i].head=t=Adj(ta);
+							else 
+							 subdomains[i].head=t=ta;
+							if(t<triangles || t >= triangles+nbt || t->det < 0 || t->link == 0) {
+								_error_("bad definition of SubSomain " << i);
+							}
+							long it = GetId(t);
+							if (mark[it] >=0) {
+								break;
+							}
+							if(i != inew) 
+							 Exchange(subdomains[i],subdomains[inew]);
+							inew++;
+							Triangle *tt=t;
+							long kkk=0;
+							do 
+							  {
+								kkk++;
+								if (mark[GetId(tt)]>=0){
+									_error_("mark[GetId(tt)]>=0");
+								}
+								mark[GetId(tt)]=i;
+								tt=tt->link;
+							  } while (tt!=t);
+							break;
+						}
+						ta = Previous(Adj(ta));         
+						if(t == (Triangle *) ta) {
+							_error_("bad definition of SubSomain " << i);
+						}
+					}
+				}
+
+				if (inew < nbsubdomains) {
+					if (verbose>5) _printf_("WARNING: " << nbsubdomains-inew << " SubDomains are being removed\n");
+					nbsubdomains=inew;}
+
+					for (it=0;it<nbt;it++)
+					 if ( mark[it] ==-1 ) 
+					  nbtout++,triangles[it].link =0;
+					delete [] GeomEdgetoEdge;
+					delete [] mark;
+
+			  }
+			nbtout=0;
+			for (it=0;it<nbt;it++) 
+			 if(!triangles[it].link)  nbtout++;
+	}
+	/*}}}*/
+	long Mesh::GetId(const Triangle & t) const  { /*{{{*/
+		return &t - triangles;
+	}
+	/*}}}*/
+	long Mesh::GetId(const Triangle * t) const  { /*{{{*/
+		return t - triangles;
+	}
+	/*}}}*/
+	long Mesh::GetId(const BamgVertex & t) const  { /*{{{*/
+		return &t - vertices;
+	}
+	/*}}}*/
+	long Mesh::GetId(const BamgVertex * t) const  { /*{{{*/
+		return t - vertices;
+	}
+	/*}}}*/
+	long Mesh::GetId(const Edge & t) const  { /*{{{*/
+		return &t - edges;
+	}
+	/*}}}*/
+	long Mesh::GetId(const Edge * t) const  { /*{{{*/
+		return t - edges;
+	}
+	/*}}}*/
+	void Mesh::Init(long maxnbv_in) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/PreInit)*/
+
+		/* initialize random seed: */
+		srand(19999999);
+
+		/*Initialize fields*/
+		NbRef=0;
+		quadtree=NULL;
+		nbv=0;
+		nbt=0;
+		nbe=0;
+		edges=NULL;
+		nbq=0;
+		nbsubdomains=0;
+		subdomains=NULL;
+		maxnbv=maxnbv_in;
+		maxnbt=2 *maxnbv_in-2;
+		NbVertexOnBThVertex=0;
+		VertexOnBThVertex=NULL;
+		NbVertexOnBThEdge=0;
+		VertexOnBThEdge=NULL;
+		NbCrackedVertices=0;
+		CrackedVertices =NULL;
+		NbCrackedEdges =0;
+		CrackedEdges =NULL;
+		NbVerticesOnGeomVertex=0;
+		VerticesOnGeomVertex=NULL;
+		NbVerticesOnGeomEdge=0;
+		VerticesOnGeomEdge=NULL;
+
+		/*Allocate if maxnbv_in>0*/
+		if (maxnbv_in) {
+			vertices=new BamgVertex[maxnbv];
+			_assert_(vertices);
+			orderedvertices=new BamgVertex* [maxnbv];
+			_assert_(orderedvertices);
+			triangles=new Triangle[maxnbt];
+			_assert_(triangles);
+		}
+		else {
+			vertices=NULL;
+			orderedvertices=NULL;
+			triangles=NULL;
+			maxnbt=0;
+		} 
+	}
+	/*}}}*/
+	void Mesh::Insert(bool random) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Insert)*/
+
+		/*Insert points in the existing Geometry*/
+
+		//Intermediary
+		int i;
+
+		/*Get options*/
+		long int verbose=2;
+
+		//Display info
+		if (verbose>2) _printf_("   Insert initial " << nbv << " vertices\n");
+
+		//Compute integer coordinates for the existing vertices
+		SetIntCoor();
+
+		/*Now we want to build a list (orderedvertices) of the vertices in a random
+		 * order. To do so, we use the following method:
+		 *
+		 * From an initial k0 in [0 nbv[ random (vertex number)
+		 * the next k (vertex number) is computed using a big
+		 * prime number (PN>>nbv) following:
+		 *
+		 * k_{i+1} = k_i + PN  [nbv]
+		 *
+		 * let's show that:
+		 *
+		 *   for all j in [0 nbv[, ∃! i in [0 nbv[ such that k_i=j
+		 *
+		 * Let's assume that there are 2 distinct j1 and j2 such that
+		 * k_j1 = k_j2
+		 *
+		 * This means that
+		 *  
+		 *  k0+j1*PN = k0+j2*PN [nbv]
+		 *  (j1-j2)*PN =0       [nbv]
+		 * since PN is a prime number larger than nbv, and nbv!=1
+		 *  j1-j2=0             [nbv]
+		 * BUT
+		 *  j1 and j2 are in [0 nbv[ which is impossible.
+		 *
+		 *  We hence have built a random list of nbv elements of
+		 *  [0 nbv[ all distincts*/
+
+		//Get Prime number
+		const long PrimeNumber= BigPrimeNumber(nbv);
+		int temp = rand(); if(!random) temp = 756804110;
+		int  k0=temp%nbv; 
+
+		//Build orderedvertices
+		for (i=0; i<nbv; i++){
+			orderedvertices[i]=&vertices[k0=(k0+PrimeNumber)%nbv];
+		}
+
+		/*Modify orderedvertices such that the first 3 vertices form a triangle*/
+
+		//get first vertex i such that [0,1,i] are not aligned
+		for (i=2; det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;){
+			//if i is higher than nbv, it means that all the determinants are 0,
+			//all vertices are aligned!
+			if  (++i>=nbv) _error_("all the vertices are aligned");
+		}
+		// exchange i et 2 in "orderedvertices" so that
+		// the first 3 vertices are not aligned (real triangle)
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Take the first edge formed by the first two vertices and build
+		 * the initial simple mesh from this edge and 2 boundary triangles*/
+
+		BamgVertex *v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		nbt = 2;
+		triangles[0](0) = NULL;//infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+		triangles[1](0) = NULL;//infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+
+		//Build adjacence
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  //boundary triangle: det = -1
+		triangles[1].det = -1;  //boundary triangle: det = -1
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		//build quadtree
+		if (!quadtree)  quadtree = new BamgQuadtree(this,0);
+		quadtree->Add(*v0);
+		quadtree->Add(*v1);
+
+		/*Now, add the vertices One by One*/
+		long NbSwap=0;
+		if (verbose>3) _printf_("   Begining of insertion process...\n");
+
+		for (int icount=2; icount<nbv; icount++) {
+
+			//Get new vertex
+			BamgVertex *newvertex=orderedvertices[icount];
+
+			//Find the triangle in which newvertex is located
+			Icoor2 det3[3];
+			Triangle* tcvi = TriangleFindFromCoord(newvertex->i,det3); //(newvertex->i = integer coordinates)
+
+			//Add newvertex to the quadtree
+			quadtree->Add(*newvertex); 
+
+			//Add newvertex to the existing mesh
+			AddVertex(*newvertex,tcvi,det3);
+
+			//Make the mesh Delaunay around newvertex by swaping the edges
+			NbSwap += newvertex->Optim(1,0);
+		}
+
+		//Display info
+		if (verbose>3) {
+			_printf_("      NbSwap of insertion: " << NbSwap << "\n");
+			_printf_("      NbSwap/nbv:          " << NbSwap/nbv << "\n");
+		}
+	}
+	/*}}}*/
+	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap,bool random) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/InsertNewPoints)*/
+
+		long int verbose=0;
+		double seuil= 1.414/2 ;// for two close point 
+		long i;
+		long NbSwap=0;
+		Icoor2 det3[3];
+
+		//number of new points
+		const long nbvnew=nbv-nbvold;
+
+		//display info if required
+		if (verbose>5) _printf_("      Try to Insert " << nbvnew << " new points\n");
+
+		//return if no new points
+		if (!nbvnew) return 0; 
+
+		/*construction of a random order*/
+		const long PrimeNumber= BigPrimeNumber(nbv)  ;
+		//remainder of the division of rand() by nbvnew
+		int  temp = rand(); if(!random) temp = 1098566905;
+		long k3 = temp%nbvnew;
+		//loop over the new points
+		for (int is3=0; is3<nbvnew; is3++){
+			long j=nbvold +(k3 = (k3+PrimeNumber)%nbvnew);
+			long i=nbvold+is3; 
+			orderedvertices[i]= vertices + j;
+			orderedvertices[i]->ReferenceNumber=i;
+		}
+
+		// for all the new point
+		long iv=nbvold;
+		for (i=nbvold;i<nbv;i++){
+			BamgVertex &vi=*orderedvertices[i];
+			vi.i=R2ToI2(vi.r);
+			vi.r=I2ToR2(vi.i);
+			double hx,hy;
+			vi.m.Box(hx,hy);
+			Icoor1 hi=(Icoor1) (hx*coefIcoor),hj=(Icoor1) (hy*coefIcoor);
+			if (!quadtree->ToClose(vi,seuil,hi,hj)){
+				// a good new point 
+				BamgVertex &vj = vertices[iv];
+				long  j=vj.ReferenceNumber; 
+				if (&vj!=orderedvertices[j]){
+					_error_("&vj!= orderedvertices[j]");
+				}
+				if(i!=j){ 
+					Exchange(vi,vj);
+					Exchange(orderedvertices[j],orderedvertices[i]);
+				}
+				vj.ReferenceNumber=0; 
+				Triangle *tcvj=TriangleFindFromCoord(vj.i,det3);
+				if (tcvj && !tcvj->link){
+					tcvj->Echo();
+					_error_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
+				}
+				quadtree->Add(vj);
+				AddVertex(vj,tcvj,det3);
+				NbSwap += vj.Optim(1);          
+				iv++;
+			}
+		} 
+		if (verbose>3) {
+			_printf_("         number of new points: " << iv << "\n");
+			_printf_("         number of to close (?) points: " << nbv-iv << "\n");
+			_printf_("         number of swap after: " << NbSwap << "\n");
+		}
+		nbv = iv;
+
+		for (i=nbvold;i<nbv;i++) NbSwap += vertices[i].Optim(1);  
+		if (verbose>3) _printf_("   NbSwap=" << NbSwap << "\n");
+
+		NbTSwap +=  NbSwap ;
+		return nbv-nbvold;
+	}
+	/*}}}*/
+	Edge** Mesh::MakeGeomEdgeToEdge() {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeGeomEdgeToEdge)*/
+
+		if (!Gh.nbe){
+			_error_("!Gh.nbe");
+		}
+		Edge **e= new Edge* [Gh.nbe];
+
+		long i;
+		for ( i=0;i<Gh.nbe ; i++)
+		 e[i]=NULL;
+		for ( i=0;i<nbe ; i++) 
+		  { 
+			Edge * ei = edges+i;
+			GeomEdge *GeomEdgeHook = ei->GeomEdgeHook; 
+			e[Gh.GetId(GeomEdgeHook)] = ei;    
+		  }
+		for ( i=0;i<nbe ; i++) 
+		 for (int ii=0;ii<2;ii++) { 
+			 Edge * ei = edges+i;
+			 GeomEdge *GeomEdgeHook = ei->GeomEdgeHook;
+			 int j= ii;
+			 while (!(*GeomEdgeHook)[j].Required()) { 
+				 Adj(GeomEdgeHook,j); // next geom edge
+				 j=1-j;
+				 if (e[Gh.GetId(GeomEdgeHook)])  break; // optimisation
+				 e[Gh.GetId(GeomEdgeHook)] = ei; 
+			 }
+		 }
+
+		int kk=0;
+		for ( i=0;i<Gh.nbe ; i++){
+			if (!e[i]){
+				kk++;
+				if(kk<10) _printf_("BUG: the geometrical edge " << i << " is on no edge curve\n");
+			}
+		}
+		if(kk) _error_("See above");
+
+		return e;
+	}
+	/*}}}*/
+	void Mesh::MakeQuadrangles(double costheta){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeQuadrangles)*/
+
+		long int verbose=0;
+
+		if (verbose>2) _printf_("MakeQuadrangles costheta = " << costheta << "\n");
+
+		if (costheta >1) {
+			if (verbose>5) _printf_("   do nothing: costheta > 1\n");
+		}
+
+			long nbqq = (nbt*3)/2;
+			DoubleAndInt *qq = new DoubleAndInt[nbqq];
+
+			long i,ij;
+			int j;
+			long k=0;
+			for (i=0;i<nbt;i++)
+			 for (j=0;j<3;j++)
+			  if ((qq[k].q=triangles[i].QualityQuad(j))>=costheta)
+				qq[k++].i3j=i*3+j;
+			//  sort  qq
+			HeapSort(qq,k);
+
+			long kk=0;
+			for (ij=0;ij<k;ij++) { 
+				i=qq[ij].i3j/3;
+				j=(int) (qq[ij].i3j%3);
+				// optisamition no float computation  
+				if (triangles[i].QualityQuad(j,0) >=costheta) 
+				 triangles[i].SetHidden(j),kk++;
+			  }
+			nbq = kk;
+			if (verbose>2){
+				_printf_("   number of quadrilaterals    = " << nbq << "\n");
+				_printf_("   number of triangles         = " << nbt-nbtout- nbq*2 << "\n");
+				_printf_("   number of outside triangles = " << nbtout << "\n");
+			}
+			delete [] qq;
+	}
+	/*}}}*/
+	void Mesh::MakeBamgQuadtree() {  /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeBamgQuadtree)*/
+		if(!quadtree) quadtree = new BamgQuadtree(this);
+	}
+	/*}}}*/
+	double Mesh::MaximalHmax() {/*{{{*/
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}
+	/*}}}*/
+	void  Mesh::MaxSubDivision(double maxsubdiv) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/MaxSubDivision)*/
+
+		long int verbose=0;
+
+		const  double maxsubdiv2 = maxsubdiv*maxsubdiv;
+		if(verbose>1) _printf_("   Limit the subdivision of a edges in the new mesh by " << maxsubdiv << "\n");
+		// for all the edges 
+		// if the len of the edge is to long 
+		long it,nbchange=0;    
+		double lmax=0;
+		for (it=0;it<nbt;it++){
+			Triangle &t=triangles[it];
+			for (int j=0;j<3;j++){
+				Triangle &tt = *t.TriangleAdj(j);
+				if ( (!&tt ||  it < GetId(tt)) && ( tt.link || t.link)){
+					BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+					BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+					R2 AB= (R2) v1-(R2) v0;
+					Metric M = v0;
+					double l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2 MM = Rt1*D*Rt1.t();
+						v0.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+					M = v1;
+					l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2  MM = Rt1*D*Rt1.t();
+						v1.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+				}
+			}
+		}
+		if(verbose>3){
+			_printf_("      number of metric changes = " << nbchange << ", maximum number of subdivision of a edges before change = " << pow(lmax,0.5) << "\n");
+		}
+	}
+	/*}}}*/
+	Metric Mesh::MetricAt(const R2 & A) const { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MetricAt)*/
+
+		I2 a = R2ToI2(A);
+		Icoor2 deta[3];
+		Triangle * t =TriangleFindFromCoord(a,deta);
+		if (t->det <0) { // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(a,t,ba,bb) ;
+			return Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			return Metric(aa,(*t)[0],(*t)[1],(*t)[2]);
+		}
+	}
+	/*}}}*/
+	double Mesh::MinimalHmin() {/*{{{*/
+		return 2.0/coefIcoor;
+	}
+	/*}}}*/
+	BamgVertex* Mesh::NearestVertex(Icoor1 i,Icoor1 j) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NearestVertex)*/
+		return  quadtree->NearestVertex(i,j); 
+	} 
+	/*}}}*/
+	void  Mesh::NewPoints(Mesh & Bh,BamgOpts* bamgopts,int KeepVertices){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		int i,j,k;
+		long NbTSwap=0;
+		long nbtold=nbt;
+		long nbvold=nbv;
+		long Headt=0;
+		long next_t;
+		long* first_np_or_next_t=new long[maxnbt];
+		Triangle* t=NULL;
+
+		/*Recover options*/
+		int verbose=bamgopts->verbose;
+
+		/*First, insert old points if requested*/
+		if (KeepVertices && (&Bh != this) && (nbv+Bh.nbv< maxnbv)){
+			if (verbose>5) _printf_("         Inserting initial mesh points\n");
+			for (i=0;i<Bh.nbv;i++){ 
+				BamgVertex &bv=Bh[i];
+				if (!bv.GeomEdgeHook){
+					vertices[nbv].r   = bv.r;
+					vertices[nbv++].m = bv.m;
+				}
+			}
+			Bh.CreateSingleVertexToTriangleConnectivity();     
+			InsertNewPoints(nbvold,NbTSwap,bamgopts->random);
+		}  
+		else Bh.CreateSingleVertexToTriangleConnectivity();     
+
+		// generation of the list of next Triangle 
+		for(i=0;i<nbt;i++) first_np_or_next_t[i]=-(i+1);
+		// the next traingle of i is -first_np_or_next_t[i]
+
+		// Big loop (most time consuming)
+		int iter=0;
+		if (verbose>5) _printf_("         Big loop\n");
+		do {
+			/*Update variables*/
+			iter++;
+			nbtold=nbt;
+			nbvold=nbv;
+
+			/*We test all triangles*/
+			i=Headt;
+			next_t=-first_np_or_next_t[i];
+			for(t=&triangles[i];i<nbt;t=&triangles[i=next_t],next_t=-first_np_or_next_t[i]){
+
+				//check i
+				if (i<0 || i>=nbt ){
+					_error_("Index problem in NewPoints (i=" << i << " not in [0 " << nbt-1 << "])");
+				}
+				//change first_np_or_next_t[i]
+				first_np_or_next_t[i] = iter; 
+
+				//Loop over the edges of t
+				for(j=0;j<3;j++){
+					AdjacentTriangle tj(t,j);
+					BamgVertex &vA = *tj.EdgeVertex(0);
+					BamgVertex &vB = *tj.EdgeVertex(1);
+
+					//if t is a boundary triangle, or tj locked, continue
+					if (!t->link)     continue;
+					if (t->det <0)    continue;
+					if (t->Locked(j)) continue;
+
+					AdjacentTriangle tadjj = t->Adj(j);	  
+					Triangle* ta=tadjj;
+
+					//if the adjacent triangle is a boundary triangle, continur
+					if (ta->det<0) continue;	  
+
+					R2 A=vA;
+					R2 B=vB;
+					k=GetId(ta);
+
+					//if this edge has already been done, go to next edge of triangle
+					if(first_np_or_next_t[k]==iter) continue;
+
+					lIntTria.SplitEdge(Bh,A,B);
+					lIntTria.NewPoints(vertices,nbv,maxnbv);
+				} // end loop for each edge 
+			}// for triangle   
+
+			if (!InsertNewPoints(nbvold,NbTSwap,bamgopts->random)) break;
+			for (i=nbtold;i<nbt;i++) first_np_or_next_t[i]=iter;
+			Headt = nbt; // empty list 
+
+			// for all the triangle containing the vertex i
+			for (i=nbvold;i<nbv;i++){ 
+				BamgVertex*          s  = vertices + i;
+				AdjacentTriangle ta(s->t, EdgesVertexTriangle[s->IndexInTriangle][1]);
+				Triangle*        tbegin= (Triangle*) ta;
+				long kt;
+				do { 
+					kt = GetId((Triangle*) ta);
+					if (first_np_or_next_t[kt]>0){
+						first_np_or_next_t[kt]=-Headt;
+						Headt=kt;
+					}
+					if (ta.EdgeVertex(0)!=s){
+						_error_("ta.EdgeVertex(0)!=s");
+					}
+					ta = Next(Adj(ta));
+				} while ( (tbegin != (Triangle*) ta)); 
+			}
+
+		}while(nbv!=nbvold);
+		delete [] first_np_or_next_t;
+
+		long NbSwapf =0;
+		for(i=0;i<nbv;i++) NbSwapf += vertices[i].Optim(0);
+	}/*}}}*/
+	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,/*{{{*/
+				double theta,BamgVertex & R,VertexOnEdge &  BR,VertexOnGeom & GR) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/ProjectOnCurve)*/
+
+		void *pA=0,*pB=0;
+		double tA=0,tB=0;
+		R2 A=vA,B=vB;
+		BamgVertex * pvA=&vA, * pvB=&vB;
+		if (vA.IndexInTriangle == IsVertexOnVertex){
+			pA=vA.BackgroundVertexHook;
+		}
+		else if (vA.IndexInTriangle == IsVertexOnEdge){
+			pA=vA.BackgroundEdgeHook->be;
+			tA=vA.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vA) << " forget call to SetVertexFieldOnBTh");
+		} 
+
+		if (vB.IndexInTriangle == IsVertexOnVertex){
+			pB=vB.BackgroundVertexHook;
+		}
+		else if(vB.IndexInTriangle == IsVertexOnEdge){
+			pB=vB.BackgroundEdgeHook->be;
+			tB=vB.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
+		} 
+		Edge * e = &BhAB;
+		if (!pA || !pB || !e){
+			_error_("!pA || !pB || !e");
+		}
+		// be carefull the back ground edge e is on same geom edge 
+		// of the initiale edge def by the 2 vertex A B;
+		//check Is a background Mesh;   
+		if (e<BTh.edges || e>=BTh.edges+BTh.nbe){
+			_error_("e<BTh.edges || e>=BTh.edges+BTh.nbe");
+		}
+		// walk on BTh edge 
+		//not finish ProjectOnCurve with BackGround Mesh);
+		// 1 first find a back ground edge contening the vertex A
+		// 2 walk n back gound boundary to find the final vertex B
+
+		if( vA.IndexInTriangle == IsVertexOnEdge) 
+		  { // find the start edge 
+			e = vA.BackgroundEdgeHook->be;	 
+
+		  } 
+		else if (vB.IndexInTriangle == IsVertexOnEdge) 
+		  {
+			theta = 1-theta;
+			Exchange(tA,tB);
+			Exchange(pA,pB);
+			Exchange(pvA,pvB);
+			Exchange(A,B);
+			e =  vB.BackgroundEdgeHook->be;
+
+		  } 
+		else{ // do the search by walking 
+			_error_("case not supported yet");
+		}
+
+		// find the direction of walking with direction of edge and pA,PB;
+		R2 AB=B-A;
+
+		double cosE01AB = (( (R2) (*e)[1] - (R2) (*e)[0] ) , AB);
+		int kkk=0;
+		int direction = (cosE01AB>0) ? 1 : 0;
+
+		//   double l=0; // length of the edge AB
+		double abscisse = -1;
+
+		for (int step=0;step<2;step++){
+			// 2 times algo:
+			//    1 for computing the length l
+			//    2 for find the vertex 
+			int  iii;
+			BamgVertex  *v0=pvA,*v1; 
+			Edge *neee,*eee;
+			double lg =0; // length of the curve 
+			double te0;
+			// we suppose take the curve's abcisse 
+			for ( eee=e,iii=direction,te0=tA;
+						eee && ((( void*) eee) != pB) && (( void*) (v1=&((*eee)[iii]))) != pB ;
+						neee = eee->adj[iii],iii = 1-neee->Intersection(*eee),eee = neee,v0=v1,te0=1-iii ) { 
+
+				kkk=kkk+1;
+				_assert_(kkk<100);
+				_assert_(eee);
+				double lg0 = lg;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;
+				if (step && abscisse <= lg) { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*iii;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				}
+			}
+			// we find the end 
+			if (v1 != pvB){
+				if (( void*) v1 == pB)
+				 tB = iii;
+
+				double lg0 = lg;
+				_assert_(eee);
+				v1 = pvB;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;	
+				abscisse = lg*theta;
+				if (abscisse <= lg && abscisse >= lg0 ) // small optimisation we know the lenght because end
+				  { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*tB;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				  }
+			}
+			abscisse = lg*theta;
+
+		}
+		_error_("Big bug...");
+		return 0; // just for the compiler 
+	}                  
+	/*}}}*/
+	void Mesh::ReconstructExistingMesh(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
+
+		/*This routine reconstruct an existing mesh to make it CONVEX:
+		 * -all the holes are filled
+		 * -concave boundaries are filled
+		 * A convex mesh is required for a lot of operations. This is why every mesh
+		 * goes through this process.
+		 * This routine also generates mesh properties such as adjencies,...
+		 */
+
+		/*Intermediary*/
+		int verbose=0;
+
+		// generation of the integer coordinate
+
+		// find extrema coordinates of vertices pmin,pmax
+		long i;
+		if(verbose>2) _printf_("      Reconstruct mesh of " << nbv << " vertices\n"); 
+
+		//initialize orderedvertices
+		_assert_(orderedvertices);
+		for (i=0;i<nbv;i++) orderedvertices[i]=0;
+
+		//Initialize nbsubdomains
+		nbsubdomains =0;
+
+		/* generation of triangles adjacency*/
+
+		//First add existing edges
+		long kk =0;
+		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+		for (i=0;i<nbe;i++){
+			kk=kk+(i==edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
+		}
+		if (kk != nbe){ 
+			_error_("There are " << kk-nbe << " double edges in the mesh");
+		}
+
+		//Add edges of all triangles in existing mesh
+		long* st = new long[nbt*3];
+		for (i=0;i<nbt*3;i++) st[i]=-1;
+		for (i=0;i<nbt;i++){
+			for (int j=0;j<3;j++){
+
+				//Add current triangle edge to edge4
+				long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+
+				long invisible=triangles[i].Hidden(j);
+
+				//If the edge has not been added to st, add it
+				if(st[k]==-1) st[k]=3*i+j;
+
+				//If the edge already exists, add adjacency
+				else if(st[k]>=0) {
+					_assert_(!triangles[i].TriangleAdj(j));
+					_assert_(!triangles[st[k]/3].TriangleAdj((int) (st[k]%3)));
+
+					triangles[i].SetAdj2(j,triangles+st[k]/3,(int)(st[k]%3));
+					if (invisible) triangles[i].SetHidden(j);
+					if (k<nbe)     triangles[i].SetLocked(j);
+
+					//Make st[k] negative so that it will throw an error message if it is found again
+					st[k]=-2-st[k]; 
+				}
+
+				//An edge belongs to 2 triangles
+				else {
+					_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
+				}
+			}
+		}
+
+		//Display info if required
+		if(verbose>5) {
+			_printf_("         info of Mesh:\n");
+			_printf_("            - number of vertices    = " << nbv << " \n"); 
+			_printf_("            - number of triangles   = " << nbt << " \n"); 
+			_printf_("            - number of given edges = " << nbe << " \n"); 
+			_printf_("            - number of all edges   = " << edge4->nb() << "\n"); 
+			_printf_("            - Euler number 1 - nb of holes = " << nbt-edge4->nb()+nbv << "\n"); 
+		}
+
+		//check the consistency of edge[].adj and the geometrical required vertex
+		long k=0;
+		for (i=0;i<edge4->nb();i++){
+			if (st[i]>=0){ // edge alone 
+				if (i<nbe){
+					long i0=edge4->i(i);
+					orderedvertices[i0] = vertices+i0;
+					long i1=edge4->j(i);
+					orderedvertices[i1] = vertices+i1;
+				}
+				else {
+					k=k+1;
+					if (k<10) {
+						//print only 10 edges
+						_printf_("Lost boundary edges " << i << " : " << edge4->i(i) << " " << edge4->j(i) << "\n");
+					}
+					else if (k==10){
+						_printf_("Other lost boundary edges not shown...\n");
+					}
+				}
+			}
+		}
+		if(k) {
+			_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
+		}
+
+		/* mesh generation with boundary points*/
+		long nbvb=0;
+		for (i=0;i<nbv;i++){ 
+			vertices[i].t=0;
+			vertices[i].IndexInTriangle=0;
+			if (orderedvertices[i]) orderedvertices[nbvb++]=orderedvertices[i];
+		}
+
+		Triangle* savetriangles=triangles;
+		long savenbt=nbt;
+		long savemaxnbt=maxnbt;
+		SubDomain* savesubdomains=subdomains;
+		subdomains=0;
+
+		long  Nbtriafillhole=2*nbvb;
+		Triangle* triafillhole=new Triangle[Nbtriafillhole];
+		triangles = triafillhole;
+
+		nbt=2;
+		maxnbt= Nbtriafillhole;
+
+		//Find a vertex that is not aligned with vertices 0 and 1
+		for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
+		 if  (++i>=nbvb) {
+			 _error_("ReconstructExistingMesh: All the vertices are aligned");
+		 }
+		//Move this vertex (i) to the 2d position in orderedvertices
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Reconstruct mesh beginning with 2 triangles*/
+		BamgVertex *  v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		triangles[0](0) = NULL; // Infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+
+		triangles[1](0) = NULL;// Infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  // boundary triangles
+		triangles[1].det = -1;  // boundary triangles
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		if (!quadtree) delete quadtree; //ReInitialise;
+		quadtree = new BamgQuadtree(this,0);
+		quadtree->Add(*v0);
+		quadtree->Add(*v1);
+
+		// vertices are added one by one
+		long NbSwap=0;
+		for (int icount=2; icount<nbvb; icount++) {
+			BamgVertex *vi  = orderedvertices[icount];
+			Icoor2 det3[3];
+			Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
+			quadtree->Add(*vi); 
+			AddVertex(*vi,tcvi,det3);
+			NbSwap += vi->Optim(1,1);
+		}
+
+		//enforce the boundary 
+		AdjacentTriangle ta(0,0);
+		long nbloss = 0,knbe=0;
+		for ( i = 0; i < nbe; i++){
+			if (st[i] >=0){ //edge alone => on border
+				BamgVertex &a=edges[i][0], &b=edges[i][1];
+				if (a.t && b.t){
+					knbe++;
+					if (ForceEdge(a,b,ta)<0) nbloss++;
+				}
+			}
+		}
+		if(nbloss) {
+			_error_("we lost " << nbloss << " existing edges other " << knbe);
+		}
+
+		FindSubDomain(1);
+		// remove all the hole 
+		// remove all the good sub domain
+		long krm =0;
+		for (i=0;i<nbt;i++){
+			if (triangles[i].link){ // remove triangles
+				krm++;
+				for (int j=0;j<3;j++){
+					AdjacentTriangle ta =  triangles[i].Adj(j);
+					Triangle &tta = *(Triangle*)ta;
+					//if edge between remove and not remove 
+					if(! tta.link){ 
+						// change the link of ta;
+						int ja = ta;
+						BamgVertex *v0= ta.EdgeVertex(0);
+						BamgVertex *v1= ta.EdgeVertex(1);
+						long k =edge4->SortAndAdd(v0?GetId(v0):nbv,v1? GetId(v1):nbv);
+
+						_assert_(st[k]>=0);
+						tta.SetAdj2(ja,savetriangles + st[k] / 3,(int) (st[k]%3));
+						ta.SetLock();
+						st[k]=-2-st[k]; 
+					}
+				}
+			}
+		}
+		long NbTfillHoll =0;
+		for (i=0;i<nbt;i++){
+			if (triangles[i].link) {
+				triangles[i]=Triangle((BamgVertex *) NULL,(BamgVertex *) NULL,(BamgVertex *) NULL);
+				triangles[i].color=-1;
+			}
+			else{
+				triangles[i].color= savenbt+ NbTfillHoll++;
+			}
+		}
+		_assert_(savenbt+NbTfillHoll<=savemaxnbt);
+
+		// copy of the outside triangles in saveMesh 
+		for (i=0;i<nbt;i++){
+			if(triangles[i].color>=0) {
+				savetriangles[savenbt]=triangles[i];
+				savetriangles[savenbt].link=0;
+				savenbt++;
+			}
+		}
+		// gestion of the adj
+		k =0;
+		Triangle * tmax = triangles + nbt;
+		for (i=0;i<savenbt;i++) { 
+			Triangle & ti = savetriangles[i];
+			for (int j=0;j<3;j++){
+				Triangle * ta = ti.TriangleAdj(j);
+				int aa = ti.NuEdgeTriangleAdj(j);
+				int lck = ti.Locked(j);
+				if (!ta) k++; // bug 
+				else if ( ta >= triangles && ta < tmax){
+					ta= savetriangles + ta->color;
+					ti.SetAdj2(j,ta,aa);
+					if(lck) ti.SetLocked(j);
+				}
+			}
+		}
+
+		// restore triangles;
+		nbt=savenbt;
+		maxnbt=savemaxnbt;
+		delete [] triangles;
+		delete [] subdomains;
+		triangles = savetriangles;
+		subdomains = savesubdomains;
+		if (k) {
+			_error_("number of triangles edges alone = " << k);
+		}
+		FindSubDomain();
+
+		delete edge4;
+		delete [] st;
+		for (i=0;i<nbv;i++) quadtree->Add(vertices[i]);
+
+		SetVertexFieldOn();
+
+		/*Check requirements consistency*/
+		for (i=0;i<nbe;i++){
+			/*If the current mesh edge is on Geometry*/
+			if(edges[i].GeomEdgeHook){
+				for(int j=0;j<2;j++){
+					/*Go through the edges adjacent to current edge (if on the same curve)*/
+					if (!edges[i].adj[j]){
+						/*The edge is on Geometry and does not have 2 adjacent edges... (not on a closed curve)*/
+						/*Check that the 2 vertices are on geometry AND required*/
+						if(!edges[i][j].GeomEdgeHook->IsRequiredVertex()){
+							_printf_("ReconstructExistingMesh error message: problem with the edge number " << i+1 << ": [" << GetId(edges[i][0])+1 << " " << GetId(edges[i][1])+1 << "]\n");
+							_printf_("This edge is on geometrical edge number " << Gh.GetId(edges[i].GeomEdgeHook)+1 << "\n");
+							if (edges[i][j].GeomEdgeHook->OnGeomVertex())
+							 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric BamgVertex number " << Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1 << "\n");
+							else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
+							 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric Edge number " << Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1 << "\n");
+							else
+							 _printf_("Its pointer is " << edges[i][j].GeomEdgeHook << "\n");
+
+							_printf_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required\n");
+							_error_("See above (might be cryptic...)");
+						}
+					}
+				}
+			}
+		}
+	}
+	/*}}}*/
+	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingTheTriangleBySubDomain)*/
+
+		long *renu= new long[nbt];
+		Triangle *t0,*t,*te=triangles+nbt;
+		long k=0,it,i,j;
+
+		for ( it=0;it<nbt;it++) 
+		 renu[it]=-1; // outside triangle 
+		for ( i=0;i<nbsubdomains;i++)
+		  { 
+			t=t0=subdomains[i].head;
+			if (!t0){ // not empty sub domain
+				_error_("!t0");
+			}
+			do { 
+				long kt = GetId(t);
+				if (kt<0 || kt >= nbt ){
+					_error_("kt<0 || kt >= nbt");
+				}
+				if (renu[kt]!=-1){
+					_error_("renu[kt]!=-1");
+				}
+				renu[kt]=k++;
+			}
+			while (t0 != (t=t->link));
+		  }
+		// take is same numbering if possible    
+		if(justcompress)
+		 for ( k=0,it=0;it<nbt;it++) 
+		  if(renu[it] >=0 ) 
+			renu[it]=k++;
+
+		// put the outside triangles at the end
+		for ( it=0;it<nbt;it++){
+			if (renu[it]==-1) renu[it]=k++;
+		}
+		if (k != nbt){
+			_error_("k != nbt");
+		}
+		// do the change on all the pointeur 
+		for ( it=0;it<nbt;it++)
+		 triangles[it].Renumbering(triangles,te,renu);
+
+		for ( i=0;i<nbsubdomains;i++)
+		 subdomains[i].head=triangles+renu[GetId(subdomains[i].head)];
+
+		// move the Triangles  without a copy of the array 
+		// be carefull not trivial code 
+		for ( it=0;it<nbt;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 Triangle ti=triangles[i],tj;
+			 while ( (j=renu[i]) >= 0) 
+				{ // i is old, and j is new 
+				 renu[i] = -1; // mark 
+				 tj = triangles[j]; // save new
+				 triangles[j]= ti; // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		delete [] renu;
+
+	}
+	/*}}}*/
+	void Mesh::SetIntCoor(const char * strfrom) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SetIntCoor)*/
+
+		/*Set integer coordinate for existing vertices*/
+
+		//Get extrema coordinates of the existing vertices
+		pmin =  vertices[0].r;
+		pmax =  vertices[0].r;
+		long i;
+		for (i=0;i<nbv;i++) {
+			pmin.x = Min(pmin.x,vertices[i].r.x);
+			pmin.y = Min(pmin.y,vertices[i].r.y);
+			pmax.x = Max(pmax.x,vertices[i].r.x);
+			pmax.y = Max(pmax.y,vertices[i].r.y);
+		}
+		R2 DD = (pmax-pmin)*0.05;
+		pmin = pmin-DD;
+		pmax = pmax+DD; 
+
+		//Compute coefIcoor
+		coefIcoor= (MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+		if (coefIcoor<=0){
+			_error_("coefIcoor should be positive, a problem in the geometry is likely");
+		}
+
+		// generation of integer coord  
+		for (i=0;i<nbv;i++) {
+			vertices[i].i = R2ToI2(vertices[i].r);    
+		}
+
+		// computation of the det 
+		int number_of_errors=0;
+		for (i=0;i<nbt;i++) {
+			BamgVertex & v0 = triangles[i][0];
+			BamgVertex & v1 = triangles[i][1];
+			BamgVertex & v2 = triangles[i][2];
+
+			//If this is not a boundary triangle
+			if ( &v0 && &v1 &&  &v2 ){
+
+				/*Compute determinant*/
+				triangles[i].det= det(v0,v1,v2);
+
+				/*Check that determinant is positive*/
+				if (triangles[i].det <=0){
+
+					/*increase number_of_errors and print error only for the first 20 triangles*/
+					number_of_errors++;
+					if (number_of_errors<20){
+						_printf_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")\n");
+					}
+				}
+			}
+
+			//else, set as -1
+			else triangles[i].det=-1;
+		}
+
+		if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
+	}
+	/*}}}*/
+	void Mesh::SmoothingVertex(int nbiter,double omega ) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SmoothingVertex)*/
+
+		long int verbose=0;
+		//  if quatree exist remove it end reconstruct
+		if (quadtree) delete quadtree;
+		quadtree=0;
+		CreateSingleVertexToTriangleConnectivity();
+		Triangle vide; // a triangle to mark the boundary vertex
+		Triangle   ** tstart= new Triangle* [nbv];
+		long i,j,k;
+		//   attention si Background == Triangle alors on ne peut pas utiliser la rechech rapide 
+		if ( this == & BTh)
+		 for ( i=0;i<nbv;i++)
+		  tstart[i]=vertices[i].t;     
+		else 
+		 for ( i=0;i<nbv;i++)
+		  tstart[i]=0;
+		for ( j=0;j<NbVerticesOnGeomVertex;j++ ) 
+		 tstart[ GetId(VerticesOnGeomVertex[j].meshvertex)]=&vide;
+		for ( k=0;k<NbVerticesOnGeomEdge;k++ ) 
+		 tstart[ GetId(VerticesOnGeomEdge[k].meshvertex)]=&vide;
+		if(verbose>2) _printf_("   SmoothingVertex: nb Iteration = " << nbiter << ", Omega=" << omega << "\n");
+		for (k=0;k<nbiter;k++)
+		  {
+			long i,NbSwap =0;
+			double delta =0;
+			for ( i=0;i<nbv;i++)
+			 if (tstart[i] != &vide) // not a boundary vertex 
+			  delta=Max(delta,vertices[i].Smoothing(*this,BTh,tstart[i],omega));
+			if (!nbq)
+			 for ( i=0;i<nbv;i++)
+			  if (tstart[i] != &vide) // not a boundary vertex 
+				NbSwap += vertices[i].Optim(1);
+			if (verbose>3) _printf_("      move max = " << pow(delta,0.5) << ", iteration = " << k << ", nb of swap = " << NbSwap << "\n");
+		  }
+
+		delete [] tstart;
+		if (quadtree) quadtree= new BamgQuadtree(this);
+	}
+	/*}}}*/
+	void Mesh::SmoothMetric(double raisonmax) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/SmoothMetric)*/
+
+		long int verbose=0;
+
+		if(raisonmax<1.1) return;
+		if(verbose > 1) _printf_("   Mesh::SmoothMetric raisonmax = " << raisonmax << "\n");
+		CreateSingleVertexToTriangleConnectivity();
+		long i,j,kch,kk,ip;
+		long *first_np_or_next_t0 = new long[nbv];
+		long *first_np_or_next_t1 = new long[nbv];
+		long Head0 =0,Head1=-1;
+		double logseuil= log(raisonmax);
+
+		for(i=0;i<nbv-1;i++)
+		 first_np_or_next_t0[i]=i+1; 
+		first_np_or_next_t0[nbv-1]=-1;// end;
+		for(i=0;i<nbv;i++)
+		 first_np_or_next_t1[i]=-1;
+		kk=0;
+		while(Head0>=0&& kk++<100){
+			kch=0;
+			for(i=Head0;i>=0;i=first_np_or_next_t0[ip=i],first_np_or_next_t0[ip]=-1) {
+				//  pour tous les triangles autour du sommet s
+				Triangle* t= vertices[i].t;
+				if (!t){
+					_error_("!t");
+				}
+				BamgVertex & vi = vertices[i];
+				AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
+				BamgVertex *pvj0 = ta.EdgeVertex(0);
+				while (1) {
+					ta=Previous(Adj(ta));
+					if (vertices+i != ta.EdgeVertex(1)){
+						_error_("vertices+i != ta.EdgeVertex(1)");
+					}
+					BamgVertex & vj = *(ta.EdgeVertex(0));
+					if ( &vj ) {
+						j= &vj-vertices;
+						if (j<0 || j >= nbv){
+							_error_("j<0 || j >= nbv");
+						}
+						R2 Aij = (R2) vj - (R2) vi;
+						double ll =  Norme2(Aij);
+						if (0) {  
+							double hi = ll/vi.m(Aij);
+							double hj = ll/vj.m(Aij);
+							if(hi < hj)
+							  {
+								double dh=(hj-hi)/ll;
+								if (dh>logseuil) {
+									vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
+									if(first_np_or_next_t1[j]<0)
+									 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+								}
+							  }
+						} 
+						else
+						  {
+							double li = vi.m(Aij);
+							if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
+							 if(first_np_or_next_t1[j]<0) // if the metrix change 
+							  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+						  }
+					}
+					if  ( &vj ==  pvj0 ) break;
+				}
+			}
+			Head0 = Head1;
+			Head1 = -1;
+			Exchange(first_np_or_next_t0,first_np_or_next_t1);
+		}
+		if(verbose>2) _printf_("      number of iterations = " << kch << "\n"); 
+		delete [] first_np_or_next_t0;
+		delete [] first_np_or_next_t1;
+	}
+	/*}}}*/
+	long  Mesh::SplitInternalEdgeWithBorderVertices(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SplitInternalEdgeWithBorderVertices)*/
+
+		long NbSplitEdge=0;
+		SetVertexFieldOn();  
+		long it;
+		long nbvold=nbv;
+		long int verbose=2;
+		for (it=0;it<nbt;it++){
+			Triangle &t=triangles[it];
+			if (t.link)
+			 for (int j=0;j<3;j++)
+			  if(!t.Locked(j) && !t.Hidden(j)){
+				  Triangle &tt = *t.TriangleAdj(j);
+				  if ( &tt && tt.link && it < GetId(tt)) 
+					 { // an internal edge 
+					  BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+					  BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+					  if (v0.GeomEdgeHook && v1.GeomEdgeHook){
+						  R2 P= ((R2) v0 + (R2) v1)*0.5;
+						  if ( nbv<maxnbv) {
+							  vertices[nbv].r = P;
+							  vertices[nbv++].m = Metric(0.5,v0.m,0.5,v1.m);
+							  vertices[nbv].ReferenceNumber=0;
+							  vertices[nbv].DirOfSearch = NoDirOfSearch ;
+						  }
+						  NbSplitEdge++;
+					  }
+					 }
+			  }
+		}
+		CreateSingleVertexToTriangleConnectivity();    
+		if (nbvold!=nbv){
+			long  iv = nbvold;
+			long NbSwap = 0;
+			Icoor2 det3[3];  
+			for (int i=nbvold;i<nbv;i++) {// for all the new point
+				BamgVertex & vi = vertices[i];
+				vi.i = R2ToI2(vi.r);
+				vi.r = I2ToR2(vi.i);
+
+				// a good new point 
+				vi.ReferenceNumber=0; 
+				vi.DirOfSearch =NoDirOfSearch;
+				Triangle *tcvi = TriangleFindFromCoord(vi.i,det3);
+				if (tcvi && !tcvi->link) {
+					_printf_("problem inserting point in SplitInternalEdgeWithBorderVertices (tcvj && !tcvj->link)\n");
+				}
+
+				quadtree->Add(vi);
+				if (!tcvi || tcvi->det<0){// internal
+					_error_("!tcvi || tcvi->det < 0");
+				}
+				AddVertex(vi,tcvi,det3);
+				NbSwap += vi.Optim(1);          
+				iv++;
+			}
+			if (verbose>3) {
+				_printf_("   number of points: " << iv << "\n");
+				_printf_("   number of swap to  split internal edges with border vertices: " << NbSwap << "\n");
+				nbv = iv;
+			}
+		}
+		if (NbSplitEdge>nbv-nbvold) _printf_("WARNING: not enough vertices  to split all internal edges, we lost " << NbSplitEdge - ( nbv-nbvold) << " edges...\n");
+		if (verbose>2) _printf_("SplitInternalEdgeWithBorderVertices: Number of splited edge " << NbSplitEdge << "\n");
+
+		return  NbSplitEdge;
+	}
+	/*}}}*/
+	I2 Mesh::R2ToI2(const R2 & P) const {/*{{{*/
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)),(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}
+	/*}}}*/
+	R2 Mesh::I2ToR2(const I2 & P) const {/*{{{*/
+		return  R2( (double) P.x/coefIcoor+pmin.x, (double) P.y/coefIcoor+pmin.y);
+	}
+	/*}}}*/
+	Triangle * Mesh::TriangleFindFromCoord(const I2 & B,Icoor2 det3[3], Triangle *tstart) const {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindTriangleContening)*/
+
+		Triangle * t=0;	
+		int j,jp,jn,jj;
+		int counter;
+
+		/*Get starting triangle. Take tsart if provided*/
+		if (tstart) t=tstart;
+
+		/*Else find the closest Triangle using the quadtree*/
+		else {
+
+			/*Check that the quadtree does exist*/
+			if (!quadtree) _error_("no starting triangle provided and no quadtree available");
+
+			/*Call NearestVertex*/
+			BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
+
+			/*Check output (Vertex a)*/
+			if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
+			if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
+			_assert_(a>=vertices && a<vertices+nbv);
+
+			/*Get starting triangle*/
+			t = a->t;
+			_assert_(t>=triangles && t<triangles+nbt);
+		}
+
+		Icoor2  detop ;
+
+		/*initialize number of test triangle*/
+		counter=0; 
+
+		/*The initial triangle might be outside*/
+		while (t->det < 0){ 
+
+			/*Get a real vertex from this triangle (k0)*/
+			int k0=(*t)(0)?(((*t)(1)?((*t)(2)?-1:2):1)):0;
+			_assert_(k0>=0);// k0 the NULL vertex
+			int k1=NextVertex[k0],k2=PreviousVertex[k0];
+			det3[k0]=det(B,(*t)[k1],(*t)[k2]);
+			det3[k1]=det3[k2]=-1;     
+			if (det3[k0] > 0) // outside B 
+			 return t; 
+			t = t->TriangleAdj(OppositeEdge[k0]);
+			counter++;
+			_assert_(counter<2);
+		}
+
+		jj=0;
+		detop = det(*(*t)(VerticesOfTriangularEdge[jj][0]),*(*t)(VerticesOfTriangularEdge[jj][1]),B);
+
+		while(t->det>0){
+
+			/*Increase counter*/
+			if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
+
+			j= OppositeVertex[jj];
+			det3[j] = detop;  //det(*b,*s1,*s2);
+			jn = NextVertex[j];
+			jp = PreviousVertex[j];
+			det3[jp]= det(*(*t)(j),*(*t)(jn),B);
+			det3[jn] = t->det-det3[j] -det3[jp];
+
+			// count the number k of  det3 <0
+			int k=0,ii[3];
+			if (det3[0] < 0 ) ii[k++]=0; 
+			if (det3[1] < 0 ) ii[k++]=1;
+			if (det3[2] < 0 ) ii[k++]=2;
+			// 0 => ok
+			// 1 => go in way 1
+			// 2 => two way go in way 1 or 2 randomly
+
+			if (k==0) break;
+			if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
+			_assert_(k<3);
+			AdjacentTriangle t1 = t->Adj(jj=ii[0]);
+			if ((t1.det() < 0 ) && (k == 2))
+			 t1 = t->Adj(jj=ii[1]);
+			t=t1;
+			j=t1;// for optimisation we now the -det[OppositeVertex[j]];
+			detop = -det3[OppositeVertex[jj]];
+			jj = j;
+		}
+
+		if (t->det<0) // outside triangle 
+		 det3[0]=det3[1]=det3[2]=-1,det3[OppositeVertex[jj]]=detop;
+		return t;
+	}
+	/*}}}*/
+	void Mesh::TriangleIntNumbering(long* renumbering){/*{{{*/
+
+		long num=0;
+		for (int i=0;i<nbt;i++){
+			if (triangles[i].det>0) renumbering[i]=num++;
+			else renumbering[i]=-1;
+		}
+		return;   
+	}
+	/*}}}*/
+	long  Mesh::TriangleReferenceList(long* reft) const {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
+
+		Triangle *t0,*t;
+		long k=0, num;   
+
+		//initialize all triangles as -1 (outside)
+		for (int it=0;it<nbt;it++) reft[it]=-1;
+
+		//loop over all subdomains
+		for (int i=0;i<nbsubdomains;i++){ 
+
+			//first triangle of the subdomain i
+			t=t0=subdomains[i].head;
+
+			//check that the subdomain is not empty
+			if (!t0){ _error_("At least one subdomain is empty");}
+
+			//loop
+			do{
+				k++;
+
+				//get current triangle number
+				num = GetId(t);
+
+				//check that num is in [0 nbt[
+				_assert_(num>=0 && num<nbt);
+
+				//reft of this triangle is the subdomain number
+				reft[num]=i;
+
+			} while (t0 != (t=t->link));
+			//stop when all triangles of subdomains have been tagged
+
+		}
+		return k;   
+	}
+	/*}}}*/
+	void Mesh::Triangulate(double* x,double* y,int nods){/*{{{*/
+
+		int verbose=0;
+		int i;
+		Metric M1(1);
+
+		/*Initialize mesh*/
+		Init(nods);//this resets nbv to 0
+		nbv=nods;
+
+		//Vertices
+		if(verbose) _printf_("Reading vertices (" << nbv << ")\n");
+		for(i=0;i<nbv;i++){
+			vertices[i].r.x=x[i];
+			vertices[i].r.y=y[i];
+			vertices[i].ReferenceNumber=1;
+			vertices[i].DirOfSearch =NoDirOfSearch;
+			vertices[i].m=M1;
+			vertices[i].color=0;
+		}
+		maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+		/*Insert Vertices*/
+		Insert(true);
+	}
+	/*}}}*/
+	void Mesh::TriangulateFromGeom0(BamgOpts* bamgopts){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles0)*/
+		/*Generate mesh from geometry*/
+
+		/*Intermediaries*/
+		int                i,k;
+		int                nbcurves    = 0;
+		int                NbNewPoints,NbEdgeCurve;
+		double             lcurve,lstep,s;
+		const int          MaxSubEdge  = 10;
+
+		R2          AB;
+		GeomVertex *a, *b;
+		BamgVertex *va,*vb;
+		GeomEdge   *e;
+
+		// add a ref to GH to make sure that it is not destroyed by mistake
+		Gh.NbRef++;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		//build background mesh flag (1 if background, else 0)
+		bool background=(&BTh != this);
+
+		/*Build VerticesOnGeomVertex*/
+
+		//Compute the number of geometrical vertices that we are going to use to mesh
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) NbVerticesOnGeomVertex++;
+		}
+		//allocate
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];  
+		if(NbVerticesOnGeomVertex >= maxnbv) _error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		_assert_(nbv==0);
+		//Build VerticesOnGeomVertex
+		for (i=0;i<Gh.nbv;i++){
+			/* Add vertex only if required*/
+			if (Gh[i].Required()) {//Gh  vertices Required
+
+				//Add the vertex
+				_assert_(nbv<maxnbv);
+				vertices[nbv]=Gh[i];
+
+				//Add pointer from geometry (Gh) to vertex from mesh (Th)
+				Gh[i].MeshVertexHook=vertices+nbv;
+
+				//Build VerticesOnGeomVertex for current point
+				VerticesOnGeomVertex[nbv]=VertexOnGeom(*Gh[i].MeshVertexHook,Gh[i]);
+
+				//nbv increment
+				nbv++;
+			}
+		}
+
+		/*Build VerticesOnGeomEdge*/
+
+		//check that edges is still empty (Init)
+		_assert_(!edges);
+
+		/* Now we are going to create the first edges corresponding
+		 * to the one present in the geometry provided.
+		 * We proceed in 2 steps
+		 *  -step 0: we count all the edges
+		 *           we allocate the number of edges at the end of step 0
+		 *  -step 1: the edges are created */
+		for (int step=0;step<2;step++){
+
+			//initialize number of edges and number of edges max
+			long nbex=0;
+			nbe=0;
+			long NbVerticesOnGeomEdge0=NbVerticesOnGeomEdge;
+			Gh.UnMarkEdges();	
+			nbcurves=0;
+
+			//go through the edges of the geometry
+			for (i=0;i<Gh.nbe;i++){
+
+				//ei = current Geometrical edge
+				GeomEdge &ei=Gh.edges[i];   
+
+				//loop over the two vertices of the edge ei
+				for(int j=0;j<2;j++) {
+
+					/*Take only required vertices (corner->beginning of a new curve)*/
+					if (!ei.Mark() && ei[j].Required()){ 
+
+						long  nbvend=0;
+						Edge* PreviousNewEdge=NULL;
+						lstep = -1;
+
+						/*If Edge is required (do that only once for the 2 vertices)*/
+						if(ei.Required()){
+							if (j==0){
+								//do not create internal points if required (take it as is)
+								if(step==0) nbe++;
+								else{ 
+									e=&ei;
+									a=ei(0);
+									b=ei(1);
+
+									//check that edges has been allocated
+									_assert_(edges);
+									edges[nbe].v[0]=a->MeshVertexHook;
+									edges[nbe].v[1]=b->MeshVertexHook;;
+									edges[nbe].ReferenceNumber = e->ReferenceNumber;
+									edges[nbe].GeomEdgeHook = e;
+									edges[nbe].adj[0] = 0;
+									edges[nbe].adj[1] = 0;
+									nbe++;
+								}
+							}
+						}
+
+						/*If Edge is not required: we are on a curve*/
+						else {
+							for (int kstep=0;kstep<=step;kstep++){
+								//kstep=0, compute number of edges (discretize curve)
+								//kstep=1  create the points and edge
+								PreviousNewEdge=0;
+								NbNewPoints=0;
+								NbEdgeCurve=0;
+								if (nbvend>=maxnbv) _error_("maximum number of vertices too low! Check the domain outline or increase maxnbv");
+								lcurve =0;
+								s = lstep; //-1 initially, then length of each sub edge
+
+								/*reminder: i = edge number, j=[0;1] vertex index in edge*/
+								k=j;            // k = vertex index in edge (0 or 1)
+								e=&ei;          // e = reference of current edge
+								a=ei(k);        // a = pointer toward the kth vertex of the current edge
+								va = a->MeshVertexHook; // va = pointer toward mesh vertex associated
+								e->SetMark();   // Mark edge
+
+								/*Loop until we reach the end of the curve*/
+								for(;;){ 
+									k = 1-k;            // other vertx index of the curve
+									b = (*e)(k);        // b = pointer toward the other vertex of the current edge
+									AB= b->r - a->r;   // AB = vector of the current edge
+									Metric MA = background ? BTh.MetricAt(a->r) :a->m ;  //Get metric associated to A
+									Metric MB = background ? BTh.MetricAt(b->r) :b->m ;  //Get metric associated to B
+									double ledge = (MA(AB) + MB(AB))/2;                  //Get edge length in metric
+
+									/* We are now creating the mesh edges from the geometrical edge selected above.
+									 * The edge will be divided according to the metric previously computed and cannot
+									 * be divided more than 10 times (MaxSubEdge). */
+
+									//By default, there is only one subedge that is the geometrical edge itself
+									int NbSubEdge = 1;
+
+									//initialize lSubEdge, holding the length of each subedge (cannot be higher than 10)
+									double lSubEdge[MaxSubEdge];
+
+									//Build Subedges according to the edge length
+									if (ledge < 1.5){
+										//if ledge < 1.5 (between one and 2), take the edge as is
+										lSubEdge[0] = ledge;
+									}
+									//else, divide the edge
+									else {
+										//compute number of subedges (division of the edge), Maximum is 10
+										NbSubEdge = Min( MaxSubEdge, (int) (ledge +0.5));
+										/*Now, we are going to divide the edge according to the metric.
+										 * Get segment by sement along the edge.
+										 * Build lSubEdge, which holds the distance between the first vertex
+										 * of the edge and the next point on the edge according to the 
+										 * discretization (each SubEdge is AB)*/
+										R2 A,B;
+										A=a->r;
+										Metric MAs=MA,MBs;
+										ledge=0; 
+										double x =0, xstep= 1./NbSubEdge;
+										for (int kk=0; kk < NbSubEdge; kk++,A=B,MAs=MBs ) {
+											x += xstep;
+											B =  e->F(k ? x : 1-x);
+											MBs= background ? BTh.MetricAt(B) : Metric(1-x,MA,x,MB);
+											AB = A-B;
+											lSubEdge[kk]=(ledge+=(MAs(AB)+MBs(AB))/2);
+										}
+									}
+
+									double lcurveb = lcurve+ledge;
+
+									/*Now, create corresponding points*/
+									while(s>=lcurve && s<=lcurveb && nbv<nbvend){
+
+										/*Schematic of current curve
+										 *
+										 *  a                   vb                  b          // vertex
+										 *  0              ll0     ll1              ledge      // length from a
+										 *  + --- + - ... - + --S-- + --- + - ... - +          // where is S
+										 *  0              kk0     kk1              NbSubEdge  // Sub edge index
+										 *
+										 */
+
+										double ss = s-lcurve;
+
+										/*Find the SubEdge containing ss using Dichotomy*/
+										int kk0=-1,kk1=NbSubEdge-1,kkk;
+										double ll0=0,ll1=ledge,llk;
+										while (kk1-kk0>1){
+											if (ss < (llk=lSubEdge[kkk=(kk0+kk1)/2]))
+											 kk1=kkk,ll1=llk;
+											else
+											 kk0=kkk,ll0=llk;
+										}
+										_assert_(kk1!=kk0);
+
+										/*Curvilinear coordinate in [0 1] of ss in current edge*/
+										// WARNING: This is what we would do
+										// ssa = (ss-ll0)/(ll1-ll0);
+										// aa = (kk0+ssa)/NbSubEdge
+										// This is what Bamg does:
+										double sbb = (ss-ll0)/(ll1-ll0);
+										/*Curvilinear coordinate in [0 1] of ss in current curve*/
+										double bb = (kk1+sbb)/NbSubEdge;
+										double aa = 1-bb;
+
+										// new vertex on edge
+										vb = &vertices[nbv++];
+										vb->m = Metric(aa,a->m,bb,b->m);
+										vb->ReferenceNumber = e->ReferenceNumber;
+										vb->DirOfSearch =NoDirOfSearch;
+										double abcisse = k ? bb : aa;
+										vb->r =  e->F(abcisse);
+										VerticesOnGeomEdge[NbVerticesOnGeomEdge++]= VertexOnGeom(*vb,*e,abcisse);        
+
+										// to take into account the direction of the edge
+										s += lstep;
+										edges[nbe].v[0]=va;
+										edges[nbe].v[1]=vb;
+										edges[nbe].ReferenceNumber =e->ReferenceNumber;
+										edges[nbe].GeomEdgeHook = e;
+										edges[nbe].adj[0] = PreviousNewEdge;
+										if(PreviousNewEdge) PreviousNewEdge->adj[1]=&edges[nbe];
+										PreviousNewEdge=edges+nbe;
+										nbe++;
+										va = vb;
+									}
+
+									/*We just added one edge to the curve: Go to the next one*/
+									lcurve = lcurveb;
+									e->SetMark();
+									a=b;
+
+									/*If b is required, we are on a new curve->break*/
+									if (b->Required()) break;
+									int kprev=k;
+									k = e->AdjVertexIndex[kprev];// next vertices
+									e = e->Adj[kprev];
+									_assert_(e);
+								}// for(;;)
+								vb = b->MeshVertexHook;
+
+								/*Number of edges in the last disretized curve*/
+								NbEdgeCurve = Max((long) (lcurve +0.5), (long) 1);
+								/*Number of internal vertices in the last disretized curve*/
+								NbNewPoints = NbEdgeCurve-1;
+								if(!kstep){
+									NbVerticesOnGeomEdge0 += NbNewPoints;
+									nbcurves++;
+								}
+								nbvend=nbv+NbNewPoints; 
+								lstep = lcurve / NbEdgeCurve; //approximately one
+							}// end of curve --
+							if (edges) { // last edges of the curves 
+								edges[nbe].v[0]=va;
+								edges[nbe].v[1]=vb;
+								edges[nbe].ReferenceNumber = e->ReferenceNumber;
+								edges[nbe].GeomEdgeHook = e;
+								edges[nbe].adj[0] = PreviousNewEdge;
+								edges[nbe].adj[1] = 0;
+								if(PreviousNewEdge) PreviousNewEdge->adj[1] = & edges[nbe];
+								nbe++;
+							}
+							else nbe += NbEdgeCurve;
+						} // end on  curve ---
+					}
+				}
+			} // for (i=0;i<nbe;i++)
+			if(!step) {
+				_assert_(!edges);
+				_assert_(!VerticesOnGeomEdge);
+
+				edges = new Edge[nbex=nbe];
+				if(NbVerticesOnGeomEdge0) VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge0];
+
+				// do the vertex on a geometrical vertex
+				_assert_(VerticesOnGeomEdge || NbVerticesOnGeomEdge0==0);
+				NbVerticesOnGeomEdge0 = NbVerticesOnGeomEdge;       
+			}
+			else{
+				_assert_(NbVerticesOnGeomEdge==NbVerticesOnGeomEdge0);
+			}
+		}
+
+		//Insert points inside existing triangles
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) _printf_("         Inserting boundary points\n");
+		Insert(bamgopts->random);
+
+		//Force the boundary
+		if (verbose>3) _printf_("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printf_("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) _printf_("      Inserting internal points\n");
+		NewPoints(*this,bamgopts,0) ;
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+	}
+	/*}}}*/
+	void Mesh::TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices){ /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles1)*/
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		Gh.NbRef++;// add a ref to Gh
+
+		/************************************************************************* 
+		 * method in 2 steps
+		 * 1 - compute the number of new edges to allocate
+		 * 2 - construct the edges
+		 * remark:
+		 * in this part we suppose to have a background mesh with the same geometry 
+		 * 
+		 * To construct the discretization of the new mesh we have to 
+		 * rediscretize the boundary of background Mesh 
+		 * because we have only the pointeur from the background mesh to the geometry.
+		 * We need the abcisse of the background mesh vertices on geometry
+		 * so a vertex is 
+		 * 0 on GeomVertex ;
+		 * 1 on GeomEdge + abcisse
+		 * 2 internal 
+		 *************************************************************************/
+
+		//Check that background mesh and current mesh do have the same geometry
+		_assert_(&BTh.Gh==&Gh);
+		BTh.NbRef++; // add a ref to BackGround Mesh
+
+		//Initialize new mesh
+		BTh.SetVertexFieldOn();
+		int* bcurve = new int[Gh.nbcurves]; // 
+
+		/* There are 2 ways to make the loop 
+		 * 1) on the geometry 
+		 * 2) on the background mesh
+		 *  if you do the loop on geometry, we don't have the pointeur on background,
+		 *  and if you do the loop in background we have the pointeur on geometry
+		 * so do the walk on  background */
+
+		NbVerticesOnGeomVertex=0;
+		NbVerticesOnGeomEdge=0;
+
+		/*STEP 1 copy of Required vertices*/
+
+		int i; 
+		for (i=0;i<Gh.nbv;i++) if (Gh[i].Required()) NbVerticesOnGeomVertex++;
+		printf("\n");
+		if(NbVerticesOnGeomVertex >= maxnbv){
+			_error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		}
+
+		VerticesOnGeomVertex = new VertexOnGeom[  NbVerticesOnGeomVertex];
+		VertexOnBThVertex    = new VertexOnVertex[NbVerticesOnGeomVertex];
+
+		//At this point there is NO vertex but vertices should have been allocated by Init
+		_assert_(vertices);
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) {//Gh vertices Required
+				vertices[nbv]  =Gh[i];
+				vertices[nbv].i=I2(0,0);
+				Gh[i].MeshVertexHook = vertices + nbv;// save Geom -> Th
+				VerticesOnGeomVertex[nbv]= VertexOnGeom(vertices[nbv],Gh[i]);
+				nbv++;
+			}
+			else Gh[i].MeshVertexHook=0;
+		} 
+		for (i=0;i<BTh.NbVerticesOnGeomVertex;i++){ 
+			VertexOnGeom &vog=BTh.VerticesOnGeomVertex[i];
+			if (vog.IsRequiredVertex()){
+				GeomVertex* gv=vog;
+				BamgVertex *bv = vog;
+				_assert_(gv->MeshVertexHook); // use of Geom -> Th
+				VertexOnBThVertex[NbVertexOnBThVertex++]=VertexOnVertex(gv->MeshVertexHook,bv);
+				gv->MeshVertexHook->m = bv->m; // for taking the metric of the background mesh
+			}
+		}
+		_assert_(NbVertexOnBThVertex==NbVerticesOnGeomVertex); /*This might be due to MaxCornerAngle too small*/
+
+		/*STEP 2: reseed boundary edges*/
+
+		//  find the begining of the curve in BTh
+		Gh.UnMarkEdges();	
+		int bfind=0;
+		for (int i=0;i<Gh.nbcurves;i++) bcurve[i]=-1; 
+
+		/*Loop over the backgrounf mesh BTh edges*/
+		for (int iedge=0;iedge<BTh.nbe;iedge++){      
+			Edge &ei = BTh.edges[iedge];
+
+			/*Loop over the 2 vertices of the current edge*/
+			for(int je=0;je<2;je++){
+
+				/* If one of the vertex is required we are in a new curve*/
+				if (ei[je].GeomEdgeHook->IsRequiredVertex()){ 
+
+					/*Get curve number*/
+					int nc=ei.GeomEdgeHook->CurveNumber;
+
+					//_printf_("Dealing with curve number " << nc << "\n");
+					//_printf_("edge on geometry is same as GhCurve? " << (ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge)?"yes":"no\n");
+					//if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge){
+					//	_printf_("Do we have the right extremity? curve first vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex])?"yes":"no\n");
+					//	_printf_("Do we have the right extremity? curve last  vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex])?"yes":"no\n");
+					//}
+					//BUG FIX from original bamg
+					/*Check that we are on the same edge and right vertex (0 or 1) */
+					if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex]){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+					else if ((ei.GeomEdgeHook==Gh.curves[nc].LastEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex]) && bcurve[nc]==-1){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+				}
+			}
+		} 
+		if (bfind!=Gh.nbcurves){
+			delete [] bcurve;
+			_error_("problem generating number of curves (" << Gh.nbcurves << " found in the geometry but " << bfind << " curve found in the mesh)");
+		}
+
+		// method in 2 + 1 step 
+		//  0.0) compute the length and the number of vertex to do allocation
+		//  1.0) recompute the length
+		//  1.1) compute the  vertex 
+
+		long nbex=0,NbVerticesOnGeomEdgex=0;
+		for (int step=0; step <2;step++){
+
+			long NbOfNewPoints=0;
+			long NbOfNewEdge=0;
+			long iedge;
+			Gh.UnMarkEdges();	
+			double L=0;
+
+			/*Go through all geometrical curve*/
+			for (int icurve=0;icurve<Gh.nbcurves;icurve++){ 
+
+				/*Get edge and vertex (index) of background mesh on this curve*/
+				iedge=bcurve[icurve]/2;
+				int jedge=bcurve[icurve]%2;
+
+				/*Get edge of Bth with index iedge*/
+				Edge &ei = BTh.edges[iedge];
+
+				/*Initialize variables*/
+				double Lstep=0;             // step between two points   (phase==1) 
+				long NbCreatePointOnCurve=0;// Nb of new points on curve (phase==1) 
+
+				/*Do phase 0 to step*/
+				for(int phase=0;phase<=step;phase++){
+
+					/*Current curve pointer*/
+					Curve *curve= Gh.curves+icurve;
+
+					/*Get index of current curve*/
+					int icurveequi= Gh.GetId(curve);
+
+					/*For phase 0, check that we are at the begining of the curve only*/
+					if(phase==0 &&  icurveequi!=icurve)  continue;
+
+					int   k0=jedge,k1;
+					Edge* pe=  BTh.edges+iedge;
+					int   iedgeequi=bcurve[icurveequi]/2;
+					int   jedgeequi=bcurve[icurveequi]%2;
+
+					int k0equi=jedgeequi,k1equi;		  
+					Edge * peequi= BTh.edges+iedgeequi;
+					GeomEdge *ongequi = peequi->GeomEdgeHook;
+
+					double sNew=Lstep;// abscisse of the new points (phase==1) 
+					L=0;// length of the curve
+					long i=0;// index of new points on the curve
+					GeomVertex * GA0 = *(*peequi)[k0equi].GeomEdgeHook;
+					BamgVertex *A0;
+					A0 = GA0->MeshVertexHook;  // the vertex in new mesh
+					BamgVertex *A1;
+					VertexOnGeom *GA1;
+					Edge* PreviousNewEdge = 0;
+
+					// New Curve phase 
+					_assert_(A0-vertices>=0 && A0-vertices<nbv);
+					if(ongequi->Required()){
+						GeomVertex *GA1 = *(*peequi)[1-k0equi].GeomEdgeHook;
+						A1 = GA1->MeshVertexHook;  //
+					}       
+					else {
+						for(;;){
+							Edge &ee=*pe; 
+							Edge &eeequi=*peequi; 
+							k1 = 1-k0; // next vertex of the edge 
+							k1equi= 1 - k0equi;
+							_assert_(pe && ee.GeomEdgeHook);
+							ee.GeomEdgeHook->SetMark();
+							BamgVertex & v0=ee[0], & v1=ee[1];
+							R2 AB=(R2)v1-(R2)v0;
+							double L0=L,LAB;
+							LAB=LengthInterpole(v0.m,v1.m,AB);
+							L+= LAB;
+
+							if (phase){
+								// computation of the new points for the given curve
+								while ((i!=NbCreatePointOnCurve) && sNew<=L) { 
+
+									//some checks
+									_assert_(sNew>=L0);
+									_assert_(LAB);
+									_assert_(vertices && nbv<maxnbv);
+									_assert_(edges && nbe<nbex);
+									_assert_(VerticesOnGeomEdge && NbVerticesOnGeomEdge<NbVerticesOnGeomEdgex);
+
+									// new vertex on edge
+									A1=vertices+nbv++;
+									GA1=VerticesOnGeomEdge+NbVerticesOnGeomEdge;
+									Edge* e = edges + nbe++;
+									double se= (sNew-L0)/LAB;
+									if (se<0 || se>=1.000000001){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = abscisseInterpole(v0.m,v1.m,AB,se,1);
+									if (se<0 || se>1){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = k1         ? se : 1. - se;
+									se = k1==k1equi ? se : 1. - se;
+									VertexOnBThEdge[NbVerticesOnGeomEdge++] = VertexOnEdge(A1,&eeequi,se); // save 
+									ongequi=Gh.ProjectOnCurve(eeequi,se,*A1,*GA1); 
+									A1->ReferenceNumber = eeequi.ReferenceNumber;
+									A1->DirOfSearch =NoDirOfSearch;
+									e->GeomEdgeHook = ongequi;
+									e->v[0]=A0;
+									e->v[1]=A1;
+									e->ReferenceNumber = eeequi.ReferenceNumber;
+									e->adj[0]=PreviousNewEdge;
+
+									if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+									PreviousNewEdge=e;
+									A0=A1;
+									sNew += Lstep;
+									if (++i== NbCreatePointOnCurve) break;
+								}
+							}
+
+							//some checks
+							_assert_(ee.GeomEdgeHook->CurveNumber==ei.GeomEdgeHook->CurveNumber);
+							if (ee[k1].GeomEdgeHook->IsRequiredVertex()) {
+								_assert_(eeequi[k1equi].GeomEdgeHook->IsRequiredVertex());
+								GeomVertex * GA1 = *eeequi[k1equi].GeomEdgeHook;
+								A1=GA1->MeshVertexHook;// the vertex in new mesh
+								_assert_(A1-vertices>=0 && A1-vertices<nbv);
+								break;
+							}
+							if (!ee.adj[k1]) {
+								_error_("adj edge " << BTh.GetId(ee) << ", nbe=" << nbe << ", Gh.vertices=" << Gh.vertices);
+							}
+							pe = ee.adj[k1]; // next edge
+							k0 = pe->Intersection(ee); 
+							peequi= eeequi.adj[k1equi];  // next edge
+							k0equi=peequi->Intersection(eeequi);            
+						}// for(;;) end of the curve
+					}
+
+					if (phase){ // construction of the last edge
+						Edge* e=edges + nbe++;
+						e->GeomEdgeHook  = ongequi;
+						e->v[0]=A0;
+						e->v[1]=A1;
+						e->ReferenceNumber = peequi->ReferenceNumber;
+						e->adj[0]=PreviousNewEdge;
+						e->adj[1]=0;
+						if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+						PreviousNewEdge = e;
+
+						_assert_(i==NbCreatePointOnCurve);
+					}
+
+					if (!phase)  { // 
+						long NbSegOnCurve = Max((long)(L+0.5),(long) 1);// nb of seg
+						Lstep = L/NbSegOnCurve; 
+						NbCreatePointOnCurve = NbSegOnCurve-1;
+						NbOfNewEdge += NbSegOnCurve;
+						NbOfNewPoints += NbCreatePointOnCurve;
+					}
+				}
+			}//  end of curve loop 
+
+			//Allocate memory
+			if(step==0){
+				if(nbv+NbOfNewPoints > maxnbv) {
+					_error_("too many vertices on geometry: " << nbv+NbOfNewPoints << " >= " << maxnbv);
+				}
+				edges = new Edge[NbOfNewEdge];
+				nbex = NbOfNewEdge;
+				if(NbOfNewPoints) {
+					VerticesOnGeomEdge    = new VertexOnGeom[NbOfNewPoints];
+					NbVertexOnBThEdge     = NbOfNewPoints;
+					VertexOnBThEdge       = new  VertexOnEdge[NbOfNewPoints];
+					NbVerticesOnGeomEdgex = NbOfNewPoints;
+				}
+				NbOfNewPoints =0;
+				NbOfNewEdge = 0;
+			}
+		}
+		_assert_(nbe!=0);
+		delete [] bcurve;
+
+		//Insert points inside existing triangles
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) _printf_("         Inserting boundary points\n");
+		Insert(bamgopts->random);
+
+		//Force the boundary
+		if (verbose>3) _printf_("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printf_("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) _printf_("      Inserting internal points\n");
+		NewPoints(BTh,bamgopts,KeepVertices) ;
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+	}
+	/*}}}*/
+
+	/*Intermediary*/
+	AdjacentTriangle CloseBoundaryEdge(I2 A,Triangle *t, double &a,double &b) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CloseBoundaryEdge)*/
+
+		int k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
+		int dir=0;
+		if (k<0){
+			_error_("k<0");
+		}
+		int kkk=0;  
+		Icoor2 IJ_IA,IJ_AJ;
+		AdjacentTriangle edge(t,OppositeEdge[k]);          
+		for (;;edge = dir >0 ? Next(Adj(Next(edge))) : Previous(Adj(Previous(edge)))) {  
+			kkk++;
+			if (kkk>=1000){
+				_error_("kkk>=1000");
+			}
+			BamgVertex  &vI =  *edge.EdgeVertex(0);
+			BamgVertex  &vJ =  *edge.EdgeVertex(1);
+			I2 I=vI, J=vJ, IJ= J-I;
+			IJ_IA = (IJ ,(A-I));
+			if (IJ_IA<0) {
+				if (dir>0) {a=1;b=0;return edge;}// change of signe => I
+				else {dir=-1;
+					continue;}};// go in direction i 
+					IJ_AJ = (IJ ,(J-A));
+					if (IJ_AJ<0) {
+						if(dir<0)  {a=0;b=1;return edge;}            
+						else {dir = 1;
+							continue;}}// go in direction j
+							double IJ2 = IJ_IA + IJ_AJ;
+							if (IJ2==0){
+								_error_("IJ2==0");
+							}
+							a= IJ_AJ/IJ2;
+							b= IJ_IA/IJ2;
+							return edge;
+		} 
+	}
+	/*}}}*/
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+		int NbSwap =0;
+		if (!a.t || !b.t){ // the 2 vertex is in a mesh
+			_error_("!a.t || !b.t");
+		}
+		int k=0;
+		taret=AdjacentTriangle(0,0); // erreur 
+
+		AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+		BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+		// we turn around a in the  direct direction  
+
+		Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
+		if(v2) // normal case 
+		 det2 = det(*v2,a,b);
+		else { // no chance infini vertex try the next
+			tta= Previous(Adj(tta));
+			v2 = tta.EdgeVertex(0);
+			vbegin =v2;
+			if (!v2){
+				_error_("!v2");
+			}
+			det2 = det(*v2,a,b);
+		}
+
+		while (v2 != &b) {
+			AdjacentTriangle tc = Previous(Adj(tta));    
+			v1 = v2; 
+			v2 = tc.EdgeVertex(0);
+			det1 = det2;
+			det2 =  v2 ? det(*v2,a,b): det2; 
+
+			if((det1 < 0) && (det2 >0)) { 
+				// try to force the edge 
+				BamgVertex * va = &a, *vb = &b;
+				tc = Previous(tc);
+				if (!v1 || !v2){
+					_error_("!v1 || !v2");
+				}
+				Icoor2 detss = 0,l=0;
+				while ((SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+				 if(l++ > 10000000) {
+					 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+				 }
+				BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
+				if (((aa == &a ) && (bb == &b)) ||((bb ==  &a ) && (aa == &b))){
+					tc.SetLock();
+					a.Optim(1,0);
+					b.Optim(1,0);
+					taret = tc;
+					return NbSwap;
+				}
+				else 
+				  {
+					taret = tc;
+					return -2; // error  boundary is crossing
+				  }
+			}
+			tta = tc;
+			k++;
+			if (k>=2000){
+				_error_("k>=2000");
+			}
+			if ( vbegin == v2 ) return -1;// error 
+		}
+
+		tta.SetLock();
+		taret=tta;
+		a.Optim(1,0);
+		b.Optim(1,0);
+		return NbSwap; 
+	}
+	/*}}}*/
+	void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+		// --------------------------------------------------------------
+		// short a2=aa[a];// les 2 numero de l arete dans les 2 triangles
+		//                               
+		//               sb                     sb    
+		//             / | \                   /   \                      !
+		//         as1/  |  \                 /a2   \                     !
+		//           /   |   \               /    t2 \                    !
+		//       s1 /t1  | t2 \s2  -->   s1 /___as2___\s2                 !
+		//          \  a1|a2  /             \   as1   /  
+		//           \   |   /               \ t1    /   
+		//            \  |  / as2             \   a1/    
+		//             \ | /                   \   /     
+		//              sa                       sa   
+		//  -------------------------------------------------------------
+		int as1 = NextEdge[a1];
+		int as2 = NextEdge[a2];
+		int ap1 = PreviousEdge[a1];
+		int ap2 = PreviousEdge[a2];
+		(*t1)(VerticesOfTriangularEdge[a1][1]) = s2 ; // avant sb
+		(*t2)(VerticesOfTriangularEdge[a2][1]) = s1  ; // avant sa
+		// mise a jour des 2 adjacences externes 
+		AdjacentTriangle taas1 = t1->Adj(as1),
+							  taas2 = t2->Adj(as2),
+							  tas1(t1,as1), tas2(t2,as2),
+							  ta1(t1,a1),ta2(t2,a2);
+		// externe haut gauche
+		taas1.SetAdj2(ta2, taas1.GetAllFlag_UnSwap());
+		// externe bas droite
+		taas2.SetAdj2(ta1, taas2.GetAllFlag_UnSwap());
+		// remove the Mark  UnMarkSwap 
+		t1->SetUnMarkUnSwap(ap1);
+		t2->SetUnMarkUnSwap(ap2);
+		// interne 
+		tas1.SetAdj2(tas2);
+
+		t1->det = det1;
+		t2->det = det2;
+
+		t1->SetSingleVertexToTriangleConnectivity();
+		t2->SetSingleVertexToTriangleConnectivity();
+	} // end swap 
+	/*}}}*/
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
+		// l'arete ta coupe l'arete pva pvb
+		// de cas apres le swap sa coupe toujours
+		// on cherche l'arete suivante 
+		// on suppose que detsa >0 et detsb <0
+		// attention la routine echange pva et pvb 
+
+		if(tt1.Locked()) return 0; // frontiere croise 
+
+		AdjacentTriangle tt2 = Adj(tt1);
+		Triangle *t1=tt1,*t2=tt2;// les 2 triangles adjacent
+		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
+		if ( a1<0 || a1>=3 ){
+			_error_("a1<0 || a1>=3");
+		}
+
+		BamgVertex & sa= (* t1)[VerticesOfTriangularEdge[a1][0]];
+		BamgVertex & s1= (*t1)[OppositeVertex[a1]];
+		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
+
+		Icoor2 dets2 = det(*pva,*pvb,s2);
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		if ((det1<=0 ) || (det2<=0)){
+			_error_("(det1<=0 ) || (det2<=0)");
+		}
+		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
+			_error_("(detsa>=0) || (detsb<=0)");
+		}
+		Icoor2 ndet1 = bamg::det(s1,sa,s2);
+		Icoor2 ndet2 = detT - ndet1;
+
+		int ToSwap =0; //pas de swap
+		if ((ndet1 >0) && (ndet2 >0)) 
+		  { // on peut swaper  
+			if ((dets1 <=0 && dets2 <=0) || (dets2 >=0 && detsb >=0))
+			 ToSwap =1; 
+			else // swap alleatoire 
+			 if (BinaryRand()) 
+			  ToSwap =2; 
+		  }
+		if (ToSwap) NbSwap++,
+		 bamg::swap(t1,a1,t2,a2,&s1,&s2,ndet1,ndet2);
+
+		int ret=1;
+
+		if (dets2 < 0) {// haut
+			dets1 = ToSwap ? dets1 : detsa ;
+			detsa = dets2; 
+			tt1 =  Previous(tt2) ;}
+		else if (dets2 > 0){// bas 
+			dets1 = ToSwap ? dets1 : detsb ;
+			detsb = dets2;
+			//xxxx tt1 = ToSwap ? tt1 : Next(tt2);
+			if(!ToSwap) tt1 =  Next(tt2);
+		}
+		else { // changement de direction 
+			ret = -1;
+			Exchange(pva,pvb);
+			Exchange(detsa,detsb);
+			Exchange(dets1,dets2);
+			Exchange(tt1,tt2);
+			dets1=-dets1;
+			dets2=-dets2;
+			detsa=-detsa;
+			detsb=-detsb;
+
+			if(ToSwap){
+				if (dets2 < 0) {// haut
+					dets1 = (ToSwap ? dets1 : detsa) ;
+					detsa = dets2; 
+					tt1 =  Previous(tt2) ;}
+				else if(dets2 > 0){// bas 
+					dets1 = (ToSwap ? dets1 : detsb) ;
+					detsb =  dets2;
+					if(!ToSwap) tt1 =  Next(tt2);
+				}
+				else {// on a fin ???
+					tt1 = Next(tt2);
+					ret =0;}
+			}
+
+		}
+		return ret;
+	}
+	/*}}}*/
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Mesh.h	(revision 18231)
@@ -0,0 +1,187 @@
+#ifndef _MESH_H_
+#define _MESH_H_
+
+#include "./include.h"
+#include "./BamgOpts.h"
+#include "./BamgMesh.h"
+#include "./BamgGeom.h"
+#include "./Triangle.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./ListofIntersectionTriangles.h"
+
+namespace bamg {
+
+	class Geometry;
+	class CrackedEdge;
+	class BamgQuadtree;
+	class SubDomain;
+
+	class Mesh {
+
+		public:
+
+			Geometry                    & Gh;                    // Geometry
+			Mesh                        & BTh;                   // Background Mesh Bth== *this =>no background
+			BamgVertex                   *vertices;
+			Triangle                     *triangles;
+			Edge                         *edges;
+			BamgQuadtree                 *quadtree;
+			BamgVertex                  **orderedvertices;
+			SubDomain                    *subdomains;
+			long                          NbRef;                 // counter of ref on the this class if 0 we can delete
+			long                          maxnbv,maxnbt;         // nombre max de sommets , de triangles
+			long                          nbv,nbt,nbe,nbq;       // nb of vertices, of triangles, of edges and quadrilaterals
+			long                          nbsubdomains;
+			long                          nbtout;                // Nb of oudeside triangle
+
+			R2                            pmin,pmax;             // extrema
+			double                        coefIcoor;             // coef to integer Icoor1;
+			ListofIntersectionTriangles   lIntTria;
+
+			long                          NbVerticesOnGeomVertex;
+			VertexOnGeom                 *VerticesOnGeomVertex;
+			long                          NbVerticesOnGeomEdge;
+			VertexOnGeom                 *VerticesOnGeomEdge;
+			long                          NbVertexOnBThVertex;
+			VertexOnVertex               *VertexOnBThVertex;
+			long                          NbVertexOnBThEdge;
+			VertexOnEdge                 *VertexOnBThEdge;
+			long                          NbCrackedVertices;
+			long                         *CrackedVertices;
+			long                          NbCrackedEdges;
+			CrackedEdge                  *CrackedEdges;
+
+			//Constructors/Destructors
+			Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh,BamgOpts* bamgopts);
+			Mesh(int* index,double* x,double* y,int nods,int nels);/*MeshConvert*/
+			Mesh(double* x,double* y,int nods); /*BamgTriangulate*/
+			Mesh(Mesh &,Geometry * pGh=0,Mesh* pBTh=0,long maxnbv_in=0 ); //copy operator
+			Mesh(const Mesh &,const int *flag,const int *bb,BamgOpts* bamgopts); // truncature
+			Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices=1);
+			Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts);
+			~Mesh(); 
+
+			//Operators
+			const BamgVertex &operator[](long i) const { return vertices[i];  };
+			BamgVertex       &operator[](long i) { return vertices[i];        };
+			const Triangle   &operator()(long i) const { return triangles[i]; };
+			Triangle         &operator()(long  i) { return triangles[i];             };
+
+			//Methods
+			void SetIntCoor(const char * from =0);
+			double MinimalHmin();
+			double MaximalHmax();
+			I2 R2ToI2(const R2 & P) const;
+			R2 I2ToR2(const I2 & P) const;
+			void AddVertex(BamgVertex & s,Triangle * t,Icoor2 *  =0) ;
+			void Insert(bool random);
+			void Echo(void);
+			void ForceBoundary();
+			void FindSubDomain(int OutSide=0);
+			long TriangleReferenceList(long*) const;
+			void TriangleIntNumbering(long* renumbering);
+			void CrackMesh(BamgOpts* bamgopts);
+			void SmoothMetric(double raisonmax) ;
+			void BoundAnisotropy(double anisomax,double hminaniso= 1e-100) ;
+			void MaxSubDivision(double maxsubdiv);
+			Edge** MakeGeomEdgeToEdge();
+			long SplitInternalEdgeWithBorderVertices();
+			void MakeQuadrangles(double costheta);
+			void MakeBamgQuadtree();
+			void NewPoints(Mesh &,BamgOpts* bamgopts,int KeepVertices=1);
+			long InsertNewPoints(long nbvold,long & NbTSwap,bool random); 
+			void TrianglesRenumberBySubDomain(bool justcompress=false);
+			void SmoothingVertex(int =3,double=0.3);
+			Metric MetricAt (const R2 &) const;
+			GeomEdge* ProjectOnCurve( Edge & AB, BamgVertex &  A, BamgVertex & B,double theta, BamgVertex & R,VertexOnEdge & BR,VertexOnGeom & GR);
+			long GetId(const Triangle & t) const;
+			long GetId(const Triangle * t) const;
+			long GetId(const BamgVertex & t) const;
+			long GetId(const BamgVertex * t) const;
+			long GetId(const Edge & t) const;
+			long GetId(const Edge * t) const;
+			BamgVertex* NearestVertex(Icoor1 i,Icoor1 j) ;
+			Triangle* TriangleFindFromCoord(const I2 & ,Icoor2 [3],Triangle *tstart=0) const;
+			void ReadMesh(int* index,double* x,double* y,int nods,int nels);
+			void ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts);
+			void WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts);
+			void ReadMetric(const BamgOpts* bamgopts);
+			void WriteMetric(BamgOpts* bamgopts);
+			void WriteIndex(int** pindex,int* pnels);
+			void AddMetric(BamgOpts* bamgopts);
+			void BuildMetric0(BamgOpts* bamgopts);
+			void BuildMetric1(BamgOpts* bamgopts);
+			void AddGeometryMetric(BamgOpts* bamgopts);
+			void BuildGeometryFromMesh(BamgOpts* bamgopts=NULL);
+			void ReconstructExistingMesh();
+
+			//Inline methods
+			inline  void CreateSingleVertexToTriangleConnectivity(){
+				for (int i=0;i<nbv;i++) vertices[i].IndexInTriangle=0, vertices[i].t=NULL;
+				for (int i=0;i<nbt;i++) triangles[i].SetSingleVertexToTriangleConnectivity();
+			}
+			inline  void  UnMarkUnSwapTriangle(){
+				for (int i=0;i<nbt;i++)
+				 for(int j=0;j<3;j++)
+				  triangles[i].SetUnMarkUnSwap(j);
+			  }
+			inline  void  SetVertexFieldOn(){
+				for (int i=0;i<nbv;i++)                    vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVerticesOnGeomVertex;j++) VerticesOnGeomVertex[j].SetOn();
+				for (int k=0;k<NbVerticesOnGeomEdge;k++ )  VerticesOnGeomEdge[k].SetOn();
+			}	       
+			inline  void   SetVertexFieldOnBTh(){
+				for (int i=0;i<nbv;i++)                 vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVertexOnBThVertex;j++) VertexOnBThVertex[j].SetOnBTh();
+				for (int k=0;k<NbVertexOnBThEdge;k++ )  VertexOnBThEdge[k].SetOnBTh();
+			}
+
+		private:
+			void TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices=1);// the real constructor mesh adaption
+			void TriangulateFromGeom0(BamgOpts* bamgopts);// the real constructor mesh generator
+			void Triangulate(double* x,double* y,int nods);
+			void Init(long);
+	};
+
+	/*Intermediary*/
+	AdjacentTriangle CloseBoundaryEdge(I2 ,Triangle *, double &,double &) ;
+	void  swap(Triangle *t1,short a1,
+				Triangle *t2,short a2,
+				BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2);
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
+				AdjacentTriangle & tt1,Icoor2 & dets1,
+				Icoor2 & detsa,Icoor2 & detsb, int & nbswap);
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+	inline AdjacentTriangle Previous(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,PreviousEdge[ta.a]);
+	}
+	inline AdjacentTriangle Next(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,NextEdge[ta.a]);
+	}
+	inline  AdjacentTriangle Adj(const AdjacentTriangle & a){
+		return  a.Adj();
+	}
+	inline void Adj(GeomEdge * & on,int &i){
+		int j=i;i=on->AdjVertexIndex[i];on=on->Adj[j];
+	}
+	inline double qualite(const BamgVertex &va,const BamgVertex &vb,const BamgVertex &vc){
+		double ret; 
+		I2 ia=va,ib=vb,ic=vc;
+		I2 ab=ib-ia,bc=ic-ib,ac=ic-ia;
+		Icoor2 deta=Det(ab,ac);
+		if (deta <=0) ret = -1;
+		else {
+			double a = sqrt((double) (ac,ac)),
+					 b = sqrt((double) (bc,bc)),
+					 c = sqrt((double) (ab,ab)),
+					 p = a+b+c;
+			double h= Max(Max(a,b),c),ro=deta/p;
+			ret = ro/h;
+		}
+		return ret;
+	}
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.cpp	(revision 18231)
@@ -0,0 +1,341 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "Metric.h"
+#include "../shared/shared.h"
+
+using namespace std;
+
+namespace bamg {
+
+	SaveMetricInterpole  LastMetricInterpole;
+
+	/*Constructor/Destructor*/
+	Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){/*{{{*/
+
+	}/*}}}*/
+	Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){/*{{{*/
+
+	}/*}}}*/
+	Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric& m2 ){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/Metric)*/
+
+		Metric mab(a[0]*m0.a11 + a[1]*m1.a11 + a[2]*m2.a11,
+					a[0]*m0.a21 + a[1]*m1.a21 + a[2]*m2.a21,
+					a[0]*m0.a22 + a[1]*m1.a22 + a[2]*m2.a22);
+
+		EigenMetric vab(mab);
+
+		R2 v1(vab.v.x,vab.v.y);
+		R2 v2(-v1.y,v1.x);
+
+		double h1 = a[0] / m0(v1) + a[1] / m1(v1) + a[2] / m2(v1);
+		double h2 = a[0] / m0(v2) + a[1] / m1(v2) + a[2] / m2(v2);
+
+		vab.lambda1 =  1 / (h1*h1);
+		vab.lambda2 =  1 / (h2*h2);
+		*this = vab;
+	}
+	/*}}}*/
+	Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/EigenMetric)*/
+
+		/*Compute metric (linear combination of ma and mb)*/
+		Metric mab(a*ma.a11+b*mb.a11,a*ma.a21+b*mb.a21,a*ma.a22+b*mb.a22);
+
+		/*Get Eigen values and vectors*/
+		EigenMetric vab(mab);
+		R2 v1(vab.v.x,vab.v.y);
+		R2 v2(-v1.y,v1.x);
+
+		/*Modify eigen values (a+b=1)*/
+		double h1 = a/ma(v1) + b/mb(v1);
+		double h2 = a/ma(v2) + b/mb(v2);
+		vab.lambda1 =  1/(h1*h1);
+		vab.lambda2 =  1/(h2*h2);
+		*this=vab;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	double Metric::det() const {/*{{{*/
+		return a11*a22-a21*a21;
+	}  /*}}}*/
+	void Metric::Echo(void){/*{{{*/
+
+		_printf_("Metric:\n");
+		_printf_("   [a11 a21 a22]: [" << a11 << " " << a21 << " " << a22 << "]\n");
+
+		return;
+	}
+	/*}}}*/
+	int Metric::IntersectWith(const Metric& M2) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectWith)*/
+
+		/*Get a new metric from an existing metric (M1=this)
+		 * and a new metric given in input M2 using a 
+		 * Simultaneous Matrix Reduction:
+		 * If M1 and M2 are 2 metrics, we must build N=M1^-1 M2 (Alauzet2003 p16) 
+		 * the eigen vectors of N form a matrix P
+		 * The new metric M = M1 inter M2 is then given by:
+		 *
+		 *      -T [ max(lambda1, mu1)          0         ]  -1				 
+		 * M = P   [                                      ] P		 
+		 *         [        0            max(lambda2, mu2)] 
+		 *
+		 * where lambdai and mui can be computed using Rayleigh formula: 
+		 *    lambdai = vi' M1 vi
+		 * with vi eigen vectors of N (columns of P)
+		 */
+
+		int         change=0;
+		Metric &M1=*this;
+		D2xD2       P;
+
+		//Get P, eigen vectors of N=inv(M1) M2
+		SimultaneousMatrixReduction(*this,M2,P);
+
+		//extract the eigen vectors of P (columns)
+		R2 v1(P.x.x,P.y.x);
+		R2 v2(P.x.y,P.y.y);
+
+		//compute lambdai mui
+		double lambda1=M1(v1,v1);
+		double lambda2=M1(v2,v2);
+		double mu1=M2(v1,v1);
+		double mu2=M2(v2,v2);
+
+		//check where any change needs to be done on M1
+		if ( lambda1 < mu1 )  change=1,lambda1=mu1;
+		if ( lambda2 < mu2 )  change=1,lambda2=mu2; 
+
+		//update M1 if necessary
+		if (change) {
+			D2xD2 invP(P.inv());
+			D2xD2 D(lambda1,0,0,lambda2); 
+			D2xD2 M(invP.t()*D*invP);
+			a11=M.x.x;
+			a21=0.5*(M.x.y+M.y.x);
+			a22=M.y.y;
+		}
+		return change;
+	}
+	/*}}}*/
+	R2     Metric::mul(const R2 x)const {/*{{{*/
+		return R2(a11*x.x+a21*x.y,a21*x.x+a22*x.y);
+	}/*}}}*/
+
+	/*Intermediary*/
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/LengthInterpole)*/
+
+		double k=1./2.;
+		int level=0;
+		static int kkk=0;
+		static  Metric Ms1[32],Ms2[32];
+		static double lMs1[32],lMs2[32];
+		static double K[32];
+		double l=0,sss=0;
+		Ms1[level]=Ma;
+		Ms2[level]=Mb;
+		double sa =  Ma(AB);
+		double sb =  Mb(AB);
+		lMs1[level]=sa;
+		lMs2[level]=sb;
+		K[level]=k;
+		level++;
+		int i=0;
+		double * L= LastMetricInterpole.L, *S = LastMetricInterpole.S;
+		double  sstop = 0.1; // Max(0.6,(sa+sb)/5000);
+		while (level) {
+			level--;
+			Metric M1=Ms1[level];
+			Metric M2=Ms2[level];
+			k=K[level];
+			double s1=  lMs1[level];
+			double s2=  lMs2[level];
+
+			double s= (s1+s2)*k;
+			if( s > sstop   && level < 30 && i < 500-level ) {
+				Metric Mi(0.5,M1,0.5,M2);
+				double si = Mi(AB);
+				if( Abs((s1+s2)-(si+si)) > s1*0.001) 
+				  {
+					k=k/2;
+					// we begin by the end to walk in the correct direction from a to b
+					// due to the stack 
+					Ms1[level]=Mi;
+					Ms2[level]=M2;
+					lMs1[level]=si;
+					lMs2[level]=s2;
+					K[level]=k;
+					level++;
+					Ms1[level]=M1;
+					Ms2[level]=Mi;
+					lMs1[level]=s1;
+					lMs2[level]=si;
+					K[level]=k;
+					level++;
+				  }
+				else
+				 L[i]= l += s,S[i]=sss+=k,i++;
+			}
+			else 
+			 L[i]= l += s,S[i]=sss+=k,i++;
+		}
+		// warning for optimisation S is in [0:0.5] not in [0:1]
+		if (i>=512){
+			_error_("i>=512");
+		}
+		LastMetricInterpole.lab=l;
+		LastMetricInterpole.opt=i;
+		if (i>200 && kkk++<10) _printf_("WARNING: LengthInterpole: ( i=" << i << " l=" << l << " sss=" << sss << " ) " << sstop << "\n"); 
+		return l;
+	}
+	/*}}}*/
+	void SimultaneousMatrixReduction( Metric M1,  Metric M2, D2xD2 &V) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/ReductionSimultanee)*/
+
+		/*In this routine we must return a matrix V that is composed of the 
+		 * eigen vectors of N=inv(M1) M2.
+		 * Instead of looking at N directly, we are going to use the fact that
+		 * M1 and M2 are symmetrical, positive definite. 
+		 * The eigen values of N are given by solving
+		 *    inv(M1) M2 V = lambda V
+		 * which is equivalent to
+		 *    M2 V = lambda M1 V
+		 * and we will hence solve
+		 *    (M2 - lambda M1) V = 0
+		 */
+
+		//M1 and M2 components
+		double a11=M1.a11,a21=M1.a21,a22=M1.a22;
+		double b11=M2.a11,b21=M2.a21,b22=M2.a22;
+
+		/*To get the eigen values, we solve the following problem:
+		 *    det(M2-lambda M1) = 0
+		 *    (b11 - lambda a11)(b22-lambda a22) - (b21-lambda a21)^2
+		 * and we have the following trinome:
+		 *    a lambda^2 + b lambda + c =0
+		 * with:
+		 *    a = a11 a22 - a21 a21 (=det(M1))
+		 *    b = -a11 b22 -b11 a22 + 2 b21 a21
+		 *    c = b11 b22 - b21 b21 (=det(M2))
+		 *    */
+		const double a= a11*a22  - a21*a21;
+		const double b=-a11*b22 - b11*a22+2*b21*a21;
+		const double c=-b21*b21 + b11*b22;
+		const double bb=b*b,ac=a*c;
+		const double delta= bb-4*ac;
+
+		// first, case of a double root if:
+		//  - all the terms are very small (a??)
+		//  - or : delta is very small
+		if ( (bb + Abs(ac) < 1.0e-34 ) ||  (delta < 1.0e-6*bb) ){
+			//all vectors are eigen vectors -> choose 1,0 and 0,1
+			V= D2xD2(1,0,0,1);
+		}
+
+		//general case: two distinct roots: lambda1 and lambda2
+		else {
+
+			/*Compute eigen values*/
+			const double delta2 = sqrt(delta);
+			double lambda[2];
+			lambda[0]= (-b - delta2)/(2*a);
+			lambda[1]= (-b + delta2)/(2*a);
+
+			/*compute eigen vectors*/
+			double vp[2][2];
+			double v0,v1,v2;
+			double s0,s1;
+
+			for(int i=0;i<2;i++){
+				/*Now, one must find the eigen vectors. For that we use the 
+				 * following property of the inner product
+				 *    (Ax,b) = transp(b) Ax = transp(x) transp(A) b
+				 *           = (transp(A) b ,x)
+				 * Here we are dealing with A= M2 - lambda M1 which is symmetrical:
+				 *    for all (x,y) in R2 
+				 *       ((M2 - lambda M1)x,y)=((M2 - lambda M1)y,x)
+				 * If y is in Ker(M2 - lambda M1):
+				 *    for all x in R2
+				 *       ((M2 - lambda M1)y,x)=0
+				 * This shows that:
+				 *    Ker(M2 - lambda M1) is orthogonal to Im(M2 - lambda M1)
+				 * To find the eigen vectors, we only have to find two vectors
+				 * of the image and take their perpendicular as long as they are
+				 * not 0.
+				 * To do that, we take (1,0) and (0,1) and take the larger norm*/
+
+				//compute V = M2 - lambdai M1
+				v0 = b11 - lambda[i]*a11;
+				v1 = b21 - lambda[i]*a21;
+				v2 = b22 - lambda[i]*a22;
+
+				// compute s1=norm(V(1,0)) and s0=norm(V(0,1))
+				s0 = v0*v0 + v1*v1;
+				s1 = v1*v1 + v2*v2;
+
+				//compute vp1 = (vp1x,vp1y)
+				if(s1 < s0){
+					s0=sqrt(s0);
+					vp[0][i]=   v1/s0;
+					vp[1][i]= - v0/s0;
+				}
+				else{
+					s1=sqrt(s1);
+					vp[0][i]=   v2/s1;
+					vp[1][i]= - v1/s1;
+				}
+			}
+
+			//compute V from vp
+			V=D2xD2(vp[0][0],vp[0][1],vp[1][0],vp[1][1]);
+		}
+	}
+	/*}}}*/
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/abscisseInterpole)*/
+
+		if(!optim)  LengthInterpole(Ma,Mb,AB);
+		double l  = s* LastMetricInterpole.lab,r;
+		int j=LastMetricInterpole.opt-1;
+
+		double * L= LastMetricInterpole.L, *S = LastMetricInterpole.S;
+		// warning for optimisation S is the abcisse in [0:0.5]
+		// and L is le lenght 
+		if(l<=L[0]){
+			r=2*S[0]*l/L[0];
+		}
+		else if (l>=L[j]){
+			r=1;
+		}
+		else{
+			int i=0;
+			while (j-i>1){
+				int k;
+				k= (i+j)/2;
+				if(l<=L[k]){
+					j=k;// l<=L[j] 
+				}
+				else{
+					i=k; //  L[i]<l
+				}
+			};
+			if (i==j){
+				r = 2*S[i];
+			}
+			else{
+				r =  2*(S[i]*(L[j]-l)+ S[j]*(l-L[i]))/(L[j]-L[i]);
+			}
+		}
+		if (r>1 || r<0){
+			_error_("r>1 || r<0");
+		}
+		return r ;
+	}
+	/*}}}*/
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Metric.h	(revision 18231)
@@ -0,0 +1,135 @@
+#ifndef _METRIC_H
+#define _METRIC_H
+
+#include "./include.h"
+#include "../shared/shared.h"
+#include "R2.h"
+#include <math.h>
+
+namespace bamg {
+
+	typedef P2<double,double>    D2;
+	typedef P2xP2<double,double> D2xD2;
+
+	class Metric;
+	class EigenMetric;
+
+	class Metric{
+
+		public:
+
+			//fields
+			double a11,a21,a22;
+
+			//friends
+			friend class EigenMetric;
+
+			//functions
+			Metric():a11(0),a21(0),a22(0){};
+			Metric(const EigenMetric&);
+			Metric(double a);
+			Metric(double a,double b,double c);
+			Metric( double  a,const  Metric& ma, double  b,const  Metric& mb);
+			Metric(const double  a[3],const  Metric& m0,const  Metric& m1,const  Metric& m2 );
+			void        Echo();
+			R2          mul(const R2 x)const;
+			double      det() const;
+			int         IntersectWith(const  Metric& M2);
+			inline void Box(double &hx,double &hy) const;
+
+			/*The following functions must remain the the header file because it is called before Metric
+			 * is compiled by other classes*/
+			R2 Orthogonal(const R2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+			R2 Orthogonal(const I2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+
+			//operators
+			Metric operator*(double c) const {double c2=c*c;return  Metric(a11*c2,a21*c2,a22*c2);} 
+			Metric operator/(double c) const {double c2=1/(c*c);return  Metric(a11*c2,a21*c2,a22*c2);} 
+			operator D2xD2(){ return D2xD2(a11,a21,a21,a22);}
+			double  operator()(R2 x) const { return sqrt(x.x*x.x*a11+2*x.x*x.y*a21+x.y*x.y*a22);};        // length of x in metric sqrt(<Mx,x>)
+			double  operator()(R2 x,R2 y) const { return x.x*y.x*a11+(x.x*x.y+x.y*y.x)*a21+x.y*y.y*a22;};
+
+	};
+
+	class EigenMetric{
+		public:
+
+			//fields
+			double lambda1,lambda2;
+			D2     v;
+
+			//friends
+			friend  class Metric;
+
+			//functions
+			EigenMetric(const Metric& );
+			EigenMetric(double r1,double r2,const D2& vp1);
+			void   Echo();
+			void   Abs();
+			void   pow(double  p);
+			void   Min(double  a);
+			void   Max(double  a);
+			void   Minh(double h);
+			void   Maxh(double h);
+			double hmin()   const;
+			double hmax()   const;
+			double lmax()   const;
+			double lmin()   const;
+			double Aniso2() const;
+			inline void BoundAniso2(const double coef);
+
+			//operators
+			void operator *=(double coef){ lambda1*=coef;lambda2*=coef;}
+	};
+
+	class SaveMetricInterpole {
+		friend double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+		friend double abscisseInterpole(const Metric& Ma ,const  Metric& Mb, R2 ,double s,int optim);
+		public:
+		int opt;
+		double lab;
+		double L[1024],S[1024];
+	};
+
+	extern SaveMetricInterpole  LastMetricInterpole; // for optimization 
+	//Functions
+	void  SimultaneousMatrixReduction( Metric M1,  Metric M2,D2xD2 &V);
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim=0);
+
+	//inlines
+	inline void  EigenMetric::BoundAniso2(const double coef){
+		if (coef<=1.00000000001){
+			if (lambda1 < lambda2)
+			 lambda1 = bamg::Max(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Max(lambda2,lambda1*coef);
+		}
+		else{  //TO BE CHECKED
+			if (lambda1 > lambda2)
+			 lambda1 = bamg::Min(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Min(lambda2,lambda1*coef);
+		}
+	}
+	inline Metric::Metric(const EigenMetric& M) {
+		double v00=M.v.x*M.v.x;
+		double v11=M.v.y*M.v.y;
+		double v01=M.v.x*M.v.y;
+		a11=v00*M.lambda1+v11*M.lambda2;
+		a21=v01*(M.lambda1-M.lambda2);
+		a22=v00*M.lambda2+v11*M.lambda1;
+	}
+	inline   void  Metric::Box(double &hx,double &hy) const {
+		double d=  a11*a22-a21*a21;
+		hx = sqrt(a22/d);
+		hy = sqrt(a11/d);
+	}
+	inline double LengthInterpole(double la,double lb) {
+		return ( Abs(la - lb) < 1.0e-6*Max3(la,lb,1.0e-20) ) ?  (la+lb)/2  : la*lb*log(la/lb)/(la-lb);
+	}
+	inline double abscisseInterpole(double la,double lb,double lab,double s){
+		return ( Abs(la - lb) <1.0e-6*Max3(la,lb,1.0e-20))  ? s : (exp(s*lab*(la-lb)/(la*lb))-1)*lb/(la-lb);
+	}
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/R2.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/R2.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/R2.h	(revision 18231)
@@ -0,0 +1,101 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, R2.h)*/
+#ifndef _R2_H
+#define _R2_H
+
+#include <cstdio>
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	template <class R,class RR> class P2{
+
+		  public:  
+
+			  //fields
+			  R x,y;
+
+			  //functions
+			  P2 () :x(0),y(0) {};
+			  P2 (R a,R b)  :x(a),y(b)  {}
+			  P2 (P2 A,P2 B) : x(B.x-A.x),y(B.y-A.y) {}
+			  void Echo(){
+				  printf("Member of P2:\n");
+				  printf("   x: %g or %i\n",x,x);
+				  printf("   y: %g or %i\n",y,y);
+			  }
+			  //operators
+			  RR       operator,(const P2<R,RR> & cc) const {return  (RR) x* (RR) cc.x+(RR) y* (RR) cc.y;} //scalar product
+			  P2<R,RR> operator+(const P2<R,RR> & cc) const {return P2<R,RR>(x+cc.x,y+cc.y);}
+			  P2<R,RR> operator-(const P2<R,RR> & cc) const {return P2<R,RR>(x-cc.x,y-cc.y);}
+			  P2<R,RR> operator-()  const{return P2<R,RR>(-x,-y);}
+			  P2<R,RR> operator*(R  cc) const {return P2<R,RR>(x*cc,y*cc);}
+			  P2<R,RR> operator/(R  cc) const {return P2<R,RR>(x/cc,y/cc);}
+			  P2<R,RR> operator+=(const  P2<R,RR> & cc) {x += cc.x;y += cc.y;return *this;}
+			  P2<R,RR> operator/=(const  R r) {x /= r;y /= r;return *this;}
+			  P2<R,RR> operator*=(const  R r) {x *= r;y *= r;return *this;}
+			  P2<R,RR> operator-=(const  P2<R,RR> & cc) {x -= cc.x;y -= cc.y;return *this;}
+
+	  };
+
+	template <class R,class RR> class P2xP2{
+
+		  public:
+
+			  //fields
+			  P2<R,RR> x,y; 
+
+			  //functions
+			  P2xP2 (): x(),y()  {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b): x(a),y(b) {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b,P2<R,RR> c ): x(b-a),y(c-a) {}
+			  P2xP2 (R xx,R xy,R yx,R yy) :x(xx,xy),y(yx,yy) {}
+			  void Echo(){
+				  printf("Member of P2xP2:\n");
+				  printf("   x.x: %g   x.y: %g\n",x.x,x.y);
+				  printf("   y.x: %g   y.x: %g\n",y.x,y.y);
+			  }
+			  RR          det() const {return (RR) x.x* (RR) y.y - (RR) x.y * (RR) y.x;}
+			  P2xP2<R,RR> inv()  const{
+				  RR d = (*this).det(); 
+				  return P2xP2<R,RR>((R)( y.y /d) ,(R)(-x.y/d),(R)( -y.x/d) ,(R)( x.x/d) );
+			  };
+			  P2xP2<R,RR> t()  {return P2xP2<R,RR>(x.x,y.x,x.y,y.y);} //transposer 
+			  P2<R,RR>    tx() {return P2<R,RR>(x.x,y.x);} 
+			  P2<R,RR>    ty() {return P2<R,RR>(x.y,y.y);} 
+			  //Operators
+			  P2<R,RR>     operator*(const P2<R,RR>& c) const {return P2<R,RR>(x.x*c.x + x.y*c.y, y.x*c.x + y.y*c.y);}
+			  P2xP2<R,RR>  operator*(P2xP2<R,RR> c) const{
+				  return  P2xP2<R,RR>(x.x*c.x.x + x.y*c.y.x,
+							  x.x*c.x.y + x.y*c.y.y,
+							  y.x*c.x.x + y.y*c.y.x,
+							  y.x*c.x.y + y.y*c.y.y);
+			  }
+	  };  
+
+	//inline functions
+	template  <class R,class RR>  
+	  inline RR Det(const P2<R,RR> x,const P2<R,RR> y) {
+		  return (RR) x.x * (RR) y.y - (RR) x.y * (RR) y.x ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Area2 (const P2<R,RR> a,const P2<R,RR> b,const P2<R,RR> c) {
+		  return Det(b-a,c-a) ;
+	  }
+	template  <class R,class RR>  
+	  inline R Norme1 (const P2<R,RR> x) {
+		  return (Abs(x.x)+Abs(x.y)) ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2_2 (const P2<R,RR> x) {
+		  return (RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2 (const P2<R,RR> x) {
+		  return sqrt((RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y) ;
+	  } 
+	template  <class R,class RR>  
+	  inline P2<R,RR> Orthogonal (const P2<R,RR> x) {
+		  return  P2<R,RR>(-x.y,x.x);
+	  } 
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.cpp	(revision 18231)
@@ -0,0 +1,107 @@
+#include "./bamgobjects.h"
+
+using namespace std;
+namespace bamg {
+
+	/*Constructor*/
+	SetOfEdges4::SetOfEdges4(long mmx,long nnx){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/SetOfEdges4)*/
+
+		/*Intermediary*/
+		int i;
+
+		//initialize fields
+		nx   =nnx;   //number of vertices
+		nbax =mmx;   // 3 * number of triangles
+		NbOfEdges=0;
+		head = new long [nx];
+		Edges= new IntEdge[nbax];
+
+		//initialize head (-1 everywhere)
+		i=nx;
+		while(i--) head[i]=-1;
+	}
+	/*}}}*/
+
+	/*Methods*/ 
+	long SetOfEdges4::add(long ii,long jj) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/add)*/
+
+		/*Intermediary*/
+		int h,n;
+
+		//get n from h (usually h=ii)
+		_assert_(head);
+		n=head[h=Abs(ii)%nx];
+
+		//go through the existing edges that holds h (=ii) and check that 
+		//the edge ii jj is not already in Edge
+		while (n >= 0){
+
+			//if the edge ii jj is already in Edges, return n
+			if (ii == Edges[n].i && jj == Edges[n].j) return n;
+
+			//else go to next edge that holds ii
+			else n = Edges[n].next;
+		}
+
+		//check that nbax <=NbOfEdges
+		if (nbax <=NbOfEdges ) {
+			_error_("SetOfEdges4::add overflow: NbOfEdges=" << NbOfEdges << " > nbax=" << nbax);
+		}
+
+		//update chain
+		Edges[NbOfEdges].i=ii;
+		Edges[NbOfEdges].j=jj;
+		Edges[NbOfEdges].next= head[h];
+		head[h] = NbOfEdges;
+		return NbOfEdges ++;
+	}
+	/*}}}*/
+	long SetOfEdges4::find(long ii,long jj) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/find)*/
+
+		/*Intermediary*/
+		int n;
+
+		//check that head is not empty
+		_assert_(head);
+
+		//get n from h (usually h=ii)
+		n=head[Abs(ii)%nx];
+
+		//go through the existing edges that holds h (=ii) and return position in Edge
+		while (n >= 0){
+
+			//if the edge ii jj is already in Edges, return n
+			if (ii == Edges[n].i && jj == Edges[n].j) return n;
+
+			//else go to next edge that holds ii
+			else n = Edges[n].next;
+		}
+
+		//if we reach this point, the edge does not exist return -1
+		return -1;
+	}
+	/*}}}*/
+	long SetOfEdges4::i(long k){/*{{{*/
+		return Edges[k].i;
+	}
+	/*}}}*/
+	long SetOfEdges4::j(long k){/*{{{*/
+		return Edges[k].j;
+	}
+	/*}}}*/
+	long SetOfEdges4::nb(){/*{{{*/
+		return NbOfEdges;
+	}
+	/*}}}*/
+	long SetOfEdges4::SortAndAdd (long ii,long jj) {/*{{{*/
+		return ii <=jj ? add (ii,jj)  : add (jj,ii) ;
+	}
+	/*}}}*/
+	long SetOfEdges4::SortAndFind (long ii,long jj) {/*{{{*/
+		return ii <=jj ? find (ii,jj)  : find (jj,ii) ;
+	}
+	/*}}}*/
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SetOfE4.h	(revision 18231)
@@ -0,0 +1,41 @@
+#ifndef _SetOfEdge4_h
+#define _SetOfEdge4_h
+
+namespace bamg {
+
+	class SetOfEdges4;
+
+	class IntEdge{
+		friend class SetOfEdges4;
+		public:
+		long i,j;
+		long next; 
+	};
+
+	class SetOfEdges4 {
+
+		private:
+			long nx,nbax,NbOfEdges;
+			long* head; 
+			IntEdge* Edges;
+
+		public:
+
+			// Constructors
+			SetOfEdges4(long ,long);// nb Edges mx , nb de sommet 
+			~SetOfEdges4() {delete [] head; delete [] Edges;}
+
+			//operators
+			IntEdge & operator[](long k){return  Edges[k];}
+
+			//Methods
+			long add (long ii,long jj);
+			long SortAndAdd (long ii,long jj);
+			long nb();
+			long find (long ii,long jj);
+			long SortAndFind (long ii,long jj);
+			long i(long k);
+			long j(long k);
+	};
+}
+#endif 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.cpp	(revision 18231)
@@ -0,0 +1,27 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "SubDomain.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){/*{{{*/
+		*this = Th.subdomains[i];
+		if( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
+			_error_("head-Th.triangles<0 || head-Th.triangles>=Th.nbt");
+		}
+		head = ThNew.triangles + Th.GetId(head) ; 
+		if(edge-Th.edges<0 || edge-Th.edges>=Th.nbe){
+			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+		}
+		edge = ThNew.edges+ Th.GetId(edge);
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/SubDomain.h	(revision 18231)
@@ -0,0 +1,26 @@
+#ifndef _SUBDOMAIN_H_
+#define _SUBDOMAIN_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Mesh;
+
+	class SubDomain {
+
+		public:
+
+			Triangle *head;
+			long      ReferenceNumber;
+			int       direction;   // -1 or 1
+			Edge     *edge;        // to geometrical
+
+			//Methods
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.cpp	(revision 18231)
@@ -0,0 +1,382 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	Triangle::Triangle(void){/*{{{*/
+
+	}
+	/*}}}*/
+	Triangle::Triangle(Mesh *Th,long i,long j,long k) {/*{{{*/
+		BamgVertex *v=Th->vertices;
+		long nbv = Th->nbv;
+		if (i<0 || j<0 || k<0){
+			_error_("i<0 || j<0 || k<0");
+		}
+		if (i>=nbv || j>=nbv || k>=nbv){
+			_error_("i>=nbv || j>=nbv || k>=nbv");
+		}
+		vertices[0]=v+i;
+		vertices[1]=v+j;
+		vertices[2]=v+k;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		det=0;
+	}
+	/*}}}*/
+	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){/*{{{*/
+		vertices[0]=v0;
+		vertices[1]=v1;
+		vertices[2]=v2;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		if (v0) det=0;
+		else {
+			det=-1;
+			link=NULL;};  
+	}
+	/*}}}*/
+
+	/*Methods*/
+	AdjacentTriangle Triangle::Adj(int i)  const {/*{{{*/
+		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
+	};/*}}}*/
+	double Triangle::Length() const{/*{{{*/
+
+		double l;
+
+		/*Get three vertices A,B and C*/
+		R2 A=*this->vertices[0];
+		R2 B=*this->vertices[1];
+		R2 C=*this->vertices[2];
+
+		/*Compute edges*/
+		R2 e1=B-A;
+		R2 e2=C-A;
+		R2 e3=B-C;
+
+		/*Compute edge length*/
+		l=Norme2(e1);
+		l=max(l,Norme2(e2));
+		l=max(l,Norme2(e3));
+
+		return l;
+	};/*}}}*/
+	void Triangle::Echo(void){/*{{{*/
+
+		int i;
+
+		_printf_("Triangle:\n");
+		_printf_("   vertices pointer towards three vertices\n");
+		_printf_("      vertices[0] vertices[1] vertices[2] = " << vertices[0] << " " << vertices[1] << " " << vertices[2] << "\n");
+		_printf_("   adj pointer towards three adjacent triangles\n");
+		_printf_("      adj[0] adj[1] adj[2] = " << adj[0] << " " << adj[1] << " " << adj[2] << "\n");
+		_printf_("   det (integer triangle determinant) = " << det << "\n");
+		if (link){
+			_printf_("   link (pointer toward duplicate triangle)= " << link << "\n");
+		}
+		else{
+			_printf_("   color = " << color << "\n");
+		}
+
+		_printf_("\nThree vertices:\n");
+		for(i=0;i<3;i++){
+			if (vertices[i]){
+				vertices[i]->Echo();
+			}
+			else{
+				_printf_("   vertex " << i+1 << " does not exist\n");
+			}
+		}
+
+		return;
+	}
+	/*}}}*/
+	int    Triangle::GetAllflag(int a){/*{{{*/
+		return AdjEdgeIndex[a] & 1020;
+	}/*}}}*/
+	int    Triangle::Hidden(int a)const {/*{{{*/
+		return AdjEdgeIndex[a]&16;
+	} /*}}}*/
+	int    Triangle::Locked(int a)const {/*{{{*/
+		return AdjEdgeIndex[a]&4;
+	} /*}}}*/
+	short  Triangle::NuEdgeTriangleAdj(int i) const {/*{{{*/
+		/*Number of the  adjacent edge in adj tria (make sure it is between 0 and 2*/
+		return AdjEdgeIndex[i&3]&3;
+	}/*}}}*/
+	long  Triangle::Optim(short i,int koption) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Optim)*/
+
+		// turn around (positive direction)
+		Triangle *t=this;
+		long NbSwap =0;
+		int  k = 0;
+		int  j = OppositeEdge[i];
+		int  jp= PreviousEdge[j];
+
+		// initialize tp, jp the previous triangle & edge
+		Triangle *tp=adj[jp];
+		jp = AdjEdgeIndex[jp]&3;
+		do {
+			while (t->swap(j,koption)){
+				if (k>=20000) _error_("k>=20000");
+				NbSwap++;
+				k++;
+				t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+				j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+			}
+			// end on this  Triangle 
+			tp = t;
+			jp = NextEdge[j];
+
+			t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+			j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+
+		} while( t != this);
+		return NbSwap;
+	}
+	/*}}}*/
+	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{/*{{{*/
+		// return the other triangle of the quad if a quad or 0 if not a quat
+		Triangle * t =0;
+		if (link) {
+			int a=-1;
+			if (AdjEdgeIndex[0] & 16 ) a=0;
+			if (AdjEdgeIndex[1] & 16 ) a=1;
+			if (AdjEdgeIndex[2] & 16 ) a=2;
+			if (a>=0) {
+				t = adj[a];
+				//  if (t-this<0) return 0;
+				v2 = vertices[VerticesOfTriangularEdge[a][0]];
+				v0 = vertices[VerticesOfTriangularEdge[a][1]];
+				v1 = vertices[OppositeEdge[a]];
+				v3 = t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+			}
+		}
+		return t;
+	}
+	/*}}}*/
+	double   Triangle::QualityQuad(int a,int option) const{/*{{{*/
+		double q;
+		if (!link || AdjEdgeIndex[a] &4)
+		 q=  -1;
+		else {
+			Triangle * t = adj[a];
+			if (t-this<0) q=  -1;// because we do 2 times 
+			else if (!t->link ) q=  -1;
+			else if (AdjEdgeIndex[0] & 16 || AdjEdgeIndex[1] & 16  || AdjEdgeIndex[2] & 16 || t->AdjEdgeIndex[0] & 16 || t->AdjEdgeIndex[1] & 16 || t->AdjEdgeIndex[2] & 16 )
+			 q= -1;
+			else if(option){ 
+				const BamgVertex & v2 = *vertices[VerticesOfTriangularEdge[a][0]];
+				const BamgVertex & v0 = *vertices[VerticesOfTriangularEdge[a][1]];
+				const BamgVertex & v1 = *vertices[OppositeEdge[a]];
+				const BamgVertex & v3 = * t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+				q =  QuadQuality(v0,v1,v2,v3); // do the float part
+			}
+			else q= 1;
+		}
+		return  q;
+	}
+	/*}}}*/
+	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){/*{{{*/
+
+		if (link  >=tb && link  <te) link  = tb + renu[link -tb];
+		if (adj[0] >=tb && adj[0] <te) adj[0] = tb + renu[adj[0]-tb];
+		if (adj[1] >=tb && adj[1] <te) adj[1] = tb + renu[adj[1]-tb];
+		if (adj[2] >=tb && adj[2] <te) adj[2] = tb + renu[adj[2]-tb];    
+	}/*}}}*/
+	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){/*{{{*/
+		if (vertices[0] >=vb && vertices[0] <ve) vertices[0] = vb + renu[vertices[0]-vb];
+		if (vertices[1] >=vb && vertices[1] <ve) vertices[1] = vb + renu[vertices[1]-vb];
+		if (vertices[2] >=vb && vertices[2] <ve) vertices[2] = vb + renu[vertices[2]-vb];    
+	}/*}}}*/
+	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ /*{{{*/
+		*this = rec;
+		if ( vertices[0] ) vertices[0] = ThNew.vertices +  Th.GetId(vertices[0]);
+		if ( vertices[1] ) vertices[1] = ThNew.vertices +  Th.GetId(vertices[1]);
+		if ( vertices[2] ) vertices[2] = ThNew.vertices +  Th.GetId(vertices[2]);
+		if(adj[0]) adj[0] =  ThNew.triangles + Th.GetId(adj[0]);
+		if(adj[1]) adj[1] =  ThNew.triangles + Th.GetId(adj[1]);
+		if(adj[2]) adj[2] =  ThNew.triangles + Th.GetId(adj[2]);
+		if (link  >= Th.triangles && link  < Th.triangles + Th.nbt)
+		 link = ThNew.triangles + Th.GetId(link);
+	}
+	/*}}}*/
+	void Triangle::SetAdjAdj(short a){/*{{{*/
+		// Copy all the mark 
+		a &= 3;
+		Triangle *tt=adj[a];
+		AdjEdgeIndex [a] &= 55; // remove MarkUnSwap
+		short aatt = AdjEdgeIndex[a] & 3;
+		if(tt){ 
+			tt->adj[aatt]=this;
+			tt->AdjEdgeIndex[aatt]=a + (AdjEdgeIndex[a] & 60 ) ;
+		}
+	}/*}}}*/
+	void Triangle::SetAdj2(short a,Triangle *t,short aat){/*{{{*/
+		/*For current triangle:
+		 * - a is the index of the edge were the adjency is set (in [0 2])
+		 * - t is the adjacent triangle
+		 * - aat is the index of the same edge in the adjacent triangle*/
+		adj[a]=t;
+		AdjEdgeIndex[a]=aat;
+		if(t){ //if t!=NULL add adjacent triangle to t (this)
+			t->adj[aat]=this;
+			t->AdjEdgeIndex[aat]=a;
+		}
+	}/*}}}*/
+	void Triangle::SetHidden(int a){/*{{{*/
+		//Get Adjacent Triangle number a
+		Triangle* t = adj[a];
+		//if it exist
+		//C|=D -> C=(C|D) bitwise inclusive OR
+		if(t) t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=16;
+		AdjEdgeIndex[a] |= 16;
+	}/*}}}*/
+	void Triangle::SetLocked(int a){/*{{{*/
+		//mark the edge as on Boundary
+		Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=4;
+		AdjEdgeIndex[a] |= 4;
+	}/*}}}*/
+	void Triangle::SetMarkUnSwap(int a){/*{{{*/
+		Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=8;
+		AdjEdgeIndex[a] |=8 ;
+	}/*}}}*/
+	void Triangle::SetSingleVertexToTriangleConnectivity() { /*{{{*/
+		if (vertices[0]) (vertices[0]->t=this,vertices[0]->IndexInTriangle=0);
+		if (vertices[1]) (vertices[1]->t=this,vertices[1]->IndexInTriangle=1);
+		if (vertices[2]) (vertices[2]->t=this,vertices[2]->IndexInTriangle=2);
+	}/*}}}*/
+	void Triangle::SetUnMarkUnSwap(int a){ /*{{{*/
+		Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] &=55; // 23 + 32 
+		AdjEdgeIndex[a] &=55 ;
+	}/*}}}*/
+	int Triangle::swap(short a,int koption){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+
+		if(a/4 !=0) return 0;// arete lock or MarkUnSwap
+
+		Triangle *t1=this,*t2=adj[a];// les 2 triangles adjacent
+		short a1=a,a2=AdjEdgeIndex[a];// les 2 numero de l arete dans les 2 triangles
+		if(a2/4 !=0) return 0; // arete lock or MarkUnSwap
+
+		BamgVertex  *sa=t1->vertices[VerticesOfTriangularEdge[a1][0]];
+		BamgVertex  *sb=t1->vertices[VerticesOfTriangularEdge[a1][1]];
+		BamgVertex  *s1=t1->vertices[OppositeVertex[a1]];
+		BamgVertex  *s2=t2->vertices[OppositeVertex[a2]];
+
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		Icoor2 detA = Abs(det1) + Abs(det2);
+		Icoor2 detMin = Min(det1,det2);
+
+		int OnSwap = 0;       
+		// si 2 triangle infini (bord) => detT = -2;
+		if (sa == 0) {// les deux triangles sont frontieres
+			det2=bamg::det(s2->i,sb->i,s1->i);
+			OnSwap = det2 >0;}
+		else if (sb == 0) { // les deux triangles sont frontieres
+			det1=bamg::det(s1->i,sa->i,s2->i);
+			OnSwap = det1 >0;}
+		else if(( s1 != 0) && (s2 != 0) ) {
+			det1 = bamg::det(s1->i,sa->i,s2->i);
+			det2 = detT - det1;
+			OnSwap = (Abs(det1) + Abs(det2)) < detA;
+
+			Icoor2 detMinNew=Min(det1,det2);
+			//     if (detMin<0 && (Abs(det1) + Abs(det2) == detA)) OnSwap=BinaryRand();// just for test   
+			if (! OnSwap &&(detMinNew>0)) {
+				OnSwap = detMin ==0;
+				if (! OnSwap) {
+					int  kopt = koption;
+					while (1)
+					 if(kopt) {
+						 // critere de Delaunay pure isotrope
+						 Icoor2 xb1 = sb->i.x - s1->i.x,
+									 x21 = s2->i.x - s1->i.x,
+									 yb1 = sb->i.y - s1->i.y,
+									 y21 = s2->i.y - s1->i.y,
+									 xba = sb->i.x - sa->i.x, 
+									 x2a = s2->i.x - sa->i.x,
+									 yba = sb->i.y - sa->i.y,
+									 y2a = s2->i.y - sa->i.y;
+						 double
+							cosb12 =  double(xb1*x21 + yb1*y21),
+									 cosba2 =  double(xba*x2a + yba*y2a) ,
+									 sinb12 = double(det2),
+									 sinba2 = double(t2->det);
+
+						 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
+						 OnSwap =  ((double) cosb12 * (double)  sinba2) <  ((double) cosba2 * (double) sinb12);
+						 break;
+					 }
+					 else {	
+						 // critere de Delaunay anisotrope 
+						 double som;
+						 I2 AB=(I2) *sb - (I2) *sa;
+						 I2 MAB2=((I2) *sb + (I2) *sa);
+						 R2 MAB(MAB2.x*0.5,MAB2.y*0.5);
+						 I2 A1=(I2) *s1 - (I2) *sa;
+						 I2 D = (I2) * s1 - (I2) * sb ;
+						 R2 S2(s2->i.x,s2->i.y);
+						 R2 S1(s1->i.x,s1->i.y);
+							{
+							 Metric M=s1->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if (Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  = M(C - S2)/M(C - S1);
+							 } else 
+								{kopt=1;continue;}
+
+							}
+							{
+							 Metric M=s2->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2 
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if(Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  += M(C - S2)/M(C -  S1);
+							 } else 
+								{kopt=1;continue;}
+							}
+						 OnSwap = som < 2;
+						 break;
+					 }
+
+				} // OnSwap 
+			} // (! OnSwap &&(det1 > 0) && (det2 > 0) )
+		}
+		if( OnSwap ) 
+		 bamg::swap(t1,a1,t2,a2,s1,s2,det1,det2);
+		else {
+			t1->SetMarkUnSwap(a1);     
+		}
+		return OnSwap;
+	}
+	/*}}}*/
+	Triangle* Triangle::TriangleAdj(int i) const {/*{{{*/
+		return adj[i&3];
+	}/*}}}*/
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/Triangle.h	(revision 18231)
@@ -0,0 +1,71 @@
+#ifndef _TRIANGLE_H_
+#define _TRIANGLE_H_
+
+#include "./include.h"
+#include "AdjacentTriangle.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+	class Triangle;
+
+	class Triangle {
+
+		friend class AdjacentTriangle;
+
+		private:
+			BamgVertex *vertices[3];        // 3 vertices if t is triangle, t[i] allowed by access function, (*t)[i] if pointer
+			Triangle   *adj[3];             // 3 pointers toward the adjacent triangles
+			short       AdjEdgeIndex[3];   // edge id in the adjacent triangles. The edge number 1 is the edge number AdjEdgeIndex[1] in the Adjacent triangle 1
+
+		public: 
+			Icoor2 det; //Integer determinant (twice its area)
+			union { 
+				Triangle *link;
+				long      color;
+			};
+
+			//Constructors/Destructors
+			Triangle();
+			Triangle(Mesh *Th,long i,long j,long k);
+			Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2);
+
+			//Operators
+			const BamgVertex & operator[](int i) const {return *vertices[i];};
+			BamgVertex & operator[](int i)  {return *vertices[i];};
+			const BamgVertex * operator()(int i) const {return vertices[i];};
+			BamgVertex * & operator()(int i)  {return vertices[i];};
+
+			//Methods
+			void              Echo();
+			double            Length() const;
+			int               swap(short a1,int=0);
+			long              Optim(short a,int =0);
+			int               Locked(int a)const;
+			int               Hidden(int a)const;
+			int               GetAllflag(int a);
+			double            QualityQuad(int a,int option=1) const;
+			short             NuEdgeTriangleAdj(int i) const;
+			AdjacentTriangle  Adj(int i) const;
+			Triangle         *TriangleAdj(int i) const;
+			Triangle         *Quadrangle(BamgVertex  *& v0,BamgVertex *& v1,BamgVertex *& v2,BamgVertex *& v3) const;
+			void              Renumbering(Triangle   *tb,Triangle *te, long *renu);
+			void              Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			void              SetAdjAdj(short a);
+			void              SetAdj2(short a,Triangle *t,short aat);
+			void              SetSingleVertexToTriangleConnectivity();
+			void              SetHidden(int a);
+			void              SetLocked(int a);
+			void              SetMarkUnSwap(int a);
+			void              SetUnMarkUnSwap(int a);
+
+			//Inline methods
+			double qualite() ;
+			void  Set(const Triangle &,const Mesh &,Mesh &);
+			int   In(BamgVertex *v) const { return vertices[0]==v || vertices[1]==v || vertices[2]==v ;}
+
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.cpp	(revision 18231)
@@ -0,0 +1,23 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnEdge.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Methods*/
+	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){/*{{{*/
+		*this = Th.VertexOnBThEdge[i];  
+		v = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	void VertexOnEdge::SetOnBTh(){/*{{{*/
+		v->BackgroundEdgeHook=this;
+		v->IndexInTriangle=IsVertexOnEdge;  
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnEdge.h	(revision 18231)
@@ -0,0 +1,35 @@
+#ifndef _VERTEXONEDGE_H_
+#define _VERTEXONEDGE_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+
+	class VertexOnEdge {
+
+		public:
+			BamgVertex* v;
+			Edge*   be;
+			double abcisse;
+
+			//Constructors
+			VertexOnEdge(BamgVertex * w, Edge *bw,double s) :v(w),be(bw),abcisse(s) {};
+			VertexOnEdge(){};
+
+			//Operators
+			operator double () const { return abcisse;}
+			operator BamgVertex* () const { return v;}  
+			operator Edge* () const { return be;}  
+			BamgVertex & operator[](int i) const { return (*be)[i];}
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);  
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.cpp	(revision 18231)
@@ -0,0 +1,63 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnGeom.h"
+#include "Mesh.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	VertexOnGeom::VertexOnGeom(){/*{{{*/
+		meshvertex=NULL;
+		curvilincoord=0;
+		gv=0;
+	} 
+	/*}}}*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){/*{{{*/
+		meshvertex=&m;
+		curvilincoord=-1;
+		gv=&g;
+	}
+	/*}}}*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){/*{{{*/
+		meshvertex=&m;
+		curvilincoord=s;
+		ge=&g;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){/*{{{*/
+		*this = rec;  
+		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
+		if(gv){
+		 if (curvilincoord < 0 )
+		  gv = ThNew.Gh.vertices + Th.Gh.GetId(gv);
+		 else
+		  ge = ThNew.Gh.edges + Th.Gh.GetId(ge);
+		}
+
+	}
+	/*}}}*/
+	int VertexOnGeom::OnGeomVertex()const{/*{{{*/
+		return this? curvilincoord <0 :0;
+	}
+	/*}}}*/
+	int VertexOnGeom::OnGeomEdge() const{/*{{{*/
+		return this? curvilincoord >=0 :0;
+	}
+	/*}}}*/
+	int VertexOnGeom::IsRequiredVertex() {/*{{{*/
+		return this? ((curvilincoord<0 ? (gv?gv->Required():0):0 )) : 0;
+	}
+	/*}}}*/
+	void VertexOnGeom::SetOn(){/*{{{*/
+		meshvertex->GeomEdgeHook=this;
+		meshvertex->IndexInTriangle=IsVertexOnGeom;
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnGeom.h	(revision 18231)
@@ -0,0 +1,45 @@
+#ifndef _VERTEXONGEOM_H_
+#define _VERTEXONGEOM_H_
+
+#include "./include.h"
+#include "./GeomVertex.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+	class GeomEdge;
+
+	class VertexOnGeom{
+
+		public:
+
+			BamgVertex* meshvertex;
+			double curvilincoord;  
+			union{ 
+				GeomVertex* gv; // if curvilincoord <0; 
+				GeomEdge*   ge; // if curvilincoord in [0..1]
+			};
+
+			//Constructors/Destructors
+			VertexOnGeom();
+			VertexOnGeom(BamgVertex & m,GeomVertex &g);
+			VertexOnGeom(BamgVertex & m,GeomEdge &g,double s);
+
+			//Operators
+			operator BamgVertex*() const  {return meshvertex;}
+			operator GeomVertex * () const  {return gv;}
+			operator GeomEdge * () const  {return ge;}
+			operator const double & () const {return curvilincoord;}
+
+			//Methods
+			int  OnGeomVertex()const;
+			int  OnGeomEdge() const;
+			int  IsRequiredVertex();
+			void SetOn();
+
+			//Inline methods
+			void Set(const VertexOnGeom&,const Mesh &,Mesh &);  
+	};
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.cpp	(revision 18231)
@@ -0,0 +1,30 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnVertex.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	VertexOnVertex::VertexOnVertex() {/*{{{*/
+		v=NULL;
+		bv=NULL;
+	};/*}}}*/
+	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){/*{{{*/
+
+	}/*}}}*/
+
+	/*Methods*/
+	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { /*{{{*/
+		*this = Th.VertexOnBThVertex[i];  
+		v     = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	void VertexOnVertex::SetOnBTh(){/*{{{*/
+		v->BackgroundVertexHook=bv;v->IndexInTriangle=IsVertexOnVertex;
+	}/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/VertexOnVertex.h	(revision 18231)
@@ -0,0 +1,27 @@
+#ifndef _VERTEXONVERTEX_H_
+#define _VERTEXONVERTEX_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	class Mesh;
+
+	class VertexOnVertex {
+
+		public:
+			BamgVertex* v;
+			BamgVertex* bv;
+
+			//Constructors
+			VertexOnVertex();
+			VertexOnVertex(BamgVertex * w,BamgVertex *bw);
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/bamgobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/bamgobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/bamgobjects.h	(revision 18231)
@@ -0,0 +1,34 @@
+/* \file bamgobjects.h
+ * \brief: prototype header for all bamg related objects.
+ */
+
+#ifndef BAMG_OBJECTS_H_
+#define BAMG_OBJECTS_H_
+
+/*Bamg: */
+#include "./BamgOpts.h"
+#include "./BamgGeom.h"
+#include "./BamgMesh.h"
+#include "./Metric.h"
+#include "./DoubleAndInt.h"
+#include "./Direction.h"
+#include "./BamgVertex.h"
+#include "./AdjacentTriangle.h"
+#include "./Edge.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+#include "./Triangle.h"
+#include "./ListofIntersectionTriangles.h"
+#include "./GeomSubDomain.h"
+#include "./SubDomain.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./CrackedEdge.h"
+#include "./Mesh.h"
+#include "./Geometry.h"
+#include "./BamgQuadtree.h"
+#include "./SetOfE4.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/det.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/det.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/det.h	(revision 18231)
@@ -0,0 +1,15 @@
+#ifndef _BAMGDET_H_
+#define _BAMGDET_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	Icoor2 inline det(const I2 &a,const I2 & b,const I2 &c){
+		Icoor2 bax = b.x - a.x ,bay = b.y - a.y; 
+		Icoor2 cax = c.x - a.x ,cay = c.y - a.y; 
+		return  bax*cay - bay*cax;
+	}
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/include.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/include.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/include.h	(revision 18231)
@@ -0,0 +1,11 @@
+/*!\file: include.h
+ * \brief prototypes for include.h
+ */ 
+
+#ifndef _INCLUDE2_H_
+#define  _INCLUDE2_H_
+
+#include "./macros.h"
+#include "./typedefs.h"
+
+#endif //ifndef _INCLUDE2_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/macros.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/macros.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/macros.h	(revision 18231)
@@ -0,0 +1,24 @@
+#ifndef _BAMGMACROS_H
+#define _BAMGMACROS_H
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	const double Pi =3.141592653589793238462643383279502884197169399375105820974944592308;
+	const float  fPi=3.141592653589793238462643383279502884197169399375105820974944592308;
+	const  int   IsVertexOnGeom = 8;
+	const  int   IsVertexOnVertex = 16;
+	const  int   IsVertexOnEdge = 32;
+	static const short VerticesOfTriangularEdge[3][2] = {{1,2},{2,0},{0,1}};
+	static const short EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
+	static const short OppositeVertex[3] = {0,1,2};
+	static const short OppositeEdge[3] =  {0,1,2};
+	static const short NextEdge[3] = {1,2,0};
+	static const short PreviousEdge[3] = {2,0,1};
+	static const short NextVertex[3] = {1,2,0};
+	static const short PreviousVertex[3] = {2,0,1};
+	const  Icoor1 MaxICoor   = 1073741823; // 2^30-1 =111...111 (29 times one)
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/typedefs.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/typedefs.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/bamg/typedefs.h	(revision 18231)
@@ -0,0 +1,17 @@
+#ifndef _BAMGTYPEDEFS_H
+#define _BAMGTYPEDEFS_H
+
+#include "./R2.h"
+
+namespace bamg {
+
+	/*Integer coordinates types*/
+	typedef int  Icoor1; 
+	typedef long long Icoor2;
+
+	/*I2 and R2*/
+	typedef P2<Icoor1,Icoor2>  I2;
+	typedef P2<double,double>  R2;
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraint.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraint.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraint.h	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file:  Constraint.h
+ * \brief abstract class for Constraint object
+ * This class is a place holder for constraints
+ * It is derived from Object, so DataSets can contain them.
+ */ 
+
+#ifndef _CONSTRAINT_H_
+#define _CONSTRAINT_H_
+
+/*Headers:*/
+/*{{{*/
+class Nodes;
+#include "../../datastructures/datastructures.h"
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Constraint: public Object{
+
+	public: 
+
+		virtual      ~Constraint(){};
+		virtual void ConstrainNode(Nodes* nodes,Parameters* parameters)=0;
+		virtual bool InAnalysis(int analysis_type)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*
+ * \file Constraints.cpp
+ * \brief: Implementation of Constraints class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Constraints.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Numerics: */
+int Constraints::NumberOfConstraints(void){/*{{{*/
+
+	int localconstraints;
+	int numberofconstraints;
+
+	/*Get number of local constraints*/
+	localconstraints=this->Size();
+
+	/*figure out total number of constraints combining all the cpus (no clones here)*/
+	ISSM_MPI_Reduce(&localconstraints,&numberofconstraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofconstraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	return numberofconstraints;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/Constraints.h	(revision 18231)
@@ -0,0 +1,33 @@
+#ifndef _CONTAINER_CONSTRAINTS_H_
+#define  _CONTAINER_CONSTRAINTS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*! \brief Declaration of Constraints class. 
+ *
+ * Declaration of Constraints class for handling Single Point Constraints (SPCs).
+ * Constraints are vector lists (Containers) of Constraint objects.
+ */ 
+class Constraints: public DataSet{
+
+	public:
+
+		/*Object constructors and destructor*/
+		Constraints(){/*{{{*/
+			enum_type=ConstraintsEnum;
+			return;
+		}
+		/*}}}*/
+		~Constraints(){/*{{{*/
+			return;
+		}
+		/*}}}*/
+
+		/*numerics*/
+		int   NumberOfConstraints(void);
+
+};
+
+#endif //ifndef _CONSTRAINTS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.cpp	(revision 18231)
@@ -0,0 +1,117 @@
+/*!\file SpcDynamic.c
+ * \brief: implementation of the SpcDynamic object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "./Constraint.h"
+#include "../../shared/shared.h"
+
+/*SpcDynamic constructors and destructor*/
+SpcDynamic::SpcDynamic(){/*{{{*/
+	return;
+}
+/*}}}*/
+SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){/*{{{*/
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	value=0;
+	analysis_type=spc_analysis_type;
+	isset=false;
+
+	return;
+}
+/*}}}*/
+SpcDynamic::~SpcDynamic(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void SpcDynamic::Echo(void){/*{{{*/
+
+	_printf_("SpcDynamic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   isset: " <<(isset?"true":"false") << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+void SpcDynamic::DeepEcho(void){/*{{{*/
+
+	this->Echo();
+	return;
+}		
+/*}}}*/
+int    SpcDynamic::Id(void){ return sid; }/*{{{*/
+/*}}}*/
+int SpcDynamic::ObjectEnum(void){/*{{{*/
+
+	return SpcDynamicEnum;
+
+}
+/*}}}*/
+Object* SpcDynamic::copy() {/*{{{*/
+	return new SpcDynamic(*this); 
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions: */
+bool SpcDynamic::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void SpcDynamic::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcDynamic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*We should first check that the value has been set... (test306)*/
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcDynamic functions*/
+int SpcDynamic::GetDof(){/*{{{*/
+	return dof;
+}
+/*}}}*/
+int   SpcDynamic::GetNodeId(){/*{{{*/
+
+	return nodeid;
+}
+/*}}}*/
+IssmDouble SpcDynamic::GetValue(){/*{{{*/
+	_assert_(this->isset);
+	_assert_(!xIsNan<IssmDouble>(value));
+	return value;
+}
+/*}}}*/
+void SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){/*{{{*/
+
+	int pos;
+
+	Node* node=(Node*)nodes->GetObjectById(NULL,nodeid);
+	pos=node->GetDof(dof,GsetEnum);
+
+	this->value=yg_serial[pos];
+	this->isset=true;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcDynamic.h	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file SpcDynamic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCDynamic_H_
+#define _SPCDynamic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcDynamic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble value; /*value*/
+		bool isset;
+		int analysis_type;
+
+	public:
+
+		/*SpcDynamic constructors, destructors:{{{*/
+		SpcDynamic();
+		SpcDynamic(int sid,int nodeid, int dof,int analysis_type);
+		~SpcDynamic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcDynamic management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		void   SetDynamicConstraint(Nodes* nodes,IssmDouble *yg_serial);
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.cpp	(revision 18231)
@@ -0,0 +1,106 @@
+/*!\file SpcStatic.c
+ * \brief: implementation of the SpcStatic object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "./Constraint.h"
+#include "../../shared/shared.h"
+
+/*SpcStatic constructors and destructor*/
+SpcStatic::SpcStatic(){/*{{{*/
+	return;
+}
+/*}}}*/
+SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){/*{{{*/
+
+	sid           = spc_sid;
+	nodeid        = spc_nodeid;
+	dof           = spc_dof;
+	value         = spc_value;
+	analysis_type = spc_analysis_type;
+
+	return;
+}
+/*}}}*/
+SpcStatic::~SpcStatic(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void SpcStatic::Echo(void){/*{{{*/
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+void SpcStatic::DeepEcho(void){/*{{{*/
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}		
+/*}}}*/
+int    SpcStatic::Id(void){ return sid; }/*{{{*/
+/*}}}*/
+int SpcStatic::ObjectEnum(void){/*{{{*/
+
+	return SpcStaticEnum;
+
+}
+/*}}}*/
+Object* SpcStatic::copy() {/*{{{*/
+	return new SpcStatic(*this); 
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions: */
+bool SpcStatic::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcStatic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcStatic functions*/
+int SpcStatic::GetDof(){/*{{{*/
+	return dof;
+}
+/*}}}*/
+int   SpcStatic::GetNodeId(){/*{{{*/
+
+	return nodeid;
+}
+/*}}}*/
+IssmDouble SpcStatic::GetValue(){/*{{{*/
+	_assert_(!xIsNan<IssmDouble>(value));
+	return value;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcStatic.h	(revision 18231)
@@ -0,0 +1,48 @@
+/*!\file SpcStatic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCStatic_H_
+#define _SPCStatic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcStatic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble value; /*value*/
+		int analysis_type;
+
+	public:
+
+		/*SpcStatic constructors, destructors:{{{*/
+		SpcStatic();
+		SpcStatic(int sid,int nodeid, int dof,IssmDouble value,int analysis_type);
+		~SpcStatic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcStatic management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.cpp	(revision 18231)
@@ -0,0 +1,153 @@
+/*!\file SpcTransient.c
+ * \brief: implementation of the SpcTransient object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "./Constraint.h"
+#include "shared/shared.h"
+
+/*SpcTransient constructors and destructor*/
+SpcTransient::SpcTransient(){/*{{{*/
+	sid=-1;
+	nodeid=-1;
+	dof=-1;
+	values=NULL;
+	times=NULL;
+	nsteps=-1;
+	analysis_type=-1;
+	return;
+}
+/*}}}*/
+SpcTransient::SpcTransient(int spc_sid,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){/*{{{*/
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	nsteps=spc_nsteps;
+	if(spc_nsteps){
+		values=xNew<IssmDouble>(spc_nsteps);
+		times=xNew<IssmDouble>(spc_nsteps);
+		xMemCpy<IssmDouble>(values,spc_values,nsteps);
+		xMemCpy<IssmDouble>(times,spc_times,nsteps);
+	}
+	analysis_type=spc_analysis_type;
+	return;
+}
+/*}}}*/
+SpcTransient::~SpcTransient(){/*{{{*/
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void SpcTransient::Echo(void){/*{{{*/
+
+	int i;
+	_printf_("SpcTransient:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   nsteps: " << nsteps << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   steps|times|values\n");
+	for(i=0;i<nsteps;i++){
+		_printf_(i << "-" << times[i] << ":" << values[i] << "\n");
+	}
+	return;
+}
+/*}}}*/
+void SpcTransient::DeepEcho(void){/*{{{*/
+	this->Echo();
+}		
+/*}}}*/
+int    SpcTransient::Id(void){ return sid; }/*{{{*/
+/*}}}*/
+int SpcTransient::ObjectEnum(void){/*{{{*/
+
+	return SpcTransientEnum;
+
+}
+/*}}}*/
+Object* SpcTransient::copy() {/*{{{*/
+	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions:*/
+bool SpcTransient::InAnalysis(int in_analysis_type){/*{{{*/
+
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
+
+	Node       *node  = NULL;
+	IssmDouble  time  = 0.;
+	int         i;
+	IssmDouble  alpha = -1.;
+	IssmDouble  value;
+	bool        found = false;
+
+	/*Chase through nodes and find the node to which this SpcTransient applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*Retrieve time in parameters: */
+		parameters->FindParam(&time,TimeEnum);
+
+		/*Now, go fetch value for this time: */
+		if (time<=times[0]){
+			value=values[0];
+			found=true;
+		}
+		else if (time>=times[nsteps-1]){
+			value=values[nsteps-1];
+			found=true;
+		}
+		else{
+			for(i=0;i<nsteps-1;i++){
+				if (times[i]<=time && time<times[i+1]){
+					alpha=(time-times[i])/(times[i+1]-times[i]);
+					value=(1-alpha)*values[i]+alpha*values[i+1];
+					found=true;
+					break;
+				}
+			}
+		}
+
+		if(!found)_error_("could not find time segment for constraint");
+
+		/*Apply or relax constraint: */
+		if(xIsNan<IssmDouble>(value)){
+			printf("-------------- file: SpcTransient.cpp line: %i\n",__LINE__); 
+			node->RelaxConstraint(dof);
+		}
+		else node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcTransient functions*/
+int SpcTransient::GetDof(){/*{{{*/
+	return dof;
+}
+/*}}}*/
+int   SpcTransient::GetNodeId(){/*{{{*/
+
+	return nodeid;
+}
+/*}}}*/
+IssmDouble SpcTransient::GetValue(){/*{{{*/
+	return values[0];
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Constraints/SpcTransient.h	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file SpcTransient.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCTRANSIENT_H_
+#define _SPCTRANSIENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcTransient: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble* values; /*different values in time*/
+		IssmDouble* times; /*different time steps*/
+		int nsteps; /*number of time steps*/
+		int analysis_type;
+
+	public:
+
+		/*SpcTransient constructors, destructors:{{{*/
+		SpcTransient();
+		SpcTransient(int sid,int nodeid, int dof,int nsteps, IssmDouble* times, IssmDouble* values,int analysis_type);
+		~SpcTransient();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcTransient management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCTRANSIENT_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contour.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contour.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contour.h	(revision 18231)
@@ -0,0 +1,84 @@
+/*!\file Contour.h
+ * \brief: header file for Contour object
+ */
+
+#ifndef _CONTOUR_H_
+#define _CONTOUR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+template <class doubletype>
+class Contour: public Object{
+
+	public: 
+
+		int         id;
+		int         nods;     //number of vertices in the contour
+		doubletype *x;
+		doubletype *y;
+		bool        closed;   //is this contour closed?
+
+		/*Contour constructors, destructors :*/
+		Contour(){/*{{{*/
+			this->id     = 0;
+			this->nods   = 0;
+			this->x      = NULL;
+			this->y      = NULL;
+			this->closed = false;
+		}
+		/*}}}*/
+		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){/*{{{*/
+
+			this->id     = pid;
+			this->nods   = pnods;
+			this->closed = pclosed;
+			if(nods){
+				this->x=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->x,px,nods);
+				this->y=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->y,py,nods);
+			}
+		}
+		/*}}}*/
+		~Contour(){/*{{{*/
+			xDelete<doubletype>(this->x);
+			xDelete<doubletype>(this->y);
+		}
+		/*}}}*/
+
+		/*Object virtual function resolutoin: */
+		void Echo(void){/*{{{*/
+			_printf_(" Contour: " << id << "\n");
+			_printf_("    nods: " << nods << "\n");
+			_printf_("  closed: " << (closed?"true":"false") << "\n");
+			if(nods){
+				_printf_("   x , y:\n");
+				for(int i=0;i<nods;i++){
+					_printf_(i << ": " << x[i] << " | " << y[i] << "\n");
+				}
+			}
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int Id(void){/*{{{*/
+			return id;
+		}
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+			return ContourEnum;
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			return new Contour(*this); 
+		}
+		/*}}}*/
+};
+
+#endif  /* _CONTOUR_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.cpp	(revision 18231)
@@ -0,0 +1,64 @@
+/*
+ * \file Contours.cpp
+ * \brief: Implementation of Contours class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Contours.h"
+#include "../shared/shared.h"
+#include "./Contour.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Contours::Contours(){/*{{{*/
+	enum_type=ContoursEnum;
+	return;
+}
+/*}}}*/
+Contours::~Contours(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Numerics: */
+int ExpWrite(Contours* contours,char* domainname){/*{{{*/
+
+	/*I/O: */
+	FILE* fid=NULL;
+	Contour<double>* contour = NULL;
+
+	/*open domain outline file for writing: */
+	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
+
+	for(int counter=0;counter<contours->Size();counter++){
+		contour=(Contour<double>*)contours->GetObjectByOffset(counter);
+
+		/*Write header: */
+		fprintf(fid,"## Name:%s\n",domainname);
+		fprintf(fid,"## Icon:0\n");
+		fprintf(fid,"# Points Count	Value\n");
+		fprintf(fid,"%u %s\n",contour->nods  ,"1.");
+		fprintf(fid,"# X pos	Y pos\n");
+
+		/*Write vertices: */
+		for(int i=0;i<contour->nods;i++){
+			fprintf(fid,"%lf\t%lf\n",contour->x[i],contour->y[i]);
+		}
+
+		/*Write blank line: */
+		if(counter<contours->Size()-1) fprintf(fid,"\n");
+	}
+
+	/*close Exp file: */
+	fclose(fid);
+
+	return 1;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Contours.h	(revision 18231)
@@ -0,0 +1,49 @@
+/*!\brief Declaration of Contours class.
+ */ 
+
+#ifndef _CONTAINER_CONTOURS_H_
+#define  _CONTAINER_CONTOURS_H_
+
+#include "../datastructures/datastructures.h"
+#include "./Contour.h"
+
+class Contours: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Contours();
+		~Contours();
+};
+
+/*Methods that relate to datasets: */
+int ExpWrite(Contours* contours,char* domainname);
+template <class doubletype> Contours* ExpRead(char* domainname){ /*{{{*/
+
+	/*intermediary: */
+	int                  nprof;
+	int                 *profnvertices = NULL;
+	doubletype         **pprofx        = NULL;
+	doubletype         **pprofy        = NULL;
+
+	/*output: */
+	Contours *domain = NULL;
+
+	/*If domainname is an empty string, return empty dataset*/
+	if (strcmp(domainname,"")==0){
+		nprof=0;
+	}
+	else{
+		ExpRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
+	}
+
+	/*now create dataset of contours: */
+	domain=new Contours();
+
+	for(int i=0;i<nprof;i++){
+		domain->AddObject(new Contour<doubletype>(i,profnvertices[i],pprofx[i],pprofy[i],1));
+	}
+	return domain;
+} /*}}}*/
+
+#endif //ifndef _CONTOURS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Definition.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Definition.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Definition.h	(revision 18231)
@@ -0,0 +1,19 @@
+/*!\file: Definition.h: abstract class used by some objects to behave like response objects 
+ * that can be called according to a string (the output definition)
+ */ 
+
+#ifndef _DEFINITION_H_
+#define  _DEFINITION_H_
+
+/*Headers:*/
+class FemModel;
+class Definition {
+
+	public:
+		virtual       ~Definition(){};
+		virtual char*  Name()=0;
+		virtual IssmDouble  Response(FemModel*)=0;
+
+};
+
+#endif //ifndef _DEFINITION_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file DependentObject.c
+ * \brief: implementation of the DependentObject object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "shared/shared.h"
+#include "../modules/modules.h"
+
+/*DependentObject constructors and destructor*/
+DependentObject::DependentObject(){/*{{{*/
+	this->name=NULL;
+	this->type=0;
+	this->index=-1;
+}
+/*}}}*/
+DependentObject::DependentObject(char* in_name, int in_type,int in_index){/*{{{*/
+
+	this->name=xNew<char>(strlen(in_name)+1); xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+	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!");
+
+}
+/*}}}*/
+DependentObject::~DependentObject(){ //destructor/*{{{*/
+	xDelete<char>(this->name);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DependentObject::Echo(void){/*{{{*/
+
+	_printf_("DependentObject:\n");
+	_printf_("   name: " << this->name << "\n");
+	if(this->type==0)
+		_printf_("   type: scalar\n");
+	else if(this->type==1)
+		_printf_("   type: vertex\n");
+	else
+		_error_(" unknown type: " << this->type);
+	if(this->index>=0) _printf_("   index: " << this->index << "\n");
+}
+/*}}}*/
+void DependentObject::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+int    DependentObject::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DependentObject::ObjectEnum(void){/*{{{*/
+
+	return DependentObjectEnum;
+
+}
+/*}}}*/
+Object* DependentObject::copy(void) { /*{{{*/
+	return new DependentObject(name,type,index);
+} /*}}}*/
+
+/*DependentObject methods: */
+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);
+}
+/*}}}*/
+void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){/*{{{*/
+
+	/*Is this some special type of response for which we need to go in the output definitions? :*/
+	if (StringToEnumx(this->name,false)==-1){
+		*poutput_value=OutputDefinitionsResponsex(femmodel,this->name);
+	}
+	else femmodel->Responsex(poutput_value,this->name);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DependentObject.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*!\file: DependentObject.h
+ * \brief prototype for DependentObject.h
+ */ 
+
+#ifndef _DEPENDENTOBJECT_H_
+#define  _DEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+class FemModel;
+
+class DependentObject: public Object{
+
+	public:
+
+		char* name;
+		int type;  /*0: scalar, 1: vertex*/
+		int index;  /*0: scalar, 1: vertex*/
+
+		/*DependentObject constructors, destructors {{{*/
+		DependentObject();
+		DependentObject(char* 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/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.cpp	(revision 18231)
@@ -0,0 +1,241 @@
+/*!\file DofIndexing.c
+ * \brief: implementation of the DofIndexing object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+
+#include "./DofIndexing.h"
+#include "../shared/Numerics/types.h"
+#include "../shared/Numerics/constants.h"
+#include "../shared/io/Print/Print.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../shared/MemOps/MemOps.h"
+#include "../shared/Enum/Enum.h"
+
+/*DofIndexing constructors and destructor*/
+DofIndexing::DofIndexing(){/*{{{*/
+
+	this->gsize    = UNDEF;
+	this->fsize    = UNDEF;
+	this->ssize    = UNDEF;
+	this->clone    = false;
+	this->active   = true;
+	this->f_set    = NULL;
+	this->s_set    = NULL;
+	this->svalues  = NULL;
+	this->doftype  = NULL;
+	this->gdoflist = NULL;
+	this->fdoflist = NULL;
+	this->sdoflist = NULL;
+
+}
+/*}}}*/
+DofIndexing::DofIndexing(int in_gsize){/*{{{*/
+
+	this->Init(in_gsize,NULL);
+
+}
+/*}}}*/
+DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor/*{{{*/
+
+	this->gsize  = in->gsize;
+	this->fsize  = in->fsize;
+	this->ssize  = in->ssize;
+	this->clone  = in->clone;
+	this->active = in->active;
+
+	if(this->gsize>0){
+		this->f_set=xNew<bool>(this->gsize);
+		this->s_set=xNew<bool>(this->gsize);
+		this->svalues=xNew<IssmDouble>(this->gsize);
+		if(in->doftype)this->doftype=xNew<int>(this->gsize); 
+		this->gdoflist=xNew<int>(this->gsize); 
+	}
+	else{
+		this->f_set    = NULL;
+		this->s_set    = NULL;
+		this->svalues  = NULL;
+		this->doftype  = NULL;
+		this->gdoflist = NULL;
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
+	if(this->ssize>0 && this->ssize!=UNDEF)this->sdoflist=xNew<int>(this->ssize); else this->sdoflist=NULL;
+
+	if(this->gsize>0){
+		memcpy(this->f_set,in->f_set,this->gsize*sizeof(bool));
+		memcpy(this->s_set,in->s_set,this->gsize*sizeof(bool));
+		xMemCpy<IssmDouble>(this->svalues,in->svalues,this->gsize);
+		if(this->doftype)memcpy(this->doftype,in->doftype,this->gsize*sizeof(int));
+		memcpy(this->gdoflist,in->gdoflist,this->gsize*sizeof(int));
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)memcpy(this->fdoflist,in->fdoflist,this->fsize*sizeof(int));
+	if(this->ssize>0 && this->ssize!=UNDEF)memcpy(this->sdoflist,in->sdoflist,this->ssize*sizeof(int));
+
+}
+/*}}}*/
+DofIndexing::~DofIndexing(){ //destructor/*{{{*/
+
+	xDelete<bool>(f_set); 
+	xDelete<bool>(s_set); 
+	xDelete<IssmDouble>(svalues);
+	xDelete<int>(doftype); 
+	xDelete<int>(gdoflist);
+	xDelete<int>(fdoflist);
+	xDelete<int>(sdoflist);
+
+}
+/*}}}*/
+void DofIndexing::Init(int in_gsize,int* in_doftype){/*{{{*/
+
+	this->gsize = in_gsize;
+
+	/*At this point, assume this is not a clone (will be dealt with later)*/
+	this->clone = false;
+
+	/*memory allocation */
+	if(this->gsize>0){
+		this->f_set    = xNew<bool>(this->gsize);
+		this->s_set    = xNew<bool>(this->gsize);
+		this->svalues  = xNew<IssmDouble>(this->gsize);
+		this->gdoflist = xNew<int>(this->gsize);
+
+		if(in_doftype)
+		 this->doftype = xNew<int>(this->gsize);
+	}
+
+	/*Assign values assuming no Dirichlet at this point*/
+	for(int i=0;i<this->gsize;i++){
+		this->f_set[i]    = true;
+		this->s_set[i]    = false;
+		this->svalues[i]  = 0.;      //0 constraint is the default value
+		this->gdoflist[i] = UNDEF;
+
+		if(this->doftype)
+		 this->doftype[i]=in_doftype[i];
+	}
+}
+/*}}}*/
+void DofIndexing::InitSet(int setenum){/*{{{*/
+
+	int i;
+	int size=0;
+
+	/*go through sets, and figure out how many dofs belong to this set, except for g-set, 
+	 * which has already been initialized: */
+	if(setenum==FsetEnum){
+		size=0;
+		for(i=0;i<this->gsize;i++) if(f_set[i])size++;
+		this->fsize=size;
+		xDelete<int>(this->fdoflist);
+
+		if(this->fsize)
+		 this->fdoflist=xNew<int>(size);
+		else
+		 this->fdoflist=NULL;
+	}
+	else if(setenum==SsetEnum){
+		size=0;
+		for(i=0;i<this->gsize;i++) if(s_set[i])size++;
+		this->ssize=size;
+		xDelete<int>(this->sdoflist);
+
+		if(this->ssize)
+		 this->sdoflist=xNew<int>(size);
+		else
+		 this->sdoflist=NULL;
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+void DofIndexing::Echo(void){/*{{{*/
+
+	_printf_("DofIndexing:\n");
+	_printf_("   gsize:  " << gsize << "\n");
+	_printf_("   fsize:  " << fsize << "\n");
+	_printf_("   ssize:  " << ssize << "\n");
+	_printf_("   clone:  " << clone << "\n");
+	_printf_("   active: " << active << "\n");
+}
+/*}}}*/
+void DofIndexing::DeepEcho(void){/*{{{*/
+
+	int i;
+
+	_printf_("DofIndexing:\n");
+	_printf_("   gsize:  " << gsize << "\n");
+	_printf_("   fsize:  " << fsize << "\n");
+	_printf_("   ssize:  " << ssize << "\n");
+	_printf_("   clone:  " << clone << "\n");
+	_printf_("   active: " << active << "\n");
+
+	_printf_("   set membership: f,s sets \n");
+	for(i=0;i<gsize;i++){
+		_printf_("      dof " << i << ": " <<(f_set[i]?"true":"false")<< " " <<(s_set[i]?"true":"false") << "\n");
+	}
+
+	_printf_("   svalues (" << this->ssize << "): |");
+	for(i=0;i<this->gsize;i++){
+		if(this->s_set[i])_printf_(" " << svalues[i] << " |");
+	}
+	_printf_("\n");
+
+	if(doftype){
+		_printf_("   doftype: |");
+		for(i=0;i<gsize;i++){
+			_printf_(" " << doftype[i] << " |");
+		}
+		_printf_("\n");
+	}
+	else _printf_("   doftype: NULL\n");
+
+	_printf_("   g_doflist (" << this->gsize << "): |");
+	for(i=0;i<this->gsize;i++){
+		_printf_(" " << gdoflist[i] << " |");
+	}
+	_printf_("\n");
+
+	_printf_("   f_doflist (" << this->fsize << "): |");
+	for(i=0;i<this->fsize;i++){
+		_printf_(" " << fdoflist[i] << " |");
+	}
+	_printf_("\n");
+
+	_printf_("   s_doflist (" << this->ssize << "): |");
+	for(i=0;i<this->ssize;i++){
+		_printf_(" " << sdoflist[i] << " |");
+	}
+	_printf_("\n");
+}		
+/*}}}*/
+void DofIndexing::Deactivate(void){/*{{{*/
+	this->active = false;
+
+	/*Constrain to 0. at this point*/
+	for(int i=0;i<this->gsize;i++){
+		this->f_set[i]    = false;
+		this->s_set[i]    = true;
+		this->svalues[i]  = 0.; 
+	}
+	return;
+}
+/*}}}*/
+void DofIndexing::Activate(void){/*{{{*/
+	this->active = true;
+
+	/*Constrain to 0. at this point*/
+	for(int i=0;i<this->gsize;i++){
+		this->f_set[i]    = true;
+		this->s_set[i]    = false;
+		this->svalues[i]  = 0.; 
+	}
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/DofIndexing.h	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file: DofIndexing.h
+ * \brief prototype for DofIndexing.h
+ */ 
+
+#ifndef _DOFINDEXING_H_
+#define _DOFINDEXING_H_
+
+#include "../shared/Numerics/types.h"
+
+class DofIndexing{
+
+	public:
+
+		/*sizes: */
+		int gsize;   //number of dofs for a node
+		int fsize;   //number of dofs solver for
+		int ssize;   //number of constrained dofs
+
+		/*partitioning: */
+		bool clone;   //this node is replicated from another one
+		bool active;  //Is this node active or inactive (all dofs are constrained)
+
+		/*boundary conditions sets: */
+		bool       *f_set;     //is dof on f-set (on which we solve)
+		bool       *s_set;     //is dof on s-set (on which boundary conditions -dirichlet- are applied)
+		IssmDouble *svalues;   //list of constraint values. size g_size, for ease of use.
+
+		/*types of dofs: */
+		int        *doftype;   //approximation type of the dofs (used only for coupling), size g_size
+
+		/*list of degrees of freedom: */
+		int *gdoflist;   //dof list in g_set
+		int *fdoflist;   //dof list in f_set
+		int *sdoflist;   //dof list in s_set
+
+		/*DofIndexing constructors, destructors {{{*/
+		DofIndexing();
+		DofIndexing(int g_size);
+		void Init(int g_size,int* doftype);
+		void InitSet(int setenum);
+		DofIndexing(DofIndexing* properties);
+		~DofIndexing();
+		/*}}}*/
+		/*Object like functionality: {{{*/
+		void  Echo(void); 
+		void  DeepEcho(void); 
+		void  copy(DofIndexing* properties);
+		/*}}}*/
+		/*DofIndexing management: {{{*/
+		DofIndexing* Spawn(int* indices, int numindices);
+		void Activate(void);
+		void Deactivate(void);
+		/*}}}*/
+
+};
+#endif //ifndef _DOFINDEXING_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.cpp	(revision 18231)
@@ -0,0 +1,1795 @@
+/*!\file Element.cpp
+ * \brief: implementation of the Element object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+Element::Element(){/*{{{*/
+	this->id  = -1;
+	this->sid = -1;
+	this->inputs     = NULL;
+	this->nodes      = NULL;
+	this->vertices   = NULL;
+	this->material   = NULL;
+	this->matpar     = NULL;
+	this->inputs     = NULL;
+	this->parameters = NULL;
+	this->element_type_list=NULL;
+}/*}}}*/
+Element::~Element(){/*{{{*/
+	xDelete<int>(element_type_list);
+	delete inputs;
+}
+/*}}}*/
+
+/*Other*/
+void       Element::AddInput(Input* input_in){/*{{{*/
+
+	/*Call inputs method*/
+	_assert_(this->inputs);
+	this->inputs->AddInput(input_in);
+}/*}}}*/
+void       Element::ComputeNewDamage(){/*{{{*/
+
+	IssmDouble *xyz_list=NULL;
+	IssmDouble  eps_xx,eps_xy,eps_yy,eps_xz,eps_yz,eps_zz,eps_eff;
+	IssmDouble  epsmin=1.e-27;
+	int         dim;
+
+	/*Retrieve all inputs we will be needing: */
+	/* TODO: retrieve parameters eps_0 and eps_f and input DamageD(bar?) */
+	this->GetVerticesCoordinates(&xyz_list);
+	this->ComputeStrainRate();
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	Input* eps_xx_input=this->GetInput(StrainRatexxEnum); _assert_(eps_xx_input);
+	Input* eps_yy_input=this->GetInput(StrainRateyyEnum); _assert_(eps_yy_input);
+	Input* eps_xy_input=this->GetInput(StrainRatexyEnum); _assert_(eps_xy_input);
+	Input* eps_xz_input=NULL;
+	Input* eps_yz_input=NULL;
+	Input* eps_zz_input=NULL;
+	if(dim==3){
+		eps_xz_input=this->GetInput(StrainRatexzEnum); _assert_(eps_xz_input);
+		eps_yz_input=this->GetInput(StrainRateyzEnum); _assert_(eps_yz_input);
+		eps_zz_input=this->GetInput(StrainRatezzEnum); _assert_(eps_zz_input);
+	}
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	int numvertices = this->GetNumberOfVertices();
+	for (int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		eps_xx_input->GetInputValue(&eps_xx,gauss);
+		eps_yy_input->GetInputValue(&eps_yy,gauss);
+		eps_xy_input->GetInputValue(&eps_xy,gauss);
+		if(dim==3){
+			eps_xz_input->GetInputValue(&eps_xz,gauss);
+			eps_yz_input->GetInputValue(&eps_yz,gauss);
+			eps_zz_input->GetInputValue(&eps_zz,gauss);
+		}
+		else{eps_xz=0; eps_yz=0; eps_zz=0;}
+
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		eps_eff=sqrt(eps_xx*eps_xx+eps_yy*eps_yy+eps_xy*eps_xy+eps_xz*eps_xz+eps_yz*eps_yz+eps_xx*eps_xx*epsmin*epsmin);
+
+		/*TODO: compute kappa from initial D, then compute new D */
+
+	}
+
+	/* TODO: add newdamage input to DamageEnum and NewDamageEnum */
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+
+}/*}}}*/
+void       Element::ComputeStrainRate(){/*{{{*/
+
+	int         dim;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  epsilon[6];
+
+	/*Retrieve all inputs we will be needing: */
+	this->GetVerticesCoordinates(&xyz_list);
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	Input* vx_input=this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=NULL;
+	if(dim==3){vz_input=this->GetInput(VzEnum); _assert_(vz_input);}
+
+	/*Allocate arrays*/
+	int numvertices = this->GetNumberOfVertices();
+	IssmDouble* eps_xx = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_yy = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_zz = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_xy = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_xz = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_yz = xNew<IssmDouble>(numvertices);
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for (int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		if(dim==2)
+		 this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		else
+		 this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		if(dim==2){
+			 /* epsilon=[exx,eyy,exy];*/
+			eps_xx[iv]=epsilon[0]; 
+			eps_yy[iv]=epsilon[1];
+			eps_xy[iv]=epsilon[2];
+		}
+		else{
+			/*epsilon=[exx eyy ezz exy exz eyz]*/
+			eps_xx[iv]=epsilon[0]; 
+			eps_yy[iv]=epsilon[1];
+			eps_zz[iv]=epsilon[2];
+			eps_xy[iv]=epsilon[3]; 
+			eps_xz[iv]=epsilon[4];
+			eps_yz[iv]=epsilon[5];
+		}
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->AddInput(StrainRatexxEnum,eps_xx,P1Enum);
+	this->AddInput(StrainRatexyEnum,eps_xy,P1Enum);
+	this->AddInput(StrainRatexzEnum,eps_xz,P1Enum);
+	this->AddInput(StrainRateyyEnum,eps_yy,P1Enum);
+	this->AddInput(StrainRateyzEnum,eps_yz,P1Enum);
+	this->AddInput(StrainRatezzEnum,eps_zz,P1Enum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(eps_xx);
+	xDelete<IssmDouble>(eps_yy);
+	xDelete<IssmDouble>(eps_zz);
+	xDelete<IssmDouble>(eps_xy);
+	xDelete<IssmDouble>(eps_xz);
+	xDelete<IssmDouble>(eps_yz);
+
+}
+/*}}}*/
+void       Element::CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i,counter;
+	int         numdofs   = 0;
+	IssmDouble  norm;
+	IssmDouble *transform = NULL;
+	IssmDouble  coord_system[3][3];
+
+	/*Some checks in debugging mode*/
+	_assert_(numnodes && nodes_list);
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Allocate and initialize transform matrix*/
+	transform=xNew<IssmDouble>(numdofs*numdofs);
+	for(i=0;i<numdofs*numdofs;i++) transform[i]=0.0;
+
+	/*Create transform matrix for all nodes (x,y for 2d and x,y,z for 3d). It is a block matrix
+	 *for 3 nodes:
+
+	 *     | T1 0  0 |
+	 * Q = | 0  T2 0 |
+	 *     | 0  0  T3|
+	 *
+	 * Where T1 is the transform matrix for node 1. It is a simple copy of the coordinate system
+	 * associated to this node*/
+	counter=0;
+	for(i=0;i<numnodes;i++){
+		nodes_list[i]->GetCoordinateSystem(&coord_system[0][0]);
+		switch(cs_array[i]){
+			case PressureEnum:
+				/*DO NOT change anything*/
+				transform[(numdofs)*(counter) + counter] = 1.;
+				counter+=1;
+				break;
+			case XYEnum:
+				/*We remove the z component, we need to renormalize x and y: x=[x1 x2 0] y=[-x2 x1 0]*/
+				norm = sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]); _assert_(norm>1.e-4);
+				transform[(numdofs)*(counter+0) + counter+0] =   coord_system[0][0]/norm;
+				transform[(numdofs)*(counter+0) + counter+1] = - coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+0] =   coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+1] =   coord_system[0][0]/norm;
+				counter+=2;
+				break;
+			case XYZEnum:
+				/*The 3 coordinates are changed (x,y,z)*/
+				transform[(numdofs)*(counter+0) + counter+0] = coord_system[0][0];
+				transform[(numdofs)*(counter+0) + counter+1] = coord_system[0][1];
+				transform[(numdofs)*(counter+0) + counter+2] = coord_system[0][2];
+				transform[(numdofs)*(counter+1) + counter+0] = coord_system[1][0];
+				transform[(numdofs)*(counter+1) + counter+1] = coord_system[1][1];
+				transform[(numdofs)*(counter+1) + counter+2] = coord_system[1][2];
+				transform[(numdofs)*(counter+2) + counter+0] = coord_system[2][0];
+				transform[(numdofs)*(counter+2) + counter+1] = coord_system[2][1];
+				transform[(numdofs)*(counter+2) + counter+2] = coord_system[2][2];
+				counter+=3;
+				break;
+			default:
+				_error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Assign output pointer*/
+	*ptransform=transform;
+}
+/*}}}*/
+void       Element::DeleteMaterials(void){/*{{{*/
+	delete this->material;
+}/*}}}*/
+void       Element::DeepEcho(void){/*{{{*/
+
+	_printf_(EnumToStringx(this->ObjectEnum())<<" element:\n");
+	_printf_("   id : "<<this->id <<"\n");
+	_printf_("   sid: "<<this->sid<<"\n");
+	if(vertices){
+		int numvertices = this->GetNumberOfVertices();
+		for(int i=0;i<numvertices;i++) vertices[i]->Echo();
+	}
+	else _printf_("vertices = NULL\n");
+
+	if(nodes){
+		int numnodes = this->GetNumberOfNodes();
+		for(int i=0;i<numnodes;i++) nodes[i]->DeepEcho();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->DeepEcho();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->DeepEcho();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->DeepEcho();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->DeepEcho();
+	else _printf_("inputs=NULL\n");
+
+	return;
+}
+/*}}}*/
+void       Element::Echo(void){/*{{{*/
+	_printf_(EnumToStringx(this->ObjectEnum())<<" element:\n");
+	_printf_("   id : "<<this->id <<"\n");
+	_printf_("   sid: "<<this->sid<<"\n");
+	if(vertices){
+		int numvertices = this->GetNumberOfVertices();
+		for(int i=0;i<numvertices;i++) vertices[i]->Echo();
+	}
+	else _printf_("vertices = NULL\n");
+
+	if(nodes){
+		int numnodes = this->GetNumberOfNodes();
+		for(int i=0;i<numnodes;i++) nodes[i]->Echo();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->Echo();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->Echo();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->Echo();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->Echo();
+	else _printf_("inputs=NULL\n");
+}
+/*}}}*/
+IssmDouble Element::Divergence(void){/*{{{*/
+	/*Compute element divergence*/
+
+	/*Intermediaries*/
+	int        dim;
+	IssmDouble Jdet;
+	IssmDouble divergence=0.;
+	IssmDouble dvx[3],dvy[3],dvz[3];
+	IssmDouble *xyz_list = NULL;
+
+	/*Get inputs and parameters*/
+	this->FindParam(&dim,DomainDimensionEnum);
+	Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){
+		vz_input = this->GetInput(VzEnum); _assert_(vz_input);
+	}
+	this->GetVerticesCoordinates(&xyz_list);
+
+	Gauss* gauss=this->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		this->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get strain rate assuming that epsilon has been allocated*/
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		if(dim==2){
+			divergence += (dvx[0]+dvy[1])*gauss->weight*Jdet;
+		}
+		else{
+			vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+			divergence += (dvx[0]+dvy[1]+dvz[2])*gauss->weight*Jdet;
+		}
+
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return divergence;
+}/*}}}*/
+void       Element::dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble epsilon1d;   /* epsilon=[exx];    */
+	IssmDouble eps_eff;
+
+	 if(dim==2){
+		 /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		 this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		 eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	 }
+	 else{
+		 /* eps_eff^2 = 1/2 exx^2*/
+		 this->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		 eps_eff = sqrt(epsilon1d*epsilon1d/2.);
+	 }
+
+	/*Get viscosity*/
+	material->GetViscosity_B(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
+void       Element::dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble epsilon1d;   /* epsilon=[exx];    */
+	IssmDouble eps_eff;
+
+	if(dim==2){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	}
+	else{
+		/* eps_eff^2 = 1/2 exx^2*/
+		this->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		eps_eff = sqrt(epsilon1d*epsilon1d/2.);
+	}
+
+	/*Get viscosity*/
+	material->GetViscosity_D(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
+void       Element::ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
+	matpar->ThermalToEnthalpy(penthalpy,temperature,waterfraction,pressure);
+}/*}}}*/
+void       Element::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	matpar->EnthalpyToThermal(ptemperature,pwaterfraction,enthalpy,pressure);
+}/*}}}*/
+IssmDouble Element::EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	return matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+}/*}}}*/
+IssmDouble Element::EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
+	return matpar->GetEnthalpyDiffusionParameterVolume(numvertices,enthalpy,pressure);
+}/*}}}*/
+void       Element::FindParam(bool* pvalue,int paramenum){/*{{{*/
+	this->parameters->FindParam(pvalue,paramenum);
+}/*}}}*/
+void       Element::FindParam(int* pvalue,int paramenum){/*{{{*/
+	this->parameters->FindParam(pvalue,paramenum);
+}/*}}}*/
+void       Element::FindParam(IssmDouble* pvalue,int paramenum){/*{{{*/
+	this->parameters->FindParam(pvalue,paramenum);
+}/*}}}*/
+void       Element::FindParam(int** pvalues,int* psize,int paramenum){/*{{{*/
+	this->parameters->FindParam(pvalues,psize,paramenum);
+}/*}}}*/
+void       Element::GetDofList(int** pdoflist,int approximation_enum,int setenum){/*{{{*/
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->GetNumberOfNodes();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=0;i<numnodes;i++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+void       Element::GetDofListVelocity(int** pdoflist,int setenum){/*{{{*/
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodesVelocity();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=0;i<numnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSvelocityEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+void       Element::GetDofListPressure(int** pdoflist,int setenum){/*{{{*/
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSApproximationEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+IssmDouble Element::GetMaterialParameter(int enum_in){/*{{{*/
+
+	_assert_(this->matpar);
+	switch(enum_in){ // FIXME: change this to material
+		case MaterialsRheologyNEnum:
+			return this->material->GetN();
+		case MaterialsRheologyBEnum:
+			return this->material->GetB();
+		case MaterialsRheologyBbarEnum:
+			return this->material->GetBbar();
+		default:
+			return this->matpar->GetMaterialParameter(enum_in);
+	}
+}/*}}}*/
+void       Element::GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity){/*{{{*/
+	/*Compute deformational heating from epsilon and viscosity */
+
+	IssmDouble epsilon_matrix[3][3];
+	IssmDouble epsilon_eff;
+	IssmDouble epsilon_sqr[3][3];
+
+	/* Build epsilon matrix */
+	epsilon_matrix[0][0]=epsilon[0];
+	epsilon_matrix[1][0]=epsilon[3];
+	epsilon_matrix[2][0]=epsilon[4];
+	epsilon_matrix[0][1]=epsilon[3];
+	epsilon_matrix[1][1]=epsilon[1];
+	epsilon_matrix[2][1]=epsilon[5];
+	epsilon_matrix[0][2]=epsilon[4];
+	epsilon_matrix[1][2]=epsilon[5];
+	epsilon_matrix[2][2]=epsilon[2];
+
+	/* Effective value of epsilon_matrix */
+	epsilon_sqr[0][0]=epsilon_matrix[0][0]*epsilon_matrix[0][0];
+	epsilon_sqr[1][0]=epsilon_matrix[1][0]*epsilon_matrix[1][0];
+	epsilon_sqr[2][0]=epsilon_matrix[2][0]*epsilon_matrix[2][0];
+	epsilon_sqr[0][1]=epsilon_matrix[0][1]*epsilon_matrix[0][1];
+	epsilon_sqr[1][1]=epsilon_matrix[1][1]*epsilon_matrix[1][1];
+	epsilon_sqr[2][1]=epsilon_matrix[2][1]*epsilon_matrix[2][1];
+	epsilon_sqr[0][2]=epsilon_matrix[0][2]*epsilon_matrix[0][2];
+	epsilon_sqr[1][2]=epsilon_matrix[1][2]*epsilon_matrix[1][2];
+	epsilon_sqr[2][2]=epsilon_matrix[2][2]*epsilon_matrix[2][2];
+	epsilon_eff=1/sqrt(2.)*sqrt(epsilon_sqr[0][0]+epsilon_sqr[0][1]+ epsilon_sqr[0][2]+ epsilon_sqr[1][0]+ epsilon_sqr[1][1]+ epsilon_sqr[1][2]+ epsilon_sqr[2][0]+ epsilon_sqr[2][1]+ epsilon_sqr[2][2]);
+
+	/*Phi = Tr(sigma * eps) 
+	 *    = Tr(sigma'* eps)
+	 *    = 2 * eps_eff * sigma'_eff
+	 *    = 4 * mu * eps_eff ^2*/
+	*phi=4.*epsilon_eff*epsilon_eff*viscosity;
+}
+/*}}}*/
+Input*     Element::GetInput(int inputenum){/*{{{*/
+	return inputs->GetInput(inputenum);
+}/*}}}*/
+void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	/*Recover input*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Fetch number vertices for this element*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	Gauss*gauss=this->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
+
+	/*Recover input*/
+	Input* input=this->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/*Fetch number vertices for this element*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		Gauss* gauss=this->NewGauss();
+		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;
+	}
+}
+/*}}}*/
+void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
+
+	_assert_(pvalue);
+
+	Input *input    = this->GetInput(enumtype);
+	int    numnodes = this->GetNumberOfNodes();
+
+	/* Start looping on the number of vertices: */
+	if(input){
+		Gauss* gauss=this->NewGauss();
+		for(int iv=0;iv<numnodes;iv++){
+			gauss->GaussNode(this->FiniteElement(),iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for(int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	_assert_(pvalue);
+
+	int    numnodes = this->GetNumberOfNodes();
+	Input *input    = this->GetInput(enumtype);
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for(int iv=0;iv<numnodes;iv++){
+		gauss->GaussNode(this->FiniteElement(),iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	_assert_(pvalue);
+
+	int    numnodes = this->NumberofNodesVelocity();
+	Input *input    = this->GetInput(enumtype);
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for(int iv=0;iv<numnodes;iv++){
+		gauss->GaussNode(this->VelocityInterpolation(),iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputValue(bool* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(int* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(IssmDouble* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue,gauss);
+
+}/*}}}*/
+void       Element::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+	int numnodes = this->GetNumberOfNodes();
+	for(int i=0;i<numnodes;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
+void       Element::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+	int numnodes = this->GetNumberOfNodes();
+	for(int i=0;i<numnodes;i++){
+		lidlist[i]=nodes[i]->Lid();
+	}
+}
+/*}}}*/
+void       Element::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){/*{{{*/
+
+	/*Fetch number vertices for this element and allocate arrays*/
+	int numvertices = this->GetNumberOfVertices();
+	int*        vertexpidlist = xNew<int>(numvertices);
+	IssmDouble* values        = xNew<IssmDouble>(numvertices);
+
+	/*Fill in values*/
+	this->GetVertexPidList(vertexpidlist);
+	this->GetInputListOnVertices(values,input_enum);
+	vector->SetValues(numvertices,vertexpidlist,values,INS_VAL);
+
+	/*Clean up*/
+	xDelete<int>(vertexpidlist);
+	xDelete<IssmDouble>(values);
+
+}
+/*}}}*/
+void       Element::GetVertexPidList(int* pidlist){/*{{{*/
+
+	int numvertices = this->GetNumberOfVertices();
+	for(int i=0;i<numvertices;i++) pidlist[i]=vertices[i]->Pid();
+
+}
+/*}}}*/
+void       Element::GetVerticesCoordinates(IssmDouble** pxyz_list){/*{{{*/
+
+	int         numvertices = this->GetNumberOfVertices();
+	IssmDouble* xyz_list    = xNew<IssmDouble>(numvertices*3);
+	::GetVerticesCoordinates(xyz_list,this->vertices,numvertices);
+
+	*pxyz_list = xyz_list;
+
+}/*}}}*/
+void       Element::GetVerticesSidList(int* sidlist){/*{{{*/
+
+	int numvertices = this->GetNumberOfVertices();
+	for(int i=0;i<numvertices;i++) sidlist[i]=this->vertices[i]->Sid();
+}
+/*}}}*/
+void       Element::GetVerticesConnectivityList(int* connectivity){/*{{{*/
+
+	int numvertices = this->GetNumberOfVertices();
+	for(int i=0;i<numvertices;i++) connectivity[i]=this->vertices[i]->Connectivity();
+}
+/*}}}*/
+IssmDouble Element::GetXcoord(IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*output*/
+	IssmDouble x;
+
+	/*Create list of x*/
+	int         numvertices = this->GetNumberOfVertices();
+	IssmDouble* x_list      = xNew<IssmDouble>(numvertices);
+
+	for(int i=0;i<numvertices;i++) x_list[i]=xyz_list[i*3+0];
+	ValueP1OnGauss(&x,x_list,gauss);
+
+	xDelete<IssmDouble>(x_list);
+	return x;
+}/*}}}*/
+IssmDouble Element::GetYcoord(IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*output*/
+	IssmDouble y;
+
+	/*Create list of y*/
+	int         numvertices = this->GetNumberOfVertices();
+	IssmDouble* y_list      = xNew<IssmDouble>(numvertices);
+
+	for(int i=0;i<numvertices;i++) y_list[i]=xyz_list[i*3+1];
+	ValueP1OnGauss(&y,y_list,gauss);
+
+	xDelete<IssmDouble>(y_list);
+	return y;
+}/*}}}*/
+IssmDouble Element::GetZcoord(IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*output*/
+	IssmDouble z;
+
+	/*Create list of z*/
+	int         numvertices = this->GetNumberOfVertices();
+	IssmDouble* z_list      = xNew<IssmDouble>(numvertices);
+
+	for(int i=0;i<numvertices;i++) z_list[i]=xyz_list[i*3+2];
+	ValueP1OnGauss(&z,z_list,gauss);
+
+	xDelete<IssmDouble>(z_list);
+	return z;
+}/*}}}*/
+void       Element::GradientIndexing(int* indexing,int control_index){/*{{{*/
+
+	/*Get number of controls*/
+	int num_controls;
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+
+	/*Get number of vertices*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/*get gradient indices*/
+	for(int i=0;i<numvertices;i++){
+		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+	}
+
+}
+/*}}}*/
+bool       Element::HasNodeOnBase(){/*{{{*/
+	return (this->inputs->Max(MeshVertexonbaseEnum)>0.);
+}/*}}}*/
+bool       Element::HasNodeOnSurface(){/*{{{*/
+	return (this->inputs->Max(MeshVertexonsurfaceEnum)>0.);
+}/*}}}*/
+int        Element::Id(){/*{{{*/
+
+	return this->id;
+
+}
+/*}}}*/
+void       Element::InputChangeName(int original_enum,int new_enum){/*{{{*/
+	this->inputs->ChangeEnum(original_enum,new_enum);
+}
+/*}}}*/
+void       Element::InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){/*{{{*/
+
+	/*Intermediaries*/
+	int        i,t;
+	IssmDouble time;
+
+	/*Branch on type of vector: nodal or elementary: */
+	if(vector_type==1){ //nodal vector
+
+		int         numvertices = this->GetNumberOfVertices();
+		int        *vertexids   = xNew<int>(numvertices);
+		IssmDouble *values      = xNew<IssmDouble>(numvertices);
+
+		/*Recover vertices ids needed to initialize inputs*/
+		_assert_(iomodel->elements);
+		for(i=0;i<numvertices;i++){ 
+			vertexids[i]=reCast<int>(iomodel->elements[numvertices*this->Sid()+i]); //ids for vertices are in the elements array from Matlab
+		}
+
+		/*Are we in transient or static? */
+		if(M==iomodel->numberofvertices){
+			for(i=0;i<numvertices;i++) values[i]=vector[vertexids[i]-1];
+			this->AddInput(vector_enum,values,P1Enum);
+		}
+		else if(M==iomodel->numberofvertices+1){
+			/*create transient input: */
+			IssmDouble* times = xNew<IssmDouble>(N);
+			for(t=0;t<N;t++) times[t] = vector[(M-1)*N+t];
+			TransientInput* transientinput=new TransientInput(vector_enum,times,N);
+			for(t=0;t<N;t++){
+				for(i=0;i<numvertices;i++) values[i]=vector[N*(vertexids[i]-1)+t];
+				switch(this->ObjectEnum()){
+					case TriaEnum:  transientinput->AddTimeInput(new TriaInput( vector_enum,values,P1Enum)); break;
+					case PentaEnum: transientinput->AddTimeInput(new PentaInput(vector_enum,values,P1Enum)); break;
+					case TetraEnum: transientinput->AddTimeInput(new TetraInput(vector_enum,values,P1Enum)); break;
+					default: _error_("Not implemented yet");
+				}
+			}
+			this->inputs->AddInput(transientinput);
+			xDelete<IssmDouble>(times);
+		}
+		else _error_("nodal vector is either numberofvertices or numberofvertices+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+
+		xDelete<IssmDouble>(values);
+		xDelete<int>(vertexids);
+	}
+	else if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==iomodel->numberofelements){
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[this->Sid()])));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int>(vector[this->Sid()])));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[this->Sid()]));
+			}
+			else _error_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error_("transient element inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+}/*}}}*/
+void       Element::InputDuplicate(int original_enum,int new_enum){/*{{{*/
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+void       Element::InputUpdateFromConstant(int constant, int name){/*{{{*/
+
+	/*Check that name is an element input*/
+	if(!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+void       Element::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
+
+	/*Check that name is an element input*/
+	if(!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+void       Element::InputUpdateFromConstant(bool constant, int name){/*{{{*/
+
+	/*Check that name is an element input*/
+	if(!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+bool       Element::IsFloating(){/*{{{*/
+
+	bool shelf;
+	int  migration_style;
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+
+	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum || migration_style==ContactEnum){ //Floating if all nodes are floating
+		if(this->inputs->Max(MaskGroundediceLevelsetEnum) <= 0.) shelf=true;
+		else shelf=false;
+	}
+	else if(migration_style==NoneEnum || migration_style==AggressiveMigrationEnum || migration_style==SoftMigrationEnum){ //Floating if all nodes are floating
+		if(this->inputs->Min(MaskGroundediceLevelsetEnum) > 0.) shelf=false;
+		else shelf=true;
+	}
+	else _error_("migration_style not implemented yet");
+
+	return shelf;
+}/*}}}*/
+bool       Element::IsIceInElement(){/*{{{*/
+	return (this->inputs->Min(MaskIceLevelsetEnum)<0.);
+}
+/*}}}*/
+bool       Element::IsInput(int name){/*{{{*/
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BaseEnum ||
+				name==BedEnum ||
+				name==BalancethicknessThickeningRateEnum ||
+				name==BalancethicknessApparentMassbalanceEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==BasalforcingsGroundediceMeltingRateEnum ||
+				name==BasalforcingsFloatingiceMeltingRateEnum ||
+				name==BasalforcingsGeothermalfluxEnum ||
+				name==SurfaceAreaEnum||
+				name==DamageDEnum ||
+				name==DamageDbarEnum ||
+				name==PressureEnum ||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==VzEnum ||
+				name==VxMeshEnum ||
+				name==VyMeshEnum ||
+				name==VzMeshEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==InversionVzObsEnum ||
+				name==TemperatureEnum ||
+				name==EnthalpyEnum ||
+				name==EnthalpyPicardEnum ||
+				name==WaterfractionEnum||
+				name==WatercolumnEnum || 
+				name==FrictionCoefficientEnum ||
+				name==MaskGroundediceLevelsetEnum ||
+				name==MaskIceLevelsetEnum ||
+				name==IceMaskNodeActivationEnum ||
+				name==LevelsetfunctionSlopeXEnum ||
+				name==LevelsetfunctionSlopeYEnum ||
+				name==LevelsetfunctionPicardEnum ||
+				name==MasstransportCalvingrateEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum  ||
+				name==ConvergedEnum || 
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuVzEnum ||
+				name==QmuVxMeshEnum ||
+				name==QmuVyMeshEnum ||
+				name==QmuVzMeshEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBaseEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum ||
+				name==QmuMaskGroundediceLevelsetEnum ||
+				name==QmuMaskIceLevelsetEnum ||
+				name==QmuMaterialsRheologyBEnum ||
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum ||
+				name==GiaWEnum || 
+				name==GiadWdtEnum ||
+				name==SedimentHeadEnum ||
+				name==EplHeadEnum ||
+				name==SedimentHeadOldEnum ||
+				name==EplHeadOldEnum ||
+				name==HydrologydcEplThicknessOldEnum ||
+				name==HydrologydcEplInitialThicknessEnum ||
+				name==HydrologydcEplThicknessEnum ||
+				name==HydrologydcMaskEplactiveNodeEnum ||
+				name==MeshVertexonbaseEnum 
+
+				) {
+					return true;
+				}
+	else return false;
+}
+/*}}}*/
+void       Element::LinearFloatingiceMeltingRate(){/*{{{*/
+
+	int numvertices      = this->GetNumberOfVertices();
+	IssmDouble  deepwaterel,upperwaterel,deepwatermelt;
+	IssmDouble* base     = xNew<IssmDouble>(numvertices);
+	IssmDouble* values   = xNew<IssmDouble>(numvertices);
+
+	parameters->FindParam(&deepwaterel,BasalforcingsDeepwaterElevationEnum);
+	parameters->FindParam(&upperwaterel,BasalforcingsUpperwaterElevationEnum);
+	parameters->FindParam(&deepwatermelt,BasalforcingsDeepwaterMeltingRateEnum);
+
+	this->GetInputListOnVertices(base,BaseEnum);
+	for(int i=0;i<numvertices;i++){
+		if(base[i]>upperwaterel)      values[i]=0;
+		else if (base[i]<deepwaterel) values[i]=deepwatermelt;
+		else values[i]=deepwatermelt*(base[i]-upperwaterel)/(deepwaterel-upperwaterel);
+	}
+
+	this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,values,P1Enum);
+
+}/*}}}*/
+ElementVector* Element::NewElementVector(int approximation_enum){/*{{{*/
+	return new ElementVector(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
+}
+/*}}}*/
+ElementMatrix* Element::NewElementMatrix(int approximation_enum){/*{{{*/
+	return new ElementMatrix(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
+}
+/*}}}*/
+ElementMatrix* Element::NewElementMatrixCoupling(int number_nodes,int approximation_enum){/*{{{*/
+	return new ElementMatrix(nodes,number_nodes,this->parameters,approximation_enum);
+}
+/*}}}*/
+IssmDouble Element::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
+	return this->matpar->PureIceEnthalpy(pressure);
+}/*}}}*/
+void       Element::ResultInterpolation(int* pinterpolation,int* pnodesperelement,int output_enum){/*{{{*/
+
+	Input* input=this->inputs->GetInput(output_enum);
+
+	/*If this input is not already in Inputs, maybe it needs to be computed?*/
+	if(!input){
+		switch(output_enum){
+			case ViscousHeatingEnum:
+				this->ViscousHeatingCreateInput();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressTensorxxEnum: 
+			case StressTensorxyEnum: 
+			case StressTensorxzEnum: 
+			case StressTensoryyEnum: 
+			case StressTensoryzEnum: 
+			case StressTensorzzEnum: 
+				this->ComputeStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StrainRatexxEnum:
+			case StrainRatexyEnum:
+			case StrainRatexzEnum:
+			case StrainRateyyEnum:
+			case StrainRateyzEnum:
+			case StrainRatezzEnum:
+				this->ComputeStrainRate();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case DeviatoricStressxxEnum: 
+			case DeviatoricStressxyEnum: 
+			case DeviatoricStressxzEnum: 
+			case DeviatoricStressyyEnum: 
+			case DeviatoricStressyzEnum: 
+			case DeviatoricStresszzEnum: 
+				this->ComputeDeviatoricStressTensor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case SigmaNNEnum: 
+				this->ComputeSigmaNN();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case NewDamageEnum:
+				this->ComputeNewDamage();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			default:
+				_error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+		}
+	}
+
+	/*Assign output pointer*/
+	*pinterpolation   = input->GetResultInterpolation();
+	*pnodesperelement = input->GetResultNumberOfNodes();
+}/*}}}*/
+void       Element::ResultToVector(Vector<IssmDouble>* vector,int output_enum){/*{{{*/
+
+	Input* input=this->inputs->GetInput(output_enum);
+	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+
+	switch(input->GetResultInterpolation()){
+		case P0Enum:{
+			IssmDouble  value;
+			bool        bvalue;
+			Input*      input = this->GetInput(output_enum); _assert_(input);
+			switch(input->ObjectEnum()){
+				case DoubleInputEnum:
+					input->GetInputValue(&value);
+					break;
+				case BoolInputEnum:
+					input->GetInputValue(&bvalue);
+					value=reCast<IssmDouble>(bvalue);
+					break;
+				default:
+					Gauss* gauss = this->NewGauss();
+					input->GetInputValue(&value,gauss);
+					delete gauss;
+			}
+			vector->SetValue(this->Sid(),value,INS_VAL);
+			break;
+		}
+		case P1Enum:{
+			int         numvertices = this->GetNumberOfVertices();
+			IssmDouble *values      = xNew<IssmDouble>(numvertices);
+			int        *connectivity= xNew<int>(numvertices);
+			int        *sidlist     = xNew<int>(numvertices);
+
+			this->GetVerticesSidList(sidlist);
+			this->GetVerticesConnectivityList(connectivity);
+			this->GetInputListOnVertices(values,output_enum);
+			for(int i=0;i<numvertices;i++) values[i] = values[i]/reCast<IssmDouble>(connectivity[i]);
+
+			vector->SetValues(numvertices,sidlist,values,ADD_VAL);
+
+			xDelete<IssmDouble>(values);
+			xDelete<int>(connectivity);
+			xDelete<int>(sidlist);
+			break;
+		}
+		default:
+					 _error_("interpolation "<<EnumToStringx(input->GetResultInterpolation())<<" not supported yet");
+	}
+} /*}}}*/
+void       Element::ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum){/*{{{*/
+
+	Input* input=this->inputs->GetInput(output_enum);
+	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+
+	input->ResultToPatch(values,nodesperelement,this->Sid());
+
+} /*}}}*/
+void       Element::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
+
+	/*Intermediaries*/
+	const int numnodes = this->GetNumberOfNodes();
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<numnodes;i++){
+
+		if(!flags[this->nodes[i]->Lid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Special case: 2d/3d coupling, the node of this element might be connected
+	 *to the basal element*/
+	int analysis_type,approximation,numlayers;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	if(analysis_type==StressbalanceAnalysisEnum){
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==SSAHOApproximationEnum || approximation==SSAFSApproximationEnum){
+			parameters->FindParam(&numlayers,MeshNumberoflayersEnum);
+			o_nz += numlayers*3;
+			d_nz += numlayers*3;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
+int        Element::Sid(){/*{{{*/
+
+	return this->sid;
+
+}
+/*}}}*/
+IssmDouble Element::TMeltingPoint(IssmDouble pressure){/*{{{*/
+	_assert_(matpar);
+	return this->matpar->TMeltingPoint(pressure);
+}/*}}}*/
+void       Element::ViscousHeatingCreateInput(void){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble phi;
+	IssmDouble viscosity;
+	IssmDouble epsilon[6];
+	IssmDouble thickness;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number vertices and allocate memory*/
+	int         numvertices    = this->GetNumberOfVertices();
+	IssmDouble* viscousheating = xNew<IssmDouble>(numvertices);
+
+	/*Retrieve all inputs and parameters*/
+	this->GetVerticesCoordinatesBase(&xyz_list);
+	Input* vx_input        = this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input        = this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input        = this->GetInput(VzEnum); _assert_(vz_input);
+	Input* thickness_input = this->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/*loop over vertices: */
+	Gauss* gauss=this->NewGauss();
+	for (int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
+		this->GetPhi(&phi,&epsilon[0],viscosity);
+
+		viscousheating[iv]=phi*thickness;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->AddInput(ViscousHeatingEnum,viscousheating,P1Enum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(viscousheating);
+	delete gauss;
+}
+/*}}}*/
+void       Element::ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+	/*The effective strain rate is defined in Paterson 3d Ed p 91 eq 9,
+	 * and Cuffey p 303 eq 8.18:
+	 *
+	 *  2 eps_eff^2 = eps_xx^2 + eps_yy^2 + eps_zz^2 + 2(eps_xy^2 + eps_xz^2 + eps_yz^2)
+	 *
+	 *  or
+	 *
+	 *  eps_eff = 1/sqrt(2) sqrt( \sum_ij eps_ij^2 )
+	 *
+	 *          = 1/sqrt(2) ||eps||_F
+	 *
+	 *  where ||.||_F is the Frobenius norm */
+
+	/*Intermediaries*/
+	IssmDouble viscosity;
+	IssmDouble epsilon3d[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble epsilon2d[3]; /* epsilon=[exx,eyy,exy];            */
+	IssmDouble eps_eff;
+	IssmDouble eps0=1.e-27;
+
+	if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		this->StrainRateFS(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[3]*epsilon3d[3] +  epsilon3d[4]*epsilon3d[4] + epsilon3d[5]*epsilon3d[5] + epsilon3d[0]*epsilon3d[1]+eps0*eps0);
+	}
+	else{
+		/* eps_eff^2 = 1/2 ( exx^2 + eyy^2 + 2*exy^2 )*/
+		this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + 2.*epsilon2d[2]*epsilon2d[2]);
+	}
+
+	/*Get viscosity*/
+	material->GetViscosity(&viscosity,eps_eff);
+
+	/*Assign output pointer*/
+	*pviscosity=viscosity;
+}
+/*}}}*/
+void       Element::ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surface_input){/*{{{*/
+	/*Compute the L1L2 viscosity
+	 *
+	 *      1
+	 * mu = - A^-1 (sigma'_e)^(1-n)
+	 *      2
+	 *
+	 * sigma'_e^2 = |sigma'_//|^2 + |sigma'_perp|^2 (see Perego 2012 eq. 17,18)
+	 *
+	 * L1L2 assumptions:
+	 *
+	 * (1) |eps_b|_// = A (|sigma'_//|^2 + |sigma'_perp|^2)^((n-1)/2) |sigma'_//|
+	 * (2) |sigma'_perp|^2 = |rho g (s-z) grad(s)|^2
+	 *
+	 * Assuming that n = 3, we have a polynom of degree 3 to solve (the only unkown is X=|sigma'_//|)
+	 *
+	 * A X^3 + A |rho g (s-z) grad(s)|^2 X - |eps_b|_// = 0     */
+
+	IssmDouble z,s,viscosity,p,q,delta;
+	IssmDouble tau_perp,tau_par,eps_b,A;
+	IssmDouble epsilon[5];   /*exx eyy exy exz eyz*/
+	IssmDouble slope[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !surface_input) _error_("Input missing");
+
+	/*Get tau_perp*/
+	surface_input->GetInputValue(&s,gauss);
+	surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+	z=this->GetZcoord(xyz_list,gauss);
+	tau_perp = matpar->GetRhoIce() * matpar->GetG() * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
+
+	/* Get eps_b*/
+	this->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+	eps_b = sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[0]*epsilon[1] + epsilon[2]*epsilon[2]);
+	if(eps_b==0.){
+		*pviscosity = 2.5e+17;
+		return;
+	}
+
+	/*Get A*/
+	_assert_(material->GetN()==3.0);
+	A=material->GetA();
+
+	/*Solve for tau_perp (http://fr.wikipedia.org/wiki/Méthode_de_Cardan)*/
+	p     = tau_perp *tau_perp;
+	q     = - eps_b/A;
+	delta = q *q + p*p*p*4./27.;
+	_assert_(delta>0);
+	tau_par = pow(0.5*(-q+sqrt(delta)),1./3.) - pow(0.5*(q+sqrt(delta)),1./3.);
+
+	/*Viscosity*/
+	viscosity = 1./(2.*A*(tau_par*tau_par + tau_perp*tau_perp));
+	_assert_(!xIsNan(viscosity));
+	_assert_(viscosity > 0.);
+
+	/*Assign output pointer*/
+	*pviscosity = viscosity;
+}/*}}}*/
+void       Element::ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble viscosity;
+	IssmDouble epsilon3d[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble epsilon2d[2];/* epsilon=[exx,exy];            */
+	IssmDouble eps_eff;
+
+	if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		this->StrainRateHO(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[2]*epsilon3d[2] +  epsilon3d[3]*epsilon3d[3] + epsilon3d[4]*epsilon3d[4] + epsilon3d[0]*epsilon3d[1]);
+	}
+	else{
+		/* eps_eff^2 = 1/2 (exx^2 + 2*exy^2 )*/
+		this->StrainRateHO2dvertical(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + 2.*epsilon2d[1]*epsilon2d[1]);
+	}
+
+	/*Get viscosity*/
+	material->GetViscosity(&viscosity,eps_eff);
+
+	/*Assign output pointer*/
+	*pviscosity=viscosity;
+}/*}}}*/
+void       Element::ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble viscosity;
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble epsilon1d;   /* epsilon=[exx];    */
+	IssmDouble eps_eff;
+
+	 if(dim==2){
+		 /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		 this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		 eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	 }
+	 else{
+		 /* eps_eff^2 = 1/2 exx^2*/
+		 this->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		 eps_eff = sqrt(epsilon1d*epsilon1d/2.);
+	 }
+
+	/*Get viscosity*/
+	material->GetViscosityBar(&viscosity,eps_eff);
+
+	/*Assign output pointer*/
+	*pviscosity=viscosity;
+}/*}}}*/
+void       Element::ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	this->material->GetViscosity2dDerivativeEpsSquare(pmu_prime,epsilon);
+}/*}}}*/
+void       Element::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+}/*}}}*/
+void       Element::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+}/*}}}*/
+void       Element::StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+	/*Compute the 3d Strain Rate (6 components):
+	 *
+	 * epsilon=[exx eyy ezz exy exz eyz]
+	 */
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+	IssmDouble dvz[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !vz_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = dvz[2];
+	epsilon[3] = 0.5*(dvx[1] + dvy[0]);
+	epsilon[4] = 0.5*(dvx[2] + dvz[0]);
+	epsilon[5] = 0.5*(dvy[2] + dvz[1]);
+
+}/*}}}*/
+void       Element::StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	/*Compute the 3d Blatter/HOStrain Rate (5 components):
+	 *
+	 * epsilon=[exx eyy exy exz eyz]
+	 *
+	 * with exz=1/2 du/dz
+	 *      eyz=1/2 dv/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
+	epsilon[3] = 0.5*dvx[2];
+	epsilon[4] = 0.5*dvy[2];
+
+}/*}}}*/
+void       Element::StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	/*Compute the 2d Blatter/HOStrain Rate (2 components):
+	 *
+	 * epsilon=[exx exz]
+	 *
+	 * with exz=1/2 du/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input <<"\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = 0.5*dvx[1];
+
+}/*}}}*/
+void       Element::StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+
+	/*Check that both inputs have been found*/
+	if(!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
+
+}/*}}}*/
+void       Element::StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	*epsilon = dvx[0];
+
+}/*}}}*/
+void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int numnodes  = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	TransformInvStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i,j;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R*Ke*R^T */
+	TripleMultiply(transform,numdofs,numdofs,0,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,1,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformLoadVectorCoord(pe,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,int* cs_array){/*{{{*/
+
+	this->TransformLoadVectorCoord(pe,this->nodes,this->GetNumberOfNodes(),cs_array);
+
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current load vector*/
+	values=xNew<IssmDouble>(pe->nrows);
+	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R^T*pe */
+	MatrixMultiply(transform,numdofs,numdofs,1,
+				values,pe->nrows,1,0,
+				&pe->values[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int* transformenum_list){/*{{{*/
+	this->TransformSolutionCoord(values,this->nodes,this->GetNumberOfNodes(),transformenum_list);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int numnodes,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array){/*{{{*/
+	this->TransformSolutionCoord(solution,this->nodes,numnodes,cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,Node** nodes_list,int numnodes,int transformenum){/*{{{*/
+	/*NOT NEEDED*/
+	/*All nodes have the same Coordinate System*/
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,nodes_list,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* solution,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current solution vector*/
+	values=xNew<IssmDouble>(numdofs);
+	for(i=0;i<numdofs;i++) values[i]=solution[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R*U */
+	MatrixMultiply(transform,numdofs,numdofs,0,
+				values,numdofs,1,0,
+				&solution[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* transformenum_list){/*{{{*/
+	this->TransformStiffnessMatrixCoord(Ke,this->nodes,this->GetNumberOfNodes(),transformenum_list);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         numdofs = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(int i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(int i=0;i<Ke->nrows*Ke->ncols;i++) values[i]=Ke->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R^T*Ke*R */
+	TripleMultiply(transform,numdofs,numdofs,1,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,0,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Element.h	(revision 18231)
@@ -0,0 +1,287 @@
+/*!\file:  Element.h
+ * \brief abstract class for Element object
+ * This class is a place holder for the Tria and the Penta elements. 
+ * It is derived from Element, so DataSets can contain them.
+ */ 
+
+#ifndef _ELEMENT_H_
+#define _ELEMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../../toolkits/toolkits.h"
+#include "../Update.h"
+class DataSet;
+class Parameters;
+class Parameter;
+class Elements;
+class Loads;
+class Nodes;
+class Node;
+class Vertices;
+class Vertex;
+class Materials;
+class Material;
+class Matpar;
+class Inputs;
+class Input;
+class Gauss;
+class ElementVector;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+class ElementMatrix;
+class ElementVector;
+/*}}}*/
+
+class Element: public Object,public Update{
+
+	public:
+		int          id;
+		int          sid;
+		Inputs      *inputs;
+		Node       **nodes;
+		Vertex     **vertices;
+		Material    *material;
+		Matpar      *matpar;
+		Parameters  *parameters;
+
+		int* element_type_list;
+		int  element_type;
+
+	public: 
+		/*Constructors/Destructores*/
+		Element();
+		~Element();
+
+		/*Functions*/
+		void       AddInput(Input* input_in);
+		/* bool       AllActive(void); */
+		/* bool       AnyActive(void); */
+		void       ComputeNewDamage();
+		void       ComputeStrainRate();
+		void       CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
+		void       Echo();
+		void       DeepEcho();
+		void       DeleteMaterials(void);
+		void       dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		IssmDouble Divergence(void);
+		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
+		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
+		void       FindParam(bool* pvalue,int paramenum);
+		void       FindParam(int* pvalue,int paramenum);
+		void       FindParam(IssmDouble* pvalue,int paramenum);
+		void       FindParam(int** pvalues,int* psize,int paramenum);
+		void	     GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	     GetDofListVelocity(int** pdoflist,int setenum);
+		void	     GetDofListPressure(int** pdoflist,int setenum);
+		Input*     GetInput(int inputenum);
+		void       GetInputListOnNodes(IssmDouble* pvalue,int enumtype);
+		void       GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void       GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype);
+		void       GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
+		void       GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void       GetInputValue(bool* pvalue,int enum_type);
+		void       GetInputValue(int* pvalue,int enum_type);
+		void       GetInputValue(IssmDouble* pvalue,int enum_type);
+		void       GetInputValue(IssmDouble* pvalue,Gauss* gauss,int enum_type);
+		IssmDouble GetMaterialParameter(int enum_in);
+		void       GetNodesSidList(int* sidlist);
+		void       GetNodesLidList(int* lidlist);
+		void       GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
+		void       GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
+		void	     GetVertexPidList(int* pidlist);
+		void       GetVerticesCoordinates(IssmDouble** xyz_list);
+		void       GetVerticesSidList(int* sidlist);
+		void       GetVerticesConnectivityList(int* connectivitylist);
+		IssmDouble GetXcoord(IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble GetYcoord(IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble GetZcoord(IssmDouble* xyz_list,Gauss* gauss);
+		void       GradientIndexing(int* indexing,int control_index);
+		bool       HasNodeOnBase();
+		bool       HasNodeOnSurface();
+		int        Id();
+		int        Sid();
+		void       InputChangeName(int enum_type,int enum_type_old);
+		void       InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void       InputDuplicate(int original_enum,int new_enum);
+		void       InputUpdateFromConstant(IssmDouble constant, int name);
+		void       InputUpdateFromConstant(int constant, int name);
+		void       InputUpdateFromConstant(bool constant, int name);
+		bool       IsIceInElement();
+		bool	     IsInput(int name);
+		bool       IsFloating(); 
+		void       LinearFloatingiceMeltingRate(); 
+		ElementVector*  NewElementVector(int approximation_enum=NoneApproximationEnum);
+		ElementMatrix*  NewElementMatrix(int approximation_enum=NoneApproximationEnum);
+		ElementMatrix*  NewElementMatrixCoupling(int number_nodes,int approximation_enum=NoneApproximationEnum);
+		IssmDouble PureIceEnthalpy(IssmDouble pressure);
+		void       ResultInterpolation(int* pinterpolation,int*nodesperelement,int output_enum);
+		void       ResultToVector(Vector<IssmDouble>* vector,int output_enum);
+		void       ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum);
+		void       SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
+		void       StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input);
+		void       StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		IssmDouble TMeltingPoint(IssmDouble pressure);
+		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
+		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+		void       TransformLoadVectorCoord(ElementVector* pe,int cs_enum);
+		void       TransformLoadVectorCoord(ElementVector* pe,int* cs_array);
+		void       TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
+		void       TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
+		void       TransformSolutionCoord(IssmDouble* solution,int cs_enum);
+		void       TransformSolutionCoord(IssmDouble* solution,int* cs_array);
+		void       TransformSolutionCoord(IssmDouble* solution,int numnodes,int cs_enum);
+		void       TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array);
+		void       TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum);
+		void       TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array);
+		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
+		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* cs_array);
+		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+		void       ViscousHeatingCreateInput(void);
+		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
+		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       TransformLoadVectorCoord(ElementVector* pe,int numnodes,int transformenum){_error_("not implemented yet");};/*Tiling only*/
+		void       TransformLoadVectorCoord(ElementVector* pe,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
+		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
+
+		/*Virtual functions*/
+		virtual void       AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
+		virtual void       AddInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
+		virtual IssmDouble CharacteristicLength(void)=0;
+		virtual void       Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void   ElementSizes(IssmDouble* phx,IssmDouble* phy,IssmDouble* phz)=0;
+
+		virtual int    FiniteElement(void)=0;
+		virtual IssmDouble MinEdgeLength(IssmDouble* xyz_list)=0;
+		virtual void   NodalFunctions(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void   NodalFunctionsP1(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void   NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss)=0;
+		virtual void   NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss)=0;
+		virtual void   NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss)=0;
+		virtual void   NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   NormalSection(IssmDouble* normal,IssmDouble* xyz_list)=0;
+		virtual void   NormalTop(IssmDouble* normal,IssmDouble* xyz_list)=0;
+		virtual void   NormalBase(IssmDouble* normal,IssmDouble* xyz_list)=0;
+
+		virtual Element* GetUpperElement(void)=0;
+		virtual Element* GetBasalElement(void)=0;
+
+		virtual void   JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   JacobianDeterminantSurface(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   JacobianDeterminantBase(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
+		virtual void   JacobianDeterminantTop(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
+		virtual void   GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int solutionenum)=0;
+		virtual int    GetNodeIndex(Node* node)=0;
+		virtual int    GetNumberOfNodes(void)=0;
+		virtual int    GetNumberOfVertices(void)=0;
+
+		virtual bool   IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
+		virtual bool   IsOnBase()=0;
+		virtual bool   IsOnSurface()=0;
+		virtual void   GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating)=0;
+		virtual IssmDouble GetGroundedPortion(IssmDouble* xyz_list)=0;
+		virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
+		virtual Node*  GetNode(int node_number)=0;
+		virtual void   GetVerticesCoordinatesBase(IssmDouble** xyz_list)=0;
+		virtual void   GetVerticesCoordinatesTop(IssmDouble** xyz_list)=0;
+
+		virtual int    GetElementType(void)=0;
+
+		virtual IssmDouble SurfaceArea(void)=0;
+		virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type)=0;
+		virtual void   ComputeSigmaNN(void)=0;
+		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
+		virtual void   ComputeStressTensor(void)=0;
+		virtual void   ComputeDeviatoricStressTensor(void)=0;
+
+		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
+		virtual void   InputExtrude(int input_enum)=0;
+		virtual void   InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum)=0;
+		virtual void   InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum)=0;
+
+		virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum)=0;
+		virtual int    NumberofNodesVelocity(void)=0;
+		virtual int    NumberofNodesPressure(void)=0;
+		virtual Gauss* NewGauss(void)=0;
+		virtual Gauss* NewGauss(int order)=0;
+      virtual Gauss* NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order)=0;
+      virtual Gauss* NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert)=0;
+      virtual Gauss* NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order)=0;
+		virtual Gauss* NewGaussBase(int order)=0;
+		virtual Gauss* NewGaussLine(int vertex1,int vertex2,int order)=0;
+		virtual Gauss* NewGaussTop(int order)=0;
+
+		virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
+		virtual IssmDouble TimeAdapt()=0;
+		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
+		virtual void   Delta18oParameterization(void)=0;
+	   virtual Element*   SpawnBasalElement(void)=0;
+		virtual Element*   SpawnTopElement(void)=0;
+		virtual void   ReduceMatrices(ElementMatrix* Ke,ElementVector* pe)=0;
+		virtual void   ResetFSBasalBoundaryCondition()=0;
+		virtual void   SetTemporaryElementType(int element_type_in)=0;
+		virtual IssmDouble StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa)=0;
+		virtual void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss)=0;
+		virtual void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void   ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
+
+		virtual int    VelocityInterpolation()=0;
+		virtual int    PressureInterpolation()=0;
+		virtual int    TensorInterpolation()=0;
+		virtual bool   IsZeroLevelset(int levelset_enum)=0;
+		virtual bool   IsIcefront(void)=0;
+		virtual bool   IsFaceOnBoundary(void)=0;
+		virtual void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum)=0;
+		virtual void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum)=0;
+
+		virtual void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
+		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
+		virtual IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id)=0;
+		virtual void   ElementResponse(IssmDouble* presponse,int response_enum)=0;
+		virtual IssmDouble IceVolume(void)=0;
+		virtual IssmDouble IceVolumeAboveFloatation(void)=0;
+		virtual IssmDouble TotalSmb(void)=0;
+		virtual IssmDouble Misfit(int modelenum,int observationenum,int weightsenum)=0;
+		virtual IssmDouble MisfitArea(int weightsenum)=0;
+		virtual int    VertexConnectivity(int vertexindex)=0;
+		virtual void   VerticalSegmentIndices(int** pindices,int* pnumseg)=0;
+
+		#ifdef _HAVE_GIA_
+		virtual void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y)=0;
+		#endif
+
+		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
+		virtual void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
+		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
+		virtual void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
+		virtual void   InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
+
+		virtual void UpdateConstraintsExtrudeFromBase(void)=0;
+		virtual void UpdateConstraintsExtrudeFromTop(void)=0;
+
+		virtual void   MigrateGroundingLine(IssmDouble* sheet_ungrounding)=0;
+		virtual void   FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating)=0;
+		virtual void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding)=0;
+		virtual int    UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.cpp	(revision 18231)
@@ -0,0 +1,138 @@
+/*!\file ElementHook.c
+ * \brief: implementation of the ElementHook object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+ElementHook::ElementHook(){/*{{{*/
+	numanalyses=UNDEF;
+	this->hnodes     = NULL;
+	this->hvertices  = NULL;
+	this->hmaterial  = NULL;
+	this->hmatpar    = NULL;
+	this->hneighbors = NULL;
+}
+/*}}}*/
+ElementHook::~ElementHook(){/*{{{*/
+
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hvertices;
+	delete hmaterial;
+	delete hmatpar;
+	delete hneighbors;
+}
+/*}}}*/
+ElementHook::ElementHook(int in_numanalyses,int element_id,int numvertices,IoModel* iomodel){/*{{{*/
+
+	/*intermediary: */
+	int matpar_id;
+	int material_id;
+
+	/*retrieve material_id: */
+	matpar_id = iomodel->numberofelements+1;
+
+	/*retrieve material_id*/
+	material_id = element_id;
+
+	/*retrieve vertices ids*/
+	int* vertex_ids = xNew<int>(numvertices);
+	for(int i=0;i<numvertices;i++){ 
+		vertex_ids[i]=reCast<int>(iomodel->elements[(element_id-1)*numvertices+i]);
+	}
+
+	this->numanalyses = in_numanalyses;
+	this->hnodes      = new Hook*[in_numanalyses];
+	this->hvertices   = new Hook(&vertex_ids[0],numvertices);
+	this->hmaterial   = new Hook(&material_id,1);
+	this->hmatpar     = new Hook(&matpar_id,1);
+	this->hneighbors  = NULL;
+
+	/*Initialize hnodes as NULL*/
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+	/*Clean up*/
+	xDelete<int>(vertex_ids);
+
+}
+/*}}}*/
+
+void ElementHook::SetHookNodes(int* node_ids,int numnodes,int analysis_counter){/*{{{*/
+	this->hnodes[analysis_counter]= new Hook(node_ids,numnodes);
+}
+/*}}}*/
+void ElementHook::InitHookNeighbors(int* element_ids){/*{{{*/
+	this->hneighbors=new Hook(element_ids,2);
+}
+/*}}}*/
+void ElementHook::SpawnTriaHook(ElementHook* triahook,int index1,int index2,int index3){/*{{{*/
+
+	/*Create arrow of indices depending on location (0=base 1=surface)*/
+	int indices[3];
+	indices[0] = index1;
+	indices[1] = index2;
+	indices[2] = index3;
+
+	triahook->numanalyses=this->numanalyses;
+
+	/*Spawn nodes hook*/
+	triahook->hnodes=new Hook*[this->numanalyses];
+	for(int i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,3);
+		}
+	}
+
+	/*do not spawn hmaterial. material will be taken care of by Penta*/
+	triahook->hmaterial=NULL;
+	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,3);
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
+void ElementHook::SpawnSegHook(ElementHook* triahook,int index1,int index2){/*{{{*/
+
+	triahook->numanalyses=this->numanalyses;
+
+	int indices[2];
+	indices[0]=index1;
+	indices[1]=index2;
+
+	/*Spawn nodes hook*/
+	triahook->hnodes=new Hook*[this->numanalyses];
+	for(int i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,2);
+		}
+	}
+
+	/*do not spawn hmaterial. material will be taken care of by Tria*/
+	triahook->hmaterial=NULL;
+	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,2);
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/ElementHook.h	(revision 18231)
@@ -0,0 +1,32 @@
+/*!\file: ElementHook.h
+ * \brief prototypes for ElementHook.h
+ */ 
+
+#ifndef _ELEMENTHOOK_H_
+#define _ELEMENTHOOK_H_
+
+class Hook;
+class IoModel;
+
+class ElementHook{
+
+	public: 
+		int    numanalyses;   //number of analysis types
+		Hook **hnodes;        // set of nodes for each analysis type
+		Hook  *hvertices;     // vertices
+		Hook  *hmaterial;     // 1 ice material
+		Hook  *hmatpar;       // 1 material parameter
+		Hook  *hneighbors;    // 2 elements, first down, second up in 3d only
+
+		/*constructors, destructors*/
+		ElementHook();
+		ElementHook(int in_numanalyses,int material_id,int numvertices,IoModel* iomodel);
+		~ElementHook();
+
+		void SetHookNodes(int* node_ids,int numnodes,int analysis_counter);
+		void SpawnTriaHook(ElementHook* triahook,int index1,int index2,int index3); //3d only
+		void SpawnSegHook(ElementHook* triahook,int ndex1,int index2); //2d only
+		void InitHookNeighbors(int* element_ids);               //3d only
+};
+
+#endif //ifndef _ELEMENTHOOK_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.cpp	(revision 18231)
@@ -0,0 +1,103 @@
+/*
+ * \file Elements.cpp
+ * \brief: Implementation of Elements class, derived from DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Element.h"
+#include "./Elements.h"
+#include "../Params/Parameters.h"
+#include "../ExternalResults/Results.h"
+#include "../ExternalResults/GenericExternalResult.h"
+#include "../../toolkits/toolkits.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Elements::Elements(){/*{{{*/
+	enum_type=MeshElementsEnum;
+	return;
+}
+/*}}}*/
+Elements::~Elements(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+void Elements::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Element* element=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		element=dynamic_cast<Element*>((*object));
+		element->Configure(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+void Elements::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Element* element=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		element=dynamic_cast<Element*>((*object));
+		element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+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: */
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+
+	return max;
+}
+/*}}}*/
+int  Elements::NumberOfElements(void){/*{{{*/
+
+	int local_nelem;
+	int numberofelements;
+
+	local_nelem=this->Size();
+	ISSM_MPI_Allreduce((void*)&local_nelem,(void*)&numberofelements,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+
+	return numberofelements;
+}
+/*}}}*/
+void Elements::InputDuplicate(int input_enum,int output_enum){/*{{{*/
+
+	for(int i=0;i<this->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		element->InputDuplicate(input_enum,output_enum);
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Elements.h	(revision 18231)
@@ -0,0 +1,34 @@
+#ifndef _CONTAINER_ELEMENTS_H_
+#define  _CONTAINER_ELEMENTS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Materials;
+class Parameters;
+class Vertices;
+class Loads;
+class Nodes;
+class Results;
+
+/*! \brief Declaration of Elements class 
+ *
+ * Declaration of Elements class.  Elements are vector lists (Containers) of Element objects.
+ */ 
+class Elements: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Elements();
+		~Elements();
+
+		/*numerics*/
+		void   Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		int    MaxNumNodes(void);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		int    NumberOfElements(void);
+		void   InputDuplicate(int input_enum,int output_enum);
+
+};
+
+#endif //ifndef _ELEMENTS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.cpp	(revision 18231)
@@ -0,0 +1,3183 @@
+/*!\file Penta.cpp
+ * \brief: implementation of the Penta object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   6
+#define NUMVERTICES2D 3
+
+/*Constructors/destructor/copy*/
+Penta::~Penta(){/*{{{*/
+	this->parameters=NULL;
+}
+/*}}}*/
+Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
+	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+
+	int penta_elements_ids[2];
+
+	/*Checks in debugging mode*/
+	_assert_(iomodel->Data(MeshUpperelementsEnum));
+	_assert_(iomodel->Data(MeshLowerelementsEnum));
+
+	/*id: */
+	this->id  = penta_id;
+	this->sid = penta_sid;
+
+	/*Build neighbors list*/
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshUpperelementsEnum)[index]) || iomodel->Data(MeshUpperelementsEnum)[index]==-1.) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data(MeshUpperelementsEnum)[index]));
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshLowerelementsEnum)[index]) || iomodel->Data(MeshLowerelementsEnum)[index]==-1.) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data(MeshLowerelementsEnum)[index]));
+	this->InitHookNeighbors(penta_elements_ids);
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+
+	/*intialize inputs: */
+	this->inputs=new Inputs();
+
+	/*initialize pointers:*/
+	this->nodes             = NULL;
+	this->vertices          = NULL;
+	this->material          = NULL;
+	this->matpar            = NULL;
+	this->verticalneighbors = NULL;
+
+	/*Only allocate pointer*/
+	this->element_type_list=xNew<int>(nummodels);
+}
+/*}}}*/
+Object* Penta::copy() {/*{{{*/
+
+	int i;
+
+	Penta* penta=NULL;
+
+	penta=new Penta();
+
+	//deal with PentaRef mother class
+	penta->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) penta->element_type_list[i]=this->element_type_list[i];
+
+	//deal with ElementHook
+	penta->numanalyses=this->numanalyses;
+	penta->hnodes=new Hook*[penta->numanalyses];
+	for(i=0;i<penta->numanalyses;i++)penta->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	penta->hvertices=(Hook*)this->hvertices->copy();
+	penta->hmaterial=(Hook*)this->hmaterial->copy();
+	penta->hmatpar=(Hook*)this->hmatpar->copy();
+	penta->hneighbors=(Hook*)this->hneighbors->copy();
+
+	/*deal with Penta  copy fields: */
+	penta->id=this->id;
+	penta->sid=this->sid;
+	if(this->inputs){
+		penta->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		penta->inputs=new Inputs();
+	}
+	/*point parameters: */
+	penta->parameters=this->parameters;
+
+	/*recover objects: */
+	penta->nodes=xNew<Node*>(6); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<6;i++)penta->nodes[i]=this->nodes[i];
+	penta->vertices=(Vertex**)penta->hvertices->deliverp();
+	penta->material=(Material*)penta->hmaterial->delivers();
+	penta->matpar=(Matpar*)penta->hmatpar->delivers();
+	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
+
+	return penta;
+}
+/*}}}*/
+
+/*Other*/
+void       Penta::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	_assert_(this->inputs);
+	this->inputs->AddInput(new PentaInput(input_enum,values,interpolation_enum));
+}
+/*}}}*/
+void       Penta::AddBasalInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	_assert_(this->inputs);
+	if(!IsOnBase()) return;
+	else{
+		if(interpolation_enum==P1Enum){
+			int        i;
+			IssmDouble extrudedvalues[NUMVERTICES];
+			Penta*     penta=NULL;
+
+			for(i=0;i<NUMVERTICES2D;i++){
+				extrudedvalues[i]=values[i];
+				extrudedvalues[i+NUMVERTICES2D]=values[i];
+			}
+			penta=this;
+			for(;;){
+				penta->inputs->AddInput(new PentaInput(input_enum,&extrudedvalues[0],P1Enum));
+				if (penta->IsOnSurface()) break;
+				penta=penta->GetUpperPenta(); _assert_(penta->Id()!=this->id);
+			}
+		}
+		else _error_("not implemented yet");
+	}
+}
+/*}}}*/
+void       Penta::ComputeBasalStress(Vector<IssmDouble>* sigma_b){/*{{{*/
+
+	int         i,j;
+	int         dofv[3]={0,1,2};
+	int         dofp[1]={3};
+	int         analysis_type,approximation;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[3][3];
+	IssmDouble  rho_ice,gravity,FSreconditioning;
+	IssmDouble  pressure,viscosity,Jdet2d;
+	IssmDouble  bed_normal[3];
+	IssmDouble  basalforce[3] = {0.};
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  stresstensor[6]={0.0};
+	IssmDouble  sigma_xx,sigma_yy,sigma_zz;
+	IssmDouble  sigma_xy,sigma_xz,sigma_yz;
+	IssmDouble  surface=0,value=0;
+	GaussPenta* gauss;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Check analysis_types*/
+	if (analysis_type!=StressbalanceAnalysisEnum) _error_("Not supported yet!");
+	if (approximation!=FSApproximationEnum) _error_("Not supported yet!");
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	if(!IsOnBase()){
+		//put zero
+		sigma_b->SetValue(id-1,0.0,INS_VAL);
+		return;
+	}
+
+	/*recovre material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(i=0;i<3;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx=2*viscosity*epsilon[0]-pressure*FSreconditioning; // sigma = nu eps - pressure
+		sigma_yy=2*viscosity*epsilon[1]-pressure*FSreconditioning;
+		sigma_zz=2*viscosity*epsilon[2]-pressure*FSreconditioning;
+		sigma_xy=2*viscosity*epsilon[3];
+		sigma_xz=2*viscosity*epsilon[4];
+		sigma_yz=2*viscosity*epsilon[5];
+
+		/*Get normal vector to the bed */
+		NormalBase(&bed_normal[0],&xyz_list_tria[0][0]);
+
+		/*basalforce*/
+		basalforce[0] += sigma_xx*bed_normal[0] + sigma_xy*bed_normal[1] + sigma_xz*bed_normal[2];
+		basalforce[1] += sigma_xy*bed_normal[0] + sigma_yy*bed_normal[1] + sigma_yz*bed_normal[2];
+		basalforce[2] += sigma_xz*bed_normal[0] + sigma_yz*bed_normal[1] + sigma_zz*bed_normal[2];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		value+=sigma_zz*Jdet2d*gauss->weight;
+		surface+=Jdet2d*gauss->weight;
+	}
+	value=value/surface;
+
+	/*Add value to output*/
+	sigma_b->SetValue(id-1,value,INS_VAL);
+}
+/*}}}*/
+void       Penta::ComputeStressTensor(){/*{{{*/
+
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      pressure,viscosity;
+	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble      sigma_xx[NUMVERTICES];
+	IssmDouble		sigma_yy[NUMVERTICES];
+	IssmDouble		sigma_zz[NUMVERTICES];
+	IssmDouble      sigma_xy[NUMVERTICES];
+	IssmDouble		sigma_xz[NUMVERTICES];
+	IssmDouble		sigma_yz[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_zz[iv]=2*viscosity*epsilon[2]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[3];
+		sigma_xz[iv]=2*viscosity*epsilon[4];
+		sigma_yz[iv]=2*viscosity*epsilon[5];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new PentaInput(StressTensorxxEnum,&sigma_xx[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxyEnum,&sigma_xy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxzEnum,&sigma_xz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryyEnum,&sigma_yy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryzEnum,&sigma_yz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorzzEnum,&sigma_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+void       Penta::ComputeDeviatoricStressTensor(){/*{{{*/
+
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      viscosity;
+	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble      tau_xx[NUMVERTICES];
+	IssmDouble		tau_yy[NUMVERTICES];
+	IssmDouble		tau_zz[NUMVERTICES];
+	IssmDouble      tau_xy[NUMVERTICES];
+	IssmDouble		tau_xz[NUMVERTICES];
+	IssmDouble		tau_yz[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+
+		/*Compute Stress*/
+		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps 
+		tau_yy[iv]=2*viscosity*epsilon[1];
+		tau_zz[iv]=2*viscosity*epsilon[2];
+		tau_xy[iv]=2*viscosity*epsilon[3];
+		tau_xz[iv]=2*viscosity*epsilon[4];
+		tau_yz[iv]=2*viscosity*epsilon[5];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new PentaInput(StressTensorxxEnum,&tau_xx[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxyEnum,&tau_xy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxzEnum,&tau_xz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryyEnum,&tau_yy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryzEnum,&tau_yz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorzzEnum,&tau_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+void       Penta::Configure(Elements* elementsin, Loads* loadsin, Nodes* nodesin,Vertices* verticesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	if (this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hvertices->configure(verticesin);
+	this->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+	this->hneighbors->configure(elementsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->vertices          = (Vertex**)this->hvertices->deliverp();
+	this->material          = (Material*)this->hmaterial->delivers();
+	this->matpar            = (Matpar*)this->hmatpar->delivers();
+	this->verticalneighbors = (Penta**)this->hneighbors->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+}
+/*}}}*/
+void       Penta::Delta18oParameterization(void){/*{{{*/
+
+	/*Are we on the base? If not, return*/
+	if(!IsOnBase()) return;
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input*     input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input*     input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input*     input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussPenta* gauss=new GaussPenta();
+	for(int month=0;month<12;month++) {
+		for(int iv=0;iv<NUMVERTICES;iv++) {
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		PentaInput* newmonthinput1 = new PentaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		PentaInput* newmonthinput2 = new PentaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum);
+	this->InputExtrude(SurfaceforcingsPrecipitationEnum);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+int        Penta::FiniteElement(void){/*{{{*/
+	return this->element_type;
+}
+/*}}}*/
+void       Penta::FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){/*{{{*/
+
+	if(!IsOnBase()) return;
+
+	/*Intermediaries*/
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
+	IssmDouble  bed_normal[3];
+	IssmDouble  epsilon[6]; /* epsilon=[exx eyy ezz exy exz eyz];*/
+	IssmDouble  surface=0,value=0;
+	bool grounded;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+	Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vz_input       = inputs->GetInput(VzEnum);       _assert_(vz_input);
+
+	/*Create gauss point in the middle of the basal edge*/
+	Gauss* gauss=NewGaussBase(1);
+	gauss->GaussPoint(0);
+
+	if(!IsFloating()){ 
+		/*Check for basal force only if grounded and touching GL*/
+		if(this->inputs->Min(MaskGroundediceLevelsetEnum)==0.){
+			this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+			this->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
+			pressure_input->GetInputValue(&pressure, gauss);
+			base_input->GetInputValue(&base, gauss); _assert_(base<0.);
+
+			/*Compute Stress*/
+			IssmDouble sigma_xx=2.*viscosity*epsilon[0]-pressure;
+			IssmDouble sigma_yy=2.*viscosity*epsilon[1]-pressure;
+			IssmDouble sigma_zz=2.*viscosity*epsilon[2]-pressure;
+			IssmDouble sigma_xy=2.*viscosity*epsilon[3];
+			IssmDouble sigma_xz=2.*viscosity*epsilon[4];
+			IssmDouble sigma_yz=2.*viscosity*epsilon[5];
+
+			/*Get normal vector to the bed */
+			NormalBase(&bed_normal[0],xyz_list);
+
+			/*basalforce*/
+			sigma_nn = sigma_xx*bed_normal[0]*bed_normal[0] + sigma_yy*bed_normal[1]*bed_normal[1] + sigma_zz*bed_normal[2]*bed_normal[2] 
+			  + 2.*sigma_xy*bed_normal[0]*bed_normal[1] + 2.*sigma_xz*bed_normal[0]*bed_normal[2] + 2.*sigma_yz*bed_normal[1]*bed_normal[2];
+
+			/*Compute water pressure*/
+			IssmDouble rho_ice   = matpar->GetRhoIce();
+			IssmDouble rho_water = matpar->GetRhoWater();
+			IssmDouble gravity   = matpar->GetG();
+			water_pressure=gravity*rho_water*base;
+
+			/*Compare basal stress to water pressure and determine whether it should ground*/
+			if (sigma_nn<water_pressure) grounded=true;
+			else                         grounded=false;
+		}
+		else{
+			grounded=true;
+		}
+	}
+	else{
+		/*Check for basal elevation if floating*/
+		base_input->GetInputValue(&base, gauss);
+		bed_input->GetInputValue(&bed, gauss);
+		if (base<bed) grounded=true;
+		else          grounded=false;
+	}
+	for(int i=0;i<NUMVERTICES;i++){
+		if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+		else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+	}
+
+	/*clean up*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+}
+/*}}}*/
+int        Penta::ObjectEnum(void){/*{{{*/
+
+	return PentaEnum;
+
+}
+/*}}}*/
+void       Penta::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	int         i,j,k;
+	IssmDouble  area_init,area_portion;
+	IssmDouble  xyz_bis[3][3];
+
+	area_init=fabs(xyz_list[1*3+0]*xyz_list[2*3+1] - xyz_list[1*3+1]*xyz_list[2*3+0] + xyz_list[0*3+0]*xyz_list[1*3+1] - xyz_list[0*3+1]*xyz_list[1*3+0] + xyz_list[2*3+0]*xyz_list[0*3+1] - xyz_list[2*3+1]*xyz_list[0*3+0])/2.;
+
+	/*Initialize xyz_list with original xyz_list of triangle coordinates*/
+	for(j=0;j<3;j++){ 
+		for(k=0;k<3;k++){
+			xyz_bis[j][k]=xyz_list[j*3+k];
+		}
+	}
+	for(i=0;i<numpoints;i++){
+		for(j=0;j<3;j++){ 
+			for(k=0;k<3;k++){
+				/*Change appropriate line*/
+				xyz_bis[j][k]=xyz_zero[i*3+k];
+			}
+
+			/*Compute area fraction*/
+			area_portion=fabs(xyz_bis[1][0]*xyz_bis[2][1] - xyz_bis[1][1]*xyz_bis[2][0] + xyz_bis[0][0]*xyz_bis[1][1] - xyz_bis[0][1]*xyz_bis[1][0] + xyz_bis[2][0]*xyz_bis[0][1] - xyz_bis[2][1]*xyz_bis[0][0])/2.;
+			*(area_coordinates+3*i+j)=area_portion/area_init;
+
+			/*Reinitialize xyz_list*/
+			for(k=0;k<3;k++){
+				/*Reinitialize xyz_list with original coordinates*/
+				xyz_bis[j][k]=xyz_list[j*3+k];
+			}
+		}
+	}
+}
+/*}}}*/
+Penta*     Penta::GetUpperPenta(void){/*{{{*/
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[1]; //first one (0) under, second one (1) above
+
+	return upper_penta;
+}
+/*}}}*/
+Penta*     Penta::GetLowerPenta(void){/*{{{*/
+
+	Penta* lower_penta=NULL;
+
+	lower_penta=(Penta*)verticalneighbors[0]; //first one (0) under, second one (1) above
+
+	return lower_penta;
+}
+/*}}}*/
+Penta*     Penta::GetSurfacePenta(void){/*{{{*/
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all pentas till the surface is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take upper penta*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperPenta();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+Penta*     Penta::GetBasalPenta(void){/*{{{*/
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all pentas till the bed is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take lower penta*/
+		if (penta->IsOnBase()) break;
+
+		/* get lower Penta*/
+		penta=penta->GetLowerPenta();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+Element*   Penta::GetUpperElement(void){/*{{{*/
+
+	/*Output*/
+	Element* upper_element=this->GetUpperPenta();
+	return upper_element;
+}
+/*}}}*/
+Element*   Penta::GetBasalElement(void){/*{{{*/
+
+	/*Output*/
+	Element* element=this->GetBasalPenta();
+	return element;
+}
+/*}}}*/
+void       Penta::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               floating=true;
+	int                point;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         f1,f2;
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are grounded or floating*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+		point=0;
+		f1=1.;
+		f2=1.;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		point=0;
+		f1=0.;
+		f2=0.;
+	}
+	else{
+		if(gl[0]*gl[1]*gl[2]<0) floating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			point=2;
+			f1=gl[2]/(gl[2]-gl[0]);
+			f2=gl[2]/(gl[2]-gl[1]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			point=0;
+			f1=gl[0]/(gl[0]-gl[1]);
+			f2=gl[0]/(gl[0]-gl[2]);
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			point=1;
+			f1=gl[1]/(gl[1]-gl[2]);
+			f2=gl[1]/(gl[1]-gl[0]);
+		}
+	}
+	*point1=point;
+	*fraction1=f1;
+	*fraction2=f2;
+	*mainlyfloating=floating;
+}
+/*}}}*/
+IssmDouble Penta::GetGroundedPortion(IssmDouble* xyz_list){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               mainlyfloating = true;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         phi,s1,s2,area_init,area_grounded;
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         xyz_bis[NUMVERTICES2D][3];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are grounded or floating*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+		phi=1;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		phi=0;
+	}
+	else{
+		/*Figure out if two nodes are floating or grounded*/
+		if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			/*Coordinates of point 2: same as initial point 2*/
+			xyz_bis[2][0]=xyz_list[3*2+0];
+			xyz_bis[2][1]=xyz_list[3*2+1];
+			xyz_bis[2][2]=xyz_list[3*2+2];
+
+			/*Portion of the segments*/
+			s1=gl[2]/(gl[2]-gl[1]);
+			s2=gl[2]/(gl[2]-gl[0]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=xyz_list[3*2+0]+s1*(xyz_list[3*1+0]-xyz_list[3*2+0]);
+			xyz_bis[1][1]=xyz_list[3*2+1]+s1*(xyz_list[3*1+1]-xyz_list[3*2+1]);
+			xyz_bis[1][2]=xyz_list[3*2+2]+s1*(xyz_list[3*1+2]-xyz_list[3*2+2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=xyz_list[3*2+0]+s2*(xyz_list[3*0+0]-xyz_list[3*2+0]);
+			xyz_bis[0][1]=xyz_list[3*2+1]+s2*(xyz_list[3*0+1]-xyz_list[3*2+1]);
+			xyz_bis[0][2]=xyz_list[3*2+2]+s2*(xyz_list[3*0+2]-xyz_list[3*2+2]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			/*Coordinates of point 0: same as initial point 2*/
+			xyz_bis[0][0]=*(xyz_list+3*0+0);
+			xyz_bis[0][1]=*(xyz_list+3*0+1);
+			xyz_bis[0][2]=*(xyz_list+3*0+2);
+
+			/*Portion of the segments*/
+			s1=gl[0]/(gl[0]-gl[1]);
+			s2=gl[0]/(gl[0]-gl[2]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
+			xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
+			xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
+			xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
+			xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			/*Coordinates of point 1: same as initial point 2*/
+			xyz_bis[1][0]=*(xyz_list+3*1+0);
+			xyz_bis[1][1]=*(xyz_list+3*1+1);
+			xyz_bis[1][2]=*(xyz_list+3*1+2);
+
+			/*Portion of the segments*/
+			s1=gl[1]/(gl[1]-gl[0]);
+			s2=gl[1]/(gl[1]-gl[2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
+			xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
+			xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
+			xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
+			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
+		}
+
+		/*Compute fraction of grounded element*/
+		GetTriaJacobianDeterminant(&area_init, xyz_list,NULL);
+		GetTriaJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+		if(mainlyfloating==true) area_grounded=area_init-area_grounded;
+		phi=area_grounded/area_init;
+	}
+
+	if(phi>1. || phi<0.) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
+int        Penta::GetElementType(){/*{{{*/
+
+	/*return PentaRef field*/
+	return this->element_type;
+}
+/*}}}*/
+void       Penta::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xmin,ymin,zmin;
+	IssmDouble xmax,ymax,zmax;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=zmax-zmin;
+}
+/*}}}*/
+int        Penta::GetNodeIndex(Node* node){/*{{{*/
+
+	_assert_(nodes);
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	for(int i=0;i<numnodes;i++){
+		if(node==nodes[i]) return i;
+	}
+	_error_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+int        Penta::GetNumberOfNodes(void){/*{{{*/
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int        Penta::GetNumberOfVertices(void){/*{{{*/
+	return NUMVERTICES; 
+}
+/*}}}*/
+Node*      Penta::GetNode(int node_number){/*{{{*/
+	_assert_(node_number>=0); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
+	return this->nodes[node_number];
+}
+/*}}}*/
+void       Penta::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+void       Penta::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
+
+	IssmDouble* xyz_list = xNew<IssmDouble>(NUMVERTICES2D*3);
+	::GetVerticesCoordinates(xyz_list,this->vertices,NUMVERTICES2D);
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list;
+
+}/*}}}*/
+void       Penta::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){/*{{{*/
+
+	IssmDouble* xyz_list = xNew<IssmDouble>(NUMVERTICES2D*3);
+	::GetVerticesCoordinates(xyz_list,&this->vertices[3],NUMVERTICES2D);
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list;
+
+}/*}}}*/
+void       Penta::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble AB[3];
+	IssmDouble AC[3];
+	IssmDouble norm;
+
+	AB[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	AB[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+	AB[2]=xyz_list[1*3+2] - xyz_list[0*3+2];
+	AC[0]=xyz_list[2*3+0] - xyz_list[0*3+0];
+	AC[1]=xyz_list[2*3+1] - xyz_list[0*3+1];
+	AC[2]=xyz_list[2*3+2] - xyz_list[0*3+2];
+
+	cross(normal,AB,AC);
+	norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
+
+	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
+}
+/*}}}*/
+IssmDouble Penta::StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){/*{{{*/
+	/*Compute stabilization parameter*/
+	/*kappa=thermalconductivity/(rho_ice*hearcapacity) for thermal model*/
+	/*kappa=enthalpydiffusionparameter for enthalpy model*/
+
+	IssmDouble normu;
+	IssmDouble tau_parameter;
+
+	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
+	if(normu*diameter/(3*2*kappa)<1){ 
+		tau_parameter=pow(diameter,2)/(3*2*2*kappa);
+	}
+	else tau_parameter=diameter/(2*normu);
+
+	return tau_parameter;
+}
+/*}}}*/
+void       Penta::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	/*Compute portion of the element that is grounded*/ 
+
+	int         normal_orientation=0;
+	IssmDouble  s1,s2;
+	IssmDouble  levelset[NUMVERTICES];
+	IssmDouble* xyz_zero = xNew<IssmDouble>(4*3);
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[2]/(levelset[2]-levelset[1]);
+		s2=levelset[2]/(levelset[2]-levelset[0]);
+
+		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle at base and top, depending on distribution of levelsetfunction
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);
+
+		/*New point 0*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[5*3+0]+s1*(xyz_list[4*3+0]-xyz_list[5*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[5*3+1]+s1*(xyz_list[4*3+1]-xyz_list[5*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[5*3+2]+s1*(xyz_list[4*3+2]-xyz_list[5*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[5*3+0]+s2*(xyz_list[3*3+0]-xyz_list[5*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[5*3+1]+s2*(xyz_list[3*3+1]-xyz_list[5*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[5*3+2]+s2*(xyz_list[3*3+2]-xyz_list[5*3+2]);
+	}
+	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+		/*Portion of the segments*/
+		s1=levelset[0]/(levelset[0]-levelset[2]);
+		s2=levelset[0]/(levelset[0]-levelset[1]);
+
+		if(levelset[0]<0.) normal_orientation=1;
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[3*3+0]+s1*(xyz_list[5*3+0]-xyz_list[3*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[3*3+1]+s1*(xyz_list[5*3+1]-xyz_list[3*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[3*3+2]+s1*(xyz_list[5*3+2]-xyz_list[3*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[3*3+0]+s2*(xyz_list[4*3+0]-xyz_list[3*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[3*3+1]+s2*(xyz_list[4*3+1]-xyz_list[3*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[3*3+2]+s2*(xyz_list[4*3+2]-xyz_list[3*3+2]);
+	}
+	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[1]/(levelset[1]-levelset[0]);
+		s2=levelset[1]/(levelset[1]-levelset[2]);
+
+		if(levelset[1]<0.) normal_orientation=1;
+		/*New point 0*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[4*3+0]+s1*(xyz_list[3*3+0]-xyz_list[4*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[4*3+1]+s1*(xyz_list[3*3+1]-xyz_list[4*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[4*3+2]+s1*(xyz_list[3*3+2]-xyz_list[4*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[4*3+0]+s2*(xyz_list[5*3+0]-xyz_list[4*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[4*3+1]+s2*(xyz_list[5*3+1]-xyz_list[4*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[4*3+2]+s2*(xyz_list[5*3+2]-xyz_list[4*3+2]);
+	}
+	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[0*3+0];
+		xyz_zero[3*0+1]=xyz_list[0*3+1];
+		xyz_zero[3*0+2]=xyz_list[0*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1*3+0];
+		xyz_zero[3*1+1]=xyz_list[1*3+1];
+		xyz_zero[3*1+2]=xyz_list[1*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[4*3+0];
+		xyz_zero[3*2+1]=xyz_list[4*3+1];
+		xyz_zero[3*2+2]=xyz_list[4*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[3*3+0];
+		xyz_zero[3*3+1]=xyz_list[3*3+1];
+		xyz_zero[3*3+2]=xyz_list[3*3+2];
+	}
+	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[2*3+0];
+		xyz_zero[3*0+1]=xyz_list[2*3+1];
+		xyz_zero[3*0+2]=xyz_list[2*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0*3+0];
+		xyz_zero[3*1+1]=xyz_list[0*3+1];
+		xyz_zero[3*1+2]=xyz_list[0*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3*3+0];
+		xyz_zero[3*2+1]=xyz_list[3*3+1];
+		xyz_zero[3*2+2]=xyz_list[3*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[5*3+0];
+		xyz_zero[3*3+1]=xyz_list[5*3+1];
+		xyz_zero[3*3+2]=xyz_list[5*3+2];
+	}
+	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[1*3+0];
+		xyz_zero[3*0+1]=xyz_list[1*3+1];
+		xyz_zero[3*0+2]=xyz_list[1*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2*3+0];
+		xyz_zero[3*1+1]=xyz_list[2*3+1];
+		xyz_zero[3*1+2]=xyz_list[2*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[5*3+0];
+		xyz_zero[3*2+1]=xyz_list[5*3+1];
+		xyz_zero[3*2+2]=xyz_list[5*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[4*3+0];
+		xyz_zero[3*3+1]=xyz_list[4*3+1];
+		xyz_zero[3*3+2]=xyz_list[4*3+2];
+	}
+	else _error_("Case not covered");
+
+	/*Assign output pointer*/
+	*pxyz_zero= xyz_zero;
+}
+/*}}}*/
+void       Penta::InputDepthAverageAtBase(int enum_type,int average_enum_type){/*{{{*/
+
+	int  step,i;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  Helem_list[NUMVERTICES];
+	IssmDouble  zeros_list[NUMVERTICES]={0.0};
+	IssmDouble  p0top1_list[NUMVERTICES];
+	Penta* penta=NULL;
+	Input* original_input=NULL;
+	Input* element_integrated_input=NULL;
+	Input* total_integrated_input=NULL;
+	Input* element_thickness_input=NULL;
+	Input* total_thickness_input=NULL;
+	Input* depth_averaged_input=NULL;
+
+	/*recover parameters: */
+
+	/*Are we on the base? If not, return*/
+	if(!IsOnBase()) return;
+
+	/*OK, we are on bed. Initialize global inputs as 0*/
+	total_thickness_input =new PentaInput(ThicknessEnum,zeros_list,P1Enum);
+
+	/*Now follow all the upper element from the base to the surface to integrate the input*/
+	penta=this;
+	step =0;
+	for(;;){
+
+		/*Step1: Get original input (to be depth avegaged): */
+		original_input=(Input*)penta->inputs->GetInput(enum_type);
+		if(!original_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
+
+		/*If first time, initialize total_integrated_input*/
+		if (step==0){
+			if (original_input->ObjectEnum()==PentaInputEnum)
+			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
+			else if (original_input->ObjectEnum()==ControlInputEnum)
+			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
+			else if (original_input->ObjectEnum()==DoubleInputEnum)
+			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
+			else{
+			 _error_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+			}
+		}
+
+		/*Step2: Create element thickness input*/
+		::GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
+		for(i=0;i<3;i++){
+			Helem_list[i]=xyz_list[i+3][2]-xyz_list[i][2];
+			Helem_list[i+3]=Helem_list[i];
+		}
+		element_thickness_input=new PentaInput(ThicknessEnum,Helem_list,P1Enum);
+
+		/*Step3: Vertically integrate A COPY of the original*/
+		if(original_input->ObjectEnum()==PentaInputEnum){
+			if(((PentaInput*)original_input)->interpolation_type==P0Enum){
+				original_input->GetInputValue(&p0top1_list[i]);
+				element_integrated_input= new  PentaInput(original_input->InstanceEnum(),p0top1_list,P1Enum);
+				element_integrated_input->VerticallyIntegrate(element_thickness_input);
+			}
+			else{
+				element_integrated_input= (Input*)original_input->copy();
+				element_integrated_input->VerticallyIntegrate(element_thickness_input);
+			}
+		}
+		else{
+			element_integrated_input= (Input*)original_input->copy();
+			element_integrated_input->VerticallyIntegrate(element_thickness_input);
+		}
+
+		/*Add contributions to global inputs*/
+		total_integrated_input->AXPY(element_integrated_input,1.0);
+		total_thickness_input ->AXPY(element_thickness_input,1.0);
+
+		/*Clean up*/
+		delete element_thickness_input;
+		delete element_integrated_input;
+
+		/*Stop if we have reached the surface, else, take upper penta*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperPenta();
+		_assert_(penta->Id()!=this->id);
+
+		/*increase couter*/
+		step++;
+	}
+
+	/*OK, now we only need to divide the depth integrated input by the total thickness!*/
+	depth_averaged_input=total_integrated_input->PointwiseDivide(total_thickness_input);
+	depth_averaged_input->ChangeEnum(average_enum_type);
+
+	/*Clean up*/
+	delete total_thickness_input;
+	delete total_integrated_input;
+
+	/*Finally, add to inputs*/
+	this->inputs->AddInput((Input*)depth_averaged_input);
+}
+/*}}}*/
+void       Penta::InputExtrude(int enum_type){/*{{{*/
+
+	/*Are we on the base, not on the surface?:*/
+	if(!IsOnBase()) return;
+
+	/*Step1: Get and Extrude original input: */
+	Input* base_input=(Input*)this->inputs->GetInput(enum_type);
+	if(!base_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
+	base_input->Extrude();
+
+	/*Stop if there is only one layer of element*/
+	if(this->IsOnSurface()) return;
+
+	/*Step 2: this input has been extruded for this element, now follow the upper element*/
+	Penta* penta=this;
+	for(;;){
+		/* get upper Penta*/
+		penta=penta->GetUpperPenta();
+		_assert_(penta->Id()!=this->id);
+
+		/*Add input of the basal element to penta->inputs*/
+		Input* copy=(Input*)base_input->copy();
+		penta->inputs->AddInput((Input*)copy);
+
+		/*Stop if we have reached the surface*/
+		if(penta->IsOnSurface()) break;
+	}
+}
+/*}}}*/
+void       Penta::InputScale(int enum_type,IssmDouble scale_factor){/*{{{*/
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+void       Penta::InputUpdateFromIoModel(int index,IoModel* iomodel){ /*{{{*/
+
+	/*Intermediaries*/
+	int         i,j;
+	int         penta_vertex_ids[NUMVERTICES];
+	IssmDouble  nodeinputs[NUMVERTICES];
+	IssmDouble  cmmininputs[NUMVERTICES];
+	IssmDouble  cmmaxinputs[NUMVERTICES];
+
+	IssmDouble  yts;
+	bool    control_analysis;
+	int     num_control_type,num_responses;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	_assert_(iomodel->elements);
+	for(i=0;i<NUMVERTICES;i++){ 
+		penta_vertex_ids[i]=iomodel->elements[NUMVERTICES*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			int control = reCast<int>(iomodel->Data(InversionControlParametersEnum)[i]);
+			switch(control){
+				/*yts conversion*/
+				case BalancethicknessThickeningRateEnum:
+				case VxEnum:
+				case VyEnum:
+					if(iomodel->Data(control)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[penta_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(control,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+
+				/*No yts conversion*/
+				case ThicknessEnum:
+				case FrictionCoefficientEnum:
+					if(iomodel->Data(control)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[penta_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(control,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+
+				/*Special cases (depth averaged quantities)*/
+				case MaterialsRheologyBbarEnum:
+					if(iomodel->Data(MaterialsRheologyBEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[penta_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case DamageDbarEnum:
+					if(iomodel->Data(DamageDEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(DamageDEnum)[penta_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(DamageDEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				default:
+					_error_("Control " << EnumToStringx(control) << " not implemented yet");
+			}
+		}
+	}
+
+	/*Need to know the type of approximation for this element*/
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
+	}
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)) {
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_responses;i++){
+			for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(penta_vertex_ids[j]-1)*num_responses+i];
+			datasetinput->AddInput(new PentaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+void       Penta::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){/*{{{*/
+
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new PentaInput(enum_type,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}
+/*}}}*/
+void       Penta::InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int enum_type){/*{{{*/
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	IssmDouble  values[numdof];
+	int*    doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*If not on bed, return*/
+	if (!IsOnBase()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	for(int i=0;i<numdof2d;i++){
+		values[i]         =solution[doflist[i]];
+		values[i+numdof2d]=values[i];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaInput(enum_type,values,P1Enum));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperPenta(); _assert_(penta->Id()!=this->id);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+void       Penta::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+
+	const int   numdof         = NDOF1 *NUMVERTICES;
+	int        *doflist        = NULL;
+	IssmDouble  values[numdof];
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+		case VertexPIdEnum: 
+			for (int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[this->vertices[i]->Pid()];
+			}
+			/*update input*/
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+			return;
+
+		case VertexSIdEnum: 
+			for (int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[this->vertices[i]->Sid()];
+			}
+			/*update input*/
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+			return;
+
+		case NodesEnum:
+			/*Get dof list: */
+			GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+			/*Use the dof list to index into the vector: */
+			for(int i=0;i<numdof;i++){
+				values[i]=vector[doflist[i]];
+				if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+			}
+			/*Add input to the element: */
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+
+			/*Free ressources:*/
+			xDelete<int>(doflist);
+			return;
+
+	  case NodeSIdEnum:
+			for(int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[nodes[i]->Sid()];
+				if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+			}
+			/*Add input to the element: */
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+
+			/*Free ressources:*/
+			xDelete<int>(doflist);
+			return;
+
+	  default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+bool       Penta::IsOnBase(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+	sum = values[0]+values[1]+values[2]+values[3]+values[4]+values[5];
+	_assert_(sum==0. || sum==3.);
+
+	if(sum==3){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+bool       Penta::IsOnSurface(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+	sum = values[0]+values[1]+values[2]+values[3]+values[4]+values[5];
+	_assert_(sum==0. || sum==3.);
+
+	if(sum==3){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+bool       Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[vertices[i]->Pid()]<0.){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+void       Penta::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetJacobianDeterminant(pJdet,xyz_list,(GaussPenta*)gauss);
+
+}
+/*}}}*/
+void       Penta::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetTriaJacobianDeterminant(pJdet,xyz_list_base,(GaussPenta*)gauss);
+
+}
+/*}}}*/
+void       Penta::JacobianDeterminantLine(IssmDouble* pJdet,IssmDouble* xyz_list_line,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetSegmentJacobianDeterminant(pJdet,xyz_list_line,(GaussPenta*)gauss);
+
+}
+/*}}}*/
+void       Penta::JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_top,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetTriaJacobianDeterminant(pJdet,xyz_list_top,(GaussPenta*)gauss);
+
+}
+/*}}}*/
+void       Penta::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list_quad,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetQuadJacobianDeterminant(pJdet,xyz_list_quad,(GaussPenta*)gauss);
+
+}
+/*}}}*/
+IssmDouble Penta::MinEdgeLength(IssmDouble* xyz_list){/*{{{*/
+	/*Return the minimum lenght of the nine egdes of the penta*/
+
+	int    i,node0,node1;
+	int    edges[9][2]={{0,1},{0,2},{1,2},{3,4},{3,5},{4,5},{0,3},{1,4},{2,5}}; //list of the nine edges
+	IssmDouble length;
+	IssmDouble minlength=-1;
+
+	for(i=0;i<9;i++){
+		/*Find the two nodes for this edge*/
+		node0=edges[i][0];
+		node1=edges[i][1];
+
+		/*Compute the length of this edge and compare it to the minimal length*/
+		length=sqrt(pow(xyz_list[node0*3+0]-xyz_list[node1*3+0],2)+pow(xyz_list[node0*3+1]-xyz_list[node1*3+1],2)+pow(xyz_list[node0*3+2]-xyz_list[node1*3+2],2));
+		if(length<minlength || minlength<0) minlength=length;
+	}
+
+	return minlength;
+}
+/*}}}*/
+int        Penta::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){/*{{{*/
+
+	int i;
+	int found=0;
+	IssmDouble value;
+	Input* data=NULL;
+	GaussPenta* gauss=NULL;
+
+	/*First, serarch the input: */
+	data=inputs->GetInput(natureofdataenum); 
+
+	/*figure out if we have the vertex id: */
+	found=0;
+	for(i=0;i<NUMVERTICES;i++){
+		if(index==vertices[i]->Id()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussPenta(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	delete gauss;
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(void){/*{{{*/
+	return new GaussPenta();
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(int order){/*{{{*/
+	return new GaussPenta(order,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
+
+	IssmDouble  area_coordinates[4][3];
+
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,4);
+
+	return new GaussPenta(area_coordinates,order_horiz,order_vert);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussBase(int order){/*{{{*/
+	return new GaussPenta(0,1,2,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussLine(int vertex1,int vertex2,int order){/*{{{*/
+	return new GaussPenta(vertex1,vertex2,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussTop(int order){/*{{{*/
+	return new GaussPenta(3,4,5,order);
+}
+/*}}}*/
+void       Penta::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1bubbleEnum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->TensorInterpolation());
+
+}
+/*}}}*/
+void       Penta::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
+		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
+
+	/*Bed normal is opposite to surface normal*/
+	bed_normal[0]=-normal[0]/normal_norm;
+	bed_normal[1]=-normal[1]/normal_norm;
+	bed_normal[2]=-normal[2]/normal_norm;
+}
+/*}}}*/
+void       Penta::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
+
+	int i;
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
+		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	top_normal[0]=normal[0]/normal_norm;
+	top_normal[1]=normal[1]/normal_norm;
+	top_normal[2]=normal[2]/normal_norm;
+}
+/*}}}*/
+int        Penta::NumberofNodesPressure(void){/*{{{*/
+	return PentaRef::NumberofNodes(this->PressureInterpolation());
+}
+/*}}}*/
+int        Penta::NumberofNodesVelocity(void){/*{{{*/
+	return PentaRef::NumberofNodes(this->VelocityInterpolation());
+}
+/*}}}*/
+void       Penta::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){/*{{{*/
+
+   IssmDouble agd[NUMVERTICES];             // surface mass balance
+   IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+   IssmDouble h[NUMVERTICES],s[NUMVERTICES]; // ,b
+   IssmDouble rho_water,rho_ice,desfac,s0p;
+
+   /*Recover monthly temperatures and precipitation*/
+   Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
+   Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
+   GaussPenta* gauss=new GaussPenta();
+   IssmDouble time,yts;
+   this->parameters->FindParam(&time,TimeEnum);
+   this->parameters->FindParam(&yts,ConstantsYtsEnum);
+   for(int month=0;month<12;month++) {
+     for(int iv=0;iv<NUMVERTICES;iv++) {
+       gauss->GaussVertex(iv);
+       input->GetInputValue(&monthlytemperatures[iv][month],gauss,time+month/12.*yts);
+       monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
+       input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
+       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion to m/yr
+     }
+   } 
+
+  /*Recover info at the vertices: */
+  GetInputListOnVertices(&h[0],ThicknessEnum);
+  GetInputListOnVertices(&s[0],SurfaceEnum);
+
+  /*Get material parameters :*/
+  rho_ice=matpar->GetRhoIce();
+  rho_water=matpar->GetRhoFreshwater();
+
+  /*Get desertification effect parameters*/
+  desfac=matpar->GetDesFac();
+  s0p=matpar->GetS0p();
+
+   /*measure the surface mass balance*/
+   for (int iv = 0; iv < NUMVERTICES; iv++){
+     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, 
+				  signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+   }
+
+   /*Update inputs*/    
+   this->inputs->AddInput(new PentaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
+   //this->inputs->AddInput(new PentaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+   this->InputExtrude(SurfaceforcingsMassBalanceEnum);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Penta::ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){/*{{{*/
+
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if(pe){
+		if(analysis_type==StressbalanceAnalysisEnum){
+			if(this->element_type==MINIcondensedEnum){
+				int approximation;
+				inputs->GetInputValue(&approximation,ApproximationEnum);
+				if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+					//Do nothing, condensation already done in PVectorCoupling
+				}
+				else{
+					int indices[3]={18,19,20};
+					pe->StaticCondensation(Ke,3,&indices[0]);
+				}
+			}
+			else if(this->element_type==P1bubblecondensedEnum){
+				int size   = nodes[6]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+				int offset = 0;
+				for(int i=0;i<6;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+				int* indices=xNew<int>(size);
+				for(int i=0;i<size;i++) indices[i] = offset+i;
+				pe->StaticCondensation(Ke,size,indices);
+				xDelete<int>(indices);
+			}
+		}
+	}
+
+	if(Ke){
+		if(analysis_type==StressbalanceAnalysisEnum){
+			int approximation;
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+				//Do nothing condensatino already done for Stokes part
+			}
+			else{
+				if(this->element_type==MINIcondensedEnum){
+					int indices[3]={18,19,20};
+					Ke->StaticCondensation(3,&indices[0]);
+				}
+				else if(this->element_type==P1bubblecondensedEnum){
+					int size   = nodes[6]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+					int offset = 0;
+					for(int i=0;i<6;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+					int* indices=xNew<int>(size);
+					for(int i=0;i<size;i++) indices[i] = offset+i;
+					Ke->StaticCondensation(size,indices);
+					xDelete<int>(indices);
+				}
+			}
+		}
+	}
+}
+/*}}}*/
+void       Penta::ResetFSBasalBoundaryCondition(void){/*{{{*/
+
+	int          approximation;
+	int          numindices;
+	int         *indices = NULL;
+	IssmDouble   slopex,slopey,groundedice;
+	IssmDouble   xz_plane[6];
+	IssmDouble*  vertexapproximation= NULL;
+
+	/*For FS only: we want the CS to be tangential to the bedrock*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(!IsOnBase() || (approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum &&  approximation!=HOFSApproximationEnum)) return;
+
+	/*Get number of nodes for velocity only and base*/
+	BasalNodeIndices(&numindices,&indices,this->VelocityInterpolation());
+
+	/*Get inputs*/
+	Input* slopex_input=inputs->GetInput(BedSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(BedSlopeYEnum); _assert_(slopey_input);
+	Input* groundedicelevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(groundedicelevelset_input);
+
+	/*Loop over basal nodes and update their CS*/
+	GaussPenta* gauss = new GaussPenta();
+	for(int i=0;i<numindices;i++){//FIXME
+		gauss->GaussNode(this->VelocityInterpolation(),indices[i]);
+
+		slopex_input->GetInputValue(&slopex,gauss);
+		slopey_input->GetInputValue(&slopey,gauss);
+		groundedicelevelset_input->GetInputValue(&groundedice,gauss);
+
+		/*New X axis          New Z axis*/
+		xz_plane[0]=1.;       xz_plane[3]=-slopex;  
+		xz_plane[1]=0.;       xz_plane[4]=-slopey;  
+		xz_plane[2]=slopex;   xz_plane[5]=1.;          
+
+		if(groundedice>=0){
+			if(this->nodes[indices[i]]->GetApproximation()==FSvelocityEnum){
+				this->nodes[indices[i]]->DofInSSet(2); //vz 
+			}
+			else if(this->nodes[indices[i]]->GetApproximation()==SSAFSApproximationEnum || this->nodes[indices[i]]->GetApproximation()==HOFSApproximationEnum){
+				this->nodes[indices[i]]->DofInSSet(4); //vz 
+			}
+			else _error_("Flow equation approximation"<<EnumToStringx(this->nodes[indices[i]]->GetApproximation())<<" not supported yet");
+		}
+		else{
+			if(this->nodes[indices[i]]->GetApproximation()==FSvelocityEnum){
+				this->nodes[indices[i]]->DofInFSet(2); //vz
+			}
+			else if(this->nodes[indices[i]]->GetApproximation()==SSAFSApproximationEnum || this->nodes[indices[i]]->GetApproximation()==HOFSApproximationEnum){
+				this->nodes[indices[i]]->DofInFSet(4); //vz 
+			}
+			else _error_("Flow equation approximation"<<EnumToStringx(this->nodes[indices[i]]->GetApproximation())<<" not supported yet");
+		}
+
+		XZvectorsToCoordinateSystem(&this->nodes[indices[i]]->coord_system[0][0],&xz_plane[0]);
+	}
+
+	/*cleanup*/
+	xDelete<int>(indices);
+	delete gauss;
+}
+/*}}}*/
+void       Penta::SetClone(int* minranks){/*{{{*/
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+void       Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
+void       Penta::SetTemporaryElementType(int element_type_in){/*{{{*/
+	this->element_type=element_type_in;
+}
+/*}}}*/
+Tria*      Penta::SpawnTria(int index1,int index2,int index3){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Create Tria*/
+	Tria* tria=new Tria();
+	tria->id=this->id;
+	tria->inputs=(Inputs*)this->inputs->SpawnTriaInputs(index1,index2,index3);
+	tria->parameters=this->parameters;
+	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),index1,index2,index3);
+
+	/*Spawn material*/
+	tria->material=(Material*)this->material->copy2(tria);
+
+	/*recover nodes, material and matpar: */
+	tria->nodes=(Node**)tria->hnodes[analysis_counter]->deliverp();
+	tria->vertices=(Vertex**)tria->hvertices->deliverp();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	/*Return new Tria*/
+	return tria;
+}
+/*}}}*/
+Element*   Penta::SpawnBasalElement(void){/*{{{*/
+
+	_assert_(this->IsOnBase());
+
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
+	if(this->inputs->GetInput(VxEnum)) this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	if(this->inputs->GetInput(VyEnum)) this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->inputs->DeleteInput(DamageDbarEnum);
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	return tria;
+}
+/*}}}*/
+Element*   Penta::SpawnTopElement(void){/*{{{*/
+
+	_assert_(this->IsOnSurface());
+
+	Tria* tria=(Tria*)SpawnTria(3,4,5);
+
+	return tria;
+}
+/*}}}*/
+IssmDouble Penta::SurfaceArea(void){/*{{{*/
+
+	int    approximation;
+	IssmDouble S;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(!IsIceInElement())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non SSA not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBase())){
+		return 0;
+	}
+	else if (approximation==SSAApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceArea*/
+		tria=(Tria*)SpawnTria(0,1,2);
+		S=tria->SurfaceArea();
+		delete tria->material; delete tria;
+		return S;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5);
+		S=tria->SurfaceArea();
+		delete tria->material; delete tria;
+		return S;
+	}
+}
+/*}}}*/
+IssmDouble Penta::TimeAdapt(void){/*{{{*/
+
+	int    i;
+	IssmDouble C,dx,dy,dz,dt;
+	IssmDouble maxabsvx,maxabsvy,maxabsvz;
+	IssmDouble maxx,minx,maxy,miny,maxz,minz;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	maxabsvx = this->inputs->MaxAbs(VxEnum);
+	maxabsvy = this->inputs->MaxAbs(VyEnum);
+	maxabsvz = this->inputs->MaxAbs(VzEnum);
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+	minz=xyz_list[0][2];
+	maxz=xyz_list[0][2];
+
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+		if (xyz_list[i][2]<minz)minz=xyz_list[i][2];
+		if (xyz_list[i][2]>maxz)maxz=xyz_list[i][2];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+	dz=maxz-minz;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy+maxabsvz/dz);
+
+	return dt;
+}/*}}}*/
+void       Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){ /*{{{*/
+
+	/*Intermediaries*/
+	int        i;
+	int        penta_vertex_ids[6];
+	IssmDouble nodeinputs[6];
+	IssmDouble yts;
+	bool       dakota_analysis;
+	bool       isFS;
+	int        numnodes;
+	int*       penta_node_ids = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Checks if debuging*/
+	_assert_(iomodel->elements);
+
+	/*Recover element type*/
+	this->element_type_list[analysis_counter]=finiteelement_type;
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<6;i++) penta_vertex_ids[i]=iomodel->elements[6*index+i]; //ids for vertices are in the elements array from Matlab
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	switch(finiteelement_type){
+		case P1Enum:
+			numnodes         = 6;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numnodes         = 7;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+			break;
+		case P1xP2Enum:
+			numnodes         = 9;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			break;
+		case P1xP3Enum:
+			numnodes         = 12;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+0]+2;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+1]+2;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+2*iomodel->elementtoedgeconnectivity[9*index+2]+2;
+			break;
+		case P2xP1Enum:
+			numnodes         = 12;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			break;
+		case P2xP4Enum:
+			numnodes         = 30;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0]; /*Vertex 1*/
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1]; /*Vertex 2*/
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2]; /*Vertex 3*/
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3]; /*Vertex 4*/
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4]; /*Vertex 5*/
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5]; /*Vertex 6*/
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+1; /*mid vertical edge 1*/
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+1; /*mid vertical edge 2*/
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+1; /*mid vertical edge 3*/
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+3]+1; /*mid basal edge 1*/
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+4]+1; /*mid basal edge 2*/
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+5]+1; /*mid basal edge 3*/
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+6]+1; /*mid top edge 1*/
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+7]+1; /*mid top edge 2*/
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+8]+1; /*mid top edge 3*/
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+2; /* 1/4 vertical edge 1*/
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+2; /* 1/4 vertical edge 2*/
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+2; /* 1/4 vertical edge 3*/
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+3; /* 2/4 vertical edge 1*/
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+3; /* 2/4 vertical edge 2*/
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+3; /* 2/4 vertical edge 3*/
+			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+1; /* 1/4 vertical face 1*/
+			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+1; /* 1/4 vertical face 2*/
+			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+1; /* 1/4 vertical face 3*/
+			penta_node_ids[24]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+2; /* 2/4 vertical face 1*/
+			penta_node_ids[25]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+2; /* 2/4 vertical face 2*/
+			penta_node_ids[26]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+2; /* 2/4 vertical face 3*/
+			penta_node_ids[27]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+3; /* 3/4 vertical face 1*/
+			penta_node_ids[28]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+3; /* 3/4 vertical face 2*/
+			penta_node_ids[29]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+3; /* 3/4 vertical face 3*/
+			break;
+		case P2Enum:
+			numnodes         = 18;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			numnodes         = 19;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+index+1;
+			break;
+		case P1P1Enum: case P1P1GLSEnum:
+			numnodes         = 12;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+0];
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+1];
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+2];
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+3];
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+4];
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+5];
+			break;
+		case MINIEnum: case MINIcondensedEnum:
+			numnodes         = 13;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+0];
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+1];
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+2];
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+3];
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+4];
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+5];
+			break;
+		case TaylorHoodEnum:
+			numnodes         = 24;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+0];
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+1];
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+2];
+			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+3];
+			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+4];
+			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+5];
+			break;
+		case LATaylorHoodEnum:
+			numnodes         = 18;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			break;
+		case OneLayerP4zEnum:
+			numnodes         = 30+6;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0]; /*Vertex 1*/
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1]; /*Vertex 2*/
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2]; /*Vertex 3*/
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3]; /*Vertex 4*/
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4]; /*Vertex 5*/
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5]; /*Vertex 6*/
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+1; /*mid vertical edge 1*/
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+1; /*mid vertical edge 2*/
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+1; /*mid vertical edge 3*/
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+3]+1; /*mid basal edge 1*/
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+4]+1; /*mid basal edge 2*/
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+5]+1; /*mid basal edge 3*/
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+6]+1; /*mid top edge 1*/
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+7]+1; /*mid top edge 2*/
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+8]+1; /*mid top edge 3*/
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+2; /* 1/4 vertical edge 1*/
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+2; /* 1/4 vertical edge 2*/
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+2; /* 1/4 vertical edge 3*/
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+3; /* 2/4 vertical edge 1*/
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+3; /* 2/4 vertical edge 2*/
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+3; /* 2/4 vertical edge 3*/
+			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+1; /* 1/4 vertical face 1*/
+			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+1; /* 1/4 vertical face 2*/
+			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+1; /* 1/4 vertical face 3*/
+			penta_node_ids[24]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+2; /* 2/4 vertical face 1*/
+			penta_node_ids[25]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+2; /* 2/4 vertical face 2*/
+			penta_node_ids[26]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+2; /* 2/4 vertical face 3*/
+			penta_node_ids[27]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+3; /* 3/4 vertical face 1*/
+			penta_node_ids[28]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+3; /* 3/4 vertical face 2*/
+			penta_node_ids[29]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+4]+3; /* 3/4 vertical face 3*/
+
+			penta_node_ids[30]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+0];
+			penta_node_ids[31]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+1];
+			penta_node_ids[32]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+2];
+			penta_node_ids[33]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+3];
+			penta_node_ids[34]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+4];
+			penta_node_ids[35]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+5];
+			break;
+		case CrouzeixRaviartEnum:
+			numnodes         = 25;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+index+1;
+
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+1;
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+2;
+			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+3;
+			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+4;
+			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+5;
+			penta_node_ids[24]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+6;
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
+	}
+
+	/*hooks: */
+	this->SetHookNodes(penta_node_ids,numnodes,analysis_counter); this->nodes=NULL;
+	xDelete<int>(penta_node_ids);
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Defaults if not provided in iomodel*/
+	switch(analysis_type){
+
+		case StressbalanceAnalysisEnum:
+
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==HOFSApproximationEnum){
+				/*Create VzHO and VzFS Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderFSEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaInput(VzHOEnum,nodeinputs,P1Enum));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(VzHOEnum,nodeinputs,P1Enum));
+				}
+			}
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==SSAFSApproximationEnum){
+				/*Create VzSSA and VzFS Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderFSEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaInput(VzSSAEnum,nodeinputs,P1Enum));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(VzSSAEnum,nodeinputs,P1Enum));
+				}
+			}
+			break;
+		default:
+			/*No update for other solution types*/
+			break;
+	}
+}
+/*}}}*/
+void       Penta::UpdateConstraintsExtrudeFromBase(void){/*{{{*/
+
+	if(!IsOnBase()) return;
+
+	int        extrusioninput;
+	IssmDouble value,isonbase;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput);      _assert_(extrusioninput);
+	Input* onbase = inputs->GetInput(MeshVertexonbaseEnum); _assert_(onbase);
+
+	GaussPenta* gauss=new GaussPenta();
+	for(int iv=0;iv<this->NumberofNodes(this->element_type);iv++){
+		gauss->GaussNode(this->element_type,iv);
+		onbase->GetInputValue(&isonbase,gauss);
+		if(isonbase==1.){
+			input->GetInputValue(&value,gauss);
+			this->nodes[iv]->ApplyConstraint(0,value);
+		}
+	}
+	delete gauss;
+
+}
+/*}}}*/
+void       Penta::UpdateConstraintsExtrudeFromTop(void){/*{{{*/
+
+	if(!IsOnSurface()) return;
+
+	int extrusioninput;
+	int indices[3]={3,4,5};
+	IssmDouble value;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput); _assert_(extrusioninput);
+
+	GaussPenta* gauss=new GaussPenta();
+	for(int i=0;i<3;i++){
+		gauss->GaussNode(P1Enum,indices[i]);
+		input->GetInputValue(&value,gauss);
+		this->nodes[indices[i]]->ApplyConstraint(0,value);
+	}
+	delete gauss;
+
+}
+/*}}}*/
+void       Penta::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
+	PentaRef::GetInputValue(pvalue,values,gauss,P1Enum);
+}
+/*}}}*/
+void       Penta::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	PentaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+}
+/*}}}*/
+int        Penta::VertexConnectivity(int vertexindex){/*{{{*/
+	_assert_(this->vertices);
+	return this->vertices[vertexindex]->Connectivity();
+}
+/*}}}*/
+void       Penta::VerticalSegmentIndices(int** pindices,int* pnumseg){/*{{{*/
+
+	/*output*/
+	int *indices = xNew<int>(3*2);
+	indices[0*2 + 0] = 0; indices[0*2 + 1] = 3;
+	indices[1*2 + 0] = 1; indices[1*2 + 1] = 4;
+	indices[2*2 + 0] = 2; indices[2*2 + 1] = 5;
+
+	/*Assign output pointers*/
+	*pindices = indices;
+	*pnumseg  = 3;
+}
+/*}}}*/
+void       Penta::ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble phi;
+	IssmDouble viscosity;
+	IssmDouble epsilon[6];
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->StrainRateFS(&epsilon[0],xyz_list,(GaussPenta*)gauss,vx_input,vy_input,vz_input);
+	this->ViscosityFS(&viscosity,3,xyz_list,(GaussPenta*)gauss,vx_input,vy_input,vz_input);
+	GetPhi(&phi,&epsilon[0],viscosity);
+
+	/*Assign output pointer*/
+	*pphi = phi;
+}
+/*}}}*/
+int        Penta::VelocityInterpolation(void){/*{{{*/
+	return PentaRef::VelocityInterpolation(this->element_type);
+}
+/*}}}*/
+int        Penta::PressureInterpolation(void){/*{{{*/
+	return PentaRef::PressureInterpolation(this->element_type);
+}
+/*}}}*/
+bool       Penta::IsZeroLevelset(int levelset_enum){/*{{{*/
+
+	bool        iszerols;
+	IssmDouble  ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],levelset_enum);
+
+	/*If the level set has always same sign, there is no ice front here*/
+	iszerols = false;
+	if(IsIceInElement()){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
+			iszerols = true;
+		}
+	}
+	return iszerols;
+}
+/*}}}*/
+bool       Penta::IsIcefront(void){/*{{{*/
+
+	bool isicefront;
+	int i,nrice;
+   IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	isicefront=false;
+	if(IsIceInElement()){
+		nrice=0;       
+		for(i=0;i<NUMVERTICES2D;i++)
+			if(ls[i]<0.) nrice++;
+		if(nrice==1) isicefront= true;
+	}
+	return isicefront;
+}/*}}}*/
+void       Penta::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
+	_error_("Not supported yet!");
+}
+/*}}}*/
+IssmDouble Penta::IceVolume(void){/*{{{*/
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	IssmDouble base,height;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement())return 0;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
+
+	/*Return: */
+	return base*height;
+}
+/*}}}*/
+IssmDouble Penta::IceVolumeAboveFloatation(void){/*{{{*/
+
+	/*Volume above floatation: H + rho_water/rho_ice*bathymetry for nodes on the bed*/
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,bed,surface,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement() || IsFloating() || !IsOnBase())return 0;
+
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height above floatation*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
+	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	base_input->GetInputAverage(&bed);
+	bed_input->GetInputAverage(&bathymetry);
+
+	/*Return: */
+	return base*(surface - bed + min( rho_water/rho_ice * bathymetry, 0.) );
+}
+/*}}}*/
+IssmDouble Penta::MassFlux( IssmDouble* segment){/*{{{*/
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBase()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	mass_flux=tria->MassFlux(segment);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+IssmDouble Penta::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBase()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	mass_flux=tria->MassFlux(x1,y1,x2,y2,segment_id);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+void       Penta::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+		case DamageDbarEnum:
+			*presponse=this->material->GetDbar();
+			break;
+		case VelEnum:
+			{
+
+				/*Get input:*/
+				IssmDouble vel;
+				Input* vel_input;
+
+				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+				vel_input->GetInputAverage(&vel);
+
+				/*Assign output pointers:*/
+				*presponse=vel;
+			}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+IssmDouble Penta::TotalSmb(void){/*{{{*/
+
+	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	if(!IsIceInElement() || !IsOnSurface()) return 0.;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+
+	smb_input->GetInputAverage(&smb);
+	Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+
+#ifdef _HAVE_GIA_
+void       Penta::GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){/*{{{*/
+	_error_("GIA deflection not implemented yet!");
+}
+/*}}}*/
+#endif
+
+void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==DamageDbarEnum){
+		input=(Input*)inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+void       Penta::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
+
+	Input* input=NULL;
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(control_enum==DamageDbarEnum){
+		input=(Input*)inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(control_enum);
+	}
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetVerticesConnectivityList(&connectivity[0]);
+	this->GetVerticesSidList(&sidlist[0]);
+
+	GaussPenta* gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
+
+}/*}}}*/
+void       Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			if (!IsOnBase()) goto cleanup_and_return;
+			input=(Input*)this->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else if(control_type[i]==DamageDbarEnum){
+			if (!IsOnBase()) goto cleanup_and_return;
+			input=(Input*)this->inputs->GetInput(DamageDEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			this->InputExtrude(MaterialsRheologyBEnum);
+		}
+		else if(control_type[i]==DamageDbarEnum){
+			this->InputExtrude(DamageDEnum);
+		}
+	}
+
+	/*Clean up and return*/
+cleanup_and_return:
+	xDelete<int>(control_type);
+}
+/*}}}*/
+void       Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){/*{{{*/
+
+	int vertexpidlist[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get input (either in element or material)*/
+	if(control_enum==MaterialsRheologyBbarEnum) control_enum=MaterialsRheologyBEnum;
+	Input* input=inputs->GetInput(control_enum);
+	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
+}
+/*}}}*/
+void       Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(control_enum==MaterialsRheologyBbarEnum){
+		control_enum=MaterialsRheologyBEnum;
+		if(!IsOnBase()) return;
+	}
+	if(control_enum==DamageDbarEnum){
+		control_enum=DamageDEnum;
+		if(!IsOnBase()) return;
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	Input* new_input = new PentaInput(control_enum,values,P1Enum);
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+
+	if(control_init==MaterialsRheologyBbarEnum){
+		this->InputExtrude(control_enum);
+	}
+	if(control_init==DamageDbarEnum){
+		this->InputExtrude(control_enum);
+	}
+}
+/*}}}*/
+
+#ifdef _HAVE_DAKOTA_
+void       Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaInput*/
+			IssmDouble values[6];
+
+			/*Get values on the 6 vertices*/
+			for (i=0;i<6;i++){
+				values[i]=vector[this->vertices[i]->Sid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium*/
+					IssmDouble  thickness[6];
+					IssmDouble  thickness_init[6];
+					IssmDouble  hydrostatic_ratio[6];
+					IssmDouble  surface[6];
+					IssmDouble  bed[6];
+
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BaseEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new thickness: */
+//					for(j=0;j<6;j++)thickness[j]=values[j];
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						IssmDouble rho_ice,rho_water,di;
+						rho_ice=this->matpar->GetRhoIce();
+						rho_water=this->matpar->GetRhoWater();
+
+						di=rho_ice/rho_water;
+
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
+							if     (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+
+						/*  check the computed thickness and update bed  */
+							if (thickness[j] < 0.)
+								thickness[j]=1./(1.-di);
+							bed[j]=surface[j]-thickness[j];
+						}
+
+//						for(j=0;j<6;j++){
+//							surface[j]=(1-di)*thickness[j];
+//							bed[j]=-di*thickness[j];
+//						}
+					}
+					else{
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed thickness, use scaled value  */
+							if(hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j];
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+						}
+
+						/*update bed on grounded ice: */
+//						for(j=0;j<6;j++)surface[j]=bed[j]+thickness[j];
+						for(j=0;j<6;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new PentaInput(ThicknessEnum,thickness,P1Enum));
+					this->inputs->AddInput(new PentaInput(BaseEnum,bed,P1Enum));
+					this->inputs->AddInput(new PentaInput(SurfaceEnum,surface,P1Enum));
+					break;
+
+				default:
+					this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+			}
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+void       Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
+
+	int             i,t,row;
+	IssmDouble      time;
+	TransientInput *transientinput = NULL;
+	IssmDouble      values[6];
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			/*Create transient input: */
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=this->vertices[i]->Sid();
+					values[i]=matrix[ncols*row+t];
+				}
+
+				/*time:*/
+				time=matrix[(nrows-1)*ncols+t];
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new PentaInput(name,values,P1Enum),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+void       Penta::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble   values[numdof];
+	IssmDouble   enum_value;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		enum_input->GetInputValue(&enum_value,gauss);
+		values[i]=enum_value;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+void       Penta::MigrateGroundingLine(IssmDouble* phi_ungrounding){/*{{{*/
+
+	int        i,migration_style;
+	IssmDouble bed_hydro,yts;
+	IssmDouble rho_water,rho_ice,density;
+	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
+	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];
+
+	if(!IsOnBase()) return;
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BaseEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+	rho_water   = matpar->GetRhoWater();
+	rho_ice     = matpar->GetRhoIce();
+	density     = rho_ice/rho_water;
+
+	/*go through vertices, and update inputs, considering them to be PentaVertex type: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+		if(phi[i]<=0){
+			if(b[i]<=r[i]){ 
+				b[i]        = r[i];
+				s[i]        = b[i]+h[i];
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AggressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{
+			bed_hydro=-density*h[i];
+			if(bed_hydro>r[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AggressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else{
+					if(migration_style!=SoftMigrationEnum) _error_("Error: migration should be Aggressive, Soft or Subelement");
+				}
+			}
+		}
+	}
+
+	/*Recalculate phi*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(migration_style==SoftMigrationEnum){
+			bed_hydro=-density*h[i];
+			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
+				phi[i]=h[i]+r[i]/density;
+			}
+		}
+		else phi[i]=h[i]+r[i]/density;
+	}
+	this->inputs->AddInput(new PentaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
+	this->InputExtrude(MaskGroundediceLevelsetEnum);
+
+	/*Update inputs*/
+	this->inputs->AddInput(new PentaInput(SurfaceEnum,&s[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(BaseEnum,&b[0],P1Enum));
+
+	/*Extrude inputs*/
+	this->InputExtrude(SurfaceEnum);
+	this->InputExtrude(BaseEnum);
+}
+/*}}}*/
+void       Penta::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
+
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
+	for(int i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (gl[i]>0.){
+			bed_hydro=-density*h[i];
+			if(bed_hydro>r[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+int        Penta::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<NUMVERTICES;i++){
+		if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
+			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Penta.h	(revision 18231)
@@ -0,0 +1,180 @@
+/*! \file Penta.h 
+ *  \brief: header file for penta object
+ */
+
+#ifndef _PENTA_H_
+#define _PENTA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./PentaRef.h"
+class Object;
+class Parameters;
+class Results;
+class Inputs;
+class Input;
+class IoModel;
+class Node;
+class Material;
+class Matpar;
+class Tria;
+class ElementMatrix;
+class ElementVector;
+class GaussPenta;
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Penta: public Element,public ElementHook,public PentaRef{
+
+	public:
+
+		Penta      **verticalneighbors;           // 2 neighbors: first one under, second one above
+
+		/*Penta constructors and destructor: {{{*/
+		Penta(){};
+		Penta(int penta_id,int penta_sid,int i, IoModel* iomodel,int nummodels);
+		~Penta();
+		/*}}}*/
+		/*Object virtual functions definitions: {{{*/
+		Object *copy();
+		int     ObjectEnum();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{*/
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
+		#endif
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		IssmDouble CharacteristicLength(void){_error_("not implemented yet");};
+		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void   ComputeSigmaNN(){_error_("not implemented yet");};
+		void   ComputeStressTensor();
+		void   ComputeDeviatoricStressTensor();
+		void   Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void   ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		int    FiniteElement(void);
+		void   FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void   Delta18oParameterization(void);
+		Penta* GetUpperPenta(void);
+		Penta* GetLowerPenta(void);
+		Penta* GetSurfacePenta(void);
+		Penta* GetBasalPenta(void);
+		Element* GetUpperElement(void);
+		Element* GetBasalElement(void);
+		void   GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
+		IssmDouble GetGroundedPortion(IssmDouble* xyz_list);
+		int    GetNodeIndex(Node* node);
+		int    GetNumberOfNodes(void);
+		int    GetNumberOfVertices(void);
+		void   GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
+		void   GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
+		void   GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+
+		void   InputDepthAverageAtBase(int enum_type,int average_enum_type);
+		void   InputScale(int enum_type,IssmDouble scale_factor);
+		int    NumberofNodesVelocity(void);
+		int    NumberofNodesPressure(void);
+		int    VelocityInterpolation();
+		int    PressureInterpolation();
+		int    TensorInterpolation(){_error_("not implemented yet");};
+		bool   IsZeroLevelset(int levelset_enum);
+		bool   IsIcefront(void);
+		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
+		void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
+		void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
+		void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
+		void   ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void   ResetFSBasalBoundaryCondition(void);
+		void   SetTemporaryElementType(int element_type_in);
+	   Element* SpawnBasalElement(void);
+		Element* SpawnTopElement(void);
+		IssmDouble SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		IssmDouble TimeAdapt();
+		void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
+		int    VertexConnectivity(int vertexindex);
+		void   VerticalSegmentIndices(int** pindices,int* pnumseg);
+		void   ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+
+		void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		IssmDouble IceVolume(void);
+		IssmDouble IceVolumeAboveFloatation(void);
+		IssmDouble TotalSmb(void);
+		IssmDouble MassFlux(IssmDouble* segment);
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
+		void   ElementResponse(IssmDouble* presponse,int response_enum);
+
+		#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
+		#endif
+
+		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
+		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
+		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
+
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding);
+		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
+		int    UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		/*}}}*/
+		/*Penta specific routines:{{{*/
+		void           AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		void           AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		void	         NormalBase(IssmDouble* bed_normal, IssmDouble* xyz_list);
+		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void	         NormalTop(IssmDouble* bed_normal, IssmDouble* xyz_list);
+		ElementMatrix* CreateBasalMassMatrix(void);
+		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints);
+		int            GetElementType(void);
+		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		Node*          GetNode(int node_number);
+		void	         InputExtrude(int enum_type);
+		void           InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
+		void           InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solutiong,int enum_type);
+		bool	         IsOnSurface(void);
+		bool	         IsOnBase(void);
+		bool           IsNodeOnShelfFromFlags(IssmDouble* flags);
+		void           JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		void           JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		Gauss*         NewGauss(void);
+		Gauss*         NewGauss(int order);
+		Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){_error_("not implemented yet");};
+		Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
+		Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){_error_("not implemented yet");};
+		Gauss*         NewGaussBase(int order);
+		Gauss*         NewGaussLine(int vertex1,int vertex2,int order);
+		Gauss*         NewGaussTop(int order);
+		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
+		IssmDouble     MinEdgeLength(IssmDouble* xyz_list);
+		void	         SetClone(int* minranks);
+		Tria*	         SpawnTria(int index1,int index2,int index3);
+		IssmDouble     StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa);
+
+		void           UpdateConstraintsExtrudeFromBase(void);
+		void           UpdateConstraintsExtrudeFromTop(void);
+		/*}}}*/
+};
+#endif  /* _PENTA_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.cpp	(revision 18231)
@@ -0,0 +1,1158 @@
+/*!\file PentaRef.c
+ * \brief: implementation of the PentaRef object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP0    1
+#define NUMNODESP1    6
+#define NUMNODESP1_2d 3
+#define NUMNODESP1b   7
+#define NUMNODESP1xP2 9
+#define NUMNODESP1xP3 12
+#define NUMNODESP2xP1 12
+#define NUMNODESP2    18
+#define NUMNODESP2b   19
+#define NUMNODESP2xP4 30
+
+/*Object constructors and destructor*/
+PentaRef::PentaRef(){/*{{{*/
+}
+/*}}}*/
+PentaRef::~PentaRef(){/*{{{*/
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+void PentaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble A1,A2,A3;  // area coordinates
+	IssmDouble xi,eta,zi; // parametric coordinates
+	IssmDouble x1,x2,x3,x4,x5,x6;
+	IssmDouble y1,y2,y3,y4,y5,y6;
+	IssmDouble z1,z2,z3,z4,z5,z6;
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Figure out xi,eta and zi (parametric coordinates), for this gaussian point: */
+	A1  = gauss->coord1;
+	A2  = gauss->coord2;
+	A3  = gauss->coord3;
+	xi  = A2-A1;
+	eta = SQRT3*A3;
+	zi  = gauss->coord4;
+
+	x1=xyz_list[3*0+0];
+	x2=xyz_list[3*1+0];
+	x3=xyz_list[3*2+0];
+	x4=xyz_list[3*3+0];
+	x5=xyz_list[3*4+0];
+	x6=xyz_list[3*5+0];
+
+	y1=xyz_list[3*0+1];
+	y2=xyz_list[3*1+1];
+	y3=xyz_list[3*2+1];
+	y4=xyz_list[3*3+1];
+	y5=xyz_list[3*4+1];
+	y6=xyz_list[3*5+1];
+
+	z1=xyz_list[3*0+2];
+	z2=xyz_list[3*1+2];
+	z3=xyz_list[3*2+2];
+	z4=xyz_list[3*3+2];
+	z5=xyz_list[3*4+2];
+	z6=xyz_list[3*5+2];
+
+	J[NDOF3*0+0] = 0.25*(x1-x2-x4+x5)*zi+0.25*(-x1+x2-x4+x5);
+	J[NDOF3*1+0] = SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*zi+SQRT3/12.0*(-x1-x2+2*x3-x4-x5+2*x6);
+	J[NDOF3*2+0] = SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*eta+1/4*(x1-x2-x4+x5)*xi +0.25*(-x1+x5-x2+x4);
+
+	J[NDOF3*0+1] = 0.25*(y1-y2-y4+y5)*zi+0.25*(-y1+y2-y4+y5);
+	J[NDOF3*1+1] = SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*zi+SQRT3/12.0*(-y1-y2+2*y3-y4-y5+2*y6);
+	J[NDOF3*2+1] = SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*eta+0.25*(y1-y2-y4+y5)*xi+0.25*(y4-y1+y5-y2);
+
+	J[NDOF3*0+2] = 0.25*(z1-z2-z4+z5)*zi+0.25*(-z1+z2-z4+z5);
+	J[NDOF3*1+2] = SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*zi+SQRT3/12.0*(-z1-z2+2*z3-z4-z5+2*z6);
+	J[NDOF3*2+2] = SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*eta+0.25*(z1-z2-z4+z5)*xi+0.25*(-z1+z5-z2+z4);
+}
+/*}}}*/
+void PentaRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*On a penta, Jacobian varies according to coordinates. We need to get the Jacobian, and take 
+	 * the determinant of it: */
+	IssmDouble J[3][3];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix3x3Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void PentaRef::GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble z3=xyz_list[3*2+2];
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+
+	*Jdet=.5*sqrt(pow(x2-x1,2) + pow(y2-y1,2) + pow(z2-z1,2));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void PentaRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
+void PentaRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get current coordinates in reference element*/
+	IssmDouble zeta=gauss->coord4;
+
+	switch(finiteelement){
+		case P0Enum: 
+			basis[0]=1.;
+			return;
+		case P1Enum: case P1DGEnum:
+			basis[0]=gauss->coord1*(1.-zeta)/2.;
+			basis[1]=gauss->coord2*(1.-zeta)/2.;
+			basis[2]=gauss->coord3*(1.-zeta)/2.;
+			basis[3]=gauss->coord1*(1.+zeta)/2.;
+			basis[4]=gauss->coord2*(1.+zeta)/2.;
+			basis[5]=gauss->coord3*(1.+zeta)/2.;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			basis[0]=gauss->coord1*(1.-zeta)/2.;
+			basis[1]=gauss->coord2*(1.-zeta)/2.;
+			basis[2]=gauss->coord3*(1.-zeta)/2.;
+			basis[3]=gauss->coord1*(1.+zeta)/2.;
+			basis[4]=gauss->coord2*(1.+zeta)/2.;
+			basis[5]=gauss->coord3*(1.+zeta)/2.;
+			basis[6]=27.*gauss->coord1*gauss->coord2*gauss->coord3*(1.+zeta)*(1.-zeta);
+			return;
+		case P2xP1Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*(1.-zeta)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*(1.-zeta)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*(1.-zeta)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*(1.+zeta)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*(1.+zeta)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*(1.+zeta)/2.;
+			/*mid-sides of triangles*/
+			basis[ 6]=4.*gauss->coord3*gauss->coord2*(1.-zeta)/2.;
+			basis[ 7]=4.*gauss->coord3*gauss->coord1*(1.-zeta)/2.;
+			basis[ 8]=4.*gauss->coord1*gauss->coord2*(1.-zeta)/2.;
+			basis[ 9]=4.*gauss->coord3*gauss->coord2*(1.+zeta)/2.;
+			basis[10]=4.*gauss->coord3*gauss->coord1*(1.+zeta)/2.;
+			basis[11]=4.*gauss->coord1*gauss->coord2*(1.+zeta)/2.;
+			return;
+		case P1xP2Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(1.-zeta*zeta);
+			return;
+		case P2Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(2.*gauss->coord1-1.)*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(2.*gauss->coord2-1.)*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(2.*gauss->coord3-1.)*(1.-zeta*zeta);
+			/*mid-sides of triangles*/
+			basis[ 9]=4.*gauss->coord3*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[10]=4.*gauss->coord3*gauss->coord1*zeta*(zeta-1.)/2.;
+			basis[11]=4.*gauss->coord1*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[12]=4.*gauss->coord3*gauss->coord2*zeta*(zeta+1.)/2.;
+			basis[13]=4.*gauss->coord3*gauss->coord1*zeta*(zeta+1.)/2.;
+			basis[14]=4.*gauss->coord1*gauss->coord2*zeta*(zeta+1.)/2.;
+			/*quad faces*/
+			basis[15]=4.*gauss->coord3*gauss->coord2*(1.-zeta*zeta);
+			basis[16]=4.*gauss->coord3*gauss->coord1*(1.-zeta*zeta);
+			basis[17]=4.*gauss->coord1*gauss->coord2*(1.-zeta*zeta);
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(2.*gauss->coord1-1.)*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(2.*gauss->coord2-1.)*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(2.*gauss->coord3-1.)*(1.-zeta*zeta);
+			/*mid-sides of triangles*/
+			basis[ 9]=4.*gauss->coord3*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[10]=4.*gauss->coord3*gauss->coord1*zeta*(zeta-1.)/2.;
+			basis[11]=4.*gauss->coord1*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[12]=4.*gauss->coord3*gauss->coord2*zeta*(zeta+1.)/2.;
+			basis[13]=4.*gauss->coord3*gauss->coord1*zeta*(zeta+1.)/2.;
+			basis[14]=4.*gauss->coord1*gauss->coord2*zeta*(zeta+1.)/2.;
+			/*quad faces*/
+			basis[15]=4.*gauss->coord3*gauss->coord2*(1.-zeta*zeta);
+			basis[16]=4.*gauss->coord3*gauss->coord1*(1.-zeta*zeta);
+			basis[17]=4.*gauss->coord1*gauss->coord2*(1.-zeta*zeta);
+			/*bubble*/
+			basis[18]=27.*gauss->coord1*gauss->coord2*gauss->coord3*(1.+zeta)*(1.-zeta);
+			return;
+		case P2xP4Enum :
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(2.*gauss->coord1-1)*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[ 7]=gauss->coord2*(2.*gauss->coord2-1)*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[ 8]=gauss->coord3*(2.*gauss->coord3-1)*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			/*mid-sides of triangles*/
+			basis[ 9]=4.*gauss->coord2*gauss->coord3*(2./3.)*(zeta-1.)*(zeta-0.5)*zeta*(zeta+0.5);
+			basis[10]=4.*gauss->coord1*gauss->coord3*(2./3.)*(zeta-1.)*(zeta-0.5)*zeta*(zeta+0.5);
+			basis[11]=4.*gauss->coord1*gauss->coord2*(2./3.)*(zeta-1.)*(zeta-0.5)*zeta*(zeta+0.5);
+			basis[12]=4.*gauss->coord2*gauss->coord3*(2./3.)*(zeta-0.5)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[13]=4.*gauss->coord1*gauss->coord3*(2./3.)*(zeta-0.5)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[14]=4.*gauss->coord1*gauss->coord2*(2./3.)*(zeta-0.5)*zeta*(zeta+0.5)*(zeta+1.);
+			/*quarter-sides of quads*/
+			basis[15]=gauss->coord1*(2.*gauss->coord1-1.)*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[16]=gauss->coord2*(2.*gauss->coord2-1.)*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[17]=gauss->coord3*(2.*gauss->coord3-1.)*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[18]=gauss->coord1*(2.*gauss->coord1-1.)*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[19]=gauss->coord2*(2.*gauss->coord2-1.)*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[20]=gauss->coord3*(2.*gauss->coord3-1.)*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			/* mid-sides of interior triangles*/
+			basis[21]=4.*gauss->coord2*gauss->coord3*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[22]=4.*gauss->coord1*gauss->coord3*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[23]=4.*gauss->coord1*gauss->coord2*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[24]=4.*gauss->coord2*gauss->coord3*4.*(zeta-1.0)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[25]=4.*gauss->coord1*gauss->coord3*4.*(zeta-1.0)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[26]=4.*gauss->coord1*gauss->coord2*4.*(zeta-1.0)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[27]=4.*gauss->coord2*gauss->coord3*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[28]=4.*gauss->coord1*gauss->coord3*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[29]=4.*gauss->coord1*gauss->coord2*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			return;
+		case P1xP3Enum :
+			/*Corner nodes*/
+			basis[ 0]=-(9.)/(16.)*gauss->coord1*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);	
+			basis[ 1]=-(9.)/(16.)*gauss->coord2*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);	
+			basis[ 2]=-(9.)/(16.)*gauss->coord3*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);	
+			basis[ 3]=(9.)/(16.)*gauss->coord1*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			basis[ 4]=(9.)/(16.)*gauss->coord2*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			basis[ 5]=(9.)/(16.)*gauss->coord3*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			/*quarter-sides of quads*/
+			basis[ 6]=(27.)/(16.)*gauss->coord1*(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			basis[ 7]=(27.)/(16.)*gauss->coord2*(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			basis[ 8]=(27.)/(16.)*gauss->coord3*(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			basis[ 9]=-(27.)/(16.)*gauss->coord1*(zeta-1)*(zeta+1./3.)*(zeta+1.);
+			basis[10]=-(27.)/(16.)*gauss->coord2*(zeta-1)*(zeta+1./3.)*(zeta+1.);
+			basis[11]=-(27.)/(16.)*gauss->coord3*(zeta-1)*(zeta+1./3.)*(zeta+1.);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+}
+/*}}}*/
+void PentaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv[3][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement);
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 *
+	 * [dhi/dx]= Jinv'*[dhi/dr]
+	 * [dhi/dy]        [dhi/ds]
+	 * [dhi/dz]        [dhi/dzeta]
+	 */
+
+	for(int i=0;i<numnodes;i++){
+		dbasis[numnodes*0+i]=Jinv[0][0]*dbasis_ref[0*numnodes+i]+Jinv[0][1]*dbasis_ref[1*numnodes+i]+Jinv[0][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*1+i]=Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i]+Jinv[1][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*2+i]=Jinv[2][0]*dbasis_ref[0*numnodes+i]+Jinv[2][1]*dbasis_ref[1*numnodes+i]+Jinv[2][2]*dbasis_ref[2*numnodes+i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+}
+/*}}}*/
+void PentaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss_in,int finiteelement){/*{{{*/
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss_in);
+
+	/*Cast gauss to GaussPenta*/
+	_assert_(gauss_in->Enum()==GaussPentaEnum);
+	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+
+	/*Get current coordinates in reference element*/
+	IssmDouble zeta=gauss->coord4;
+
+	switch(finiteelement){
+		case P0Enum: 
+			/*Zero derivative*/
+			dbasis[NUMNODESP0*0+0]   = 0.;
+			dbasis[NUMNODESP0*1+0]   = 0.;
+			dbasis[NUMNODESP0*2+0]   = 0.;
+			return;
+		case P1Enum: case P1DGEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1*0+0]   = (zeta-1.)/4.;
+			dbasis[NUMNODESP1*1+0]   = SQRT3/12.*(zeta-1.);
+			dbasis[NUMNODESP1*2+0]   = -.5*gauss->coord1;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1*0+1]   = (1.-zeta)/4.;
+			dbasis[NUMNODESP1*1+1]   = SQRT3/12.*(zeta-1);
+			dbasis[NUMNODESP1*2+1]   = -.5*gauss->coord2;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1*0+2]   = 0.;
+			dbasis[NUMNODESP1*1+2]   = SQRT3/6.*(1.-zeta);
+			dbasis[NUMNODESP1*2+2]   = -.5*gauss->coord3;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1*0+3]   = -(1.+zeta)/4.;
+			dbasis[NUMNODESP1*1+3]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1*2+3]   = .5*gauss->coord1;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP1*0+4]   = (1.+zeta)/4.;
+			dbasis[NUMNODESP1*1+4]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1*2+4]   = .5*gauss->coord2;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP1*0+5]   = 0.;
+			dbasis[NUMNODESP1*1+5]   = SQRT3/6.*(1.+zeta);
+			dbasis[NUMNODESP1*2+5]   = .5*gauss->coord3;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1b*0+0]   = (zeta-1.)/4.;
+			dbasis[NUMNODESP1b*1+0]   = SQRT3/12.*(zeta-1.);
+			dbasis[NUMNODESP1b*2+0]   = -.5*gauss->coord1;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1b*0+1]   = (1.-zeta)/4.;
+			dbasis[NUMNODESP1b*1+1]   = SQRT3/12.*(zeta-1);
+			dbasis[NUMNODESP1b*2+1]   = -.5*gauss->coord2;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1b*0+2]   = 0.;
+			dbasis[NUMNODESP1b*1+2]   = SQRT3/6.*(1.-zeta);
+			dbasis[NUMNODESP1b*2+2]   = -.5*gauss->coord3;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1b*0+3]   = -(1.+zeta)/4.;
+			dbasis[NUMNODESP1b*1+3]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+3]   = .5*gauss->coord1;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP1b*0+4]   = (1.+zeta)/4.;
+			dbasis[NUMNODESP1b*1+4]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+4]   = .5*gauss->coord2;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP1b*0+5]   = 0.;
+			dbasis[NUMNODESP1b*1+5]   = SQRT3/6.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+5]   = .5*gauss->coord3;
+			/*Nodal function 7*/
+			dbasis[NUMNODESP1b*0+6] = 27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP1b*1+6] = 27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			dbasis[NUMNODESP1b*2+6] = -54*gauss->coord1*gauss->coord2*gauss->coord3*zeta;
+			return;
+		case P2xP1Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2xP1*0+0 ] = .5*(1.-zeta)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2xP1*1+0 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+0 ] = -.5*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2xP1*0+1 ] = .5*(1.-zeta)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2xP1*1+1 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+1 ] = -.5*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2xP1*0+2 ] = 0.;
+			dbasis[NUMNODESP2xP1*1+2 ] = .5*(1.-zeta)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2xP1*2+2 ] = -.5*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2xP1*0+3 ] = .5*(1.+zeta)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2xP1*1+3 ] = .5*(1.+zeta)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+3 ] = .5*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2xP1*0+4 ] = .5*(1.+zeta)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2xP1*1+4 ] = .5*(1.+zeta)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+4 ] = .5*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2xP1*0+5 ] = 0.;
+			dbasis[NUMNODESP2xP1*1+5 ] = .5*(1.+zeta)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2xP1*2+5 ] = .5*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2xP1*0+6 ] = (1.-zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+6 ] = .5*(1.-zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+6 ] = -2.*gauss->coord3*gauss->coord2;
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2xP1*0+7 ] = -(1.-zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+7 ] = .5*(1.-zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+7 ] = -2.*gauss->coord3*gauss->coord1;
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2xP1*0+8 ] = (1.-zeta)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2xP1*1+8 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2xP1*2+8 ] = -2.*gauss->coord1*gauss->coord2;
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2xP1*0+9 ] = (1.+zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+9 ] = .5*(1.+zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+9 ] = 2.*gauss->coord3*gauss->coord2;
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2xP1*0+10] = -(1.+zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+10] = .5*(1.+zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+10] = 2.*gauss->coord3*gauss->coord1;
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2xP1*0+11] = (1.+zeta)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2xP1*1+11] = .5*(1.+zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2xP1*2+11] = 2.*gauss->coord1*gauss->coord2;
+			return;
+		case P1xP2Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1xP2*0+0]   = -zeta*(zeta-1.)/4.;
+			dbasis[NUMNODESP1xP2*1+0]   = -SQRT3/12.*zeta*(zeta-1.);
+			dbasis[NUMNODESP1xP2*2+0]   = .5*(2.*zeta-1.)*gauss->coord1;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1xP2*0+1]   = zeta*(zeta-1.)/4.;
+			dbasis[NUMNODESP1xP2*1+1]   = -SQRT3/12.*zeta*(zeta-1);
+			dbasis[NUMNODESP1xP2*2+1]   = .5*(2.*zeta-1.)*gauss->coord2;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1xP2*0+2]   = 0.;
+			dbasis[NUMNODESP1xP2*1+2]   = SQRT3/6.*zeta*(zeta-1.);
+			dbasis[NUMNODESP1xP2*2+2]   = .5*(2.*zeta-1.)*gauss->coord3;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1xP2*0+3]   = -zeta*(zeta+1)/4.;
+			dbasis[NUMNODESP1xP2*1+3]   = -SQRT3/12.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+3]   = .5*(2.*zeta+1.)*gauss->coord1;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP1xP2*0+4]   = zeta*(zeta+1.)/4.;
+			dbasis[NUMNODESP1xP2*1+4]   = -SQRT3/12.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+4]   = .5*(2.*zeta+1.)*gauss->coord2;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP1xP2*0+5]   = 0.;
+			dbasis[NUMNODESP1xP2*1+5]   = SQRT3/6.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+5]   = .5*(2.*zeta+1.)*gauss->coord3;
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP1xP2*0+6 ] = -0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*1+6 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+6 ] = -2.*zeta*gauss->coord1;
+			/*Nodal function 8*/
+			dbasis[NUMNODESP1xP2*0+7 ] = 0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*1+7 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+7 ] = -2.*zeta*gauss->coord2;
+			/*Nodal function 9*/
+			dbasis[NUMNODESP1xP2*0+8 ] = 0.;
+			dbasis[NUMNODESP1xP2*1+8 ] = SQRT3/3.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+8 ] = -2.*zeta*gauss->coord3;
+			return;
+		case P2Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2*0+0 ] = .5*zeta*(zeta-1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2*1+0 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+0 ] = .5*(2.*zeta-1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2*0+1 ] = .5*zeta*(zeta-1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2*1+1 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+1 ] = .5*(2.*zeta-1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2*0+2 ] = 0.;
+			dbasis[NUMNODESP2*1+2 ] = .5*zeta*(zeta-1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2*2+2 ] = .5*(2.*zeta-1.)*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2*0+3 ] = .5*zeta*(zeta+1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2*1+3 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+3 ] = .5*(2.*zeta+1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2*0+4 ] = .5*zeta*(zeta+1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2*1+4 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+4 ] = .5*(2.*zeta+1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2*0+5 ] = 0.;
+			dbasis[NUMNODESP2*1+5 ] = .5*zeta*(zeta+1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2*2+5 ] = .5*(2.*zeta+1.)*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2*0+6 ] = (-2.*gauss->coord1 + 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+6 ] = (-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+6 ] = -2.*zeta*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2*0+7 ] = (+2.*gauss->coord2 - 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+7 ] = (-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+7 ] = -2.*zeta*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2*0+8 ] = 0.;
+			dbasis[NUMNODESP2*1+8 ] = (+4.*SQRT3/3.*gauss->coord3 - SQRT3/3.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+8 ] = -2.*zeta*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2*0+9 ] = zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+9 ] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+9 ] = 2.*gauss->coord3*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2*0+10] = -zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+10] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+10] = 2.*gauss->coord3*gauss->coord1*(2.*zeta-1.);
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2*0+11] = zeta*(zeta-1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+11] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2*2+11] = 2.*gauss->coord1*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 13*/
+			dbasis[NUMNODESP2*0+12] = zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+12] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+12] = 2.*gauss->coord3*gauss->coord2*(2.*zeta+1.);
+			/*Nodal function 14*/
+			dbasis[NUMNODESP2*0+13] = -zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+13] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+13] = 2.*gauss->coord3*gauss->coord1*(2.*zeta+1.);
+			/*Nodal function 15*/
+			dbasis[NUMNODESP2*0+14] = zeta*(zeta+1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+14] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2*2+14] = 2.*gauss->coord1*gauss->coord2*(2.*zeta+1.);
+
+			/*Nodal function 16*/
+			dbasis[NUMNODESP2*0+15] = 2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+15] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+15] = -2.*zeta*4.*gauss->coord3*gauss->coord2;
+			/*Nodal function 17*/
+			dbasis[NUMNODESP2*0+16] = -2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+16] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+16] = -2.*zeta*4.*gauss->coord3*gauss->coord1;
+			/*Nodal function 18*/
+			dbasis[NUMNODESP2*0+17] = 2.*(gauss->coord1-gauss->coord2)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+17] = (1.-zeta*zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2*2+17] = -2.*zeta*4.*gauss->coord1*gauss->coord2;
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2b*0+0 ] = .5*zeta*(zeta-1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2b*1+0 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+0 ] = .5*(2.*zeta-1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2b*0+1 ] = .5*zeta*(zeta-1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2b*1+1 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+1 ] = .5*(2.*zeta-1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2b*0+2 ] = 0.;
+			dbasis[NUMNODESP2b*1+2 ] = .5*zeta*(zeta-1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2b*2+2 ] = .5*(2.*zeta-1.)*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2b*0+3 ] = .5*zeta*(zeta+1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2b*1+3 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+3 ] = .5*(2.*zeta+1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2b*0+4 ] = .5*zeta*(zeta+1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2b*1+4 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+4 ] = .5*(2.*zeta+1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2b*0+5 ] = 0.;
+			dbasis[NUMNODESP2b*1+5 ] = .5*zeta*(zeta+1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2b*2+5 ] = .5*(2.*zeta+1.)*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2b*0+6 ] = (-2.*gauss->coord1 + 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+6 ] = (-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+6 ] = -2.*zeta*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2b*0+7 ] = (+2.*gauss->coord2 - 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+7 ] = (-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+7 ] = -2.*zeta*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2b*0+8 ] = 0.;
+			dbasis[NUMNODESP2b*1+8 ] = (+4.*SQRT3/3.*gauss->coord3 - SQRT3/3.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+8 ] = -2.*zeta*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2b*0+9 ] = zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+9 ] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+9 ] = 2.*gauss->coord3*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2b*0+10] = -zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+10] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+10] = 2.*gauss->coord3*gauss->coord1*(2.*zeta-1.);
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2b*0+11] = zeta*(zeta-1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+11] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+11] = 2.*gauss->coord1*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 13*/
+			dbasis[NUMNODESP2b*0+12] = zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+12] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+12] = 2.*gauss->coord3*gauss->coord2*(2.*zeta+1.);
+			/*Nodal function 14*/
+			dbasis[NUMNODESP2b*0+13] = -zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+13] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+13] = 2.*gauss->coord3*gauss->coord1*(2.*zeta+1.);
+			/*Nodal function 15*/
+			dbasis[NUMNODESP2b*0+14] = zeta*(zeta+1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+14] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+14] = 2.*gauss->coord1*gauss->coord2*(2.*zeta+1.);
+
+			/*Nodal function 16*/
+			dbasis[NUMNODESP2b*0+15] = 2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+15] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+15] = -2.*zeta*4.*gauss->coord3*gauss->coord2;
+			/*Nodal function 17*/
+			dbasis[NUMNODESP2b*0+16] = -2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+16] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+16] = -2.*zeta*4.*gauss->coord3*gauss->coord1;
+			/*Nodal function 18*/
+			dbasis[NUMNODESP2b*0+17] = 2.*(gauss->coord1-gauss->coord2)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+17] = (1.-zeta*zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+17] = -2.*zeta*4.*gauss->coord1*gauss->coord2;
+
+			/*Nodal function 19*/
+			dbasis[NUMNODESP2b*0+18] = 27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP2b*1+18] = 27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			dbasis[NUMNODESP2b*2+18] = -54*gauss->coord1*gauss->coord2*gauss->coord3*zeta;
+			return;
+		case P2xP4Enum :
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2xP4*0+0 ] = (-2* gauss->coord1 + 0.5 ) *(2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*1+0 ] = (-((2.*SQRT3)/(3.))*gauss->coord1 + (SQRT3/6.) )*(2./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*2+0 ] =  gauss->coord1 *(2.* gauss->coord1 -1)* 2./3.*( (2.*zeta-1)*(zeta -0.5)*(zeta +0.5) + 2.* zeta *zeta *(zeta -1.)); 
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2xP4*0+1 ] = (2.*gauss->coord2 - 0.5 ) *(2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*1+1 ] = (-((2.*SQRT3)/(3.))*gauss->coord2 + (SQRT3/6.) )*(2./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*2+1 ] = gauss->coord2*(2.*gauss->coord2 -1.)* 2./3.* ((2.*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2. * zeta *zeta*(zeta -1.)); 
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2xP4*0+2 ] = 0. ; 
+			dbasis[NUMNODESP2xP4*1+2 ] = (((4.*SQRT3)/(3.))*gauss->coord3 - (SQRT3)/(3.))*(2./3.)*(zeta -1.)*(zeta-0.5)*(zeta)*(zeta+0.5); 
+			dbasis[NUMNODESP2xP4*2+2 ] = gauss->coord3*(2.* gauss->coord3 -1.)* 2./3.*( (2.*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta -1.)); 
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2xP4*0+3 ] = (-2.* gauss->coord1 + 0.5 ) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+3 ] = (-((2.*SQRT3)/(3.)) *gauss->coord1 + (SQRT3)/(6.) ) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*2+3 ] = gauss->coord1*(2.*gauss->coord1 -1.)* 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1.)); 
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2xP4*0+4 ] = (2*gauss->coord2 - 0.5 ) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+4 ] = (-((2.*SQRT3)/(3.)) *gauss->coord2 + (SQRT3/6.))*(2./3.)*(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. );
+			dbasis[NUMNODESP2xP4*2+4 ] = gauss->coord2 *(2.*gauss->coord2 -1.)* 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1.)); 
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2xP4*0+5 ] = 0. ; 
+			dbasis[NUMNODESP2xP4*1+5 ] = (((4.*SQRT3)/(3.))*gauss->coord3 - SQRT3/3. ) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*2+5 ] = gauss->coord3 *(2.*gauss->coord3 -1.)* 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1)); 
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2xP4*0+6 ] =  (-2.* gauss->coord1 + 0.5 ) * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+6 ] =  (-((2.*SQRT3)/(3.)) *gauss->coord1 + (SQRT3)/(6.) )* 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1.)  ; 
+			dbasis[NUMNODESP2xP4*2+6 ] =  gauss->coord1*(2.*gauss->coord1-1)* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2xP4*0+7 ] =  (2*gauss->coord2 - 0.5 )* 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+7 ] =  (-((2.*SQRT3)/(3.)) *gauss->coord2 + (SQRT3)/(6.)) * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. )  ; 
+			dbasis[NUMNODESP2xP4*2+7 ] =  gauss->coord2*(2.*gauss->coord2-1)* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2xP4*0+8 ] = 0. ; 
+			dbasis[NUMNODESP2xP4*1+8 ] = (((4.*SQRT3)/(3.))*gauss->coord3 - SQRT3/3. ) * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. )  ; 
+			dbasis[NUMNODESP2xP4*2+8 ] = gauss->coord3*(2.*gauss->coord3-1)* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2xP4*0+9 ] = 2.*gauss->coord3 * 2./3.*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*1+9 ] = (4.* SQRT3/3.* gauss->coord2- 2.*SQRT3/3. *gauss->coord3) *(2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP2xP4*2+9 ] = 4.* gauss->coord2 * gauss->coord3 *(2./3.)*((2.*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2.* zeta*zeta*(zeta -1.)); 
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2xP4*0+10] = -2.* gauss->coord3* 2./3.*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*1+10] = (4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3) * (2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP2xP4*2+10] = 4.* gauss->coord3*gauss->coord1 *(2./3.)*( (2*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2* zeta * zeta*(zeta -1));
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2xP4*0+11] = 2.* (gauss->coord1- gauss->coord2)* (2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5) ; 
+			dbasis[NUMNODESP2xP4*1+11] = -2.* SQRT3/3.*(gauss->coord2 +gauss->coord1) *(2./3.) *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP2xP4*2+11] = 4.* gauss->coord1*gauss->coord2 *(2./3.) *( (2.*zeta-1)*(zeta -0.5)*(zeta +0.5) + 2* zeta* zeta*(zeta -1));
+			/*Nodal function 13*/
+			dbasis[NUMNODESP2xP4*0+12] = 2.* gauss->coord3 * 2./3.*(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+12] = (4.*SQRT3/3.* gauss->coord2 - 2.*SQRT3/3. *gauss->coord3) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. );
+			dbasis[NUMNODESP2xP4*2+12] = 4.*gauss->coord2*gauss->coord3 *(2./3.)*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2*zeta*zeta*(zeta +1.)); 
+			/*Nodal function 14*/
+			dbasis[NUMNODESP2xP4*0+13] = - 2.*gauss->coord3* 2./3.*(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+13] = (4.*SQRT3/3.*gauss->coord1- 2.*SQRT3/3.*gauss->coord3) * (2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. );
+			dbasis[NUMNODESP2xP4*2+13] = 4.*gauss->coord3*gauss->coord1 *(2./3.)*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1.)); 
+			/*Nodal function 15*/
+			dbasis[NUMNODESP2xP4*0+14] = 2.* (gauss->coord1- gauss->coord2)* (2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+14] = -2.* SQRT3/3.*(gauss->coord2 +gauss->coord1) *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. );
+			dbasis[NUMNODESP2xP4*2+14] = 4.*gauss->coord1*gauss->coord2 *(2./3.)*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2* zeta *zeta*(zeta +1.)); 
+			/*Nodal function 16*/
+			dbasis[NUMNODESP2xP4*0+15] = (-2.* gauss->coord1 + 0.5 )* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+15] = (-2.*SQRT3/3. *gauss->coord1 + SQRT3/6.) * (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+15] = gauss->coord1*(2.*gauss->coord1-1) * (-8./3.)*((2.*zeta -1.)*(zeta-0.5)*(zeta +1.) +zeta*(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 17*/
+			dbasis[NUMNODESP2xP4*0+16] = (2*gauss->coord2 - 0.5 )* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+16] = (-2.*SQRT3/3. *gauss->coord2 + SQRT3/6.)* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+16] = gauss->coord2*(2.*gauss->coord2-1) * (-8./3.)*((2.*zeta -1.)*(zeta-0.5)*(zeta +1.) +zeta *(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 18*/
+			dbasis[NUMNODESP2xP4*0+17] = 0. ; 
+			dbasis[NUMNODESP2xP4*1+17] = (4.*SQRT3/3.*gauss->coord3 - SQRT3/3. )* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+17] = gauss->coord3*(2*gauss->coord3-1) * (-8./3.)*((2.*zeta-1.)*(zeta-0.5)*(zeta +1.) +zeta *(zeta -1.)*( 2.*zeta + 0.5));
+			/*Nodal function 19*/
+			dbasis[NUMNODESP2xP4*0+18] = (-2.* gauss->coord1 + 0.5 ) * (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+18] =  (-2.*SQRT3/3. *gauss->coord1 + SQRT3/6. )* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+18] = gauss->coord1*(2.*gauss->coord1-1) * (-8./3.)*((2.*zeta -1. ) *(zeta+0.5)* (zeta +1.) +  zeta* (zeta -1.)*( 2.*zeta + 3./2.));
+			/*Nodal function 20*/
+			dbasis[NUMNODESP2xP4*0+19] = (2*gauss->coord2 - 0.5 )* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*1+19] = (-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.) * (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+19] = gauss->coord2*(2.*gauss->coord2-1)* (-8./3.)*((2.*zeta -1. )*(zeta+0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 3./2.)); 
+			/*Nodal function 21*/
+			dbasis[NUMNODESP2xP4*0+20] = 0 ; 
+			dbasis[NUMNODESP2xP4*1+20] = (4.*SQRT3/3.*gauss->coord3 - SQRT3/3.)* (-8./3.)*(zeta - 1.)*(zeta + 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+20] = gauss->coord3*(2*gauss->coord3-1) * (-8./3.)*((2. *zeta -1. )*(zeta+0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 3./2.));
+			/*Nodal function 22*/
+			dbasis[NUMNODESP2xP4*0+21] = 2. *gauss->coord3 * (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+21] = (4.* SQRT3/3.*gauss->coord2- 2.*SQRT3/3.*gauss->coord3) * (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+21] = 4.*gauss->coord2 *gauss->coord3* (-8./3.)*((2.*zeta -1. )*(zeta-0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 23*/
+			dbasis[NUMNODESP2xP4*0+22] = -2. *gauss->coord3 *( -8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+22] = (4.* SQRT3/3.*gauss->coord1- 2.*SQRT3/3.*gauss->coord3 )*(-8./3.)*(zeta -1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+22] = 4.*gauss->coord1*gauss->coord3* (-8./3.)*((2.*zeta -1. )*(zeta-0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 24*/
+			dbasis[NUMNODESP2xP4*0+23] = 2.*(gauss->coord1- gauss->coord2) * (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+23] = -2.*SQRT3/3.*(gauss->coord2+ gauss->coord1) * (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+23] = 4.*gauss->coord1*gauss->coord2* (-8./3.)*((2.*zeta -1. )* (zeta-0.5) *(zeta +1.) +  zeta* (zeta -1.)*( 2.*zeta + 0.5));
+			/*Nodal function 25*/
+			dbasis[NUMNODESP2xP4*0+24] = 2. *gauss->coord3 *4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+24] = (4.*SQRT3/3.*gauss->coord2 - 2.* SQRT3/3. *gauss->coord3) *4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+24] = 4.* gauss->coord2 * gauss->coord3* 4.*( 4.* zeta*zeta*zeta - 5./2. *zeta ); 
+			/*Nodal function 26*/
+			dbasis[NUMNODESP2xP4*0+25] = -2. *gauss->coord3*4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+25] = (4.*SQRT3/3.*gauss->coord1- 2.*SQRT3/3.*gauss->coord3 )*4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+25] = 4. * gauss->coord1 * gauss->coord3 *4.*( 4. *zeta*zeta*zeta - 5./2.* zeta );
+			/*Nodal function 27*/
+			dbasis[NUMNODESP2xP4*0+26] = 2.*( gauss->coord1-gauss->coord2) * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+26] = -2.* SQRT3/3.*(gauss->coord1+ gauss->coord2 )*4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+26] = 4. *gauss->coord1 *gauss->coord2 *4.*( 4.* zeta*zeta*zeta - 5./2.*zeta ); 
+			/*Nodal function 28*/
+			dbasis[NUMNODESP2xP4*0+27] = 2.* gauss->coord3* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+27] = (4.*SQRT3/3.*gauss->coord2- 2.*SQRT3/3.*gauss->coord3) * (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+27] = 4.* gauss->coord2*gauss->coord3* (-8./3.)*((2.*zeta -1. )*(zeta+0.5)*(zeta +1.) +zeta*(zeta -1.)*( 2.*zeta + 3./2.)); 
+			/*Nodal function 29*/
+			dbasis[NUMNODESP2xP4*0+28] = -2.*gauss->coord3 *(-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+28] = (4.*SQRT3/3.*gauss->coord1- 2.*SQRT3/3.*gauss->coord3) * (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+28] = 4.* gauss->coord1*gauss->coord3* (-8./3.)*((2.*zeta -1. )*(zeta+0.5)*(zeta +1.) +zeta*(zeta -1.)*( 2.*zeta + 3./2.)); 
+			/*Nodal function 30*/
+			dbasis[NUMNODESP2xP4*0+29] = 2.*(gauss->coord1-gauss->coord2)* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP2xP4*1+29] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2) * (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP2xP4*2+29] = 4.* gauss->coord1*gauss->coord2 * (-8./3.)*((2.*zeta -1. )*(zeta+0.5)*(zeta +1) +zeta*(zeta -1.)*( 2.*zeta + 3./2.)); 
+			return;
+		case P1xP3Enum :
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1xP3*0+0 ] =  (9./32.)*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);
+			dbasis[NUMNODESP1xP3*1+0 ] = ((3.*SQRT3)/32.)*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);
+			dbasis[NUMNODESP1xP3*2+0 ] =- (9./16.)* gauss->coord1 *( 2. *zeta *( zeta -1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1xP3*0+1 ] = - (9./32.)*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);
+			dbasis[NUMNODESP1xP3*1+1 ] = ((3.*SQRT3)/32.) *(zeta-1)*(zeta-1./3.)*(zeta+1./3.);
+			dbasis[NUMNODESP1xP3*2+1 ] =- (9./16.)*gauss->coord2 *( 2.* zeta* ( zeta -1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1xP3*0+2 ] =  0.;
+			dbasis[NUMNODESP1xP3*1+2 ] = - ((3.*SQRT3)/16.)*(zeta-1)*(zeta-1./3.)*(zeta+1./3.);
+			dbasis[NUMNODESP1xP3*2+2 ] = - (9./16.)* gauss->coord3* ( 2. *zeta *( zeta -1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 4*/	 
+			dbasis[NUMNODESP1xP3*0+3 ] = -  (9./32.)*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*1+3 ] =  -((3.*SQRT3)/32.) *(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+3 ] = (9./16.)* gauss->coord1*( 2.* zeta *( zeta +1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 5*/	
+			dbasis[NUMNODESP1xP3*0+4 ] =   (9./32.)* (zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*1+4 ] = - ((3.*SQRT3)/32.) *(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+4 ] = (9./16.)* gauss->coord2* ( 2.* zeta *( zeta +1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 6*/	
+			dbasis[NUMNODESP1xP3*0+5 ] =  0.;
+			dbasis[NUMNODESP1xP3*1+5 ] =  ((3.*SQRT3)/16.)  *(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+5 ] =  (9./16.)* gauss->coord3 *( 2.* zeta * ( zeta  + 1. ) + ( zeta - (1./3.) )*( zeta + (1./3.) ));
+			/*Nodal function 7*/	
+			dbasis[NUMNODESP1xP3*0+6 ] = -  (27./32.) *(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*1+6 ] = -  (9.*SQRT3/32.) *(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+6 ] =  gauss->coord1*(27./16.)*( 2.* zeta *( zeta - (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			/*Nodal function 8*/	
+			dbasis[NUMNODESP1xP3*0+7 ] =  (27./32.) *(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*1+7 ] = -((9.*SQRT3)/32.) *(zeta-1)*(zeta-1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+7 ] =  gauss->coord2*(27./16.)*( 2.* zeta *( zeta - (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			/*Nodal function 9*/	
+			dbasis[NUMNODESP1xP3*0+8 ] = 0.;
+			dbasis[NUMNODESP1xP3*1+8 ] =  ((9.*SQRT3)/16.) *(zeta-1.)*(zeta-1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+8 ] =  gauss->coord3*(27./16.)*( 2. *zeta *( zeta - (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			/*Nodal function 10*/	
+			dbasis[NUMNODESP1xP3*0+9 ] = (27./32.) *(zeta-1.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*1+9 ] = ((9.*SQRT3)/32.) *(zeta-1.)*(zeta+1./3.)*(zeta+1.);
+			dbasis[NUMNODESP1xP3*2+9 ] =  -gauss->coord1 *(27./16.)*( 2* zeta *( zeta + (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			/*Nodal function 11*/	
+			dbasis[NUMNODESP1xP3*0+10] = - (27./32.) *(zeta-1)*(zeta+1./3.)*(zeta+1);
+			dbasis[NUMNODESP1xP3*1+10] = ((9.*SQRT3)/32.)  *(zeta-1.)*(zeta+1./3.)*(zeta+1);
+			dbasis[NUMNODESP1xP3*2+10] = -gauss->coord2 *(27./16.) *( 2.* zeta *( zeta + (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			/*Nodal function 12*/	
+			dbasis[NUMNODESP1xP3*0+11] = 0.;
+			dbasis[NUMNODESP1xP3*1+11] = -((9.*SQRT3)/16.) *(zeta-1.)*(zeta+1./3.)*(zeta+1);
+			dbasis[NUMNODESP1xP3*2+11] = -gauss->coord3 *(27./16.)*( 2.* zeta *( zeta + (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+void PentaRef::GetQuadJacobianDeterminant(IssmDouble* Jdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	IssmDouble x1,x2,x3,x4,y1,y2,y3,y4,z1,z2,z3,z4;
+
+	x1=xyz_list[0*3+0];
+	y1=xyz_list[0*3+1];
+	z1=xyz_list[0*3+2];
+	x2=xyz_list[1*3+0];
+	y2=xyz_list[1*3+1];
+	z2=xyz_list[1*3+2];
+	x3=xyz_list[2*3+0];
+	y3=xyz_list[2*3+1];
+	z3=xyz_list[2*3+2];
+	x4=xyz_list[3*3+0];
+	y4=xyz_list[3*3+1];
+	z4=xyz_list[3*3+2];
+
+	/*Jdet = (Area of the trapezoid)/(Area trapezoid ref) with AreaRef = 4*/
+	/*Area of a trabezoid = altitude * (base1 + base2)/2 */
+	*Jdet= sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) * (z4-z1 + z3-z2)/8.;
+	if(*Jdet<0.) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*pvalue = value;
+
+}
+/*}}}*/
+void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
+	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
+	 * gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+	IssmDouble dpz=0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	p[0]=dpx;
+	p[1]=dpy;
+	p[2]=dpz;
+
+}
+/*}}}*/
+int  PentaRef::NumberofNodes(int finiteelement){/*{{{*/
+
+	switch(finiteelement){
+		case NoneEnum:              return 0;
+		case P0Enum:                return NUMNODESP0;
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		case P1bubbleEnum:          return NUMNODESP1b;
+		case P1bubblecondensedEnum: return NUMNODESP1b;
+		case P2Enum:                return NUMNODESP2;
+		case P2bubbleEnum:          return NUMNODESP2b;
+		case P2bubblecondensedEnum: return NUMNODESP2b;
+		case P2xP1Enum:             return NUMNODESP2xP1;
+		case P1xP2Enum:             return NUMNODESP1xP2;
+		case P2xP4Enum:             return NUMNODESP2xP4;
+		case P1xP3Enum:             return NUMNODESP1xP3;
+		case P1P1Enum:              return NUMNODESP1*2;
+		case P1P1GLSEnum:           return NUMNODESP1*2;
+		case MINIcondensedEnum:     return NUMNODESP1b+NUMNODESP1;
+		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
+		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:      return NUMNODESP2;
+		case OneLayerP4zEnum:       return NUMNODESP2xP4+NUMNODESP1;
+		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
+		default:       _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  PentaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1bubbleEnum;
+		case MINIEnum:           return P1bubbleEnum;
+		case TaylorHoodEnum:     return P2Enum;
+		case LATaylorHoodEnum:   return P2Enum;
+		case OneLayerP4zEnum:    return P2xP4Enum;
+		case CrouzeixRaviartEnum:return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  PentaRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1Enum;
+		case MINIEnum:           return P1Enum;
+		case TaylorHoodEnum:     return P1Enum;
+		case LATaylorHoodEnum:   return NoneEnum;
+		case OneLayerP4zEnum:    return P1Enum;
+		case CrouzeixRaviartEnum:return P1DGEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  PentaRef::TensorInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum:    return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+void PentaRef::BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
+
+	/*Output*/
+	int  numindices;
+	int* indices = NULL;
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P2xP1Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 6;
+			indices[4] = 7;
+			indices[5] = 8;
+			break;
+		case P1xP2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P1xP3Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P2Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P2bubbleEnum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P2xP4Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
+void PentaRef::SurfaceNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
+
+	/*Output*/
+	int  numindices;
+	int* indices = NULL;
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		case P2xP1Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P1xP2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			return;
+		case P2Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			indices[3] = 12;
+			indices[4] = 13;
+			indices[5] = 14;
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/PentaRef.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*!\file:  PentaRef.h
+ * \brief abstract class for handling Penta oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _PENTAREF_H_
+#define _PENTAREF_H_
+
+class Gauss;
+class PentaRef{
+
+	public: 
+		PentaRef();
+		~PentaRef();
+
+		/*Numerics*/
+		void GetNodalFunctions(IssmDouble* basis, Gauss* gauss,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
+		void GetQuadJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
+		void GetLprimeFSSSA(IssmDouble* LprimeFSSSA, IssmDouble* xyz_list, Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, Gauss* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+
+		void BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
+		void SurfaceNodeIndices(int* pnumindices,int** pindices,int finiteelement);
+		int  NumberofNodes(int finiteelement);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.cpp	(revision 18231)
@@ -0,0 +1,212 @@
+/*!\file Seg.cpp
+ * \brief: implementation of the Segment object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+/*Constructors/destructor/copy*/
+Seg::Seg(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
+		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+
+			/*id: */
+			this->id  = seg_id;
+			this->sid = seg_sid;
+
+			//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+			this->parameters = NULL;
+
+			/*intialize inputs: */
+			this->inputs  = new Inputs();
+
+			/*initialize pointers:*/
+			this->nodes    = NULL;
+			this->vertices = NULL;
+			this->material = NULL;
+			this->matpar   = NULL;
+
+			/*Only allocate pointer*/
+			this->element_type_list=xNew<int>(nummodels);
+		}
+/*}}}*/
+Seg::~Seg(){/*{{{*/
+	this->parameters=NULL;
+}
+/*}}}*/
+Object* Seg::copy(){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+
+IssmDouble Seg::CharacteristicLength(void){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble x1,y1,x2,y2;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x1=xyz_list[0][0]; y1=xyz_list[0][1];
+	x2=xyz_list[1][0]; y2=xyz_list[1][1];
+
+	return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
+}
+/*}}}*/
+int        Seg::FiniteElement(void){/*{{{*/
+	return this->element_type;
+}
+/*}}}*/
+int        Seg::ObjectEnum(void){/*{{{*/
+
+	return SegEnum;
+
+}
+/*}}}*/
+void       Seg::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	
+	/* Intermediaries */
+	int nrfrontnodes,index;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+	/* Get nodes where there is no ice */
+	nrfrontnodes=0;
+	for(int i=0;i<NUMVERTICES;i++){
+		if(levelset[i]>=0.){
+			index=i;
+			nrfrontnodes++;
+		}
+	}
+
+	_assert_(nrfrontnodes==1);
+
+	IssmDouble* xyz_front = xNew<IssmDouble>(3);
+
+	/* Return nodes */
+	for(int dir=0;dir<3;dir++){
+		xyz_front[dir]=xyz_list[3*index+dir];
+	}
+
+	*pxyz_front=xyz_front;
+}/*}}}*/
+void       Seg::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P1Enum);
+
+}
+/*}}}*/
+int        Seg::GetNumberOfNodes(void){/*{{{*/
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int        Seg::GetNumberOfVertices(void){/*{{{*/
+	return NUMVERTICES;
+}
+/*}}}*/
+void       Seg::GetVerticesCoordinates(IssmDouble** pxyz_list){/*{{{*/
+
+	IssmDouble* xyz_list = xNew<IssmDouble>(NUMVERTICES*3);
+	::GetVerticesCoordinates(xyz_list,this->vertices,NUMVERTICES);
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list;
+
+}/*}}}*/
+bool       Seg::IsIcefront(void){/*{{{*/
+
+	bool isicefront;
+	int i,nrice;
+	IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	isicefront=false;
+	if(IsIceInElement()){
+		nrice=0;       
+		for(i=0;i<NUMVERTICES;i++)
+		 if(ls[i]<0.) nrice++;
+		if(nrice==1) isicefront= true;
+	}
+	return isicefront;
+}/*}}}*/
+void       Seg::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetJacobianDeterminant(pJdet,xyz_list,(GaussSeg*)gauss);
+
+}
+/*}}}*/
+void       Seg::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	*pJdet = 1.;
+
+}
+/*}}}*/
+Gauss*     Seg::NewGauss(void){/*{{{*/
+	return new GaussSeg();
+}
+/*}}}*/
+Gauss*     Seg::NewGauss(int order){/*{{{*/
+	return new GaussSeg(order);
+}
+/*}}}*/
+Gauss*     Seg::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){/*{{{*/
+
+	/*Output*/
+	Gauss* gauss = NULL;
+
+	if(xyz_list_front[0] == xyz_list[0]){
+		gauss = new GaussSeg(-1.);
+	}
+	else if(xyz_list_front[0] == xyz_list[3*1+0]){
+		gauss = new GaussSeg(+1.);
+	}
+	else{
+		_error_("front is not located on element edge");
+	}
+
+	return gauss;
+}
+/*}}}*/
+void       Seg::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Seg::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussSeg*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Seg::NormalSection(IssmDouble* normal,IssmDouble* xyz_list_front){/*{{{*/
+
+	IssmDouble* xyz_list = xNew<IssmDouble>(NUMVERTICES*3);
+	::GetVerticesCoordinates(xyz_list,this->vertices,NUMVERTICES);
+
+	if(xyz_list_front[0]>xyz_list[0])
+	 normal[0]= + 1.;
+	else
+	 normal[0]= - 1.;
+
+	xDelete<IssmDouble>(xyz_list);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Seg.h	(revision 18231)
@@ -0,0 +1,167 @@
+/*! \file Seg.h 
+ *  \brief: header file for seg object
+ */
+
+#ifndef _SEG_H_
+#define _SEG_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./SegRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Results;
+class Node;
+class Material;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+class Vertex;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Seg: public Element,public ElementHook,public SegRef{
+
+	public:
+
+		/*Seg constructors, destructors {{{*/
+		Seg(){};
+		Seg(int seg_id,int seg_sid,int i, IoModel* iomodel,int nummodels);
+		~Seg();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void  InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
+#endif
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		void        AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
+		void        AddInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
+		IssmDouble  CharacteristicLength(void);
+		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
+		void        ComputeSigmaNN(){_error_("not implemented yet");};
+		void        ComputeStressTensor(){_error_("not implemented yet");};
+		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
+		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        Delta18oParameterization(void){_error_("not implemented yet");};
+		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){_error_("not implemented yet");};
+		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
+		int         FiniteElement(void);
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		int         GetNodeIndex(Node* node){_error_("not implemented yet");};
+		int         GetNumberOfNodes(void);
+		int         GetNumberOfVertices(void);
+		void        GetVerticesCoordinates(IssmDouble** pxyz_list);
+		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list){_error_("not implemented yet");};
+		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list){_error_("not implemented yet");};
+		bool        IsOnBase(){_error_("not implemented yet");};
+		bool        IsOnSurface(){_error_("not implemented yet");};
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
+		void        JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){_error_("not implemented yet");};
+		void        JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){_error_("not implemented yet");};
+		IssmDouble  MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
+		int         NumberofNodesVelocity(void){_error_("not implemented yet");};
+		int         NumberofNodesPressure(void){_error_("not implemented yet");};
+	   Element*    SpawnBasalElement(void){_error_("not implemented yet");};
+		Element*    SpawnTopElement(void){_error_("not implemented yet");};
+		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		int         PressureInterpolation(void){_error_("not implemented yet");};
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){_error_("not implemented yet");};
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		int         VelocityInterpolation(void){_error_("not implemented yet");};
+		int         TensorInterpolation(void){_error_("not implemented yet");};
+		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
+		Node*       GetNode(int node_number){_error_("Not implemented");};
+		int         GetElementType(void){_error_("not implemented yet");};
+		Gauss*      NewGauss(void);
+		Gauss*      NewGauss(int order);
+      Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order);
+      Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){_error_("not implemented yet");};
+      Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){_error_("not implemented yet");};
+		Gauss*      NewGaussBase(int order){_error_("not implemented yet");};
+		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
+		Gauss*      NewGaussTop(int order){_error_("not implemented yet");};
+		int         VertexConnectivity(int vertexindex){_error_("not implemented yet");};
+		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
+		void        ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not implemented yet");};
+		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
+		bool		   IsIcefront(void);
+		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
+		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented");};
+		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
+		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){_error_("not implemented yet");};
+		void        ResetFSBasalBoundaryCondition(void){_error_("not implemented yet");};
+		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){_error_("not implemented yet");};
+		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
+		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
+		void UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
+		void UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
+
+		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
+		IssmDouble IceVolume(void){_error_("not implemented yet");};
+		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		IssmDouble TotalSmb(void){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
+		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
+		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
+
+#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
+#endif
+
+		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
+		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
+		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
+		void       InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+
+		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding){_error_("not implemented yet");};
+		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+		/*}}}*/
+};
+#endif  /* _SEG_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.cpp	(revision 18231)
@@ -0,0 +1,201 @@
+/*!\file SegRef.c
+ * \brief: implementation of the SegRef object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP0  1
+#define NUMNODESP1  2
+
+/*Object constructors and destructor*/
+SegRef::SegRef(){/*{{{*/
+}
+/*}}}*/
+SegRef::~SegRef(){/*{{{*/
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	switch(finiteelement){
+		case P0Enum:
+			basis[0]=1.;
+			return;
+		case P1Enum: case P1DGEnum:
+			basis[0]=(1.-gauss->coord1)/2.;
+			basis[1]=(1.+gauss->coord1)/2.;
+			return;
+		case P2Enum:
+			basis[0]=(gauss->coord1-1.)*gauss->coord1/2.;
+			basis[1]=gauss->coord1*(1.+gauss->coord1)/2.;
+			basis[2]=(1.-gauss->coord1)*(1.+gauss->coord1);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+}
+/*}}}*/
+void SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){/*{{{*/
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv, xyz_list, gauss);
+
+	/*Build dbasis: 
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 */
+	for(int i=0;i<numnodes;i++){
+		dbasis[i] = Jinv*dbasis_ref[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+
+}
+/*}}}*/
+void SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss);
+
+	switch(finiteelement){
+		case P0Enum:
+			/*Nodal function 1*/
+			dbasis[0] = 0.;
+			break;
+		case P1Enum: case P1DGEnum:
+			/*Nodal function 1*/
+			dbasis[0] = -0.5;
+			/*Nodal function 2*/
+			dbasis[1] = 0.5;
+			return;
+		case P2Enum:
+			/*Nodal function 1*/
+			dbasis[0] = (gauss->coord1-1.)/2. + gauss->coord1/2.;
+			dbasis[1] = (1.+gauss->coord1)/2. + gauss->coord1/2.;
+			dbasis[2] = -2.*gauss->coord1;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){/*{{{*/
+
+	/*From node values of parameter p (plist[0],plist[1]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx
+	 *
+	 * p is a vector already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx = 0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(1*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	*p=dpx;
+
+}
+/*}}}*/
+void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){/*{{{*/
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*p = value;
+}
+/*}}}*/
+void SegRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size 1*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble x2=xyz_list[3*1+0];
+
+	*J=.5*fabs(x2-x1);
+}
+/*}}}*/
+void SegRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(Jdet, xyz_list, gauss);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void SegRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J;
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J, xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	*Jinv = 1./J;
+}
+/*}}}*/
+int  SegRef::NumberofNodes(int finiteelement){/*{{{*/
+
+	switch(finiteelement){
+		case P0Enum:                return NUMNODESP0;
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/SegRef.h	(revision 18231)
@@ -0,0 +1,28 @@
+
+/*!\file:  SegRef.h
+ * \brief abstract class for handling Seg oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _SEGREF_H_
+#define _SEGREF_H_
+
+class GaussSeg;
+
+class SegRef{
+
+	public: 
+		SegRef();
+		~SegRef();
+
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss);
+		void GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement);
+		int  NumberofNodes(int finiteelement);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.cpp	(revision 18231)
@@ -0,0 +1,997 @@
+/*!\file Tetra.cpp
+ * \brief: implementation of the Tetrament object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 4
+
+/*Constructors/destructor/copy*/
+Tetra::Tetra(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
+		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+
+			/*id: */
+			this->id  = seg_id;
+			this->sid = seg_sid;
+
+			//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+			this->parameters = NULL;
+
+			/*intialize inputs: */
+			this->inputs  = new Inputs();
+
+			/*initialize pointers:*/
+			this->nodes    = NULL;
+			this->vertices = NULL;
+			this->material = NULL;
+			this->matpar   = NULL;
+
+			/*Only allocate pointer*/
+			this->element_type_list=xNew<int>(nummodels);
+		}
+/*}}}*/
+Tetra::~Tetra(){/*{{{*/
+	this->parameters=NULL;
+}
+/*}}}*/
+Object* Tetra::copy() {/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+
+int      Tetra::FiniteElement(void){/*{{{*/
+	return this->element_type;
+} /*}}}*/
+int      Tetra::ObjectEnum(void){/*{{{*/
+
+	return TetraEnum;
+
+}/*}}}*/
+void     Tetra::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	/*Call inputs method*/
+	_assert_(this->inputs);
+	this->inputs->AddInput(new TetraInput(input_enum,values,interpolation_enum));
+}
+/*}}}*/
+void     Tetra::Configure(Elements* elementsin, Loads* loadsin, Nodes* nodesin,Vertices* verticesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	if (this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hvertices->configure(verticesin);
+	this->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->vertices          = (Vertex**)this->hvertices->deliverp();
+	this->material          = (Material*)this->hmaterial->delivers();
+	this->matpar            = (Matpar*)this->hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+}
+/*}}}*/
+void     Tetra::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xmin,ymin,zmin;
+	IssmDouble xmax,ymax,zmax;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=zmax-zmin;
+}
+/*}}}*/
+void     Tetra::FaceOnBaseIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[4][3] = {{0,1,2},{0,3,1},{1,3,2},{0,2,3}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+
+	for(int i=0;i<4;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1. && values[indices[i][2]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			*pindex3 = indices[i][2];
+			return;
+		}
+	}
+
+	_error_("Could not find 3 vertices on bed");
+}
+/*}}}*/
+void     Tetra::FaceOnSurfaceIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[4][3] = {{0,1,2},{0,3,1},{1,3,2},{0,2,3}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<4;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1. && values[indices[i][2]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			*pindex3 = indices[i][2];
+			return;
+		}
+	}
+
+	_error_("Could not find 3 vertices on bed");
+}
+/*}}}*/
+void     Tetra::FaceOnFrontIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[4][3] = {{0,1,2},{0,3,1},{1,3,2},{0,2,3}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MaskIceLevelsetEnum);
+
+	for(int i=0;i<4;i++){
+		if(values[indices[i][0]] == 0. && values[indices[i][1]] == 0. && values[indices[i][2]] == 0.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			*pindex3 = indices[i][2];
+			return;
+		}
+	}
+
+	_error_("Could not find 3 vertices on bed");
+}
+/*}}}*/
+int      Tetra::GetElementType(){/*{{{*/
+
+	/*return TetraRef field*/
+	return this->element_type;
+}
+/*}}}*/
+void     Tetra::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTetra* gauss=new GaussTetra();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+int      Tetra::GetNodeIndex(Node* node){/*{{{*/
+
+	_assert_(nodes);
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	for(int i=0;i<numnodes;i++){
+		if(node==nodes[i]) return i;
+	}
+	_error_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+int      Tetra::GetNumberOfNodes(void){/*{{{*/
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int      Tetra::GetNumberOfVertices(void){/*{{{*/
+	return NUMVERTICES;
+}
+/*}}}*/
+void     Tetra::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(3*3);
+	this->FaceOnBaseIndices(&indices[0],&indices[1],&indices[2]);
+	for(int i=0;i<3;i++) for(int j=0;j<3;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
+
+}/*}}}*/
+void     Tetra::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(3*3);
+	this->FaceOnSurfaceIndices(&indices[0],&indices[1],&indices[2]);
+	for(int i=0;i<3;i++) for(int j=0;j<3;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
+
+}/*}}}*/
+bool     Tetra::HasFaceOnBase(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+	sum = values[0]+values[1]+values[2]+values[3];
+
+	_assert_(sum==0. || sum==1. || sum==2. || sum==3.);
+
+	if(sum==3){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+bool     Tetra::HasFaceOnSurface(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+	sum = values[0]+values[1]+values[2]+values[3];
+
+	_assert_(sum==0. || sum==1. || sum==2. || sum==3.);
+
+	if(sum==3){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+void     Tetra::InputUpdateFromIoModel(int index,IoModel* iomodel){ /*{{{*/
+
+	/*Intermediaries*/
+	int         i,j;
+	int         tetra_vertex_ids[NUMVERTICES];
+	IssmDouble  nodeinputs[NUMVERTICES];
+	IssmDouble  cmmininputs[NUMVERTICES];
+	IssmDouble  cmmaxinputs[NUMVERTICES];
+
+	IssmDouble  yts;
+	bool    control_analysis;
+	int     num_control_type,num_responses;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	_assert_(iomodel->elements);
+	for(i=0;i<NUMVERTICES;i++){ 
+		tetra_vertex_ids[i]=iomodel->elements[NUMVERTICES*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[tetra_vertex_ids[j]-1]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(VxEnum)[tetra_vertex_ids[j]-1]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VxEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(VyEnum)[tetra_vertex_ids[j]-1]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VyEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[tetra_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+					if(iomodel->Data(MaterialsRheologyBEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[tetra_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case DamageDbarEnum:
+					if(iomodel->Data(DamageDEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(DamageDEnum)[tetra_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tetra_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(DamageDEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				default:
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
+			}
+		}
+	}
+
+	/*Need to know the type of approximation for this element*/
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
+	}
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)) {
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_responses;i++){
+			for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tetra_vertex_ids[j]-1)*num_responses+i];
+			datasetinput->AddInput(new TetraInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+void     Tetra::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){/*{{{*/
+
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TetraInput(enum_type,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}
+/*}}}*/
+bool     Tetra::IsOnBase(){/*{{{*/
+	return HasFaceOnBase();
+}
+/*}}}*/
+bool     Tetra::IsOnSurface(){/*{{{*/
+	return HasFaceOnSurface();
+}
+/*}}}*/
+bool     Tetra::IsIcefront(void){/*{{{*/
+
+	/*Retrieve all inputs and parameters*/
+	IssmDouble ls[NUMVERTICES];
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	if(IsIceInElement()){
+		int nrice=0;       
+		for(int i=0;i<NUMVERTICES;i++) if(ls[i]<0.) nrice++;
+		if(nrice==1) return true;
+	}
+	return false;
+}/*}}}*/
+void     Tetra::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetJacobianDeterminant(pJdet,xyz_list,(GaussTetra*)gauss);
+
+}
+/*}}}*/
+void     Tetra::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetJacobianDeterminantFace(pJdet,xyz_list,(GaussTetra*)gauss);
+
+}
+/*}}}*/
+void     Tetra::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetJacobianDeterminantFace(pJdet,xyz_list_base,(GaussTetra*)gauss);
+
+}
+/*}}}*/
+void     Tetra::JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetJacobianDeterminantFace(pJdet,xyz_list_base,(GaussTetra*)gauss);
+
+}
+/*}}}*/
+Gauss*   Tetra::NewGauss(void){/*{{{*/
+	return new GaussTetra();
+}
+/*}}}*/
+Gauss*   Tetra::NewGauss(int order){/*{{{*/
+	return new GaussTetra(order);
+}
+/*}}}*/
+Gauss*   Tetra::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
+	/*FIXME: this is messed up, should provide indices and not xyz_list!*/
+	int indices[3];
+	this->FaceOnFrontIndices(&indices[0],&indices[1],&indices[2]);
+	return new GaussTetra(indices[0],indices[1],indices[2],max(order_horiz,order_vert));
+}
+/*}}}*/
+Gauss*   Tetra::NewGaussBase(int order){/*{{{*/
+
+	int indices[3];
+	this->FaceOnBaseIndices(&indices[0],&indices[1],&indices[2]);
+	return new GaussTetra(indices[0],indices[1],indices[2],order);
+}
+/*}}}*/
+Gauss*   Tetra::NewGaussTop(int order){/*{{{*/
+
+	int indices[3];
+	this->FaceOnSurfaceIndices(&indices[0],&indices[1],&indices[2]);
+	return new GaussTetra(indices[0],indices[1],indices[2],order);
+}
+/*}}}*/
+void     Tetra::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->element_type);
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->TensorInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->element_type);
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble AB[3];
+	IssmDouble AC[3];
+	IssmDouble norm;
+
+	AB[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	AB[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+	AB[2]=xyz_list[1*3+2] - xyz_list[0*3+2];
+	AC[0]=xyz_list[2*3+0] - xyz_list[0*3+0];
+	AC[1]=xyz_list[2*3+1] - xyz_list[0*3+1];
+	AC[2]=xyz_list[2*3+2] - xyz_list[0*3+2];
+
+	cross(normal,AB,AC);
+	norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
+
+	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
+}
+/*}}}*/
+void     Tetra::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
+		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
+
+	/*Bed normal is opposite to surface normal*/
+	bed_normal[0]=-normal[0]/normal_norm;
+	bed_normal[1]=-normal[1]/normal_norm;
+	bed_normal[2]=-normal[2]/normal_norm;
+
+	_assert_(bed_normal[2]<0.);
+}
+/*}}}*/
+void     Tetra::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
+		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
+
+	top_normal[0]=normal[0]/normal_norm;
+	top_normal[1]=normal[1]/normal_norm;
+	top_normal[2]=normal[2]/normal_norm;
+	_assert_(top_normal[2]>0.);
+}
+/*}}}*/
+int      Tetra::NumberofNodesPressure(void){/*{{{*/
+	return TetraRef::NumberofNodes(this->PressureInterpolation());
+}
+/*}}}*/
+int      Tetra::NumberofNodesVelocity(void){/*{{{*/
+	return TetraRef::NumberofNodes(this->VelocityInterpolation());
+}
+/*}}}*/
+void     Tetra::ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){/*{{{*/
+
+	if(pe){
+		if(this->element_type==MINIcondensedEnum){
+			int indices[3]={12,13,14};
+			pe->StaticCondensation(Ke,3,&indices[0]);
+		}
+		else if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[4]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<4;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			pe->StaticCondensation(Ke,size,indices);
+			xDelete<int>(indices);
+		}
+	}
+
+	if(Ke){
+		if(this->element_type==MINIcondensedEnum){
+			int indices[3]={12,13,14};
+			Ke->StaticCondensation(3,&indices[0]);
+		}
+		else if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[4]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<4;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			Ke->StaticCondensation(size,indices);
+			xDelete<int>(indices);
+		}
+	}
+}
+/*}}}*/
+void     Tetra::ResetFSBasalBoundaryCondition(void){/*{{{*/
+
+	int numnodes = this->GetNumberOfNodes();
+
+	int          approximation;
+	IssmDouble*  vertexonbase= NULL;
+	IssmDouble   slopex,slopey,groundedice;
+	IssmDouble   xz_plane[6];
+
+	/*For FS only: we want the CS to be tangential to the bedrock*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(!HasNodeOnBase() ||  approximation!=FSApproximationEnum) return;
+
+	//printf("element number %i \n",this->id);
+	/*Get inputs*/
+	Input* slopex_input=inputs->GetInput(BedSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(BedSlopeYEnum); _assert_(slopey_input);
+	Input* groundedicelevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(groundedicelevelset_input);
+	vertexonbase = xNew<IssmDouble>(numnodes);
+	this->GetInputListOnNodesVelocity(&vertexonbase[0],MeshVertexonbaseEnum);
+
+	/*Loop over basal nodes and update their CS*/
+	GaussTetra* gauss = new GaussTetra();
+	for(int i=0;i<this->NumberofNodesVelocity();i++){
+
+		if(vertexonbase[i]==1){
+			gauss->GaussNode(this->VelocityInterpolation(),i);
+
+			slopex_input->GetInputValue(&slopex,gauss);
+			slopey_input->GetInputValue(&slopey,gauss);
+			groundedicelevelset_input->GetInputValue(&groundedice,gauss);
+
+			/*New X axis          New Z axis*/
+			xz_plane[0]=1.;       xz_plane[3]=-slopex;  
+			xz_plane[1]=0.;       xz_plane[4]=-slopey;  
+			xz_plane[2]=slopex;   xz_plane[5]=1.;          
+
+			if(groundedice>0){
+				if(this->nodes[i]->GetApproximation()==FSvelocityEnum){
+					this->nodes[i]->DofInSSet(2); //vz 
+				}
+				else _error_("Flow equation approximation"<<EnumToStringx(this->nodes[i]->GetApproximation())<<" not supported yet");
+			}
+			else{
+				if(this->nodes[i]->GetApproximation()==FSvelocityEnum){
+					this->nodes[i]->DofInFSet(2); //vz
+				}
+				else _error_("Flow equation approximation"<<EnumToStringx(this->nodes[i]->GetApproximation())<<" not supported yet");
+			}
+
+			XZvectorsToCoordinateSystem(&this->nodes[i]->coord_system[0][0],&xz_plane[0]);
+		}
+	}
+
+	/*cleanup*/
+	xDelete<IssmDouble>(vertexonbase);
+	delete gauss;
+}
+/*}}}*/
+void     Tetra::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
+Element* Tetra::SpawnBasalElement(void){/*{{{*/
+
+	_assert_(HasFaceOnBase());
+
+	int index1,index2,index3;
+	this->FaceOnBaseIndices(&index1,&index2,&index3);
+	return SpawnTria(index1,index2,index3);
+}/*}}}*/
+Element* Tetra::SpawnTopElement(void){/*{{{*/
+
+	_assert_(HasFaceOnSurface());
+
+	int index1,index2,index3;
+	this->FaceOnSurfaceIndices(&index1,&index2,&index3);
+	return SpawnTria(index1,index2,index3);
+}/*}}}*/
+Tria*    Tetra::SpawnTria(int index1,int index2,int index3){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Create Tria*/
+	Tria* tria=new Tria();
+	tria->id=this->id;
+	tria->inputs=(Inputs*)this->inputs->SpawnTriaInputs(index1,index2,index3);
+	tria->parameters=this->parameters;
+	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),index1,index2,index3);
+
+	/*Spawn material*/
+	tria->material=(Material*)this->material->copy2(tria);
+
+	/*recover nodes, material and matpar: */
+	tria->nodes    = (Node**)tria->hnodes[analysis_counter]->deliverp();
+	tria->vertices = (Vertex**)tria->hvertices->deliverp();
+	tria->matpar   = (Matpar*)tria->hmatpar->delivers();
+
+	/*Return new Tria*/
+	return tria;
+}
+/*}}}*/
+void     Tetra::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){ /*{{{*/
+
+	/*Intermediaries*/
+	int        i;
+	int        tetra_vertex_ids[6];
+	IssmDouble nodeinputs[6];
+	IssmDouble yts;
+	bool       dakota_analysis;
+	bool       isFS;
+	int        numnodes;
+	int*       tetra_node_ids = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Checks if debuging*/
+	_assert_(iomodel->elements);
+
+	/*Recover element type*/
+	this->element_type_list[analysis_counter]=finiteelement_type;
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<4;i++) tetra_vertex_ids[i]=iomodel->elements[4*index+i]; //ids for vertices are in the elements array from Matlab
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	switch(finiteelement_type){
+		case P1Enum:
+			numnodes         = 4;
+			tetra_node_ids   = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numnodes         = 5;
+			tetra_node_ids   = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+			break;
+		case P2Enum:
+			numnodes        = 10;
+			tetra_node_ids   = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+0]+1;
+			tetra_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+1]+1;
+			tetra_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+2]+1;
+			tetra_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+3]+1;
+			tetra_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+4]+1;
+			tetra_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+5]+1;
+			break;
+		case MINIEnum: case MINIcondensedEnum:
+			numnodes         = 9;
+			tetra_node_ids   = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+
+			tetra_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[4*index+0];
+			tetra_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[4*index+1];
+			tetra_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[4*index+2];
+			tetra_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[4*index+3];
+			break;
+		case TaylorHoodEnum:
+		case XTaylorHoodEnum:
+			numnodes        = 14;
+			tetra_node_ids  = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+0]+1;
+			tetra_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+1]+1;
+			tetra_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+2]+1;
+			tetra_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+3]+1;
+			tetra_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+4]+1;
+			tetra_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+5]+1;
+
+			tetra_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[4*index+0];
+			tetra_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[4*index+1];
+			tetra_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[4*index+2];
+			tetra_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[4*index+3];
+			break;
+		case LATaylorHoodEnum:
+			numnodes        = 10;
+			tetra_node_ids  = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+0]+1;
+			tetra_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+1]+1;
+			tetra_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+2]+1;
+			tetra_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+3]+1;
+			tetra_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+4]+1;
+			tetra_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+5]+1;
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
+	}
+
+	/*hooks: */
+	this->SetHookNodes(tetra_node_ids,numnodes,analysis_counter); this->nodes=NULL;
+	xDelete<int>(tetra_node_ids);
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+}
+/*}}}*/
+void     Tetra::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
+	TetraRef::GetInputValue(pvalue,values,gauss,P1Enum);
+}
+/*}}}*/
+int      Tetra::VelocityInterpolation(void){/*{{{*/
+	return TetraRef::VelocityInterpolation(this->element_type);
+}
+/*}}}*/
+void     Tetra::ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble phi;
+	IssmDouble viscosity;
+	IssmDouble epsilon[6];
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->StrainRateFS(&epsilon[0],xyz_list,(GaussTetra*)gauss,vx_input,vy_input,vz_input);
+	this->ViscosityFS(&viscosity,3,xyz_list,(GaussTetra*)gauss,vx_input,vy_input,vz_input);
+	GetPhi(&phi,&epsilon[0],viscosity);
+
+	/*Assign output pointer*/
+	*pphi = phi;
+}
+/*}}}*/
+int      Tetra::PressureInterpolation(void){/*{{{*/
+	return TetraRef::PressureInterpolation(this->element_type);
+}
+/*}}}*/
+int      Tetra::TensorInterpolation(void){/*{{{*/
+	return TetraRef::TensorInterpolation(this->element_type);
+}
+/*}}}*/
+void     Tetra::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	/*Compute portion of the element that is grounded*/ 
+
+	IssmDouble  levelset[NUMVERTICES];
+	IssmDouble* xyz_zero = xNew<IssmDouble>(3*3);
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	if(levelset[0]==0. && levelset[1]==0. && levelset[2]==0.){ 
+		xyz_zero[3*0+0]=xyz_list[0*3+0];
+		xyz_zero[3*0+1]=xyz_list[0*3+1];
+		xyz_zero[3*0+2]=xyz_list[0*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1*3+0];
+		xyz_zero[3*1+1]=xyz_list[1*3+1];
+		xyz_zero[3*1+2]=xyz_list[1*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[2*3+0];
+		xyz_zero[3*2+1]=xyz_list[2*3+1];
+		xyz_zero[3*2+2]=xyz_list[2*3+2];
+	}
+	else if(levelset[0]==0. && levelset[1]==0. && levelset[3]==0.){ 
+		xyz_zero[3*0+0]=xyz_list[0*3+0];
+		xyz_zero[3*0+1]=xyz_list[0*3+1];
+		xyz_zero[3*0+2]=xyz_list[0*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1*3+0];
+		xyz_zero[3*1+1]=xyz_list[1*3+1];
+		xyz_zero[3*1+2]=xyz_list[1*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3*3+0];
+		xyz_zero[3*2+1]=xyz_list[3*3+1];
+		xyz_zero[3*2+2]=xyz_list[3*3+2];
+	}
+	else if(levelset[1]==0. && levelset[2]==0. && levelset[3]==0.){ 
+		xyz_zero[3*0+0]=xyz_list[1*3+0];
+		xyz_zero[3*0+1]=xyz_list[1*3+1];
+		xyz_zero[3*0+2]=xyz_list[1*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2*3+0];
+		xyz_zero[3*1+1]=xyz_list[2*3+1];
+		xyz_zero[3*1+2]=xyz_list[2*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3*3+0];
+		xyz_zero[3*2+1]=xyz_list[3*3+1];
+		xyz_zero[3*2+2]=xyz_list[3*3+2];
+	}
+	else if(levelset[2]==0. && levelset[0]==0. && levelset[3]==0.){ 
+		xyz_zero[3*0+0]=xyz_list[2*3+0];
+		xyz_zero[3*0+1]=xyz_list[2*3+1];
+		xyz_zero[3*0+2]=xyz_list[2*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0*3+0];
+		xyz_zero[3*1+1]=xyz_list[0*3+1];
+		xyz_zero[3*1+2]=xyz_list[0*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3*3+0];
+		xyz_zero[3*2+1]=xyz_list[3*3+1];
+		xyz_zero[3*2+2]=xyz_list[3*3+2];
+	}
+	else _error_("Case not covered");
+
+	/*Assign output pointer*/
+	*pxyz_zero= xyz_zero;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tetra.h	(revision 18231)
@@ -0,0 +1,173 @@
+/*! \file Tetra.h 
+ *  \brief: header file for seg object
+ */
+
+#ifndef _TETRA_H_
+#define _TETRA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./TetraRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Results;
+class Node;
+class Material;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+class Vertex;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Tetra: public Element,public ElementHook,public TetraRef{
+
+	public:
+
+		/*Tetra constructors, destructors {{{*/
+		Tetra(){};
+		Tetra(int seg_id,int seg_sid,int i, IoModel* iomodel,int nummodels);
+		~Tetra();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void  InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum);
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
+#endif
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		void        AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
+		void        AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		IssmDouble  CharacteristicLength(void){_error_("not implemented yet");};
+		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
+		void        ComputeSigmaNN(){_error_("not implemented yet");};
+		void        ComputeStressTensor(){_error_("not implemented yet");};
+		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
+		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void        Delta18oParameterization(void){_error_("not implemented yet");};
+		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		void        FaceOnFrontIndices(int* pindex1,int* pindex2,int* pindex3);
+		void        FaceOnBaseIndices(int* pindex1,int* pindex2,int* pindex3);
+		void        FaceOnSurfaceIndices(int* pindex1,int* pindex2,int* pindex3);
+		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
+		int         FiniteElement(void);
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		int         GetNodeIndex(Node* node);
+		int         GetNumberOfNodes(void);
+		int         GetNumberOfVertices(void);
+		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
+		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+		bool        HasFaceOnBase();
+		bool        HasFaceOnSurface();
+		bool        IsOnBase();
+		bool        IsOnSurface();
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
+		void        JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		void        JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		IssmDouble  MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
+		int         NumberofNodesVelocity(void);
+		int         NumberofNodesPressure(void);
+	   Element*    SpawnBasalElement(void);
+		Element*    SpawnTopElement(void);
+		Tria*       SpawnTria(int index1,int index2,int index3);
+		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		int         PressureInterpolation(void);
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		int         VelocityInterpolation(void);
+		int         TensorInterpolation(void);
+		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		Node*       GetNode(int node_number){_error_("Not implemented");};
+		int         GetElementType(void);
+		Gauss*      NewGauss(void);
+		Gauss*      NewGauss(int order);
+      Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){_error_("not implemented yet");};
+      Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
+      Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){_error_("not implemented yet");};
+		Gauss*      NewGaussBase(int order);
+		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
+		Gauss*      NewGaussTop(int order);
+		int         VertexConnectivity(int vertexindex){_error_("not implemented yet");};
+		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
+		void        ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
+		bool		   IsIcefront(void);
+		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
+		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
+		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
+		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){_error_("not implemented yet");};
+		void        ResetFSBasalBoundaryCondition(void);
+		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
+		void UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
+		void UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
+
+		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
+		IssmDouble IceVolume(void){_error_("not implemented yet");};
+		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		IssmDouble TotalSmb(void){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
+		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
+		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
+
+#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
+#endif
+
+		IssmDouble DragCoefficientAbsGradient(void){_error_("not implemented yet");};
+		void       GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
+		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
+		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
+		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
+		void       InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+
+		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding){_error_("not implemented yet");};
+		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+		/*}}}*/
+};
+#endif  /* _TETRA_H_*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.cpp	(revision 18231)
@@ -0,0 +1,403 @@
+/*!\file TetraRef.c
+ * \brief: implementation of the TetraRef object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP0  1
+#define NUMNODESP1  4
+#define NUMNODESP1b 5
+#define NUMNODESP2  10
+
+/*Object constructors and destructor*/
+TetraRef::TetraRef(){/*{{{*/
+}
+/*}}}*/
+TetraRef::~TetraRef(){/*{{{*/
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+void TetraRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	/*Cast gauss to GaussTetra*/
+	_assert_(gauss_in->Enum()==GaussTetraEnum);
+	GaussTetra* gauss = dynamic_cast<GaussTetra*>(gauss_in);
+
+	switch(finiteelement){
+		case P0Enum:
+			basis[0]=1.;
+			return;
+		case P1Enum: case P1DGEnum:
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			basis[3]=gauss->coord4;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			basis[3]=gauss->coord4;
+			/*bubble*/
+			basis[4]=256.*gauss->coord1*gauss->coord2*gauss->coord3*gauss->coord4;
+			return;
+		case P2Enum:
+			/*Vertices*/
+			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
+			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
+			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			basis[3]=gauss->coord4*(2.*gauss->coord4-1.);
+			/*Edges*/
+			basis[4]=4.*gauss->coord2*gauss->coord3;
+			basis[5]=4.*gauss->coord1*gauss->coord3;
+			basis[6]=4.*gauss->coord1*gauss->coord2;
+			basis[7]=4.*gauss->coord2*gauss->coord4;
+			basis[8]=4.*gauss->coord3*gauss->coord4;
+			basis[9]=4.*gauss->coord1*gauss->coord4;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+}
+/*}}}*/
+void TetraRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv[3][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 *
+	 * [dhi/dx]= Jinv'*[dhi/dr]
+	 * [dhi/dy]        [dhi/ds]
+	 * [dhi/dz]        [dhi/dzeta]
+	 */
+
+	for(int i=0;i<numnodes;i++){
+		dbasis[numnodes*0+i]=Jinv[0][0]*dbasis_ref[0*numnodes+i]+Jinv[0][1]*dbasis_ref[1*numnodes+i]+Jinv[0][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*1+i]=Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i]+Jinv[1][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*2+i]=Jinv[2][0]*dbasis_ref[0*numnodes+i]+Jinv[2][1]*dbasis_ref[1*numnodes+i]+Jinv[2][2]*dbasis_ref[2*numnodes+i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+}
+/*}}}*/
+void TetraRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss);
+
+	switch(finiteelement){
+		case P0Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP0*0+0] = 0.;
+			dbasis[NUMNODESP0*1+0] = 0.;
+			dbasis[NUMNODESP0*2+0] = 0.;
+			return;
+		case P1Enum: case P1DGEnum:
+			dbasis[NUMNODESP1*0+0] = -1.;
+			dbasis[NUMNODESP1*1+0] = -1.;
+			dbasis[NUMNODESP1*2+0] = -1.;
+
+			dbasis[NUMNODESP1*0+1] = 1.;
+			dbasis[NUMNODESP1*1+1] = 0.;
+			dbasis[NUMNODESP1*2+1] = 0.;
+
+			dbasis[NUMNODESP1*0+2] = 0.;
+			dbasis[NUMNODESP1*1+2] = 1.;
+			dbasis[NUMNODESP1*2+2] = 0.;
+
+			dbasis[NUMNODESP1*0+3] = 0.;
+			dbasis[NUMNODESP1*1+3] = 0.;
+			dbasis[NUMNODESP1*2+3] = 1.;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			dbasis[NUMNODESP1b*0+0] = -1.;
+			dbasis[NUMNODESP1b*1+0] = -1.;
+			dbasis[NUMNODESP1b*2+0] = -1.;
+
+			dbasis[NUMNODESP1b*0+1] = 1.;
+			dbasis[NUMNODESP1b*1+1] = 0.;
+			dbasis[NUMNODESP1b*2+1] = 0.;
+
+			dbasis[NUMNODESP1b*0+2] = 0.;
+			dbasis[NUMNODESP1b*1+2] = 1.;
+			dbasis[NUMNODESP1b*2+2] = 0.;
+
+			dbasis[NUMNODESP1b*0+3] = 0.;
+			dbasis[NUMNODESP1b*1+3] = 0.;
+			dbasis[NUMNODESP1b*2+3] = 1.;
+
+			dbasis[NUMNODESP1b*0+4] = 256.*(-gauss->coord2*gauss->coord3*gauss->coord4+gauss->coord1*gauss->coord3*gauss->coord4);
+			dbasis[NUMNODESP1b*1+4] = 256.*(-gauss->coord2*gauss->coord3*gauss->coord4+gauss->coord1*gauss->coord2*gauss->coord4);
+			dbasis[NUMNODESP1b*2+4] = 256.*(-gauss->coord2*gauss->coord3*gauss->coord4+gauss->coord1*gauss->coord2*gauss->coord3);
+			return;
+		case P2Enum:
+			dbasis[NUMNODESP2*0+0] = -4.*gauss->coord1+1.;
+			dbasis[NUMNODESP2*1+0] = -4.*gauss->coord1+1.;
+			dbasis[NUMNODESP2*2+0] = -4.*gauss->coord1+1.;
+
+			dbasis[NUMNODESP2*0+1] = 4.*gauss->coord2-1.;
+			dbasis[NUMNODESP2*1+1] = 0.;
+			dbasis[NUMNODESP2*2+1] = 0.;
+
+			dbasis[NUMNODESP2*0+2] = 0.;
+			dbasis[NUMNODESP2*1+2] = 4.*gauss->coord3-1.;
+			dbasis[NUMNODESP2*2+2] = 0.;
+
+			dbasis[NUMNODESP2*0+3] = 0.;
+			dbasis[NUMNODESP2*1+3] = 0.;
+			dbasis[NUMNODESP2*2+3] = 4.*gauss->coord4-1.;
+
+			dbasis[NUMNODESP2*0+4] = 4.*gauss->coord3;
+			dbasis[NUMNODESP2*1+4] = 4.*gauss->coord2;
+			dbasis[NUMNODESP2*2+4] = 0.;
+
+			dbasis[NUMNODESP2*0+5] = -4.*gauss->coord3;
+			dbasis[NUMNODESP2*1+5] = 4.*(gauss->coord1-gauss->coord3);
+			dbasis[NUMNODESP2*2+5] = -4.*gauss->coord3;
+
+			dbasis[NUMNODESP2*0+6] = 4.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+6] = -4.*gauss->coord2;
+			dbasis[NUMNODESP2*2+6] = -4.*gauss->coord2;
+
+			dbasis[NUMNODESP2*0+7] = 4.*gauss->coord4;
+			dbasis[NUMNODESP2*1+7] = 0.;
+			dbasis[NUMNODESP2*2+7] = 4.*gauss->coord2;
+
+			dbasis[NUMNODESP2*0+8] = 0.;
+			dbasis[NUMNODESP2*1+8] = 4.*gauss->coord4;
+			dbasis[NUMNODESP2*2+8] = 4.*gauss->coord3;
+
+			dbasis[NUMNODESP2*0+9] = -4.*gauss->coord4;
+			dbasis[NUMNODESP2*1+9] = -4.*gauss->coord4;
+			dbasis[NUMNODESP2*2+9] = 4.*(gauss->coord1-gauss->coord4);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+void TetraRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
+	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
+	 * gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+	IssmDouble dpz=0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	p[0]=dpx;
+	p[1]=dpy;
+	p[2]=dpz;
+}
+/*}}}*/
+void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*p = value;
+}
+/*}}}*/
+void TetraRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size 1*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble x4=xyz_list[3*3+0];
+
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble y4=xyz_list[3*3+1];
+
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble z3=xyz_list[3*2+2];
+	IssmDouble z4=xyz_list[3*3+2];
+
+	J[NDOF3*0+0] = x2-x1;
+	J[NDOF3*0+1] = y2-y1;
+	J[NDOF3*0+2] = z2-z1;
+
+	J[NDOF3*1+0] = x3-x1;
+	J[NDOF3*1+1] = y3-y1;
+	J[NDOF3*1+2] = z3-z1;
+
+	J[NDOF3*2+0] = x4-x1;
+	J[NDOF3*2+1] = y4-y1;
+	J[NDOF3*2+2] = z4-z1;
+}
+/*}}}*/
+void TetraRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0],xyz_list, gauss);
+
+	/*Get Determinant*/
+	Matrix3x3Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void TetraRef::GetJacobianDeterminantFace(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble z3=xyz_list[3*2+2];
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+void TetraRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
+int  TetraRef::NumberofNodes(int finiteelement){/*{{{*/
+
+	switch(finiteelement){
+		case P0Enum:                return NUMNODESP0;
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		case P1bubbleEnum:          return NUMNODESP1b;
+		case P1bubblecondensedEnum: return NUMNODESP1b;
+		case P2Enum:                return NUMNODESP2;
+		case P1P1Enum:              return NUMNODESP1*2;
+		case P1P1GLSEnum:           return NUMNODESP1*2;
+		case MINIcondensedEnum:     return NUMNODESP1b+NUMNODESP1;
+		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
+		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:      return NUMNODESP2;
+		case XTaylorHoodEnum:       return NUMNODESP2+NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TetraRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1bubbleEnum;
+		case MINIEnum:          return P1bubbleEnum;
+		case TaylorHoodEnum:    return P2Enum;
+		case LATaylorHoodEnum:  return P2Enum;
+		case XTaylorHoodEnum:   return P2Enum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TetraRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1Enum;
+		case MINIEnum:          return P1Enum;
+		case TaylorHoodEnum:    return P1Enum;
+		case LATaylorHoodEnum:  return NoneEnum;
+		case XTaylorHoodEnum:   return P1Enum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}/*}}}*/
+int  TetraRef::TensorInterpolation(int fe_stokes){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum: return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TetraRef.h	(revision 18231)
@@ -0,0 +1,33 @@
+
+/*!\file:  TetraRef.h
+ * \brief abstract class for handling Tetra oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _TETRAREF_H_
+#define _TETRAREF_H_
+
+class GaussTetra;
+
+class TetraRef{
+
+	public: 
+		TetraRef();
+		~TetraRef();
+
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss);
+		void GetJacobianDeterminantFace(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss);
+		void GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussTetra* gauss);
+		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement);
+
+		int  NumberofNodes(int finiteelement);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.cpp	(revision 18231)
@@ -0,0 +1,3008 @@
+/*!\file Tria.cpp
+ * \brief: implementation of the Tria object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+#ifdef _HAVE_GIA_
+#include "../../modules/GiaDeflectionCorex/GiaDeflectionCorex.h"
+#endif
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   3
+#define NUMVERTICES1D 2
+
+/*Constructors/destructor/copy*/
+Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
+	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+
+		/*id: */
+		this->id  = tria_id;
+		this->sid = tria_sid;
+
+		//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+		this->parameters = NULL;
+
+		/*intialize inputs: */
+		this->inputs  = new Inputs();
+
+		/*initialize pointers:*/
+		this->nodes    = NULL;
+		this->vertices = NULL;
+		this->material = NULL;
+		this->matpar   = NULL;
+		this->element_type_list=xNew<int>(nummodels);
+}
+/*}}}*/
+Tria::~Tria(){/*{{{*/
+	this->parameters=NULL;
+}
+/*}}}*/
+Object* Tria::copy() {/*{{{*/
+
+	int i;
+	Tria* tria=NULL;
+
+	tria=new Tria();
+
+	//deal with TriaRef mother class
+	tria->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) tria->element_type_list[i]=this->element_type_list[i];
+
+	//deal with ElementHook mother class
+	tria->numanalyses=this->numanalyses;
+	tria->hnodes=new Hook*[tria->numanalyses];
+	for(i=0;i<tria->numanalyses;i++)tria->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	tria->hvertices = (Hook*)this->hvertices->copy();
+	tria->hmaterial = (Hook*)this->hmaterial->copy();
+	tria->hmatpar   = (Hook*)this->hmatpar->copy();
+
+	/*deal with Tria fields: */
+	tria->id  = this->id;
+	tria->sid = this->sid;
+	if(this->inputs){
+		tria->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		tria->inputs=new Inputs();
+	}
+	/*point parameters: */
+	tria->parameters=this->parameters;
+
+	/*recover objects: */
+	tria->nodes = xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
+
+	tria->vertices = (Vertex**)tria->hvertices->deliverp();
+	tria->material = (Material*)tria->hmaterial->delivers();
+	tria->matpar   = (Matpar*)tria->hmatpar->delivers();
+
+	return tria;
+}
+/*}}}*/
+
+/*Other*/
+void       Tria::AddBasalInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	/*Call inputs method*/
+	_assert_(this->inputs);
+	
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			this->inputs->AddInput(new TriaInput(input_enum,values,interpolation_enum));
+			break;
+		case Domain2DverticalEnum:{
+			if(interpolation_enum==P1Enum){
+				IssmDouble values2[NUMVERTICES]={0.};
+				int        numindices;
+				int       *indices = NULL;
+				int        index = this->EdgeOnBaseIndex();
+				NodeOnEdgeIndices(&numindices,&indices,index,this->FiniteElement());
+				for(int i=0;i<numindices;i++){
+					values2[indices[i]] = values[i];
+				}
+				this->inputs->AddInput(new TriaInput(input_enum,values2,interpolation_enum));
+				xDelete<int>(indices);
+			}
+			else _error_("not implemented yet");
+			}
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+void       Tria::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	/*Call inputs method*/
+	_assert_(this->inputs);
+	this->inputs->AddInput(new TriaInput(input_enum,values,interpolation_enum));
+}
+/*}}}*/
+IssmDouble Tria::CharacteristicLength(void){/*{{{*/
+
+	return sqrt(2*this->GetArea());
+}
+/*}}}*/
+void       Tria::ComputeBasalStress(Vector<IssmDouble>* eps){/*{{{*/
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+void       Tria::ComputeSigmaNN(){/*{{{*/
+
+	if(!IsOnBase()){
+		IssmDouble sigma_nn=0;
+		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn,P0Enum));
+		return;
+	}
+	else{
+		IssmDouble* xyz_list=NULL;
+		IssmDouble *xyz_list_base=NULL;
+		IssmDouble  pressure,viscosity,sigma_nn;
+		IssmDouble  sigma_xx,sigma_xy,sigma_yy;
+		IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+		IssmDouble  base_normal[2]; 
+		int domaintype,dim=2;
+
+		/* Get node coordinates and dof list: */
+		GetVerticesCoordinates(&xyz_list);
+	   GetVerticesCoordinatesBase(&xyz_list_base);
+
+		/*Retrieve all inputs we will be needing: */
+		this->FindParam(&domaintype,DomainTypeEnum);
+		if(domaintype==Domain2DhorizontalEnum) _error_("stress tensor calculation not supported for mesh of type " <<EnumToStringx(domaintype)<<", extrude mesh or call ComputeDeviatoricStressTensor");
+		Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+		Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+		Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+		/* Start looping on the number of vertices: */
+		Gauss* gauss=NewGaussBase(1);
+		gauss->GaussPoint(0);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		this->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,NULL);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy=2*viscosity*epsilon[1]-pressure;
+		sigma_xy=2*viscosity*epsilon[2];
+
+		/*Get normal vector to the bed */
+		NormalBase(&base_normal[0],xyz_list_base);
+
+		/*Compute sigma_nn*/
+		sigma_nn=sigma_xx*base_normal[0]*base_normal[0] + 2*sigma_xy*base_normal[0]*base_normal[1] + sigma_yy*base_normal[1]*base_normal[1];
+
+		/*Add Stress tensor components into inputs*/
+		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn,P0Enum));
+
+		/*Clean up and return*/
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(xyz_list_base);
+		delete gauss;
+	}
+}
+/*}}}*/
+void       Tria::ComputeStressTensor(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  pressure,viscosity;
+	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  sigma_xx[NUMVERTICES];
+	IssmDouble	sigma_yy[NUMVERTICES];
+	IssmDouble	sigma_zz[NUMVERTICES]={0,0,0};
+	IssmDouble  sigma_xy[NUMVERTICES];
+	IssmDouble	sigma_xz[NUMVERTICES]={0,0,0};
+	IssmDouble	sigma_yz[NUMVERTICES]={0,0,0};
+	GaussTria*  gauss=NULL;
+	int domaintype,dim=2;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	this->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype==Domain2DhorizontalEnum) _error_("stress tensor calculation not supported for mesh of type " <<EnumToStringx(domaintype)<<", extrude mesh or call ComputeDeviatoricStressTensor");
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->ViscositySSA(&viscosity,dim,&xyz_list[0][0],gauss,vx_input,vy_input);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[2];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new TriaInput(StressTensorxxEnum,&sigma_xx[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorxyEnum,&sigma_xy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorxzEnum,&sigma_xz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensoryyEnum,&sigma_yy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensoryzEnum,&sigma_yz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorzzEnum,&sigma_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+void       Tria::ComputeDeviatoricStressTensor(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  viscosity;
+	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  tau_xx[NUMVERTICES];
+	IssmDouble	tau_yy[NUMVERTICES];
+	IssmDouble	tau_zz[NUMVERTICES]={0,0,0};
+	IssmDouble  tau_xy[NUMVERTICES];
+	IssmDouble	tau_xz[NUMVERTICES]={0,0,0};
+	IssmDouble	tau_yz[NUMVERTICES]={0,0,0};
+	GaussTria*  gauss=NULL;
+	int domaintype,dim=2;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	this->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum) _error_("deviatoric stress tensor calculation not implemented for mesh of type " <<EnumToStringx(domaintype));
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate and viscosity: */
+		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->ViscositySSA(&viscosity,dim,&xyz_list[0][0],gauss,vx_input,vy_input);
+
+		/*Compute Stress*/
+		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps
+		tau_yy[iv]=2*viscosity*epsilon[1];
+		tau_xy[iv]=2*viscosity*epsilon[2];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxxEnum,&tau_xx[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxyEnum,&tau_xy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxzEnum,&tau_xz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressyyEnum,&tau_yy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressyzEnum,&tau_yz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStresszzEnum,&tau_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+void       Tria::Configure(Elements* elementsin, Loads* loadsin,Nodes* nodesin,Vertices *verticesin,Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	if(this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hvertices->configure(verticesin);
+	this->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->vertices = (Vertex**)this->hvertices->deliverp();
+	this->material = (Material*)this->hmaterial->delivers();
+	this->matpar   = (Matpar*)this->hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+
+}
+/*}}}*/
+void       Tria::Delta18oParameterization(void){/*{{{*/
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+
+	/*Recover parameters*/
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input* input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input* input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input* input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussTria* gauss=new GaussTria();
+	for(int month=0;month<12;month++){
+		for(int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		TriaInput* newmonthinput1 = new TriaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		TriaInput* newmonthinput2 = new TriaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Tria::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xmin,ymin;
+	IssmDouble xmax,ymax;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=0.;
+}
+/*}}}*/
+int        Tria::FiniteElement(void){/*{{{*/
+	return this->element_type;
+}
+/*}}}*/
+int        Tria::ObjectEnum(void){/*{{{*/
+
+	return TriaEnum;
+
+}
+/*}}}*/
+IssmDouble Tria::GetArea(void){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble x1,y1,x2,y2,x3,y3;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x1=xyz_list[0][0]; y1=xyz_list[0][1];
+	x2=xyz_list[1][0]; y2=xyz_list[1][1];
+	x3=xyz_list[2][0]; y3=xyz_list[2][1];
+
+	_assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
+	return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+}
+/*}}}*/
+void       Tria::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	int         i,j,k;
+	IssmDouble  area_init,area_portion;
+	IssmDouble  xyz_bis[NUMVERTICES][3];
+
+	area_init=GetArea();
+
+	/*Initialize xyz_list with original xyz_list of triangle coordinates*/
+	for(j=0;j<3;j++){ 
+		for(k=0;k<3;k++){
+			xyz_bis[j][k]=xyz_list[j*3+k];
+		}
+	}
+	for(i=0;i<numpoints;i++){
+		for(j=0;j<3;j++){ 
+			for(k=0;k<3;k++){
+				/*Change appropriate line*/
+				xyz_bis[j][k]=xyz_zero[i*3+k];
+			}
+
+			/*Compute area fraction*/
+			area_portion=fabs(xyz_bis[1][0]*xyz_bis[2][1] - xyz_bis[1][1]*xyz_bis[2][0] + xyz_bis[0][0]*xyz_bis[1][1] - xyz_bis[0][1]*xyz_bis[1][0] + xyz_bis[2][0]*xyz_bis[0][1] - xyz_bis[2][1]*xyz_bis[0][0])/2.;
+			*(area_coordinates+3*i+j)=area_portion/area_init;
+
+			/*Reinitialize xyz_list*/
+			for(k=0;k<3;k++){
+				/*Reinitialize xyz_list with original coordinates*/
+				xyz_bis[j][k]=xyz_list[j*3+k];
+			}
+		}
+	}
+}
+/*}}}*/
+int        Tria::GetElementType(){/*{{{*/
+
+	/*return TriaRef field*/
+	return this->element_type;
+
+}
+/*}}}*/
+void       Tria::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               floating=true;
+	int                point;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         f1,f2;
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are grounded or floating*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+		point=0;
+		f1=1.;
+		f2=1.;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		point=0;
+		f1=0.;
+		f2=0.;
+	}
+	else{
+		if(gl[0]*gl[1]*gl[2]<0) floating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			point=2;
+			f1=gl[2]/(gl[2]-gl[0]);
+			f2=gl[2]/(gl[2]-gl[1]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			point=0;
+			f1=gl[0]/(gl[0]-gl[1]);
+			f2=gl[0]/(gl[0]-gl[2]);
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			point=1;
+			f1=gl[1]/(gl[1]-gl[2]);
+			f2=gl[1]/(gl[1]-gl[0]);
+		}
+	}
+	*point1=point;
+	*fraction1=f1;
+	*fraction2=f2;
+	*mainlyfloating=floating;
+}
+/*}}}*/
+IssmDouble Tria::GetGroundedPortion(IssmDouble* xyz_list){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool              mainlyfloating = true;
+	int               domaintype,index1,index2;
+	const IssmPDouble epsilon        = 1.e-15;
+	IssmDouble        phi,s1,s2,area_init,area_grounded;
+	IssmDouble        gl[NUMVERTICES];
+	IssmDouble        xyz_bis[3][3];
+
+	/*Recover parameters and values*/
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	if(domaintype==Domain2DverticalEnum){
+		this->EdgeOnBaseIndices(&index1,&index2);
+		if(gl[index1]>0 && gl[index2]>0) phi=1; // All grounded
+		else if(gl[index1]<0 && gl[index2]<0) phi=0; // All floating
+		else if(gl[index1]<0 && gl[index2]>0){ //index2 grounded
+			phi=1./(1.-gl[index1]/gl[index2]);
+		}
+		else if(gl[index2]<0 && gl[index1]>0){ //index1 grounded
+			phi=1./(1.-gl[index2]/gl[index1]);
+		}
+
+	}
+	else if(domaintype==Domain2DhorizontalEnum || domaintype==Domain3DEnum){
+		/*Check that not all nodes are grounded or floating*/
+		if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+			phi=1;
+		}
+		else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+			phi=0;
+		}
+		else{
+			/*Figure out if two nodes are floating or grounded*/
+			if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
+
+			if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+				/*Coordinates of point 2: same as initial point 2*/
+				xyz_bis[2][0]=*(xyz_list+3*2+0);
+				xyz_bis[2][1]=*(xyz_list+3*2+1);
+				xyz_bis[2][2]=*(xyz_list+3*2+2);
+
+				/*Portion of the segments*/
+				s1=gl[2]/(gl[2]-gl[1]);
+				s2=gl[2]/(gl[2]-gl[0]);
+
+				/*New point 1*/
+				xyz_bis[1][0]=*(xyz_list+3*2+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*2+0));
+				xyz_bis[1][1]=*(xyz_list+3*2+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*2+1));
+				xyz_bis[1][2]=*(xyz_list+3*2+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*2+2));
+
+				/*New point 0*/
+				xyz_bis[0][0]=*(xyz_list+3*2+0)+s2*(*(xyz_list+3*0+0)-*(xyz_list+3*2+0));
+				xyz_bis[0][1]=*(xyz_list+3*2+1)+s2*(*(xyz_list+3*0+1)-*(xyz_list+3*2+1));
+				xyz_bis[0][2]=*(xyz_list+3*2+2)+s2*(*(xyz_list+3*0+2)-*(xyz_list+3*2+2));
+			}
+			else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+				/*Coordinates of point 0: same as initial point 2*/
+				xyz_bis[0][0]=*(xyz_list+3*0+0);
+				xyz_bis[0][1]=*(xyz_list+3*0+1);
+				xyz_bis[0][2]=*(xyz_list+3*0+2);
+
+				/*Portion of the segments*/
+				s1=gl[0]/(gl[0]-gl[1]);
+				s2=gl[0]/(gl[0]-gl[2]);
+
+				/*New point 1*/
+				xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
+				xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
+				xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
+
+				/*New point 2*/
+				xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
+				xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
+				xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
+			}
+			else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+				/*Coordinates of point 1: same as initial point 2*/
+				xyz_bis[1][0]=*(xyz_list+3*1+0);
+				xyz_bis[1][1]=*(xyz_list+3*1+1);
+				xyz_bis[1][2]=*(xyz_list+3*1+2);
+
+				/*Portion of the segments*/
+				s1=gl[1]/(gl[1]-gl[0]);
+				s2=gl[1]/(gl[1]-gl[2]);
+
+				/*New point 0*/
+				xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
+				xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
+				xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
+
+				/*New point 2*/
+				xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
+				xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
+				xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
+			}
+
+			/*Compute fraction of grounded element*/
+			GetJacobianDeterminant(&area_init, xyz_list,NULL);
+			GetJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+			if(mainlyfloating==true) area_grounded=area_init-area_grounded;
+			phi=area_grounded/area_init;
+		}
+	}
+	else _error_("mesh type "<<EnumToStringx(domaintype)<<"not supported yet ");
+
+	if(phi>1 || phi<0) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
+void       Tria::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
+	this->EdgeOnBaseIndices(&indices[0],&indices[1]);
+	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
+
+}/*}}}*/
+void       Tria::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
+
+}/*}}}*/
+void       Tria::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+
+	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
+void       Tria::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+
+	int         normal_orientation=0;
+	IssmDouble  s1,s2;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	IssmDouble* xyz_zero = xNew<IssmDouble>(2*3);
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[2]/(levelset[2]-levelset[1]);
+		s2=levelset[2]/(levelset[2]-levelset[0]);
+
+		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle depending on distribution of levelsetfunction
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);
+
+		/*New point 0*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
+	}
+	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+		/*Portion of the segments*/
+		s1=levelset[0]/(levelset[0]-levelset[2]);
+		s2=levelset[0]/(levelset[0]-levelset[1]);
+
+		if(levelset[0]<0.) normal_orientation=1;
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
+	}
+	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[1]/(levelset[1]-levelset[0]);
+		s2=levelset[1]/(levelset[1]-levelset[2]);
+
+		if(levelset[1]<0.) normal_orientation=1;
+		/*New point 0*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
+	}
+	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[0*3+0];
+		xyz_zero[3*0+1]=xyz_list[0*3+1];
+		xyz_zero[3*0+2]=xyz_list[0*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1*3+0];
+		xyz_zero[3*1+1]=xyz_list[1*3+1];
+		xyz_zero[3*1+2]=xyz_list[1*3+2];
+	}
+	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[2*3+0];
+		xyz_zero[3*0+1]=xyz_list[2*3+1];
+		xyz_zero[3*0+2]=xyz_list[2*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0*3+0];
+		xyz_zero[3*1+1]=xyz_list[0*3+1];
+		xyz_zero[3*1+2]=xyz_list[0*3+2];
+	}
+	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[1*3+0];
+		xyz_zero[3*0+1]=xyz_list[1*3+1];
+		xyz_zero[3*0+2]=xyz_list[1*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2*3+0];
+		xyz_zero[3*1+1]=xyz_list[2*3+1];
+		xyz_zero[3*1+2]=xyz_list[2*3+2];
+	}
+	else _error_("Case not covered");
+
+	/*Assign output pointer*/
+	*pxyz_zero= xyz_zero;
+}
+/*}}}*/
+void       Tria::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	
+	/* Intermediaries */
+	int i, dir,nrfrontnodes;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	int* indicesfront = xNew<int>(NUMVERTICES);
+	/* Get nodes where there is no ice */
+	nrfrontnodes=0;
+	for(i=0;i<NUMVERTICES;i++){
+		if(levelset[i]>=0.){
+			indicesfront[nrfrontnodes]=i;
+			nrfrontnodes++;
+		}
+	}
+
+	_assert_(nrfrontnodes==2);
+
+	/* arrange order of frontnodes such that they are oriented counterclockwise */
+	if((NUMVERTICES+indicesfront[0]-indicesfront[1])%NUMVERTICES!=NUMVERTICES-1){
+		int index=indicesfront[0];
+		indicesfront[0]=indicesfront[1];
+		indicesfront[1]=index;
+	}	
+
+	IssmDouble* xyz_front = xNew<IssmDouble>(3*nrfrontnodes);
+	/* Return nodes */
+	for(i=0;i<nrfrontnodes;i++){
+		for(dir=0;dir<3;dir++){
+			xyz_front[3*i+dir]=xyz_list[3*indicesfront[i]+dir];
+		}
+	}
+
+	*pxyz_front=xyz_front;
+
+	xDelete<int>(indicesfront);
+}/*}}}*/
+int        Tria::GetNodeIndex(Node* node){/*{{{*/
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error_("Node provided not found among element nodes");
+}
+/*}}}*/
+int        Tria::GetNumberOfNodes(void){/*{{{*/
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int        Tria::GetNumberOfVertices(void){/*{{{*/
+	return NUMVERTICES;
+}
+/*}}}*/
+void       Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+Node*      Tria::GetNode(int node_number){/*{{{*/
+	_assert_(node_number>=0); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
+	return this->nodes[node_number];
+
+}/*}}}*/
+void       Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type){/*{{{*/
+
+	/*New input*/
+	Input* oldinput=NULL;
+	Input* newinput=NULL;
+
+	/*copy input of enum_type*/
+	oldinput=(Input*)this->inputs->GetInput(enum_type);
+	if(!oldinput)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+	newinput=(Input*)oldinput->copy();
+
+	/*Assign new name (average)*/
+	newinput->ChangeEnum(average_enum_type);
+
+	/*Add new input to current element*/
+	this->inputs->AddInput((Input*)newinput);
+}
+/*}}}*/
+void       Tria::InputScale(int enum_type,IssmDouble scale_factor){/*{{{*/
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+void       Tria::InputUpdateFromIoModel(int index, IoModel* iomodel){ //i is the element index/*{{{*/
+
+	/*Intermediaries*/
+	int        i,j;
+	int        tria_vertex_ids[3];
+	IssmDouble nodeinputs[3];
+	IssmDouble cmmininputs[3];
+	IssmDouble cmmaxinputs[3];
+	bool       control_analysis   = false;
+	int        num_control_type,num_responses;
+	IssmDouble yts;
+
+	/*Get parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum); 
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<3;i++){ 
+		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Need to know the type of approximation for this element*/
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
+	}
+
+	/*Control Inputs*/
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			int control = reCast<int>(iomodel->Data(InversionControlParametersEnum)[i]);
+			switch(control){
+				/*yts conversion*/
+				case BalancethicknessThickeningRateEnum:
+				case BalancethicknessApparentMassbalanceEnum:
+				case VxEnum:
+				case VyEnum:
+					if(iomodel->Data(control)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(control,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+
+				/*No yts conversion*/
+				case ThicknessEnum:
+				case FrictionCoefficientEnum:
+				case BalancethicknessNuxEnum:
+				case BalancethicknessNuyEnum:
+					if(iomodel->Data(control)){
+						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(control,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+
+				/*Special cases (depth averaged quantities)*/
+				case MaterialsRheologyBbarEnum:
+					if(iomodel->Data(MaterialsRheologyBEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case DamageDbarEnum:
+					if(iomodel->Data(DamageDEnum)){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data(DamageDEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(DamageDbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				default:
+					_error_("Control " << EnumToStringx(control) << " not implemented yet");
+			}
+		}
+	}
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)){
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_responses;i++){
+			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_responses+i];
+			datasetinput->AddInput(new TriaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+void       Tria::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){/*{{{*/
+
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaInput(enum_type,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}
+/*}}}*/
+void       Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	int         numnodes;
+	int        *doflist = NULL;
+	IssmDouble *values  = NULL;
+
+	switch(type){
+	case VertexPIdEnum: 
+		values = xNew<IssmDouble>(NUMVERTICES);
+		for(int i=0;i<NUMVERTICES;i++){
+			values[i]=vector[this->vertices[i]->Pid()];
+		}
+		/*update input*/
+		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		break;
+
+	case VertexSIdEnum: 
+		values = xNew<IssmDouble>(NUMVERTICES);
+		for(int i=0;i<NUMVERTICES;i++){
+			values[i]=vector[this->vertices[i]->Sid()];
+		}
+		/*update input*/
+		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		break;
+
+	case NodesEnum:
+
+		/*Get number of nodes and dof list: */
+		numnodes = this->NumberofNodes(this->element_type);
+		values   = xNew<IssmDouble>(numnodes);
+		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+		for(int i=0;i<numnodes;i++){
+			values[i]=vector[doflist[i]];
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
+		}
+		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
+		break;
+
+	case NodeSIdEnum:
+
+		/*Get number of nodes and dof list: */
+		numnodes = this->NumberofNodes(this->element_type);
+		values   = xNew<IssmDouble>(numnodes);
+
+		for(int i=0;i<numnodes;i++){
+			values[i]=vector[nodes[i]->Sid()];
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
+		}
+		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
+		break;
+
+	default:
+		_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+	/*Clean-up*/
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+
+}
+/*}}}*/
+bool       Tria::IsOnBase(){/*{{{*/
+
+	int domaintype;
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:
+			return HasEdgeOnBase();
+		case Domain2DhorizontalEnum:
+			return true;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}
+/*}}}*/
+bool       Tria::IsOnSurface(){/*{{{*/
+
+	int domaintype;
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:
+			return HasEdgeOnSurface();
+		case Domain2DhorizontalEnum:
+			return true;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}
+/*}}}*/
+void       Tria::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetJacobianDeterminant(pJdet,xyz_list,(GaussTria*)gauss);
+
+}
+/*}}}*/
+void       Tria::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetSegmentJacobianDeterminant(pJdet,xyz_list_base,(GaussTria*)gauss);
+
+}
+/*}}}*/
+void       Tria::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetSegmentJacobianDeterminant(pJdet,xyz_list,(GaussTria*)gauss);
+
+}
+/*}}}*/
+void       Tria::JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_top,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetSegmentJacobianDeterminant(pJdet,xyz_list_top,(GaussTria*)gauss);
+
+}
+/*}}}*/
+bool       Tria::HasEdgeOnBase(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on bed not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+bool       Tria::HasEdgeOnSurface(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on surface not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+void       Tria::EdgeOnBaseIndices(int* pindex1,int* pindex2){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+void       Tria::EdgeOnSurfaceIndices(int* pindex1,int* pindex2){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
+int        Tria::EdgeOnBaseIndex(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+int        Tria::EdgeOnSurfaceIndex(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
+void       Tria::FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){/*{{{*/
+
+	if(!IsOnBase()) return;
+
+	/*Intermediaries*/
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* xyz_list_base = NULL;
+	IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
+	IssmDouble  bed_normal[2];
+	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  surface=0,value=0;
+	bool grounded;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list);
+	GetVerticesCoordinatesBase(&xyz_list_base);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+	Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
+
+	/*Create gauss point in the middle of the basal edge*/
+	Gauss* gauss=NewGaussBase(1);
+	gauss->GaussPoint(0);
+
+	if(!IsFloating()){ 
+		/*Check for basal force only if grounded and touching GL*/
+		if(this->inputs->Min(MaskGroundediceLevelsetEnum)==0.){
+			this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+			this->ViscosityFS(&viscosity,2,xyz_list,gauss,vx_input,vy_input,NULL);
+			pressure_input->GetInputValue(&pressure, gauss);
+			base_input->GetInputValue(&base, gauss); _assert_(base<0.);
+
+			/*Compute Stress*/
+			IssmDouble sigma_xx=2.*viscosity*epsilon[0]-pressure;
+			IssmDouble sigma_yy=2.*viscosity*epsilon[1]-pressure;
+			IssmDouble sigma_xy=2.*viscosity*epsilon[2];
+
+			/*Get normal vector to the bed */
+			NormalBase(&bed_normal[0],xyz_list_base);
+
+			/*basalforce*/
+			sigma_nn = sigma_xx*bed_normal[0]*bed_normal[0] + sigma_yy*bed_normal[1]*bed_normal[1] + 2.*sigma_xy*bed_normal[0]*bed_normal[1];
+
+			/*Compute water pressure*/
+			IssmDouble rho_ice   = matpar->GetRhoIce();
+			IssmDouble rho_water = matpar->GetRhoWater();
+			IssmDouble gravity   = matpar->GetG();
+			water_pressure=gravity*rho_water*base;
+
+			/*Compare basal stress to water pressure and determine whether it should ground*/
+			if (sigma_nn<water_pressure) grounded=true;
+			else                         grounded=false;
+		}
+		else{
+			grounded=true;
+		}
+	}
+	else{
+		/*Check for basal elevation if floating*/
+		base_input->GetInputValue(&base, gauss);
+		bed_input->GetInputValue(&bed, gauss);
+		if (base<bed) grounded=true;
+		else          grounded=false;
+	}
+	for(int i=0;i<NUMVERTICES;i++){
+		if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+		else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+	}
+
+	/*clean up*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_base);
+}
+/*}}}*/
+bool       Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[vertices[i]->Pid()]<0.){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+Gauss*     Tria::NewGauss(void){/*{{{*/
+	return new GaussTria();
+}
+/*}}}*/
+Gauss*     Tria::NewGauss(int order){/*{{{*/
+	return new GaussTria(order);
+}
+/*}}}*/
+Gauss*     Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){/*{{{*/
+
+	IssmDouble  area_coordinates[2][3];
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
+	return new GaussTria(area_coordinates,order);
+}
+/*}}}*/
+Gauss*     Tria::NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){/*{{{*/
+
+	return new GaussTria(point1,fraction1,fraction2,mainlyfloating,order);
+}
+/*}}}*/
+Gauss*     Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
+
+	IssmDouble  area_coordinates[2][3];
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
+	return new GaussTria(area_coordinates,order_vert);
+}
+/*}}}*/
+Gauss*     Tria::NewGaussBase(int order){/*{{{*/
+
+	int indices[2];
+	this->EdgeOnBaseIndices(&indices[0],&indices[1]);
+	return new GaussTria(indices[0],indices[1],order);
+}
+/*}}}*/
+Gauss*     Tria::NewGaussTop(int order){/*{{{*/
+
+	int indices[2];
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+	return new GaussTria(indices[0],indices[1],order);
+}
+/*}}}*/
+void       Tria::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->TensorInterpolation());
+
+}
+/*}}}*/
+int        Tria::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){/*{{{*/
+
+	int         found = 0;
+	IssmDouble  value;
+	Input      *data  = NULL;
+	GaussTria  *gauss = NULL;
+
+	/*First, serarch the input: */
+	data=inputs->GetInput(natureofdataenum); 
+
+	/*figure out if we have the vertex id: */
+	found=0;
+	for(int i=0;i<NUMVERTICES;i++){
+		if(index==vertices[i]->Id()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussTria(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+void       Tria::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+
+	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
+
+	bed_normal[0]= + vector[1]/norm;
+	bed_normal[1]= - vector[0]/norm;
+	_assert_(bed_normal[1]<0); 
+}
+/*}}}*/
+void       Tria::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	int index1,index2;
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	this->EdgeOnSurfaceIndices(&index1,&index2);
+	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+
+	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
+
+	top_normal[0]= + vector[1]/norm;
+	top_normal[1]= - vector[0]/norm;
+	_assert_(top_normal[1]>0); 
+}
+/*}}}*/
+int        Tria::VelocityInterpolation(void){/*{{{*/
+	return TriaRef::VelocityInterpolation(this->element_type);
+}
+/*}}}*/
+int        Tria::PressureInterpolation(void){/*{{{*/
+	return TriaRef::PressureInterpolation(this->element_type);
+}
+/*}}}*/
+int        Tria::TensorInterpolation(void){/*{{{*/
+	return TriaRef::TensorInterpolation(this->element_type);
+}
+/*}}}*/
+int        Tria::NumberofNodesPressure(void){/*{{{*/
+	return TriaRef::NumberofNodes(this->PressureInterpolation());
+}
+/*}}}*/
+int        Tria::NumberofNodesVelocity(void){/*{{{*/
+	return TriaRef::NumberofNodes(this->VelocityInterpolation());
+}
+/*}}}*/
+void       Tria::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){/*{{{*/
+
+   IssmDouble agd[NUMVERTICES];             // surface mass balance
+   IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+   IssmDouble h[NUMVERTICES],s[NUMVERTICES];
+   IssmDouble rho_water,rho_ice,desfac,s0p;
+
+   /*Recover monthly temperatures and precipitation*/
+   Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
+   Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
+   GaussTria* gauss=new GaussTria();
+   IssmDouble time,yts;
+   this->parameters->FindParam(&time,TimeEnum);
+   this->parameters->FindParam(&yts,ConstantsYtsEnum);
+   for(int month=0;month<12;month++) {
+     for(int iv=0;iv<NUMVERTICES;iv++) {
+       gauss->GaussVertex(iv);
+       input->GetInputValue(&monthlytemperatures[iv][month],gauss,time+month/12.*yts);
+       monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
+       input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
+       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion in m/y
+     }
+   }
+
+  /*Recover info at the vertices: */
+  GetInputListOnVertices(&h[0],ThicknessEnum);
+  GetInputListOnVertices(&s[0],SurfaceEnum);
+
+  /*Get material parameters :*/
+  rho_ice=matpar->GetRhoIce();
+  rho_water=matpar->GetRhoFreshwater();
+
+  /*Get desertification effect parameters*/
+  desfac=matpar->GetDesFac();
+  s0p=matpar->GetS0p();
+
+   /*measure the surface mass balance*/
+   for (int iv = 0; iv<NUMVERTICES; iv++){
+     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+   }
+
+   /*Update inputs*/    
+   this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
+   // this->inputs->AddInput(new TriaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Tria::ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){/*{{{*/
+
+	/*Static condensation if requested*/
+	if(pe){
+		if(this->element_type==MINIcondensedEnum){
+			int indices[2]={6,7};
+			pe->StaticCondensation(Ke,2,&indices[0]);
+		}
+		else if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			pe->StaticCondensation(Ke,size,indices);
+			xDelete<int>(indices);
+		}
+	}
+
+	if(Ke){
+		if(this->element_type==MINIcondensedEnum){
+			int indices[2]={6,7};
+			Ke->StaticCondensation(2,&indices[0]);
+		}
+		else if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			Ke->StaticCondensation(size,indices);
+			xDelete<int>(indices);
+		}
+	}
+
+
+}
+/*}}}*/
+void       Tria::ResetFSBasalBoundaryCondition(void){/*{{{*/
+
+	int numnodes = this->NumberofNodesVelocity();
+
+	int          approximation;
+	IssmDouble*  vertexonbase= NULL;
+	IssmDouble   slope,groundedice;
+	IssmDouble   xz_plane[6];
+
+	/*For FS only: we want the CS to be tangential to the bedrock*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(!HasNodeOnBase() ||  approximation!=FSApproximationEnum) return;
+
+	//printf("element number %i \n",this->id);
+	/*Get inputs*/
+	Input* slope_input=inputs->GetInput(BedSlopeXEnum);                             _assert_(slope_input);
+	Input* groundedicelevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(groundedicelevelset_input);
+	vertexonbase = xNew<IssmDouble>(numnodes);
+	this->GetInputListOnNodesVelocity(&vertexonbase[0],MeshVertexonbaseEnum);
+
+	/*Loop over basal nodes and update their CS*/
+	GaussTria* gauss = new GaussTria();
+	for(int i=0;i<this->NumberofNodesVelocity();i++){
+
+		if(vertexonbase[i]==1){
+			gauss->GaussNode(this->VelocityInterpolation(),i);
+			slope_input->GetInputValue(&slope,gauss);
+			groundedicelevelset_input->GetInputValue(&groundedice,gauss);
+			IssmDouble theta = atan(slope);
+
+			/*New X axis                  New Z axis*/
+			xz_plane[0]=cos(theta);       xz_plane[3]=0.;  
+			xz_plane[1]=sin(theta);       xz_plane[4]=0.;  
+			xz_plane[2]=0.;               xz_plane[5]=1.;          
+			if(groundedice>=0){
+				this->nodes[i]->DofInSSet(1); //vy
+			}
+			else{
+				this->nodes[i]->DofInFSet(1); //vy
+			}
+
+			XZvectorsToCoordinateSystem(&this->nodes[i]->coord_system[0][0],&xz_plane[0]);
+		}
+	}
+
+	/*cleanup*/
+	xDelete<IssmDouble>(vertexonbase);
+	delete gauss;
+}
+/*}}}*/
+void       Tria::SetClone(int* minranks){/*{{{*/
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+Seg*       Tria::SpawnSeg(int index1,int index2){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Create Seg*/
+	Seg* seg=new Seg();
+	seg->id=this->id;
+	seg->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	seg->parameters=this->parameters;
+	seg->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnSegHook(dynamic_cast<ElementHook*>(seg),index1,index2);
+
+	/*Spawn material*/
+	seg->material=(Material*)this->material->copy2(seg);
+
+	/*recover nodes, material and matpar: */
+	seg->nodes    = (Node**)seg->hnodes[analysis_counter]->deliverp();
+	seg->vertices = (Vertex**)seg->hvertices->deliverp();
+	seg->matpar   = (Matpar*)seg->hmatpar->delivers();
+
+	/*Return new Seg*/
+	return seg;
+}
+/*}}}*/
+Element*   Tria::SpawnBasalElement(void){/*{{{*/
+
+	int index1,index2;
+	int domaintype;
+
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			return this;
+		case Domain2DverticalEnum:
+			_assert_(HasEdgeOnBase());
+			this->EdgeOnBaseIndices(&index1,&index2);
+			return SpawnSeg(index1,index2);
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+Element*   Tria::SpawnTopElement(void){/*{{{*/
+
+	int index1,index2;
+	int domaintype;
+
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			return this;
+		case Domain2DverticalEnum:
+			_assert_(HasEdgeOnSurface());
+			this->EdgeOnSurfaceIndices(&index1,&index2);
+			return SpawnSeg(index2,index1); //reverse order
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+void       Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
+IssmDouble Tria::SurfaceArea(void){/*{{{*/
+
+	IssmDouble S;
+	IssmDouble normal[3];
+	IssmDouble v13[3],v23[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*If on water, return 0: */
+	if(!IsIceInElement()) return 0.;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	S = 0.5 * sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	/*Return: */
+	return S;
+}
+/*}}}*/
+IssmDouble Tria::TimeAdapt(void){/*{{{*/
+
+	/*intermediary: */
+	int    i;
+	IssmDouble C,dt;
+	IssmDouble dx,dy;
+	IssmDouble maxx,minx;
+	IssmDouble maxy,miny;
+	IssmDouble maxabsvx,maxabsvy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	maxabsvx = this->inputs->MaxAbs(VxEnum);
+	maxabsvy = this->inputs->MaxAbs(VyEnum);
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy);
+
+	return dt;
+}
+/*}}}*/
+void       Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){/*{{{*/
+
+	/*Intermediaries*/
+	int  numnodes;
+	int* tria_node_ids = NULL;
+
+	/*Checks if debuging*/
+	_assert_(iomodel->elements);
+
+	/*Recover element type*/
+	this->element_type_list[analysis_counter]=finiteelement_type;
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	switch(finiteelement_type){
+		case P1Enum:
+			numnodes        = 3;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			break;
+		case P1DGEnum:
+			numnodes        = 3;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+3*index+1;
+			tria_node_ids[1]=iomodel->nodecounter+3*index+2;
+			tria_node_ids[2]=iomodel->nodecounter+3*index+3;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numnodes        = 4;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+			break;
+		case P2Enum:
+			numnodes        = 6;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			numnodes        = 7;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+index+1;
+			break;
+		case P1P1Enum: case P1P1GLSEnum:
+			numnodes        = 6;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+0];
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+1];
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+2];
+			break;
+		case MINIEnum: case MINIcondensedEnum:
+			numnodes       = 7;
+			tria_node_ids  = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
+
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+0];
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+1];
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+2];
+			break;
+		case TaylorHoodEnum:
+		case XTaylorHoodEnum:
+			numnodes        = 9;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+0];
+			tria_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+1];
+			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+2];
+			break;
+		case LATaylorHoodEnum:
+			numnodes        = 6;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			break;
+		case CrouzeixRaviartEnum:
+			numnodes        = 10;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+index+1;
+
+			tria_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+1;
+			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+2;
+			tria_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+3;
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
+	}
+
+	/*hooks: */
+	this->SetHookNodes(tria_node_ids,numnodes,analysis_counter); this->nodes=NULL;
+	xDelete<int>(tria_node_ids);
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+}
+/*}}}*/
+void       Tria::UpdateConstraintsExtrudeFromBase(void){/*{{{*/
+
+	if(!HasEdgeOnBase()) return;
+
+	int        extrusioninput;
+	IssmDouble value,isonbase;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput);      _assert_(input);
+	Input* onbase = inputs->GetInput(MeshVertexonbaseEnum); _assert_(onbase);
+
+	GaussTria* gauss=new GaussTria();
+	for(int iv=0;iv<this->NumberofNodes(this->element_type);iv++){
+		gauss->GaussNode(this->element_type,iv);
+		onbase->GetInputValue(&isonbase,gauss);
+		if(isonbase==1.){
+			input->GetInputValue(&value,gauss);
+			this->nodes[iv]->ApplyConstraint(0,value);
+		}
+	}
+	delete gauss;
+
+}
+/*}}}*/
+void       Tria::UpdateConstraintsExtrudeFromTop(void){/*{{{*/
+
+	if(!HasEdgeOnSurface()) return;
+
+	int extrusioninput;
+	int indices[2];
+	IssmDouble value;
+
+	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
+	Input* input = inputs->GetInput(extrusioninput); _assert_(input);
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+
+	GaussTria* gauss=new GaussTria();
+	for(int i=0;i<2;i++){
+		gauss->GaussNode(P1Enum,indices[i]);
+		input->GetInputValue(&value,gauss);
+		this->nodes[indices[i]]->ApplyConstraint(0,value);
+	}
+	delete gauss;
+
+}
+/*}}}*/
+void       Tria::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
+	TriaRef::GetInputValue(pvalue,values,gauss,P1Enum);
+}
+/*}}}*/
+void       Tria::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+}
+/*}}}*/
+int        Tria::VertexConnectivity(int vertexindex){/*{{{*/
+	_assert_(this->vertices);
+	return this->vertices[vertexindex]->Connectivity();
+}
+/*}}}*/
+bool       Tria::IsZeroLevelset(int levelset_enum){/*{{{*/
+
+	bool iszerols;
+	IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],levelset_enum);
+
+	/*If the level set is awlays <0, there is no ice front here*/
+	iszerols= false;
+	if(IsIceInElement()){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
+			iszerols = true;
+		}
+	}
+
+	return iszerols;
+}
+/*}}}*/
+bool       Tria::IsIcefront(void){/*{{{*/
+
+	bool isicefront;
+	int i,nrice;
+   IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	isicefront=false;
+	if(IsIceInElement()){
+		nrice=0;       
+		for(i=0;i<NUMVERTICES;i++)
+			if(ls[i]<0.) nrice++;
+		if(nrice==1) isicefront= true;
+	}
+	return isicefront;
+}/*}}}*/
+bool       Tria::IsFaceOnBoundary(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonboundaryEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on boundary not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}/*}}}*/
+void       Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
+
+	bool       already = false;
+	int        i,j;
+	int        partition[NUMVERTICES];
+	int        offsetsid[NUMVERTICES];
+	int        offsetdof[NUMVERTICES];
+	IssmDouble area;
+	IssmDouble mean;
+
+	/*First, get the area: */
+	area=this->GetArea();
+
+	/*Figure out the average for this element: */
+	this->GetVerticesSidList(&offsetsid[0]);
+	this->GetVertexPidList(&offsetdof[0]);
+	mean=0;
+	for(i=0;i<NUMVERTICES;i++){
+		partition[i]=reCast<int>(qmu_part[offsetsid[i]]);
+		mean=mean+1.0/NUMVERTICES*vertex_response[offsetdof[i]];
+	}
+
+	/*Add contribution: */
+	for(i=0;i<NUMVERTICES;i++){
+		already=false;
+		for(j=0;j<i;j++){
+			if (partition[i]==partition[j]){
+				already=true;
+				break;
+			}
+		}
+		if(!already){
+			partition_contributions->SetValue(partition[i],mean*area,ADD_VAL);
+			partition_areas->SetValue(partition[i],area,ADD_VAL);
+		};
+	}
+}
+/*}}}*/
+IssmDouble Tria::IceVolume(void){/*{{{*/
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	IssmDouble base,surface,bed;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement())return 0;
+
+	/*First get back the area of the base*/
+	base=this->GetArea();
+
+	/*Now get the average height*/
+	Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+	surface_input->GetInputAverage(&surface);
+	base_input->GetInputAverage(&bed);
+
+	/*Return: */
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype==Domain2DverticalEnum){
+	  return base;
+	}
+	else{
+	  return base*(surface-bed);
+	}
+}
+/*}}}*/
+IssmDouble Tria::IceVolumeAboveFloatation(void){/*{{{*/
+
+	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,surface,bed,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement() || IsFloating())return 0;
+
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height and bathymetry*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
+	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	base_input->GetInputAverage(&bed);
+	bed_input->GetInputAverage(&bathymetry);
+	
+	/*Return: */
+	return base*(surface-bed+min(rho_water/rho_ice*bathymetry,0.));
+}
+/*}}}*/
+IssmDouble Tria::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
+
+	int        domaintype;
+	IssmDouble mass_flux=0.;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	/*First off, check that this segment belongs to this element: */
+	if (segment_id!=this->id)_error_("error message: segment with id " << segment_id << " does not belong to element with id:" << this->id);
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+IssmDouble Tria::MassFlux( IssmDouble* segment){/*{{{*/
+
+	int        domaintype;
+	IssmDouble mass_flux=0.;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble x1,y1,x2,y2,h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	/*First off, check that this segment belongs to this element: */
+	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
+
+	/*Recover segment node locations: */
+	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+void       Tria::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+
+		case VelEnum:{
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*Assign output pointers:*/
+			*presponse=vel;}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+IssmDouble Tria::TotalSmb(void){/*{{{*/
+
+	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+   if(!IsIceInElement())return 0;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));	// area of element in m2
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
+   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+IssmDouble Tria::MisfitArea(int weightsenum){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+
+	/*If on water, return 0: */
+	if(!IsIceInElement())return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		weights_input->GetInputValue(&weight,gauss);
+
+		/*compute misfit between model and observation */
+		Jelem+=Jdet*weight*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+IssmDouble Tria::Misfit(int modelenum,int observationenum,int weightsenum){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble model,observation,weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+
+	/*If on water, return 0: */
+	if(!IsIceInElement())return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* model_input=inputs->GetInput(modelenum);   _assert_(model_input);
+	Input* observation_input=inputs->GetInput(observationenum);_assert_(observation_input);
+	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		model_input->GetInputValue(&model,gauss);
+		observation_input->GetInputValue(&observation,gauss);
+		weights_input->GetInputValue(&weight,gauss);
+
+		/*compute misfit between model and observation */
+		Jelem+=0.5*(model-observation)*(model-observation)*Jdet*weight*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+
+#ifdef _HAVE_GIA_
+void       Tria::GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x, IssmDouble* y){/*{{{*/
+
+	int i;
+	int gsize;
+	IssmDouble xi,yi,ri,re,area;
+	IssmDouble x0,y0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*thickness averages: */
+	IssmDouble* hes=NULL;
+	IssmDouble* times=NULL;
+	IssmDouble  currenttime;
+	int         numtimes;
+	Input* thickness_input=NULL;
+
+	/*gia solution parameters:*/
+	int cross_section_shape=0;
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_density;
+	Input* mantle_viscosity_input=NULL;
+	IssmDouble mantle_viscosity;
+	Input* lithosphere_thickness_input=NULL;
+	IssmDouble lithosphere_thickness;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*constants: */
+	IssmDouble yts;
+
+	/*output: */
+	IssmDouble  wi;
+	IssmDouble  dwidt;
+
+	/*arguments to GiaDeflectionCorex: */
+	GiaDeflectionCoreArgs arguments;
+
+	/*how many dofs are we working with here? */
+	this->parameters->FindParam(&gsize,MeshNumberofverticesEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*recover gia solution parameters: */
+	this->parameters->FindParam(&cross_section_shape,GiaCrossSectionShapeEnum);
+
+	/*what time is it? :*/
+	this->parameters->FindParam(&currenttime,TimeEnum);
+
+	/*recover material parameters: */
+	lithosphere_shear_modulus=matpar->GetLithosphereShearModulus();
+	lithosphere_density=matpar->GetLithosphereDensity();
+	mantle_shear_modulus=matpar->GetMantleShearModulus();
+	mantle_density=matpar->GetMantleDensity();
+	rho_ice=matpar->GetRhoIce();
+
+	/*pull thickness averages: */
+	thickness_input=inputs->GetInput(ThicknessEnum); 
+	if (!thickness_input)_error_("thickness input needed to compute gia deflection!");
+	thickness_input->GetInputUpToCurrentTimeAverages(&hes,&times,&numtimes,currenttime);
+
+	/*recover mantle viscosity: */
+	mantle_viscosity_input=inputs->GetInput(GiaMantleViscosityEnum);
+	if (!mantle_viscosity_input)_error_("mantle viscosity input needed to compute gia deflection!");
+	mantle_viscosity_input->GetInputAverage(&mantle_viscosity);
+
+	/*recover lithosphere thickness: */
+	lithosphere_thickness_input=inputs->GetInput(GiaLithosphereThicknessEnum);
+	if (!lithosphere_thickness_input)_error_("lithosphere thickness input needed to compute gia deflection!");
+	lithosphere_thickness_input->GetInputAverage(&lithosphere_thickness);
+
+	/*pull area of this Tria: */
+	area=this->GetArea();
+
+	/*element radius: */
+	re=sqrt(area/PI);
+
+	/*figure out gravity center of our element: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x0=(xyz_list[0][0]+xyz_list[1][0]+xyz_list[2][0])/3.0;
+	y0=(xyz_list[0][1]+xyz_list[1][1]+xyz_list[2][1])/3.0;
+
+	/*start loading GiaDeflectionCore arguments: */
+	arguments.re=re;
+	arguments.hes=hes;
+	arguments.times=times;
+	arguments.numtimes=numtimes;
+	arguments.currenttime=currenttime;
+	arguments.lithosphere_shear_modulus=lithosphere_shear_modulus;
+	arguments.lithosphere_density=lithosphere_density;
+	arguments.mantle_shear_modulus=mantle_shear_modulus;
+	arguments.mantle_viscosity=mantle_viscosity;
+	arguments.mantle_density=mantle_density;
+	arguments.lithosphere_thickness=lithosphere_thickness;
+	arguments.rho_ice=rho_ice;
+	arguments.idisk=this->id;
+	arguments.iedge=cross_section_shape;
+	arguments.yts=yts;
+
+	for(i=0;i<gsize;i++){
+		/*compute distance from the center of the tria to the vertex i: */
+		xi=x[i]; yi=y[i];
+		ri=sqrt(pow(xi-x0,2)+pow(yi-y0,2));
+
+		/*load ri onto arguments for this vertex i: */
+		arguments.ri=ri;
+
+		/*for this Tria, compute contribution to rebound at vertex i: */
+		GiaDeflectionCorex(&wi,&dwidt,&arguments);
+
+		/*plug value into solution vector: */
+		wg->SetValue(i,wi,ADD_VAL);
+		dwgdt->SetValue(i,dwidt,ADD_VAL);
+
+	}
+
+	/*Free ressources: */
+	xDelete<IssmDouble>(hes);
+	xDelete<IssmDouble>(times);
+
+	return;
+}
+/*}}}*/
+#endif
+
+void       Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+		input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+		}
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+}
+/*}}}*/
+void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+
+	Input* input=inputs->GetInput(enum_type);
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);
+
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+void       Tria::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
+
+	Input* input=inputs->GetInput(control_enum);
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetVerticesConnectivityList(&connectivity[0]);
+	this->GetVerticesSidList(&sidlist[0]);
+
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
+
+}/*}}}*/
+void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){/*{{{*/
+
+	int vertexpidlist[NUMVERTICES];
+	Input *input=NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get input (either in element or material)*/
+	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
+}
+/*}}}*/
+void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+
+	/*Get Domain type*/
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(domaintype==Domain2DverticalEnum){
+		if(control_enum==MaterialsRheologyBbarEnum){
+			control_enum=MaterialsRheologyBEnum;
+			if(!IsOnBase()) return;
+		}
+		if(control_enum==DamageDbarEnum){
+			control_enum=DamageDEnum;
+			if(!IsOnBase()) return;
+		}
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	Input* new_input = new TriaInput(control_enum,values,P1Enum);
+	Input* input     = (Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+void       Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
+
+	int        *doflist = NULL;
+	IssmDouble  value;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
+
+	/*Get inputs*/
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	/*Ok, we have the values, fill in the array: */
+	GaussTria* gauss=new GaussTria();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(this->element_type,i);
+
+		enum_input->GetInputValue(&value,gauss);
+		values[i]=value;
+	}
+
+	solution->SetValues(numnodes,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+	delete gauss;
+}
+/*}}}*/
+
+#ifdef _HAVE_DAKOTA_
+void       Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New TriaInput*/
+			IssmDouble values[3];
+
+			/*Get values on the 3 vertices*/
+			for (i=0;i<3;i++){
+				values[i]=vector[this->vertices[i]->Sid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					IssmDouble  thickness[3];
+					IssmDouble  thickness_init[3];
+					IssmDouble  hydrostatic_ratio[3];
+					IssmDouble  surface[3];
+					IssmDouble  bed[3];
+
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BaseEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						IssmDouble rho_ice,rho_water,di;
+						rho_ice   = this->matpar->GetRhoIce();
+						rho_water = this->matpar->GetRhoWater();
+						di        = rho_ice/rho_water;
+
+						/*build new thickness: */
+						for (j=0; j<3; j++) {
+							/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
+							if (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
+							/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+
+							/*  check the computed thickness and update bed*/
+							if (thickness[j] < 0.) thickness[j]=1./(1.-di);
+							bed[j]=surface[j]-thickness[j];
+						}
+					}
+					else{
+						/*build new thickness: */
+						for (j=0; j<3; j++) {
+							/*  for observed thickness, use scaled value  */
+							if (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j];
+							/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+						}
+
+						/*update bed on grounded ice: */
+						for(j=0;j<3;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new TriaInput(ThicknessEnum,thickness,P1Enum));
+					this->inputs->AddInput(new TriaInput(BaseEnum,bed,P1Enum));
+					this->inputs->AddInput(new TriaInput(SurfaceEnum,surface,P1Enum));
+
+					break;
+				case MaterialsRheologyBEnum:
+					this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
+					break;
+				default:
+					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+			}
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+void       Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
+
+	int             i,t,row;
+	IssmDouble      time;
+	TransientInput *transientinput = NULL;
+	IssmDouble      values[3];
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			/*Create transient input: */
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=this->vertices[i]->Sid();
+					values[i]=matrix[ncols*row+t];
+				}
+
+				/*time:*/
+				time=matrix[(nrows-1)*ncols+t];
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new TriaInput(name,values,P1Enum),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+
+void       Tria::MigrateGroundingLine(IssmDouble* phi_ungrounding){/*{{{*/
+
+	int        i,migration_style;
+	bool       groundedelement = false;
+	IssmDouble bed_hydro,yts;
+	IssmDouble rho_water,rho_ice,density;
+	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
+	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BaseEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+	rho_water   = matpar->GetRhoWater();
+	rho_ice     = matpar->GetRhoIce();
+	density     = rho_ice/rho_water;
+
+	if(migration_style == ContactEnum){
+		for(i = 0;i < NUMVERTICES;i++) phi[i] = phi_ungrounding[vertices[i]->Pid()];
+		this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
+
+		/*go through vertices, and update inputs, considering them to be TriaVertex type: */
+		for(i = 0;i < NUMVERTICES;i++){
+			/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+			if(phi[i] >= 0.){
+					b[i]  = r[i];
+			}
+		}
+
+		/*Update inputs*/
+		this->inputs->AddInput(new TriaInput(BaseEnum,&b[0],P1Enum));
+		return;
+	}
+
+	this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
+
+	/*go through vertices, and update inputs, considering them to be TriaVertex type: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+		if(phi[i]<=0.){
+			if(b[i]<=r[i]){ 
+				b[i]        = r[i];
+				s[i]        = b[i]+h[i];
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AggressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{ // phi>0
+			bed_hydro=-density*h[i];
+			if (bed_hydro>r[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AggressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else{
+					if(migration_style!=SoftMigrationEnum) _error_("Error: migration should be Aggressive, Soft or Subelement");
+				}
+			}
+		}
+	}
+
+	/*Recalculate phi*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(migration_style==SoftMigrationEnum){
+			bed_hydro=-density*h[i];
+			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
+				phi[i]=h[i]+r[i]/density;
+			}
+		}
+		else phi[i]=h[i]+r[i]/density;
+	}
+	this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
+
+	/*Update inputs*/
+	this->inputs->AddInput(new TriaInput(SurfaceEnum,&s[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(BaseEnum,&b[0],P1Enum));
+
+}
+/*}}}*/
+void       Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
+
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*go through vertices, and figure out which ones are grounded and want to unground: */
+	for(int i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (gl[i]>0.){
+			bed_hydro=-density*h[i];
+			if(bed_hydro>r[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+int        Tria::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<3;i++){
+		if (reCast<bool>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
+			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/Tria.h	(revision 18231)
@@ -0,0 +1,184 @@
+/*! \file Tria.h 
+ *  \brief: header file for tria object
+ */
+
+#ifndef _TRIA_H_
+#define _TRIA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./TriaRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Results;
+class Node;
+class Material;
+class Matpar;
+class Seg;
+class ElementMatrix;
+class ElementVector;
+class Vertex;
+class GaussTria;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Tria: public Element,public ElementHook,public TriaRef{
+
+	public:
+
+		/*Tria constructors, destructors {{{*/
+		Tria(){};
+		Tria(int tria_id,int tria_sid,int i, IoModel* iomodel,int nummodels);
+		~Tria();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
+		#endif
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		IssmDouble  CharacteristicLength(void);
+		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void        ComputeSigmaNN();
+		void        ComputeStressTensor();
+		void        ComputeDeviatoricStressTensor();
+		void        ComputeSurfaceNormalVelocity();
+		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void        Delta18oParameterization(void);
+		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
+		int         FiniteElement(void);
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list);
+		int         GetNodeIndex(Node* node);
+		int         GetNumberOfNodes(void);
+		int         GetNumberOfVertices(void);
+		bool        IsOnBase();
+		bool        IsOnSurface();
+		bool        HasEdgeOnBase();
+		bool        HasEdgeOnSurface();
+		void        EdgeOnSurfaceIndices(int* pindex1,int* pindex);
+		void        EdgeOnBaseIndices(int* pindex1,int* pindex);
+		int         EdgeOnBaseIndex();
+		int         EdgeOnSurfaceIndex();
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags);
+		int         NumberofNodesVelocity(void);
+		int         NumberofNodesPressure(void);
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
+		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
+		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type);
+		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor);
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
+		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void        ResetFSBasalBoundaryCondition(void);
+	   Element*    SpawnBasalElement(void);
+		Element*    SpawnTopElement(void);
+		int         VelocityInterpolation();
+		int         PressureInterpolation();
+		int         TensorInterpolation();
+		IssmDouble  SurfaceArea(void);
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		IssmDouble  TimeAdapt();
+		void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
+		int         VertexConnectivity(int vertexindex);
+		void   VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
+		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
+		void	    GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		bool        IsZeroLevelset(int levelset_enum);
+		bool		IsIcefront(void);
+		bool		IsFaceOnBoundary(void);
+
+		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		IssmDouble IceVolume(void);
+		IssmDouble IceVolumeAboveFloatation(void);
+		IssmDouble TotalSmb(void);
+		IssmDouble MassFlux(IssmDouble* segment);
+		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
+		void       ElementResponse(IssmDouble* presponse,int response_enum);
+		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum);
+		IssmDouble MisfitArea(int weightsenum);
+
+		#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
+		#endif
+
+		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
+		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
+		void       InputControlUpdate(IssmDouble scalar,bool save_parameter);
+
+		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding);
+		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+
+		/*}}}*/
+		/*Tria specific routines:{{{*/
+		void           AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		void           AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		IssmDouble     GetArea(void);
+		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints);
+		int            GetElementType(void);
+		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void           NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
+		void           NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
+		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void           GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		Node*          GetNode(int node_number);
+		void	         InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type);
+		void	         InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int enum_type){_error_("not implemented yet");};
+		void           JacobianDeterminant(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void           JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		void           JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		IssmDouble     MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
+		Gauss*         NewGauss(void);
+		Gauss*         NewGauss(int order);
+      Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order);
+      Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order);
+      Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
+		Gauss*         NewGaussBase(int order);
+		Gauss*         NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
+		Gauss*         NewGaussTop(int order);
+		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
+		void	         SetClone(int* minranks);
+		void           SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
+		Seg*	         SpawnSeg(int index1,int index2);
+		IssmDouble     StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		void           ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not implemented yet");};
+
+		void UpdateConstraintsExtrudeFromBase(void);
+		void UpdateConstraintsExtrudeFromTop(void);
+		/*}}}*/
+
+};
+#endif  /* _TRIA_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.cpp	(revision 18231)
@@ -0,0 +1,534 @@
+/*!\file TriaRef.c
+ * \brief: implementation of the TriaRef object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP0  1
+#define NUMNODESP1  3
+#define NUMNODESP1b 4
+#define NUMNODESP2  6
+#define NUMNODESP2b 7
+
+/*Object constructors and destructor*/
+TriaRef::TriaRef(){/*{{{*/
+}
+/*}}}*/
+TriaRef::~TriaRef(){/*{{{*/
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+void TriaRef::GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
+	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume B has been allocated already, of size: 1x4
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss,finiteelement);
+
+	/*Build B for this segment*/
+	B[0] = +basis[index1];
+	B[1] = +basis[index2];
+	B[2] = -basis[index1];
+	B[3] = -basis[index2];
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume Bprime has been allocated already, of size: 1x4
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss,finiteelement);
+
+	/*Build B'*/
+	Bprime[0] = basis[index1];
+	Bprime[1] = basis[index2];
+	Bprime[2] = basis[index1];
+	Bprime[3] = basis[index2];
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+void TriaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1 = xyz_list[3*0+0];
+	IssmDouble y1 = xyz_list[3*0+1];
+	IssmDouble x2 = xyz_list[3*1+0];
+	IssmDouble y2 = xyz_list[3*1+1];
+	IssmDouble x3 = xyz_list[3*2+0];
+	IssmDouble y3 = xyz_list[3*2+1];
+
+	J[2*0+0] = 0.5*(x2-x1);
+	J[2*1+0] = SQRT3/6.0*(2*x3-x1-x2);
+	J[2*0+1] = 0.5*(y2-y1);
+	J[2*1+1] = SQRT3/6.0*(2*y3-y1-y2);
+}
+/*}}}*/
+void TriaRef::GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated*/
+
+	IssmDouble x1 = xyz_list[3*0+0];
+	IssmDouble y1 = xyz_list[3*0+1];
+	IssmDouble x2 = xyz_list[3*1+0];
+	IssmDouble y2 = xyz_list[3*1+1];
+
+	*Jdet = .5*sqrt(pow(x2-x1,2) + pow(y2-y1,2));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void TriaRef::GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	IssmDouble J[2][2];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix2x2Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void TriaRef::GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J[2][2];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix2x2Invert(Jinv,&J[0][0]);
+
+}
+/*}}}*/
+void TriaRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	/*Cast gauss to GaussTria*/
+	_assert_(gauss_in->Enum()==GaussTriaEnum);
+	GaussTria* gauss = dynamic_cast<GaussTria*>(gauss_in);
+
+	switch(finiteelement){
+		case NoneEnum:
+			return;
+		case P0Enum:
+			basis[0]=1.;
+			return;
+		case P1Enum: case P1DGEnum:
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			/*bubble*/
+			basis[3]=27.*gauss->coord1*gauss->coord2*gauss->coord3;
+			return;
+		case P2Enum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
+			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
+			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			/*Mid-sides*/
+			basis[3]=4.*gauss->coord3*gauss->coord2;
+			basis[4]=4.*gauss->coord3*gauss->coord1;
+			basis[5]=4.*gauss->coord1*gauss->coord2;
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
+			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
+			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			/*Mid-sides*/
+			basis[3]=4.*gauss->coord3*gauss->coord2;
+			basis[4]=4.*gauss->coord3*gauss->coord1;
+			basis[5]=4.*gauss->coord1*gauss->coord2;
+			/*bubble*/
+			basis[6]=27.*gauss->coord1*gauss->coord2*gauss->coord3;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+}
+/*}}}*/
+void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss,int index1,int index2,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(index1>=0 && index1<3);
+	_assert_(index2>=0 && index2<3);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* triabasis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(triabasis,gauss,finiteelement);
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		case P2Enum:
+			_assert_(index2<index1);
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			basis[2]=triabasis[3+index2-1];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(triabasis);
+}
+/*}}}*/
+void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv[2][2];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss,finiteelement); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 */
+	for(int i=0;i<numnodes;i++){
+		dbasis[numnodes*0+i] = Jinv[0][0]*dbasis_ref[0*numnodes+i]+Jinv[0][1]*dbasis_ref[1*numnodes+i];
+		dbasis[numnodes*1+i] = Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+
+}
+/*}}}*/
+void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss_in,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss_in);
+
+	/*Cast gauss to GaussTria*/
+	_assert_(gauss_in->Enum()==GaussTriaEnum);
+	GaussTria* gauss = dynamic_cast<GaussTria*>(gauss_in);
+
+	switch(finiteelement){
+		case P0Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP0*0+0] = 0.;
+			dbasis[NUMNODESP0*1+0] = 0.;
+			return;
+		case P1Enum: case P1DGEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1*0+0] = -0.5;
+			dbasis[NUMNODESP1*1+0] = -SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1*0+1] = 0.5;
+			dbasis[NUMNODESP1*1+1] = -SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1*0+2] = 0;
+			dbasis[NUMNODESP1*1+2] = SQRT3/3.;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1b*0+0] = -0.5;
+			dbasis[NUMNODESP1b*1+0] = -SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1b*0+1] = 0.5;
+			dbasis[NUMNODESP1b*1+1] = -SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1b*0+2] = 0;
+			dbasis[NUMNODESP1b*1+2] = SQRT3/3.;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1b*0+3] = 27.*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP1b*1+3] = 27.*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			return;
+		case P2Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2*0+0] = -2.*gauss->coord1 + 0.5;
+			dbasis[NUMNODESP2*1+0] = -2.*SQRT3/3.*gauss->coord1 + SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2*0+1] = +2.*gauss->coord2 - 0.5;
+			dbasis[NUMNODESP2*1+1] = -2.*SQRT3/3.*gauss->coord2 + SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2*0+2] = 0.;
+			dbasis[NUMNODESP2*1+2] = +4.*SQRT3/3.*gauss->coord3 - SQRT3/3.;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2*0+3] = +2.*gauss->coord3;
+			dbasis[NUMNODESP2*1+3] = +4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2*0+4] = -2.*gauss->coord3;
+			dbasis[NUMNODESP2*1+4] = +4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2*0+5] = 2.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+5] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2b*0+0] = -2.*gauss->coord1 + 0.5;
+			dbasis[NUMNODESP2b*1+0] = -2.*SQRT3/3.*gauss->coord1 + SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2b*0+1] = +2.*gauss->coord2 - 0.5;
+			dbasis[NUMNODESP2b*1+1] = -2.*SQRT3/3.*gauss->coord2 + SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2b*0+2] = 0.;
+			dbasis[NUMNODESP2b*1+2] = +4.*SQRT3/3.*gauss->coord3 - SQRT3/3.;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2b*0+3] = +2.*gauss->coord3;
+			dbasis[NUMNODESP2b*1+3] = +4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2b*0+4] = -2.*gauss->coord3;
+			dbasis[NUMNODESP2b*1+4] = +4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2b*0+5] = 2.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+5] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2b*0+6] = 27.*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP2b*1+6] = 27.*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *
+	 * p is a vector already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	p[0]=dpx;
+	p[1]=dpy;
+
+}
+/*}}}*/
+void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*p = value;
+}
+/*}}}*/
+int  TriaRef::NumberofNodes(int finiteelement){/*{{{*/
+
+	switch(finiteelement){
+		case NoneEnum:              return 0;
+		case P0Enum:                return NUMNODESP0;
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		case P1bubbleEnum:          return NUMNODESP1b;
+		case P1bubblecondensedEnum: return NUMNODESP1b;
+		case P2Enum:                return NUMNODESP2;
+		case P2bubbleEnum:          return NUMNODESP2b;
+		case P2bubblecondensedEnum: return NUMNODESP2b;
+		case P1P1Enum:              return NUMNODESP1*2;
+		case P1P1GLSEnum:           return NUMNODESP1*2;
+		case MINIcondensedEnum:     return NUMNODESP1b+NUMNODESP1;
+		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
+		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:      return NUMNODESP2;
+		case XTaylorHoodEnum:       return NUMNODESP2+NUMNODESP1;
+		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TriaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1bubbleEnum;
+		case MINIEnum:           return P1bubbleEnum;
+		case TaylorHoodEnum:     return P2Enum;
+		case LATaylorHoodEnum:   return P2Enum;
+		case XTaylorHoodEnum:    return P2Enum;
+		case CrouzeixRaviartEnum:return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TriaRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:            return P1Enum;
+		case P1P1GLSEnum:         return P1Enum;
+		case MINIcondensedEnum:   return P1Enum;
+		case MINIEnum:            return P1Enum;
+		case TaylorHoodEnum:      return P1Enum;
+		case LATaylorHoodEnum:    return NoneEnum;
+		case XTaylorHoodEnum:     return P1Enum;
+		case CrouzeixRaviartEnum: return P1DGEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TriaRef::TensorInterpolation(int fe_stokes){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum: return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+}
+/*}}}*/
+void TriaRef::NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement){/*{{{*/
+
+	/*Output*/
+	int  numindices;
+	int* indices = NULL;
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum: case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 2;
+			indices    = xNew<int>(numindices);
+			switch(index){
+				case 0:
+					indices[0] = 1;
+					indices[1] = 2;
+					break;
+				case 1:
+					indices[0] = 2;
+					indices[1] = 0;
+					break;
+				case 2:
+					indices[0] = 0;
+					indices[1] = 1;
+					break;
+				default:
+					_error_("Edge index provided ("<<index<<") is not between 0 and 2");
+			}
+			break;
+		case P2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			switch(index){
+				case 0:
+					indices[0] = 1;
+					indices[1] = 2;
+					indices[2] = 3;
+					break;
+				case 1:
+					indices[0] = 2;
+					indices[1] = 0;
+					indices[2] = 4;
+					break;
+				case 2:
+					indices[0] = 0;
+					indices[1] = 1;
+					indices[2] = 5;
+					break;
+				default:
+					_error_("Edge index provided ("<<index<<") is not between 0 and 2");
+			}
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Elements/TriaRef.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*!\file:  TriaRef.h
+ * \brief abstract class for handling Tria oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _TRIAREF_H_
+#define _TRIAREF_H_
+
+class Gauss;
+
+class TriaRef{
+
+	public: 
+		TriaRef();
+		~TriaRef();
+
+		/*Numerics*/
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
+		void GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
+		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss,int finiteelement);
+		void GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* pp, IssmDouble* plist, Gauss* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+
+		void NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement);
+		int  NumberofNodes(int finiteelement);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/ExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/ExternalResult.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/ExternalResult.h	(revision 18231)
@@ -0,0 +1,31 @@
+/*!\file:  ExternalResult.h
+ * \brief abstract class for ExternalResult object
+ */ 
+
+#ifndef _EXTERNALRESULT_H_
+#define _EXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../Node.h"
+/*}}}*/
+
+class ExternalResult: public Object{
+
+	public: 
+
+		virtual         ~ExternalResult(){};
+		virtual void   WriteData(FILE* fid,bool io_gather)=0;
+		virtual char*  GetResultName(void)=0;
+		virtual int    GetStep(void)=0;
+		virtual double GetValue(void)=0;
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 18231)
@@ -0,0 +1,544 @@
+/*! \file GenericExternalResult.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _GENERIC_EXTERNAL_RESULT_
+#define _GENERIC_EXTERNAL_RESULT_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include "./ExternalResult.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+template <class ResultType> 
+class GenericExternalResult: public ExternalResult {
+
+	private: 
+		int        id;
+		char*      result_name;
+		ResultType value;
+		int        M;
+		int        N;
+		int        step;
+		IssmDouble time;
+
+	public:
+		/*Diverse: must be in front, as it is used in what follows*/
+		void GenericEcho(void){/*{{{*/
+			_printf_("   id          : " << this->id << "\n");
+			_printf_("   result_name : " << this->result_name<< "\n");
+			_printf_("   step        : " << this->step << "\n");
+			_printf_("   time        : " << this->time << "\n");
+		}
+		/*}}}*/
+		void GenericWriteData(FILE* fid){/*{{{*/ 
+
+			IssmPDouble  passiveDouble;
+
+			/*First write name: */
+			int length=(strlen(this->result_name)+1)*sizeof(char);
+			fwrite(&length,sizeof(int),1,fid);
+			fwrite(this->result_name,length,1,fid);
+
+			/*Now write time and step: */
+			passiveDouble=reCast<IssmPDouble>(time);
+			fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+			fwrite(&step,sizeof(int),1,fid);
+		} /*}}}*/
+
+		/*GenericExternalResult constructors and  destructors*/
+		GenericExternalResult(){ /*{{{*/
+			id          = 0;
+			result_name = NULL;
+			M           = 0;
+			N           = 0;
+			step        = 0;
+			time        = 0;
+		} /*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+			id          = 0;
+			result_name = NULL;
+			M           = 0;
+			N           = 0;
+			step        = 0;
+			time        = 0;
+			_error_("template GenericExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_N,int in_step,IssmDouble in_time) not implemented for this ResultType\n");
+		}
+/*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
+			id        = in_id;
+			value     = in_value;
+			step      = in_step;
+			time      = in_time;
+
+			/*Convert enum to name*/
+			EnumToStringx(&this->result_name,in_enum_type);
+		}
+		/*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_value,int in_step){ /*{{{*/
+			id        = in_id;
+			value     = in_value;
+			step      = in_step;
+			time      = UNDEF;
+
+			/*Convert enum to name*/
+			EnumToStringx(&this->result_name,in_enum_type);
+		}
+		/*}}}*/
+		GenericExternalResult(int in_id,const char* in_result_name,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
+			id        = in_id;
+			value     = in_value;
+			step      = in_step;
+			time      = in_time;
+
+			/*Copy name*/
+			this->result_name = xNew<char>(strlen(in_result_name)+1);
+			xMemCpy<char>(this->result_name,in_result_name,strlen(in_result_name)+1);
+		}
+		/*}}}*/
+		~GenericExternalResult(){ /*{{{*/
+			xDelete<char>(result_name);
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(void){ /*{{{*/
+			this->DeepEcho();
+		}
+		/*}}}*/
+		void DeepEcho(void){ /*{{{*/
+			_error_("template DeepEcho not implemented for this ResultType\n");
+		}
+		/*}}}*/
+		int Id(void){ /*{{{*/ 
+			return -1; 
+		} /*}}}*/
+		int ObjectEnum(void){ /*{{{*/
+			_error_("template ObjectEnum not implemented for this ResultType\n");
+		} /*}}}*/
+		Object* copy(void) { /*{{{*/
+			return new GenericExternalResult<ResultType>(this->id,this->result_name,this->value,this->step,this->time);
+		} /*}}}*/
+
+		/*GenericExternalResult management: */
+void  WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     type;
+	int     size;
+	IssmPDouble  passiveDouble;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a IssmPDouble for Matlab or Python to post-process, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+
+	/*cast to a IssmPDouble: */
+	passiveDouble=reCast<IssmPDouble>(value);
+	fwrite(&passiveDouble,size*sizeof(IssmPDouble),1,fid);
+
+} /*}}}*/
+char* GetResultName(void){ /*{{{*/
+		char* name = xNew<char>(strlen(this->result_name)+1);
+		xMemCpy<char>(name,this->result_name,strlen(this->result_name)+1);
+		return name;
+} /*}}}*/
+int   GetStep(void){ /*{{{*/
+	return this->step;
+} /*}}}*/
+IssmPDouble GetValue(void){ /*{{{*/
+	/*Only supported by IssmPDouble result, error out by default*/
+	_error_("not supported for this type of result");
+	return 0.;
+} /*}}}*/
+};
+
+/*Specific instantiations for bool: */
+template <> inline void GenericExternalResult<bool>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<bool>:\n");
+	this->GenericEcho();
+	_printf_("   value: " <<(this->value?"true":"false") << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<bool>::ObjectEnum(void){ /*{{{*/
+	return BoolExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for int: */
+template <> inline void GenericExternalResult<int>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<int>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<int>::ObjectEnum(void){ /*{{{*/
+	return IntExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for double: */
+template <> inline void GenericExternalResult<double>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<double>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<double>::ObjectEnum(void){ /*{{{*/
+	return DoubleExternalResultEnum;
+} /*}}}*/
+template <> inline double GenericExternalResult<double>::GetValue(void){ /*{{{*/
+	return value;
+} /*}}}*/
+
+/*Specific instantiations for char*: */
+template <> inline GenericExternalResult<char*>::GenericExternalResult(int in_id, int in_enum_type,char* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+
+	id = in_id;
+	value = xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+	step  = in_step;
+	time  = in_time;
+
+	/*Convert enum to name*/
+	EnumToStringx(&this->result_name,in_enum_type);
+
+} /*}}}*/
+template <> inline GenericExternalResult<char*>::GenericExternalResult(int in_id, int in_enum_type,char* in_value,int in_step){ /*{{{*/
+
+	id = in_id;
+	value = xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+	step  = in_step;
+	time  = UNDEF;
+
+	/*Convert enum to name*/
+	EnumToStringx(&this->result_name,in_enum_type);
+
+} /*}}}*/
+template <> inline GenericExternalResult<char*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(result_name);
+	xDelete<char>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<char*>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     type;
+	int     length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a string, type is 2: */
+	type=2;
+	fwrite(&type,sizeof(int),1,fid);
+
+	length=(strlen(this->value)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->value,length,1,fid);
+}
+/*}}}*/
+template <> inline int GenericExternalResult<char*>::ObjectEnum(void){ /*{{{*/
+	return StringExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for IssmPDouble*: */
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+
+	id = in_id;
+	M  = in_M;
+	N  = in_N;
+
+	EnumToStringx(&this->result_name,in_enum_type);
+
+	step = in_step;
+	time = in_time;
+
+	/*Copy result in values*/
+	if(M*N){
+		value=xNew<IssmPDouble>(M*N);
+		xMemCpy<IssmPDouble>(value,in_values,M*N);
+	}
+	else value=NULL;
+}
+/*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+	_error_("you cannot initialize a GenericExternalResult<IssmPDouble*> without providing the dimensions of the matrix! Please use a more appropriate constructor!");
+} /*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(result_name);
+	xDelete<IssmPDouble>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::Echo(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<IssmPDouble*>:\n");
+	this->GenericEcho();
+	_printf_("   matrix size: " << this->M << "-" << this->N << "\n");
+
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::DeepEcho(void){ /*{{{*/
+
+	int i,j;
+
+	_printf_("GenericExternalResult<IssmPDouble*>:\n");
+	this->GenericEcho();
+
+	_printf_("   matrix size: " << this->M << "-" << this->N << "\n");
+	for (i=0;i<this->M;i++){  
+		_printf_("   [ ");
+		for (j=0;j<this->N;j++){
+			_printf_( " " << setw(11) << setprecision (5) << this->value[i*this->N+j]);
+		}  
+		_printf_(" ]\n");
+	}  
+
+} /*}}}*/
+template <> inline Object* GenericExternalResult<IssmPDouble*>::copy(void){ /*{{{*/
+	return new GenericExternalResult<IssmPDouble*>(this->id,StringToEnumx(this->result_name),this->value,this->M,this->N,this->step,this->time);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	IssmPDouble passiveDouble;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	/*First write enum: */
+	int length=(strlen(this->result_name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->result_name,length,1,fid);
+
+	/*Now write time and step: */
+	passiveDouble=reCast<IssmPDouble>(time);
+	fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a IssmDouble array, type is 3:*/
+	type=3;
+	fwrite(&type,sizeof(int),1,fid);
+	rows=this->M;
+	fwrite(&rows,sizeof(int),1,fid);
+	cols=this->N;
+	fwrite(&cols,sizeof(int),1,fid);
+	fwrite(value,cols*rows*sizeof(IssmPDouble),1,fid);
+
+}
+/*}}}*/
+template <> inline int GenericExternalResult<IssmPDouble*>::ObjectEnum(void){ /*{{{*/
+	return DoubleMatExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for IssmDouble*: */
+#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 GenericExternalResult<IssmDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     i;
+	int     my_rank;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	IssmPDouble passiveDouble;
+	IssmPDouble* passiveDoubles;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	/*First write enum: */
+	int length=(strlen(this->result_name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->result_name,length,1,fid);
+
+	/*Now write time and step: */
+	passiveDouble=reCast<IssmPDouble>(time);
+	fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a IssmDouble array, type is 3:*/
+	type=3;
+	fwrite(&type,sizeof(int),1,fid);
+	rows=this->M;
+	fwrite(&rows,sizeof(int),1,fid);
+	cols=this->N;
+	fwrite(&cols,sizeof(int),1,fid);
+
+	passiveDoubles=xNew<IssmPDouble>(this->M*this->N);
+	for (i=0;i<this->M*this->N;i++)passiveDoubles[i]=reCast<IssmPDouble>(value[i]);
+	fwrite(passiveDoubles,cols*rows*sizeof(IssmPDouble),1,fid);
+	xDelete<IssmPDouble>(passiveDoubles);
+
+}
+/*}}}*/
+#endif
+
+/*Specifics instantiations for Vector*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::GenericExternalResult(int in_id, int in_enum_type,Vector<IssmPDouble>* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+	_error_("instanciation not correct");
+}
+/*}}}*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::GenericExternalResult(int in_id, int in_enum_type,Vector<IssmPDouble>* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+	id = in_id;
+	M  = 0;
+	N  = 0;
+
+	/*Convert enum to name*/
+	EnumToStringx(&this->result_name,in_enum_type);
+
+	step = in_step;
+	time = in_time;
+
+	value = in_value;
+} /*}}}*/
+template <> inline GenericExternalResult<Vector<IssmPDouble>*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(this->result_name);
+	delete value;
+} /*}}}*/
+template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::Echo(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<Vector<IssmPDouble>*>:\n");
+	this->GenericEcho();
+	this->value->Echo();
+
+} /*}}}*/
+template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::DeepEcho(void){ /*{{{*/
+
+	this->Echo();
+
+} /*}}}*/
+template <> inline Object* GenericExternalResult<Vector<IssmPDouble>*>::copy(void){ /*{{{*/
+	return new GenericExternalResult<Vector<IssmPDouble>*>(this->id,StringToEnumx(this->result_name),this->value,this->step,this->time);
+} /*}}}*/
+#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 GenericExternalResult<Vector<IssmPDouble>*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	char *name   = NULL;
+	int   length,rows,cols=1;
+
+	if(!io_gather){
+		_error_("not supported yet");
+	}
+
+	/*Serialize vector*/
+	IssmPDouble* serialvalues = this->value->ToMPISerial();
+	this->value->GetSize(&rows);
+
+	if(IssmComm::GetRank()==0){
+		/*First write name: */
+		length=(strlen(this->result_name)+1)*sizeof(char);
+		fwrite(&length,sizeof(int),1,fid);
+		fwrite(this->result_name,length,1,fid);
+
+		/*Now write time and step: */
+		IssmPDouble passiveDouble=reCast<IssmPDouble>(time);
+		fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+		fwrite(&step,sizeof(int),1,fid);
+
+		/*writing a IssmDouble array, type is 3:*/
+		int type=3;
+		fwrite(&type,sizeof(int),1,fid);
+		fwrite(&rows,sizeof(int),1,fid);
+		fwrite(&cols,sizeof(int),1,fid);
+		fwrite(serialvalues,cols*rows*sizeof(IssmPDouble),1,fid);
+	}
+
+	/*Clean up*/
+	xDelete<IssmPDouble>(serialvalues);
+
+}
+/*}}}*/
+#endif
+template <> inline int GenericExternalResult<Vector<IssmPDouble>*>::ObjectEnum(void){ /*{{{*/
+	return NoneEnum;
+	/*???? FIXME*/
+} /*}}}*/
+
+/*Specifics instantiations for Vector<IssmDouble>*/
+template <> inline void GenericExternalResult<Vector<IssmDouble>*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int i;
+	char *name   = NULL;
+	int   length,rows,cols=1;
+	IssmDouble*  serialvalues = NULL;
+	IssmPDouble* pserialvalues = NULL;
+
+	if(!io_gather){
+		_error_("not supported yet");
+	}
+
+	/*Serialize vector*/
+	serialvalues = this->value->ToMPISerial();
+	this->value->GetSize(&rows);
+	
+	pserialvalues=xNew<IssmPDouble>(rows);
+	for(i=0;i<rows;i++)pserialvalues[i]=reCast<IssmPDouble>(serialvalues[i]);
+
+	if(IssmComm::GetRank()==0){
+		/*First write name: */
+		length=(strlen(this->result_name)+1)*sizeof(char);
+		fwrite(&length,sizeof(int),1,fid);
+		fwrite(this->result_name,length,1,fid);
+
+		/*Now write time and step: */
+		IssmPDouble passiveDouble=reCast<IssmPDouble>(time);
+		fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+		fwrite(&step,sizeof(int),1,fid);
+
+		/*writing a IssmDouble array, type is 3:*/
+		int type=3;
+		fwrite(&type,sizeof(int),1,fid);
+		fwrite(&rows,sizeof(int),1,fid);
+		fwrite(&cols,sizeof(int),1,fid);
+		fwrite(pserialvalues,cols*rows*sizeof(IssmPDouble),1,fid);
+	}
+
+	/*Clean up*/
+	xDelete<IssmPDouble>(pserialvalues);
+	xDelete<IssmDouble>(serialvalues);
+
+}
+/*}}}*/
+
+#endif  /* _EXTERNAL_RESULTOBJECT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.cpp	(revision 18231)
@@ -0,0 +1,95 @@
+/*
+ * \file Results.cpp
+ * \brief: Implementation of the Results class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Results.h"
+#include "./ExternalResult.h"
+#include "../../shared/shared.h"
+#include "../Params/Parameters.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Results::Results(){/*{{{*/
+	enum_type=ResultsEnum;
+	return;
+}
+/*}}}*/
+Results::~Results(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+void Results::Write(Parameters* parameters){/*{{{*/
+
+	FILE       *fid  = NULL;
+	bool        io_gather;
+
+	/*Recover file descriptor: */
+	parameters->FindParam(&fid,OutputFilePointerEnum);
+	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+		result->WriteData(fid,io_gather);
+	}
+
+}
+/*}}}*/
+int Results::AddResult(ExternalResult* in_result){/*{{{*/
+
+	/*First, go through dataset of inputs and check whether any input 
+	 * with the same name is already in. If so, erase the corresponding 
+	 * object before adding this new one: */
+
+	/*In debugging mode, check that the input is not a NULL pointer*/
+	_assert_(in_result);
+
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+
+		if(result->GetStep()==in_result->GetStep()){
+			char*    result_name =    result->GetResultName();
+			char* in_result_name = in_result->GetResultName();
+			if(strcmp(in_result_name,result_name)==0){
+
+				this->DeleteObject(result);
+				xDelete<char>(result_name);
+				xDelete<char>(in_result_name);
+				break;
+			}
+			xDelete<char>(result_name);
+			xDelete<char>(in_result_name);
+		}
+	}
+	this->AddObject(in_result);
+
+	return 1;
+}
+/*}}}*/
+int Results::DeleteResult(int result_enum,int result_step){/*{{{*/
+
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+
+		if(result->GetStep()==result_step){
+			if(strcmp(result->GetResultName(),EnumToStringx(result_enum))==0){
+				this->DeleteObject(result);
+				break;
+			}
+		}
+	}
+
+	return 1;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/ExternalResults/Results.h	(revision 18231)
@@ -0,0 +1,27 @@
+#ifndef _CONTAINER_RESULTS_H_
+#define _CONTAINER_RESULTS_H_
+
+#include "../../datastructures/datastructures.h"
+
+/*forward declarations */
+class Parameters;
+class ExternalResult;
+
+/*!\brief Declaration of Results class.
+ *
+ * Declaration of Results class.  Results are vector lists (Containers) of Result objects.
+ */ 
+class Results: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Results();
+		~Results();
+
+		/*Mehthos*/
+		int AddResult(ExternalResult* result);
+		int DeleteResult(int result_enum,int result_step);
+		void Write(Parameters* parameters);
+};
+#endif //ifndef _RESULTS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.cpp	(revision 18231)
@@ -0,0 +1,1617 @@
+/*!\file FemModel.cpp
+ * \brief: implementation of the FemModel object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../cores/cores.h"
+#include "../shared/io/io.h"
+#include "./classes.h"
+#include "./modules/modules.h"
+#include "../shared/Enum/Enum.h"
+
+#include "../analyses/analyses.h"
+
+/*module includes: {{{*/
+#include "../modules/ModelProcessorx/ModelProcessorx.h"
+#include "../modules/VerticesDofx/VerticesDofx.h"
+#include "../modules/SpcNodesx/SpcNodesx.h"
+#include "../modules/ConfigureObjectsx/ConfigureObjectsx.h"
+#include "../modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
+#include "../modules/GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "../modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h"
+#include "../modules/NodesDofx/NodesDofx.h"
+#include "../modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
+#include "../modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
+#include "../modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h"
+#include "../modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h"
+#include "../modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h"
+#include "../modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
+#include "../modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h"
+#include "../modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
+#include "../modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "../modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+#include "../modules/NodalValuex/NodalValuex.h"
+#include "../modules/GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "../modules/AverageOntoPartitionx/AverageOntoPartitionx.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+FemModel::FemModel(int argc,char** argv,ISSM_MPI_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();
+
+	/*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);
+
+}
+/*}}}*/
+FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
+
+	/*Call InitFromFiles. This constructor is just a wrapper: */
+	this->InitFromFiles(rootpath, inputfilename, outputfilename, toolkitsfilename, lockfilename, in_solution_type,analyses,nummodels);
+
+}
+/*}}}*/
+FemModel::~FemModel(){/*{{{*/
+
+	/*Intermediary*/
+	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){
+		_printf0_("write lock file:\n");
+		WriteLockFile(lockfilename);
+	}
+
+	/*Delete all the datasets: */
+	xDelete<int>(analysis_type_list);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(lockfilename);
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete constraints;
+	delete loads;
+	delete materials;
+	delete parameters;
+	delete results;
+
+	/*Before we delete the profiler, report statistics for this run: */
+	profiler->Tag(Finish);  //final tagging
+	_printf0_("\n");
+	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(StartInit,FinishInit) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore) << "\n");
+	_printf0_("\n");
+	_printf0_("   Total elapsed time:"
+			<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
+			<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
+			<<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
+			);
+	_printf0_("\n");
+
+	/*Now delete: */
+	delete profiler;
+
+	/*Finalize PETSC for this model: */
+	#ifdef _HAVE_PETSC_
+	_printf0_("closing PETSc\n");
+	PetscFinalize(); 
+	#endif
+
+}
+/*}}}*/
+
+/*Object management*/
+void FemModel::Echo(void){/*{{{*/
+
+	_printf_("FemModel echo: \n");
+	_printf_("   number of fem models: " << nummodels << "\n");
+	_printf_("   analysis_type_list: \n");
+	for(int i=0;i<nummodels;i++)_printf_("     " << i << ": " << EnumToStringx(analysis_type_list[i]) << "\n");
+	_printf_("   current analysis_type: \n");
+	_printf_("     " << analysis_counter << ": " << EnumToStringx(analysis_type_list[analysis_counter]) << "\n");
+
+}
+/*}}}*/
+void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
+
+	/*intermediary*/
+	int         i;
+	int         analysis_type;
+	FILE       *IOMODEL = NULL;
+	FILE       *toolkitsoptionsfid = 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 = pfopen0(inputfilename ,"rb");
+
+	/*Open toolkits file: */
+	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
+
+	/*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,toolkitsoptionsfid,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()) _printf0_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":\n");
+		analysis_type=analysis_type_list[i];
+		this->SetCurrentConfiguration(analysis_type);
+
+		if(i==0){
+			if(VerboseMProcessor()) _printf0_("      creating vertex PIDs\n");
+			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
+		}
+
+		if(VerboseMProcessor()) _printf0_("      resolving node constraints\n");
+		SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+		if(VerboseMProcessor()) _printf0_("      creating nodal degrees of freedom\n");
+		NodesDofx(nodes,parameters,analysis_type);
+
+		if(VerboseMProcessor()) _printf0_("      configuring element and loads\n");
+		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
+	}
+
+	/*Close input file and toolkits file descriptors: */
+	if(my_rank==0) pfclose(IOMODEL,inputfilename);
+	pfclose(toolkitsoptionsfid,toolkitsfilename);
+
+	/*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));
+
+	}
+/*}}}*/
+void FemModel::SetStaticComm(void){/*{{{*/
+
+	/*This routine sets the global communicator variable hidden inside the IssmComm 
+	 *class: */
+	IssmComm::SetComm(this->comm);
+
+}
+/*}}}*/
+void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){/*{{{*/
+
+	/*Use configuration_type to setup the analysis counter, the configurations of objects etc ... but use 
+	 * analysis_type to drive the element numerics. This allows for use of 1 configuration_type for several 
+	 * analyses. For example: do a SurfaceSlopeX, SurfaceSlopeY, BedSlopeX and BedSlopeY analysis using the 
+	 * Slope configuration.*/
+	int found=-1;
+	for(int i=0;i<nummodels;i++){
+	
+		if (analysis_type_list[i]==configuration_type){
+			found=i;
+			break;
+		}
+	}
+	if(found!=-1) analysis_counter=found;
+	else _error_("Could not find alias for analysis_type " << EnumToStringx(configuration_type) << " in list of FemModel analyses");
+
+	/*Now, plug analysis_counter and analysis_type inside the parameters: */
+	this->parameters->SetParam(analysis_counter,AnalysisCounterEnum);
+	this->parameters->SetParam(analysis_type,AnalysisTypeEnum);
+	this->parameters->SetParam(configuration_type,ConfigurationTypeEnum);
+
+	/*configure elements, loads and nodes, for this new analysis: */
+	this->elements->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
+	this->loads->SetCurrentConfiguration(elements, loads, nodes,vertices, materials,parameters);
+
+	/*take care of toolkits options, that depend on this analysis type (present only after model processor)*/
+	if(this->parameters->Exist(ToolkitsOptionsStringsEnum)){
+		ToolkitsOptionsFromAnalysis(this->parameters,analysis_type);
+		if(VerboseSolver()) _printf0_("      toolkits Options set for analysis type: " << EnumToStringx(analysis_type) << "\n");
+	}
+
+}
+/*}}}*/
+void FemModel::SetCurrentConfiguration(int configuration_type){/*{{{*/
+	this->SetCurrentConfiguration(configuration_type,configuration_type);
+}
+/*}}}*/
+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
+
+	_printf0_("call computational core:\n");
+
+	/*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);
+
+		_printf0_("Core solution elapsed time    : " << solution_time   << " Seconds\n");
+		_printf0_("Core solution number of flops : " << solution_flops  << " Flops\n");
+		_printf0_("Core solution memory used     : " << solution_memory << " Bytes\n");
+
+		/*Add to results: */
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum, solution_time, 1, 0));
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentMemEnum, solution_memory, 1, 0));
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentFlopsEnum, solution_flops, 1, 0));
+
+		#ifdef _HAVE_ADOLC_
+		solution_time=profiler->DeltaTime(StartAdCore,FinishAdCore);
+		solution_flops=profiler->DeltaFlops(StartAdCore,FinishAdCore);
+		solution_memory=profiler->Memory(FinishAdCore);
+
+		_printf0_("AD Solution elapsed time    : " << solution_time   << " Seconds\n");
+		_printf0_("AD Solution number of flops : " << solution_flops  << " Flops\n");
+		_printf0_("AD Solution memory used     : " << solution_memory << " Bytes\n");
+
+		#endif
+
+			}
+}
+/*}}}*/
+/*Modules:*/
+int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
+
+	IssmDouble         *surface = NULL;
+	IssmDouble         *bed     = NULL;
+
+	/*get vertex vectors for bed and thickness: */
+	GetVectorFromInputsx(&surface  ,this, SurfaceEnum,VertexEnum);
+	GetVectorFromInputsx(&bed      ,this, BaseEnum,    VertexEnum);
+
+	/*Allocate vector*/
+	Vector<IssmDouble> *vx=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	Vector<IssmDouble> *vy=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	Vector<IssmDouble> *vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
+
+	/*Update verices new geometry: */
+	for(int i=0;i<vertices->Size();i++){
+		Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		vertex->UpdatePosition(vx,vy,vz,parameters,surface,bed);
+	}
+
+	/*Assemble mesh velocity*/
+	vx->Assemble();
+	vy->Assemble();
+	vz->Assemble();
+
+	/*Update element inputs*/
+	InputUpdateFromVectorx(this,vx,VxMeshEnum,VertexPIdEnum);
+	InputUpdateFromVectorx(this,vy,VyMeshEnum,VertexPIdEnum);
+	InputUpdateFromVectorx(this,vz,VzMeshEnum,VertexPIdEnum);
+
+	/*Free ressources:*/
+	delete vx;
+	delete vy;
+	delete vz;
+	xDelete<IssmDouble>(bed);
+	xDelete<IssmDouble>(surface);
+	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()) _printf0_("   Updating constraints and active domain of analysis " << EnumToStringx(analysis_type)  << " for time: " << time << "\n");
+
+	Analysis* analysis= EnumToAnalysis(analysis_type);
+	analysis->UpdateConstraints(this);
+	delete analysis;
+	
+	/*Second, constraints might be time dependent: */
+	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){/*{{{*/
+
+	int response_descriptor_enum=StringToEnumx(response_descriptor);
+	this->Responsex(responses, response_descriptor_enum);
+
+}
+/*}}}*/
+void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum){/*{{{*/
+
+	switch (response_descriptor_enum){
+
+		case DivergenceEnum:               this->Divergencex(responses); break;
+		case IceVolumeEnum:                this->IceVolumex(responses); break;
+		case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(responses); break;
+		case MinVelEnum:                   this->MinVelx(responses); break;
+		case MaxVelEnum:                   this->MaxVelx(responses); break;
+		case MinVxEnum:                    this->MinVxx(responses); break;
+		case MaxVxEnum:                    this->MaxVxx(responses); break;
+		case MaxAbsVxEnum:                 this->MaxAbsVxx(responses); break;
+		case MinVyEnum:                    this->MinVyx(responses); break;
+		case MaxVyEnum:                    this->MaxVyx(responses); break;
+		case MaxAbsVyEnum:                 this->MaxAbsVyx(responses); break;
+		case MinVzEnum:                    this->MinVzx(responses); break;
+		case MaxVzEnum:                    this->MaxVzx(responses); break;
+		case MaxAbsVzEnum:                 this->MaxAbsVzx(responses); break;
+		case MassFluxEnum:                 this->MassFluxx(responses); break;
+		case SurfaceAbsVelMisfitEnum:      SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceRelVelMisfitEnum:      SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVelMisfitEnum:      SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVxVyMisfitEnum:     SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceAverageVelMisfitEnum:  SurfaceAverageVelMisfitx(responses,this); break;
+		case ThicknessAbsMisfitEnum:       ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAbsGradientEnum:     this->ThicknessAbsGradientx(responses); break;
+		case ThicknessAlongGradientEnum:   ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAcrossGradientEnum:  ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case RheologyBbarAbsGradientEnum:  RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case BalancethicknessMisfitEnum:   BalancethicknessMisfitx(responses); break;
+		case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(responses); break;
+		case TotalSmbEnum:					  this->TotalSmbx(responses); break;
+		case MaterialsRheologyBbarEnum:    this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
+		case VelEnum:                      this->ElementResponsex(responses,VelEnum); break;
+		case FrictionCoefficientEnum:      NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
+		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break; 
+	}
+
+}
+/*}}}*/
+void FemModel::RequestedOutputsx(Results **presults,char** requested_outputs, int numoutputs, bool save_results){/*{{{*/
+
+	/*Intermediaries*/
+	bool        isvec,results_on_nodes;
+	int         step,output_enum;
+	IssmDouble  time;
+	IssmDouble  double_result;
+	const char *output_string = NULL;
+
+	/*recover results*/
+	Results* results = *presults;
+	if(!results) results = new Results();
+
+	/*Get time and step*/
+	parameters->FindParam(&step,StepEnum);
+	parameters->FindParam(&time,TimeEnum);
+	parameters->FindParam(&results_on_nodes,SettingsResultsOnNodesEnum);
+
+	/*Go through all requested output*/
+	for(int i=0;i<numoutputs;i++){
+
+		output_string = requested_outputs[i];
+		output_enum   = StringToEnumx(output_string,false);
+		isvec         = false;
+
+		/*If string is not an enum, it is defined in output definitions*/
+		if(output_enum<0){
+			double_result = OutputDefinitionsResponsex(this,output_string);
+			if(save_results){
+				results->AddResult(new GenericExternalResult<IssmPDouble>(results->Size()+1,output_string,reCast<IssmPDouble>(double_result),step,time));
+				continue;
+			}
+		}
+		else{
+			switch(output_enum){
+
+				/*Scalar output*/
+				case DivergenceEnum:               this->Divergencex(&double_result);               break;
+				case IceVolumeEnum:                this->IceVolumex(&double_result);                break;
+				case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(&double_result); break;
+				case MinVelEnum:                   this->MinVelx(&double_result);                   break;
+				case MaxVelEnum:                   this->MaxVelx(&double_result);                   break;
+				case MinVxEnum:                    this->MinVxx(&double_result);                    break;
+				case MaxVxEnum:                    this->MaxVxx(&double_result);                    break;
+				case MaxAbsVxEnum:                 this->MaxAbsVxx(&double_result);                 break;
+				case MinVyEnum:                    this->MinVyx(&double_result);                    break;
+				case MaxVyEnum:                    this->MaxVyx(&double_result);                    break;
+				case MaxAbsVyEnum:                 this->MaxAbsVyx(&double_result);                 break;
+				case MinVzEnum:                    this->MinVzx(&double_result);                    break;
+				case MaxVzEnum:                    this->MaxVzx(&double_result);                    break;
+				case MaxAbsVzEnum:                 this->MaxAbsVzx(&double_result);                 break;
+				case MassFluxEnum:                 this->MassFluxx(&double_result);                 break;
+				case TotalSmbEnum:                 this->TotalSmbx(&double_result);                 break;
+
+			   /*Scalar control output*/
+				case SurfaceAbsVelMisfitEnum:       SurfaceAbsVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceRelVelMisfitEnum:       SurfaceRelVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceLogVelMisfitEnum:       SurfaceLogVelMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);        break;
+				case SurfaceLogVxVyMisfitEnum:      SurfaceLogVxVyMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);       break;
+				case SurfaceAverageVelMisfitEnum:   SurfaceAverageVelMisfitx(&double_result,this);                                                  break;
+				case ThicknessAbsMisfitEnum:        ThicknessAbsMisfitx(&double_result,elements,nodes,vertices,loads,materials,parameters);         break;
+				case ThicknessAbsGradientEnum:      this->ThicknessAbsGradientx(&double_result);                                                    break;
+				case ThicknessAlongGradientEnum:    ThicknessAlongGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);     break;
+				case ThicknessAcrossGradientEnum:   ThicknessAcrossGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
+				case RheologyBbarAbsGradientEnum:   RheologyBbarAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
+				case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters); break;
+				case BalancethicknessMisfitEnum:    BalancethicknessMisfitx(&double_result);                                                        break;
+				case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(&double_result); break;
+
+			   /*Vector */
+				default:
+
+					/*Vector layout*/
+					int interpolation,nodesperelement,size;
+					int rank_interpolation=-1,rank_nodesperelement=-1;
+
+					/*Get interpolation (and compute input if necessary)*/
+					for(int j=0;j<elements->Size();j++){
+						Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
+						element->ResultInterpolation(&rank_interpolation,&rank_nodesperelement,output_enum);
+					}
+
+					/*Broadcast for cpus that do not have any elements*/
+					ISSM_MPI_Reduce(&rank_interpolation,&interpolation,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&rank_nodesperelement,&nodesperelement,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+					ISSM_MPI_Bcast(&interpolation,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+					ISSM_MPI_Bcast(&nodesperelement,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+					if(results_on_nodes){
+
+						/*Allocate matrices*/
+						int         nbe       = this->elements->NumberOfElements();
+						IssmDouble* values    = xNewZeroInit<IssmDouble>(nbe*nodesperelement);
+						IssmDouble* allvalues = xNew<IssmDouble>(nbe*nodesperelement);
+
+						/*Fill-in matrix*/
+						for(int j=0;j<elements->Size();j++){
+							Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
+							element->ResultToPatch(values,nodesperelement,output_enum);
+						}
+
+						/*Gather from all cpus*/
+						ISSM_MPI_Allreduce((void*)values,(void*)allvalues,nbe*nodesperelement,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+						xDelete<IssmDouble>(values);
+
+						if(save_results)results->AddResult(new GenericExternalResult<IssmDouble*>(results->Size()+1,output_enum,allvalues,nbe,nodesperelement,step,time));
+						xDelete<IssmDouble>(allvalues);
+
+					}
+					else{
+
+						/*Allocate vector depending on interpolation*/
+						switch(interpolation){
+							case P0Enum: size = this->elements->NumberOfElements(); break;
+							case P1Enum: size = this->vertices->NumberOfVertices(); break;
+							default:     _error_("Interpolation "<<EnumToStringx(interpolation)<<" not supported yet");
+
+						}
+						Vector<IssmDouble> *vector_result = new Vector<IssmDouble>(size);
+
+						/*Fill in vector*/
+						for(int j=0;j<elements->Size();j++){
+							Element* element=(Element*)elements->GetObjectByOffset(j);
+							element->ResultToVector(vector_result,output_enum);
+						}
+						vector_result->Assemble();
+
+						if(save_results)results->AddResult(new GenericExternalResult<Vector<IssmDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
+					}
+					isvec = true;
+					break;
+			}
+		}
+
+		/*Add result to Results*/
+		if(!isvec && save_results){
+			results->AddResult(new GenericExternalResult<IssmPDouble>(results->Size()+1,output_string,reCast<IssmPDouble>(double_result),step,time));
+		}
+	}
+
+	/*Assign pointer and clean up*/
+	*presults = results;
+}
+/*}}}*/
+void FemModel::RequestedOutputsx(Results **presults,int* requested_outputs, int numoutputs,bool save_results){/*{{{*/
+
+	/*Convert list of enums to list of string*/
+	char** enumlist = xNew<char*>(numoutputs);
+	for(int i=0;i<numoutputs;i++){
+		EnumToStringx(&enumlist[i],requested_outputs[i]);
+	}
+
+	/*Call main module*/
+	this->RequestedOutputsx(presults,enumlist,numoutputs,save_results);
+
+	/*clean up and return*/
+	for(int i=0;i<numoutputs;i++) xDelete<char>(enumlist[i]);
+	xDelete<char*>(enumlist);
+	return;
+}
+/*}}}*/
+void FemModel::RequestedDependentsx(void){/*{{{*/
+
+	bool        isautodiff      = false;
+	IssmDouble  output_value;
+
+	int         num_dependents;
+	IssmPDouble *dependents;
+	DataSet*    dependent_objects=NULL;
+	int my_rank=IssmComm::GetRank();
+
+	/*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);
+				if (my_rank==0) {
+					output_value>>=dependents[i];
+				}
+			}
+		}
+		delete dependent_objects;
+		if(num_dependents)xDelete<IssmPDouble>(dependents);
+		#else
+		_error_("Should not be requesting dependents when an AD library is not available!");
+		#endif
+	}
+}
+/*}}}*/
+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: */
+	ISSM_MPI_Reduce (&min_dt,&node_min_dt,1,ISSM_MPI_DOUBLE,ISSM_MPI_MIN,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_min_dt,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	min_dt=node_min_dt;
+
+	/*Assign output pointers:*/
+	*pdt=min_dt;
+}
+/*}}}*/
+void FemModel::UpdateConstraintsExtrudeFromBasex(void){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->UpdateConstraintsExtrudeFromBase();
+	}
+
+}
+/*}}}*/
+void FemModel::UpdateConstraintsExtrudeFromTopx(void){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->UpdateConstraintsExtrudeFromTop();
+	}
+
+}
+/*}}}*/
+void FemModel::MassFluxx(IssmDouble* pmass_flux){/*{{{*/
+
+	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);
+				break;
+			}
+		}
+	}
+
+	ISSM_MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+	mass_flux=all_mass_flux;
+
+	/*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){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvx=element->inputs->MaxAbs(VxEnum);
+		if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxabsvx,&node_maxabsvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvx=node_maxabsvx;
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+
+}/*}}}*/
+void FemModel::MaxAbsVyx(IssmDouble* pmaxabsvy){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvy=element->inputs->MaxAbs(VyEnum);
+		if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxabsvy,&node_maxabsvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvy=node_maxabsvy;
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+
+}/*}}}*/
+void FemModel::MaxAbsVzx(IssmDouble* pmaxabsvz){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvz=element->inputs->MaxAbs(VzEnum);
+		if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxabsvz,&node_maxabsvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvz=node_maxabsvz;
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+
+}/*}}}*/
+void FemModel::MaxVelx(IssmDouble* pmaxvel){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvel = element->inputs->Max(VelEnum);
+		if(element_maxvel>maxvel) maxvel=element_maxvel;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxvel,&node_maxvel,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvel,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvel=node_maxvel;
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+
+}/*}}}*/
+void FemModel::MaxVxx(IssmDouble* pmaxvx){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvx = element->inputs->Max(VxEnum);
+		if(element_maxvx>maxvx) maxvx=element_maxvx;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxvx,&node_maxvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvx=node_maxvx;
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+
+}/*}}}*/
+void FemModel::MaxVyx(IssmDouble* pmaxvy){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvy = element->inputs->Max(VyEnum);
+		if(element_maxvy>maxvy) maxvy=element_maxvy;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxvy,&node_maxvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvy=node_maxvy;
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+
+}/*}}}*/
+void FemModel::MaxVzx(IssmDouble* pmaxvz){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvz = element->inputs->Max(VzEnum);
+		if(element_maxvz>maxvz) maxvz=element_maxvz;
+	}
+
+	/*Figure out maximum across the cluster: */
+	ISSM_MPI_Reduce(&maxvz,&node_maxvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvz=node_maxvz;
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+
+}/*}}}*/
+void FemModel::MinVelx(IssmDouble* pminvel){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvel = element->inputs->Min(VelEnum);
+		if(element_minvel<minvel) minvel=element_minvel;
+	}
+
+	/*Figure out minimum across the cluster: */
+	ISSM_MPI_Reduce(&minvel,&node_minvel,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvel,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvel=node_minvel;
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+
+}/*}}}*/
+void FemModel::MinVxx(IssmDouble* pminvx){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvx = element->inputs->Min(VxEnum);
+		if(element_minvx<minvx) minvx=element_minvx;
+	}
+
+	/*Figure out minimum across the cluster: */
+	ISSM_MPI_Reduce(&minvx,&node_minvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvx=node_minvx;
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+
+}/*}}}*/
+void FemModel::MinVyx(IssmDouble* pminvy){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvy = element->inputs->Min(VyEnum);
+		if(element_minvy<minvy) minvy=element_minvy;
+	}
+
+	/*Figure out minimum across the cluster: */
+	ISSM_MPI_Reduce(&minvy,&node_minvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvy=node_minvy;
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+
+}/*}}}*/
+void FemModel::MinVzx(IssmDouble* pminvz){/*{{{*/
+
+	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=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvz = element->inputs->Min(VzEnum);
+		if(element_minvz<minvz) minvz=element_minvz;
+	}
+
+	/*Figure out minimum across the cluster: */
+	ISSM_MPI_Reduce(&minvz,&node_minvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvz=node_minvz;
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+
+}/*}}}*/
+void FemModel::TotalSmbx(IssmDouble* pSmb){/*{{{*/
+
+	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();
+	}
+	ISSM_MPI_Reduce(&local_smb,&total_smb,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_smb,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pSmb=total_smb;
+
+}/*}}}*/
+void FemModel::Divergencex(IssmDouble* pdiv){/*{{{*/
+
+	IssmDouble local_divergence=0;
+	IssmDouble total_divergence;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		local_divergence+=element->Divergence();
+	}
+	ISSM_MPI_Reduce(&local_divergence,&total_divergence,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_divergence,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pdiv=total_divergence;
+
+}/*}}}*/
+void FemModel::IceVolumex(IssmDouble* pV){/*{{{*/
+
+	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();
+	}
+	ISSM_MPI_Reduce(&local_ice_volume,&total_ice_volume,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_ice_volume,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pV=total_ice_volume;
+
+}/*}}}*/
+void FemModel::IceVolumeAboveFloatationx(IssmDouble* pV){/*{{{*/
+
+	IssmDouble local_ice_volume_af = 0;
+	IssmDouble total_ice_volume_af;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		local_ice_volume_af+=element->IceVolumeAboveFloatation();
+	}
+	ISSM_MPI_Reduce(&local_ice_volume_af,&total_ice_volume_af,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_ice_volume_af,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pV=total_ice_volume_af;
+
+}/*}}}*/
+void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum){/*{{{*/
+
+	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: */
+	ISSM_MPI_Allreduce ( &found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
+
+	/*Ok, we found the element, compute responseocity: */
+	if(my_rank==cpu_found){
+		element->ElementResponse(&response,response_enum);
+	}
+
+	/*Broadcast and plug into response: */
+	ISSM_MPI_Allreduce ( &cpu_found,&cpu_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&response,1,ISSM_MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
+
+	/*Assign output pointers: */
+	*presponse=response;
+
+}/*}}}*/
+void FemModel::BalancethicknessMisfitx(IssmDouble* presponse){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  weight,vx,vy,H,dvx[2],dvy[2],dH[2];
+	IssmDouble  temp,Jdet,dhdt,groundedice_melting,surface_mass_balance;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  dp[3];
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input* weights_input                   = element->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+		Input* thickness_input                 = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+		Input* vx_input                        = element->GetInput(VxEnum);                                  _assert_(vx_input);
+		Input* vy_input                        = element->GetInput(VyEnum);                                  _assert_(vy_input);
+		Input* surface_mass_balance_input      = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(surface_mass_balance_input);
+		Input* groundedice_melting_input       = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedice_melting_input);
+		Input* dhdt_input                      = element->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,BalancethicknessMisfitEnum);
+			thickness_input->GetInputValue(&H, gauss);
+			thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
+			surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+			groundedice_melting_input->GetInputValue(&groundedice_melting,gauss);
+			dhdt_input->GetInputValue(&dhdt,gauss);
+			vx_input->GetInputValue(&vx,gauss);
+			vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+			vy_input->GetInputValue(&vy,gauss);
+			vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+
+			/*Balance thickness soft constraint J = 1/2 (div(Hv)-a)^2*/
+			temp  = vx*dH[0]+vy*dH[1]+H*(dvx[0]+dvy[1]) - (surface_mass_balance-groundedice_melting-dhdt);
+			J    +=weight*1/2*temp*temp*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*presponse=J;
+
+}/*}}}*/
+void FemModel::Balancethickness2Misfitx(IssmDouble* presponse){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  weight,thicknessobs,thickness,potential;
+	IssmDouble  Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input* weights_input     =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		Input* thickness_input   =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+		Input* thicknessobs_input=element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+		Input* potential_input   =element->GetInput(PotentialEnum);                          _assert_(potential_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
+			thickness_input->GetInputValue(&thickness,gauss);
+			thicknessobs_input->GetInputValue(&thicknessobs,gauss);
+			potential_input->GetInputValue(&potential,gauss);
+			gauss->GaussPoint(ig);
+
+			//J +=0.5*(thickness*thickness - thicknessobs*thicknessobs)*(thickness*thickness - thicknessobs*thicknessobs)*weight*Jdet*gauss->weight;
+			J +=.5*potential*potential*weight*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*presponse=J;
+
+}/*}}}*/
+void FemModel::ThicknessAbsGradientx( IssmDouble* pJ){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  Jdet;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  dp[3];
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+
+		/*Retrieve all inputs we will be needing: */
+		Input* weights_input   =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		Input* thickness_input =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,ThicknessAcrossGradientEnum);
+			thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+			/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+			J+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+/*}}}*/
+void FemModel::CostFunctionx(IssmDouble* pJ,IssmDouble** pJlist,int* pn){/*{{{*/
+
+	/*Intermediary*/
+	int      num_responses;
+	int     *responses      = NULL;
+	Results *cost_functions = NULL;
+
+	/*Recover parameters*/
+	parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Get the value of all cost functions*/
+	this->RequestedOutputsx(&cost_functions,responses,num_responses);
+
+	/*Get and add all contributions one by one*/
+	IssmDouble  J=0;
+	IssmDouble* Jlist = xNew<IssmDouble>(num_responses);
+	for(int i=0;i<num_responses;i++){
+		ExternalResult* result=(ExternalResult*)cost_functions->GetObjectByOffset(i);
+		Jlist[i] = reCast<IssmDouble>(result->GetValue());
+		J       += Jlist[i];
+	}
+	_assert_(cost_functions->Size()==num_responses);
+
+	/*Assign output pointers: */
+	delete cost_functions;
+	xDelete<int>(responses);
+	if(pJ)     *pJ     = J;
+	if(pJlist) *pJlist = Jlist;
+	else        xDelete<IssmDouble>(Jlist);
+	if(pn)     *pn     = num_responses;
+}
+/*}}}*/
+void FemModel::OutputControlsx(Results **presults){/*{{{*/
+
+	/*parameters: */
+	int         num_controls,step;
+	IssmDouble  time;
+	int        *control_type = NULL;
+
+	/*recover results*/
+	Results* results = *presults;
+	if(!results) results = new Results();
+
+	/*Get list of Controls*/
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	this->parameters->FindParam(&step,StepEnum);
+	this->parameters->FindParam(&time,TimeEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		int control_enum = control_type[i];
+		int gradient_enum;
+
+		switch(i){
+			case 0: gradient_enum = Gradient1Enum; break;
+			case 1: gradient_enum = Gradient2Enum; break;
+			case 2: gradient_enum = Gradient3Enum; break;
+			default: _error_("more than 3 controls not implemented yet");
+		}
+
+		/*Allocate vector*/
+		Vector<IssmPDouble> *vector_control  = new Vector<IssmPDouble>(this->vertices->NumberOfVertices());
+		Vector<IssmPDouble> *vector_gradient = new Vector<IssmPDouble>(this->vertices->NumberOfVertices());
+
+		/*Fill in vector*/
+		for(int j=0;j<elements->Size();j++){
+			Element* element=(Element*)elements->GetObjectByOffset(j);
+			element->ControlToVectors(vector_control,vector_gradient,control_enum);
+		}
+		vector_control->Assemble();
+		vector_gradient->Assemble();
+
+		results->AddResult(new GenericExternalResult<Vector<IssmPDouble>*>(results->Size()+1,control_enum,vector_control ,step,time));
+		results->AddResult(new GenericExternalResult<Vector<IssmPDouble>*>(results->Size()+1,gradient_enum,vector_gradient,step,time));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+}
+/*}}}*/
+#ifdef  _HAVE_DAKOTA_
+void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
+
+	int        i,j;
+	int        my_rank;
+
+	/*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,this, 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);
+
+			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);
+
+			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){
+		_printf_("   responses: " << d_numresponses << ": ");
+		for(i=0;i<d_numresponses-1;i++)_printf_(d_responses[i] << "|");
+		_printf_(d_responses[d_numresponses-1]);
+		_printf_("\n");
+	}
+	/*}}}*/
+
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_GIA_
+void FemModel::Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y){ /*{{{*/
+
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->GiaDeflection(wg,dwgdt, x,y);
+	}
+}
+/*}}}*/
+#endif
+void FemModel::HydrologyEPLupdateDomainx(void){ /*{{{*/
+
+	Vector<IssmDouble>* mask          = NULL;
+	IssmDouble*         serial_mask   = NULL;
+	Vector<IssmDouble>* active        = NULL;
+	IssmDouble*         serial_active = NULL;
+	
+	HydrologyDCEfficientAnalysis* effanalysis =  new HydrologyDCEfficientAnalysis();
+	/*Step 1: update mask, the mask might be extended by residual and/or using downstream sediment head*/
+	mask=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetMask(mask,element);
+	}
+
+	/*Assemble and serialize*/
+	mask->Assemble();
+	serial_mask=mask->ToMPISerial();
+	delete mask;
+
+	/*Update Mask*/
+	InputUpdateFromVectorx(this,serial_mask,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
+	xDelete<IssmDouble>(serial_mask);
+
+	/*Step 2: update node activity. If one element is connected to mask=1, all nodes are active*/
+	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetActive(active,element);
+	}
+
+	/*Assemble and serialize*/
+	active->Assemble();
+	serial_active=active->ToMPISerial();
+	delete active;
+
+	/*Update node activation accordingly*/
+	int counter =0;
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(HydrologyDCEfficientAnalysisEnum)){
+			if(serial_active[node->Sid()]==1.){
+				node->Activate();
+				counter++;
+			}
+			else{
+				node->Deactivate();
+			}
+		}
+	}
+	xDelete<IssmDouble>(serial_active);
+	delete effanalysis;
+	int sum_counter;
+	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	counter=sum_counter;
+	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
+
+	/*Update dof indexings*/
+	this->UpdateConstraintsx();
+
+}
+/*}}}*/
+void FemModel::UpdateConstraintsL2ProjectionEPLx(void){ /*{{{*/
+
+	Vector<IssmDouble>* active        = NULL;
+	IssmDouble*         serial_active = NULL;
+	HydrologyDCEfficientAnalysis* effanalysis = new HydrologyDCEfficientAnalysis();
+
+	/*update node activity. If one element is connected to mask=1, all nodes are active*/
+	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetActive(active,element);
+	}
+
+	/*Assemble and serialize*/
+	active->Assemble();
+	serial_active=active->ToMPISerial();
+	delete active;
+	delete effanalysis;
+
+	/*Update node activation accordingly*/
+	int counter =0;
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(L2ProjectionEPLAnalysisEnum)){
+			if(serial_active[node->Sid()]==1.){
+				node->Activate();
+				counter++;
+			}
+			else{
+				node->Deactivate();
+			}
+		}
+	}
+	xDelete<IssmDouble>(serial_active);
+	int sum_counter;
+	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	counter=sum_counter;
+	if(VerboseSolution()) _printf0_("   Number of active nodes L2 Projection: "<< counter <<"\n");
+
+	/*Update dof indexings*/
+	this->UpdateConstraintsx();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/FemModel.h	(revision 18231)
@@ -0,0 +1,104 @@
+/*
+ * FemModel.h: 
+ */
+
+#ifndef _FEMMODEL_H_
+#define _FEMMODEL_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../toolkits/toolkits.h"
+class DataSet;
+class Parameters;
+class NodeSets;
+class Nodes;
+class Vertices;
+class Results;
+class Constraints;
+class Loads;
+class Materials;
+class Profiler;
+class Elements;
+/*}}}*/
+
+class FemModel {
+
+	/*no private members, as we need access to these datasets quite often!:*/
+
+	public:
+
+		int          nummodels;
+		int          solution_type;
+		int         *analysis_type_list;   //list of analyses this femmodel is going to carry out
+		int          analysis_counter;     //counter into analysis_type_list
+
+		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 
+		ISSM_MPI_Comm        comm;                  //communicator for this particular model
+
+		/*constructors, destructors: */
+		FemModel(int argc,char** argv,ISSM_MPI_Comm comm_init);
+		FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		~FemModel();
+
+		/*Methods:*/
+		void Echo();
+		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		void Solve(void);
+		void SetStaticComm();
+		void SetCurrentConfiguration(int configuration_type);
+		void SetCurrentConfiguration(int configuration_type,int analysis_type);
+
+		/*Modules*/ 
+		void MassFluxx(IssmDouble* presponse);
+		void MaxAbsVxx(IssmDouble* presponse);
+		void MaxAbsVyx(IssmDouble* presponse);
+		void MaxAbsVzx(IssmDouble* presponse);
+		void MaxVelx(IssmDouble* presponse);
+		void MaxVxx(IssmDouble* presponse);
+		void MaxVyx(IssmDouble* presponse);
+		void MaxVzx(IssmDouble* presponse);
+		void MinVelx(IssmDouble* presponse);
+		void MinVxx(IssmDouble* presponse);
+		void MinVyx(IssmDouble* presponse);
+		void MinVzx(IssmDouble* presponse);
+		void TotalSmbx(IssmDouble* pSmb);
+		void Divergencex(IssmDouble* pdiv);
+		void IceVolumex(IssmDouble* pV);
+		void IceVolumeAboveFloatationx(IssmDouble* pV);
+		void ElementResponsex(IssmDouble* presponse,int response_enum);
+		void BalancethicknessMisfitx(IssmDouble* pV);
+		void Balancethickness2Misfitx(IssmDouble* pV);
+		#ifdef  _HAVE_DAKOTA_
+		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
+		#endif
+		void RequestedOutputsx(Results **presults,char** requested_outputs, int numoutputs,bool save_results=true);
+		void RequestedOutputsx(Results **presults,int* requested_outputs, int numoutputs,bool save_results=true);
+		void RequestedDependentsx(void);
+		void Responsex(IssmDouble* presponse,int response_descriptor_enum);
+		void Responsex(IssmDouble* presponse,const char* response_descriptor);
+		void OutputControlsx(Results **presults);
+		void CostFunctionx(IssmDouble* pJ,IssmDouble** pJlist,int* pn);
+		void ThicknessAbsGradientx( IssmDouble* pJ);
+		#ifdef _HAVE_GIA_
+		void Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y);
+		#endif
+		void TimeAdaptx(IssmDouble* pdt);
+		void UpdateConstraintsx(void);
+		int  UpdateVertexPositionsx(void);
+		void UpdateConstraintsExtrudeFromBasex();
+		void UpdateConstraintsExtrudeFromTopx();
+		void HydrologyEPLupdateDomainx(void);
+		//		void HydrologyEPLThicknessx(void);
+		void UpdateConstraintsL2ProjectionEPLx(void);
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/GiaDeflectionCoreArgs.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/GiaDeflectionCoreArgs.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/GiaDeflectionCoreArgs.h	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file:  GiaDeflectionCoreArgs.h
+ * \brief place holder for arguments to the GiaDeflectionCoreArgs routine
+ */ 
+
+#ifndef _GIADEFLECTIONCOREARGS_H_
+#define _GIADEFLECTIONCOREARGS_H_
+
+struct GiaDeflectionCoreArgs{
+
+	/*inputs: */
+	IssmDouble ri; //radial distance from center of disk to vertex  i
+	IssmDouble re; //radius of disk
+	IssmDouble* hes; //loading history (in ice thickness)
+	IssmDouble* times; //loading history times
+	int numtimes; //loading history length
+	IssmDouble currenttime; 
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_viscosity;
+	IssmDouble mantle_density;
+	IssmDouble lithosphere_thickness;
+
+	/*gia solution parameters: */
+	int iedge;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*constants: */
+	IssmDouble yts;
+
+	/*debug info: */
+	int        idisk; //id of the element we are running the gia code in.
+
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.cpp	(revision 18231)
@@ -0,0 +1,230 @@
+/*!\file Hook.cpp
+ * \brief: implementation of the Hook object: see Hook.h for more explanations.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./classes.h"
+#include "../shared/Enum/Enum.h"
+#include "../shared/shared.h"
+
+/*Constructor/Destructors*/
+Hook::Hook(){/*{{{*/
+	this->num     = 0;
+	this->objects = NULL;
+	this->ids     = NULL;
+	this->offsets = NULL;
+}
+/*}}}*/
+Hook::Hook(int* in_ids, int in_num){/*{{{*/
+
+	/*Get number of objects to hook*/
+	this->num=in_num;
+
+	/*Get out if num=0*/
+	if (num==0){
+		/*Empty hook*/
+		this->ids     = NULL;
+		this->objects = NULL;
+		this->offsets = NULL;
+	}
+	else{
+		/*Allocate: */
+		this->objects=xNew<Object*>(this->num);
+		this->ids=xNew<int>(this->num);
+		this->offsets=xNew<int>(this->num);
+
+		/*Copy ids: */
+		for(int i=0;i<this->num;i++){
+			this->ids[i]     = in_ids[i];
+			this->objects[i] = NULL;
+			this->offsets[i] = 0;
+		}
+	}
+}
+/*}}}*/
+Hook::~Hook(){/*{{{*/
+	xDelete<Object*>(this->objects);
+	xDelete<int>(this->ids);
+	xDelete<int>(this->offsets);
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+void Hook::Echo(void){/*{{{*/
+	_assert_(this);
+	int i;
+	if (num){
+		_printf_("   Hook: \n");
+		_printf_("      num=" << this->num << "\n");
+		_printf_("      ids: ");
+		for(i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
+		_printf_("\n");
+		_printf_("      offsets: ");
+		for (i=0;i<this->num;i++) _printf_(this->offsets[i] << " ");
+		_printf_("\n");
+	}
+	else{
+		_printf_("   Hook: num=0 \n");
+	}
+}
+/*}}}*/
+void Hook::DeepEcho(void){/*{{{*/
+
+	int i;
+	if (num){
+		_printf_("   Hook: \n");
+		_printf_("      num=" << this->num << "\n");
+		_printf_("      ids: ");
+		for (i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
+		_printf_("\n");
+		_printf_("      offsets: ");
+		for (i=0;i<this->num;i++) _printf_(this->offsets[i] << " ");
+		_printf_("\n");
+		if (!objects) _printf_("      warning: object not hooked yet\n");
+		else{
+			_printf_("      objects:\n   ");
+			for (i=0;i<this->num;i++){
+				_printf_("         object " << i << "\n");
+				if(objects[i]) objects[i]->DeepEcho();
+				else           _printf_("            no object hooked yet (not configured)\n");
+			}
+		}
+	}
+	else{
+		_printf_("   Hook: num=0 \n");
+	}
+}
+/*}}}*/
+Object* Hook::copy(void){/*{{{*/
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*initalize output: */
+	output=new Hook();
+
+	/*copy in the fields: */
+	output->num=this->num;
+	if(output->num){
+		output->objects = xNew<Object*>(output->num);
+		output->ids     = xNew<int>(output->num);
+		output->offsets = xNew<int>(output->num);
+	}
+
+	for(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];
+	}
+
+	return (Object*)output;
+}
+/*}}}*/
+
+/*Hook management: */
+void Hook::configure(DataSet* dataset){/*{{{*/
+
+	/*intermediary: */
+	Object* object=NULL;
+	int i;
+
+	/*Checks if debugging mode*/
+	_assert_(this->num==0 || this->ids!=NULL);
+
+	for(i=0;i<this->num;i++){
+
+		/*is this object id -1? If so, drop this search, it was not requested: */
+		if (this->ids[i]==-1) continue;
+
+		/*Check whether existing this->objects are correct: */
+		if(this->objects[i]){
+			if(this->objects[i]->Id()==this->ids[i]) continue; //this node is good.
+			else this->objects[i]=NULL; //this node was incorrect, reset it.
+		}
+
+		/*May be the object this->offsets into this->objects are valid?: */
+		if(this->offsets[i]!=UNDEF){
+			/* Look at the this->offsets[i]'th node in the nodes dataset. If it has the correct id, 
+			 * we are good: */
+			object=(Object*)dataset->GetObjectByOffset(this->offsets[i]);
+			if (object->Id()==this->ids[i]){
+				this->objects[i]=object;
+				continue;
+			}
+			else this->offsets[i]=UNDEF; //object offset was wrong, reset it.
+		}
+
+		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
+		if(this->objects[i]==NULL){
+			this->objects[i]=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!");
+		}
+	}
+}
+/*}}}*/
+Object* Hook::delivers(void){/*{{{*/
+
+	/*first, check that we only have one T object in our object list: */
+	if (this->num!=1) _error_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
+
+	/*check NULL: */
+	if (this->objects==NULL) _error_("hook is not pointing to any object, objects pointer is NULL");
+
+	return *objects;
+}
+
+/*}}}*/
+Object** Hook::deliverp(void){/*{{{*/
+	return objects;
+}
+/*}}}*/
+int* Hook::Ids(void){/*{{{*/
+	return this->ids;
+}
+/*}}}*/
+int Hook::GetNum(void){/*{{{*/
+	return this->num;
+}
+/*}}}*/
+Hook* Hook::Spawn(int* indices, int numindices){/*{{{*/
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*allocate: */
+	output=new Hook();
+
+	/*If this Hook is empty, simply return*/
+	if(this->num==0){
+		output->num=0;
+		return output;
+	}
+
+	/*Else, check that we are requesting a half of num*/
+	if(numindices>this->num) _error_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
+
+	/*go pickup the correct objects, ids and offsets :*/
+	output->num=numindices;
+	if(output->num<1) _error_("Trying to spawn an empty ElementProperties!");
+
+	output->objects = xNew<Object*>(output->num);
+	output->ids     = xNew<int>(output->num);
+	output->offsets = xNew<int>(output->num);
+
+	for(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]];
+	}
+
+	return output;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Hook.h	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\file Hook.h
+ * \brief: header file for hook object.
+ * A hook is a class  that can store the id, offset, and object corresponding to this id and offset into a dataset.
+ * For example, an element has a hook to its nodes. A node has a hook to its vertex.  The hook abstracts the need for having
+ * ids and offsets (necesarry for proper configuration of an object) in our objects. 
+ */
+
+#ifndef _HOOK_H_
+#define _HOOK_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+class Hook{
+
+	private: 
+
+		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:
+
+		/*Hook constructors, destructors: {{{*/
+		Hook();
+		Hook(int* ids, int num);
+		~Hook();
+		/*}}}*/
+		/*Object like functionality:{{{*/
+		void       Echo(void);
+		void       DeepEcho(void);
+		Object*    copy(void);
+		/*}}}*/
+		/*Hook management: {{{*/
+		Object*    delivers(void); //single object deliver
+		Object**   deliverp(void); //deliver all objects
+		void       configure(DataSet* dataset);
+		Hook*      Spawn(int* indices, int numindices);
+		int*       Ids(void);
+		int        GetNum(void);
+		/*}}}*/
+};
+
+#endif  /* _HOOK_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.cpp	(revision 18231)
@@ -0,0 +1,197 @@
+/*!\file IndependentObject.c
+ * \brief: implementation of the IndependentObject object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "../shared/shared.h"
+#include "IoModel.h"
+
+/*IndependentObject constructors and destructor*/
+IndependentObject::IndependentObject(){/*{{{*/
+	this->name=NoneEnum;
+	this->type=0;
+	this->numberofindependents=0;
+}
+/*}}}*/
+IndependentObject::IndependentObject(int in_name, int in_type){/*{{{*/
+
+	this->numberofindependents=0;
+	this->name=in_name;
+	this->type=in_type;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an IndependentObject of type " << in_type);
+
+}
+/*}}}*/
+IndependentObject::~IndependentObject(){ //destructor/*{{{*/
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void IndependentObject::Echo(void){/*{{{*/
+
+	_printf_("IndependentObject:\n");
+	_printf_("   name: " << EnumToStringx(this->name) << "\n");
+	if(this->type==0)
+		_printf_("   type: scalar\n");
+	else if(this->type==1)
+		_printf_("   type: vertex\n");
+	else
+		_error_(" unknown type: " << this->type);
+	_printf_("   numberofindependents: " << this->numberofindependents << "\n");
+}
+/*}}}*/
+void IndependentObject::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+int    IndependentObject::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int IndependentObject::ObjectEnum(void){/*{{{*/
+
+	return IndependentObjectEnum;
+
+}
+/*}}}*/
+Object* IndependentObject::copy(void) { /*{{{*/
+
+	IndependentObject* object=new IndependentObject();
+	object->name=this->name;
+	object->type=this->type;
+	object->numberofindependents=this->numberofindependents;
+
+	return  object;
+} /*}}}*/
+
+/*IndependentObject methods: */
+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;
+		}
+
+		ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
+
+		/*Ok, we are almost done. scalar is now an independent variable. We don't want this variable to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent variable inthe iomodel->data[name] data slot. Because this data slot holds double*, we allocate a sizeof(double)
+		 space for it: */
+		scalar_slot=xNew<IssmDouble>(1); *scalar_slot=scalar;
+
+		iomodel->data[name]=scalar_slot;
+		iomodel->independents[name]=true;
+
+		//finally, record the number of independents:
+		this->numberofindependents=1;
+
+	} /*}}}*/
+	else if(type==1){ /* vector: {{{*/
+
+		FILE* fid=NULL;
+		int M,N;
+		IssmPDouble* buffer=NULL; //a buffer to read the data from disk
+		IssmDouble* matrix=NULL; //our independent variable
+		int code=0;
+
+		/*Set file pointer to beginning of the data: */
+		fid=iomodel->SetFilePointerToData(&code,NULL,name);
+		if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(name));
+
+		/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+		/*numberofelements: */
+		if(my_rank==0){  
+			if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+		}
+		ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+		if(my_rank==0){  
+			if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+		}
+		ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+		/*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*/
+			}
+			ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
+
+			xDelete<IssmPDouble>(buffer);
+		}
+		else _error_("cannot declare the independent variable " << EnumToStringx(name) <<  "if it's empty!");
+
+		/*Ok, we are almost done. Matrix is now a independent matrix. We don't want this matrix to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent matrix inthe iomodel->data[name] data slot: */
+		iomodel->data[name]=matrix;
+		iomodel->independents[name]=true;
+
+		//Finally, record the number of independents created: 
+		this->numberofindependents=M*N;
+
+	}/*}}}*/
+	else _error_("should not have a type of " << type);
+
+	#endif
+}
+/*}}}*/
+int  IndependentObject::NumIndependents(void){/*{{{*/
+
+	return this->numberofindependents;;
+}
+/*}}}*/
+void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){/*{{{*/
+
+	int i;
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		xp[0]=*(data[name]);
+	}
+	else if(type==1){ /* vector:*/
+		IssmDouble* values=data[name];
+		for(i=0;i<this->numberofindependents;i++){
+			xp[i]=values[i];
+		}
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IndependentObject.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*!\file: IndependentObject.h
+ * \brief prototype for IndependentObject.h
+ */ 
+
+#ifndef _INDEPENDENTOBJECT_H_
+#define  _INDEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+class IoModel;
+
+class IndependentObject: public Object{
+
+	public:
+
+		int name;
+		int type;  /*0: scalar, 1: vertex*/
+		int numberofindependents;
+
+		/*IndependentObject constructors, destructors {{{*/
+		IndependentObject();
+		IndependentObject(int name, int type);
+		~IndependentObject();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy(void);
+		/*}}}*/
+		/*IndependentObject methods: {{{*/
+		void FetchIndependent(IoModel* iomodel);
+		int  NumIndependents(void);
+		void FillIndependents(IssmDouble** data, IssmDouble* xp);
+		/*}}}*/
+
+};
+#endif //ifndef _INDEPENDENTOBJECT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.cpp	(revision 18231)
@@ -0,0 +1,150 @@
+/*!\file BoolInput.c
+ * \brief: implementation of the BoolInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*BoolInput constructors and destructor*/
+BoolInput::BoolInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+BoolInput::BoolInput(int in_enum_type,bool in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+BoolInput::~BoolInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void BoolInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void BoolInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   BoolInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<(value?"true":"false") << "\n");
+}
+/*}}}*/
+int    BoolInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int BoolInput::ObjectEnum(void){/*{{{*/
+
+	return BoolInputEnum;
+
+}
+/*}}}*/
+Object* BoolInput::copy() {/*{{{*/
+
+	return new BoolInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*BoolInput management*/
+int BoolInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* BoolInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+		/*output*/
+		BoolInput* outinput=new BoolInput();
+
+		/*only copy current value*/
+		outinput->enum_type=this->enum_type;
+		outinput->value=this->value;
+
+		/*Assign output*/
+		return outinput;
+
+}
+/*}}}*/
+Input* BoolInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+		/*output*/
+		BoolInput* outinput=new BoolInput();
+
+		/*only copy current value*/
+		outinput->enum_type=this->enum_type;
+		outinput->value=this->value;
+
+		/*Assign output*/
+		return outinput;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void BoolInput::GetInputValue(bool* pvalue){/*{{{*/
+	*pvalue=value;
+}
+/*}}}*/
+void BoolInput::GetInputValue(int* pvalue){_error_("not supported yet!");}/*{{{*/
+/*}}}*/
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}/*{{{*/
+/*}}}*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}/*{{{*/
+/*}}}*/
+void BoolInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void BoolInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+	/*square of a bool is the bool itself: */
+	*psquaremin=value;
+}
+/*}}}*/
+void BoolInput::Scale(IssmDouble scale_factor){/*{{{*/
+	/*a bool cannot be scaled: */
+}
+/*}}}*/
+void BoolInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	BoolInput*  xboolinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xboolinput=(BoolInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case BoolInputEnum:
+			this->value=reCast<bool,IssmDouble>(this->value+scalar*xboolinput->value);
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+void BoolInput::Extrude(void){/*{{{*/
+
+	/*do nothing*/
+	return;
+}
+/*}}}*/
+void BoolInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+void BoolInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/BoolInput.h	(revision 18231)
@@ -0,0 +1,72 @@
+/*! \file BoolInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _BOOLINPUT_H_
+#define _BOOLINPUT_H_
+
+/*Headers:*/
+#include "./Input.h"
+
+class BoolInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int  enum_type;
+		bool value;
+
+		/*BoolInput constructors, destructors: {{{*/
+		BoolInput();
+		BoolInput(int enum_type,bool value);
+		~BoolInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*BoolInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		int  GetResultInterpolation(void){return P0Enum;};
+		int  GetResultNumberOfNodes(void){return 1;};
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		IssmDouble Max(void){_error_("Max not implemented for booleans");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for booleans");};
+		IssmDouble Min(void){_error_("Min not implemented for booleans");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for booleans");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _BOOLINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.cpp	(revision 18231)
@@ -0,0 +1,252 @@
+/*!\file ControlInput.c
+ * \brief: implementation of the ControlInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*ControlInput constructors and destructor*/
+ControlInput::ControlInput(){/*{{{*/
+	control_id  = 0;
+	values      = NULL;
+	savedvalues = NULL;
+	minvalues   = NULL;
+	maxvalues   = NULL;
+	gradient    = NULL;
+}
+/*}}}*/
+ControlInput::ControlInput(int in_enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){/*{{{*/
+
+	control_id=id;
+	enum_type=in_enum_type;
+
+	switch(enum_input){
+		case TriaInputEnum:
+			values     =new TriaInput(enum_type,pvalues,P1Enum);
+			savedvalues=new TriaInput(enum_type,pvalues,P1Enum);
+			minvalues  =new TriaInput(enum_type,pmin,P1Enum);
+			maxvalues  =new TriaInput(enum_type,pmax,P1Enum);
+			break;
+		case PentaInputEnum:
+			values     =new PentaInput(enum_type,pvalues,P1Enum);
+			savedvalues=new PentaInput(enum_type,pvalues,P1Enum);
+			minvalues  =new PentaInput(enum_type,pmin,P1Enum);
+			maxvalues  =new PentaInput(enum_type,pmax,P1Enum);
+			break;
+		default:
+			_error_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
+	}
+	gradient   =NULL;
+}
+/*}}}*/
+ControlInput::~ControlInput(){/*{{{*/
+	delete values;
+	delete savedvalues;
+	delete minvalues;
+	delete maxvalues;
+	delete gradient;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void ControlInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void ControlInput::DeepEcho(void){/*{{{*/
+
+	_printf_("ControlInput:\n");
+	_printf_(setw(15)<<"   ControlInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<"\n");
+	_printf_("---values: \n");     if (values)      values->Echo();
+	_printf_("---savedvalues: \n");if (savedvalues) savedvalues->Echo();
+	_printf_("---minvalues: \n");  if (minvalues)   minvalues->Echo();
+	_printf_("---maxvalues: \n");  if (maxvalues)   maxvalues->Echo();
+	_printf_("---gradient: \n");   if (gradient)    gradient->Echo();
+}
+/*}}}*/
+int    ControlInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int ControlInput::ObjectEnum(void){/*{{{*/
+
+	return ControlInputEnum;
+
+}
+/*}}}*/
+Object* ControlInput::copy() {/*{{{*/
+
+	ControlInput* output=NULL;
+
+	output = new ControlInput();
+	output->enum_type=this->enum_type;
+	output->control_id=this->control_id;
+
+	if(values)      output->values      = dynamic_cast<Input*>(this->values->copy());
+	if(savedvalues) output->savedvalues = dynamic_cast<Input*>(this->savedvalues->copy());
+	if(minvalues)   output->minvalues   = dynamic_cast<Input*>(this->minvalues->copy());
+	if(maxvalues)   output->maxvalues   = dynamic_cast<Input*>(this->maxvalues->copy());
+	if(gradient)    output->gradient    = dynamic_cast<Input*>(this->gradient->copy());
+
+	return output;
+}
+/*}}}*/
+
+/*ControlInput management*/
+int ControlInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void ControlInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+	values->AXPY(xinput,scalar);
+}/*}}}*/
+void ControlInput::Constrain(void){/*{{{*/
+
+	Input* newvalues=NULL;
+
+	newvalues=this->values->PointwiseMin(maxvalues);
+	delete values; this->values=newvalues;
+	newvalues=this->values->PointwiseMax(minvalues);
+	delete values; this->values=newvalues;
+}/*}}}*/
+void ControlInput::Constrain(IssmDouble min, IssmDouble max){/*{{{*/
+	   values->Constrain(min,max);
+}/*}}}*/
+void ControlInput::Extrude(void){/*{{{*/
+	values->Extrude();
+	savedvalues->Extrude();
+	//gradient->Extrude();
+}/*}}}*/
+int  ControlInput::GetResultInterpolation(void){/*{{{*/
+
+	return values->GetResultInterpolation();
+
+}
+/*}}}*/
+int  ControlInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return values->GetResultNumberOfNodes();
+
+}
+/*}}}*/
+void ControlInput::GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){/*{{{*/
+	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
+}/*}}}*/
+void ControlInput::ScaleGradient(IssmDouble scaling_factor){/*{{{*/
+	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
+	gradient->Scale(scaling_factor);
+}/*}}}*/
+void ControlInput::SetGradient(Input* gradient_in){/*{{{*/
+
+	/*Get enum for current gradient*/
+	switch(this->control_id){
+		case 1:
+			gradient_in->ChangeEnum(Gradient1Enum);
+			break;
+		case 2:
+			gradient_in->ChangeEnum(Gradient2Enum);
+			break;
+		case 3:
+			gradient_in->ChangeEnum(Gradient3Enum);
+			break;
+		default:
+			_error_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
+	}
+
+	/*Delete old gradient and assign new gradient*/
+	if(gradient) delete gradient;
+	gradient=gradient_in;
+
+}/*}}}*/
+void ControlInput::SetInput(Input* in_input){/*{{{*/
+
+	delete values; this->values=in_input;
+	this->SaveValue(); //because this is what SpawnResult saves FIXME
+
+}/*}}}*/
+Input* ControlInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+	return values->SpawnTriaInput(index1,index2,index3);
+}/*}}}*/
+Input* ControlInput::SpawnSegInput(int index1,int index2){/*{{{*/
+	return values->SpawnSegInput(index1,index2);
+}/*}}}*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+	values->GetVectorFromInputs(vector,doflist);
+}/*}}}*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){/*{{{*/
+	 if(strcmp(data,"value")==0){
+		 _assert_(values);
+		 values->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"lowerbound")==0){
+		 _assert_(minvalues);
+		 minvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"upperbound")==0){
+		 _assert_(maxvalues);
+		 maxvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"gradient")==0){
+		 _assert_(gradient);
+		 gradient->GetVectorFromInputs(vector,doflist);
+	 }
+	 else{
+		 _error_("Data " << data << " not supported yet");
+	 }
+}/*}}}*/
+void ControlInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+	values->GetInputAverage(pvalue);
+}/*}}}*/
+void ControlInput::GetInputValue(bool* pvalue){/*{{{*/
+	values->GetInputValue(pvalue);
+}/*}}}*/
+void ControlInput::GetInputValue(int* pvalue){/*{{{*/
+	values->GetInputValue(pvalue);
+}/*}}}*/
+void ControlInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
+	values->GetInputValue(pvalue);
+}/*}}}*/
+void ControlInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+void ControlInput::GetGradientValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+	gradient->GetInputValue(pvalue,gauss);
+}/*}}}*/
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+IssmDouble ControlInput::Min(void){/*{{{*/
+
+	return values->Min();
+
+}
+/*}}}*/
+void ControlInput::SaveValue(void){/*{{{*/
+	if(!values) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(savedvalues) delete this->savedvalues;
+	this->savedvalues=dynamic_cast<Input*>(this->values->copy());
+}/*}}}*/
+void ControlInput::UpdateValue(IssmDouble scalar){/*{{{*/
+	if(!gradient)    _error_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
+	if(!savedvalues) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(values) delete this->values;
+	this->values=dynamic_cast<Input*>(this->savedvalues->copy());
+	this->values->AXPY(gradient,scalar);
+}/*}}}*/
+void ControlInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
+	values->VerticallyIntegrate(thickness_input);
+}/*}}}*/
+void ControlInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/ControlInput.h	(revision 18231)
@@ -0,0 +1,89 @@
+/*! \file ControlInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _CONTROLINPUT_H_
+#define _CONTROLINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class ControlInput: public Input{
+
+	public:
+		int    enum_type;
+		int    control_id;
+		Input* values;
+		Input* savedvalues;
+		Input* minvalues;
+		Input* maxvalues;
+		Input* gradient;
+
+		/*ControlInput constructors, destructors: {{{*/
+		ControlInput();
+		ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id);
+		~ControlInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ControlInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetGradientValue(IssmDouble* pvalue,Gauss* gauss);
+		void SetInput(Input* in_input);
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(void);
+		void Constrain(IssmDouble min,IssmDouble max);
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		int  GetResultInterpolation(void);
+		int  GetResultNumberOfNodes(void);
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist);
+		void ScaleGradient(IssmDouble scale);
+		void SetGradient(Input* gradient_in);
+		void UpdateValue(IssmDouble scalar);
+		void SaveValue(void);
+		/*}}}*/
+
+};
+#endif  /* _CONTROLINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.cpp	(revision 18231)
@@ -0,0 +1,159 @@
+/*!\file DatasetInput.c
+ * \brief: implementation of the datasetinput object
+ */
+/*Headers{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*DatasetInput constructors and destructor*/
+DatasetInput::DatasetInput(){/*{{{*/
+	enum_type = UNDEF;
+	inputs    = NULL;
+	numids    = 0;
+	ids       = NULL;
+}
+/*}}}*/
+DatasetInput::DatasetInput(int in_enum_type){/*{{{*/
+
+	enum_type = in_enum_type;
+	numids    = 0;
+	inputs    = new Inputs();
+	ids       = NULL;
+}
+/*}}}*/
+DatasetInput::~DatasetInput(){/*{{{*/
+	xDelete<int>(this->ids);
+	delete inputs;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DatasetInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void DatasetInput::DeepEcho(void){/*{{{*/
+
+	_printf_("DatasetInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   numids:"<< this->numids<< "\n");
+	_printf_("      ids: ");
+	for(int i=0;i<this->numids;i++) _printf_(this->ids[i]<<" ");
+	_printf_("\n");
+	_printf_("   inputs: \n"); inputs->Echo();
+}
+/*}}}*/
+int    DatasetInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DatasetInput::ObjectEnum(void){/*{{{*/
+
+	return DatasetInputEnum;
+
+}
+/*}}}*/
+Object* DatasetInput::copy() {/*{{{*/
+
+	DatasetInput* output=NULL;
+
+	output = new DatasetInput();
+	output->enum_type=this->enum_type;
+	output->inputs=(Inputs*)this->inputs->Copy();
+
+	return output;
+}
+/*}}}*/
+Input* DatasetInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	DatasetInput* outinput=NULL;
+
+	/*Create new Datasetinput (copy of current input)*/
+	outinput=new DatasetInput();
+	outinput->enum_type=this->enum_type;
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(index1,index2,index3));
+	outinput->numids=this->numids;
+	outinput->ids=xNew<int>(this->numids);
+	xMemCpy(outinput->ids,this->ids,this->numids);
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+Input* DatasetInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	/*output*/
+	DatasetInput* outinput=NULL;
+
+	/*Create new Datasetinput (copy of current input)*/
+	outinput=new DatasetInput();
+	outinput->enum_type=this->enum_type;
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnSegInputs(index1,index2));
+	outinput->numids=this->numids;
+	outinput->ids=xNew<int>(this->numids);
+	xMemCpy(outinput->ids,this->ids,this->numids);
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+
+/*DatasetInput management*/
+void DatasetInput::AddInput(Input* input,int id){/*{{{*/
+
+	_assert_(this->numids == this->inputs->Size());
+
+	int *old_ids = NULL;
+
+	if(this->numids>0){
+		old_ids=xNew<int>(this->numids);
+		xMemCpy(old_ids,this->ids,this->numids);
+		xDelete<int>(this->ids);
+	}
+
+	this->numids=this->numids+1;
+	this->ids=xNew<int>(this->numids);
+
+	if(this->numids>1){
+		xMemCpy(this->ids,old_ids,this->numids-1);
+		xDelete<int>(old_ids);
+	}
+
+	/*go ahead and plug: */
+	this->ids[this->numids-1]=id;
+	inputs->AddObject(input);
+
+	_assert_(this->numids == this->inputs->Size());
+}
+/*}}}*/
+int DatasetInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void DatasetInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
+void DatasetInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int id){/*{{{*/
+
+	int  offset = -1;
+	_assert_(this->numids == this->inputs->Size());
+
+	/*Get requested input within dataset*/
+	for(int i=0;i<this->numids;i++) if(this->ids[i]==id) offset=i;
+	if(offset<0) _error_("Could not find input of id "<<id);
+
+	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(offset));
+	input->GetInputValue(pvalue,gauss);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DatasetInput.h	(revision 18231)
@@ -0,0 +1,84 @@
+/*! \file DatasetInput.h 
+ *  \brief: header file for datasetinput object
+ */
+
+#ifndef _DATASETINPUT_H_
+#define _DATASETINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class DatasetInput: public Input{
+
+	public:
+		int     enum_type;
+		int     numids;
+		Inputs *inputs;
+		int    *ids;
+
+		/*DatasetInput constructors, destructors: {{{*/
+		DatasetInput();
+		DatasetInput(int enum_type);
+		~DatasetInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DatasetInput management: {{{*/
+		void   AddInput(Input* input,int id);
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(void){_error_("not implemented yet");};
+		void Constrain(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
+		int GetResultInterpolation(void){_error_("not implemented yet");};
+		int GetResultNumberOfNodes(void){_error_("not implemented yet");};
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){_error_("not implemented yet");};
+		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
+		void UpdateValue(IssmDouble scalar){_error_("not implemented yet");};
+		void SaveValue(void){_error_("not implemented yet");};
+		/*}}}*/
+
+};
+#endif  /* _DATASETINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.cpp	(revision 18231)
@@ -0,0 +1,264 @@
+/*!\file DoubleInput.c
+ * \brief: implementation of the DoubleInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*DoubleInput constructors and destructor*/
+DoubleInput::DoubleInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+DoubleInput::DoubleInput(int in_enum_type,IssmDouble in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+DoubleInput::~DoubleInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DoubleInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void DoubleInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   DoubleInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    DoubleInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleInput::ObjectEnum(void){/*{{{*/
+
+	return DoubleInputEnum;
+
+}
+/*}}}*/
+Object* DoubleInput::copy() {/*{{{*/
+
+	return new DoubleInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DoubleInput management*/
+int DoubleInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* DoubleInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	DoubleInput* outinput=new DoubleInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+Input* DoubleInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	/*output*/
+	DoubleInput* outinput=new DoubleInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void DoubleInput::GetInputValue(bool* pvalue){/*{{{*/
+	_error_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
+
+}
+/*}}}*/
+void DoubleInput::GetInputValue(int* pvalue){/*{{{*/
+	_error_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+
+}
+/*}}}*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
+
+	/*return value*/
+	*pvalue=value;
+}
+/*}}}*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){*pvalue=this->value;}/*{{{*/
+/*}}}*/
+void DoubleInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void DoubleInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	/*square min of a IssmDouble is the square of the IssmDouble itself: */
+	*psquaremin=pow(value,2);
+}
+/*}}}*/
+void DoubleInput::Scale(IssmDouble scale_factor){/*{{{*/
+	value=value*scale_factor;
+}
+/*}}}*/
+void DoubleInput::ConstrainMin(IssmDouble minimum){/*{{{*/
+	if (value<minimum) value=minimum;
+}
+/*}}}*/
+void DoubleInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	DoubleInput*  xIssmDoubleinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xIssmDoubleinput=(DoubleInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case DoubleInputEnum:
+			this->value=this->value+scalar*xIssmDoubleinput->value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=cm_min;
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=cm_max;
+
+}
+/*}}}*/
+IssmDouble DoubleInput::Max(void){/*{{{*/
+	return this->value;
+}
+/*}}}*/
+IssmDouble DoubleInput::MaxAbs(void){/*{{{*/
+	return fabs(this->value);
+}
+/*}}}*/
+IssmDouble DoubleInput::Min(void){/*{{{*/
+	return this->value;
+}
+/*}}}*/
+IssmDouble DoubleInput::MinAbs(void){/*{{{*/
+	return fabs(this->value);
+}
+/*}}}*/
+void DoubleInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+void DoubleInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+	*pvalue=value;
+}
+/*}}}*/
+void DoubleInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble thickness_value;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+
+	/*vertically integrate depending on type:*/
+	switch(thickness_input->ObjectEnum()){
+
+		case PentaInputEnum:
+			thickness_input->GetInputAverage(&thickness_value);
+			this->value=this->value*thickness_value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+Input* DoubleInput::PointwiseDivide(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       Bvalue;
+
+	/*Check that inputB is of the same type*/
+	inputB->GetInputAverage(&Bvalue);
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,this->value/Bvalue);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+Input* DoubleInput::PointwiseMin(Input* input){/*{{{*/
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       min;
+
+	/*Check that inputB is of the same type*/
+	if (input->Min() < this->Min()) min=input->Min();
+	else min=this->Min();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,min);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+Input* DoubleInput::PointwiseMax(Input* input){/*{{{*/
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       max;
+
+	/*Check that inputB is of the same type*/
+	if (input->Max() > this->Max()) max=input->Max();
+	else max=this->Max();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,max);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+void DoubleInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/DoubleInput.h	(revision 18231)
@@ -0,0 +1,75 @@
+/*! \file DoubleInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEINPUT_H_
+#define _DOUBLEINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class DoubleInput: public Input{
+
+	public:
+		int    enum_type;
+		IssmDouble value;
+
+		/*DoubleInput constructors, destructors: {{{*/
+		DoubleInput();
+		DoubleInput(int enum_type,IssmDouble value);
+		~DoubleInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DoubleInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		int  GetResultInterpolation(void){return P0Enum;};
+		int  GetResultNumberOfNodes(void){return 1;};
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _DOUBLEINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Input.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Input.h	(revision 18231)
@@ -0,0 +1,65 @@
+/*!\file:  Input.h
+ * \brief abstract class for Input object
+ */ 
+
+#ifndef _INPUT_H_
+#define _INPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+class Node;
+class Gauss;
+class Gauss;
+class GaussSeg;
+class Parameters;
+class Gauss;
+template <class doubletype> class Vector;
+/*}}}*/
+
+class Input: public Object{
+
+	public: 
+
+		virtual        ~Input(){};
+
+		virtual int  InstanceEnum()=0; 
+		virtual void GetInputValue(bool* pvalue)=0;
+		virtual void GetInputValue(int* pvalue)=0;
+		virtual void GetInputValue(IssmDouble* pvalue)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,Gauss* gauss)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,Gauss* gauss,int index)=0;
+		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss)=0;
+		virtual void GetInputAverage(IssmDouble* pvalue)=0;
+		virtual void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes)=0;
+		virtual void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime)=0;
+		virtual void ChangeEnum(int newenumtype)=0;
+		virtual void Configure(Parameters* parameters)=0;
+
+		virtual void   SquareMin(IssmDouble* psquaremin,Parameters* parameters)=0;
+		virtual void   ConstrainMin(IssmDouble minimum)=0;
+		virtual IssmDouble InfinityNorm(void)=0;
+		virtual IssmDouble MaxAbs(void)=0;
+		virtual IssmDouble MinAbs(void)=0;
+		virtual IssmDouble Max(void)=0;
+		virtual IssmDouble Min(void)=0;
+		virtual void   Set(IssmDouble setvalue)=0;
+		virtual void   Scale(IssmDouble scale_factor)=0;
+		virtual void   AXPY(Input* xinput,IssmDouble scalar)=0;
+		virtual void   Constrain(IssmDouble cm_min, IssmDouble cm_max)=0;
+		virtual void   VerticallyIntegrate(Input* thickness_input)=0;
+		virtual void   Extrude()=0;
+		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
+
+		virtual Input* SpawnTriaInput(int index1,int index2,int index3)=0;
+		virtual Input* SpawnSegInput(int index1,int index2)=0;
+		virtual Input* PointwiseDivide(Input* inputB)=0;
+		virtual Input* PointwiseMax(Input* inputmax)=0;
+		virtual Input* PointwiseMin(Input* inputmin)=0;
+		virtual int  GetResultInterpolation(void)=0;
+		virtual int  GetResultNumberOfNodes(void)=0;
+		virtual void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.cpp	(revision 18231)
@@ -0,0 +1,431 @@
+/*
+ * \file Inputs.c
+ * \brief: implementation of the Inputs class, derived from DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Input.h"
+#include "./Inputs.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Inputs::Inputs(){/*{{{*/
+	return;
+}
+/*}}}*/
+Inputs::~Inputs(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+void Inputs::GetInputValue(bool* pvalue,int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+void Inputs::GetInputValue(int* pvalue,int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object); 
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputAverage(pvalue);
+
+}
+/*}}}*/
+int  Inputs::AddInput(Input* in_input){/*{{{*/
+
+	/*First, go through dataset of inputs and check whether any input 
+	 * with the same name is already in. If so, erase the corresponding 
+	 * object before adding this new one: */
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	/*In debugging mode, check that the input is not a NULL pointer*/
+	_assert_(in_input);
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==in_input->InstanceEnum()){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+	this->AddObject(in_input);
+
+	return 1;
+}
+/*}}}*/
+void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){/*{{{*/
+
+	/*Go through dataset of inputs and look for input with 
+	 * same enum as input enum, once found, just change its name */
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	/*Delete existing input of newenumtype if it exists*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==newenumtype){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+
+	/*Change enum_type of input of oldenumtype*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==oldenumtype){
+			input->ChangeEnum(newenumtype);
+			break;
+		}
+	}
+}
+/*}}}*/
+void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){/*{{{*/
+
+	/*Find x and y inputs: */
+	Input* constrain_input=dynamic_cast<Input*>(this->GetInput(constrain_enum));
+
+	/*some checks: */
+	if(!constrain_input) _error_("input " << EnumToStringx(constrain_enum) << " could not be found!");
+
+	/*Apply ContrainMin: */
+	constrain_input->ConstrainMin(minimum);
+}
+/*}}}*/
+IssmDouble Inputs::InfinityNorm(int enumtype){/*{{{*/
+
+	/*Output*/
+	IssmDouble norm;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		norm=input->InfinityNorm();
+	}
+	else{
+		norm=0;
+	}
+
+	/*Return output*/
+	return norm;
+}
+/*}}}*/
+IssmDouble Inputs::Max(int enumtype){/*{{{*/
+
+	/*Output*/
+	IssmDouble max;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->Max();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+IssmDouble Inputs::MaxAbs(int enumtype){/*{{{*/
+
+	/*Output*/
+	IssmDouble max;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->MaxAbs();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+IssmDouble Inputs::Min(int enumtype){/*{{{*/
+
+	/*Output*/
+	IssmDouble min;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->Min();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+IssmDouble Inputs::MinAbs(int enumtype){/*{{{*/
+
+	/*Output*/
+	IssmDouble min;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->MinAbs();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+Input* Inputs::GetInput(int enum_name){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==enum_name){
+			return input;
+		}
+	}
+	return NULL;
+}
+/*}}}*/
+int  Inputs::DeleteInput(int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==enum_type){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+
+	return 1;
+
+}
+/*}}}*/
+void  Inputs::DuplicateInput(int original_enum,int new_enum){/*{{{*/
+
+	/*Make a copy of the original input: */
+	Input* original=dynamic_cast<Input*>(this->GetInput(original_enum));
+	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
+	Input* copy=dynamic_cast<Input*>(original->copy());
+
+	/*Change copy enum to reinitialized_enum: */
+	copy->ChangeEnum(new_enum);
+
+	/*Add copy into inputs, it will wipe off the one already there: */
+	this->AddInput(dynamic_cast<Input*>(copy));
+}
+/*}}}*/
+Inputs* Inputs::SpawnTriaInputs(int index1,int index2,int index3){/*{{{*/
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	Input* inputin=NULL;
+	Input* inputout=NULL;
+
+	/*Output*/
+	Inputs* newinputs=new Inputs();
+
+	/*Go through inputs and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new input*/
+		inputin=dynamic_cast<Input*>(*object);
+		inputout=inputin->SpawnTriaInput(index1,index2,index3);
+
+		/*Add input to new inputs*/
+		newinputs->AddObject(inputout);
+	}
+
+	/*Assign output pointer*/
+	return newinputs;
+}
+/*}}}*/
+Inputs* Inputs::SpawnSegInputs(int index1,int index2){/*{{{*/
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	Input* inputin=NULL;
+	Input* inputout=NULL;
+
+	/*Output*/
+	Inputs* newinputs=new Inputs();
+
+	/*Go through inputs and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new input*/
+		inputin=dynamic_cast<Input*>(*object);
+		inputout=inputin->SpawnSegInput(index1,index2);
+
+		/*Add input to new inputs*/
+		newinputs->AddObject(inputout);
+	}
+
+	/*Assign output pointer*/
+	return newinputs;
+}
+/*}}}*/
+void  Inputs::AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum){/*{{{*/
+
+	/*Find x and y inputs: */
+	Input* xinput=dynamic_cast<Input*>(this->GetInput(inputx_enum));
+	Input* yinput=dynamic_cast<Input*>(this->GetInput(inputy_enum));
+
+	/*some checks: */
+	if(!xinput) _error_("input " << EnumToStringx(inputx_enum) << " could not be found!");
+	if(!yinput) _error_("input " << EnumToStringx(inputy_enum) << " could not be found!");
+
+	/*Apply AXPY: */
+	yinput->AXPY(xinput,scalar);
+}
+/*}}}*/
+void Inputs::Configure(Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		input->Configure(parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/Inputs.h	(revision 18231)
@@ -0,0 +1,48 @@
+#ifndef _CONTAINER_INPUTS_H_
+#define _CONTAINER_INPUTS_H_
+
+/*forward declarations */
+class Parameters;
+class Input;
+
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*! \brief Declaration of Inputs class.
+ *
+ * Declaration of Inputs class.  Inputs are vector lists (Containers) of Input objects.
+ */ 
+class Inputs: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Inputs();
+		~Inputs();
+
+		/*numerics*/
+		int         AddInput(Input* in_input);
+		void        ChangeEnum(int enumtype,int new_enumtype);
+		void        ConstrainMin(int constrain_enum, IssmDouble minimum);
+		int         DeleteInput(int enum_type);
+		void        DuplicateInput(int original_enum,int new_enum);
+		Input*      GetInput(int enum_name);
+		Inputs*     SpawnTriaInputs(int position);//TO BE REMOVED (replaced by the other one)
+		Inputs*     SpawnTriaInputs(int index1,int index2,int index3);
+		Inputs*     SpawnSegInputs(int index1,int index2);
+		Inputs*     SpawnSegInputs(int position);
+		void        AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum);
+		IssmDouble  InfinityNorm(int enumtype);
+		IssmDouble  Max(int enumtype);
+		IssmDouble  MaxAbs(int enumtype);
+		IssmDouble  Min(int enumtype);
+		IssmDouble  MinAbs(int enumtype);
+		void        GetInputAverage(IssmDouble* pvalue, int enum_type);
+		void        GetInputValue(bool* pvalue,int enum_type);
+		void        GetInputValue(int* pvalue,int enum_type);
+		void        GetInputValue(IssmDouble* pvalue,int enum_type);
+		void        Configure(Parameters* parameters);
+
+};
+
+#endif //ifndef _INPUTS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.cpp	(revision 18231)
@@ -0,0 +1,155 @@
+/*!\file IntInput.c
+ * \brief: implementation of the IntInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*IntInput constructors and destructor*/
+IntInput::IntInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+IntInput::IntInput(int in_enum_type,IssmInt in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+IntInput::~IntInput(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void IntInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   IntInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    IntInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int IntInput::ObjectEnum(void){/*{{{*/
+
+	return IntInputEnum;
+
+}
+/*}}}*/
+Object* IntInput::copy() {/*{{{*/
+
+	return new IntInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*IntInput management*/
+void IntInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+int IntInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* IntInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	IntInput* outinput=new IntInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+Input* IntInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	/*output*/
+	IntInput* outinput=new IntInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+
+/*Object functions*/
+void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}/*{{{*/
+/*}}}*/
+void IntInput::GetInputValue(int* pvalue){/*{{{*/
+	*pvalue=value;
+}
+/*}}}*/
+void IntInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
+	_error_("IntInput cannot return a IssmDouble in parallel");
+}
+/*}}}*/
+void IntInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}/*{{{*/
+/*}}}*/
+void IntInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void IntInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	/*square min of an integer is the square of the integer itself: */
+	*psquaremin=pow((IssmDouble)value,2);
+}
+/*}}}*/
+void IntInput::Scale(IssmDouble scale_factor){/*{{{*/
+	IssmDouble dvalue=(IssmDouble)value*scale_factor;
+	value=reCast<int>(dvalue);
+}
+/*}}}*/
+void IntInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	IssmDouble dvalue;
+	IntInput*  xintinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xintinput=(IntInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case IntInputEnum:
+			dvalue=(IssmDouble)this->value+scalar*(IssmDouble)xintinput->value;
+			this->value=reCast<int>(dvalue);
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+void IntInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=reCast<int>(cm_min);
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=reCast<int>(cm_max);
+
+}
+/*}}}*/
+void IntInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+void IntInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/IntInput.h	(revision 18231)
@@ -0,0 +1,76 @@
+/*! \file IntInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTINPUT_H_
+#define _INTINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class IntInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmInt value;
+
+		/*IntInput constructors, destructors: {{{*/
+		IntInput();
+		IntInput(int enum_type,IssmInt value);
+		~IntInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*IntInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		int  GetResultInterpolation(void){return P0Enum;};
+		int  GetResultNumberOfNodes(void){return 1;};
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for integers");};
+		IssmDouble Max(void){_error_("Max not implemented for integers");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for integers");};
+		IssmDouble Min(void){_error_("Min not implemented for integers");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for integers");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _INTINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.cpp	(revision 18231)
@@ -0,0 +1,425 @@
+/*!\file PentaInput.c
+ * \brief: implementation of the PentaInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*PentaInput constructors and destructor*/
+PentaInput::PentaInput(){/*{{{*/
+	values = NULL;
+}
+/*}}}*/
+PentaInput::PentaInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes(this->interpolation_type));
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+}
+/*}}}*/
+PentaInput::~PentaInput(){/*{{{*/
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void PentaInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void PentaInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   PentaInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("]\n");
+}
+/*}}}*/
+int    PentaInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int PentaInput::ObjectEnum(void){/*{{{*/
+
+	return PentaInputEnum;
+
+}
+/*}}}*/
+Object* PentaInput::copy() {/*{{{*/
+
+	return new PentaInput(this->enum_type,this->values,this->interpolation_type);
+
+}
+/*}}}*/
+
+/*PentaInput management*/
+int PentaInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* PentaInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	TriaInput* outinput=NULL;
+
+	if(this->interpolation_type==P0Enum){ 
+		outinput=new TriaInput(this->enum_type,&this->values[0],P0Enum);
+	}
+	else{
+		/*Assume P1 interpolation only for now*/
+		IssmDouble newvalues[3]; 
+
+		/*Create array of indices depending on location (0=base 1=surface)*/
+		int indices[3];
+		indices[0] = index1;
+		indices[1] = index2;
+		indices[2] = index3;
+
+		/*Create new input*/
+		for(int i=0;i<3;i++){
+			_assert_(indices[i]>=0 && indices[i]<6);
+			newvalues[i]=this->values[indices[i]];
+		}
+		outinput=new TriaInput(this->enum_type,&newvalues[0],P1Enum);
+	}
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+Input* PentaInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	_error_("not supported");
+}
+/*}}}*/
+int  PentaInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
+	return P1Enum;
+
+}
+/*}}}*/
+int  PentaInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);;
+
+}
+/*}}}*/
+void PentaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Some checks*/
+	_assert_(values);
+	_assert_(numnodes==nodesperelement);
+
+	/*Fill in arrays*/
+	for(int i=0;i<numnodes;i++) values[sid*numnodes + i] = this->values[i];
+}
+/*}}}*/
+
+/*Object functions*/
+void PentaInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		pvalue=&values[0];
+	}
+	else _error_("not implemented yet");
+}
+/*}}}*/
+void PentaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+
+	/*Call PentaRef function*/
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	PentaRef::GetInputValue(pvalue,&values[0],(GaussPenta*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*Call PentaRef function*/
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussPenta*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void PentaInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void PentaInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+
+/*Intermediary*/
+void PentaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble squaremin;
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(this->values[0],2);
+	for(int i=1;i<numnodes;i++){
+		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+void PentaInput::ConstrainMin(IssmDouble minimum){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+IssmDouble PentaInput::InfinityNorm(void){/*{{{*/
+
+	/*Output*/
+	IssmDouble norm=0.;
+	int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+IssmDouble PentaInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble PentaInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble PentaInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+IssmDouble PentaInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+void PentaInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+void PentaInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	PentaInput* xpentainput=NULL;
+
+	/*If xinput is a ControlInput, take its values directly*/
+	if(xinput->ObjectEnum()==ControlInputEnum){
+		xinput=((ControlInput*)xinput)->values;
+	}
+
+	/*xinput is of the same type, so cast it: */
+	if(xinput->ObjectEnum()!=PentaInputEnum)
+	  _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	xpentainput=(PentaInput*)xinput;
+	if(xpentainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xpentainput->interpolation_type));
+
+	/*Carry out the AXPY operation depending on type:*/
+	for(int i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xpentainput->values[i];
+
+}
+/*}}}*/
+void PentaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
+
+	int i;
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	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;
+
+}
+/*}}}*/
+void PentaInput::Extrude(void){/*{{{*/
+
+	switch(this->interpolation_type){
+		case P1Enum:
+			for(int i=0;i<3;i++) this->values[3+i]=this->values[i];
+			break;
+		default:
+			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
+	}
+}
+/*}}}*/
+void PentaInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
+
+	IssmDouble thickness;
+	IssmDouble value=0.;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+
+	/*vertically integrate depending on type (and use P1 interpolation from now on)*/
+	switch(this->interpolation_type){
+		case P1Enum:
+		case P1bubbleEnum:
+		case P2Enum:
+			  {
+				this->interpolation_type=P1Enum;
+				GaussPenta *gauss=new GaussPenta();
+				for(int iv=0;iv<3;iv++){
+					gauss->GaussVertex(iv);
+					thickness_input->GetInputValue(&thickness,gauss);
+					this->values[iv]=0.5*(this->values[iv]+this->values[iv+3]) * thickness;
+					this->values[iv+3]=this->values[iv];
+				}
+				delete gauss;
+				return; 
+			  }
+		default:
+			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
+	}
+}
+/*}}}*/
+Input* PentaInput::PointwiseDivide(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	PentaInput *xinputB  = NULL;
+	const int   numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Allocate intermediary*/
+	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
+
+	/*Create point wise sum*/
+	for(int i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,AdotBvalues,this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(AdotBvalues);
+	return outinput;
+
+}
+/*}}}*/
+Input* PentaInput::PointwiseMin(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	PentaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,&minvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(minvalues);
+	return outinput;
+}
+/*}}}*/
+Input* PentaInput::PointwiseMax(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	PentaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(maxvalues);
+	return outinput;
+}
+/*}}}*/
+void PentaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+	const int numvertices=6;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+} /*}}}*/
+void PentaInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/PentaInput.h	(revision 18231)
@@ -0,0 +1,75 @@
+/*! \file PentaInput.h 
+ *  \brief: header file for PentaInput object
+ */
+
+#ifndef _PENTAINPUT_H_
+#define _PENTAINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/PentaRef.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class PentaInput: public Input, public PentaRef{
+
+	public:
+		int         enum_type;
+		int         interpolation_type;
+		IssmDouble* values;
+
+		/*PentaInput constructors, destructors*/
+		PentaInput();
+		PentaInput(int enum_type,IssmDouble* values,int element_type_in);
+		~PentaInput();
+
+		/*Object virtual functions definitions */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*PentaInput management*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		int  GetResultInterpolation(void);
+		int  GetResultNumberOfNodes(void);
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*numerics*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+
+};
+#endif  /* _PENTAINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.cpp	(revision 18231)
@@ -0,0 +1,112 @@
+/*!\file SegInput.c
+ * \brief: implementation of the SegInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*SegInput constructors and destructor*/
+SegInput::SegInput(){/*{{{*/
+	values = NULL;
+}
+/*}}}*/
+SegInput::SegInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes(this->interpolation_type));
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+}
+/*}}}*/
+SegInput::~SegInput(){/*{{{*/
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void SegInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void SegInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   SegInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("]\n");
+}
+/*}}}*/
+int    SegInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int SegInput::ObjectEnum(void){/*{{{*/
+
+	return SegInputEnum;
+
+}
+/*}}}*/
+Object* SegInput::copy() {/*{{{*/
+
+	return new SegInput(this->enum_type,this->values,this->interpolation_type);
+
+}
+/*}}}*/
+
+/*SegInput management*/
+int SegInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void SegInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+void SegInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+
+	/*Call SegRef function*/
+	_assert_(gauss->Enum()==GaussSegEnum);
+	SegRef::GetInputValue(pvalue,&values[0],(GaussSeg*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	/*Call SegRef function*/
+	_assert_(gauss->Enum()==GaussSegEnum);
+	SegRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussSeg*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void SegInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
+IssmDouble SegInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/SegInput.h	(revision 18231)
@@ -0,0 +1,76 @@
+/*! \file SegInput.h 
+ *  \brief: header file for SegInput object
+ */
+
+#ifndef _SEGINPUT_H_
+#define _SEGINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/SegRef.h"
+class GaussSeg;
+class Gauss;
+/*}}}*/
+
+class SegInput: public Input,public SegRef{
+
+	public:
+		int         enum_type;
+		int         interpolation_type;
+		IssmDouble* values;
+
+		/*SegInput constructors, destructors*/
+		SegInput();
+		SegInput(int enum_type,IssmDouble* values,int element_type_in);
+		~SegInput();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*SegInput management:*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3){_error_("not supported yet");};
+		Input* SpawnSegInput(int index1,int index2){_error_("not implemented yet");};
+		Input* PointwiseDivide(Input* inputB){_error_("not supported yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not supported yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not supported yet");};
+		int  GetResultInterpolation(void){_error_("not implemented");};
+		int  GetResultNumberOfNodes(void){_error_("not implemented");};
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void   AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void   Configure(Parameters* parameters);
+
+		/*numerics*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
+
+};
+#endif  /* _SEGINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.cpp	(revision 18231)
@@ -0,0 +1,411 @@
+/*!\file TetraInput.c
+ * \brief: implementation of the TetraInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*TetraInput constructors and destructor*/
+TetraInput::TetraInput(){/*{{{*/
+	values = NULL;
+}
+/*}}}*/
+TetraInput::TetraInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes(this->interpolation_type));
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+}
+/*}}}*/
+TetraInput::~TetraInput(){/*{{{*/
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void TetraInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void TetraInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   TetraInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("] ("<<EnumToStringx(this->interpolation_type)<<")\n");
+}
+/*}}}*/
+int    TetraInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int TetraInput::ObjectEnum(void){/*{{{*/
+
+	return TetraInputEnum;
+
+}
+/*}}}*/
+Object* TetraInput::copy() {/*{{{*/
+
+	return new TetraInput(this->enum_type,this->values,this->interpolation_type);
+
+}
+/*}}}*/
+
+/*TetraInput management*/
+int TetraInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+int  TetraInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
+	return P1Enum;
+
+}
+/*}}}*/
+int  TetraInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);
+
+}
+/*}}}*/
+void TetraInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Some checks*/
+	_assert_(values);
+	_assert_(numnodes==nodesperelement);
+
+	/*Fill in arrays*/
+	for(int i=0;i<numnodes;i++) values[sid*numnodes + i] = this->values[i];
+}
+/*}}}*/
+
+/*Object functions*/
+void TetraInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+
+	/*Call TetraRef function*/
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	TetraRef::GetInputValue(pvalue,&values[0],(GaussTetra*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void TetraInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+
+	/*Call TetraRef function*/
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	TetraRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTetra*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void TetraInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void TetraInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+void TetraInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=0.; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+void TetraInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=currenttime; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+Input* TetraInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	TriaInput* outinput=NULL;
+
+	if(this->interpolation_type==P0Enum){ 
+		outinput=new TriaInput(this->enum_type,&this->values[0],P0Enum);
+	}
+	else{
+		/*Assume P1 interpolation only for now*/
+		IssmDouble newvalues[3]; 
+
+		/*Create array of indices depending on location (0=base 1=surface)*/
+		int indices[3];
+		indices[0] = index1;
+		indices[1] = index2;
+		indices[2] = index3;
+
+		/*Create new input*/
+		for(int i=0;i<3;i++){
+			_assert_(indices[i]>=0 && indices[i]<4);
+			newvalues[i]=this->values[indices[i]];
+		}
+		outinput=new TriaInput(this->enum_type,&newvalues[0],P1Enum);
+	}
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+
+/*Intermediary*/
+void TetraInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble squaremin;
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(this->values[0],2);
+	for(int i=1;i<numnodes;i++){
+		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+void TetraInput::ConstrainMin(IssmDouble minimum){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+IssmDouble TetraInput::InfinityNorm(void){/*{{{*/
+
+	/*Output*/
+	IssmDouble norm=0.;
+	int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+IssmDouble TetraInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble TetraInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble TetraInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+IssmDouble TetraInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+void TetraInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+void TetraInput::Set(IssmDouble setvalue){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++)values[i]=setvalue;
+}
+/*}}}*/
+void TetraInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	TetraInput*  xtriainput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	if(xinput->ObjectEnum()!=TetraInputEnum) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	xtriainput=(TetraInput*)xinput;
+	if(xtriainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+
+	/*Carry out the AXPY operation depending on type:*/
+	for(int i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriainput->values[i];
+
+}
+/*}}}*/
+void TetraInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
+
+	int i;
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	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;
+
+}
+/*}}}*/
+void TetraInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+	const int numvertices=4;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+} /*}}}*/
+Input* TetraInput::PointwiseMin(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TetraInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TetraInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TetraInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TetraInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Tetra vertex input (copy of current input)*/
+	outinput=new TetraInput(this->enum_type,&minvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(minvalues);
+	return outinput;
+
+}
+/*}}}*/
+Input* TetraInput::PointwiseMax(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TetraInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TetraInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TetraInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TetraInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Tetra vertex input (copy of current input)*/
+	outinput=new TetraInput(this->enum_type,&maxvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(maxvalues);
+	return outinput;
+
+}
+/*}}}*/
+Input* TetraInput::PointwiseDivide(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TetraInput* outinput=NULL;
+
+	/*Intermediaries*/
+	TetraInput *xinputB  = NULL;
+	const int   numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TetraInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TetraInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Allocate intermediary*/
+	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
+
+	/*Create point wise division*/
+	for(int i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Tetra vertex input (copy of current input)*/
+	outinput=new TetraInput(this->enum_type,AdotBvalues,this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(AdotBvalues);
+	return outinput;
+
+}
+/*}}}*/
+void TetraInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TetraInput.h	(revision 18231)
@@ -0,0 +1,76 @@
+/*! \file TetraInput.h 
+ *  \brief: header file for TetraInput object
+ */
+
+#ifndef _TETRAINPUT_H_
+#define _TETRAINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/TetraRef.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class TetraInput: public Input,public TetraRef{
+
+	public:
+		int         enum_type;
+		int         interpolation_type;
+		IssmDouble* values;
+
+		/*TetraInput constructors, destructors*/
+		TetraInput();
+		TetraInput(int enum_type,IssmDouble* values,int element_type_in);
+		~TetraInput();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*TetraInput management:*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2){_error_("not supported yet");};
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		int    GetResultInterpolation(void);
+		int    GetResultNumberOfNodes(void);
+		void   ResultToPatch(IssmDouble* values,int nodesperelement,int sid);
+		void   AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void   Configure(Parameters* parameters);
+
+		/*numerics*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue);
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+
+};
+#endif  /* _TETRAINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.cpp	(revision 18231)
@@ -0,0 +1,536 @@
+/*!\file TransientInput.c
+ * \brief: implementation of the TransientInput object
+ */
+/*Headers{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*TransientInput constructors and destructor*/
+TransientInput::TransientInput(){/*{{{*/
+
+	enum_type=UNDEF;
+	inputs=NULL;
+	this->numtimesteps=0;
+	this->parameters=NULL;
+	this->timesteps=NULL;
+
+}
+/*}}}*/
+TransientInput::TransientInput(int in_enum_type)/*{{{*/
+{
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Allocate values and timesteps, and copy: */
+	this->numtimesteps=0;
+	this->timesteps=NULL;
+	inputs = new Inputs();
+	this->parameters=NULL;
+
+}
+/*}}}*/
+TransientInput::TransientInput(int in_enum_type,IssmDouble* timesin,int N){/*{{{*/
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Allocate values and timesteps, and copy: */
+	this->numtimesteps=N;
+	this->timesteps=xNew<IssmDouble>(N);
+	xMemCpy(this->timesteps,timesin,N);
+
+	inputs = new Inputs();
+	this->parameters=NULL;
+}
+/*}}}*/
+TransientInput::~TransientInput(){/*{{{*/
+	xDelete(this->timesteps);
+	this->timesteps=NULL;
+	this->numtimesteps=0;
+	parameters=NULL;
+	delete this->inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void TransientInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void TransientInput::DeepEcho(void){/*{{{*/
+
+	int i;
+
+	_printf_("TransientInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   numtimesteps: " << this->numtimesteps << "\n");
+	_printf_("---inputs: \n"); 
+	for(i=0;i<this->numtimesteps;i++){
+		_printf_("   time: " << this->timesteps[i]<<"  ");
+		((Input*)this->inputs->GetObjectByOffset(i))->Echo();
+	}
+}
+/*}}}*/
+int    TransientInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int TransientInput::ObjectEnum(void){/*{{{*/
+
+	return TransientInputEnum;
+
+}
+/*}}}*/
+Object* TransientInput::copy() {/*{{{*/
+
+	TransientInput* output=NULL;
+
+	output = new TransientInput();
+	output->enum_type=this->enum_type;
+	output->numtimesteps=this->numtimesteps;
+	output->timesteps=xNew<IssmDouble>(this->numtimesteps);
+        xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
+	output->inputs=(Inputs*)this->inputs->Copy();
+	output->parameters=this->parameters;
+
+	return output;
+
+}
+/*}}}*/
+
+/*TransientInput management*/
+int TransientInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* TransientInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(index1,index2,index3);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+Input* TransientInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+	outinput->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+
+/*Object functions*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){/*{{{*/
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+void TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputDerivativeValue(p,xyz_list,gauss);
+
+	delete input;
+}
+/*}}}*/
+void TransientInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void TransientInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputAverage(pvalue);
+
+	delete input;
+
+}
+/*}}}*/
+void TransientInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
+
+	int i;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+
+	/*allocate: */
+	times=xNew<IssmDouble>(this->numtimesteps);
+	values=xNew<IssmDouble>(this->numtimesteps);
+
+	for(i=0;i<numtimesteps;i++){
+		Input* input=(Input*)this->inputs->GetObjectByOffset(i);
+		input->GetInputAverage(values+i);
+		times[i]=this->timesteps[i];
+	}
+
+	*pvalues=values;
+	*ptimes=times;
+	*pnumtimes=numtimesteps;
+}
+/*}}}*/
+void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
+
+	int         i;
+	IssmDouble *times  = NULL;
+	IssmDouble *values = NULL;
+	int         numsteps;
+	bool        iscurrenttime_included = false;
+
+	/*Figure out how many time steps we are going to return: */
+	numsteps=0;
+	for(i=0;i<numtimesteps;i++){
+		if(this->timesteps[i]==currenttime)iscurrenttime_included=true;
+		if (this->timesteps[i]>currenttime)break;
+		else numsteps++;
+	}
+	if(iscurrenttime_included==false)numsteps++;
+
+	/*allocate: */
+	times=xNew<IssmDouble>(numsteps);
+	values=xNew<IssmDouble>(numsteps);
+
+	for(i=0;i<numsteps;i++){
+
+		if((iscurrenttime_included==false) && (i==(numsteps-1))){
+
+			/*Retrieve interpolated values for current time step: */
+			Input* input=GetTimeInput(currenttime);
+			input->GetInputAverage(values+i);
+			times[i]=currenttime;
+		}
+		else{
+			Input* input=(Input*)this->inputs->GetObjectByOffset(i);
+			input->GetInputAverage(values+i);
+			times[i]=this->timesteps[i];
+		}
+	}
+
+	*pvalues=values;
+	*ptimes=times;
+	*pnumtimes=numtimesteps;
+}
+/*}}}*/
+
+/*Intermediary*/
+void TransientInput::AddTimeInput(Input* input,IssmDouble time){/*{{{*/
+
+	/*insert values at time step: */
+	if (this->numtimesteps>0 && time<=this->timesteps[this->numtimesteps-1]) _error_("timestep values must increase sequentially");
+
+	//copy timesteps, add the new time, delete previous timesteps, and add the new input: inputs->AddObject(input);
+	IssmDouble* old_timesteps=NULL;
+
+	if (this->numtimesteps > 0){
+		old_timesteps=xNew<IssmDouble>(this->numtimesteps);
+		xMemCpy(old_timesteps,this->timesteps,this->numtimesteps);
+		xDelete(this->timesteps);
+	}
+
+	this->numtimesteps=this->numtimesteps+1;
+	this->timesteps=xNew<IssmDouble>(this->numtimesteps);
+
+	if (this->numtimesteps > 1){
+		xMemCpy(this->timesteps,old_timesteps,this->numtimesteps-1);
+		xDelete(old_timesteps);
+	}
+
+	/*go ahead and plug: */
+	this->timesteps[this->numtimesteps-1]=time;
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+void TransientInput::AddTimeInput(Input* input){/*{{{*/
+
+	_assert_(this->inputs->Size()<this->numtimesteps);
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+int TransientInput::GetResultInterpolation(void){/*{{{*/
+
+	IssmDouble time;
+	int        output;
+
+	parameters->FindParam(&time,TimeEnum);
+	Input* input=GetTimeInput(time);
+	output = input->GetResultInterpolation();
+
+	/*Clean up and return*/
+	delete input;
+	return output;
+
+}
+/*}}}*/
+int TransientInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	IssmDouble time;
+	int        output;
+
+	parameters->FindParam(&time,TimeEnum);
+	Input* input=GetTimeInput(time);
+	output = input->GetResultNumberOfNodes();
+
+	/*Clean up and return*/
+	delete input;
+	return output;
+
+}
+/*}}}*/
+void TransientInput::Extrude(void){/*{{{*/
+
+	for(int i=0;i<this->numtimesteps;i++){
+		((Input*)this->inputs->GetObjectByOffset(i))->Extrude();
+	}
+}
+/*}}}*/
+void TransientInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->SquareMin(psquaremin,parameters);
+
+	delete input;
+
+}
+/*}}}*/
+IssmDouble TransientInput::InfinityNorm(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble infnorm;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	infnorm=input->InfinityNorm();
+
+	/*Clean-up and return*/
+	delete input;
+	return infnorm;
+}
+/*}}}*/
+IssmDouble TransientInput::Max(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble max;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	max=input->Max();
+
+	delete input;
+
+	return max;
+}
+/*}}}*/
+IssmDouble TransientInput::MaxAbs(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble maxabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	maxabs=input->MaxAbs();
+
+	/*Clean-up and return*/
+	delete input;
+	return maxabs;
+
+}
+/*}}}*/
+IssmDouble TransientInput::Min(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble min;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	min=input->Min();
+
+	/*Clean-up and return*/
+	delete input;
+	return min;
+
+}
+/*}}}*/
+IssmDouble TransientInput::MinAbs(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble minabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	minabs=input->MinAbs();
+
+	/*Clean-up and return*/
+	delete input;
+	return minabs;
+}
+/*}}}*/
+void TransientInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetVectorFromInputs(vector,doflist);
+
+	delete input;
+
+} /*}}}*/
+Input* TransientInput::GetTimeInput(IssmDouble intime){/*{{{*/
+
+	IssmDouble deltat;
+	IssmDouble alpha1,alpha2;
+	int        found;
+	int        offset;
+	bool       interp;
+
+	/*First, recover interp bool: */
+	this->parameters->FindParam(&interp,TimesteppingInterpForcingsEnum);
+
+	Input *input  = NULL;
+	Input *input1 = NULL;
+	Input *input2 = NULL;
+
+	/*go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	found=binary_search(&offset,intime,this->timesteps,this->numtimesteps);
+	if(!found) _error_("Input not found (is TransientInput sorted ?)");
+
+	if (offset==-1){
+		/*get values for the first time: */
+		_assert_(intime<this->timesteps[0]);
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
+	}
+	else if(offset==(this->numtimesteps-1) || !interp){
+		/*get values for the last time: */
+		_assert_(intime>=this->timesteps[offset]);
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(offset))->copy();
+	}
+	else {
+		/*get values between two times [offset:offset+1[, Interpolate linearly*/
+		_assert_(intime>=this->timesteps[offset] && intime<this->timesteps[offset+1]);
+		deltat=this->timesteps[offset+1]-this->timesteps[offset];
+		alpha2=(intime-this->timesteps[offset])/deltat;
+		alpha1=(1.0-alpha2);
+
+		input1=(Input*)this->inputs->GetObjectByOffset(offset); 
+		input2=(Input*)this->inputs->GetObjectByOffset(offset+1);
+
+		input=(Input*)input1->copy();
+		input->Scale(alpha1);
+		input->AXPY(input2,alpha2);
+	}
+
+	/*Assign output pointer*/
+	return input;
+}
+/*}}}*/
+void TransientInput::Configure(Parameters* parameters){/*{{{*/
+	this->parameters=parameters;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TransientInput.h	(revision 18231)
@@ -0,0 +1,83 @@
+/*! \file TransientInput.h 
+ *  \brief: header file for transientinput object
+ */
+
+#ifndef _TRANSIENTINPUT_H_
+#define _TRANSIENTINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class Gauss;
+class Parameters;
+class Gauss;
+/*}}}*/
+
+class TransientInput: public Input{
+
+	public:
+		int         enum_type;
+		int         numtimesteps;
+		Inputs     *inputs;
+		IssmDouble *timesteps;
+		Parameters *parameters;     //to find current time.
+
+		/*TransientInput constructors, destructors: {{{*/
+		TransientInput();
+		TransientInput(int enum_type);
+		TransientInput(int in_enum_type,IssmDouble* times,int N);
+		~TransientInput();
+		void AddTimeInput(Input* input,IssmDouble time);
+		void AddTimeInput(Input* input);
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TransientInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
+		int  GetResultInterpolation(void);
+		int  GetResultNumberOfNodes(void);
+		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetTimeValues(IssmDouble* values,IssmDouble time){_error_("not implemented yet");};
+		Input* GetTimeInput(IssmDouble time);
+		/*}}}*/
+
+};
+#endif  /* _TRANSIENTINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.cpp	(revision 18231)
@@ -0,0 +1,419 @@
+/*!\file TriaInput.c
+ * \brief: implementation of the TriaInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*TriaInput constructors and destructor*/
+TriaInput::TriaInput(){/*{{{*/
+	values = NULL;
+}
+/*}}}*/
+TriaInput::TriaInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes(this->interpolation_type));
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+}
+/*}}}*/
+TriaInput::~TriaInput(){/*{{{*/
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void TriaInput::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void TriaInput::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(15)<<"   TriaInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("] ("<<EnumToStringx(this->interpolation_type)<<")\n");
+}
+/*}}}*/
+int    TriaInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int TriaInput::ObjectEnum(void){/*{{{*/
+
+	return TriaInputEnum;
+
+}
+/*}}}*/
+Object* TriaInput::copy() {/*{{{*/
+
+	return new TriaInput(this->enum_type,this->values,this->interpolation_type);
+
+}
+/*}}}*/
+
+/*TriaInput management*/
+int TriaInput::InstanceEnum(void){/*{{{*/
+
+	return this->enum_type;
+
+}
+/*}}}*/
+Input* TriaInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
+
+	/*output*/
+	TriaInput* outinput=NULL;
+
+	/*Create new Tria input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&this->values[0],this->interpolation_type);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+Input* TriaInput::SpawnSegInput(int index1,int index2){/*{{{*/
+
+	/*output*/
+	SegInput* outinput=NULL;
+
+	if(this->interpolation_type==P0Enum){ 
+		outinput=new SegInput(this->enum_type,&this->values[0],P0Enum);
+	}
+	else{
+		/*Assume P1 interpolation only for now*/
+		IssmDouble newvalues[2];
+
+		/*Create array of indices depending on location (0=base 1=surface)*/
+		newvalues[0]=this->values[index1];
+		newvalues[1]=this->values[index2];
+
+		/*Create new Seg input*/
+		outinput=new SegInput(this->enum_type,&newvalues[0],P1Enum);
+	}
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+int  TriaInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
+	return P1Enum;
+
+}
+/*}}}*/
+int  TriaInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);
+
+}
+/*}}}*/
+void TriaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Some checks*/
+	_assert_(values);
+	_assert_(numnodes==nodesperelement);
+
+	/*Fill in arrays*/
+	for(int i=0;i<numnodes;i++) values[sid*numnodes + i] = this->values[i];
+}
+/*}}}*/
+
+/*Object functions*/
+void TriaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
+
+	/*Call TriaRef function*/
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	TriaRef::GetInputValue(pvalue,&values[0],(GaussTria*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+
+	/*Call TriaRef function*/
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTria*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void TriaInput::ChangeEnum(int newenumtype){/*{{{*/
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+void TriaInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+void TriaInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=0.; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+void TriaInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=currenttime; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+
+/*Intermediary*/
+void TriaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble squaremin;
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(this->values[0],2);
+	for(int i=1;i<numnodes;i++){
+		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+void TriaInput::ConstrainMin(IssmDouble minimum){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+IssmDouble TriaInput::InfinityNorm(void){/*{{{*/
+
+	/*Output*/
+	IssmDouble norm=0.;
+	int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+IssmDouble TriaInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble TriaInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+IssmDouble TriaInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+IssmDouble TriaInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+void TriaInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+void TriaInput::Set(IssmDouble setvalue){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	for(int i=0;i<numnodes;i++)values[i]=setvalue;
+}
+/*}}}*/
+void TriaInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+	TriaInput*  xtriainput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	if(xinput->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	xtriainput=(TriaInput*)xinput;
+	if(xtriainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+
+	/*Carry out the AXPY operation depending on type:*/
+	for(int i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriainput->values[i];
+
+}
+/*}}}*/
+void TriaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
+
+	int i;
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
+
+	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;
+
+}
+/*}}}*/
+void TriaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
+	const int numvertices=3;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+} /*}}}*/
+Input* TriaInput::PointwiseMin(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TriaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TriaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&minvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(minvalues);
+	return outinput;
+
+}
+/*}}}*/
+Input* TriaInput::PointwiseMax(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TriaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
+	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(maxvalues);
+	return outinput;
+
+}
+/*}}}*/
+Input* TriaInput::PointwiseDivide(Input* inputB){/*{{{*/
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	TriaInput *xinputB  = NULL;
+	const int   numnodes = this->NumberofNodes(this->interpolation_type);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=TriaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaInput*)inputB;
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
+
+	/*Allocate intermediary*/
+	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
+
+	/*Create point wise division*/
+	for(int i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,AdotBvalues,this->interpolation_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(AdotBvalues);
+	return outinput;
+
+}
+/*}}}*/
+void TriaInput::Configure(Parameters* parameters){/*{{{*/
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Inputs/TriaInput.h	(revision 18231)
@@ -0,0 +1,76 @@
+/*! \file TriaInput.h 
+ *  \brief: header file for TriaInput object
+ */
+
+#ifndef _TRIAINPUT_H_
+#define _TRIAINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/TriaRef.h"
+class Gauss;
+class Gauss;
+/*}}}*/
+
+class TriaInput: public Input,public TriaRef{
+
+	public:
+		int         enum_type;
+		int         interpolation_type;
+		IssmDouble* values;
+
+		/*TriaInput constructors, destructors*/
+		TriaInput();
+		TriaInput(int enum_type,IssmDouble* values,int element_type_in);
+		~TriaInput();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*TriaInput management:*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int index1,int index2,int index3);
+		Input* SpawnSegInput(int index1,int index2);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		int    GetResultInterpolation(void);
+		int    GetResultNumberOfNodes(void);
+		void   ResultToPatch(IssmDouble* values,int nodesperelement,int sid);
+		void   AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void   Configure(Parameters* parameters);
+
+		/*numerics*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list,Gauss* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Set(IssmDouble setvalue);
+		void Scale(IssmDouble scale_factor);
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+
+};
+#endif  /* _TRIAINPUT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.cpp	(revision 18231)
@@ -0,0 +1,1740 @@
+/*! \file IoModel.cpp
+ * \brief  file containing the methods that will help in processing the input data coming 
+ * into ISSM, from Matlab, or through a binary file opened for reading.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "./classes.h"
+#include "../shared/io/io.h"
+#include "../shared/shared.h"
+
+IoModel::IoModel(){/*{{{*/
+	this->fid=NULL;
+	this->data=NULL;
+	this->independents=NULL;
+	this->independent_objects=NULL;
+	this->constants=NULL;
+
+	this->my_elements=NULL;
+	this->my_vertices=NULL;
+
+	this->domaintype=-1;
+	this->domaindim=-1;
+	this->meshelementtype=-1;
+	this->numberofvertices=-1;
+	this->numberofelements=-1;
+	this->numberoffaces=-1;
+	this->numberofedges=-1;
+	this->facescols=-1;
+	this->elements=NULL;
+	this->faces=NULL;
+	this->edges=NULL;
+	this->elementtofaceconnectivity      =NULL;
+	this->elementtoedgeconnectivity      =NULL;
+	this->singlenodetoelementconnectivity=NULL;
+	this->numbernodetoelementconnectivity=NULL;
+
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+IoModel::IoModel(FILE* iomodel_handle){/*{{{*/
+
+	/*First, keep track of the file handle: */
+	this->fid=iomodel_handle;
+
+	/*Check that Enums are Synchronized*/
+	this->CheckEnumSync();
+
+	/*Initialize data: */
+	this->data=xNew<IssmDouble*>(MaximumNumberOfDefinitionsEnum);
+	for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++) this->data[i]=NULL;
+
+	/*If we are running in AD mode, we need to start the trace and declare our independent variables now, 
+	 *and prevent them from being erased during successive calls to iomodel->FetchConstants, iomodel->FetchData and 
+	 iomodel->DeleteData:*/
+	this->StartTrace();
+	this->DeclareIndependents();
+
+	/*Initialize and read constants:*/
+	this->constants=new Parameters();
+	this->FetchConstants(); /*this routine goes through the input file, and fetches bools, ints, IssmDoubles and strings only, nothing memory intensive*/
+
+	/*Initialize permanent data: */
+	this->my_elements = NULL;
+	this->my_vertices = NULL;
+
+	FetchData(&this->domaintype,DomainTypeEnum);
+	FetchData(&this->domaindim,DomainDimensionEnum);
+	FetchData(&this->meshelementtype,MeshElementtypeEnum);
+	FetchData(&this->numberofvertices,MeshNumberofverticesEnum);
+	FetchData(&this->numberofelements,MeshNumberofelementsEnum);
+	FetchData(&this->elements,NULL,NULL,MeshElementsEnum);
+	this->facescols                       = -1;
+	this->faces                           = NULL;
+	this->edges                           = NULL;
+	this->elementtofaceconnectivity       = NULL;
+	this->elementtoedgeconnectivity       = NULL;
+	this->singlenodetoelementconnectivity = NULL;
+	this->numbernodetoelementconnectivity = NULL;
+
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+IoModel::~IoModel(){/*{{{*/
+
+	/*Delete independents*/
+	if(this->independents){
+		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
+			if(this->independents[i]){
+				IssmDouble* array=this->data[i];
+				xDelete<IssmDouble>(array);
+			}
+		}
+	}
+
+	/*checks in debugging mode*/
+	#ifdef _ISSM_DEBUG_
+	if(this->data){
+		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
+			if(this->data[i]){
+				_printf0_("WARNING: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)\n");
+			}
+		}
+	}
+	#endif
+
+	if(this->constants) delete this->constants;
+
+	xDelete<IssmDouble*>(this->data);
+	xDelete<bool>(this->independents);
+	if(this->independent_objects)delete this->independent_objects;
+
+	xDelete<bool>(this->my_elements);
+	xDelete<int>(this->my_vertices);
+
+	xDelete<int>(this->elements);
+	xDelete<int>(this->faces);
+	xDelete<int>(this->edges);
+	xDelete<int>(this->elementtofaceconnectivity);
+	xDelete<int>(this->elementtoedgeconnectivity);
+	xDelete<int>(this->singlenodetoelementconnectivity);
+	xDelete<int>(this->numbernodetoelementconnectivity);
+}
+/*}}}*/
+
+void  IoModel::CheckEnumSync(void){/*{{{*/
+
+	int record_enum,record_length;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Check that some fields have been allocated*/
+	_assert_(this->fid || my_rank);
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){ //cpu 0
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(this->fid,0,SEEK_SET);
+
+		/*Get first Enum*/
+		if(fread(&record_enum,sizeof(int),1,this->fid)==0){
+			_error_("Marshalled file is empty");
+		}
+		else{
+			if(record_enum!=MaximumNumberOfDefinitionsEnum){
+				_printf0_("\n");
+				_printf0_("=========================================================================\n");
+				_printf0_(" Enums in marshalled file are not compatible with compiled code          \n");
+				_printf0_("                                                                         \n");
+				_printf0_("   * If you are running ISSM on your local machine:                      \n");
+				_printf0_("     make sure that all the code is compiled and installed (make install)\n");
+				_printf0_("   * If you are running ISSM on a remote cluster:                        \n");
+				_printf0_("     make sure that you are using the same version of ISSM on your local \n");
+				_printf0_("     machine and remote cluster (you might need to run svn update)       \n");
+				_printf0_("   * If you are a developer and just added a new Enum:                   \n");
+				_printf0_("     you might need to run ./Synchronize.sh in src/c/shared/Enum         \n");
+				_printf0_("     and recompile                                                       \n");
+				_printf0_("=========================================================================\n");
+				_printf0_("\n");
+				_error_("Enums not consistent (See error message above)");
+			}
+		}
+
+		/*Get last enum*/
+		bool found     = false;
+		int  last_enum = 0;
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+		for(;;){
+			/*Have we reached the end of file ?*/
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				break;
+			}
+
+			/*Have we found the last Enum ?*/
+			if(record_enum==MaximumNumberOfDefinitionsEnum+1){
+				found = true;
+				break;
+			}
+
+			/*Check that record_enum is an enum*/
+			if(record_enum>=0 && record_enum<=MaximumNumberOfDefinitionsEnum){
+				if(record_enum>0) last_enum = record_enum;
+			}
+
+			/*Go to next Enum*/
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			fseek(fid,record_length,SEEK_CUR);
+		}
+		if(!found){
+			_printf0_("\n");
+			_printf0_("=========================================================================\n");
+			_printf0_(" Marshalled file is corrupted                                            \n");
+			_printf0_("                                                                         \n");
+			_printf0_("   * If you are running an old model, send it to the ISSM developers     \n");
+			_printf0_("     so that a check is added before marshall                            \n");
+			_printf0_("   * Last Enum found: " << EnumToStringx(last_enum)<<"Enum ("<<last_enum<<")\n");
+			_printf0_("     the corresponding model field has probably been marshalled          \n");
+			_printf0_("     incorrectly                                                         \n");
+			_printf0_("                                                                         \n");
+			_printf0_("=========================================================================\n");
+			_printf0_("\n");
+			_error_("Binary file corrupted (See error message above)");
+		}
+	}
+}
+/*}}}*/
+void IoModel::Constant(bool* poutput,int constant_enum){/*{{{*/
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+void IoModel::Constant(int* poutput,int constant_enum){/*{{{*/
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+void IoModel::Constant(IssmDouble* poutput,int constant_enum){/*{{{*/
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+void IoModel::Constant(char** poutput,int constant_enum){/*{{{*/
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+Param* IoModel::CopyConstantObject(int constant_enum){/*{{{*/
+
+	_assert_(this->constants);
+
+	/*Find constant*/
+	Param* param=dynamic_cast<Param*>(this->constants->FindParamObject(constant_enum));
+	if(!param) _error_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
+
+	return dynamic_cast<Param*>(param->copy());
+}
+/*}}}*/
+IssmDouble* IoModel::Data(int data_enum){/*{{{*/
+
+	_assert_(data_enum<MaximumNumberOfDefinitionsEnum);
+	_assert_(data_enum>=0);
+
+	return this->data[data_enum];
+}
+/*}}}*/
+void IoModel::StartTrace(void){/*{{{*/
+
+	bool autodiff = false;
+	bool keep=false;
+	IssmDouble gcTriggerRatio;
+	IssmDouble gcTriggerMaxSize;
+	IssmDouble obufsize;
+	IssmDouble lbufsize;
+	IssmDouble cbufsize;
+	IssmDouble tbufsize;
+
+	int my_rank=IssmComm::GetRank();
+
+	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
+	if(autodiff){
+
+		#ifdef _HAVE_ADOLC_
+		/*Retrieve parameters: */
+		this->FetchData(&keep,AutodiffKeepEnum);
+		int keepTaylors=keep?1:0;
+		this->FetchData(&gcTriggerRatio,AutodiffGcTriggerRatioEnum);
+		this->FetchData(&gcTriggerMaxSize,AutodiffGcTriggerMaxSizeEnum);
+		this->FetchData(&obufsize,AutodiffObufsizeEnum);
+		this->FetchData(&lbufsize,AutodiffLbufsizeEnum);
+		this->FetchData(&cbufsize,AutodiffCbufsizeEnum);
+		this->FetchData(&tbufsize,AutodiffTbufsizeEnum);
+
+		/*Set garbage collection parameters: */
+		setStoreManagerControl(reCast<IssmPDouble>(gcTriggerRatio),reCast<size_t>(gcTriggerMaxSize));
+
+		/*Start trace: */
+		int skipFileDeletion=1;
+		trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
+		#endif
+	}
+
+}
+/*}}}*/
+void IoModel::DeclareIndependents(void){/*{{{*/
+
+	int  i;
+	bool autodiff = false;
+	int  num_independent_objects;
+
+	int *names = NULL;
+	int *types = NULL;
+
+	int  dummy;
+
+	/*Initialize array detecting whether data[i] is an independent AD mode variable: */
+	this->independents=xNew<bool>(MaximumNumberOfDefinitionsEnum);
+	for(i=0;i<MaximumNumberOfDefinitionsEnum;i++) this->independents[i]=false;
+
+	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
+	if(autodiff){
+
+		#ifdef _HAVE_ADOLC_
+		/*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]);
+
+				/*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;
+
+}
+/*}}}*/
+void  IoModel::DeleteData(int num,...){/*{{{*/
+
+	va_list ap;
+	int     dataenum;
+
+	/*Go through the entire list of enums and delete the corresponding data from the iomodel-data dataset: */
+	va_start(ap,num);
+	for(int i=0;i<num;i++){
+		dataenum=va_arg(ap,int);
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum);
+
+		/*do not erase independent variables for the AD mode computations!: */
+		if (!this->independents[dataenum]) xDelete<IssmDouble>(this->data[dataenum]);
+	}
+	va_end(ap);
+} /*}}}*/
+void  IoModel::DeleteData(IssmDouble* vector, int dataenum){/*{{{*/
+
+	/*do not erase independent variables for the AD mode computations!: */
+	if(vector)if (!this->independents[dataenum]) xDelete<IssmDouble>(vector);
+
+} /*}}}*/
+void  IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum){/*{{{*/
+
+	int i;
+	char** stringarray=*pstringarray;
+	
+	if (numstrings){
+		for (i=0;i<numstrings;i++){
+			char* string=stringarray[i]; 
+			xDelete<char>(string);
+		}
+		xDelete<char*>(stringarray);
+	}
+	*pstringarray=NULL;
+} /*}}}*/
+void  IoModel::FetchConstants(void){/*{{{*/
+
+	int my_rank;
+
+	/*record descriptions; */
+	int record_enum;
+	int record_length;
+	int record_code; //1 to 7 number
+
+	/*records: */
+	int  booleanint=0;
+	int  integer=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*/
+	_assert_(this->fid || my_rank);
+	_assert_(this->constants);
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){ //cpu 0{{{
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(this->fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifiers (bool,int,IssmDouble or string): */
+		for(;;){
+			if(fread(&record_enum,sizeof(int),1,this->fid)==0){
+
+				/*Ok, we have reached the end of the file. break: */
+				record_code=0; //0 means bailout
+				ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*tell others cpus we are bailing: */
+				break;
+			}
+			else{
+
+				/* Read the record length and the data type code: */
+				if(fread(&record_length,sizeof(int),1,this->fid)!=1) _error_("Cound not read record_length");
+				if(fread(&record_code  ,sizeof(int),1,this->fid)!=1) _error_("Cound not read record_code");
+
+				/*Tell other cpus what we are doing: */
+				ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*tell other cpus what we are going to do: */
+
+				/*Tell other cpus the name of the data, then branch according to the data type: */
+				ISSM_MPI_Bcast(&record_enum,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
+				ISSM_MPI_Bcast(&record_length,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
+
+				switch(record_code){
+					case 1: 
+						/*Read the boolean and broadcast it to other cpus:*/
+						if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error_("could not read boolean ");
+						ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+						/*create BoolParam: */
+						this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to boolean
+
+						break;
+					case 2:
+						/*Read the integer and broadcast it to other cpus:*/
+						if(fread(&integer,sizeof(int),1,this->fid)!=1) _error_("could not read integer ");
+						ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+						/*create IntParam: */
+						this->constants->AddObject(new IntParam(record_enum,integer));
+
+						break;
+					case 3:
+						/*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 ");
+							ISSM_MPI_Bcast(&pscalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+							scalar=pscalar;
+						}
+
+						/*create DoubleParam: */
+						this->constants->AddObject(new DoubleParam(record_enum,scalar));
+
+						break;
+					case 4: 
+						/*We have to read a string from disk. First read the dimensions of the string, then the string: */
+						if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error_("could not read length of string ");
+						ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+						if(string_size){
+							string=xNew<char>(string_size+1);
+							string[string_size]='\0';
+
+							/*Read string, then broadcast: */
+							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error_(" could not read string ");
+							ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+						}
+						else{
+							string=xNew<char>(1);
+							string[0]='\0';
+						}
+
+						/*Add string to parameters: */
+						this->constants->AddObject(new StringParam(record_enum,string));
+
+						/*Free string*/
+						xDelete<char>(string);
+
+						break;
+					case 5: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+					case 6: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+					case 7: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					case 8: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					case 9: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					default: 
+						_error_("unknown record type:" << record_code); 
+						break;;
+				}
+			}
+		}
+	} //}}}
+	else{ //cpu ~0 {{{
+		for(;;){ //wait on cpu 0
+			ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*get from cpu 0 what we are going to do: */
+			if(record_code==0){
+				break; //we are done, break from the loop
+			}
+			else{
+				ISSM_MPI_Bcast(&record_enum,1,ISSM_MPI_INT,0,IssmComm::GetComm());   //get from cpu 0 name of the data
+				ISSM_MPI_Bcast(&record_length,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
+				switch(record_code){
+				case 1: 
+					/*boolean. get it from cpu 0 */
+					ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+					/*create BoolParam: */
+					this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to a boolean
+					break;
+
+				case 2:
+					/*integer. get it from cpu 0 */
+					ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+					/*create IntParam: */
+					this->constants->AddObject(new IntParam(record_enum,integer));
+
+					break;
+				case 3:
+					/*scalar. get it from cpu 0 */
+					ISSM_MPI_Bcast(&pscalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+					scalar=pscalar;
+					/*create DoubleParam: */
+					this->constants->AddObject(new DoubleParam(record_enum,scalar));
+
+					break;
+				case 4: 
+					ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+					if(string_size){
+						string=xNew<char>((string_size+1));
+						string[string_size]='\0';
+
+						/*Read string from cpu 0: */
+						ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+					}
+					else{
+						string=xNew<char>(1);
+						string[0]='\0';
+					}
+					/*Add string to parameters: */
+					this->constants->AddObject(new StringParam(record_enum,string));
+
+					/*Free string*/
+					xDelete<char>(string);
+
+					break;
+				case 5: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 6: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 7: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 8: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 9: break; //do nothing. not interested in this type of data, which is memory intensive.
+
+				default: 
+					_error_("unknown record type:" << record_code); 
+					break;;
+				}
+
+			}
+		}
+	} //}}}
+}
+/*}}}*/
+void  IoModel::FetchData(bool* pboolean,int data_enum){/*{{{*/
+
+	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){  
+		if(fread(&booleanint,sizeof(int),1,fid)!=1) _error_("could not read boolean ");
+	}
+	ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*cast to bool: */
+	/*Assign output pointers: */
+	*pboolean=(bool)booleanint;
+
+}
+/*}}}*/
+void  IoModel::FetchData(int* pinteger,int data_enum){/*{{{*/
+
+	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){  
+		if(fread(&integer,sizeof(int),1,fid)!=1) _error_("could not read integer ");
+	}
+
+	ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers: */
+	*pinteger=integer;
+}
+/*}}}*/
+void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){/*{{{*/
+
+	int my_rank;
+
+	/*output: */
+	IssmPDouble   scalar;
+	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){
+		if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
+	}
+	ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers: */
+	*pscalar=scalar;
+
+}
+/*}}}*/
+void  IoModel::FetchData(char** pstring,int data_enum){/*{{{*/
+
+	int my_rank;
+
+	/*output: */
+	char* string=NULL;
+	int   string_size;
+	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){  
+		if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
+	}
+
+	ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Now allocate string: */
+	if(string_size){
+		string=xNew<char>((string_size+1));
+		string[string_size]='\0';
+
+		/*Read string on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
+		}
+		ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+	}
+	else{
+		string=xNew<char>(1);
+		string[0]='\0';
+	}
+
+	/*Assign output pointers: */
+	*pstring=string;
+}
+/*}}}*/
+void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){/*{{{*/
+
+	int my_rank;
+	int i,j;
+
+	/*output: */
+	int M,N;
+	IssmPDouble* matrix=NULL;
+	int*    integer_matrix=NULL;
+	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!=5 && code!=6 && code!=7)_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum)<<" (Code is "<<code<<")");
+
+	/*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 ");
+	}
+
+	ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+	}
+	ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=xNew<IssmPDouble>(M*N);
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+		}
+
+		ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+	}
+
+	/*Now cast to integer: */
+	if(M*N){
+		integer_matrix=xNew<int>(M*N);
+		for (i=0;i<M;i++){
+			for (j=0;j<N;j++){
+				integer_matrix[i*N+j]=(int)matrix[i*N+j];
+			}
+		}
+	}
+	else{
+		integer_matrix=NULL;
+	}
+	/*Free ressources:*/
+	xDelete<IssmPDouble>(matrix);
+
+	/*Assign output pointers: */
+	*pmatrix=integer_matrix;
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+
+}
+/*}}}*/
+void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){/*{{{*/
+
+	int my_rank;
+
+	/*output: */
+	int M,N;
+	IssmPDouble* matrix=NULL;
+	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!=5 && code!=6 && code!=7)_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum)<<" (Code is "<<code<<")");
+
+	/*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 ");
+	}
+	ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+	}
+	ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=xNew<IssmPDouble>(M*N);
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+		}
+		ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+		_assert_(this->independents);
+		if(this->independents[data_enum]){
+			/*this data has already been checked out! So cancel all that we've done here, and return 
+			 * the data[data_enum] directly: */
+			*pmatrix=this->data[data_enum];
+		}
+		else{
+			*pmatrix=xNew<IssmDouble>(M*N);
+			for(int i=0;i<M*N;++i) (*pmatrix)[i]=matrix[i];
+		}
+		xDelete<IssmPDouble>(matrix);
+	}
+	else
+	  *pmatrix=NULL;
+	/*Assign output pointers: */
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+}
+/*}}}*/
+void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){/*{{{*/
+
+	int my_rank;
+
+	int i;
+
+	/*output: */
+	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){  
+		if(fread(&numstrings,sizeof(int),1,fid)!=1) _error_("could not read length of string array");
+	}
+	ISSM_MPI_Bcast(&numstrings,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Now allocate string array: */
+	if(numstrings){
+		strings=xNew<char*>(numstrings);
+		for(i=0;i<numstrings;i++)strings[i]=NULL;
+
+		/*Go through strings, and read: */
+		for(i=0;i<numstrings;i++){
+
+			if(my_rank==0){  
+				if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
+			}
+			ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+			if(string_size){
+				string=xNew<char>((string_size+1));
+				string[string_size]='\0';
+
+				/*Read string on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
+				}
+				ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+			}
+			else{
+				string=xNew<char>(1);
+				string[0]='\0';
+			}
+
+			strings[i]=string;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pstrings=strings;
+	*pnumstrings=numstrings;
+}
+/*}}}*/
+void  IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
+
+	int i;
+
+	int my_rank;
+
+	/*output: */
+	IssmDouble** matrices=NULL;
+	int*     mdims=NULL;
+	int*     ndims=NULL;
+	int      numrecords=0;
+
+	/*intermediary: */
+	int     M, N;
+	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){  
+		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error_("could not read number of records in matrix array ");
+	}
+	ISSM_MPI_Bcast(&numrecords,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	if(numrecords){
+
+		/*Allocate matrices :*/
+		matrices=xNew<IssmDouble*>(numrecords);
+		mdims=xNew<int>(numrecords);
+		ndims=xNew<int>(numrecords);
+
+		for(i=0;i<numrecords;i++){
+			matrices[i]=NULL;
+			mdims[i]=0;
+			ndims[i]=0;
+		}
+
+		/*Loop through records and fetch matrix: */
+		for(i=0;i<numrecords;i++){
+
+			if(my_rank==0){  
+				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows in " << i << "th matrix of matrix array");
+			}
+			ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns in " << i << "th matrix of matrix array");
+			}
+			ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			/*Now allocate matrix: */
+			if(M*N){
+				matrix=xNew<IssmPDouble>(M*N);
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+				}
+
+				ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+				matrices[i]=xNew<IssmDouble>(M*N);
+				for (int j=0;j<M*N;++j) {matrices[i][j]=matrix[j];}
+				xDelete<IssmPDouble>(matrix);
+			}
+			else
+			  matrices[i]=NULL;
+			/*Assign: */
+			mdims[i]=M;
+			ndims[i]=N;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	*pmdims=mdims;
+	*pndims=ndims;
+	*pnumrecords=numrecords;
+}
+/*}}}*/
+void  IoModel::FetchData(Option** poption,int index){/*{{{*/
+
+	/*output: */
+	int     code;
+	char   *name        = NULL;
+
+	/*First get option name*/
+	this->FetchData(&name,index);
+
+	/*Get option value*/
+	fid=this->SetFilePointerToData(&code,NULL,index+1);
+	switch(code){
+		case 3: {//IssmDouble
+					GenericOption<IssmDouble>* option;
+					IssmDouble value;
+					FetchData(&value,index+1);
+					option = new GenericOption<IssmDouble>();
+					option->value = value;
+					option->name  = name;
+					option->numel = 1;
+					option->ndims = 1;
+					option->size  = NULL;
+					/*Assign output pointers: */
+					*poption=option;
+					break;
+				}
+		case 4: {//char
+					GenericOption<char*>* option;
+					char* value = NULL;
+					FetchData(&value,index+1);
+					option = new GenericOption<char*>();
+					option->value = value;
+					option->name  = name;
+					option->numel = 1;
+					option->ndims = 1;
+					option->size  = NULL;
+					*poption=option;
+					break;
+				}
+		default:
+			  _error_("Option of format " << code << " not supported yet");
+	}
+
+}
+/*}}}*/
+void  IoModel::FetchData(int num,...){/*{{{*/
+
+	va_list     ap;
+	int         dataenum;
+	IssmDouble *matrix   = NULL;
+	int         M,N;
+	int         i;
+
+	/*Go through the entire list of enums and fetch the corresponding data. Add it to the iomodel->data dataset. Everything
+	 *we fetch is a IssmDouble* : */
+
+	va_start(ap,num);
+	for(i=0; i<num; i++){
+
+		dataenum=va_arg(ap, int);
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum); 
+		_assert_(dataenum>=0);
+
+		if (this->independents[dataenum]){
+			/*this data has already been checked out! Continue: */
+			continue;
+		}
+
+		/*Some checks in debugging mode*/
+		/*{{{*/
+		#ifdef _ISSM_DEBUG_
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum);
+		if(this->data[dataenum]){
+			_error_("Info: trying to fetch " << EnumToStringx(dataenum) << " but previous pointer has not been freed (DeleteData has not been called)");
+		}
+		#endif
+		/*}}}*/
+
+		/*Add to this->data: */
+		this->FetchData(&matrix,&M,&N,dataenum);
+		this->data[dataenum]=matrix;
+	}
+	va_end(ap);
+
+}
+/*}}}*/
+void  IoModel::FetchMultipleData(char*** pstrings,int* pnumstrings,int data_enum){/*{{{*/
+
+	int  num_instances;
+
+	/*output: */
+	int    numstrings = 0;
+	char **strings    = NULL;
+
+	/*intermediary: */
+	char   *string         = NULL;
+	int     string_size;
+	int    *codes          = NULL;
+	int    *code           = NULL;
+	fpos_t *file_positions = NULL;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+		strings=xNew<char*>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				/*check we are indeed finding a string, not something else: */
+				if(codes[i]!=4)_error_("expecting a string for enum " << EnumToStringx(data_enum));
+		
+				/*We have to read a string from disk. First read the dimensions of the string, then the string: */
+				fsetpos(fid,file_positions+i);
+				if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
+			}
+
+			ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			/*Now allocate string: */
+			if(string_size){
+				string=xNew<char>((string_size+1));
+				string[string_size]='\0';
+
+				/*Read string on node 0, then broadcast: */
+				if(my_rank==0){
+					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
+				}
+				ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+			}
+			else{
+				string=xNew<char>(1);
+				string[0]='\0';
+			}
+			strings[i]=string;
+		}
+	}
+	/*Free ressources:*/
+	xDelete<int>(codes);
+	xDelete<fpos_t>(file_positions);
+	
+	/*Assign output pointers: */
+	*pstrings=strings;
+	*pnumstrings=num_instances;
+}
+/*}}}*/
+void  IoModel::FetchMultipleData(int** pvector, int* pnum_instances,int data_enum){/*{{{*/
+
+	int     num_instances;
+	fpos_t* file_positions=NULL;
+
+	/*output: */
+	int* vector=NULL;
+
+	/*intermediary: */
+	int          integer;
+	int         *codes   = NULL;
+	int          code;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+	
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+
+		/*Allocate vector :*/
+		vector=xNew<int>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				code=codes[i];
+
+				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: */
+				fsetpos(fid,file_positions+i);
+				if(my_rank==0){  
+					if(fread(&integer,sizeof(int),1,fid)!=1) _error_("could not read integer ");
+				}
+			}
+			ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			/*Assign: */
+			vector[i]=integer;
+		}
+	}
+			
+	/*Free ressources:*/
+	xDelete<fpos_t>(file_positions);
+	xDelete<int>(codes);
+
+	/*Assign output pointers: */
+	*pvector=vector;
+	*pnum_instances=num_instances;
+}
+/*}}}*/
+void  IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
+
+	int     num_instances;
+	fpos_t* file_positions=NULL;
+
+	/*output: */
+	IssmDouble **matrices = NULL;
+	int         *mdims    = NULL;
+	int         *ndims    = NULL;
+
+	/*intermediary: */
+	int          M, N;
+	IssmPDouble *pmatrix = NULL;
+	IssmDouble  *matrix  = NULL;
+	int         *codes   = NULL;
+	int          code;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+	
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+
+		/*Allocate matrices :*/
+		matrices=xNew<IssmDouble*>(num_instances);
+		mdims=xNew<int>(num_instances);
+		ndims=xNew<int>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				code=codes[i];
+
+				if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+
+				/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+				/*numberofelements: */
+				fsetpos(fid,file_positions+i);
+				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+			}
+			ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+			}
+			ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+
+			/*Now allocate matrix: */
+			if(M*N){
+				pmatrix=xNew<IssmPDouble>(M*N);
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(pmatrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+				}
+				ISSM_MPI_Bcast(pmatrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+				_assert_(this->independents);
+				if(this->independents[data_enum]){
+					/*this data has already been checked out! So cancel all that we've done here, and return 
+					 * the data[data_enum] directly: */
+					matrix=this->data[data_enum];
+				}
+				else{
+					matrix=xNew<IssmDouble>(M*N);
+					for (int i=0;i<M*N;++i) matrix[i]=pmatrix[i];
+				}
+				xDelete<IssmPDouble>(pmatrix);
+			}
+			else
+				matrix=NULL;
+			
+			
+			/*Assign: */
+			mdims[i]=M;
+			matrices[i]=matrix;
+			ndims[i]=N;
+		}
+	}
+			
+	/*Free ressources:*/
+	xDelete<fpos_t>(file_positions);
+	xDelete<int>(codes);
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	if(pmdims){
+		*pmdims=mdims;
+	}
+	else{
+		xDelete<int>(mdims);
+	}
+	if(pndims){
+		*pndims=ndims;
+	}
+	else{
+		xDelete<int>(ndims);
+	}
+	*pnumrecords=num_instances;
+}
+/*}}}*/
+void  IoModel::FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
+
+	int     num_instances;
+	fpos_t* file_positions=NULL;
+
+	/*output: */
+	int        **matrices = NULL;
+	int         *mdims    = NULL;
+	int         *ndims    = NULL;
+
+	/*intermediary: */
+	int          M, N;
+	IssmPDouble *pmatrix = NULL;
+	IssmDouble  *matrix  = NULL;
+	int         *integer_matrix=NULL;
+	int         *codes   = NULL;
+	int          code;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+	
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+
+		/*Allocate matrices :*/
+		matrices=xNew<int*>(num_instances);
+		mdims=xNew<int>(num_instances);
+		ndims=xNew<int>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				code=codes[i];
+
+				if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+
+				/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+				/*numberofelements: */
+				fsetpos(fid,file_positions+i);
+				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+			}
+			ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+			}
+			ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+
+			/*Now allocate matrix: */
+			if(M*N){
+				pmatrix=xNew<IssmPDouble>(M*N);
+				integer_matrix=xNew<int>(M*N);
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(pmatrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+				}
+				ISSM_MPI_Bcast(pmatrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+				_assert_(this->independents);
+				if(this->independents[data_enum]){
+					/*this data has already been checked out! So cancel all that we've done here, and return 
+					 * the data[data_enum] directly: */
+					matrix=this->data[data_enum];
+					for (int i=0;i<M*N;++i) integer_matrix[i]=reCast<int>(matrix[i]);
+				}
+				else{
+					for (int i=0;i<M*N;++i) integer_matrix[i]=pmatrix[i];
+				}
+				xDelete<IssmPDouble>(pmatrix);
+			}
+			else
+				integer_matrix=NULL;
+			
+			
+			/*Assign: */
+			mdims[i]=M;
+			matrices[i]=integer_matrix;
+			ndims[i]=N;
+		}
+	}
+			
+	/*Free ressources:*/
+	xDelete<fpos_t>(file_positions);
+	xDelete<int>(codes);
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	if(pmdims){
+		*pmdims=mdims;
+	}
+	else{
+		xDelete<int>(mdims);
+	}
+	if(pndims){
+		*pndims=ndims;
+	}
+	else{
+		xDelete<int>(ndims);
+	}
+	*pnumrecords=num_instances;
+}
+/*}}}*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){/*{{{*/
+
+	/*intermediary: */
+	int         code,vector_layout;
+	IssmDouble *doublearray = NULL;
+	int         M,N;
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	this->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	/*Defaulting only supported for double arrays*/
+	if(code!=7) _error_(EnumToStringx(vector_enum)<<" is not a double array");
+
+	this->FetchData(&doublearray,&M,&N,vector_enum);
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		if(!doublearray) element->AddInput(vector_enum,&default_value,P0Enum); 
+		else             element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+	}
+
+	/*Free ressources. Pay attention to not freeing an AD mode independent variable though!:*/
+	if(!this->independents[vector_enum]) xDelete<IssmDouble>(doublearray);
+}
+/*}}}*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum){/*{{{*/
+
+	/*intermediary: */
+	int     i;
+	int     code,vector_layout;
+
+	/*variables being fetched: */
+	bool        boolean;
+	int         integer;
+	IssmDouble  scalar;
+	char       *string           = NULL;
+	IssmDouble *doublearray = NULL;
+	int         M,N;
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	this->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	switch(code){
+		case 1: //boolean constant
+			this->FetchData(&boolean,vector_enum);
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(boolean,vector_enum);
+			}
+			break;
+		case 2: //integer constant
+			this->FetchData(&integer,vector_enum);
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(integer,vector_enum);
+			}
+			break;
+		case 3: //IssmDouble constant
+			this->FetchData(&scalar,vector_enum);
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputUpdateFromConstant(scalar,vector_enum);
+			}
+			break; 
+		case 5: //boolean vector
+			this->FetchData(&doublearray,&M,&N,vector_enum); //we still have a doublearray, because it might include times in transient mode
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		case 6: //int vector
+			this->FetchData(&doublearray,&M,&N,vector_enum); //we still have a doublearray, because it might include times in transient mode
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		case 7: //IssmDouble vector
+			this->FetchData(&doublearray,&M,&N,vector_enum);
+			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
+			for(i=0;i<elements->Size();i++){
+				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+			}
+			break;
+		default:
+			_error_("data code " << code << " not supported yet!");
+			break;
+	}
+	/*Free ressources. Pay attention to not freeing an AD mode independent variable though!:*/
+	if (!this->independents[vector_enum]) xDelete<IssmDouble>(doublearray);
+	xDelete<char>(string);
+}
+/*}}}*/
+void IoModel::LastIndex(int *pindex){/*{{{*/
+
+	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: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&index,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*read the record length, and use it to skip this record: */
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			fseek(fid,record_length,SEEK_CUR);
+			lastindex=index;
+		}
+	}
+	/*Broadcast code and vector type: */
+	ISSM_MPI_Bcast(&lastindex,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pindex=lastindex;
+}
+/*}}}*/
+/*FUNCTION IoModel::SetFilePointerToData{{{*/
+FILE* IoModel::SetFilePointerToData(int* pcode,int* pvector_type, int data_enum){
+
+	int my_rank;
+
+	int found         = 0;
+	int record_enum;
+	int record_length;
+	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: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				found=0;
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum){
+				/*Ok, we have found the correct string. Pass the record length, and read data type code: */
+				fseek(fid,sizeof(int),SEEK_CUR);
+				if(fread(&record_code,sizeof(int),1,fid)!=1) _error_("Could not read record_code");
+
+				/*if record_code points to a vector, get its type (nodal or elementary): */
+				if(5<=record_code && record_code<=7){
+					if(fread(&vector_type,sizeof(int),1,fid)!=1) _error_("Could not read vector_type");
+				}
+				found=1;
+				break;
+			}
+			else{
+				/*This is not the correct string, read the record length, and use it to skip this record: */
+				if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+				/*skip: */
+				fseek(fid,record_length,SEEK_CUR);
+			}
+		}
+	}
+	ISSM_MPI_Bcast(&found,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	if(!found)_error_("could not find data with name " << EnumToStringx(data_enum) << " in binary file");
+
+	/*Broadcast code and vector type: */
+	ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(&vector_type,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pcode=record_code;
+	if(pvector_type)*pvector_type=vector_type;
+
+	return fid;
+}
+/*}}}*/
+fpos_t* IoModel::SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum){/*{{{*/
+
+	int     found          = 0;
+	int     record_enum;
+	int     record_length;
+	int     record_code;           //1 to 7 number
+	int     vector_type;           //1 to 7 number
+	int    *vector_types   = NULL;
+	int    *codes          = NULL;
+	int     num_instances  = 0;
+	int     counter;
+	fpos_t *file_positions = NULL;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Go find in the binary file, the data we want to fetch and count the number of 
+	 * instances it appears: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum) num_instances++;
+
+			/*Read the record length, and use it to skip the record: */
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			fseek(fid,record_length,SEEK_CUR);
+		}
+
+		/*Ok, initialize the number of file handles we are going to return: */
+		if(num_instances){
+			file_positions = xNew<fpos_t>(num_instances);
+			codes          = xNew<int>(num_instances);
+			vector_types   = xNew<int>(num_instances);
+		}
+	
+		/*Reset FILE* position to the beginning of the file, and start again, this time saving the data information 
+		 * as we find it: */
+		counter=0;
+		fseek(fid,0,SEEK_SET);
+
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum){
+				/*Ok, we have found the correct string. Pass the record length, and read data type code: */
+				fseek(fid,sizeof(int),SEEK_CUR);
+				if(fread(&record_code,sizeof(int),1,fid)!=1) _error_("Could not read record_code");
+
+				/*if record_code points to a vector, get its type (nodal or elementary): */
+				if(5<=record_code && record_code<=7){
+					if(fread(&vector_type,sizeof(int),1,fid)!=1) _error_("Could not read vector_type");
+				}
+				codes[counter]        = record_code;
+				vector_types[counter] = vector_type;
+				fgetpos(fid,file_positions+counter);
+				
+				/*backup and skip over the record, as we have more work to do: */
+				if(5<=record_code && record_code<=7) fseek(fid,-sizeof(int),SEEK_CUR);
+				fseek(fid,-sizeof(int),SEEK_CUR);
+				fseek(fid,-sizeof(int),SEEK_CUR);
+				
+				/*increment counter: */
+				counter++;
+			}
+
+			/*Read the record length, and use it to skip this record, as it has already been processed: */
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
+			/*skip: */
+			fseek(fid,record_length,SEEK_CUR);
+		}
+	}
+
+	/*Broadcast data: */
+	ISSM_MPI_Bcast(&num_instances,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pcodes         = codes;
+	*pnum_instances = num_instances;
+	if(pvector_types){
+		*pvector_types=vector_types;
+	}
+	else{
+		xDelete<int>(vector_types);
+	}
+	return file_positions;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/IoModel.h	(revision 18231)
@@ -0,0 +1,99 @@
+/* \file IoModel.h
+ * \brief  Header file defining the IoModel structure that will help in processing the input data coming 
+ * into ISSM, from Matlab, or through a binary file opened for reading.
+ * \sa IoModel.cpp
+ */
+
+#ifndef _IOMODEL_H
+#define _IOMODEL_H
+
+#include "../shared/Enum/Enum.h"
+
+class Parameters;
+class Elements;
+class Param;
+class Option;
+
+class IoModel {
+
+	private: 
+		Parameters *constants;   //this dataset holds all IssmDouble, int, bool and char from input
+
+	public:
+		IssmDouble **data;   //this dataset holds temporary data, memory intensive.
+
+		/*pointer to input file*/
+		FILE *fid;
+
+		/*Partitioning*/
+		bool *my_elements;
+		int  *my_vertices;
+
+		/*Mesh properties and connectivity tables*/
+		int  domaintype;
+		int  domaindim;
+		int  meshelementtype;
+		int  numberofvertices;
+		int  numberofelements;
+		int  numberoffaces;
+		int  numberofedges;
+		int  facescols;
+		int *elements;
+		int *faces;
+		int *edges;
+		int *elementtoedgeconnectivity;
+		int *elementtofaceconnectivity;
+		int *singlenodetoelementconnectivity;
+		int *numbernodetoelementconnectivity;
+
+		/*Data to synchronize through low level object drivers: */
+		int nodecounter;         //keep track of how many nodes are being created in each analysis
+		int loadcounter;         //keep track of how many loads are being created in each analysis
+		int constraintcounter;   //keep track of how many constraints are being created in each analysis
+
+		/*for AD mode: to keep track of our independent variables we fetch:*/
+		bool    *independents;
+		DataSet *independent_objects;
+
+		/*Methods*/
+		~IoModel();
+		IoModel();
+		IoModel(FILE* iomodel_handle);
+
+		/*Input/Output*/
+		void        CheckEnumSync(void);
+		void        Constant(bool *poutput,int constant_enum);
+		void        Constant(int *poutput,int constant_enum);
+		void        Constant(IssmDouble *poutput,int constant_enum);
+		void        Constant(char **poutput,int constant_enum);
+		Param      *CopyConstantObject(int constant_enum);
+		IssmDouble *Data(int dataenum);
+		void        DeleteData(int num,...);
+		void        DeleteData(IssmDouble* vector, int dataenum);
+		void        DeleteData(char*** pstringarray, int numstrings, int dataenum);
+		void        FetchConstants(void);
+		void        FetchData(bool* pboolean,int data_enum);
+		void        FetchData(int* pinteger,int data_enum);
+		void        FetchData(IssmDouble* pscalar,int data_enum);
+		void        FetchData(char** pstring,int data_enum);
+		void        FetchData(int** pmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(IssmDouble**  pscalarmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(char***   pstringarray,int* pnumstrings,int data_enum);
+		void        FetchData(IssmDouble*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		void        FetchMultipleData(char***   pstringarray,int* pnumstrings,int data_enum);
+		void        FetchMultipleData(IssmDouble*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		void        FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		void        FetchMultipleData(int** pvector, int* pnum_instances,int data_enum);
+		void        FetchData(Option **poption,int data_enum);
+		void        FetchData(int num,...);
+		void        FetchDataToInput(Elements* elements,int vector_enum);
+		void        FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value);
+		void        LastIndex(int *pindex);
+		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
+		fpos_t*     SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum);
+		void        DeclareIndependents(void);
+		void        StartTrace(void);
+		void        FetchIndependent(int dependent_enum);
+};
+
+#endif  /* _IOMODEL_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.cpp	(revision 18231)
@@ -0,0 +1,220 @@
+/*!\file Friction.c
+ * \brief: implementation of the Friction object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/	
+
+/*Constructors/destructors*/
+Friction::Friction(){/*{{{*/
+	this->element=NULL;
+	this->dim=0;
+	this->law=0;
+
+}
+/*}}}*/
+Friction::Friction(Element* element_in,int dim_in){/*{{{*/
+
+	this->element=element_in;
+	this->dim=dim_in;
+	element_in->FindParam(&this->law,FrictionLawEnum);
+}
+/*}}}*/
+Friction::~Friction(){/*{{{*/
+}
+/*}}}*/
+
+/*methods: */
+void Friction::Echo(void){/*{{{*/
+	_printf_("Friction:\n");
+	_printf_("   dim: " << this->dim<< "\n");
+}
+/*}}}*/
+void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	switch(this->law){
+		case 1:
+			GetAlpha2Viscous(palpha2,gauss);
+			break;
+		case 2:
+			GetAlpha2Weertman(palpha2,gauss);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+}/*}}}*/
+void Friction::GetAlpha2Viscous(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	element->GetInputValue(&drag_p,FrictionPEnum);
+	element->GetInputValue(&drag_q,FrictionQEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&bed, gauss,BaseEnum);
+	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+	if(Neff<0)Neff=0;
+
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha2=0.;
+	else alpha2=drag_coefficient*drag_coefficient*pow(Neff,r)*pow(vmag,(s-1.));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2Weertman(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient alpha2= C^-1/m |v|^(1/m-1) */
+
+	/*diverse: */
+	IssmDouble  C,m;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	element->GetInputValue(&C,gauss,FrictionCEnum);
+	element->GetInputValue(&m,FrictionMEnum);
+
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (1./m-1.)<0.) alpha2=0.;
+	else alpha2=pow(C,-1./m)*pow(vmag,(1./m-1.));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	if(this->law!=1)_error_("not supported");
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_p,drag_q;
+	IssmDouble  Neff;
+	IssmDouble  drag_coefficient;
+	IssmDouble  bed,thickness;
+	IssmDouble  alpha_complement;
+
+	/*Recover parameters: */
+	element->GetInputValue(&drag_p,FrictionPEnum);
+	element->GetInputValue(&drag_q,FrictionQEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&bed, gauss,BaseEnum);
+	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+	if(Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha_complement=0.;
+	else alpha_complement=pow(Neff,r)*pow(vmag,(s-1));_assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Friction.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*!\file Friction.h
+ * \brief: header file for friction object
+ */
+
+#ifndef _FRICTION_H_
+#define _FRICTION_H_
+
+/*Headers:*/
+/*{{{*/
+class Inputs;
+class Matpar;
+class GaussPenta;
+class GaussTria;
+/*}}}*/
+
+class Friction{
+
+	public:
+		int analysis_type;
+
+		Element* element;
+		int      dim;
+		int      law;
+
+		/*methods: */
+		Friction();
+		Friction(Element* element_in,int dim_in);
+		~Friction();
+
+		void  Echo(void);
+		void  GetAlpha2(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlpha2Viscous(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlpha2Weertman(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlphaComplement(IssmDouble* alpha_complement,Gauss* gauss);
+};
+
+#endif  /* _FRICTION_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Load.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Load.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Load.h	(revision 18231)
@@ -0,0 +1,42 @@
+/*!\file:  Load.h
+ * \brief abstract class for Load object
+ * This class is a place holder for the Icefront  and the Penpair loads.
+ * It is derived from Load, so DataSets can contain them.
+ */ 
+
+#ifndef _LOAD_H_
+#define _LOAD_H_
+
+/*Headers:*/
+class Node;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+class Elements;
+class Loads;
+class Nodes;
+class Vertices;
+class Materials;
+class Parameters;
+#include "../../datastructures/datastructures.h"
+#include "../Update.h"
+
+class Load: public Object,public Update{
+
+	public: 
+		virtual       ~Load(){};
+		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual bool  IsPenalty(void)=0;
+		virtual int   GetNumberOfNodes(void)=0;
+		virtual void  GetNodesSidList(int* sidlist)=0;
+		virtual void  GetNodesLidList(int* lidlist)=0;
+		virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
+		virtual void  CreatePVector(Vector<IssmDouble>* pf)=0;
+		virtual void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax)=0;
+		virtual void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax)=0;
+		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum)=0;
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.cpp	(revision 18231)
@@ -0,0 +1,167 @@
+/*
+ * \file Loads.cpp
+ * \brief: Implementation of Loads class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+
+#include "./Loads.h"
+#include "./Load.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Loads::Loads(){/*{{{*/
+	enum_type=LoadsEnum;
+	return;
+}
+/*}}}*/
+Loads::~Loads(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Numerics:*/
+void Loads::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Load* load=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		load=dynamic_cast<Load*>(*object);
+		load->Configure(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+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: */
+	ISSM_MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	ispenalty=allispenalty;
+
+	if(ispenalty)
+	 return true;
+	else
+	 return false;
+}
+/*}}}*/
+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: */
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+
+	return max;
+}
+/*}}}*/
+int Loads::NumberOfLoads(void){/*{{{*/
+
+	int localloads;
+	int numberofloads;
+
+	/*Get number of local loads*/
+	localloads=this->Size();
+
+	/*figure out total number of loads combining all the cpus (no clones here)*/
+	ISSM_MPI_Reduce(&localloads,&numberofloads,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofloads,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	return numberofloads;
+}
+/*}}}*/
+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)*/
+	ISSM_MPI_Reduce(&localloads,&numberofloads,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofloads,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	return numberofloads;
+}
+/*}}}*/
+int Loads::Size(void){/*{{{*/
+
+	return this->DataSet::Size();
+}
+/*}}}*/
+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;
+}
+/*}}}*/
+void Loads::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Load* load=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		load=dynamic_cast<Load*>(*object);
+		load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Loads.h	(revision 18231)
@@ -0,0 +1,36 @@
+#ifndef _CONTAINER_LOADS_H_
+#define  _CONTAINER_LOADS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Nodes;
+
+/*!\brief Declaration of Loads class.
+ *
+ * Declaration of Loads class.  Loads are vector lists (Containers) of Load objects.
+ */ 
+class Loads: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Loads();
+		~Loads();
+
+		/*numerics*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		bool  IsPenalty(int analysis);
+		int   MaxNumNodes(int analysis);
+		int   NumberOfLoads(void);
+		int   NumberOfLoads(int analysis);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		int   Size(int analysis);
+		int   Size(void);
+
+};
+
+#endif //ifndef _LOADS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.cpp	(revision 18231)
@@ -0,0 +1,916 @@
+/*!\file Numericalflux.c
+ * \brief: implementation of the Numericalflux object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "shared/shared.h"
+#include "../classes.h"
+/*}}}*/	
+
+/*Load macros*/
+#define NUMVERTICES 2
+#define NUMNODES_INTERNAL 4
+#define NUMNODES_BOUNDARY 2
+
+/*Numericalflux constructors and destructor*/
+Numericalflux::Numericalflux(){/*{{{*/
+	this->parameters = NULL;
+	this->helement   = NULL;
+	this->element    = NULL;
+	this->hnodes     = NULL;
+	this->hvertices  = NULL;
+	this->nodes      = NULL;
+}
+/*}}}*/
+Numericalflux::Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel, int in_analysis_type){/*{{{*/
+
+	/* Intermediary */
+	int  j;
+	int  pos1,pos2,pos3,pos4;
+	int  num_nodes;
+
+	/*numericalflux constructor data: */
+	int   numericalflux_elem_ids[2];
+	int   numericalflux_vertex_ids[2];
+	int   numericalflux_node_ids[4];
+	int   numericalflux_type;
+
+	/*Get edge*/
+	int i1 = iomodel->faces[4*index+0];
+	int i2 = iomodel->faces[4*index+1];
+	int e1 = iomodel->faces[4*index+2];
+	int e2 = iomodel->faces[4*index+3];
+
+	/*First, see wether this is an internal or boundary edge (if e2=-1)*/
+	if(e2==-1){
+		/* Boundary edge, only one element */
+		num_nodes=2;
+		numericalflux_type=BoundaryEnum;
+		numericalflux_elem_ids[0]=e1;
+	}
+	else{
+		/* internal edge: connected to 2 elements */
+		 num_nodes=4;
+		numericalflux_type=InternalEnum;
+		numericalflux_elem_ids[0]=e1;
+		numericalflux_elem_ids[1]=e2;
+	}
+
+	/*1: Get vertices ids*/
+	numericalflux_vertex_ids[0]=i1;
+	numericalflux_vertex_ids[1]=i2;
+
+	/*2: Get node ids*/
+	if (numericalflux_type==InternalEnum){
+
+		/*Now, we must get the nodes of the 4 nodes located on the edge*/
+
+		/*2: Get the column where these ids are located in the index*/
+		pos1=pos2=pos3=pos4=UNDEF;
+		for(j=0;j<3;j++){
+			if(iomodel->elements[3*(e1-1)+j]==i1) pos1=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i2) pos2=j+1;
+			if(iomodel->elements[3*(e2-1)+j]==i1) pos3=j+1;
+			if(iomodel->elements[3*(e2-1)+j]==i2) pos4=j+1;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF && pos3!=UNDEF && pos4!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+		numericalflux_node_ids[2]=iomodel->nodecounter+3*(e2-1)+pos3;
+		numericalflux_node_ids[3]=iomodel->nodecounter+3*(e2-1)+pos4;
+	}
+	else{
+
+		/*2: Get the column where these ids are located in the index*/
+		pos1=pos2=UNDEF;
+		for(j=0;j<3;j++){
+			if(iomodel->elements[3*(e1-1)+j]==i1) pos1=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i2) pos2=j+1;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+	}
+
+	/*Ok, we have everything to build the object: */
+	this->id=numericalflux_id;
+	this->analysis_type=in_analysis_type;
+	this->flux_type = numericalflux_type;
+
+	/*Hooks: */
+	this->hnodes    =new Hook(numericalflux_node_ids,num_nodes);
+	this->hvertices =new Hook(&numericalflux_vertex_ids[0],2);
+	this->helement  =new Hook(numericalflux_elem_ids,1); // take only the first element for now
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->element=NULL;
+	this->nodes=NULL;
+}
+/*}}}*/
+Numericalflux::~Numericalflux(){/*{{{*/
+	this->parameters=NULL;
+	delete helement;
+	delete hnodes;
+	delete hvertices;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Numericalflux::Echo(void){/*{{{*/
+	_printf_("Numericalflux:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   flux_type: " << this->flux_type<< "\n");
+	hnodes->Echo();
+	hvertices->Echo();
+	helement->Echo();
+	_printf_("   parameters: " << parameters << "\n");
+}
+/*}}}*/
+void Numericalflux::DeepEcho(void){/*{{{*/
+
+	_printf_("Numericalflux:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   flux_type: " << this->flux_type<< "\n");
+	hnodes->DeepEcho();
+	hvertices->DeepEcho();
+	helement->DeepEcho();
+	_printf_("   parameters\n");
+	if(parameters)
+	 parameters->DeepEcho();
+	else
+	 _printf_("      NULL\n");
+}		
+/*}}}*/
+int    Numericalflux::Id(void){/*{{{*/
+	return id;
+}
+/*}}}*/
+int Numericalflux::ObjectEnum(void){/*{{{*/
+
+	return NumericalfluxEnum;
+
+}
+/*}}}*/
+Object* Numericalflux::copy() {/*{{{*/
+
+	Numericalflux* numericalflux=NULL;
+
+	numericalflux=new Numericalflux();
+
+	/*copy fields: */
+	numericalflux->id=this->id;
+	numericalflux->analysis_type=this->analysis_type;
+	numericalflux->flux_type=this->flux_type;
+
+	/*point parameters: */
+	numericalflux->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	numericalflux->hnodes    = (Hook*)this->hnodes->copy();
+	numericalflux->hvertices = (Hook*)this->hvertices->copy();
+	numericalflux->helement  = (Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	numericalflux->nodes    = (Node**)numericalflux->hnodes->deliverp();
+	numericalflux->vertices = (Vertex**)numericalflux->hvertices->deliverp();
+	numericalflux->element  = (Element*)numericalflux->helement->delivers();
+
+	return numericalflux;
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+void  Numericalflux::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure((DataSet*)nodesin);
+	hvertices->configure((DataSet*)verticesin);
+	helement->configure((DataSet*)elementsin);
+
+	/*Initialize hooked fields*/
+	this->nodes    = (Node**)hnodes->deliverp();
+	this->vertices = (Vertex**)hvertices->deliverp();
+	this->element  = (Element*)helement->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+}
+/*}}}*/
+void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Numericalflux::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+
+	/*recover some parameters*/
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		case MasstransportAnalysisEnum:
+			Ke=CreateKMatrixMasstransport();
+			break;
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+
+}
+/*}}}*/
+void  Numericalflux::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
+
+	/*recover some parameters*/
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case MasstransportAnalysisEnum:
+			pe=CreatePVectorMasstransport();
+			break;
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+void Numericalflux::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	switch(this->flux_type){
+		case InternalEnum:
+			for(int i=0;i<NUMNODES_INTERNAL;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		case BoundaryEnum:
+			for(int i=0;i<NUMNODES_BOUNDARY;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(this->flux_type) << " not supported yet");
+	}
+}
+/*}}}*/
+void Numericalflux::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	switch(this->flux_type){
+		case InternalEnum:
+			for(int i=0;i<NUMNODES_INTERNAL;i++) lidlist[i]=nodes[i]->Lid();
+			return;
+		case BoundaryEnum:
+			for(int i=0;i<NUMNODES_BOUNDARY;i++) lidlist[i]=nodes[i]->Lid();
+			return;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(this->flux_type) << " not supported yet");
+	}
+}
+/*}}}*/
+int Numericalflux::GetNumberOfNodes(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return NUMNODES_INTERNAL;
+		case BoundaryEnum:
+			return NUMNODES_BOUNDARY;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(this->flux_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+bool Numericalflux::IsPenalty(void){/*{{{*/
+	return false;
+}
+/*}}}*/
+void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
+
+	/*No penalty loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+bool Numericalflux::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,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]->Lid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
+
+/*Numericalflux management*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransport(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreateKMatrixMasstransportInternal();
+		case BoundaryEnum:
+			return CreateKMatrixMasstransportBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportInternal(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,dt,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     B[numdof];
+	IssmDouble     Bprime[numdof];
+	IssmDouble     Ke_g1[numdof][numdof];
+	IssmDouble     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*dt*UdotN/2;
+		DL2=gauss->weight*Jdet*dt*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*dt*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreateKMatrixBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     B[numdof];
+	IssmDouble     Bprime[numdof];
+	IssmDouble     Ke_g1[numdof][numdof];
+	IssmDouble     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*UdotN/2;
+		DL2=gauss->weight*Jdet*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreateKMatrixAdjointBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixAdjointBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){/*{{{*/
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
+	if (Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){/*{{{*/
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
+	if(Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransport(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreatePVectorMasstransportInternal();
+		case BoundaryEnum:
+			return CreatePVectorMasstransportBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){/*{{{*/
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input   =tria->inputs->GetInput(VxEnum);                     _assert_(vxaverage_input); 
+	Input* vyaverage_input   =tria->inputs->GetInput(VyEnum);                     _assert_(vyaverage_input);
+	Input* spcthickness_input=tria->inputs->GetInput(MasstransportSpcthicknessEnum); _assert_(spcthickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		spcthickness_input->GetInputValue(&thickness,gauss);
+		if(xIsNan<IssmDouble>(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorBalancethickness(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreatePVectorBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreatePVectorBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){/*{{{*/
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,ig,index1,index2;
+	IssmDouble DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input); 
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	Input* thickness_input=tria->inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){/*{{{*/
+
+	/*No PVector for the Adjoint*/
+	return NULL;
+}
+/*}}}*/
+void Numericalflux:: GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	vector[0]=xyz_list[1][0] - xyz_list[0][0];
+	vector[1]=xyz_list[1][1] - xyz_list[0][1];
+
+	norm=sqrt(pow(vector[0],2.0)+pow(vector[1],2.0));
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Numericalflux.h	(revision 18231)
@@ -0,0 +1,95 @@
+/*!\file Numericalflux.h
+ * \brief: header file for icefront object
+ */
+
+#ifndef _NUMERICALFLUX_H_
+#define _NUMERICALFLUX_H_
+
+/*Headers:*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class IoModel;
+class Element;
+class Vertex;
+class ElementMatrix;
+class ElementVector;
+
+class Numericalflux: public Load {
+
+	public: 
+		int id;
+		int analysis_type;
+		int flux_type;
+
+		/*Hooks*/
+		Hook *helement;
+		Hook *hnodes;
+		Hook *hvertices;
+
+		/*Corresponding fields*/
+		Element     *element;
+		Vertex     **vertices;
+		Node       **nodes;
+		Parameters  *parameters;
+
+		/*Numericalflux constructors,destructors {{{*/
+		Numericalflux();
+		Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel,int analysis_type);
+		~Numericalflux();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
+		void InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
+		void InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*Do nothing*/}
+		void InputUpdateFromConstant(IssmDouble constant, int name){/*Do nothing*/};
+		void InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
+		void InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
+		void InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void CreatePVector(Vector<IssmDouble>* pf);
+		void GetNodesSidList(int* sidlist);
+		void GetNodesLidList(int* lidlist);
+		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* flagsindices,int set1_enum,int set2_enum);
+		bool InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Numericalflux management:{{{*/
+		void           GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
+		ElementMatrix* CreateKMatrixMasstransport(void);
+		ElementMatrix* CreateKMatrixMasstransportInternal(void);
+		ElementMatrix* CreateKMatrixMasstransportBoundary(void);
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorMasstransport(void);
+		ElementVector* CreatePVectorMasstransportInternal(void);
+		ElementVector* CreatePVectorMasstransportBoundary(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethicknessInternal(void);
+		ElementVector* CreatePVectorBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		/*}}}*/
+
+};
+
+#endif  /* _NUMERICALFLUX_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.cpp	(revision 18231)
@@ -0,0 +1,686 @@
+/*!\file Pengrid.c
+ * \brief: implementation of the Pengrid object
+ */
+
+/*Headers*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+#include "../../analyses/analyses.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   1
+
+/*Pengrid constructors and destructor*/
+Pengrid::Pengrid(){/*{{{*/
+	this->parameters=NULL;
+	this->hnode=NULL;
+	this->node=NULL;
+	this->helement=NULL;
+	this->element=NULL;
+	this->hmatpar=NULL;
+	this->matpar=NULL;
+
+	/*not active, not zigzagging: */
+	active=0;
+	zigzag_counter=0;
+
+}
+/*}}}*/
+Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index/*{{{*/
+
+	int pengrid_node_id;
+	int pengrid_matpar_id;
+	int pengrid_element_id;
+
+	/*Some checks if debugging activated*/
+	_assert_(iomodel->singlenodetoelementconnectivity);
+	_assert_(index>=0 && index<iomodel->numberofvertices);
+	_assert_(id);
+
+	/*id: */
+	this->id=id;
+	this->analysis_type=in_analysis_type;
+
+	/*hooks: */
+	pengrid_node_id=iomodel->nodecounter+index+1;
+	pengrid_element_id=iomodel->singlenodetoelementconnectivity[index];
+	_assert_(pengrid_element_id);
+	pengrid_matpar_id=iomodel->numberofelements+1; //refers to the constant material parameters object
+
+	this->hnode=new Hook(&pengrid_node_id,1);
+	this->helement=new Hook(&pengrid_element_id,1);
+	this->hmatpar=new Hook(&pengrid_matpar_id,1);
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+
+	//let's not forget internals
+	this->active=0;
+	this->zigzag_counter=0;
+
+}
+/*}}}*/
+Pengrid::~Pengrid(){/*{{{*/
+	delete hnode;
+	delete helement;
+	delete hmatpar;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Pengrid::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void Pengrid::DeepEcho(void){/*{{{*/
+
+	_printf_("Pengrid:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnode->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	_printf_("   active " << this->active << "\n");
+	_printf_("   zigzag_counter " << this->zigzag_counter << "\n");
+	_printf_("   parameters\n");
+	parameters->DeepEcho();
+}
+/*}}}*/
+int    Pengrid::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Pengrid::ObjectEnum(void){/*{{{*/
+
+	return PengridEnum;
+}
+/*}}}*/
+Object* Pengrid::copy() {/*{{{*/
+
+	Pengrid* pengrid=NULL;
+
+	pengrid=new Pengrid();
+
+	/*copy fields: */
+	pengrid->id=this->id;
+	pengrid->analysis_type=this->analysis_type;
+
+	/*point parameters: */
+	pengrid->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	pengrid->hnode=(Hook*)this->hnode->copy();
+	pengrid->hmatpar=(Hook*)this->hmatpar->copy();
+	pengrid->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	pengrid->node  =(Node*)pengrid->hnode->delivers();
+	pengrid->matpar =(Matpar*)pengrid->hmatpar->delivers();
+	pengrid->element=(Element*)pengrid->helement->delivers();
+
+	//let's not forget internals
+	pengrid->active=this->active=0;
+	pengrid->zigzag_counter=this->zigzag_counter=0;
+
+	return pengrid;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+void  Pengrid::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+	/*Take care of hooking up all objects for this load, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnode->configure(nodesin);
+	helement->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Get corresponding fields*/
+	node=(Node*)hnode->delivers();
+	element=(Element*)helement->delivers();
+	matpar=(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+}
+/*}}}*/
+void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Pengrid::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Pengrid::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
+
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		
+	case HydrologyDCInefficientAnalysisEnum:
+		pe = CreatePVectorHydrologyDCInefficient();
+		break;
+	default:
+		/*No loads applied, do nothing: */
+		return;
+	}
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+void Pengrid::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(node);
+
+	sidlist[0]=node->Sid();
+}
+/*}}}*/
+void Pengrid::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(node);
+
+	lidlist[0]=node->Lid();
+}
+/*}}}*/
+int Pengrid::GetNumberOfNodes(void){/*{{{*/
+
+	return NUMVERTICES;
+}
+/*}}}*/
+void  Pengrid::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case ThermalAnalysisEnum:
+			Ke=PenaltyCreateKMatrixThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMelting(kmax);
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			Ke=PenaltyCreateKMatrixHydrologyDCInefficient(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+void  Pengrid::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case ThermalAnalysisEnum:
+			pe=PenaltyCreatePVectorThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			pe=PenaltyCreatePVectorMelting(kmax);
+			break;
+		case StressbalanceAnalysisEnum: case AdjointHorizAnalysisEnum:
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			pe=PenaltyCreatePVectorHydrologyDCInefficient(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+bool Pengrid::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+bool Pengrid::IsPenalty(void){/*{{{*/
+	return true;
+}
+/*}}}*/
+void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	if(!flags[this->node->Lid()]){
+
+		/*flag current node so that no other element processes it*/
+		flags[this->node->Lid()]=true;
+
+		int counter=0;
+		while(flagsindices[counter]>=0) counter++;
+		flagsindices[counter]=this->node->Lid();
+
+		/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+		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:*/
+void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
+	/*Nothing*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromConstant(int constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromConstant(bool constant, int name){/*{{{*/
+
+	switch(name){
+
+		case ResetPenaltiesEnum:
+			if (constant) zigzag_counter=0;
+			return;
+
+	}
+}
+/*}}}*/
+
+/*Pengrid management:*/
+void  Pengrid::ConstraintActivate(int* punstable){/*{{{*/
+
+	int analysis_type;
+
+	/*Retrieve parameters: */
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if (analysis_type==StressbalanceAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	else if (analysis_type==ThermalAnalysisEnum){
+		ConstraintActivateThermal(punstable);
+	}
+	else if (analysis_type==MeltingAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	else if (analysis_type==HydrologyDCInefficientAnalysisEnum){
+		ConstraintActivateHydrologyDCInefficient(punstable);
+		return;
+	}
+	else{
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+void  Pengrid::ConstraintActivateThermal(int* punstable){/*{{{*/
+
+	//   The penalty is stable if it doesn't change during to successive iterations.   
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble t_pmp;
+	int        new_active;
+	int        unstable=0;
+	int        penalty_lock;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	//First recover pressure and temperature values, using the element: */
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperaturePicardEnum);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
+
+	//Compute pressure melting point
+	t_pmp=matpar->TMeltingPoint(pressure);
+
+	//Figure out if temperature is over melting_point, in which case, this penalty needs to be activated.
+
+	if (temperature>t_pmp){
+		new_active=1;
+	}
+	else{
+		new_active=0;
+	}
+
+	//Figure out stability of this penalty
+	if (active==new_active){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		if(penalty_lock)zigzag_counter++;
+	}
+
+	/*If penalty keeps zigzagging more than 5 times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+
+	//Set penalty flag
+	active=new_active;
+
+	//*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure,temperature,t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load*/
+	if (temperature<t_pmp){ //If T<Tpmp, there must be no melting. Therefore, melting should be  constrained to 0 when T<Tpmp, instead of using spcs, use penalties
+		Ke->values[0]=kmax*pow(10.,penalty_factor);
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){/*{{{*/
+
+	IssmDouble    penalty_factor;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble melting_offset;
+	IssmDouble t_pmp;
+	IssmDouble dt,penalty_factor;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementVector* pe=new ElementVector(&node,NUMVERTICES,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&melting_offset,MeltingOffsetEnum);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load
+	  This time, the penalty must have the same value as the one used for the thermal computation
+	  so that the corresponding melting can be computed correctly
+	  In the thermal computation, we used kmax=melting_offset, and the same penalty_factor*/
+	if (temperature<t_pmp){ //%no melting
+		pe->values[0]=0;
+	}
+	else{
+		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp)/dt;
+		else    pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp);
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure;
+	IssmDouble t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	pe->values[0]=kmax*pow(10.,penalty_factor)*t_pmp;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+void  Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){/*{{{*/
+
+	//   The penalty is stable if it doesn't change during two consecutive iterations.   
+	int        unstable=0;
+	int        new_active;
+	int        penalty_lock;
+	IssmDouble pressure;
+	IssmDouble h;
+	IssmDouble h_max;	
+	HydrologyDCInefficientAnalysis* inefanalysis = NULL;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if(node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+	if(!element->IsOnBase()){
+		unstable=0;
+		active=0;
+		*punstable=unstable;
+		return;
+	}
+
+	/*Get sediment water head h*/
+	inefanalysis = new HydrologyDCInefficientAnalysis();
+	element->GetInputValue(&h,node,SedimentHeadEnum);
+	inefanalysis->GetHydrologyDCInefficientHmax(&h_max,element,node);
+	parameters->FindParam(&penalty_lock,HydrologydcPenaltyLockEnum);
+
+	if (h>h_max){
+	 new_active=1;
+	}
+	else{
+	 new_active=0;
+	}
+
+	if(this->active==new_active){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		if(penalty_lock)zigzag_counter++;
+	}
+
+	/*If penalty keeps zigzagging more than penalty_lock times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+	/*Set penalty flag*/
+	this->active=new_active;
+
+	/*Assign output pointers:*/
+	delete inefanalysis;
+	*punstable=unstable;
+}
+/*}}}*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){/*{{{*/
+	IssmDouble    penalty_factor;
+
+	/*Retrieve parameters*/
+	parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementVector* Pengrid::PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax){/*{{{*/
+
+	IssmDouble h_max;
+	IssmDouble penalty_factor;
+	HydrologyDCInefficientAnalysis* inefanalysis = NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+	inefanalysis = new HydrologyDCInefficientAnalysis();
+
+	/*Retrieve parameters*/
+	parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+
+	/*Get h_max and compute penalty*/
+	inefanalysis->GetHydrologyDCInefficientHmax(&h_max,element,node);
+
+	pe->values[0]=kmax*pow(10.,penalty_factor)*h_max;
+
+	/*Clean up and return*/
+	delete inefanalysis;
+	return pe;
+}
+/*}}}*/
+ElementVector* Pengrid::CreatePVectorHydrologyDCInefficient(void){/*{{{*/
+
+	IssmDouble moulin_load,dt;
+
+	/*Initialize Element matrix*/
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	this->element->GetInputValue(&moulin_load,node,HydrologydcBasalMoulinInputEnum);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	if(dt!=0.0) pe->values[0]=moulin_load*dt;
+
+	/*Clean up and return*/
+	return pe;
+ }
+/*}}}*/
+void  Pengrid::ResetConstraint(void){/*{{{*/
+	active         = 0;
+	zigzag_counter = 0;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Pengrid.h	(revision 18231)
@@ -0,0 +1,99 @@
+/*!\file Pengrid.h
+ * \brief: header file for pengrid object */
+
+#ifndef _PENGRID_H_
+#define _PENGRID_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Load.h"
+class Hook;
+class Inputs;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Pengrid: public Load{
+
+	private: 
+
+		int        id;
+		int        analysis_type;
+
+		/*Hooks*/
+		Hook* hnode;  //hook to 1 node
+		Hook* helement;  //hook to 1 element
+		Hook* hmatpar; //hook to 1 matpar
+
+		/*Corresponding fields*/
+		Node    *node;
+		Element *element;
+		Matpar  *matpar;
+
+		Parameters* parameters; //pointer to solution parameters
+
+		/*internals: */
+		int active;
+		int zigzag_counter;
+
+	public:
+
+		/*Pengrid constructors, destructors {{{*/
+		Pengrid();
+		Pengrid(int index, int id, IoModel* iomodel,int analysis_type);
+		~Pengrid();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix ,int nrows, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
+		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* flagsindices,int set1_enum,int set2_enum);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Pengrid management {{{*/
+		ElementMatrix* PenaltyCreateKMatrixThermal(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixMelting(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorThermal(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorMelting(IssmDouble kmax);
+		void           ConstraintActivateThermal(int* punstable);
+		ElementMatrix* PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax);
+		void           ConstraintActivateHydrologyDCInefficient(int* punstable);
+		void  ConstraintActivate(int* punstable);
+		ElementVector* CreatePVectorHydrologyDCInefficient(void);
+		void  ResetConstraint(void);
+		/*}}}*/
+
+};
+
+#endif  /* _PENGRID_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.cpp	(revision 18231)
@@ -0,0 +1,381 @@
+/*!\file Penpair.c
+ * \brief: implementation of the Penpair object
+ */
+
+/*Headers*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Penpair constructors and destructor*/
+Penpair::Penpair(){/*{{{*/
+
+	this->hnodes=NULL;
+	this->nodes=NULL;
+	this->parameters=NULL;
+	return;
+}
+/*}}}*/
+Penpair::Penpair(int penpair_id, int* penpair_node_ids,int in_analysis_type){/*{{{*/
+
+	this->id=penpair_id;
+	this->analysis_type=in_analysis_type;
+	this->hnodes=new Hook(penpair_node_ids,2);
+	this->parameters=NULL;
+	this->nodes=NULL;
+
+	return;
+}
+/*}}}*/
+Penpair::~Penpair(){/*{{{*/
+	delete hnodes;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Penpair::Echo(void){/*{{{*/
+
+	_printf_("Penpair:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->Echo();
+
+	return;
+}
+/*}}}*/
+void Penpair::DeepEcho(void){/*{{{*/
+
+	_printf_("Penpair:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+
+	return;
+}		
+/*}}}*/
+int    Penpair::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Penpair::ObjectEnum(void){/*{{{*/
+
+	return PenpairEnum;
+}
+/*}}}*/
+Object* Penpair::copy() {/*{{{*/
+
+	Penpair* penpair=NULL;
+
+	penpair=new Penpair();
+
+	/*copy fields: */
+	penpair->id=this->id;
+	penpair->analysis_type=this->analysis_type;
+
+	/*now deal with hooks and objects: */
+	penpair->hnodes=(Hook*)this->hnodes->copy();
+	penpair->nodes =(Node**)penpair->hnodes->deliverp();
+
+	/*point parameters: */
+	penpair->parameters=this->parameters;
+
+	return penpair;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+void  Penpair::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure((DataSet*)nodesin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Penpair::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+	/*If you code this piece, don't forget that a penalty will be inactive if it is dealing with clone nodes*/
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Penpair::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){/*{{{*/
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+void Penpair::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+void Penpair::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
+}
+/*}}}*/
+int Penpair::GetNumberOfNodes(void){/*{{{*/
+
+	return NUMVERTICES;
+}
+/*}}}*/
+bool Penpair::IsPenalty(void){/*{{{*/
+	return true;
+}
+/*}}}*/
+void  Penpair::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case StressbalanceAnalysisEnum:
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
+			break;
+		case MasstransportAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMasstransport(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+void  Penpair::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
+	/*No loads applied, do nothing: */
+	return;
+}
+/*}}}*/
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){/*{{{*/
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+bool Penpair::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,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]->Lid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+void  Penpair::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Penpair::InputUpdateFromConstant(int constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Penpair::InputUpdateFromConstant(bool constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Penpair management:*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){/*{{{*/
+
+	int    approximation0=nodes[0]->GetApproximation();
+	int    approximation1=nodes[1]->GetApproximation();
+
+	switch(approximation0){
+		case SSAApproximationEnum:
+			switch(approximation1){
+				case SSAApproximationEnum: return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				case HOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
+			}
+		case HOApproximationEnum:
+			switch(approximation1){
+				case SSAApproximationEnum: return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				case HOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
+			}
+		case FSvelocityEnum:
+			switch(approximation1){
+				case FSvelocityEnum: return PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
+			}
+		case NoneApproximationEnum:
+			switch(approximation1){
+				case FSvelocityEnum: return PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixStressbalanceFS(kmax); 
+			}
+		default: _error_("Approximation "<<EnumToStringx(approximation0)<<" not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax){/*{{{*/
+
+	const int numdof=NUMVERTICES*NDOF2;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_offset);
+	Ke->values[0*numdof+2]=-kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+0]=-kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+2]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_offset);
+	Ke->values[1*numdof+3]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+1]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow(10.,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){/*{{{*/
+
+	const int  numdof=NUMVERTICES*NDOF3;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_offset);
+	Ke->values[0*numdof+3]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+0]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_offset);
+	Ke->values[1*numdof+4]=-kmax*pow(10.,penalty_offset);
+	Ke->values[4*numdof+1]=-kmax*pow(10.,penalty_offset);
+	Ke->values[4*numdof+4]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[2*numdof+2]=+kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+5]=-kmax*pow(10.,penalty_offset);
+	Ke->values[5*numdof+2]=-kmax*pow(10.,penalty_offset);
+	Ke->values[5*numdof+5]=+kmax*pow(10.,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){/*{{{*/
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble penalty_factor;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,MasstransportPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_factor);
+	Ke->values[0*numdof+1]=-kmax*pow(10.,penalty_factor);
+	Ke->values[1*numdof+0]=-kmax*pow(10.,penalty_factor);
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Penpair.h	(revision 18231)
@@ -0,0 +1,72 @@
+/*!\file Penpair.h
+ * \brief: header file for penpair object */
+
+#ifndef _PENPAIR_H_
+#define _PENPAIR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Load.h"
+#include "../Node.h"
+#include "../Elements/Element.h"
+
+class Element;
+/*}}}*/
+
+class Penpair: public Load{
+
+	private: 
+		int          id;
+		int          analysis_type;
+		Hook        *hnodes;          //hook to 2 nodes
+		Node       **nodes;
+		Parameters  *parameters;      //pointer to solution parameters
+
+	public:
+
+		/*Penpair constructors, destructors: {{{*/
+		Penpair();
+		Penpair(int penpair_id,int* penpair_node_ids,int analysis_type);
+		~Penpair();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols,int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+			/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
+		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* flagsindices,int set1_enum,int set2_enum);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+			/*Penpair management: {{{*/
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixMasstransport(IssmDouble kmax);
+		/*}}}*/
+};
+
+#endif  /* _PENPAIR_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.cpp	(revision 18231)
@@ -0,0 +1,652 @@
+/*!\file Riftfront.cpp
+ * \brief: implementation of the Riftfront object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "shared/shared.h"
+#include "modules/ModelProcessorx/ModelProcessorx.h"
+#include "../classes.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Riftfront constructors and destructor*/
+Riftfront::Riftfront(){/*{{{*/
+	this->parameters=NULL;
+	this->hnodes=NULL;
+	this->helements=NULL;
+	this->hmatpar=NULL;
+	this->nodes=NULL;
+	this->elements=NULL;
+	this->matpar=NULL;
+}
+/*}}}*/
+Riftfront::Riftfront(int riftfront_id,int i, IoModel* iomodel,int riftfront_analysis_type){/*{{{*/
+
+	/*data: */
+	const int RIFTINFOSIZE = 12;
+	int    riftfront_node_ids[2];
+	int    riftfront_elem_ids[2];
+	int    riftfront_matpar_id;
+	IssmDouble riftfront_friction;
+	IssmDouble riftfront_fractionincrement;
+	int    penalty_lock;
+
+	/*intermediary: */
+	int el1    ,el2;
+	int node1  ,node2;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&penalty_lock,StressbalanceRiftPenaltyLockEnum);
+
+	/*Ok, retrieve all the data needed to add a penalty between the two nodes: */
+	el1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2));
+	el2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3)) ;
+
+	node1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0));
+	node2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1));
+
+	/*id: */
+	this->id=riftfront_id;
+	this->analysis_type=riftfront_analysis_type;
+
+	/*hooks: */
+	riftfront_node_ids[0]=iomodel->nodecounter+node1;
+	riftfront_node_ids[1]=iomodel->nodecounter+node2;
+	riftfront_elem_ids[0]=el1;
+	riftfront_elem_ids[1]=el2;
+	riftfront_matpar_id=iomodel->numberofelements+1; //matlab indexing
+
+	/*Hooks: */
+	this->hnodes=new Hook(riftfront_node_ids,2);
+	this->helements=new Hook(riftfront_elem_ids,2);
+	this->hmatpar=new Hook(&riftfront_matpar_id,1);
+
+	/*computational parameters: */
+	this->active=0;
+	this->frozen=0;
+	this->counter=0;
+	this->prestable=0;
+	this->penalty_lock=penalty_lock;
+	this->material_converged=0;
+	this->normal[0]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+4);
+	this->normal[1]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+5);
+	this->length=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+6);
+	this->fraction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+9);
+	this->state=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11));
+
+	//intialize properties
+	this->type=SegmentRiftfrontEnum;
+	this->fill = reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7));
+	this->friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
+	this->fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
+	this->shelf=reCast<bool,IssmDouble>(iomodel->Data(MaskGroundediceLevelsetEnum)[node1-1]<0.);
+
+	//parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->nodes= NULL;
+	this->elements= NULL;
+	this->matpar= NULL;
+
+}
+/*}}}*/
+Riftfront::~Riftfront(){/*{{{*/
+	this->parameters=NULL;
+	delete hnodes;
+	delete helements;
+	delete hmatpar;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Riftfront::Echo(void){/*{{{*/
+
+	_printf_("Riftfront:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   hnodes: " << hnodes << "\n");
+	_printf_("   helements: " << helements << "\n");
+	_printf_("   hmatpar: " << hmatpar << "\n");
+	_printf_("   parameters: " << parameters << "\n");
+	_printf_("   internal parameters: \n");
+	_printf_("   normal: " << normal[0] << "|" << normal[1] << "\n");
+	_printf_("   length: " << length << "\n");
+	_printf_("   penalty_lock: " << penalty_lock << "\n");
+	_printf_("   active: " <<(active ? "true":"false") << "\n");
+	_printf_("   counter: " << counter << "\n");
+	_printf_("   prestable: " << (prestable ? "true":"false") << "\n");
+	_printf_("   material_converged: " << (material_converged ? "true":"false") << "\n");
+	_printf_("   fill: " << fill << "\n");
+	_printf_("   friction: " << friction << "\n");
+	_printf_("   fraction: " << fraction << "\n");
+	_printf_("   fractionincrement: " << fractionincrement << "\n");
+	_printf_("   state: " << state << "\n");
+	_printf_("   frozen: " << (frozen ? "true":"false") << "\n");
+
+}
+/*}}}*/
+void Riftfront::DeepEcho(void){/*{{{*/
+
+	_printf_("Riftfront:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+	helements->DeepEcho();
+	hmatpar->DeepEcho();
+	_printf_("   parameters\n");
+	if(parameters)parameters->DeepEcho();
+}
+/*}}}*/
+int    Riftfront::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Riftfront::ObjectEnum(void){/*{{{*/
+
+	return RiftfrontEnum;
+
+}
+/*}}}*/
+Object* Riftfront::copy() {/*{{{*/
+
+	Riftfront* riftfront=NULL;
+
+	riftfront=new Riftfront();
+
+	/*copy fields: */
+	riftfront->id=this->id;
+	riftfront->analysis_type=this->analysis_type;
+	riftfront->type=this->type;
+	riftfront->fill=this->fill;
+	riftfront->friction=this->friction;
+	riftfront->fractionincrement=this->fractionincrement;
+	riftfront->shelf=this->shelf;
+
+	/*point parameters: */
+	riftfront->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	riftfront->hnodes=(Hook*)this->hnodes->copy();
+	riftfront->helements=(Hook*)this->helements->copy();
+	riftfront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	riftfront->nodes   =(Node**)riftfront->hnodes->deliverp();
+	riftfront->elements=(Element**)riftfront->helements->deliverp();
+	riftfront->matpar  =(Matpar*)riftfront->hmatpar->delivers();
+
+	/*internal data: */
+	riftfront->penalty_lock=this->penalty_lock;
+	riftfront->active=this->active;
+	riftfront->frozen=this->frozen;
+	riftfront->state=this->state;
+	riftfront->counter=this->counter;
+	riftfront->prestable=this->prestable;
+	riftfront->material_converged=this->material_converged;
+	riftfront->normal[0]=this->normal[0];
+	riftfront->normal[1]=this->normal[1];
+	riftfront->length=this->length;
+	riftfront->fraction=this->fraction;
+
+	return riftfront;
+
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+void  Riftfront::InputUpdateFromConstant(bool constant,int name){/*{{{*/
+}
+/*}}}*/
+void  Riftfront::InputUpdateFromConstant(IssmDouble constant,int name){/*{{{*/
+
+}
+/*}}}*/
+void    Riftfront::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+
+	_error_("not implemented yet");
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+void  Riftfront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+	helements->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes   =(Node**)hnodes->deliverp();
+	this->elements=(Element**)helements->deliverp();
+	this->matpar  =(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+bool Riftfront::IsPenalty(void){/*{{{*/
+	return true;
+}
+/*}}}*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Riftfront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case StressbalanceAnalysisEnum:
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+void  Riftfront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case StressbalanceAnalysisEnum:
+			pe=PenaltyCreatePVectorStressbalanceHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			/*No penalty applied on load vector*/
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+void Riftfront::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+void Riftfront::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
+}
+/*}}}*/
+int Riftfront::GetNumberOfNodes(void){/*{{{*/
+
+	return NUMVERTICES;
+}
+/*}}}*/
+bool Riftfront::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,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]->Lid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			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*/
+ElementMatrix* Riftfront::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){/*{{{*/
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	IssmDouble  thickness;
+	IssmDouble  h[2];
+	IssmDouble  penalty_offset;
+
+	/*Objects: */
+	Tria       *tria1               = NULL;
+	Tria       *tria2               = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some parameters: */
+	this->parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+
+	/*There is contact, we need to constrain the normal velocities (zero penetration), and the 
+	 *contact slip friction. */
+
+	/*From Peter Wriggers book (Computational Contact Mechanics, p191): */
+	Ke->values[0*numdof+0]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+1]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+2]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+3]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[1*numdof+0]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+1]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+2]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+3]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	Ke->values[2*numdof+0]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+1]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+2]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+3]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[3*numdof+0]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+1]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+2]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+3]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	/*Now take care of the friction: of type sigma=frictiontangent_velocity2-tangent_velocity1)*/
+
+	Ke->values[0*numdof+0]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+1]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[0*numdof+2]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+3]+= +normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[1*numdof+0]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+1]+= +pow(normal[0],2)*thickness*length*friction;
+	Ke->values[1*numdof+2]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+3]+= -pow(normal[0],2)*thickness*length*friction;
+
+	Ke->values[2*numdof+0]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+1]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[2*numdof+2]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+3]+= -normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[3*numdof+0]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+1]+= -pow(normal[0],2)*thickness*length*friction;
+	Ke->values[3*numdof+2]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+3]+= +pow(normal[0],2)*thickness*length*friction;
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementVector* Riftfront::PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax){/*{{{*/
+
+	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;
+
+	/*Objects: */
+	Tria *tria1 = NULL;
+	Tria *tria2 = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(this->active) return NULL; /*The penalty is active. No loads implied here.*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some inputs: */
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+	tria1->GetInputValue(&b[0],nodes[0],BaseEnum);
+	tria2->GetInputValue(&b[1],nodes[1],BaseEnum);
+	if (b[0]!=b[1])_error_("different beds not supported for rift fronts");
+	bed=b[0];
+
+	/*Ok, this rift is opening. We should put loads on both sides of the rift flanks. Because we are dealing with contact mechanics, 
+	 * and we want to avoid zigzagging of the loads, we want lump the loads onto nodes, not onto surfaces between nodes.:*/
+
+	/*Ok, to compute the pressure, we are going to need material properties, thickness and bed for the two nodes. We assume those properties to 
+	 * be the same across the rift.: */
+
+	/*Ok, now compute the pressure (in norm) that is being applied to the flanks, depending on the type of fill: */
+	if(fill==WaterEnum){
+		if(shelf){
+			/*We are on an ice shelf, hydrostatic equilibrium is used to determine the pressure for water fill: */
+			pressure=rho_ice*gravity*pow(thickness,2)/2.- rho_water*gravity*pow(bed,2)/2.; 
+		}
+		else{
+			//We are on an icesheet, we assume the water column fills the entire front: */
+			pressure=rho_ice*gravity*pow(thickness,2)/2.- rho_water*gravity*pow(thickness,2)/2.; 
+		}
+	}
+	else if(fill==AirEnum){
+		pressure=rho_ice*gravity*pow(thickness,2)/2.;   //icefront on an ice sheet, pressure imbalance ice vs air.
+	}
+	else if(fill==IceEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
+		pressure=0;
+	}
+	else if(fill==MelangeEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
+
+		if(!shelf) _error_("fill type " << fill << " not supported on ice sheets yet.");
+
+		pressure_litho=rho_ice*gravity*pow(thickness,2)/2.;
+		pressure_air=0;
+		pressure_melange=rho_ice*gravity*pow(fraction*thickness,2)/2.;
+		pressure_water=1.0/2.0*rho_water*gravity*  ( pow(bed,2.0)-pow(rho_ice/rho_water*fraction*thickness,2.0) );
+
+		pressure=pressure_litho-pressure_air-pressure_melange-pressure_water;
+	}
+	else{
+		_error_("fill type " << fill << " not supported yet.");
+	}
+
+	/*Ok, add contribution to first node, along the normal i==0: */
+	for (j=0;j<2;j++){
+		pe->values[j]+=pressure*normal[j]*length;
+	}
+
+	/*Add contribution to second node, along the opposite normal: i==1 */
+	for (j=0;j<2;j++){
+		pe->values[2+j]+= -pressure*normal[j]*length;
+	}	
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#define _ZIGZAGCOUNTER_
+int Riftfront::Constrain(int* punstable){/*{{{*/
+
+	IssmDouble  penetration;
+	bool        activate;
+	int         unstable;
+	IssmDouble  vx1;
+	IssmDouble  vy1;
+	IssmDouble  vx2;
+	IssmDouble  vy2;
+
+	/*Objects: */
+	Tria  *tria1 = NULL;
+	Tria  *tria2 = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Is this constraint frozen? In which case we don't touch: */
+	if (this->frozen){
+		*punstable=0;
+		return 1;
+	}
+
+	/*Is this rift segment state specified by user input? :*/
+	if (this->state==OpenEnum || this->state==ClosedEnum){
+
+		if(this->state==OpenEnum)this->active=0;
+		if(this->state==ClosedEnum)this->active=1;
+
+		/*this segment is like frozen, no instability here: */
+		*punstable=0;
+		return 1;
+	}
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*activation: */
+	if(penetration<0)activate=true;
+	else  activate=false;
+
+	/*Here, we try to avoid zigzaging. When a penalty activates and deactivates for more than penalty_lock times, 
+	 * we increase the fraction of melange:*/
+	if(this->counter>this->penalty_lock){
+		/*reset counter: */
+		this->counter=0;
+		/*increase melange fraction: */
+		this->fraction+=fractionincrement;
+		if (this->fraction>1)this->fraction=1.;
+		//_printf_("riftfront " << this->Id() << " fraction: " << this->fraction << "\n");
+	}
+
+	//Figure out stability of this penalty
+	if(this->active==activate){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		this->counter++;
+	}
+
+	//Set penalty flag
+	this->active=activate;
+
+	//if ((penetration>0) && (this->active==1))_printf_("Riftfront " << Id() << " wants to be released\n");
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+void   Riftfront::FreezeConstraints(void){/*{{{*/
+
+	/*Just set frozen flag to 1: */
+	this->frozen=1;
+
+}
+/*}}}*/
+bool   Riftfront::IsFrozen(void){/*{{{*/
+
+	/*Just set frozen flag to 1: */
+	if(this->frozen)return 1;
+	else return 0;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Loads/Riftfront.h	(revision 18231)
@@ -0,0 +1,98 @@
+/*!\file Riftfront.h
+ * \brief: header file for riftfront object
+ */
+
+#ifndef _RIFTFRONT_H_
+#define _RIFTFRONT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Riftfront: public Load {
+
+	public:
+		int		id;
+		int     analysis_type;
+
+		/*properties*/
+		int        type;
+		int        fill;
+		IssmDouble friction;
+		IssmDouble fractionincrement;
+		bool       shelf;
+
+		/*hooks: */
+		Hook* hnodes;
+		Hook* helements;
+		Hook* hmatpar;
+
+		/*Corresponding fields*/
+		Matpar   *matpar;
+		Node    **nodes;
+		Element **elements;
+
+		/*computational: */
+		int         penalty_lock;
+		bool        active;
+		bool        frozen;
+		int         counter;
+		bool        prestable;
+		bool        material_converged;
+		IssmDouble  normal[2];
+		IssmDouble  length;
+		IssmDouble  fraction;
+		int         state;
+
+		Parameters *parameters;           //pointer to solution parameters
+
+		/*Riftfrontconstructors,destructors: {{{*/
+		Riftfront();
+		Riftfront(int riftfront_id,int i, IoModel* iomodel,int analysis_type);
+		~Riftfront();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(IssmDouble constant, int name);
+		void    InputUpdateFromConstant(int constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(bool constant, int name);
+		void    InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
+		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* flagsindices,int set1_enum,int set2_enum);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Riftfront specific routines: {{{*/
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax);
+		int   Constrain(int* punstable);
+		void  FreezeConstraints(void);
+		bool  IsFrozen(void);
+		/*}}}*/
+};
+#endif  /* _RIFTFRONT_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Massfluxatgate.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Massfluxatgate.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Massfluxatgate.h	(revision 18231)
@@ -0,0 +1,154 @@
+/*!\file Massfluxatgate.h
+ * \brief: header file for Massfluxatgate object
+ */
+
+#ifndef _MASSFLUXATGATE_H_
+#define _MASSFLUXATGATE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+/*}}}*/
+
+template <class doubletype> 
+class Massfluxatgate: public Object, public Definition{
+
+	public: 
+
+		char*       name;
+		int         numsegments;
+		doubletype *x1;
+		doubletype *y1;
+		doubletype *x2;
+		doubletype *y2;
+		int*        elements;
+
+		/*Massfluxatgate constructors, destructors :*/
+		Massfluxatgate(){/*{{{*/
+			this->name        = 0;
+			this->numsegments = 0;
+			this->segments    = 0;
+		}
+		/*}}}*/
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_segments) {/*{{{*/
+			
+			int i;
+
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->numsegments=in_numsegments;
+
+			if(this->numsegments){
+				this->x1=xNew<doubletype>(this->numsegments);
+				this->x2=xNew<doubletype>(this->numsegments);
+				this->y1=xNew<doubletype>(this->numsegments);
+				this->y2=xNew<doubletype>(this->numsegments);
+				this->elements=xNew<int>(this->numsegments);
+
+				for(i=0;i<this->numsegments;i++){
+					this->x1[i]=in_segments[5*i+0];
+					this->y1[i]=in_segments[5*i+1];
+					this->x2[i]=in_segments[5*i+2];
+					this->y2[i]=in_segments[5*i+3];
+					this->elements[i]=reCast<int,doubletype>(in_segments[5*i+4]);
+				}
+			}
+		}
+		/*}}}*/
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){/*{{{*/
+
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->numsegments=in_numsegments;
+
+			if(this->numsegments){
+				this->x1=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->x1,in_x1,this->numsegments);
+				this->y1=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->y1,in_y1,this->numsegments);
+				this->x2=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->x2,in_x2,this->numsegments);
+				this->y2=xNew<doubletype>(this->numsegments); xMemCpy<doubletype>(this->y2,in_y2,this->numsegments);
+				this->elements=xNew<int>(this->numsegments); xMemCpy<int>(this->elements,in_elements,this->numsegments);
+				
+			}
+		}
+		/*}}}*/
+		~Massfluxatgate(){/*{{{*/
+			xDelete<doubletype>(this->x1);
+			xDelete<doubletype>(this->y1);
+			xDelete<doubletype>(this->x2);
+			xDelete<doubletype>(this->y2);
+			xDelete<int>(this->elements);
+			xDelete<char>(this->name);
+		}
+		/*}}}*/
+
+		/*Object virtual function resolutoin: */
+		void Echo(void){/*{{{*/
+			_printf_(" Massfluxatgate: " << name << "\n");
+			_printf_("    numsegments: " << numsegments << "\n");
+			if(numsegments){
+				_printf_("   element: x1, y1, x2, y2:\n");
+				for(int i=0;i<numsegments;i++){
+					_printf_(elements[i] << " " << x1[i] << " " << y1[i] << " " << x2[i] << " " << y2[i] << "\n");
+				}
+			}
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int Id(void){/*{{{*/
+			return -1;
+		}
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+			return MassfluxatgateEnum;
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			return new Massfluxatgate(this->name,this->numsegments,this->x1,this->y1,this->x2,this->y2,this->elements); 
+		}
+		/*}}}*/
+		/*Definition virtual function resolutoin: */
+		char* Name(){/*{{{*/
+
+			char* name2=xNew<char>(strlen(this->name)+1);
+			xMemCpy(name2,this->name,strlen(this->name)+1);
+
+			return name2;
+		}
+		/*}}}*/
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
+
+			int          i,j;
+			Element     *element       = NULL;
+			IssmDouble mass_flux     = 0;
+			IssmDouble all_mass_flux = 0;
+
+			/*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<numsegments;i++){
+				for(j=0;j<femmodel->elements->Size();j++){
+					element=(Element*)femmodel->elements->GetObjectByOffset(j);
+					if (element->Id()==this->elements[i]){
+						/*We found the element which owns this segment, use it to compute the mass flux: */
+						mass_flux+=element->MassFlux(x1[i],y1[i],x2[i],y2[i],elements[i]);
+						break;
+					}
+				}
+			}
+
+			ISSM_MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+			mass_flux=all_mass_flux;
+			return mass_flux;
+		}
+			/*}}}*/
+};
+
+#endif  /* _MASSFLUXATGATE_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Material.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Material.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Material.h	(revision 18231)
@@ -0,0 +1,45 @@
+/*!\file:  Material.h
+ * \brief abstract class for Material object
+ */ 
+
+#ifndef _MATERIAL_H_
+#define _MATERIAL_H_
+
+/*Headers:*/
+/*{{{*/
+class Inputs;
+template <class doubletype> class Vector;
+#include "../../datastructures/datastructures.h"
+#include "../Update.h"
+class Element;
+class Elements;
+/*}}}*/
+
+class Material: public Object,public Update{
+
+	public: 
+		virtual ~Material(){};
+		/*WARNING: input should not be public but it is an easy way to update B from T (using UpdateFromSolution) from Pentas*/
+
+		/*Numerics*/
+		virtual Material*  copy2(Element* element)=0;
+		virtual void       Configure(Elements* elements)=0;
+		virtual void       GetViscosity(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual IssmDouble GetA()=0;
+		virtual IssmDouble GetAbar()=0;
+		virtual IssmDouble GetB()=0;
+		virtual IssmDouble GetBbar()=0;
+		virtual IssmDouble GetN()=0;
+		virtual IssmDouble GetD()=0;
+		virtual IssmDouble GetDbar()=0;
+		virtual bool       IsDamage()=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.cpp	(revision 18231)
@@ -0,0 +1,45 @@
+/*
+ * \file Materials.cpp
+ * \brief: Implementation of Materials class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Materials.h"
+#include "./Material.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Materials::Materials(){/*{{{*/
+	enum_type=MaterialsEnum;
+	return;
+}
+/*}}}*/
+Materials::~Materials(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+void Materials::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Material* material=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		material=dynamic_cast<Material*>(*object);
+		material->Configure(elements);
+
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Materials.h	(revision 18231)
@@ -0,0 +1,29 @@
+#ifndef _CONTAINER_MATERIALS_H_
+#define  _CONTAINER_MATERIALS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+
+/*! \brief Declaration of Materials class.
+ *
+ * Declaration of Materials class.  Materials are vector lists (Containers) of Material objects.
+ */ 
+class Materials: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Materials();
+		~Materials();
+
+		/*numerics*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+
+};
+
+#endif //ifndef _MATERIALS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.cpp	(revision 18231)
@@ -0,0 +1,568 @@
+/*!\file Matice.c
+ * \brief: implementation of the Matice object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Matice.h"
+#include "./Materials.h"
+#include "../Inputs/Input.h"
+#include "../Inputs/Inputs.h"
+#include "../Inputs/TriaInput.h"
+#include "../Inputs/PentaInput.h"
+#include "../Inputs/ControlInput.h"
+#include "../Elements/Element.h"
+#include "../Elements/Tria.h"
+#include "../Elements/Penta.h"
+#include "../Params/Parameters.h"
+#include "../Vertex.h"
+#include "../Hook.h"
+#include "../Node.h"
+#include "../IoModel.h"
+#include "../../shared/shared.h"
+
+/*Matice constructors and destructor*/
+Matice::Matice(){/*{{{*/
+	this->helement=NULL;
+	this->element=NULL;
+	return;
+}
+/*}}}*/
+Matice::Matice(int matice_mid,int index, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries:*/
+	int    matice_eid;
+
+	/*Initialize id*/
+	this->mid=matice_mid;
+
+	/*Hooks: */
+	matice_eid=index+1;
+	this->helement=new Hook(&matice_eid,1);
+	this->element=NULL;
+
+	 /*Other perporties*/
+   int    materialtype;
+   iomodel->Constant(&materialtype,MaterialsEnum);
+   if(materialtype==MatdamageiceEnum) this->isdamaged = true;
+   else if(materialtype==MaticeEnum) this->isdamaged = false;
+   else _error_("Material type not recognized");
+
+	return;
+
+}
+/*}}}*/
+Matice::~Matice(){/*{{{*/
+	delete helement;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Matice::Echo(void){/*{{{*/
+
+	_printf_("Matice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   element:\n");
+	helement->Echo();
+}
+/*}}}*/
+void Matice::DeepEcho(void){/*{{{*/
+
+	_printf_("Matice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   element:\n");
+	helement->Echo();
+}		
+/*}}}*/
+int    Matice::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+int Matice::ObjectEnum(void){/*{{{*/
+
+	return MaticeEnum;
+
+}
+/*}}}*/
+Object* Matice::copy() {/*{{{*/
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	matice->element =(Element*)this->helement->delivers();
+	matice->isdamaged = this->isdamaged;
+
+	return matice;
+}
+/*}}}*/
+Material* Matice::copy2(Element* element_in) {/*{{{*/
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	matice->element =element_in;
+	matice->isdamaged = this->isdamaged;
+
+	return matice;
+}
+/*}}}*/
+
+/*Matice management*/
+void  Matice::Configure(Elements* elementsin){/*{{{*/
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	helement->configure((DataSet*)elementsin);
+	this->element  = (Element*)helement->delivers();
+}
+/*}}}*/
+void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+IssmDouble Matice::GetA(){/*{{{*/
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+IssmDouble Matice::GetAbar(){/*{{{*/
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	element->inputs->GetInputAverage(&B,MaterialsRheologyBbarEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+IssmDouble Matice::GetB(){/*{{{*/
+
+	/*Output*/
+	IssmDouble B;
+
+	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+IssmDouble Matice::GetBbar(){/*{{{*/
+
+	/*Output*/
+	IssmDouble Bbar;
+
+	element->inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+IssmDouble Matice::GetN(){/*{{{*/
+
+	/*Output*/
+	IssmDouble n;
+
+	element->inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+IssmDouble Matice::GetD(){/*{{{*/
+
+	_assert_(this->isdamaged);
+	/*Output*/
+	IssmDouble D;
+	if(this->isdamaged)element->inputs->GetInputAverage(&D,DamageDEnum);
+	return D;
+}
+/*}}}*/
+IssmDouble Matice::GetDbar(){/*{{{*/
+
+	_assert_(this->isdamaged);
+	/*Output*/
+	IssmDouble Dbar;
+	if(this->isdamaged)element->inputs->GetInputAverage(&Dbar,DamageDbarEnum);
+	return Dbar;
+}
+/*}}}*/
+bool Matice::IsDamage(){/*{{{*/
+
+	return this->isdamaged;
+}
+/*}}}*/
+void  Matice::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+								(1-D) B
+	  viscosity= -------------------------
+						  2 eps_eff ^[(n-1)/n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , eps_eff is the effective strain rate
+	  and n the flow law exponent.
+
+	  If eps_eff = 0 , it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*Intermediary: */
+	IssmDouble B,D=0.,n;
+
+	/*Get B and n*/
+	B=GetB(); _assert_(B>0.);
+	n=GetN(); _assert_(n>0.);
+	if(this->isdamaged){
+		D=GetD();
+		_assert_(D>=0. && D<1.);
+	}
+
+	if (n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) viscosity=B/2: */
+		viscosity=(1.-D)*B/2.;
+	}
+	else{
+
+		/*if no strain rate, return maximum viscosity*/
+		if(eps_eff==0.){
+			viscosity = 1.e+14/2.;
+			//viscosity = B;
+			//viscosity=2.5*pow(10.,17);
+		}
+
+		else{
+			viscosity=(1.-D)*B/(2.*pow(eps_eff,(n-1.)/n));
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+void  Matice::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff){/*{{{*/
+
+	/*output: */
+	IssmDouble dmudB;
+
+	/*Intermediary: */
+	IssmDouble D=0.,n;
+
+	/*Get B and n*/
+	n=GetN(); _assert_(n>0.);
+	if(this->isdamaged){
+		D=GetD();
+		_assert_(D>=0. && D<1.);
+	}
+
+	if(n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) dmudB=B/2: */
+		dmudB=(1.-D)/2.;
+	}
+	else{
+		if(eps_eff==0.) dmudB = 0.;
+		else            dmudB = (1.-D)/(2.*pow(eps_eff,(n-1.)/n));
+	}
+
+	/*Return: */
+	*pdmudB=dmudB;
+}
+/*}}}*/
+void  Matice::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff){/*{{{*/
+
+	/*output: */
+	IssmDouble dmudD;
+
+	/*Intermediary: */
+	IssmDouble n,B;
+
+	/*Get B and n*/
+	n=GetN(); _assert_(n>0.);
+	B=GetBbar();
+	_assert_(this->isdamaged);
+
+	if(n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) dmudB=B/2: */
+		dmudD=-B/2.;
+	}
+	else{
+		if(eps_eff==0.) dmudD = 0.;
+		else            dmudD = -B/(2.*pow(eps_eff,(n-1.)/n));
+	}
+
+	/*Return: */
+	*pdmudD=dmudD;
+}
+/*}}}*/
+void  Matice::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+								(1-D) B
+	  viscosity= -------------------------
+						  2 eps_eff ^[(n-1)/n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , eps_eff is the effective strain rate
+	  and n the flow law exponent.
+
+	  If eps_eff = 0 , it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*Intermediary: */
+	IssmDouble B,D=0.,n;
+
+	/*Get B and n*/
+	B=GetBbar(); _assert_(B>0.);
+	n=GetN();    _assert_(n>0.);
+	if(this->isdamaged){
+		D=GetDbar();
+		_assert_(D>=0. && D<1.);
+	}
+
+	if (n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) viscosity=B/2: */
+		viscosity=(1.-D)*B/2.;
+	}
+	else{
+
+		/*if no strain rate, return maximum viscosity*/
+		if(eps_eff==0.){
+			viscosity = 1.e+14/2.;
+			//viscosity=2.5*pow(10.,17);
+		}
+
+		else{
+			viscosity=(1.-D)*B/(2.*pow(eps_eff,(n-1.)/n));
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
+	 *
+	 *  										                (1-D)
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble D=0.,n;
+
+	/*Get D and n*/
+	if(this->isdamaged){
+		D=GetDbar(); /* GetD()? */
+		_assert_(D>=0. && D<1.);
+	}
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=(1-D)/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow(10.,17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=(1-D)/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow(10.,17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(D>=0 && D<1);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
+	/*Return viscosity derivative for control method d(mu)/dD: 
+	 *
+	 *  										               B 
+	 * dviscosity= - -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=- 2.25*pow(10.,17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=- B/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=- 4.5*pow(10.,17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement<0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+		mu_prime=0.5*pow(10.,14);
+	}
+	else{
+
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		exz=epsilon[3];
+		eyz=epsilon[4];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
+
+		GetViscosity(&mu,sqrt(eff2));
+		n=GetN();
+		mu_prime=(1.-n)/(2.*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+		mu_prime=0.5*pow(10.,14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy ;
+
+		GetViscosityBar(&mu,sqrt(eff2));
+		n=GetN();
+		mu_prime=(1.-n)/(2.*n)*mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+void  Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+
+}
+/*}}}*/
+void  Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+
+}
+/*}}}*/
+void  Matice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Matice::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Matice::InputUpdateFromConstant(int constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Matice::InputUpdateFromConstant(bool constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matice.h	(revision 18231)
@@ -0,0 +1,75 @@
+/*!\file Matice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATICE_H_
+#define MATICE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+#include "../Hook.h"
+class IoModel;
+class Elements;
+class Element;
+class Loads;
+class Nodes;
+class Vertices;
+class Materials;
+class Parameters;
+/*}}}*/
+
+class Matice: public Material{
+
+	private: 
+		int      mid;
+		bool     isdamaged;
+		Hook    *helement;
+		Element *element;
+
+	public:
+		/*Matice constructors, destructors: {{{*/
+		Matice();
+		Matice(int mid,int i, IoModel* iomodel);
+		~Matice();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{*/
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   Configure(Elements* elements);
+		Material*  copy2(Element* element);
+		void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
+		void       GetViscosityDComplement(IssmDouble*, IssmDouble*);
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
+		IssmDouble GetAbar();
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetD();
+		IssmDouble GetDbar();
+		IssmDouble GetN();
+		bool       IsDamage();
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.cpp	(revision 18231)
@@ -0,0 +1,402 @@
+/*!\file Matpar.c
+ * \brief: implementation of the Matpar object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*Matpar constructors and destructor*/
+Matpar::Matpar(){/*{{{*/
+	return;
+}
+/*}}}*/
+Matpar::Matpar(int matpar_mid, IoModel* iomodel){/*{{{*/
+
+	bool isefficientlayer;
+	int  hydrology_model,smb_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	iomodel->Constant(&smb_model,SurfaceforcingsEnum);
+
+	this->mid = matpar_mid;
+	iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&this->rho_water,MaterialsRhoSeawaterEnum);
+	iomodel->Constant(&this->rho_freshwater,MaterialsRhoFreshwaterEnum);
+	iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
+	iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
+	iomodel->Constant(&this->temperateiceconductivity,MaterialsTemperateiceconductivityEnum);
+	iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
+	iomodel->Constant(&this->beta,MaterialsBetaEnum);
+	iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
+	iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
+	iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
+	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
+	iomodel->Constant(&this->g,ConstantsGEnum);
+
+	switch(smb_model){
+		case SMBEnum:
+			/*Nothing to add*/
+			break;
+		case SMBpddEnum:
+			iomodel->Constant(&this->desfac,SurfaceforcingsDesfacEnum);
+			iomodel->Constant(&this->s0p,SurfaceforcingsS0pEnum);
+			break;
+		case SMBgradientsEnum:
+			/*Nothing to add*/
+			break;
+		case SMBhenningEnum:
+			/*Nothing to add*/
+			break;
+		case SMBcomponentsEnum:
+			/*Nothing to add*/
+			break;
+		case SMBmeltcomponentsEnum:
+			/*Nothing to add*/
+			break;
+		default:
+			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+	if(hydrology_model==HydrologydcEnum){
+		iomodel->Constant(&this->sediment_compressibility,HydrologydcSedimentCompressibilityEnum);
+		iomodel->Constant(&this->sediment_porosity,HydrologydcSedimentPorosityEnum);
+		iomodel->Constant(&this->sediment_thickness,HydrologydcSedimentThicknessEnum);
+		iomodel->Constant(&this->water_compressibility,HydrologydcWaterCompressibilityEnum);
+		iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+		if(isefficientlayer){
+				iomodel->Constant(&this->epl_compressibility,HydrologydcEplCompressibilityEnum);
+				iomodel->Constant(&this->epl_porosity,HydrologydcEplPorosityEnum);
+				iomodel->Constant(&this->epl_init_thickness,HydrologydcEplInitialThicknessEnum);
+				iomodel->Constant(&this->epl_max_thickness,HydrologydcEplMaxThicknessEnum);
+				iomodel->Constant(&this->epl_conductivity,HydrologydcEplConductivityEnum);
+		}
+	}
+	else if(hydrology_model==HydrologyshreveEnum){
+		/*Nothing to add*/
+	}
+	else{
+		_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
+	}
+
+	/*gia: */
+	iomodel->Constant(&this->lithosphere_shear_modulus,MaterialsLithosphereShearModulusEnum);
+	iomodel->Constant(&this->lithosphere_density,MaterialsLithosphereDensityEnum);
+	iomodel->Constant(&this->mantle_shear_modulus,MaterialsMantleShearModulusEnum);
+	iomodel->Constant(&this->mantle_density,MaterialsMantleDensityEnum);
+}
+/*}}}*/
+Matpar::~Matpar(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Matpar::Echo(void){/*{{{*/
+
+	_printf_("Matpar:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   rho_ice: " << rho_ice << "\n");
+	_printf_("   rho_water: " << rho_water << "\n");
+	_printf_("   rho_freshwater: " << rho_freshwater << "\n");
+	_printf_("   mu_water: " << mu_water << "\n");
+	_printf_("   heatcapacity: " << heatcapacity << "\n");
+	_printf_("   thermalconductivity: " << thermalconductivity << "\n");
+	_printf_("   temperateiceconductivity: " << temperateiceconductivity << "\n");
+	_printf_("   latentheat: " << latentheat << "\n");
+	_printf_("   beta: " << beta << "\n");
+	_printf_("   meltingpoint: " << meltingpoint << "\n");
+	_printf_("   referencetemperature: " << referencetemperature << "\n");
+	_printf_("   mixed_layer_capacity: " << mixed_layer_capacity << "\n");
+	_printf_("   thermal_exchange_velocity: " << thermal_exchange_velocity << "\n");
+	_printf_("   g: " << g << "\n");
+	_printf_("   desfac: " << desfac << "\n");
+	_printf_("   s0p: " << s0p << "\n");
+	return;
+}
+/*}}}*/
+void Matpar::DeepEcho(void){/*{{{*/
+
+	this->Echo();
+}		
+/*}}}*/
+int    Matpar::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+int Matpar::ObjectEnum(void){/*{{{*/
+
+	return MatparEnum;
+
+}
+/*}}}*/
+Object* Matpar::copy() {/*{{{*/
+	return new Matpar(*this); 
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+void   Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void   Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void   Matpar::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
+
+	switch(name){
+		case MaterialsRhoIceEnum:
+			this->rho_ice=constant;
+			break;
+		case MaterialsRhoSeawaterEnum:
+			this->rho_water=constant;
+			break;
+		case MaterialsRhoFreshwaterEnum:
+			this->rho_freshwater=constant;
+			break;
+		case MaterialsMuWaterEnum:
+			this->mu_water=constant;
+			break;
+		case MaterialsHeatcapacityEnum:
+			this->heatcapacity=constant;
+			break;
+	  	case MaterialsThermalconductivityEnum:
+			this->thermalconductivity=constant;
+			break;
+	  	case MaterialsTemperateiceconductivityEnum:
+			this->temperateiceconductivity=constant;
+			break;
+		case  MaterialsLatentheatEnum:
+			this->latentheat=constant;
+			break;
+		case  MaterialsBetaEnum:
+			this->beta=constant;
+			break;
+		case  MaterialsMeltingpointEnum:
+			this->meltingpoint=constant;
+			break;
+		case  ConstantsReferencetemperatureEnum:
+			this->referencetemperature=constant;
+			break;
+		case  MaterialsMixedLayerCapacityEnum:
+			this->mixed_layer_capacity=constant;
+			break;
+		case  MaterialsThermalExchangeVelocityEnum:
+			this->thermalconductivity=constant;
+			break;
+		case  ConstantsGEnum:
+			this->g=constant;
+			break;
+		case  SurfaceforcingsDesfacEnum:
+			this->desfac=constant;
+			break;
+		case SurfaceforcingsS0pEnum:
+			this->s0p=constant;
+			break;
+		default: 
+			break;
+	}
+
+}
+/*}}}*/
+void   Matpar::InputUpdateFromConstant(int constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void   Matpar::InputUpdateFromConstant(bool constant, int name){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Matpar management: */
+void  Matpar::Configure(Elements* elementsin){/*{{{*/
+
+	/*nothing done yet!*/
+
+}
+/*}}}*/
+IssmDouble Matpar::GetMaterialParameter(int enum_in){/*{{{*/
+
+	switch(enum_in){
+		case MaterialsRhoIceEnum:                    return this->rho_ice;
+		case MaterialsRhoSeawaterEnum:                  return this->rho_water;
+		case MaterialsRhoFreshwaterEnum:             return this->rho_freshwater;
+		case MaterialsMuWaterEnum:                   return this->mu_water;
+		case MaterialsHeatcapacityEnum:              return this->heatcapacity;
+		case MaterialsThermalconductivityEnum:       return this->thermalconductivity;
+		case MaterialsTemperateiceconductivityEnum:  return this->temperateiceconductivity;
+		case MaterialsLatentheatEnum:                return this->latentheat;
+		case MaterialsBetaEnum:                      return this->beta;
+		case MaterialsMeltingpointEnum:              return this->meltingpoint;
+		case ConstantsReferencetemperatureEnum:      return this->referencetemperature;
+		case MaterialsMixedLayerCapacityEnum:        return this->mixed_layer_capacity;
+		case MaterialsThermalExchangeVelocityEnum:   return this->thermal_exchange_velocity;
+		case HydrologydcSedimentPorosityEnum:        return this->sediment_porosity;
+		case HydrologydcSedimentThicknessEnum:       return this->sediment_thickness;
+		case HydrologydcSedimentCompressibilityEnum: return this->sediment_compressibility;
+		case HydrologydcEplPorosityEnum:             return this->epl_porosity;
+		case HydrologydcEplCompressibilityEnum:      return this->epl_compressibility;
+		case HydrologydcEplConductivityEnum:         return this->epl_conductivity;
+		case HydrologydcEplInitialThicknessEnum:     return this->epl_init_thickness;
+		case HydrologydcEplMaxThicknessEnum:         return this->epl_max_thickness;
+		case HydrologydcWaterCompressibilityEnum:    return this->water_compressibility;
+		case ConstantsGEnum:                         return this->g;
+		default: _error_("Enum "<<EnumToStringx(enum_in)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+IssmDouble Matpar::GetBeta(){/*{{{*/
+	return beta;
+}
+/*}}}*/
+IssmDouble Matpar::GetG(){/*{{{*/
+	return g;
+}
+/*}}}*/
+IssmDouble Matpar::GetMeltingPoint(){/*{{{*/
+	return meltingpoint;
+}
+/*}}}*/
+IssmDouble Matpar::GetRhoIce(){/*{{{*/
+
+	return rho_ice;
+}
+/*}}}*/
+IssmDouble Matpar::GetRhoWater(){/*{{{*/
+	return rho_water;
+}
+/*}}}*/
+IssmDouble Matpar::GetRhoFreshwater(){/*{{{*/
+	return rho_freshwater;
+}
+/*}}}*/
+IssmDouble Matpar::GetDesFac(){/*{{{*/
+	return desfac;
+}
+/*}}}*/
+IssmDouble Matpar::GetS0p(){/*{{{*/
+	return s0p;
+}
+/*}}}*/
+IssmDouble Matpar::TMeltingPoint(IssmDouble pressure){/*{{{*/
+	return meltingpoint-beta*pressure;
+}
+/*}}}*/
+IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
+	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
+}
+/*}}}*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	if (enthalpy<PureIceEnthalpy(pressure))
+		return thermalconductivity/heatcapacity;
+	else
+		return temperateiceconductivity/heatcapacity;
+}
+/*}}}*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
+
+	int         iv;
+	IssmDouble  lambda;                 // fraction of cold ice
+	IssmDouble  kappa,kappa_c,kappa_t;  //enthalpy conductivities
+	IssmDouble  Hc,Ht;
+	IssmDouble* PIE   = xNew<IssmDouble>(numvertices);
+	IssmDouble* dHpmp = xNew<IssmDouble>(numvertices);
+
+	for(iv=0; iv<numvertices; iv++){
+		PIE[iv]=PureIceEnthalpy(pressure[iv]);
+		dHpmp[iv]=enthalpy[iv]-PIE[iv];
+	}
+
+	bool allequalsign=true;
+	if(dHpmp[0]<0)
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]<0));
+	else
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]>=0));
+
+	if(allequalsign){
+		kappa=GetEnthalpyDiffusionParameter(enthalpy[0], pressure[0]);
+	}
+	else {
+		/* return harmonic mean of thermal conductivities, weighted by fraction of cold/temperate ice,
+		 cf Patankar 1980, pp44 */
+		kappa_c=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)-1.,0.);
+		kappa_t=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)+1.,0.);
+		Hc=0.; Ht=0.;
+		for(iv=0; iv<numvertices;iv++){
+			if(enthalpy[iv]<PIE[iv])
+			 Hc+=(PIE[iv]-enthalpy[iv]);
+			else
+			 Ht+=(enthalpy[iv]-PIE[iv]);
+		}
+		_assert_((Hc+Ht)>0.);
+		lambda = Hc/(Hc+Ht);
+		kappa  = 1./(lambda/kappa_c + (1.-lambda)/kappa_t);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(PIE);
+	xDelete<IssmDouble>(dHpmp);
+	return kappa;
+}
+/*}}}*/
+void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+
+	/*Ouput*/
+	IssmDouble temperature,waterfraction;
+
+	if(enthalpy<PureIceEnthalpy(pressure)){
+		temperature=referencetemperature+enthalpy/heatcapacity;
+		waterfraction=0.;
+	}
+	else{
+		temperature=TMeltingPoint(pressure);
+		waterfraction=(enthalpy-PureIceEnthalpy(pressure))/latentheat;
+	}
+
+	/*Assign output pointers:*/
+	*pwaterfraction=waterfraction;
+	*ptemperature=temperature;
+}
+/*}}}*/
+void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
+
+	/*Ouput*/
+	IssmDouble enthalpy;
+
+	if(temperature<TMeltingPoint(pressure)){
+		enthalpy=heatcapacity*(temperature-referencetemperature);
+	}
+	else{
+		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
+	}
+
+	/*Assign output pointers:*/
+	*penthalpy=enthalpy;
+}
+/*}}}*/
+IssmDouble Matpar::GetLithosphereShearModulus(){		 /*{{{*/
+	return lithosphere_shear_modulus;			 
+}		 
+/*}}}*/ 
+IssmDouble Matpar::GetLithosphereDensity(){		 /*{{{*/
+	return lithosphere_density;			 
+}		 
+/*}}}*/ 
+IssmDouble Matpar::GetMantleDensity(){		 /*{{{*/
+	return mantle_density;			 
+}		 
+/*}}}*/ 
+IssmDouble Matpar::GetMantleShearModulus(){		 /*{{{*/
+	return mantle_shear_modulus;			 
+}		 
+/*}}}*/ 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Materials/Matpar.h	(revision 18231)
@@ -0,0 +1,118 @@
+/*!\file Matpar.h
+ * \brief: header file for matpar object
+ */
+
+#ifndef _MATPAR_H_
+#define _MATPAR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matpar: public Material{
+
+	private: 
+		int	      mid;
+		IssmDouble  rho_ice; 
+		IssmDouble  rho_water;
+		IssmDouble  rho_freshwater;
+		IssmDouble  mu_water;
+		IssmDouble  heatcapacity;
+		IssmDouble  thermalconductivity;
+		IssmDouble  temperateiceconductivity;
+		IssmDouble  latentheat;
+		IssmDouble  beta;
+		IssmDouble  meltingpoint;
+		IssmDouble  referencetemperature;
+		IssmDouble  mixed_layer_capacity;
+		IssmDouble  thermal_exchange_velocity;
+		IssmDouble  g;
+		IssmDouble  desfac;
+		IssmDouble  s0p;
+
+		/*hydrology Dual Porous Continuum: */	 
+		IssmDouble  sediment_compressibility;
+		IssmDouble  sediment_porosity;	 
+		IssmDouble  sediment_thickness;
+		IssmDouble  water_compressibility;
+
+		IssmDouble  epl_compressibility;
+		IssmDouble  epl_porosity;
+		IssmDouble  epl_init_thickness;
+		IssmDouble  epl_max_thickness;
+		IssmDouble  epl_conductivity;	 
+
+		/*gia: */
+		IssmDouble lithosphere_shear_modulus;
+		IssmDouble lithosphere_density;
+		IssmDouble mantle_shear_modulus;
+		IssmDouble mantle_density;
+
+	public:
+		Matpar();
+		Matpar(int matpar_id, IoModel* iomodel);
+		~Matpar();
+
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void   InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void   InputUpdateFromMatrixDakota(IssmDouble* matrix,int nrows,int ncols, int name, int type);
+		void   InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void   InputUpdateFromConstant(IssmDouble constant, int name);
+		void   InputUpdateFromConstant(int constant, int name);
+		void   InputUpdateFromConstant(bool constant, int name);
+		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		Material*  copy2(Element* element){_error_("not implemented");};
+		void       Configure(Elements* elements);
+		void       GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		IssmDouble GetA(){_error_("not supported");};
+		IssmDouble GetAbar(){_error_("not supported");};
+		IssmDouble GetB(){_error_("not supported");};
+		IssmDouble GetBbar(){_error_("not supported");};
+		IssmDouble GetN(){_error_("not supported");};
+		IssmDouble GetD(){_error_("not supported");};
+		IssmDouble GetDbar(){_error_("not supported");};
+		bool       IsDamage(){_error_("not supported");};
+		/*}}}*/
+		/*Numerics: {{{*/
+		IssmDouble GetG();
+		IssmDouble GetRhoIce();
+		IssmDouble GetRhoWater();
+		IssmDouble GetRhoFreshwater();
+		IssmDouble GetBeta();
+		IssmDouble GetMeltingPoint();
+		IssmDouble TMeltingPoint(IssmDouble pressure);
+		IssmDouble PureIceEnthalpy(IssmDouble pressure);
+		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
+		IssmDouble GetLithosphereShearModulus();
+		IssmDouble GetLithosphereDensity();
+		IssmDouble GetMantleShearModulus();
+		IssmDouble GetMantleDensity();
+		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
+		IssmDouble GetDesFac();
+		IssmDouble GetS0p(); 
+		IssmDouble GetMaterialParameter(int in_enum); 
+		/*}}}*/
+
+};
+
+#endif  /* _MATPAR_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Misfit.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Misfit.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Misfit.h	(revision 18231)
@@ -0,0 +1,149 @@
+/*!\file Misfit.h
+ * \brief: header file for Misfit object
+ */
+
+#ifndef _MISFIT_H_
+#define _MISFIT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+/*}}}*/
+
+class Misfit: public Object, public Definition{
+
+	public: 
+
+		char*       name;
+		int         model_enum;
+		int         observation_enum;
+		int         weights_enum;
+		char*       timeinterpolation;
+		
+		IssmDouble  misfit; //value carried over in time.
+		int         lock; // if lock is on, we just return the value stored in "misfit".  this is used so we don't compute misfit past the final_time
+		
+		/*Misfit constructors, destructors :*/
+		Misfit(){/*{{{*/
+
+			this->name = NULL;
+			this->model_enum = UNDEF;
+			this->observation_enum = UNDEF;
+			this->weights_enum = UNDEF;
+			this->timeinterpolation=NULL;
+			this->misfit=0;
+			this->lock=0;
+
+		}
+		/*}}}*/
+		Misfit(char* in_name, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_weights_enum){/*{{{*/
+
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->timeinterpolation   = xNew<char>(strlen(in_timeinterpolation)+1);
+			xMemCpy<char>(this->timeinterpolation,in_timeinterpolation,strlen(in_timeinterpolation)+1);
+
+			this->model_enum=in_model_enum;
+			this->observation_enum=in_observation_enum;
+			this->weights_enum=in_weights_enum;
+			
+			this->misfit=0;
+			this->lock=0;
+		}
+		/*}}}*/
+		~Misfit(){/*{{{*/
+			if(this->name)xDelete(this->name);
+			if(this->timeinterpolation)xDelete(this->timeinterpolation);
+			this->misfit=0;
+			this->lock=0;
+		}
+		/*}}}*/
+		/*Object virtual function resolutoin: */
+		void Echo(void){/*{{{*/
+			_printf_(" Misfit: " << name << "\n");
+			_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
+			_printf_("    observation_enum: " << observation_enum << " " << EnumToStringx(observation_enum) << "\n");
+			_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
+			_printf_("    timeinterpolation: " << timeinterpolation << "\n");
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int Id(void){/*{{{*/
+			return -1;
+		}
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+			return MisfitEnum;
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			return new Misfit(this->name,this->model_enum,this->observation_enum,this->timeinterpolation,this->weights_enum);
+		}
+		/*}}}*/
+		/*Definition virtual function resolutoin: */
+		char* Name(){/*{{{*/
+
+			char* name2=xNew<char>(strlen(this->name)+1);
+			xMemCpy(name2,this->name,strlen(this->name)+1);
+
+			return name2;
+		}
+		/*}}}*/
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
+
+			 int i;
+			 IssmDouble misfit_t=0.;
+			 IssmDouble all_misfit_t=0.;
+			 IssmDouble dt;
+			 IssmDouble area_t=0.;
+			 IssmDouble all_area_t;
+			 IssmDouble time,starttime,finaltime;
+
+			 femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+			 femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+			 femmodel->parameters->FindParam(&time,TimeEnum);
+
+			 /*If we are locked, return time average: */
+			 if(this->lock)return misfit/(time-starttime);
+
+
+			 for(i=0;i<femmodel->elements->Size();i++){
+				 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+				 misfit_t+=element->Misfit(model_enum,observation_enum,weights_enum);
+				 area_t+=element->MisfitArea(weights_enum);
+			 }
+
+			 ISSM_MPI_Allreduce ( (void*)&misfit_t,(void*)&all_misfit_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+			 ISSM_MPI_Allreduce ( (void*)&area_t,(void*)&all_area_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+			 area_t=all_area_t;
+			 misfit_t=all_misfit_t;
+			 
+			 /*Divide by surface area if not nill!: */
+			 if (area_t!=0) misfit_t=misfit_t/area_t;
+
+			 /*Recover delta_t: */
+			 femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+			 /*Add this time's contribution to curent misfit: */
+			 misfit+=dt*misfit_t;
+
+			 /*Do we lock? i.e. are we at final_time? :*/
+			 if(time==finaltime)this->lock=1;
+
+			 /*What we return is the value of misfit / time: */
+			 return misfit/(time-starttime);
+		 }
+			/*}}}*/
+};
+
+#endif  /* _MISFIT_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.cpp	(revision 18231)
@@ -0,0 +1,865 @@
+/*!\file Node.c
+ * \brief: implementation of the Node object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "shared/shared.h"
+#include "modules/ModelProcessorx/ModelProcessorx.h"
+#include "../analyses/analyses.h"
+/*}}}*/
+
+/*Node constructors and destructors:*/
+Node::Node(){/*{{{*/
+	this->approximation=0;
+}
+/*}}}*/
+Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int in_approximation){/*{{{*/
+
+	/*Intermediary*/
+	int k,l;
+	int *doftypes = NULL;
+
+	/*id: */
+	this->id            = node_id;
+	this->sid           = node_sid;
+	this->lid           = node_lid;
+	this->analysis_enum = analysis_enum;
+
+	/*Initialize coord_system: Identity matrix by default*/
+	for(k=0;k<3;k++) for(l=0;l<3;l++) this->coord_system[k][l]=0.0;
+	for(k=0;k<3;k++) this->coord_system[k][k]=1.0;
+
+	/*indexing:*/
+	this->indexingupdate = true;
+
+	Analysis* analysis = EnumToAnalysis(analysis_enum);
+	int numdofs        = analysis->DofsPerNode(&doftypes,iomodel->domaintype,in_approximation);
+	indexing.Init(numdofs,doftypes);
+	xDelete<int>(doftypes);
+	delete analysis;
+
+	if(analysis_enum==StressbalanceAnalysisEnum)
+	 this->approximation=in_approximation;
+	else
+	 this->approximation=0;
+
+	/*Stressbalance Horiz*/
+	if(analysis_enum==StressbalanceAnalysisEnum){
+
+		/*Coordinate system provided, convert to coord_system matrix*/
+		_assert_(iomodel->Data(StressbalanceReferentialEnum)); 
+		XZvectorsToCoordinateSystem(&this->coord_system[0][0],&iomodel->Data(StressbalanceReferentialEnum)[io_index*6]);
+		_assert_(sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]) >1.e-4);
+
+		if(iomodel->domaintype!=Domain2DhorizontalEnum){
+			/*We have a  3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonbaseEnum)); 
+			_assert_(iomodel->Data(FlowequationVertexEquationEnum));
+			if(in_approximation==SSAApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[io_index])){
+				this->Deactivate();
+			}
+			if(in_approximation==L1L2ApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[io_index])){
+				this->Deactivate();
+			}
+			if(in_approximation==SSAHOApproximationEnum && reCast<int>(iomodel->Data(FlowequationBorderSSAEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[io_index])){
+					this->Deactivate();
+				}
+			}
+			if(in_approximation==SSAFSApproximationEnum && reCast<int>(iomodel->Data(FlowequationBorderSSAEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbaseEnum)[io_index])){
+					for(k=0;k<=1;k++) this->FreezeDof(k);
+				}
+			}
+		}
+		/*spc all nodes on SIA*/
+		if(in_approximation==SIAApproximationEnum){
+			this->Deactivate();
+		}
+	}
+
+	/*2d solutions in 3d, we need to constrain all the nodes that are not on base*/
+	if(
+				analysis_enum==FreeSurfaceBaseAnalysisEnum || 
+				analysis_enum==MasstransportAnalysisEnum || 
+				analysis_enum==MeltingAnalysisEnum || 
+				analysis_enum==L2ProjectionBaseAnalysisEnum || 
+				analysis_enum==BalancethicknessAnalysisEnum ||
+				analysis_enum==HydrologyDCInefficientAnalysisEnum ||
+				analysis_enum==DamageEvolutionAnalysisEnum || 
+				analysis_enum==HydrologyDCEfficientAnalysisEnum ||
+				analysis_enum==LevelsetAnalysisEnum ||
+				analysis_enum==ExtrapolationAnalysisEnum
+				){
+		if(iomodel->domaintype!=Domain2DhorizontalEnum){
+			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonbaseEnum));
+			if(!(reCast<bool>(iomodel->Data(MeshVertexonbaseEnum)[io_index]))){
+				this->Deactivate();
+			}
+		}
+	}
+	if(
+				analysis_enum==FreeSurfaceTopAnalysisEnum
+				){
+		if(iomodel->domaintype!=Domain2DhorizontalEnum){
+			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonsurfaceEnum));
+			if(!(reCast<bool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index]))){
+				this->Deactivate();
+			}
+		}
+	}
+
+}
+/*}}}*/
+Node::~Node(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Node::Echo(void){/*{{{*/
+
+	_printf_("Node:\n");
+	_printf_("   id : " << id << "\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   analysis_enum: " << EnumToStringx(analysis_enum) << "\n");
+	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
+	_printf_("   indexingupdate: " << indexingupdate << "\n");
+	indexing.Echo();
+
+}
+/*}}}*/
+void Node::DeepEcho(void){/*{{{*/
+
+	_printf_("Node:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   analysis_enum: " << EnumToStringx(analysis_enum) << "\n");
+	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
+	_printf_("   indexingupdate: " << indexingupdate << "\n");
+	indexing.DeepEcho();
+
+}
+/*}}}*/
+int  Node::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int  Node::ObjectEnum(void){/*{{{*/
+
+	return NodeEnum;
+
+}
+/*}}}*/
+
+/*Node management:*/
+int  Node::GetDof(int dofindex,int setenum){/*{{{*/
+
+	_assert_(!this->indexingupdate);
+	if(setenum==GsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.gsize);
+		return indexing.gdoflist[dofindex];
+	}
+	else if(setenum==FsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.fsize);
+		return indexing.fdoflist[dofindex];
+	}
+	else if(setenum==SsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.ssize);
+		return indexing.sdoflist[dofindex];
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+} /*}}}*/
+void Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){/*{{{*/
+	int i;
+	int count=0;
+	int count2=0;
+
+	_assert_(!this->indexingupdate);
+
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		if(setenum==FsetEnum)for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		if(setenum==SsetEnum)for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=indexing.gdoflist[i];
+						count++;
+					}
+				}
+				_assert_(count); //at least one dof should be the approximation requested
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		}
+		else if(setenum==FsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.fdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.sdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+void Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){/*{{{*/
+	int i;
+	int count=0;
+	int count2=0;
+
+	_assert_(!this->indexingupdate);
+
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		else if(setenum==FsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.f_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.s_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=count;
+						count++;
+					}
+				}
+				_assert_(count);
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		}
+		else if(setenum==FsetEnum){
+
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.f_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.s_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+int  Node::Sid(void){/*{{{*/
+	return sid; 
+}
+/*}}}*/
+int  Node::Lid(void){/*{{{*/
+	return lid; 
+}
+/*}}}*/
+void Node::GetCoordinateSystem(IssmDouble* coord_system_out){/*{{{*/
+
+	/*Copy coord_system*/
+	for(int k=0;k<3;k++) for(int l=0;l<3;l++) coord_system_out[3*k+l]=this->coord_system[k][l];
+
+}
+/*}}}*/
+bool Node::InAnalysis(int in_analysis_enum){/*{{{*/
+	if (in_analysis_enum==this->analysis_enum) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Node numerics:*/
+void Node::ApplyConstraint(int dof,IssmDouble value){/*{{{*/
+
+	/*Dof should be added in the s set, describing which 
+	 * dofs are constrained to a certain value (dirichlet boundary condition*/
+	DofInSSet(dof);
+	this->indexing.svalues[dof]=value;
+}
+/*}}}*/
+bool Node::RequiresDofReindexing(void){/*{{{*/
+
+	return this->indexingupdate;
+
+}
+/*}}}*/
+void Node::ReindexingDone(void){/*{{{*/
+
+	this->indexingupdate = false;
+
+}
+/*}}}*/
+void Node::RelaxConstraint(int dof){/*{{{*/
+
+	/*Dof should be added to the f-set, and taken out of the s-set:*/
+	DofInFSet(dof);
+	this->indexing.svalues[dof]=0.;
+}
+/*}}}*/
+void Node::CreateNodalConstraints(Vector<IssmDouble>* ys){/*{{{*/
+
+	int i;
+	IssmDouble* values=NULL;
+	int count;
+
+	/*Recover values for s set and plug them in constraints vector: */
+	if(this->indexing.ssize){
+		values=xNew<IssmDouble>(this->indexing.ssize);
+		count=0;
+		for(i=0;i<this->indexing.gsize;i++){
+			if(this->indexing.s_set[i]){
+				values[count]=this->indexing.svalues[i];
+				_assert_(!xIsNan<IssmDouble>(values[count]));
+				count++;
+			}
+		}
+
+		/*Add values into constraint vector: */
+		ys->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+
+}
+/*}}}*/
+void Node::DofInSSet(int dof){/*{{{*/
+
+	/*Put dof for this node into the s set (ie, this dof will be constrained 
+	 * to a fixed value during computations. */
+	_assert_(dof<this->indexing.gsize);
+
+	if(this->indexing.f_set[dof] == 1){
+		this->indexingupdate = true;
+		this->indexing.f_set[dof]=0; //n splits into f (for which we solve) and s (single point constraints)
+		this->indexing.s_set[dof]=1;
+	}
+}
+/*}}}*/
+void Node::DofInFSet(int dof){/*{{{*/
+
+	/*Put dof for this node into the f set (ie, this dof will NOT be constrained 
+	 * to a fixed value during computations. */
+	_assert_(dof<this->indexing.gsize);
+
+	if(this->indexing.f_set[dof] == 0){
+		this->indexingupdate = true;
+		this->indexing.f_set[dof]=1; 
+		this->indexing.s_set[dof]=0;
+	}
+}
+/*}}}*/
+void Node::FreezeDof(int dof){/*{{{*/
+
+	DofInSSet(dof); //with 0 displacement for this dof.
+
+}
+/*}}}*/
+void Node::Deactivate(void){/*{{{*/
+
+	if(IsActive()){
+		this->indexingupdate = true;
+		indexing.Deactivate();
+	}
+
+}
+/*}}}*/
+void Node::Activate(void){/*{{{*/
+
+	if(!IsActive()){
+		this->indexingupdate = true;
+		indexing.Activate();
+	}
+
+}
+/*}}}*/
+bool Node::IsActive(void){/*{{{*/
+
+	return indexing.active;
+
+}
+/*}}}*/
+int  Node::GetApproximation(){/*{{{*/
+
+	return approximation;
+}
+/*}}}*/
+int  Node::GetNumberOfDofs(int approximation_enum,int setenum){/*{{{*/
+
+	/*Get number of degrees of freedom in a node, for a certain set (g,f or s-set)
+	 *and for a certain approximation type: */
+
+	int i;
+	int numdofs=0;
+
+	if(approximation_enum==NoneApproximationEnum){
+		if      (setenum==GsetEnum) numdofs=this->indexing.gsize;
+		else if (setenum==FsetEnum) numdofs=this->indexing.fsize;
+		else if (setenum==SsetEnum) numdofs=this->indexing.ssize;
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+		if(setenum==GsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(this->indexing.doftype[i]==approximation_enum) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.gsize;
+		}
+		else if (setenum==FsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.f_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.fsize;
+		}
+		else if (setenum==SsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.s_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.ssize;
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	return numdofs;
+}
+/*}}}*/
+int  Node::IsClone(){/*{{{*/
+
+	return indexing.clone;
+
+}
+/*}}}*/
+void Node::VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){/*{{{*/
+
+	IssmDouble *values  = NULL;
+	int        *indices = NULL;
+	int         count   = 0;
+	int         i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+			indices=xNew<int>(this->indexing.fsize);
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.fdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.fsize,indices,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			indices=xNew<int>(this->indexing.ssize);
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.sdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.ssize,indices,values,INS_VAL);
+		}
+	}
+	else _error_("VecMerge can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(indices);
+}
+/*}}}*/
+void Node::VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setenum){/*{{{*/
+
+	IssmDouble* values=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.fsize,this->indexing.fdoflist,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+		}
+	}
+	else _error_("VecReduce can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+
+/* indexing routines:*/
+void Node::DistributeDofs(int* pdofcount,int setenum){/*{{{*/
+
+	int i;
+	int dofcount;
+
+	dofcount=*pdofcount;
+
+	/*Initialize: */
+	if(setenum==FsetEnum) this->indexing.InitSet(setenum);
+	if(setenum==SsetEnum) this->indexing.InitSet(setenum);
+
+	/*For clone nodfs, don't distribute dofs, we will get them from another cpu in UpdateCloneDofs!*/
+	if(indexing.clone){
+		return;
+	}
+
+	/*This node should distribute dofs for setenum set (eg, f_set or s_set), go ahead: */
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++){
+			indexing.gdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.gsize;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++){
+			indexing.fdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.fsize;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++){
+			indexing.sdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.ssize;
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+}
+/*}}}*/
+void Node::OffsetDofs(int dofcount,int setenum){/*{{{*/
+
+	int i;
+
+	if(indexing.clone){
+		/*This node is a clone, don't off_set the dofs!: */
+		return;
+	}
+
+	/*This node should off_set the dofs, go ahead: */
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++) indexing.gdoflist[i]+=dofcount;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++) indexing.fdoflist[i]+=dofcount;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++) indexing.sdoflist[i]+=dofcount;
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+}
+/*}}}*/
+void Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){/*{{{*/
+
+	int j;
+
+	/*Are we a clone? : */
+	if(indexing.clone) return;
+
+	/*Ok, we are not a clone, just plug our dofs into truedofs: */
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) truedofs[ncols*sid+j]=indexing.gdoflist[j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) truedofs[ncols*sid+j]=indexing.fdoflist[j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) truedofs[ncols*sid+j]=indexing.sdoflist[j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+void Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){/*{{{*/
+
+	int j;
+
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(!indexing.clone)return;
+
+	/*Ok, we are a clone node, but we did not create the dofs for this node.
+	 *Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+void Node::SetClone(int* minranks){/*{{{*/
+
+	int my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if (minranks[sid]==my_rank){
+		indexing.clone=false;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same node, 
+		therefore, I am a clone*/
+		indexing.clone=true;	
+	}
+}
+/*}}}*/
+
+/*Methods inherent to Node: */
+int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation){ /*{{{*/
+
+	int  i,j,count,numdof,numgdof;
+	int* ndof_list=NULL;
+	int* ngdof_list_cumulative=NULL;
+	int *doflist = NULL;
+
+	if(numnodes){
+		/*allocate: */
+		ndof_list=xNew<int>(numnodes);
+		ngdof_list_cumulative=xNew<int>(numnodes);
+
+		/*Get number of dofs per node, and total for this given set*/
+		numdof=0;
+		numgdof=0;
+		for(i=0;i<numnodes;i++){
+
+			/*Cumulative list= number of dofs before node i*/
+			ngdof_list_cumulative[i]=numgdof;
+
+			/*Number of dofs for node i for given set and for the g set*/
+			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
+			numgdof    +=nodes[i]->GetNumberOfDofs(approximation,GsetEnum);
+			numdof     +=ndof_list[i];
+		}
+
+		if(numdof){
+			/*Allocate: */
+			doflist=xNew<int>(numdof);
+
+			/*Populate: */
+			count=0;
+			for(i=0;i<numnodes;i++){
+				nodes[i]->GetLocalDofList(&doflist[count],approximation,setenum);
+				count+=ndof_list[i];
+			}
+
+			/*We now have something like: [0 1 0 2 1 2]. Offset by gsize, to get something like: [0 1 2 4 6 7]:*/
+			count=0;
+			for(i=0;i<numnodes;i++){
+				for(j=0;j<ndof_list[i];j++){
+					doflist[count+j]+=ngdof_list_cumulative[i];
+				}
+				count+=ndof_list[i];
+			}
+		}
+		else doflist=NULL;
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(ndof_list);
+	xDelete<int>(ngdof_list_cumulative);
+
+	/*CLean-up and return*/
+	return doflist;
+}
+/*}}}*/
+int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation){/*{{{*/
+
+	int  i,numdof,count;
+	int* ndof_list=NULL;
+	int *doflist = NULL;
+
+	if(numnodes){
+
+		/*Allocate:*/
+		ndof_list=xNew<int>(numnodes);
+
+		/*First, figure out size of doflist: */
+		numdof=0;
+		for(i=0;i<numnodes;i++){
+			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
+			numdof+=ndof_list[i];
+		}
+
+		if(numdof){
+			/*Allocate: */
+			doflist=xNew<int>(numdof);
+
+			/*Populate: */
+			count=0;
+			for(i=0;i<numnodes;i++){
+				nodes[i]->GetDofList(&doflist[count],approximation,setenum);
+				count+=ndof_list[i];
+			}
+		}
+		else doflist=NULL;
+	}
+	/*Free ressources:*/
+	xDelete<int>(ndof_list);
+
+	return doflist;
+}
+/*}}}*/
+int GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation){/*{{{*/
+
+	/*output: */
+	int numberofdofs=0;
+
+	for(int i=0;i<numnodes;i++){
+		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation,setenum);
+	}
+
+	return numberofdofs;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Node.h	(revision 18231)
@@ -0,0 +1,92 @@
+/*!\file Node.h
+ * \brief: header file for node object
+ */
+
+#ifndef _NODE_H_
+#define _NODE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+#include "./DofIndexing.h"
+#include "./Update.h"
+class  Inputs;
+class  Hook;
+class  IoModel;
+class  DataSet;
+class  Vertices;
+template <class doubletype> class  Vector;
+template <class doubletype> class  Matrix;
+class ElementVector;
+class ElementMatrix;
+/*}}}*/
+
+class Node: public Object{
+
+	private:
+		int approximation; //For ice flow models, we need to know what ice flow approximation is employed on this node
+
+	public: 
+
+		int id;    // unique arbitrary id.
+		int sid;   // "serial" id (rank of this node if the dataset was serial on 1 cpu)
+		int lid;   // "local"  id (rank of this node in current partition)
+
+		bool         indexingupdate;
+		DofIndexing  indexing;
+		int          analysis_enum;
+		IssmDouble   coord_system[3][3];
+
+		/*Node constructors, destructors*/
+		Node();
+		Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int approximation_in);
+		~Node();
+
+		/*Object virtual functions definitions:*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy(){_error_("Not implemented yet (similar to Elements)"); };
+
+		/*Node numerical routines*/
+		void  CreateNodalConstraints(Vector<IssmDouble>* ys);
+		void  SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
+		int   Sid(void); 
+		int   Lid(void); 
+		void  GetCoordinateSystem(IssmDouble* coord_system_out);
+		bool  InAnalysis(int analysis_enum);
+		int   GetApproximation();
+		int   GetNumberOfDofs(int approximation_enum,int setenum);
+		int   IsClone();
+		void  ApplyConstraint(int dof,IssmDouble value);
+		void  RelaxConstraint(int dof);
+		void  DofInSSet(int dof);
+		void  DofInFSet(int dof);
+		int   GetDof(int dofindex,int setenum);
+		void  GetDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void  GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void  FreezeDof(int dof);
+		bool  IsActive(void);
+		void  Activate(void);
+		void  Deactivate(void);
+		void  ReindexingDone(void);
+		bool  RequiresDofReindexing(void);
+		int   IsFloating();
+		int   IsGrounded();
+		void  VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum);
+		void  VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setnum);
+		void  DistributeDofs(int* pdofcount,int setenum);
+		void  OffsetDofs(int dofcount,int setenum);
+		void  ShowTrueDofs(int* truerows,int ncols,int setenum);
+		void  UpdateCloneDofs(int* alltruerows,int ncols,int setenum);
+		void  SetClone(int* minranks);
+};
+
+/*Methods inherent to Node: */
+int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation);
+int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation);
+int  GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation);
+
+#endif  /* _NODE_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.cpp	(revision 18231)
@@ -0,0 +1,358 @@
+/*
+ * \file Nodes.cpp
+ * \brief: Implementation of Nodes class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Nodes.h"
+#include "../shared/shared.h"
+#include "./Node.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Nodes::Nodes(){/*{{{*/
+	enum_type=NodesEnum;
+	return;
+}
+/*}}}*/
+Nodes::~Nodes(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Numerics*/
+void  Nodes::DistributeDofs(int analysis_type,int setenum){/*{{{*/
+
+	int  i;
+	int  dofcount=0;
+	int  maxdofspernode=0;
+	int* alldofcount=NULL;
+	int* truedofs=NULL;
+	int* alltruedofs=NULL;
+	int  numnodes=0;
+
+	/*recover my_rank:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
+	/*some check: */
+	_assert_(setenum==GsetEnum || setenum==FsetEnum || setenum==SsetEnum);
+
+	/*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if(node->InAnalysis(analysis_type)){
+			node->DistributeDofs(&dofcount,setenum);
+		}
+	}
+
+	/* Now every object has distributed dofs, but locally, and with a dof count starting from 
+	 * 0. This means the dofs between all the cpus are not unique. We now offset the dofs of eache
+	 * cpus by the total last dofs of the previus cpu, starting from 0.
+	 * First: get number of dofs for each cpu*/
+	alldofcount=xNew<int>(num_procs);
+	ISSM_MPI_Gather(&dofcount,1,ISSM_MPI_INT,alldofcount,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(alldofcount,num_procs,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
+	dofcount=0;
+	for(i=0;i<my_rank;i++){
+		dofcount+=alldofcount[i];
+	}
+	for(i=0;i<this->Size();i++){
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->OffsetDofs(dofcount,setenum);
+		}
+	}
+
+	/* Finally, remember that cpus may have skipped some objects, because they were clones. For every 
+	 * object that is not a clone, tell them to show their dofs, so that later on, they can get picked 
+	 * up by their clones: */
+	maxdofspernode=this->MaxNumDofs(analysis_type,setenum);
+	numnodes=this->NumberOfNodes(analysis_type);
+	if(numnodes*maxdofspernode){
+		truedofs=   xNewZeroInit<int>(numnodes*maxdofspernode); //initialize to 0, so that we can pick up the max
+		alltruedofs=xNewZeroInit<int>(numnodes*maxdofspernode);
+	}
+
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->ShowTrueDofs(truedofs,maxdofspernode,setenum);//give maxdofspernode, column size, so that nodes can index into truedofs
+		}
+	}
+
+	ISSM_MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+
+	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
+		}
+	}
+
+	/*Update indexingupdateflag*/
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->ReindexingDone();
+		}
+	}
+
+	/* Free ressources: */
+	xDelete<int>(alldofcount);
+	xDelete<int>(truedofs);
+	xDelete<int>(alltruedofs);
+}
+/*}}}*/
+void  Nodes::FlagClones(int analysis_type){/*{{{*/
+
+	int i;
+	int num_procs;
+	int numnodes;
+
+	/*recover num_procs: */
+	num_procs=IssmComm::GetSize();
+
+	/*Figure out number of nodes for this analysis: */
+	numnodes=this->NumberOfNodes(analysis_type);
+
+	/*Allocate ranks: */
+	int* ranks    = xNew<int>(numnodes);
+	int* minranks = xNew<int>(numnodes);
+	for(i=0;i<numnodes;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
+
+	/*Now go through all our objects and ask them to report to who they belong (which rank): */
+	Ranks(ranks,analysis_type);
+
+	/*We need to take the minimum rank for each vertex, and every cpu needs to get that result. That way, 
+	 * when we start building the dof list for all vertexs, a cpu can check whether its vertex already has been 
+	 * dealt with by another cpu. We take the minimum because we are going to manage dof assignment in increasing 
+	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
+	ISSM_MPI_Allreduce((void*)ranks,(void*)minranks,numnodes,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
+
+	/*Now go through all objects, and use minranks to flag which objects are cloned: */
+	for(i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			/*For this object, decide whether it is a clone: */
+			node->SetClone(minranks);
+		}
+	}
+
+	/*Free ressources: */
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
+
+}
+/*}}}*/
+int   Nodes::MaxNumDofs(int analysis_type,int setenum){/*{{{*/
+
+	int max=0;
+	int allmax,numdofs;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			numdofs=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
+			if(numdofs>max)max=numdofs;
+		}
+	}
+
+	/*Grab max of all cpus: */
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+
+	return max;
+}
+/*}}}*/
+int   Nodes::MaximumId(){/*{{{*/
+
+	int max=-1;
+	int id,allmax;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	if(!sorted){
+		for(int i=0;i<this->Size();i++){
+			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+			id=node->Id();
+			if(id>max)max=id;
+		}
+	}
+	else{
+		if(this->Size()==0){
+			max = 0;
+		}
+		else{
+			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(this->Size()-1));
+			max = node->Id();
+		}
+	}
+
+	/*Grab max of all cpus: */
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+
+	return max;
+}
+/*}}}*/
+int   Nodes::NumberOfDofs(int analysis_type,int setenum){/*{{{*/
+
+	int   allnumdofs;
+
+	/*Get number of dofs on current cpu (excluding clones)*/
+	int numdofs=this->NumberOfDofsLocal(analysis_type,setenum);
+
+	/*Gather from all cpus: */
+	ISSM_MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	return allnumdofs;
+}
+/*}}}*/
+int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){/*{{{*/
+
+	int   numdofs=0;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			/*Ok, this object is a node, ask it to plug values into partition: */
+			if (!node->IsClone()){
+				numdofs+=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
+			}
+		}
+	}
+
+	return numdofs;
+}
+/*}}}*/
+int   Nodes::NumberOfNodes(void){/*{{{*/
+
+	/*Careful! only use once all clones have been setup for all nodes!: */
+
+	int numnodes=0;
+	int allnumnodes=0;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Ok, this object is a node, ask it to plug values into partition: */
+		if (!node->IsClone()) numnodes++;
+	}
+
+	/*Gather from all cpus: */
+	ISSM_MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+
+	return allnumnodes;
+}
+/*}}}*/
+int   Nodes::NumberOfNodes(int analysis_type){/*{{{*/
+
+	int i;
+
+	int max_sid=-1;
+	int sid;
+	int node_max_sid;
+
+	for(i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			sid=node->Sid();
+			if (sid>max_sid)max_sid=sid;
+		}
+	}
+
+	ISSM_MPI_Reduce (&max_sid,&node_max_sid,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_max_sid,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	max_sid=node_max_sid;
+
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return*/
+	return max_sid;
+}
+/*}}}*/
+void  Nodes::Ranks(int* ranks,int analysis_type){/*{{{*/
+
+	int my_rank;
+	int sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Go through nodes, and for each object, report it cpu: */
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+			/*Plug rank into ranks, according to sid: */
+			sid=node->Sid();
+			ranks[sid]=my_rank; 
+		}
+	}
+}
+/*}}}*/
+bool Nodes::RequiresDofReindexing(int analysis_type){/*{{{*/
+
+	int flag = 0;
+	int allflag;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if(node->InAnalysis(analysis_type)){
+			if(node->RequiresDofReindexing()){
+				flag = 1;
+				break;
+			}
+		}
+	}
+
+	/*Grab max of all cpus: */
+	ISSM_MPI_Allreduce((void*)&flag,(void*)&allflag,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+
+	if(allflag){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Nodes.h	(revision 18231)
@@ -0,0 +1,40 @@
+#ifndef _CONTAINER_NODES_H_
+#define  _CONTAINER_NODES_H_
+
+#include "../datastructures/datastructures.h"
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class Materials;
+
+/*!\brief Declaration of Nodes class.
+ *
+ * Declaration of Nodes class.  Nodes are vector lists of objects (Containers) of Node objects.
+ * Node objects are the degrees of freedom (DOFs) for a particular analysis type (not to be 
+ * confused with a vertex, which defines the (x,y,z) location of a point).
+ */ 
+class Nodes: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Nodes();
+		~Nodes();
+
+		/*numerics*/
+		void  DistributeDofs(int analysis_type,int SETENUM);
+		void  FlagClones(int analysis_type);
+		bool  RequiresDofReindexing(int analysis_type);
+		int   MaxNumDofs(int analysis_type,int setenum);
+		int   MaximumId(void);
+		int   NumberOfDofs(int analysis_type,int setenum);
+		int   NumberOfDofsLocal(int analysis_type,int setenum);
+		int   NumberOfNodes(int analysis_type);
+		int   NumberOfNodes(void);
+		void  Ranks(int* ranks,int analysis_type);
+
+};
+
+#endif //ifndef _NODES_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/GenericOption.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/GenericOption.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/GenericOption.h	(revision 18231)
@@ -0,0 +1,134 @@
+/*! \file GenericOption.h 
+ *  \brief: header file for generic option object
+ */
+
+#ifndef _GENERIC_OPTION_
+#define _GENERIC_OPTION_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+#include "./OptionUtilities.h"
+/*}}}*/
+
+template <class OptionType> 
+class GenericOption: public Option {
+
+	public:
+
+		char       *name;
+		OptionType  value;
+
+		int         numel;   //in case OptionType is an array
+		int         ndims;   //in case OptionType is a multi-dimensional array: */
+		int        *size;
+
+		/*GenericOption constructors, destructors*/
+		GenericOption(){ /*{{{*/
+
+			name   = NULL;
+			numel  = 0;
+			ndims  = 0;
+			size   = NULL;
+
+		} /*}}}*/
+		~GenericOption(){ /*{{{*/
+
+			if(name)   xDelete<char>(name);
+			if(size)   xDelete<int>(size);
+
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(){ /*{{{*/
+
+			this->DeepEcho();
+
+		} /*}}}*/
+		void DeepEcho(){ /*{{{*/
+
+			char  indent[81]="";
+			this->DeepEcho(indent);
+
+		} /*}}}*/
+		void DeepEcho(char* indent){ /*{{{*/
+
+			char  cstr[81];
+			bool  flag=true;
+
+			if(flag) _printf0_(indent << "         name: \"" << name << "\"\n");
+			if(flag) _printf0_(indent << "         numel: " << numel << "\n");
+			if(flag) _printf0_(indent << "         ndims: " << ndims << "\n");
+			if(size){
+				StringFromSize(cstr,size,ndims);
+				if(flag) _printf0_(indent << "          size: " << cstr << "\n");
+			}
+			else if(flag) _printf0_(indent << "          size: [empty]\n");
+			_printf_(indent << "         value: " << value << "\n");;
+		} /*}}}*/
+		int  Id(){/*{{{*/
+			_error_("Not implemented yet");
+		};/*}}}*/
+		int  ObjectEnum(){/*{{{*/
+			return GenericOptionEnum;
+		};/*}}}*/
+		Object* copy(){/*{{{*/
+			_error_("Not implemented yet");
+		};/*}}}*/
+
+		/*GenericOption functions: */
+		char* Name(){/*{{{*/
+			return name;
+		};/*}}}*/
+		int   NumEl(){/*{{{*/
+			return numel;
+		};/*}}}*/
+		int   NDims(){/*{{{*/
+			return ndims;
+		};/*}}}*/
+		int*  Size(){/*{{{*/
+			return size;
+		};/*}}}*/
+		void  Get(OptionType* pvalue){/*{{{*/
+			*pvalue=value; 
+		};/*}}}*/
+};
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
+template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmPDouble* outvalue=xNew<IssmPDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+#endif
+template <> inline void GenericOption<IssmDouble*>::Get(IssmDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmDouble* outvalue=xNew<IssmDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+template <> inline void GenericOption<char*>::Get(char** pvalue){ /*{{{*/
+
+	int   stringsize=strlen(this->value)+1;
+	char* outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->value,stringsize);
+
+	*pvalue=outstring;
+} 
+/*}}}*/
+
+#endif  /* _OPTIONOBJECT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Option.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Option.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Option.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*! \file Option.h 
+ *  \brief: header file for option abstract object
+ */
+
+#ifndef _OPTIONOBJECT_H_
+#define _OPTIONOBJECT_H_
+
+/*Headers:{{{*/
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class Option: public Object {
+
+	public:
+
+		/*Option constructors, destructors*/
+		Option(){};
+		~Option(){};
+
+		/*Object virtual functions definitions*/
+		virtual void  Echo()= 0;
+		virtual void  DeepEcho()= 0;
+		virtual void  DeepEcho(char  *indent)=0;
+		int           Id(){_error_("Not implemented yet"); };
+		int           ObjectEnum(){return OptionEnum;              };
+		Object       *copy(){_error_("Not implemented yet"); };
+
+		/*virtual functions: */
+		virtual char* Name()=0;
+		virtual int   NumEl()=0;
+		virtual int   NDims()=0;
+		virtual int*  Size()=0;
+
+};
+#endif  /* _OPTIONOBJECT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.cpp	(revision 18231)
@@ -0,0 +1,104 @@
+/*!\file OptionUtilities.cpp
+ * \brief: implementation of the options utilities
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+int ColumnWiseDimsFromIndex(int* dims,int index,int* size,int ndims){/*{{{*/
+
+	int   i;
+	int   aprod=1;
+
+	/*check for index too large  */
+	for (i=0;i<ndims;i++) aprod*=size[i];
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=ndims-1; i>=0; i--) {
+		aprod=reCast<int>(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {/*{{{*/
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0;i<ndims;i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=ndims-1; i>=0; i--){
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {/*{{{*/
+
+	int   i;
+	int   aprod=1;
+
+	/*check for index too large  */
+	for (i=0; i<ndims; i++) aprod*=size[i];
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=0; i<ndims; i++) {
+		aprod=(int)(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+int IndexFromRowWiseDims(int* dims, int* size, int ndims) {/*{{{*/
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0; i<ndims; i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=0; i<ndims; i++) {
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+int StringFromDims(char* cstr, int* dims, int ndims) {/*{{{*/
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%d,",dims[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",dims[ndims-1]);
+
+	return(0);
+}/*}}}*/
+int StringFromSize(char* cstr, int* size, int ndims) {/*{{{*/
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%dx",size[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",size[ndims-1]);
+
+	return(0);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/OptionUtilities.h	(revision 18231)
@@ -0,0 +1,22 @@
+/*! \file OptionUtilities.h 
+ *  \brief: header file for option object utilities
+ */
+
+#ifndef _OPTIONUTILITIES_H_
+#define _OPTIONUTILITIES_H_
+
+/*Headers:{{{*/
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+
+#include "./Option.h"
+/*}}}*/
+
+int ColumnWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims);
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromRowWiseDims(int* dims, int* size, int ndims);
+int StringFromDims(char* cstr, int* dims, int ndims);
+int StringFromSize(char* cstr, int* size, int ndims);
+
+#endif  /* _OPTIONUTILITIES_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.cpp	(revision 18231)
@@ -0,0 +1,107 @@
+/*
+ * \file Options.cpp
+ * \brief: Implementation of Options class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <algorithm>
+#include <cstring>
+
+#include "./Options.h"
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+Options::Options(){/*{{{*/
+	return;
+}
+/*}}}*/
+Options::~Options(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+int  Options::AddOption(Option* in_option){/*{{{*/
+
+	char* name=NULL;
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*In debugging mode, check that the option is not a NULL pointer*/
+	_assert_(in_option);
+
+	/*Also, check the option name*/
+	name=in_option->Name();
+
+	if(!name) _error_("input option has an empty name");
+	if(strchr(name,'.')) _error_("Option \"" << name << "\" has a protected character \".\"");
+	if(strchr(name,'[')) _error_("Option \"" << name << "\" has a protected character \"[\"");
+	if(strchr(name,']')) _error_("Option \"" << name << "\" has a protected character \"]\"");
+
+	/*Finally, check that no option of the same name already exists in the dataset*/
+	for(object=objects.begin();object<objects.end();object++){
+
+		option=dynamic_cast<Option*>(*object);
+		if (!strcmp(option->Name(),name)){
+			_error_("Options \"" << name << "\" found multiple times");
+			break;
+		}
+	}
+
+	/*OK, all checks went well, add option to dataset*/
+	this->AddObject(in_option);
+
+	return 1;
+}
+/*}}}*/
+Option* Options::GetOption(const char* name){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Go through options and find option: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		option=dynamic_cast<Option*>(*object);
+		if (!strncmp(name,option->Name(),strlen(option->Name()))){
+
+			/*OK, now do we have a complete name? If not, it is a cell or a structure, we need to go further*/
+			if(!strcmp(name,option->Name())){
+				return option;
+			}
+			else{
+				/*If the object is a Cell, recursive call to its options*/ 
+				if(option->ObjectEnum()==OptionCellEnum){
+					GenericOption<Options*>* celloption=(GenericOption<Options*>*)option;
+					return celloption->value->GetOption(name);
+				}
+				/*If the object is a Struct loop over its size and recursive call*/
+				else if(option->ObjectEnum()==OptionStructEnum){
+					for(int i=0;i<option->NumEl();i++){
+						GenericOption<Options**>* structoption=(GenericOption<Options**>*)option;
+						_assert_(structoption->value[i]);
+						return structoption->value[i]->GetOption(name);
+					}
+				}
+				/*Else: not supported*/
+				else{
+					_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
+				}
+			}
+		}
+	}
+
+	/*Option not found return NULL pointer*/
+	return NULL;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Options/Options.h	(revision 18231)
@@ -0,0 +1,108 @@
+#ifndef _CONTAINER_OPTIONS_H_
+#define _CONTAINER_OPTIONS_H_
+
+/*forward declarations */
+class Option;
+#include "../../datastructures/datastructures.h"
+#include "./GenericOption.h"
+
+/*!\brief Declaration of Options class. 
+ * 
+ * Declaration of Options class.  Options are vector lists (Containers) of Option objects.
+ */ 
+class Options: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Options();
+		~Options();
+
+		/*numerics*/
+		int  AddOption(Option* in_oobject);
+		Option* GetOption(const char* name);
+
+		template <class OptionType> void Get(OptionType* pvalue,const char* name){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,const char* name,OptionType default_value){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			else{
+				if(GetOption(name)) _printf_("WARNING: option "<<name<<" found but fetched format not consistent, defaulting...\n");
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name,OptionType default_value){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			else{
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+
+};
+
+#endif //ifndef _INPUTS_H_
+
+template <> inline void Options::Get(char** pvalue,const char* name,char* default_value){ /*{{{*/
+
+	/*Get option*/
+	GenericOption<char*>* genericoption=dynamic_cast<GenericOption<char*>*>(GetOption(name));
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(genericoption){
+		genericoption->Get(pvalue);
+	}
+	else{
+		/*Make a copy*/
+		int   stringsize=strlen(default_value)+1;
+		char* outstring=xNew<char>(stringsize);
+		xMemCpy<char>(outstring,default_value,stringsize);
+		*pvalue=outstring;
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.cpp	(revision 18231)
@@ -0,0 +1,55 @@
+/*!\file BoolParam.c
+ * \brief: implementation of the BoolParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*BoolParam constructors and destructor*/
+BoolParam::BoolParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+BoolParam::BoolParam(int in_enum_type,bool in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+BoolParam::~BoolParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void BoolParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void BoolParam::DeepEcho(void){/*{{{*/
+	_printf_(setw(22)<<"   BoolParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<(value?"true":"false")<<"\n");
+}
+/*}}}*/
+int    BoolParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int BoolParam::ObjectEnum(void){/*{{{*/
+
+	return BoolParamEnum;
+
+}
+/*}}}*/
+Object* BoolParam::copy() {/*{{{*/
+
+	return new BoolParam(this->enum_type,this->value);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/BoolParam.h	(revision 18231)
@@ -0,0 +1,72 @@
+/*! \file BoolParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _BOOLPARAM_H_
+#define _BOOLPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class BoolParam: public Param{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		bool value;
+
+		/*BoolParam constructors, destructors: {{{*/
+		BoolParam();
+		BoolParam(int enum_type,bool value);
+		~BoolParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){*pbool=value;}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){this->value=boolean;}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmPDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _BOOLPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.cpp	(revision 18231)
@@ -0,0 +1,65 @@
+/*!\file DataSetParam.c
+ * \brief: implementation of the DataSetParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*DataSetParam constructors and destructor*/
+DataSetParam::DataSetParam(){/*{{{*/
+	value=NULL;
+	return;
+}
+/*}}}*/
+DataSetParam::DataSetParam(int in_enum_type,DataSet* in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value->Copy();;
+}
+/*}}}*/
+DataSetParam::~DataSetParam(){/*{{{*/
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DataSetParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void DataSetParam::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(22)<<"   DataSetParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" ----- begin\n");
+	this->value->Echo();
+	_printf_(setw(22)<<"   DataSetParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" ----- end\n");
+}
+/*}}}*/
+int    DataSetParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DataSetParam::ObjectEnum(void){/*{{{*/
+
+	return DataSetParamEnum;
+
+}
+/*}}}*/
+Object* DataSetParam::copy() {/*{{{*/
+
+	return new DataSetParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DataSetParam virtual functions definitions: */
+void DataSetParam::GetParameterValue(DataSet** pdataset){/*{{{*/
+	*pdataset=value->Copy();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DataSetParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file DataSetParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DATASETPARAM_H_
+#define _DATASETPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DataSetParam: public Param{
+
+	private: 
+		int   enum_type;
+
+	public:
+		DataSet* value;
+
+		/*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");}
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 18231)
@@ -0,0 +1,212 @@
+/*!\file DoubleMatArrayParam.c
+ * \brief: implementation of the DoubleMatArrayParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*DoubleMatArrayParam constructors and destructor*/
+DoubleMatArrayParam::DoubleMatArrayParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+DoubleMatArrayParam::DoubleMatArrayParam(int in_enum_type,IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){/*{{{*/
+
+	int i;
+	IssmDouble* matrix=NULL;
+	int     m,n;
+
+	enum_type=in_enum_type;
+	M=in_M;
+	if(M){
+		array=xNew<IssmDouble*>(M);
+		mdim_array=xNew<int>(M);
+		ndim_array=xNew<int>(M);
+
+		for(i=0;i<M;i++){
+			m=in_mdim_array[i]; 
+			n=in_ndim_array[i];
+
+			mdim_array[i]=m;
+			ndim_array[i]=n;
+
+			if(m*n){
+				matrix=xNew<IssmDouble>(m*n);
+				xMemCpy<IssmDouble>(matrix,in_array[i],m*n);
+			}
+			else{
+				matrix=NULL;
+			}
+			array[i]=matrix;
+		}
+	}
+	else{
+		array=NULL;
+		mdim_array=NULL;
+		ndim_array=NULL;
+	}
+}
+/*}}}*/
+DoubleMatArrayParam::~DoubleMatArrayParam(){/*{{{*/
+
+	int i;
+	IssmDouble* matrix=NULL;
+
+	xDelete<int>(mdim_array);
+	xDelete<int>(ndim_array);
+
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xDelete<IssmDouble>(matrix);
+	}
+
+	xDelete<IssmDouble*>(array);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DoubleMatArrayParam::Echo(void){/*{{{*/
+
+	_printf_("DoubleMatArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   array size: " << this->M << "\n");
+	_printf_("   array pointer: " << this->array << "\n");
+
+}
+/*}}}*/
+void DoubleMatArrayParam::DeepEcho(void){/*{{{*/
+
+	int i,j,k;
+	int m,n;
+	IssmDouble* matrix=NULL;
+
+	_printf_("DoubleMatArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   array size: " << this->M << "\n");
+	for(i=0;i<M;i++){
+		_printf_("   array " << i << " (" << mdim_array[i] << "x" << ndim_array[i] << "):\n");
+		matrix=array[i];
+		m=mdim_array[i];
+		n=ndim_array[i];
+
+		for(j=0;j<m;j++){
+			_printf_("   ");
+			for(k=0;k<n;k++)_printf_(*(matrix+n*j+k) << " ");
+			_printf_("\n");
+		}
+	}
+}
+/*}}}*/
+int    DoubleMatArrayParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleMatArrayParam::ObjectEnum(void){/*{{{*/
+
+	return DoubleMatArrayParamEnum;
+
+}
+/*}}}*/
+Object* DoubleMatArrayParam::copy() {/*{{{*/
+
+	return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
+
+}
+/*}}}*/
+
+/*DoubleMatArrayParam virtual functions definitions: */
+void  DoubleMatArrayParam::GetParameterValue(IssmDouble*** pout_array, int* pout_M,int** pout_mdim_array, int** pout_ndim_array){/*{{{*/
+
+	int i,m,n;
+	IssmDouble* matrix=NULL;
+	IssmDouble* out_matrix=NULL;
+
+	/*output: */
+	IssmDouble** out_array=NULL;
+	int      out_M;
+	int*     out_mdim_array=NULL;
+	int*     out_ndim_array=NULL;
+
+	out_M=this->M;
+	if(out_M){
+		out_array=xNew<IssmDouble*>(M);
+		out_mdim_array=xNew<int>(M);
+		out_ndim_array=xNew<int>(M);
+
+		xMemCpy<int>(out_mdim_array,this->mdim_array,M);
+		xMemCpy<int>(out_ndim_array,this->ndim_array,M);
+
+		for(i=0;i<this->M;i++){
+			matrix=this->array[i];
+			m=this->mdim_array[i];
+			n=this->ndim_array[i];
+
+			if(m*n){
+				out_matrix=xNew<IssmDouble>(m*n);
+				xMemCpy<IssmDouble>(out_matrix,matrix,m*n);
+			}
+			else{
+				out_matrix=NULL;
+			}
+			out_array[i]=out_matrix;
+		}
+	}
+	else{
+		out_array=NULL;
+		out_matrix=NULL;
+		out_ndim_array=NULL;
+	}
+
+	/*Assign output pointers:*/
+	if(pout_M) *pout_M=out_M;
+	if(pout_mdim_array) *pout_mdim_array=out_mdim_array;
+	if(pout_ndim_array) *pout_ndim_array=out_ndim_array;
+	*pout_array=out_array;
+
+}
+/*}}}*/
+void  DoubleMatArrayParam::SetValue(IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){/*{{{*/
+
+	int i,m,n;
+	IssmDouble* in_matrix=NULL;
+	IssmDouble* matrix=NULL;
+
+	/*avoid leak: */
+	xDelete<int>(mdim_array);
+	xDelete<int>(ndim_array);
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xDelete<IssmDouble>(matrix);
+	}
+	xDelete<IssmDouble*>(array);
+
+	/*copy data: */
+	this->M=in_M;
+	this->array=xNew<IssmDouble*>(M);
+	this->mdim_array=xNew<int>(M);
+	this->ndim_array=xNew<int>(M);
+
+	xMemCpy<int>(this->mdim_array,in_mdim_array,M);
+	xMemCpy<int>(this->ndim_array,in_ndim_array,M);
+
+	for(i=0;i<M;i++){
+		in_matrix=in_array[i];
+		m=in_mdim_array[i];
+		n=in_ndim_array[i];
+
+		matrix=xNew<IssmDouble>(m*n);
+		xMemCpy<IssmDouble>(matrix,in_matrix,m*n);
+
+		this->array[i]=matrix;
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatArrayParam.h	(revision 18231)
@@ -0,0 +1,75 @@
+/*! \file DoubleMatArrayParam.h 
+ *  \brief: header file for object holding an array of serial matrices
+ */
+
+#ifndef _DOUBLEMATARRAYPARAM_H_
+#define _DOUBLEMATARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatArrayParam: public Param{
+
+	private: 
+		int          enum_type;
+		IssmDouble **array;        //array of matrices
+		int          M;            //size of array
+		int         *mdim_array;   //m-dimensions of matrices in the array
+		int         *ndim_array;   //n-dimensions -f matrices in the array
+
+	public:
+		/*DoubleMatArrayParam constructors, destructors: {{{*/
+		DoubleMatArrayParam();
+		DoubleMatArrayParam(int enum_type,IssmDouble** array, int M, int* mdim_array, int* ndim_array);
+		~DoubleMatArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims);
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array);
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATARRAYPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.cpp	(revision 18231)
@@ -0,0 +1,104 @@
+/*!\file DoubleMatParam.c
+ * \brief: implementation of the DoubleMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*DoubleMatParam constructors and destructor*/
+DoubleMatParam::DoubleMatParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+DoubleMatParam::DoubleMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N){/*{{{*/
+
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	value=xNew<IssmDouble>(M*N);
+	xMemCpy<IssmDouble>(value,in_value,M*N);
+}
+/*}}}*/
+DoubleMatParam::~DoubleMatParam(){/*{{{*/
+	xDelete<IssmDouble>(value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DoubleMatParam::Echo(void){/*{{{*/
+
+	_printf_("DoubleMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+
+}
+/*}}}*/
+void DoubleMatParam::DeepEcho(void){/*{{{*/
+
+	int i,j;
+
+	_printf_("DoubleMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+	for(i=0;i<this->M;i++){
+		for(j=0;j<this->N;j++){
+			_printf_(i << " " << j << " " << *(this->value+N*i+j) << "\n");
+		}
+	}
+}
+/*}}}*/
+int    DoubleMatParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleMatParam::ObjectEnum(void){/*{{{*/
+
+	return DoubleMatParamEnum;
+
+}
+/*}}}*/
+Object* DoubleMatParam::copy() {/*{{{*/
+
+	return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*DoubleMatParam virtual functions definitions: */
+void  DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
+	IssmDouble* output=NULL;
+
+	output=xNew<IssmDouble>(M*N);
+	xMemCpy<IssmDouble>(output,value,M*N);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
+	_error_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){/*{{{*/
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->value);
+
+	this->value=xNew<IssmDouble>(in_M*in_N);
+	xMemCpy<IssmDouble>(this->value,IssmDoublearray,in_M*in_N);
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleMatParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file DoubleMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEMATPARAM_H_
+#define _DOUBLEMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatParam: public Param{
+
+	protected: 
+		int         enum_type;
+		IssmDouble *value;
+		int         M;
+		int         N;
+
+	public:
+		/*DoubleMatParam constructors, destructors: {{{*/
+		DoubleMatParam();
+		DoubleMatParam(int enum_type,IssmDouble* value,int M,int N);
+		~DoubleMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N);
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file DoubleParam.c
+ * \brief: implementation of the DoubleParam object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+
+/*DoubleParam constructors and destructor*/
+DoubleParam::DoubleParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+DoubleParam::DoubleParam(int in_enum_type,IssmDouble in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+DoubleParam::~DoubleParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DoubleParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void DoubleParam::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(22)<<"   DoubleParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    DoubleParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleParam::ObjectEnum(void){/*{{{*/
+
+	return DoubleParamEnum;
+
+}
+/*}}}*/
+Object* DoubleParam::copy() {/*{{{*/
+
+	return new DoubleParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DoubleParam virtual functions definitions: */
+void DoubleParam::GetParameterValue(int* pinteger){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+}
+/*}}}*/
+void DoubleParam::GetParameterValue(bool* pbool){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
+}
+/*}}}*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file DoubleParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEPARAM_H_
+#define _DOUBLEPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int        enum_type;
+		IssmDouble value;
+
+	public:
+		/*DoubleParam constructors, destructors: {{{*/
+		DoubleParam();
+		DoubleParam(int enum_type,IssmDouble value);
+		~DoubleParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool);
+		void  GetParameterValue(int* pinteger);
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){*pIssmDouble=value;}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
+		void  SetValue(int integer){this->value=(IssmDouble)integer;}
+		void  SetValue(IssmDouble scalar){this->value=(IssmDouble)scalar;}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _DOUBLEPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 18231)
@@ -0,0 +1,19 @@
+/*!\file DoubleTransientMatParam.c
+ * \brief: implementation of the DoubleTransientMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+DoubleTransientMatParam::DoubleTransientMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N):DoubleMatParam(in_enum_type,in_value,in_M,in_N){/*{{{*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleTransientMatParam.h	(revision 18231)
@@ -0,0 +1,27 @@
+/*! \file DoubleTransientMatParam.h 
+ *  \brief: header file for DoubleTransientMatParam object
+ */
+
+#ifndef _DOUBLETRANSIENTMATPARAM_H_
+#define _DOUBLETRANSIENTMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleTransientMatParam: public DoubleMatParam{
+
+	public:
+		/*DoubleTransientMatParam constructors, destructors: {{{*/
+		DoubleTransientMatParam(int enum_type,IssmDouble* value,int M,int N);
+		/*}}}*/
+};
+#endif  /* _DOUBLETRANSIENTMATPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.cpp	(revision 18231)
@@ -0,0 +1,109 @@
+/*!\file DoubleVecParam.c
+ * \brief: implementation of the DoubleVecParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*DoubleVecParam constructors and destructor*/
+DoubleVecParam::DoubleVecParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+DoubleVecParam::DoubleVecParam(int in_enum_type,IssmDouble* in_values, int in_M){/*{{{*/
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	values=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(values,in_values,M);
+}
+/*}}}*/
+DoubleVecParam::~DoubleVecParam(){/*{{{*/
+	xDelete<IssmDouble>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void DoubleVecParam::Echo(void){/*{{{*/
+
+	_printf_(setw(22)<<"   DoubleVecParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" size: "<<this->M<<"\n");
+
+}
+/*}}}*/
+void DoubleVecParam::DeepEcho(void){/*{{{*/
+	_printf_(setw(22)<<"   DoubleVecParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<"[");
+	for(int i=0;i<this->M;i++) _printf_(" "<< this->values[i]);
+	_printf_("\n");
+}
+/*}}}*/
+int    DoubleVecParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleVecParam::ObjectEnum(void){/*{{{*/
+
+	return DoubleVecParamEnum;
+
+}
+/*}}}*/
+Object* DoubleVecParam::copy() {/*{{{*/
+
+	return new DoubleVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*DoubleVecParam virtual functions definitions: */
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){/*{{{*/
+	IssmDouble* output=NULL;
+	int M;
+
+	M=this->M;
+	output=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(output,values,M);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
+	IssmDouble* output=NULL;
+	int M;
+	int N;
+
+	N=1;
+	M=this->M;
+	output=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(output,values,M);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
+	_error_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){/*{{{*/
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->values);
+
+	this->values=xNew<IssmDouble>(in_M);
+	xMemCpy<IssmDouble>(this->values,IssmDoublearray,in_M);
+
+	this->M=in_M;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/DoubleVecParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file DoubleVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEVECPARAM_H_
+#define _DOUBLEVECPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleVecParam: public Param{
+
+	private: 
+		int         enum_type;
+		IssmDouble *values;
+		int         M;
+
+	public:
+		/*DoubleVecParam constructors, destructors: {{{*/
+		DoubleVecParam();
+		DoubleVecParam(int enum_type,IssmDouble* values,int M);
+		~DoubleVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M);
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file FileParam.c
+ * \brief: implementation of the FileParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*FileParam constructors and destructor*/
+FileParam::FileParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+FileParam::FileParam(int in_enum_type,FILE* in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+FileParam::~FileParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void FileParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void FileParam::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(22)<<"   FileParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    FileParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int FileParam::ObjectEnum(void){/*{{{*/
+
+	return FileParamEnum;
+
+}
+/*}}}*/
+Object* FileParam::copy() {/*{{{*/
+
+	return new FileParam(this->enum_type,this->value);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/FileParam.h	(revision 18231)
@@ -0,0 +1,72 @@
+/*! \file FileParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _FILEPARAM_H_
+#define _FILEPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class FileParam: public Param{
+
+	private: 
+		int   enum_type;
+		FILE* value;
+
+	public:
+		/*FileParam constructors, destructors: {{{*/
+		FileParam();
+		FileParam(int enum_type,FILE* fid);
+		~FileParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){*pfid=value;};
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/GenericParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/GenericParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/GenericParam.h	(revision 18231)
@@ -0,0 +1,94 @@
+/*
+ * GenericParam.h
+ *
+ *  Created on: Aug 29, 2012
+ *      Author: utke
+ */
+
+#ifndef GENERICPARAM_H_
+#define GENERICPARAM_H_
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+        #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Param.h"
+#include "../../shared/shared.h"
+
+/**
+ * here we have a class that holds an instance of P
+ * but because it should live side by side with
+ * the other instances derived from Param it - unfortunately -
+ * inherits all the accessors that are useless in this context
+ */
+template <class P> class GenericParam: public Param{
+
+        private:
+                P myP;
+                int myEnumVal;
+
+        public:
+                /*GenericParam constructors, destructors: {{{*/
+                GenericParam(int enumVal) : myEnumVal(enumVal){};
+                ~GenericParam(){};
+                /*}}}*/
+                /*Object virtual functions definitions:{{{ */
+                // unfortunately,  having to implement such a printer method implies
+                // that any structured P must provide the friend << operator
+                void  DeepEcho() {
+                  _printf_("GenericParam:\n");
+                  _printf_("   enum:  " << myEnumVal << " (" << EnumToStringx(myEnumVal) << ")\n");
+                  _printf_("   value: " << myP << "\n");;
+                }
+                void  Echo() {DeepEcho();};
+                int   Id(){ return -1; };
+                int   ObjectEnum() {return AdolcParamEnum;};
+
+                // the "copy"  has to implement the base class abstract function
+                // but I would prefer to drop this not to hide a "new" in here because
+                // it does not clarify  ownership of the newed up instance...
+                // use the default copy constructor instead
+                Object* copy() { return new GenericParam<P>(*this); };
+                /*}}}*/
+                /*Param vritual function definitions: {{{*/
+                int   InstanceEnum(){return myEnumVal;}
+                P& GetParameterValue() { return myP;}
+                const P& GetParameterValue()const { return myP;};
+
+                // none of these apply ...
+                void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a bool");}
+                void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an integer");}
+                void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble");}
+                void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble for a given time");}
+                void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string");}
+                void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a matrix array");}
+                void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Vec");}
+                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Mat");}
+                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a FILE");}
+				void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a DataSet");}
+
+                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a bool");}
+                void  SetValue(int integer){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an integer");}
+                void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an IssmDouble");}
+                void  SetValue(char* string){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string");}
+                void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string array");}
+                void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Vec");}
+                void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Mat");}
+                void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a FILE");}
+                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an array of matrices");}
+
+                /*}}}*/
+};
+
+#endif /* GENERICPARAM_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.cpp	(revision 18231)
@@ -0,0 +1,100 @@
+/*!\file IntMatParam.c
+ * \brief: implementation of the IntMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*IntMatParam constructors and destructor*/
+IntMatParam::IntMatParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+IntMatParam::IntMatParam(int in_enum_type,int* in_value, int in_M,int in_N){/*{{{*/
+
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	value=xNew<int>(M*N);
+	xMemCpy<int>(value,in_value,M*N);
+}
+/*}}}*/
+IntMatParam::~IntMatParam(){/*{{{*/
+	xDelete<int>(value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void IntMatParam::Echo(void){/*{{{*/
+
+	_printf_("IntMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+
+}
+/*}}}*/
+void IntMatParam::DeepEcho(void){/*{{{*/
+
+	int i,j;
+
+	_printf_("IntMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+	for(i=0;i<this->M;i++){
+		for(j=0;j<this->N;j++){
+			_printf_("(" << i << "," << j << ") " << *(this->value+N*i+j) << "\n");
+		}
+	}
+}
+/*}}}*/
+int    IntMatParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int IntMatParam::ObjectEnum(void){/*{{{*/
+
+	return IntMatParamEnum;
+
+}
+/*}}}*/
+Object* IntMatParam::copy() {/*{{{*/
+
+	return new IntMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*IntMatParam virtual functions definitions: */
+void  IntMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
+	int* output=NULL;
+
+	output=xNew<int>(M*N);
+	xMemCpy<int>(output,value,M*N);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pintarray=output;
+}
+/*}}}*/
+void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){/*{{{*/
+
+	/*avoid leak: */
+	xDelete<int>(this->value);
+
+	this->value=xNew<int>(in_M*in_N);
+	xMemCpy<int>(this->value,intarray,in_M*in_N);
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntMatParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file IntMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTMATPARAM_H_
+#define _INTMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntMatParam: public Param{
+
+	private: 
+		int enum_type;
+		int* value;
+		int M;
+		int N;
+
+	public:
+		/*IntMatParam constructors, destructors: {{{*/
+		IntMatParam();
+		IntMatParam(int enum_type,int* value,int M,int N);
+		~IntMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
+		void  SetValue(int* intarray,int M,int N);
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _INTMATPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file IntParam.c
+ * \brief: implementation of the IntParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*IntParam constructors and destructor*/
+IntParam::IntParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+IntParam::IntParam(int in_enum_type,IssmInt in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+IntParam::~IntParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void IntParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void IntParam::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(22)<<"   IntParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    IntParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int IntParam::ObjectEnum(void){/*{{{*/
+
+	return IntParamEnum;
+
+}
+/*}}}*/
+Object* IntParam::copy() {/*{{{*/
+
+	return new IntParam(this->enum_type,this->value);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file IntParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTPARAM_H_
+#define _INTPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmInt value;
+
+	public:
+		/*IntParam constructors, destructors: {{{*/
+		IntParam();
+		IntParam(int enum_type,IssmInt value);
+		~IntParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){*pinteger=value;}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
+		void  SetValue(int integer){this->value=integer;}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.cpp	(revision 18231)
@@ -0,0 +1,115 @@
+/*!\file IntVecParam.c
+ * \brief: implementation of the IntVecParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*IntVecParam constructors and destructor*/
+IntVecParam::IntVecParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+IntVecParam::IntVecParam(int in_enum_type,int* in_values, int in_M){/*{{{*/
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=xNew<int>(M);
+		xMemCpy<int>(values,in_values,M);
+	}
+	else values=NULL;
+}
+/*}}}*/
+IntVecParam::IntVecParam(int in_enum_type,IssmDouble* in_values, int in_M){/*{{{*/
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=xNew<int>(M);
+		for(int i=0;i<in_M;i++) values[i]=reCast<int>(in_values[i]);
+	}
+	else values=NULL;
+}
+/*}}}*/
+IntVecParam::~IntVecParam(){/*{{{*/
+	xDelete<int>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void IntVecParam::Echo(void){/*{{{*/
+
+	_printf_("IntVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+
+}
+/*}}}*/
+void IntVecParam::DeepEcho(void){/*{{{*/
+
+	int i;
+
+	_printf_("IntVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+	for(i=0;i<this->M;i++){
+		_printf_(i << " " << this->values[i] << "\n");
+	}
+}
+/*}}}*/
+int    IntVecParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int IntVecParam::ObjectEnum(void){/*{{{*/
+
+	return IntVecParamEnum;
+
+}
+/*}}}*/
+Object* IntVecParam::copy() {/*{{{*/
+
+	return new IntVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*IntVecParam virtual functions definitions: */
+void  IntVecParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
+	int* output=NULL;
+
+	if(M){
+		output=xNew<int>(M);
+		xMemCpy<int>(output,values,M);
+	}
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pintarray=output;
+}
+/*}}}*/
+void  IntVecParam::SetValue(int* intarray,int in_M){/*{{{*/
+
+	/*avoid leak: */
+	xDelete<int>(this->values);
+
+	if(in_M){
+		this->values=xNew<int>(in_M);
+		xMemCpy<int>(this->values,intarray,in_M);
+	}
+	else this->values=NULL;
+
+	this->M=in_M;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/IntVecParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file IntVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTVECPARAM_H_
+#define _INTVECPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntVecParam: public Param{
+
+	private: 
+		int enum_type;
+		int* values;
+		int M;
+
+	public:
+		/*IntVecParam constructors, destructors: {{{*/
+		IntVecParam();
+		IntVecParam(int enum_type,int* values,int M);
+		IntVecParam(int enum_type,IssmDouble* values,int M);
+		~IntVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M);
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.cpp	(revision 18231)
@@ -0,0 +1,85 @@
+/*!\file MatrixParam.c
+ * \brief: implementation of the MatrixParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*MatrixParam constructors and destructor*/
+MatrixParam::MatrixParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+MatrixParam::MatrixParam(int in_enum_type,Matrix<IssmDouble>* in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+	}
+}
+/*}}}*/
+MatrixParam::~MatrixParam(){/*{{{*/
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void MatrixParam::Echo(void){/*{{{*/
+
+	_printf_("MatrixParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+
+}
+/*}}}*/
+void MatrixParam::DeepEcho(void){/*{{{*/
+
+	_printf_("MatrixParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	this->value->Echo();
+}
+/*}}}*/
+int    MatrixParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int MatrixParam::ObjectEnum(void){/*{{{*/
+
+	return MatrixParamEnum;
+
+}
+/*}}}*/
+Object* MatrixParam::copy() {/*{{{*/
+
+	return new MatrixParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*MatrixParam virtual functions definitions: */
+void  MatrixParam::GetParameterValue(Matrix<IssmDouble>** poutput){/*{{{*/
+	Matrix<IssmDouble>* output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+	}
+	*poutput=output;
+}
+/*}}}*/
+void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){/*{{{*/
+
+	/*avoid leak: */
+	delete value;
+
+	/*copy: */
+	value=matrix->Duplicate();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/MatrixParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file MatrixParam.h 
+ *  \brief: header file for MatrixParam object
+ */
+
+#ifndef _MATRIXPARAM_H_
+#define _MATRIXPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class MatrixParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Matrix<IssmDouble>* value;
+
+	public:
+		/*MatrixParam constructors, destructors: {{{*/
+		MatrixParam();
+		MatrixParam(int enum_type,Matrix<IssmDouble>* value);
+		~MatrixParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat);
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _MATRIXPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Param.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Param.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Param.h	(revision 18231)
@@ -0,0 +1,58 @@
+/*!\file:  Param.h
+ * \brief abstract class for Param object
+ */ 
+
+#ifndef _PARAM_H_
+#define _PARAM_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../Node.h"
+/*}}}*/
+
+class Param: public Object{
+
+	public: 
+		virtual        ~Param(){};
+
+		/*Virtual functions:*/
+		virtual int   InstanceEnum()=0;
+		virtual void  GetParameterValue(bool* pbool)=0;
+		virtual void  GetParameterValue(int* pinteger)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(IssmDouble* pIssmDouble)=0;
+		virtual void  GetParameterValue(IssmDouble* pdouble,IssmDouble time)=0;
+		virtual void  GetParameterValue(char** pstring)=0;
+		virtual void  GetParameterValue(char*** pstringarray,int* pM)=0;
+		virtual void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM)=0;
+		virtual void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims)=0;
+		virtual void  GetParameterValue(Vector<IssmDouble>** pvec)=0;
+		virtual void  GetParameterValue(Matrix<IssmDouble>** pmat)=0;
+		virtual void  GetParameterValue(FILE** pfid)=0;
+		virtual void  GetParameterValue(DataSet** pdataset)=0;
+
+		virtual void  SetValue(bool boolean)=0;
+		virtual void  SetValue(int integer)=0;
+		virtual void  SetValue(IssmDouble scalar)=0;
+		virtual void  SetValue(char* string)=0;
+		virtual void  SetValue(char** stringarray,int M)=0;
+		virtual void  SetValue(IssmDouble* IssmDoublearray,int M)=0;
+		virtual void  SetValue(IssmDouble* pIssmDoublearray,int M,int N)=0;
+		virtual void  SetValue(int* intarray,int M)=0;
+		virtual void  SetValue(int* pintarray,int M,int N)=0;
+		virtual void  SetValue(Vector<IssmDouble>* vec)=0;
+		virtual void  SetValue(Matrix<IssmDouble>* mat)=0;
+		virtual void  SetValue(FILE* fid)=0;
+		virtual void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array)=0;
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.cpp	(revision 18231)
@@ -0,0 +1,572 @@
+/*
+ * \file Parameters.cpp
+ * \brief: Implementation of the Parameters class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "./Parameters.h"
+#include "./Param.h"
+
+#include "./BoolParam.h"
+#include "./DoubleMatParam.h"
+#include "./DataSetParam.h"
+#include "./DoubleParam.h"
+#include "./DoubleVecParam.h"
+#include "./IntParam.h"
+#include "./IntVecParam.h"
+#include "./IntMatParam.h"
+#include "./FileParam.h"
+#include "./MatrixParam.h"
+#include "./VectorParam.h"
+#include "./StringArrayParam.h"
+#include "./StringParam.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Parameters::Parameters(){/*{{{*/
+	enum_type=ParametersEnum;
+	return;
+}
+/*}}}*/
+Parameters::~Parameters(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+bool Parameters::Exist(int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type) return true;
+	}
+	return false;
+}
+/*}}}*/
+void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pbool);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pinteger);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar,time);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstring);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstringarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(int** pintarray,int* pM, int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(int** pintarray,int* pM,int *pN,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pvec);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pmat);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+void Parameters::FindParam(FILE** pfid,int enum_type){ _assert_(this);/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pfid);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(DataSet** pdataset,int enum_type){ /*{{{*/
+	_assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pdataset);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+
+void   Parameters::SetParam(bool boolean,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(boolean); //already exists, just set it.
+	else this->AddObject(new BoolParam(enum_type,boolean)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(int integer,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(integer); //already exists, just set it.
+	else this->AddObject(new IntParam(enum_type,integer)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(IssmDouble scalar,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(scalar); //already exists, just set it.
+	else this->AddObject(new DoubleParam(enum_type,scalar)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(char* string,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(string); //already exists, just set it.
+	else this->AddObject(new StringParam(enum_type,string)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(char** stringarray,int M, int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(stringarray,M); //already exists, just set it.
+	else this->AddObject(new StringArrayParam(enum_type,stringarray,M)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(IssmDoublearray,M); //already exists, just set it.
+	else this->AddObject(new DoubleVecParam(enum_type,IssmDoublearray,M)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int N, int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(IssmDoublearray,M,N); //already exists, just set it.
+	else this->AddObject(new DoubleMatParam(enum_type,IssmDoublearray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(int* intarray,int M, int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(intarray,M); //already exists, just set it.
+	else this->AddObject(new IntVecParam(enum_type,intarray,M)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(int* intarray,int M, int N, int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(intarray,M,N); //already exists, just set it.
+	else this->AddObject(new IntMatParam(enum_type,intarray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(vector); //already exists, just set it.
+	else this->AddObject(new VectorParam(enum_type,vector)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(matrix); //already exists, just set it.
+	else this->AddObject(new MatrixParam(enum_type,matrix)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(FILE* fid,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(fid); //already exists, just set it.
+	else this->AddObject(new FileParam(enum_type,fid)); //just add the new parameter.
+}
+/*}}}*/
+void   Parameters::SetParam(DataSet* dataset,int enum_type){/*{{{*/
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(dataset); //already exists, just set it.
+	else this->AddObject(new DataSetParam(enum_type,dataset)); //just add the new parameter.
+}
+/*}}}*/
+
+Object* Parameters::FindParamObject(int enum_type){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			return (*object);
+		}
+	}
+	return NULL;
+}
+/*}}}*/
+
+/*Methods relating to parameters: */
+char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
+
+	/* figure out ISSM options for current analysis, return a string. */ 
+
+	/*output: */
+	char*   outstring=NULL;
+
+	/*intermediary: */
+	int          dummy;
+	IssmDouble  *analyses    = NULL;
+	char       **strings     = NULL;
+	char        *string      = NULL;
+	int          numanalyses;
+	int          found       = -1;
+	int          i;
+
+	numanalyses=0;
+	parameters->FindParam(&strings,&numanalyses,ToolkitsOptionsStringsEnum);
+
+	parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum);
+
+	if(numanalyses==0)return NULL; //we did not find petsc options, don't bother.
+
+	/*ok, go through analyses and figure out if it corresponds to our analysis_type: */
+	for(i=0;i<numanalyses;i++){
+		if(analyses[i]==analysis_type){
+			found=i;
+			break;
+		}
+	}
+	if(found==-1){
+		/*still haven't found a list of petsc options, go find the default one, for analysis type DefaultAnalysisEnum: */
+		for(i=0;i<numanalyses;i++){
+			if(analyses[i]==DefaultAnalysisEnum){
+				found=i;
+				break;
+			}
+		}
+	}
+	if (found==-1){
+		_error_("could find neither a default analysis nor analysis " << EnumToStringx(analysis_type));
+	}
+
+	/*ok, grab the option string: */
+	outstring=xNew<char>(strlen(strings[found])+1);
+	strcpy(outstring,strings[found]);
+
+	/*Free ressources*/
+	xDelete<IssmDouble>(analyses);
+	for(i=0;i<numanalyses;i++){
+		string=strings[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(strings);
+	return outstring;
+} 
+/*}}}*/
+void ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
+
+	/*!\file:  ToolkitsOptionsFromAnalysis.cpp
+	 * \brief: for each analysis, setup the issmoptions string. 
+	 * This is mainly for the case where we run our toolkits using petsc. In this case, we need to 
+	 * plug our toolkits options directly into the petsc options database. This is the case for each analysis type 
+	 * and parameters
+	 */ 
+
+	char* options=NULL;
+
+	/*Recover first the options string for this analysis: */
+	options=OptionsFromAnalysis(parameters,analysis_type);
+
+	/*Initialize our Toolkit Options: */
+	ToolkitOptions::Init(options);
+
+	#ifdef _HAVE_PETSC_
+		/*In case we are using PETSC, we do not rely on issmoptions. Instead, we dump issmoptions into the Petsc 
+		 * options database: */
+
+		#if _PETSC_MAJOR_ == 2 
+		PetscOptionsDestroy();
+		PetscOptionsCreate();
+		//PetscOptionsCheckInitial_Private();
+		//PetscOptionsCheckInitial_Components();
+		PetscOptionsSetFromOptions();
+		PetscOptionsInsertMultipleString(options); //our patch
+		#else
+		PetscOptionsSetFromOptions();
+		PetscOptionsClear();
+		//PetscOptionsSetFromOptions();
+		PetscOptionsInsertMultipleString(options); //our patch
+		#endif
+
+	#endif
+
+	xDelete<char>(options);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/Parameters.h	(revision 18231)
@@ -0,0 +1,64 @@
+#ifndef _CONTAINER_PARAMETERS_H_
+#define  _CONTAINER_PARAMETERS_H_
+#include <stdio.h>
+
+/*forward declarations */
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*!\brief Declaration of Parameters class.  
+ *
+ * Declaration of Parameters class.  Parameters are vector lists (Containers) of Parameter objects.
+ */ 
+class Parameters: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/ 
+		Parameters();
+		~Parameters();
+
+		/*numerics*/
+		bool  Exist(int enum_type);
+
+		void  FindParam(bool* pinteger,int enum_type);
+		void  FindParam(int* pinteger,int enum_type);
+		void  FindParam(IssmDouble* pscalar, int enum_type);
+		void  FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time);
+		void  FindParam(char** pstring,int enum_type);
+		void  FindParam(char*** pstringarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int* PN,int enum_type);
+		void  FindParam(IssmDouble** pIssmDoublearray,int* pM,int enum_type);
+		void  FindParam(IssmDouble** pIssmDoublearray,int* pM,int* pN,int enum_type);
+		void  FindParam(IssmDouble*** parray,int* pM, int** pmdims_array,int** pndims_array,int enum_type);
+		void  FindParam(Vector<IssmDouble>** pvec,int enum_type);
+		void  FindParam(Matrix<IssmDouble>** pmat,int enum_type);
+		void  FindParam(FILE** pfid,int enum_type);
+		void  FindParam(DataSet** pdataset, int enum_type);
+
+		void  SetParam(bool boolean,int enum_type);
+		void  SetParam(int integer,int enum_type);
+		void  SetParam(IssmDouble scalar, int enum_type);
+		void  SetParam(char* string,int enum_type);
+		void  SetParam(char** stringarray,int M,int enum_type);
+		void  SetParam(IssmDouble* IssmDoublearray,int M,int enum_type);
+		void  SetParam(IssmDouble* IssmDoublearray,int M,int N,int enum_type);
+		void  SetParam(int* intarray,int M,int enum_type);
+		void  SetParam(int* intarray,int M,int N,int enum_type);
+		void  SetParam(Vector<IssmDouble>* vec,int enum_type);
+		void  SetParam(Matrix<IssmDouble>* mat,int enum_type);
+		void  SetParam(FILE* fid,int enum_type);
+		void  SetParam(DataSet* dataset,int enum_type);
+
+		Object* FindParamObject(int enum_type);
+
+};
+
+/*Methods relating to parameters: */
+char       *OptionsFromAnalysis(Parameters *parameters,int analysis_type);
+void        ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type);
+
+#endif //ifndef _PARAMETERS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.cpp	(revision 18231)
@@ -0,0 +1,142 @@
+/*!\file StringArrayParam.c
+ * \brief: implementation of the StringArrayParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*StringArrayParam constructors and destructor*/
+StringArrayParam::StringArrayParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+StringArrayParam::StringArrayParam(int in_enum_type,char** in_values, int in_numstrings){/*{{{*/
+
+	int i;
+	int size;
+
+	enum_type=in_enum_type;
+	numstrings=in_numstrings;
+
+	if(numstrings){
+		value=xNew<char*>(numstrings);
+		for(i=0;i<numstrings;i++){
+			char* string=NULL;
+			size=strlen(in_values[i])+1;
+			string=xNew<char>(size);
+			xMemCpy<char>(string,in_values[i],size);
+			value[i]=string;
+		}
+	}
+	else value=NULL;
+
+}
+/*}}}*/
+StringArrayParam::~StringArrayParam(){/*{{{*/
+
+	int i;
+
+	char* string=NULL;
+	for(i=0;i<this->numstrings;i++){
+		string=value[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void StringArrayParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void StringArrayParam::DeepEcho(void){/*{{{*/
+
+	_printf_(setw(22)<<"   StringArrayParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" {");
+	for(int i=0;i<this->numstrings;i++) _printf_(" '"<<this->value[i]<<"'");
+	_printf_("}\n");
+}
+/*}}}*/
+int    StringArrayParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int StringArrayParam::ObjectEnum(void){/*{{{*/
+
+	return StringArrayParamEnum;
+
+}
+/*}}}*/
+Object* StringArrayParam::copy() {/*{{{*/
+
+	return new StringArrayParam(this->enum_type,this->value,this->numstrings);
+
+}
+/*}}}*/
+
+/*StringArrayParam virtual functions definitions: */
+void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){/*{{{*/
+
+	int   i;
+	char** outstrings=NULL;
+	int   M;
+	char* string=NULL;
+	char* string2=NULL;
+	int   stringsize;
+
+	M=this->numstrings;
+	if(this->numstrings){
+		outstrings=xNew<char*>(this->numstrings);
+
+		for(i=0;i<this->numstrings;i++){
+			string=this->value[i];
+			stringsize=strlen(string)+1;
+
+			string2=xNew<char>(stringsize);
+			xMemCpy<char>(string2,string,stringsize);
+
+			outstrings[i]=string2;
+		}
+	}
+	else outstrings=NULL;
+
+	/*Assign output pointers:*/
+	*pM=M;
+	*pstringarray=outstrings;
+}
+/*}}}*/
+void  StringArrayParam::SetValue(char** stringarray,int M){/*{{{*/
+
+	int   i;
+	char *string     = NULL;
+	char *string2    = NULL;
+	int   stringsize;
+
+	/*first, avoid leak: */
+	for(i=0;i<this->numstrings;i++){
+		string=this->value[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(this->value);
+
+	/*copy: */
+	this->numstrings=M;
+	this->value=xNew<char*>(this->numstrings);
+	for(i=0;i<this->numstrings;i++){
+		string=stringarray[i];
+		stringsize=strlen(string)+1;
+
+		string2=xNew<char>(stringsize);
+		xMemCpy<char>(string2,string,stringsize);
+
+		this->value[i]=string2;
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringArrayParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file StringArrayParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _STRINGARRAYPARAM_H_
+#define _STRINGARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringArrayParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int      enum_type;
+		char**   value;
+		int      numstrings;
+
+	public:
+		/*StringArrayParam constructors, destructors: {{{*/
+		StringArrayParam();
+		StringArrayParam(int enum_type,char** values, int numstrings);
+		~StringArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M);
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _STRINGARRAYPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.cpp	(revision 18231)
@@ -0,0 +1,87 @@
+/*!\file StringParam.c
+ * \brief: implementation of the StringParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*StringParam constructors and destructor*/
+StringParam::StringParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+StringParam::StringParam(int in_enum_type,char* in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+	value=xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+
+}
+/*}}}*/
+StringParam::~StringParam(){/*{{{*/
+	xDelete<char>(value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void StringParam::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+void StringParam::DeepEcho(void){/*{{{*/
+	_printf_(setw(22)<<"   StringParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
+}
+/*}}}*/
+int    StringParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int StringParam::ObjectEnum(void){/*{{{*/
+
+	return StringParamEnum;
+
+}
+/*}}}*/
+Object* StringParam::copy() {/*{{{*/
+
+	return new StringParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*StringParam virtual functions definitions: */
+void  StringParam::GetParameterValue(char** pstring){/*{{{*/
+
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->value)+1;
+
+	outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->value,stringsize);
+
+	*pstring=outstring;
+
+}
+/*}}}*/
+void  StringParam::SetValue(char* string){/*{{{*/
+
+	int   stringsize;
+
+	/*avoid leak: */
+	xDelete<char>(this->value);
+
+	/*copy: */
+	stringsize=strlen(string)+1;
+	this->value=xNew<char>(stringsize);
+	xMemCpy<char>(this->value,string,stringsize);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/StringParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file StringParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _STRINGPARAM_H_
+#define _STRINGPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int   enum_type;
+		char *value;
+
+	public:
+		/*StringParam constructors, destructors: {{{*/
+		StringParam();
+		StringParam(int enum_type,char* value);
+		~StringParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring);
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string);
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _STRINGPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.cpp	(revision 18231)
@@ -0,0 +1,119 @@
+/*!\file TransientParam.c
+ * \brief: implementation of the TransientParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*TransientParam constructors and destructor*/
+TransientParam::TransientParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+TransientParam::TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N){/*{{{*/
+
+	_assert_(in_values && in_time);
+
+	enum_type=in_enum_type;
+	N=in_N;
+
+	values=xNew<IssmDouble>(N);
+	xMemCpy<IssmDouble>(values,in_values,N);
+
+	timesteps=xNew<IssmDouble>(N);
+	xMemCpy<IssmDouble>(timesteps,in_time,N);
+}
+/*}}}*/
+TransientParam::~TransientParam(){/*{{{*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(timesteps);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void TransientParam::Echo(void){/*{{{*/
+
+	_printf_("TransientParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   size: " << this->N << "\n");
+
+}
+/*}}}*/
+void TransientParam::DeepEcho(void){/*{{{*/
+
+	_printf_("TransientParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   size: " << this->N << "\n");
+	for(int i=0;i<this->N;i++){
+		_printf_(   "time: " << this->timesteps[i] << " value: " << this->values[i] << "\n");
+	}
+}
+/*}}}*/
+int    TransientParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int TransientParam::ObjectEnum(void){/*{{{*/
+
+	return TransientParamEnum;
+
+}
+/*}}}*/
+Object* TransientParam::copy() {/*{{{*/
+
+	return new TransientParam(this->enum_type,this->values,this->timesteps,this->N);
+
+}
+/*}}}*/
+
+/*TransientParam virtual functions definitions: */
+void  TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){/*{{{*/
+
+	IssmDouble output;
+	bool   found;
+
+	/*Ok, we have the time, go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	if(time<this->timesteps[0]){
+		/*get values for the first time: */
+		output=this->values[0];
+		found=true;
+	}
+	else if(time>this->timesteps[this->N-1]){
+		/*get values for the last time: */
+		output=this->values[this->N-1];
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(int i=0;i<this->N;i++){
+			if(time==this->timesteps[i]){
+				/*We are right on one step time: */
+				output=this->values[i];
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<time && time<this->timesteps[i+1]){
+					/*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
+					IssmDouble deltat=this->timesteps[i+1]-this->timesteps[i];
+					IssmDouble alpha=(time-this->timesteps[i])/deltat;
+					output=(1.0-alpha)*this->values[i] + alpha*this->values[i+1];
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error_("did not find time interval on which to interpolate values");
+	*pdouble=output;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/TransientParam.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*! \file TransientParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _TRANSIENTPARAM_H_
+#define _TRANSIENTPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class TransientParam: public Param{
+
+	protected: 
+		int         enum_type;
+		int         N;
+		IssmDouble *values;
+		IssmDouble *timesteps;
+
+	public:
+		/*TransientParam constructors, destructors: {{{*/
+		TransientParam();
+		TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N);
+		~TransientParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time);
+		void  GetParameterValue(char** pstring){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _TRANSIENTPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file VectorParam.c
+ * \brief: implementation of the VectorParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*VectorParam constructors and destructor*/
+VectorParam::VectorParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+VectorParam::VectorParam(int in_enum_type,Vector<IssmDouble>* in_value){/*{{{*/
+
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+		in_value->Copy(value);
+	}
+}
+/*}}}*/
+VectorParam::~VectorParam(){/*{{{*/
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void VectorParam::Echo(void){/*{{{*/
+
+	_printf_("VectorParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+
+}
+/*}}}*/
+void VectorParam::DeepEcho(void){/*{{{*/
+
+	_printf_("VectorParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	value->Echo();
+}
+/*}}}*/
+int    VectorParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int VectorParam::ObjectEnum(void){/*{{{*/
+
+	return VectorParamEnum;
+
+}
+/*}}}*/
+Object* VectorParam::copy() {/*{{{*/
+
+	return new VectorParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*VectorParam virtual functions definitions: */
+void  VectorParam::GetParameterValue(Vector<IssmDouble>** poutput){/*{{{*/
+	Vector<IssmDouble>*  output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+		value->Copy(output);
+	}
+	*poutput=output;
+}
+/*}}}*/
+void  VectorParam::SetValue(Vector<IssmDouble>* vector){/*{{{*/
+
+	/*avoid leak: */
+	delete value;
+
+	/*copy: */
+	value=vector->Duplicate();
+	vector->Copy(value);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Params/VectorParam.h	(revision 18231)
@@ -0,0 +1,73 @@
+/*! \file VectorParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _VECTORPARAM_H_
+#define _VECTORPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class VectorParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Vector<IssmDouble>* value;
+
+	public:
+		/*VectorParam constructors, destructors: {{{*/
+		VectorParam();
+		VectorParam(int enum_type,Vector<IssmDouble>* value);
+		~VectorParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(Vector<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec);
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _VECTORPARAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.cpp	(revision 18231)
@@ -0,0 +1,162 @@
+/*!\file Profiler.c
+ * \brief: implementation of the Profiler object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Profiler.h"
+#include "./Params/Parameters.h"
+#include "./Params/DoubleParam.h"
+#include "../toolkits/toolkits.h"
+/*}}}*/
+
+/*Profiler constructors and destructors:*/
+Profiler::Profiler(){/*{{{*/
+		 this->time=new Parameters();
+		 this->flops=new Parameters();
+		 this->memory=new Parameters();
+}
+/*}}}*/
+Profiler::~Profiler(){/*{{{*/
+	delete time;
+	delete flops;
+	delete memory;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Profiler::Echo(void){/*{{{*/
+
+	_printf_("Profiler:\n");
+	_printf_("   time tags: \n");
+	this->time->Echo();
+
+}
+/*}}}*/
+void Profiler::DeepEcho(void){/*{{{*/
+
+	_printf_("Profiler:\n");
+	_printf_("   time tags: \n");
+	this->time->DeepEcho();
+
+}
+/*}}}*/
+int    Profiler::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int Profiler::ObjectEnum(void){/*{{{*/
+
+	return ProfilerEnum;
+
+}
+/*}}}*/
+
+/*Profiler routines:*/
+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){
+		ISSM_MPI_Barrier(IssmComm::GetComm()); 
+	}
+
+	/*Capture time: */
+	#ifdef _HAVE_MPI_
+	t=ISSM_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));
+
+}
+/*}}}*/
+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
+}
+/*}}}*/
+IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){/*{{{*/
+
+	IssmDouble init, final;
+	this->flops->FindParam(&init,inittag);
+	this->flops->FindParam(&final,finaltag);
+
+	return final-init;
+}
+/*}}}*/
+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
+
+}
+/*}}}*/
+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
+}
+/*}}}*/
+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
+}
+/*}}}*/
+IssmDouble  Profiler::Memory(int tag){/*{{{*/
+
+	IssmDouble m;
+	this->memory->FindParam(&m,tag);
+
+	return m;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Profiler.h	(revision 18231)
@@ -0,0 +1,57 @@
+/*!\file Profiler.h
+ * \brief: header file for node object
+ */
+
+#ifndef _PROFILER_H_
+#define _PROFILER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+class DataSet;
+class Parameters;
+
+enum ProfilerEnums {
+	Start,
+	StartInit,
+	FinishInit,
+	StartCore,
+	FinishCore,
+	StartAdCore,
+	FinishAdCore,
+	Finish
+};
+
+class Profiler: public Object{
+
+	public: 
+		Parameters*  time;
+		Parameters*  flops;
+		Parameters*  memory;
+
+		/*Profiler constructors, destructors {{{*/
+		Profiler();
+		~Profiler();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy()        {_error_("Not implemented yet"); };
+		/*}}}*/
+		/*Profiler routines {{{*/
+		void    Tag(int tagenum,bool dontmpisync=false);
+		IssmDouble  Memory(int tag);
+		IssmDouble  DeltaTime(int inittag, int finaltag);
+		IssmDouble  DeltaFlops(int inittag, int finaltag);
+		int     DeltaTimeModHour(int inittag, int finaltag);
+		int     DeltaTimeModMin(int inittag, int finaltag);
+		int     DeltaTimeModSec(int inittag, int finaltag);
+		/*}}}*/
+};
+
+#endif  /* _PROFILER_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.cpp	(revision 18231)
@@ -0,0 +1,94 @@
+/*!\file RiftStruct.c
+ * \brief: implementation of the RiftStruct object
+ */
+
+#include "./classes.h"
+#include "../shared/Enum/Enum.h"
+#include "../shared/shared.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,int**riftssegments_in,int *riftsnumpairs_in,int**riftspairs_in,int *riftsnumpenaltypairs_in,double **riftspenaltypairs_in,int * 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<int*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->riftssegments[i]=xNew<int>(riftsnumsegments_in[i]*3);
+		xMemCpy<int>(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<int*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->riftspairs[i]=xNew<int>(riftsnumpairs_in[i]*2);
+		xMemCpy<int>(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<int>(2*numrifts_in);
+	xMemCpy<int>(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<int*>(this->riftssegments);
+	xDelete<int>(this->riftsnumpairs);
+	xDelete<int*>(this->riftspairs);
+	xDelete<int>(this->riftsnumpenaltypairs);
+	xDelete<double*>(this->riftspenaltypairs);
+	xDelete<int>(this->riftstips);
+	xDelete<double*>(this->state);
+
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/RiftStruct.h	(revision 18231)
@@ -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;
+		int    **riftssegments;
+		int     *riftsnumsegments;
+		int    **riftspairs;
+		int     *riftsnumpairs;
+		double **riftspenaltypairs;
+		int     *riftsnumpenaltypairs;
+		int     *riftstips;
+		double **state;
+
+		RiftStruct();
+		RiftStruct(int numrifts_in,int *riftsnumsegments_in,int **riftssegments_in,int *riftsnumpairs_in,int **riftspairs_in,int *riftsnumpenaltypairs_in,double **riftspenaltypairs_in,int* riftstips_in);
+		~RiftStruct();
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Segment.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Segment.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Segment.h	(revision 18231)
@@ -0,0 +1,76 @@
+/*!\file Segment.h
+ * \brief: header file for node object
+ */
+
+#ifndef _SEGMENT_H_
+#define _SEGMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/Numerics/constants.h"
+/*}}}*/
+
+template <class doubletype> 
+class Segment: public Object{
+
+	public:
+		int        eid;
+		doubletype x1;
+		doubletype y1;
+		doubletype x2;
+		doubletype y2;
+
+		/*Segment constructors, destructors :*/
+		Segment(){/*{{{*/
+			this->eid = UNDEF;
+			this->x1  = UNDEF;
+			this->y1  = UNDEF;
+			this->x2  = UNDEF;
+			this->y2  = UNDEF;
+		}
+		/*}}}*/
+		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;
+
+		}
+		/*}}}*/
+		~Segment(){/*{{{*/
+		}
+		/*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(void){/*{{{*/
+
+			_printf_("Segment:\n");
+			_printf_("   eid: " << eid << "\n");
+			_printf_("   node 1: " << this->x1 << "|" << this->y1 << "\n");
+			_printf_("   node 2: " << this->x2 << "|" << this->y2 << "\n");
+
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int    Id(void){ return eid; }/*{{{*/
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+
+			return SegmentEnum;
+
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
+		}
+		/*}}}*/
+
+};
+
+#endif  /* _SEGMENT_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Update.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Update.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Update.h	(revision 18231)
@@ -0,0 +1,28 @@
+/*!\file: Update.h: abstract class used by some objects to update their properties
+ * \brief prototypes for Update.h
+ */ 
+
+#ifndef _UPDATE_H_
+#define  _UPDATE_H_
+
+/*Headers:*/
+#include "../shared/shared.h"
+class IoModel;
+
+class Update{
+
+	public:
+
+		virtual void  InputUpdateFromVector(IssmDouble* vector, int name, int type)=0;
+		#ifdef _HAVE_DAKOTA_
+		virtual void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int rows, int ncols, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type)=0;
+		#endif
+		virtual void  InputUpdateFromConstant(IssmDouble constant, int name)=0;
+		virtual void  InputUpdateFromConstant(int constant, int name)=0;
+		virtual void  InputUpdateFromConstant(bool constant, int name)=0;
+		virtual void  InputUpdateFromIoModel(int index, IoModel* iomodel)=0;
+
+};
+
+#endif //ifndef _UPDATE_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.cpp	(revision 18231)
@@ -0,0 +1,244 @@
+/*!\file Vertex.c
+ * \brief: implementation of the Vertex object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include "classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*Vertex constructors and destructor:*/
+Vertex::Vertex(){/*{{{*/
+	return;
+}
+/*}}}*/
+Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){/*{{{*/
+
+	this->id           = vertex_id;
+	this->sid          = vertex_sid;
+	this->pid          = UNDEF;
+
+	_assert_(iomodel->Data(MeshXEnum) && iomodel->Data(MeshYEnum) && iomodel->Data(MeshZEnum));
+	this->x            = iomodel->Data(MeshXEnum)[i];
+	this->y            = iomodel->Data(MeshYEnum)[i];
+	this->z            = iomodel->Data(MeshZEnum)[i];
+	this->domaintype     = iomodel->domaintype;
+
+	_assert_(iomodel->Data(BaseEnum) && iomodel->Data(ThicknessEnum) && iomodel->numbernodetoelementconnectivity);
+	switch(iomodel->domaintype){
+		case Domain3DEnum:
+		case Domain2DhorizontalEnum:
+			this->sigma = (iomodel->Data(MeshZEnum)[i]-iomodel->Data(BaseEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
+			break;
+		case Domain2DverticalEnum:
+			this->sigma = (iomodel->Data(MeshYEnum)[i]-iomodel->Data(BaseEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
+			break;
+	}
+
+	this->connectivity = iomodel->numbernodetoelementconnectivity[i];
+
+}
+/*}}}*/
+Vertex::~Vertex(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Vertex::Echo(void){/*{{{*/
+
+	_printf_("Vertex:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   pid: " << pid << "\n");
+	_printf_("   x: " << x << "\n");
+	_printf_("   y: " << y << "\n");
+	_printf_("   z: " << z << "\n");
+	_printf_("   sigma: " << sigma << "\n");
+	_printf_("   connectivity: " << connectivity << "\n");
+	_printf_("   clone: " << clone << "\n");
+
+	return;
+}
+/*}}}*/
+void Vertex::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+int Vertex::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Vertex::ObjectEnum(void){/*{{{*/
+
+	return VertexEnum;
+
+}
+/*}}}*/
+Object* Vertex::copy() {/*{{{*/
+
+	return new Vertex(*this); 
+
+}
+/*}}}*/
+
+/*Vertex management: */
+int        Vertex::Connectivity(void){return connectivity;}/*{{{*/
+/*}}}*/
+IssmDouble Vertex::GetX(){/*{{{*/
+	return this->x;
+}
+/*}}}*/
+IssmDouble Vertex::GetY(){/*{{{*/
+	return this->y;
+}
+/*}}}*/
+IssmDouble Vertex::GetZ(){/*{{{*/
+	return this->z;
+}
+/*}}}*/
+int        Vertex::Sid(void){ return sid; }/*{{{*/
+/*}}}*/
+int        Vertex::Pid(void){ return pid; }/*{{{*/
+/*}}}*/
+void       Vertex::UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* surface,IssmDouble* bed){/*{{{*/
+
+	IssmDouble oldy,newy,vely;
+	IssmDouble oldz,newz,velz;
+	IssmDouble dt;
+
+	/*Get time stepping*/
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	/*sigma remains constant. z=bed+sigma*thickness*/
+	switch(this->domaintype){
+		case Domain2DhorizontalEnum:
+			/*Nothing*/
+			return;
+		case Domain2DverticalEnum:
+			oldy = this->y;
+			newy = bed[this->pid]+sigma*(surface[this->pid] - bed[this->pid]);
+			vely = (newy-oldy)/dt;
+			this->y = newy;
+			vy->SetValue(this->pid,vely,INS_VAL);
+			return;
+		case Domain3DEnum:
+			oldz = this->z;
+			newz = bed[this->pid]+sigma*(surface[this->pid] - bed[this->pid]);
+			velz = (newz-oldz)/dt;
+			this->z = newz;
+			vz->SetValue(this->pid,velz,INS_VAL);
+			return;
+		default:
+			_error_("not implemented");
+	}
+}
+/*}}}*/
+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;
+}
+/*}}}*/
+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;
+}
+/*}}}*/
+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;
+}
+/*}}}*/
+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];
+}
+/*}}}*/
+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;
+	}
+
+}
+/*}}}*/
+void       Vertex::ToXYZ(Matrix<IssmDouble>* matrix){/*{{{*/
+
+	IssmDouble xyz[3];
+	int        indices[3];
+
+	if (this->clone==true) return;
+
+	xyz[0]=x;
+	xyz[1]=y; 
+	xyz[2]=z;
+	indices[0]=0;
+	indices[1]=1; 
+	indices[2]=2;
+
+	matrix->SetValues(1,&sid,3,&indices[0],&xyz[0],INS_VAL);
+}
+/*}}}*/
+void       Vertex::VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz){/*{{{*/
+
+	if (this->clone==true) return;
+
+	vx->SetValue(this->sid,this->x,INS_VAL);
+	vy->SetValue(this->sid,this->y,INS_VAL);
+	vz->SetValue(this->sid,this->z,INS_VAL);
+
+	return;
+}
+/*}}}*/
+
+/*Methods relating to Vertex, but not internal methods: */
+void GetVerticesCoordinates(IssmDouble* xyz,Vertex** vertices, int numvertices){ /*{{{*/
+
+	_assert_(vertices);
+	_assert_(xyz);
+
+	for(int i=0;i<numvertices;i++) {
+		xyz[i*3+0]=vertices[i]->GetX();
+		xyz[i*3+1]=vertices[i]->GetY();
+		xyz[i*3+2]=vertices[i]->GetZ();
+	}
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertex.h	(revision 18231)
@@ -0,0 +1,65 @@
+/*! \file Vertex.h 
+ *  \brief: header file for vertex object
+ */
+
+#ifndef _VERTEX_H_
+#define _VERTEX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./classes.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../toolkits/toolkits.h"
+template <class doubletype> class Vector;
+template <class doubletype> class Matrix;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Vertex: public Object{
+
+	public: 
+		bool       clone;
+		int        domaintype;
+		int        id;           // random index
+		int        sid;          // "serial" id (rank of this vertex if the dataset was on 1 cpu)
+		int        pid;          // "parallel" id
+		IssmDouble x;
+		IssmDouble y;
+		IssmDouble z;
+		IssmDouble sigma;        //sigma coordinate: (z-bed)/thickness
+		int        connectivity; //number of vertices connected to this vertex
+
+		/*Vertex constructors, destructors {{{*/
+		Vertex();
+		Vertex(int id, int sid, int i, IoModel* iomodel);
+		~Vertex();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Vertex management:*/ 
+		int        Pid(void); 
+		int        Sid(void); 
+		int        Connectivity(void); 
+		IssmDouble GetX(void); 
+		IssmDouble GetY(void); 
+		IssmDouble GetZ(void); 
+		void       UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
+		void       DistributePids(int* ppidcount);
+		void       OffsetPids(int pidcount);
+		void       ShowTruePids(int* borderpids);
+		void       UpdateClonePids(int* allborderpids);
+		void       SetClone(int* minranks);
+		void       ToXYZ(Matrix<IssmDouble>* matrix);
+		void       VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz);
+};
+
+/*Methods relating to Vertex object: */
+void GetVerticesCoordinates(IssmDouble* xyz,Vertex** vertices, int numvertices);
+
+#endif  /* _VERTEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.cpp	(revision 18231)
@@ -0,0 +1,221 @@
+/*
+ * \file Vertices.cpp
+ * \brief: Implementation of Vertices class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "./Vertices.h"
+#include "../shared/shared.h"
+#include "./Vertex.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Vertices::Vertices(){/*{{{*/
+	enum_type=VerticesEnum;
+	return;
+}
+/*}}}*/
+Vertices::~Vertices(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Numerics management*/
+void  Vertices::DistributePids(int numberofobjects){/*{{{*/
+
+	int num_procs;
+	int my_rank;
+
+	int  i;
+	int  pidcount    = 0;
+	int *allpidcount = NULL;
+	int *truepids    = NULL;
+	int *alltruepids = NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
+	/*Go through objects, and distribute pids locally, from 0 to numberofpidsperobject*/
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->DistributePids(&pidcount);
+	}
+
+	/* Now every object has distributed pids, but locally, and with a pid count starting from 
+	 * 0. This means the pids between all the cpus are not unique. We now offset the pids of each
+	 * cpus by the total last pids of the previus cpu, starting from 0.
+	 * First: get number of pids for each cpu*/
+	allpidcount=xNew<int>(num_procs);
+	ISSM_MPI_Gather(&pidcount,1,ISSM_MPI_INT,allpidcount,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(allpidcount,num_procs,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/* Every cpu should start its own pid count at the end of the pidcount from cpu-1*/
+	pidcount=0;
+	if(my_rank!=0){
+		for(i=0;i<my_rank;i++){
+			pidcount+=allpidcount[i];
+		}
+	}
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->OffsetPids(pidcount);
+	}
+
+	/* Finally, remember that cpus may have skipped some objects, because they were clones. For every 
+	 * object that is not a clone, tell them to show their pids, so that later on, they can get picked 
+	 * up by their clones: */
+	truepids   =xNewZeroInit<int>(numberofobjects);
+	alltruepids=xNewZeroInit<int>(numberofobjects);
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->ShowTruePids(truepids);
+	}
+	ISSM_MPI_Allreduce((void*)truepids,(void*)alltruepids,numberofobjects,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+
+	/* Now every cpu knows the true pids of everyone else that is not a clone*/
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->UpdateClonePids(alltruepids);
+	}
+
+	/* Free ressources: */
+	xDelete<int>(allpidcount);
+	xDelete<int>(truepids);
+	xDelete<int>(alltruepids);
+}
+/*}}}*/
+void  Vertices::FlagClones(int numberofobjects){/*{{{*/
+
+	int i;
+	int num_procs;
+
+	int* ranks=NULL;
+	int* minranks=NULL;
+
+	/*recover num_procs:*/
+	num_procs=IssmComm::GetSize();
+
+	/*Allocate ranks: */
+	ranks=xNew<int>(numberofobjects);
+	minranks=xNew<int>(numberofobjects);
+
+	for(i=0;i<numberofobjects;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
+
+	/*Now go through all our objects and ask them to report to who they belong (which rank): */
+	Ranks(ranks);
+
+	/*We need to take the minimum rank for each vertex, and every cpu needs to get that result. That way, 
+	 * when we start building the dof list for all vertexs, a cpu can check whether its vertex already has been 
+	 * dealt with by another cpu. We take the minimum because we are going to manage dof assignment in increasing 
+	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
+	ISSM_MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
+
+	/*Now go through all objects, and use minranks to flag which objects are cloned: */
+	for(i=0;i<this->Size();i++){
+		/*For this object, decide whether it is a clone: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->SetClone(minranks);
+	}
+
+	/*Free ressources: */
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
+
+}
+/*}}}*/
+int Vertices::NumberOfVertices(void){/*{{{*/
+
+	int i,sid;
+	int max_sid=0;
+	int vertex_max_sid;
+
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		sid=vertex->Sid();
+		if (sid>max_sid)max_sid=sid;
+	}
+
+	ISSM_MPI_Reduce (&max_sid,&vertex_max_sid,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&vertex_max_sid,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	max_sid=vertex_max_sid;
+
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return:*/
+	return max_sid;
+}
+/*}}}*/
+void   Vertices::Ranks(int* ranks){/*{{{*/
+
+	int my_rank;
+	int        sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Go through a dataset, and for each object, report it cpu: */
+	for(int i=0;i<this->Size();i++){
+		/*Plug rank into ranks, according to id: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		sid=vertex->Sid();
+		ranks[sid]=my_rank; 
+	}
+}
+/*}}}*/
+IssmDouble* Vertices::ToXYZ(void){/*{{{*/
+
+	/*intermediary: */
+	int i;
+	int my_rank;
+	int num_vertices;
+
+	/*output: */
+	Matrix<IssmDouble>* xyz = NULL;
+	IssmDouble* xyz_serial=NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*First, figure out number of vertices: */
+	num_vertices=this->NumberOfVertices();
+
+	/*Now, allocate matrix to hold all the vertices x,y and z values: */
+	xyz= new Matrix<IssmDouble>(num_vertices,3);
+
+	/*Go through vertices, and for each vertex, object, report it cpu: */
+	for(i=0;i<this->Size();i++){
+
+		/*let vertex fill matrix: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->ToXYZ(xyz);
+	}
+
+	/*Assemble:*/
+	xyz->Assemble();
+
+	/*gather on cpu 0: */
+	xyz_serial=xyz->ToSerial();
+
+	/*free ressources: */
+	delete xyz;
+	if(my_rank!=0)delete xyz_serial;
+
+	/*return matrix: */
+	return xyz_serial;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/Vertices.h	(revision 18231)
@@ -0,0 +1,30 @@
+#ifndef _CONTAINER_VERTICES_H_
+#define  _CONTAINER_VERTICES_H_
+
+/*forward declarations */
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+
+/*!\brief Declaration of Vertices class.
+ *
+ * Declaration of Vertices class.  Vertices are vector lists (Containers) of Vertex objects.
+ * A vertex is a set of (x,y,z) coordinates defining the location of points in the mesh (not
+ * to be confused with a node, which is a degree of freedom (DOF) for a particular analysis).
+ */ 
+class Vertices: public DataSet{
+
+	public:
+
+		/*constructors, destructors:*/ 
+		Vertices();
+		~Vertices();
+
+		/*numerics:*/
+		void  DistributePids(int numberofnodes);
+		void  FlagClones(int numberofnodes);
+		int   NumberOfVertices(void);
+		void  Ranks(int* ranks);
+		IssmDouble* ToXYZ(void);
+};
+
+#endif //ifndef _VERTICES_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/classes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/classes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/classes.h	(revision 18231)
@@ -0,0 +1,121 @@
+/* \file classes.h
+ * \brief: prototype header for all classes used in ISSM.
+ */
+
+#ifndef _ALL_CLASSES_H_
+#define _ALL_CLASSES_H_
+
+/*Objects: */
+#include "./Contour.h"
+#include "./Vertices.h"
+#include "./Vertex.h"
+#include "./Nodes.h"
+#include "./Contours.h"
+#include "./Node.h"
+#include "./Profiler.h"
+#include "./DependentObject.h"
+#include "./IndependentObject.h"
+#include "./Segment.h"
+#include "./Massfluxatgate.h"
+#include "./Misfit.h"
+
+/*Constraints: */
+#include "./Constraints/Constraints.h"
+#include "./Constraints/Constraint.h"
+#include "./Constraints/SpcStatic.h"
+#include "./Constraints/SpcTransient.h"
+#include "./Constraints/SpcDynamic.h"
+
+/*Loads: */
+#include "./Loads/Loads.h"
+#include "./Loads/Load.h"
+#include "./Loads/Friction.h"
+#include "./Loads/Numericalflux.h"
+#include "./Loads/Riftfront.h"
+#include "./Loads/Penpair.h"
+#include "./Loads/Pengrid.h"
+
+/*Elements: */
+#include "./Elements/Elements.h"
+#include "./Elements/Element.h"
+#include "./Elements/Penta.h"
+#include "./Elements/PentaRef.h"
+#include "./Elements/Seg.h"
+#include "./Elements/SegRef.h"
+#include "./Elements/Tria.h"
+#include "./Elements/TriaRef.h"
+#include "./Elements/Tetra.h"
+#include "./Elements/TetraRef.h"
+#include "./Elements/ElementHook.h"
+
+/*Option parsing objects: */
+#include "./Options/Option.h"
+#include "./Options/Options.h"
+#include "./Options/GenericOption.h"
+#include "./Options/OptionUtilities.h"
+
+/*Inputs: */
+#include "./Inputs/Inputs.h"
+#include "./Inputs/Input.h"
+#include "./Inputs/BoolInput.h"
+#include "./Inputs/DoubleInput.h"
+#include "./Inputs/IntInput.h"
+#include "./Inputs/TetraInput.h"
+#include "./Inputs/PentaInput.h"
+#include "./Inputs/TriaInput.h"
+#include "./Inputs/SegInput.h"
+#include "./Inputs/ControlInput.h"
+#include "./Inputs/DatasetInput.h"
+#include "./Inputs/TransientInput.h"
+
+/*ExternalResults: */
+#include "./ExternalResults/Results.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/GenericExternalResult.h"
+
+/*Materials: */
+#include "./Materials/Materials.h"
+#include "./Materials/Material.h"
+#include "./Materials/Matice.h"
+#include "./Materials/Matpar.h"
+
+/*Params: */
+#include "./Params/GenericParam.h"
+#include "./Params/BoolParam.h"
+#include "./Params/DoubleMatParam.h"
+#include "./Params/DoubleTransientMatParam.h"
+#include "./Params/DoubleMatArrayParam.h"
+#include "./Params/DoubleParam.h"
+#include "./Params/DoubleVecParam.h"
+#include "./Params/IntParam.h"
+#include "./Params/IntVecParam.h"
+#include "./Params/IntMatParam.h"
+#include "./Params/FileParam.h"
+#include "./Params/Parameters.h"
+#include "./Params/Param.h"
+#include "./Params/MatrixParam.h"
+#include "./Params/VectorParam.h"
+#include "./Params/StringArrayParam.h"
+#include "./Params/StringParam.h"
+#include "./Params/TransientParam.h"
+#include "./Params/DataSetParam.h"
+
+/*matrix: */
+#include "./matrix/matrixobjects.h"
+
+/*gauss: */
+#include "./gauss/gaussobjects.h"
+
+/*kriging: */
+#include "./kriging/krigingobjects.h"
+
+/*diverse: */
+#include "./Hook.h"
+#include "./DofIndexing.h"
+#include "./IoModel.h"
+#include "./Update.h"
+#include "./FemModel.h"
+#include "./GiaDeflectionCoreArgs.h"
+#include "./RiftStruct.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/Gauss.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/Gauss.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/Gauss.h	(revision 18231)
@@ -0,0 +1,24 @@
+/*!\file Gauss.h
+ * \brief: header file for vvirtual Gauss object
+ */
+
+#ifndef _GAUSS_H_
+#define _GAUSS_H_
+
+class Gauss{
+
+	public: 
+		IssmDouble   weight;
+
+		virtual        ~Gauss(){};
+		virtual int  begin(void)=0;
+		virtual int  end(void)=0;
+		virtual void Echo(void)=0;
+		virtual int  Enum(void)=0;
+		virtual void GaussPoint(int ig)=0;
+		virtual void GaussVertex(int iv)=0;
+		virtual void GaussNode(int finitelement,int iv)=0;
+		virtual void SynchronizeGaussBase(Gauss* gauss)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.cpp	(revision 18231)
@@ -0,0 +1,759 @@
+/*!\file GaussPenta.c
+ * \brief: implementation of the GaussPenta object
+ */
+
+#include "./GaussPenta.h"
+#include "./GaussTria.h"
+#include "../../shared/io/Print/Print.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Numerics/GaussPoints.h"
+#include "../../shared/Numerics/constants.h"
+
+/*GaussPenta constructors and destructors:*/
+GaussPenta::GaussPenta(){/*{{{*/
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+	coords4=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+GaussPenta::GaussPenta(int order_horiz,int order_vert){/*{{{*/
+
+	/*Intermediaries*/
+	int     ighoriz,igvert;
+	int     numgauss_horiz;
+	int     numgauss_vert;
+	IssmDouble *coords1_horiz = NULL;
+	IssmDouble *coords2_horiz = NULL;
+	IssmDouble *coords3_horiz = NULL;
+	IssmDouble *weights_horiz  = NULL;
+	double *coords_vert = NULL;
+	double *weights_vert   = NULL;
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss_horiz,&coords1_horiz,&coords2_horiz,&coords3_horiz,&weights_horiz,order_horiz);
+	GaussLegendreLinear(&coords_vert,&weights_vert,order_vert);
+	numgauss_vert=order_vert;
+
+	/*Allocate GaussPenta fields*/
+	numgauss=numgauss_horiz*numgauss_vert;
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Combine Horizontal and vertical points*/
+	for (ighoriz=0; ighoriz<numgauss_horiz; ighoriz++){
+		for (igvert=0; igvert<numgauss_vert; igvert++){
+			coords1[numgauss_vert*ighoriz+igvert]=coords1_horiz[ighoriz];
+			coords2[numgauss_vert*ighoriz+igvert]=coords2_horiz[ighoriz];
+			coords3[numgauss_vert*ighoriz+igvert]=coords3_horiz[ighoriz];
+			coords4[numgauss_vert*ighoriz+igvert]=coords_vert[igvert];
+			weights[numgauss_vert*ighoriz+igvert]=weights_horiz[ighoriz]*weights_vert[igvert];
+		}
+	}
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+
+	/*Clean up*/
+	xDelete<IssmDouble>(coords1_horiz);
+	xDelete<IssmDouble>(coords2_horiz);
+	xDelete<IssmDouble>(coords3_horiz);
+	xDelete<double>(coords_vert);
+	xDelete<IssmDouble>(weights_horiz);
+	xDelete<double>(weights_vert);
+}
+/*}}}*/
+GaussPenta::GaussPenta(int index1, int index2,int order){/*{{{*/
+
+	/*Intermediaties*/
+	double *seg_coords  = NULL;
+	double *seg_weights = NULL;
+	int     i;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussPenta fields*/
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	if(index1==0 && index2==3){
+		for(i=0;i<numgauss;i++) coords1[i]=1.0;
+		for(i=0;i<numgauss;i++) coords2[i]=0.0;
+		for(i=0;i<numgauss;i++) coords3[i]=0.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==1 && index2==4){
+		for(i=0;i<numgauss;i++) coords1[i]=0.0;
+		for(i=0;i<numgauss;i++) coords2[i]=1.0;
+		for(i=0;i<numgauss;i++) coords3[i]=0.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==2 && index2==5){
+		for(i=0;i<numgauss;i++) coords1[i]=0.0;
+		for(i=0;i<numgauss;i++) coords2[i]=0.0;
+		for(i=0;i<numgauss;i++) coords3[i]=1.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else{
+		_error_("Penta not supported yet");
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+
+	/*clean up*/
+	xDelete<double>(seg_coords);
+	xDelete<double>(seg_weights);
+
+}
+/*}}}*/
+GaussPenta::GaussPenta(int index1, int index2, int index3, int order){/*{{{*/
+
+	/*Basal Tria*/
+	if(index1==0 && index2==1 && index3==2){
+
+		/*Get GaussTria*/
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+		/*compute z coordinate*/
+		coords4=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
+	}
+	/*Upper surface Tria*/
+	else if(index1==3 && index2==4 && index3==5){
+
+		/*Get GaussTria*/
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+		/*compute z coordinate*/
+		coords4=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=1.0;
+	}
+	else{
+		_error_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){/*{{{*/
+
+	/*Intermediaties*/
+	double *seg_horiz_coords  = NULL;
+	double *seg_horiz_weights = NULL;
+	double *seg_vert_coords   = NULL;
+	double *seg_vert_weights  = NULL;
+	int     i,j;
+
+	/*get the gauss points using the product of two line rules*/
+	GaussLegendreLinear(&seg_horiz_coords,&seg_horiz_weights,order_horiz);
+	GaussLegendreLinear(&seg_vert_coords, &seg_vert_weights, order_vert);
+
+	/*Allocate GaussPenta fields*/
+	numgauss=order_horiz*order_vert;
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Quads: get the gauss points using the product of two line rules  */
+	if(index1==0 && index2==1 && index3==4 && index4==3){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords2[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords3[i*order_vert+j]=0.0;
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else if(index1==1 && index2==2 && index3==5 && index4==4){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=0.0;
+				coords2[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords3[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else if(index1==2 && index2==0 && index3==3 && index4==5){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords2[i*order_vert+j]=0.0;
+				coords3[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else{
+		_error_("Tria not supported yet (user provided indices " << index1 << " " << index2 << " " << index3 << " " << index4 << ")");
+	}
+
+	/*clean-up*/
+	xDelete<double>(seg_horiz_coords);
+	xDelete<double>(seg_horiz_weights);
+	xDelete<double>(seg_vert_coords);
+	xDelete<double>(seg_vert_weights);
+}
+/*}}}*/
+GaussPenta::GaussPenta(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){/*{{{*/
+
+	/*
+	 *  ^ 
+	 *  |
+	 * 1|\
+	 *  |  \
+	 *  |    \
+	 *  |      \
+	 *  |        \
+	 *  |          \
+	 *  |    +(x,y)  \
+	 *  |              \
+	 *  +---------------+-->
+	 *  0               1
+	 *
+	 */
+	int         ig;
+	IssmDouble x,y;
+	IssmDouble xy_list[3][2];
+
+	if(mainlyfloating){
+		/*Get gauss points*/
+		GaussLegendreTria(&this->numgauss,&this->coords1,&this->coords2,&this->coords3,&this->weights,order);
+
+		xy_list[0][0]=0;  xy_list[0][1]=0; 
+		xy_list[1][0]=r1; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+		for(ig=0;ig<this->numgauss;ig++){
+			x = this->coords1[ig]*xy_list[0][0] + this->coords2[ig]*xy_list[1][0] + this->coords3[ig]*xy_list[2][0];
+			y = this->coords1[ig]*xy_list[0][1] + this->coords2[ig]*xy_list[1][1] + this->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					this->coords1[ig] = 1.-x-y;
+					this->coords2[ig] = x;
+					this->coords3[ig] = y;
+					break;
+				case 1:
+					this->coords1[ig] = y;
+					this->coords2[ig] = 1.-x-y;
+					this->coords3[ig] = x;
+					break;
+				case 2:
+					this->coords1[ig] = x;
+					this->coords2[ig] = y;
+					this->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			this->weights[ig] = this->weights[ig]*r1*r2;
+			this->coords4=xNew<IssmDouble>(numgauss);
+			for(ig=0;ig<numgauss;ig++) this->coords4[ig]=-1.0;
+		}
+	}
+	else{
+		/*Double number of gauss points*/
+		GaussPenta *gauss1    = NULL;
+		GaussPenta *gauss2    = NULL;
+		gauss1=new GaussPenta(0,1,2,order);
+		gauss2=new GaussPenta(0,1,2,order);
+
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=0;  xy_list[1][1]=1.; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+			//gauss1->Echo();
+		for(ig=0;ig<gauss1->numgauss;ig++){
+			x = gauss1->coords1[ig]*xy_list[0][0] + gauss1->coords2[ig]*xy_list[1][0] + gauss1->coords3[ig]*xy_list[2][0];
+			y = gauss1->coords1[ig]*xy_list[0][1] + gauss1->coords2[ig]*xy_list[1][1] + gauss1->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss1->coords1[ig] = 1.-x-y;
+					gauss1->coords2[ig] = x;
+					gauss1->coords3[ig] = y;
+					break;
+				case 1:
+					gauss1->coords1[ig] = y;
+					gauss1->coords2[ig] = 1.-x-y;
+					gauss1->coords3[ig] = x;
+					break;
+				case 2:
+					gauss1->coords1[ig] = x;
+					gauss1->coords2[ig] = y;
+					gauss1->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss1->weights[ig] = gauss1->weights[ig]*r1*(1-r2);
+		}
+			//gauss1->Echo();
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=1.; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=1.; 
+
+			//gauss2->Echo();
+		for(ig=0;ig<gauss2->numgauss;ig++){
+			x = gauss2->coords1[ig]*xy_list[0][0] + gauss2->coords2[ig]*xy_list[1][0] + gauss2->coords3[ig]*xy_list[2][0];
+			y = gauss2->coords1[ig]*xy_list[0][1] + gauss2->coords2[ig]*xy_list[1][1] + gauss2->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss2->coords1[ig] = 1.-x-y;
+					gauss2->coords2[ig] = x;
+					gauss2->coords3[ig] = y;
+					break;
+				case 1:
+					gauss2->coords1[ig] = y;
+					gauss2->coords2[ig] = 1.-x-y;
+					gauss2->coords3[ig] = x;
+					break;
+				case 2:
+					gauss2->coords1[ig] = x;
+					gauss2->coords2[ig] = y;
+					gauss2->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss2->weights[ig] = gauss2->weights[ig]*(1-r1);
+		}
+
+		this->numgauss = gauss1->numgauss + gauss2->numgauss;
+		this->coords1=xNew<IssmDouble>(this->numgauss);
+		this->coords2=xNew<IssmDouble>(this->numgauss);
+		this->coords3=xNew<IssmDouble>(this->numgauss);
+		this->coords4=xNew<IssmDouble>(this->numgauss);
+		this->weights=xNew<IssmDouble>(this->numgauss);
+
+		for(ig=0;ig<gauss1->numgauss;ig++){ // Add the first triangle gauss points
+			this->coords1[ig]=gauss1->coords1[ig];
+			this->coords2[ig]=gauss1->coords2[ig];
+			this->coords3[ig]=gauss1->coords3[ig];
+			this->coords4[ig]=gauss1->coords4[ig];
+			this->weights[ig]=gauss1->weights[ig];
+		}
+		for(ig=0;ig<gauss2->numgauss;ig++){ // Add the second triangle gauss points
+			this->coords1[gauss1->numgauss+ig]=gauss2->coords1[ig];
+			this->coords2[gauss1->numgauss+ig]=gauss2->coords2[ig];
+			this->coords3[gauss1->numgauss+ig]=gauss2->coords3[ig];
+			this->coords4[gauss1->numgauss+ig]=gauss2->coords4[ig];
+			this->weights[gauss1->numgauss+ig]=gauss2->weights[ig];
+		}
+
+		/*Delete gauss points*/
+		delete gauss1;
+		delete gauss2;
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){/*{{{*/
+
+	/*Intermediaties*/
+	IssmPDouble *seg_horiz_coords  = NULL;
+	IssmPDouble *seg_horiz_weights = NULL;
+	IssmPDouble *seg_vert_coords   = NULL;
+	IssmPDouble *seg_vert_weights  = NULL;
+
+	/*get the gauss points using the product of two line rules*/
+	GaussLegendreLinear(&seg_horiz_coords,&seg_horiz_weights,order_horiz);
+	GaussLegendreLinear(&seg_vert_coords, &seg_vert_weights, order_vert);
+
+	/*Allocate GaussPenta fields*/
+	numgauss=order_horiz*order_vert;
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Quads: get the gauss points using the product of two line rules  */
+	for(int i=0;i<order_horiz;i++){
+		for(int j=0;j<order_vert;j++){
+			coords1[i*order_vert+j]=0.5*(area_coordinates[0][0]+area_coordinates[1][0]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][0]-area_coordinates[0][0]);
+			coords2[i*order_vert+j]=0.5*(area_coordinates[0][1]+area_coordinates[1][1]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][1]-area_coordinates[0][1]);
+			coords3[i*order_vert+j]=0.5*(area_coordinates[0][2]+area_coordinates[1][2]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][2]-area_coordinates[0][2]);
+			coords4[i*order_vert+j]=seg_vert_coords[j];
+			weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+		}
+	}
+
+	/*clean-up*/
+	xDelete<IssmPDouble>(seg_horiz_coords);
+	xDelete<IssmPDouble>(seg_horiz_weights);
+	xDelete<IssmPDouble>(seg_vert_coords);
+	xDelete<IssmPDouble>(seg_vert_weights);
+}
+/*}}}*/
+GaussPenta::~GaussPenta(){/*{{{*/
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+	xDelete<IssmDouble>(coords2);
+	xDelete<IssmDouble>(coords3);
+	xDelete<IssmDouble>(coords4);
+}
+/*}}}*/
+
+/*Methods*/
+void GaussPenta::Echo(void){/*{{{*/
+
+	_printf_("GaussPenta:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
+
+	if (weights){
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
+	if (coords1){
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords1 = NULL\n");
+	if (coords2){
+	 _printf_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords2[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords2 = NULL\n");
+	if (coords3){
+	 _printf_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords3[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords3 = NULL\n");
+	if (coords4){
+		_printf_("   coords4 = ["); 
+		for(int i=0;i<numgauss;i++) _printf_(" " << coords4[i] << "\n");
+		_printf_("]\n");
+	}
+	else _printf_("coords4 = NULL\n");
+
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+	_printf_("   coord2 = " << coord2 << "\n");
+	_printf_("   coord3 = " << coord3 << "\n");
+	_printf_("   coord4 = " << coord4 << "\n");
+
+}
+/*}}}*/
+int GaussPenta::Enum(void){/*{{{*/
+	return GaussPentaEnum;
+}
+/*}}}*/
+void GaussPenta::GaussPoint(int ig){/*{{{*/
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+	 coord4=coords4[ig];
+
+}
+/*}}}*/
+void GaussPenta::GaussVertex(int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0: coord1=1.; coord2=0.; coord3=0.; coord4= -1.; break;
+		case 1: coord1=0.; coord2=1.; coord3=0.; coord4= -1.; break;
+		case 2: coord1=0.; coord2=0.; coord3=1.; coord4= -1.; break;
+		case 3: coord1=1.; coord2=0.; coord3=0.; coord4= +1.; break;
+		case 4: coord1=0.; coord2=1.; coord3=0.; coord4= +1.; break;
+		case 5: coord1=0.; coord2=0.; coord3=1.; coord4= +1.; break;
+		default: _error_("vertex index should be in [0 5]");
+
+	}
+
+}
+/*}}}*/
+void GaussPenta::GaussFaceTria(int index1, int index2, int index3, int order){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*Basal Tria*/
+	if(index1==0 && index2==1 && index3==2){
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+		coords4=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
+	}
+	else{
+		_error_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+void GaussPenta::GaussNode(int finiteelement,int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+				default: _error_("node index should be in [0 5]");
+			}
+			break;
+		case P1xP2Enum: 
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+				default: _error_("node index should be in [0 8]");
+			}
+			break;
+		case P1xP3Enum: 
+			switch(iv){
+				case 0 : coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1 : coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2 : coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3 : coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4 : coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5 : coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6 : coord1=1.; coord2=0.; coord3=0.; coord4=-1./3.; break;
+				case 7 : coord1=0.; coord2=1.; coord3=0.; coord4=-1./3.; break;
+				case 8 : coord1=0.; coord2=0.; coord3=1.; coord4=-1./3.; break;
+				case 9 : coord1=1.; coord2=0.; coord3=0.; coord4=+1./3.; break;
+				case 10: coord1=0.; coord2=1.; coord3=0.; coord4=+1./3.; break;
+				case 11: coord1=0.; coord2=0.; coord3=1.; coord4=+1./3.; break;
+				default: _error_("node index should be in [0 11]");
+			}
+			break;
+		case P2xP1Enum: 
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case  6: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case  7: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case  8: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+				default: _error_("node index should be in [0 11]");
+			}
+			break;
+		case P1bubbleEnum:  case P1bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.;    coord2=0.;    coord3=0.;    coord4=-1.; break;
+				case 1: coord1=0.;    coord2=1.;    coord3=0.;    coord4=-1.; break;
+				case 2: coord1=0.;    coord2=0.;    coord3=1.;    coord4=-1.; break;
+				case 3: coord1=1.;    coord2=0.;    coord3=0.;    coord4=+1.; break;
+				case 4: coord1=0.;    coord2=1.;    coord3=0.;    coord4=+1.; break;
+				case 5: coord1=0.;    coord2=0.;    coord3=1.;    coord4=+1.; break;
+				case 6: coord1=1./3.; coord2=1./3.; coord3=1./3.; coord4=0.;  break;
+				default: _error_("node index should be in [0 6]");
+			}
+			break;
+		case P2Enum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case 12: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 13: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 14: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+
+				case 15: coord1=0.; coord2=.5; coord3=.5; coord4=0.;break;
+				case 16: coord1=.5; coord2=0.; coord3=.5; coord4=0.;break;
+				case 17: coord1=.5; coord2=.5; coord3=0.; coord4=0.;break;
+				default: _error_("node index should be in [0 17]");
+			}
+			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case 12: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 13: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 14: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+
+				case 15: coord1=0.; coord2=.5; coord3=.5; coord4=0.;break;
+				case 16: coord1=.5; coord2=0.; coord3=.5; coord4=0.;break;
+				case 17: coord1=.5; coord2=.5; coord3=0.; coord4=0.;break;
+
+				case 18: coord1=1./3.; coord2=1./3.; coord3=1./3.; coord4=0.;  break;
+				default: _error_("node index should be in [0 18]");
+			}
+			break;
+		case P2xP4Enum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case 12: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 13: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 14: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+
+				case 15: coord1=1.; coord2=0.; coord3=0.; coord4=-.5; break;
+				case 16: coord1=0.; coord2=1.; coord3=0.; coord4=-.5; break;
+				case 17: coord1=0.; coord2=0.; coord3=1.; coord4=-.5; break;
+				case 18: coord1=1.; coord2=0.; coord3=0.; coord4=+.5; break;
+				case 19: coord1=0.; coord2=1.; coord3=0.; coord4=+.5; break;
+				case 20: coord1=0.; coord2=0.; coord3=1.; coord4=+.5; break;
+
+				case 21: coord1=0.; coord2=.5; coord3=.5; coord4=-.5;break;
+				case 22: coord1=.5; coord2=0.; coord3=.5; coord4=-.5;break;
+				case 23: coord1=.5; coord2=.5; coord3=0.; coord4=-.5;break;
+				case 24: coord1=0.; coord2=.5; coord3=.5; coord4=0.;break;
+				case 25: coord1=.5; coord2=0.; coord3=.5; coord4=0.;break;
+				case 26: coord1=.5; coord2=.5; coord3=0.; coord4=0.;break;
+				case 27: coord1=0.; coord2=.5; coord3=.5; coord4=+.5;break;
+				case 28: coord1=.5; coord2=0.; coord3=.5; coord4=+.5;break;
+				case 29: coord1=.5; coord2=.5; coord3=0.; coord4=+.5;break;
+				default: _error_("node index should be in [0 29]");
+			}
+			break;
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
+	}
+
+}
+/*}}}*/
+int GaussPenta::begin(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+int GaussPenta::end(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+void GaussPenta::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	GaussTria* gauss_tria = dynamic_cast<GaussTria*>(gauss);
+
+	gauss_tria->coord1=this->coord1;
+	gauss_tria->coord2=this->coord2;
+	gauss_tria->coord3=this->coord3;
+	gauss_tria->weight=UNDEF;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussPenta.h	(revision 18231)
@@ -0,0 +1,52 @@
+/*!\file GaussPenta.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSPENTA_H_
+#define _GAUSSPENTA_H_
+
+/*Headers:*/
+#include "../../shared/Numerics/types.h"
+#include "./Gauss.h"
+class GaussTria;
+
+class GaussPenta: public Gauss{
+
+	private:
+		int numgauss;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+		IssmDouble* coords2;
+		IssmDouble* coords3;
+		IssmDouble* coords4;
+
+	public:
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble coord3;
+		IssmDouble coord4;
+
+	public:
+
+		/*GaussPenta constructors, destructors*/
+		GaussPenta();
+		GaussPenta(int order_horiz,int order_vert);
+		GaussPenta(int index1, int index2,int order);
+		GaussPenta(int index1, int index2, int index3, int order);
+		GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert);
+		GaussPenta(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
+		GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert);
+		~GaussPenta();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		int  Enum(void);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussNode(int finitelement,int iv);
+		void GaussFaceTria(int index1, int index2, int index3, int order);
+		void SynchronizeGaussBase(Gauss* gauss);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.cpp	(revision 18231)
@@ -0,0 +1,169 @@
+/*!\file GaussSeg.c
+ * \brief: implementation of the GaussSeg object
+ */
+
+#include "./GaussSeg.h"
+#include "../../shared/io/Print/Print.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Numerics/GaussPoints.h"
+#include "../../shared/Numerics/constants.h"
+
+/*GaussSeg constructors and destructors:*/
+GaussSeg::GaussSeg(){/*{{{*/
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+}
+/*}}}*/
+GaussSeg::GaussSeg(int order){/*{{{*/
+
+	IssmPDouble* pcoords1=NULL;
+	IssmPDouble* pweights=NULL;
+
+	/*Get gauss points*/
+	this->numgauss = order;
+	GaussLegendreLinear(&pcoords1,&pweights,order);
+	
+	this->coords1=xNew<IssmDouble>(numgauss);
+	this->weights=xNew<IssmDouble>(numgauss);
+
+	/*cast : */
+	for(int i=0;i<numgauss;i++){
+		this->coords1[i]=pcoords1[i];
+		this->weights[i]=pweights[i];
+	}
+
+	/*Free ressources: */
+	xDelete<IssmPDouble>(pcoords1);
+	xDelete<IssmPDouble>(pweights);
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+}
+/*}}}*/
+GaussSeg::GaussSeg(IssmDouble position){/*{{{*/
+
+	/*Get gauss points*/
+	this->numgauss = 1;
+	this->coords1=xNew<IssmDouble>(numgauss);
+	this->weights=xNew<IssmDouble>(numgauss);
+
+	/*cast : */
+	_assert_(position>=-1. && position<=+1.);
+	this->coords1[0]=position;
+	this->weights[0]=1.;
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+}
+/*}}}*/
+GaussSeg::~GaussSeg(){/*{{{*/
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+}
+/*}}}*/
+
+/*Methods*/
+void GaussSeg::Echo(void){/*{{{*/
+
+	_printf_("GaussSeg:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
+
+	if (weights){
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
+	if (coords1){
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+
+}
+/*}}}*/
+int GaussSeg::Enum(void){/*{{{*/
+	return GaussSegEnum;
+}
+/*}}}*/
+void GaussSeg::GaussPoint(int ig){/*{{{*/
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+}
+/*}}}*/
+void GaussSeg::GaussVertex(int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0: coord1=-1.; break;
+		case 1: coord1=+1.; break;
+		default: _error_("vertex index should be in [0 1]");
+	}
+}
+/*}}}*/
+void GaussSeg::GaussNode(int finiteelement,int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			switch(iv){
+				case 0: coord1=-1.; break;
+				case 1: coord1=+1.; break;
+				default: _error_("node index should be in [0 1]");
+			}
+			break;
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
+	}
+
+}
+/*}}}*/
+int GaussSeg::begin(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+int GaussSeg::end(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+void GaussSeg::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
+
+	_error_("not supported");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussSeg.h	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file GaussSeg.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSSEG_H_
+#define _GAUSSSEG_H_
+
+/*Headers:*/
+#include "../../shared/Numerics/types.h"
+#include "./Gauss.h"
+
+class GaussSeg: public Gauss{
+
+	private:
+		int numgauss;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+
+	public:
+		IssmDouble coord1;
+
+	public:
+
+		/*GaussSeg constructors, destructors*/
+		GaussSeg();
+		GaussSeg(int order);
+		GaussSeg(IssmDouble position);
+		~GaussSeg();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		int  Enum(void);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussNode(int finitelement,int iv);
+		void SynchronizeGaussBase(Gauss* gauss);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.cpp	(revision 18231)
@@ -0,0 +1,254 @@
+/*!\file GaussTetra.c
+ * \brief: implementation of the GaussTetra object
+ */
+
+#include <math.h>
+#include "./GaussTetra.h"
+#include "../../shared/io/Print/Print.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Numerics/GaussPoints.h"
+#include "../../shared/Numerics/constants.h"
+
+/*GaussTetra constructors and destructors:*/
+GaussTetra::GaussTetra(){/*{{{*/
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+	coords4=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+GaussTetra::GaussTetra(int order){/*{{{*/
+
+	/*Get gauss points*/
+	GaussLegendreTetra(&numgauss,&coords1,&coords2,&coords3,&coords4,&weights,order);
+
+	/*Rescale weights if necessary*/
+	IssmDouble sumweights = 0.;
+	for(int i=0;i<numgauss;i++) sumweights += this->weights[i];
+	if(sumweights==1.){
+		for(int i=0;i<numgauss;i++) this->weights[i] = this->weights[i]/6.; /*rescale volume to 1/6*/
+	}
+
+	/*Check final weights in debugging mode*/
+	#ifdef _ISSM_DEBUG_
+	sumweights = 0.; for(int i=0;i<numgauss;i++) sumweights += this->weights[i];
+	_assert_(sumweights>1./6.-1e-10);
+	_assert_(sumweights<1./6.+1e-10);
+	#endif
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
+GaussTetra::GaussTetra(int index1,int index2,int index3,int order){/*{{{*/
+
+	/*Basal Tria*/
+	if(index1==0 && index2==1 && index3==2){
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+		coords4=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=0.;
+	}
+	else if(index1==0 && index2==3 && index3==1){
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords4,&weights,order);
+		coords3=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords3[i]=0.;
+	}
+	else if(index1==1 && index2==3 && index3==2){
+		GaussLegendreTria(&numgauss,&coords2,&coords3,&coords4,&weights,order);
+		coords1=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords1[i]=0.;
+	}
+	else if(index1==0 && index2==2 && index3==3){
+		GaussLegendreTria(&numgauss,&coords1,&coords3,&coords4,&weights,order);
+		coords2=xNew<IssmDouble>(numgauss);
+		for(int i=0;i<numgauss;i++) coords2[i]=0.;
+	}
+	else{
+		_error_(index1 <<" "<<index2 <<" "<<index3 <<" Not supported yet");
+	}
+}
+/*}}}*/
+GaussTetra::~GaussTetra(){/*{{{*/
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+	xDelete<IssmDouble>(coords2);
+	xDelete<IssmDouble>(coords3);
+	xDelete<IssmDouble>(coords4);
+}
+/*}}}*/
+
+/*Methods*/
+void GaussTetra::Echo(void){/*{{{*/
+
+	_printf_("GaussTetra:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
+
+	if (weights){
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
+	if (coords1){
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords1 = NULL\n");
+	if (coords2){
+	 _printf_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords2[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords2 = NULL\n");
+	if (coords3){
+	 _printf_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords3[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords3 = NULL\n");
+	if (coords4){
+		_printf_("   coords4 = ["); 
+		for(int i=0;i<numgauss;i++) _printf_(" " << coords4[i] << "\n");
+		_printf_("]\n");
+	}
+	else _printf_("coords4 = NULL\n");
+
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+	_printf_("   coord2 = " << coord2 << "\n");
+	_printf_("   coord3 = " << coord3 << "\n");
+	_printf_("   coord4 = " << coord4 << "\n");
+
+}
+/*}}}*/
+int GaussTetra::Enum(void){/*{{{*/
+	return GaussTetraEnum;
+}
+/*}}}*/
+void GaussTetra::GaussPoint(int ig){/*{{{*/
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+	 coord4=coords4[ig];
+
+}
+/*}}}*/
+void GaussTetra::GaussVertex(int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+		case 1: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+		case 2: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+		case 3: coord1=0.; coord2=0.; coord3=0.; coord4=1.; break;
+		default: _error_("vertex index should be in [0 3]");
+
+	}
+
+}
+/*}}}*/
+void GaussTetra::GaussNode(int finiteelement,int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+				case 3: coord1=0.; coord2=0.; coord3=0.; coord4=1.; break;
+				default: _error_("node index should be in [0 3]");
+			}
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+				case 3: coord1=0.; coord2=0.; coord3=0.; coord4=1.; break;
+				case 4: coord1=1./4.; coord2=1./4.; coord3=1./4.; coord4=1./4.; break;
+				default: _error_("node index should be in [0 4]");
+			}
+			break;
+		case P2Enum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+				case 3: coord1=0.; coord2=0.; coord3=0.; coord4=1.; break;
+
+				case 4: coord1=0.; coord2=.5; coord3=.5; coord4=0.; break;
+				case 5: coord1=.5; coord2=0.; coord3=.5; coord4=0.; break;
+				case 6: coord1=.5; coord2=.5; coord3=0.; coord4=0.; break;
+				case 7: coord1=.5; coord2=0.; coord3=0.; coord4=.5; break;
+				case 8: coord1=0.; coord2=.5; coord3=0.; coord4=.5; break;
+				case 9: coord1=0.; coord2=0.; coord3=.5; coord4=.5; break;
+				default: _error_("node index should be in [0 9]");
+			}
+			break;
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
+	}
+
+}
+/*}}}*/
+int GaussTetra::begin(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+int GaussTetra::end(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+void GaussTetra::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
+
+	_error_("not supported");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTetra.h	(revision 18231)
@@ -0,0 +1,46 @@
+/*!\file GaussTetra.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSTETRA_H_
+#define _GAUSSTETRA_H_
+
+/*Headers:*/
+#include "../../shared/Numerics/types.h"
+#include "./Gauss.h"
+
+class GaussTetra: public Gauss{
+
+	private:
+		int numgauss;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+		IssmDouble* coords2;
+		IssmDouble* coords3;
+		IssmDouble* coords4;
+
+	public:
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble coord3;
+		IssmDouble coord4;
+
+	public:
+
+		/*GaussTetra constructors, destructors*/
+		GaussTetra();
+		GaussTetra(int order);
+		GaussTetra(int index1,int index2,int index3,int order);
+		~GaussTetra();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		int  Enum(void);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussNode(int finitelement,int iv);
+		void SynchronizeGaussBase(Gauss* gauss);
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.cpp	(revision 18231)
@@ -0,0 +1,512 @@
+/*!\file GaussTria.c
+ * \brief: implementation of the GaussTria object
+ */
+
+#include "./GaussTria.h"
+#include "../../shared/shared.h"
+
+/*GaussTria constructors and destructors:*/
+GaussTria::GaussTria(){/*{{{*/
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
+GaussTria::GaussTria(int order){/*{{{*/
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+}
+/*}}}*/
+GaussTria::GaussTria(int index1,int index2,int order){/*{{{*/
+
+	/*Intermediaties*/
+	IssmPDouble *seg_coords  = NULL;
+	IssmPDouble *seg_weights = NULL;
+	IssmDouble  a1,b1,c1,a2,b2,c2;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussTria fields*/
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Figure out coords of index1 (a1,b1,c1) and index2 (a2,b2,c2)*/
+	if(index1==0){
+		a1=1; b1=0; c1=0;
+	}
+	else if(index1==1){
+		a1=0; b1=1; c1=0;
+	}
+	else if(index1==2){
+		a1=0; b1=0; c1=1;
+	}
+	else{
+		_error_("First indice provided is not supported yet (user provided " << index1 << ")");
+	}
+	if(index2==0){
+		a2=1; b2=0; c2=0;
+	}
+	else if(index2==1){
+		a2=0; b2=1; c2=0;
+	}
+	else if(index2==2){
+		a2=0; b2=0; c2=1;
+	}
+	else{
+	 _error_("Second indice provided is not supported yet (user provided " << index2 << " )");
+	}
+
+	/*Build Triangle Gauss point*/
+	for(int i=0;i<numgauss;i++){
+		coords1[i]=0.5*(a1+a2) + 0.5*seg_coords[i]*(a2-a1);
+		coords2[i]=0.5*(b1+b2) + 0.5*seg_coords[i]*(b2-b1);
+		coords3[i]=0.5*(c1+c2) + 0.5*seg_coords[i]*(c2-c1);
+		weights[i]=seg_weights[i];
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+	/*clean up*/
+	xDelete<double>(seg_coords);
+	xDelete<double>(seg_weights);
+}
+/*}}}*/
+GaussTria::GaussTria(IssmDouble area_coordinates[2][3],int order){/*{{{*/
+
+	/*Intermediaties*/
+	IssmPDouble *seg_coords  = NULL;
+	IssmPDouble *seg_weights = NULL;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussTria fields*/
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Build Triangle Gauss point*/
+	for(int i=0;i<numgauss;i++){
+		coords1[i]=0.5*(area_coordinates[0][0]+area_coordinates[1][0]) + 0.5*seg_coords[i]*(area_coordinates[1][0]-area_coordinates[0][0]);
+		coords2[i]=0.5*(area_coordinates[0][1]+area_coordinates[1][1]) + 0.5*seg_coords[i]*(area_coordinates[1][1]-area_coordinates[0][1]);
+		coords3[i]=0.5*(area_coordinates[0][2]+area_coordinates[1][2]) + 0.5*seg_coords[i]*(area_coordinates[1][2]-area_coordinates[0][2]);
+		weights[i]=seg_weights[i];
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+	/*clean up*/
+	xDelete<IssmPDouble>(seg_coords);
+	xDelete<IssmPDouble>(seg_weights);
+}
+/*}}}*/
+GaussTria::GaussTria(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){/*{{{*/
+
+	/*
+	 *  ^ 
+	 *  |
+	 * 1|\
+	 *  |  \
+	 *  |    \
+	 *  |      \
+	 *  |        \
+	 *  |          \
+	 *  |    +(x,y)  \
+	 *  |              \
+	 *  +---------------+-->
+	 *  0               1
+	 *
+	 */
+	int         ig;
+	IssmDouble x,y;
+	IssmDouble xy_list[3][2];
+
+	if(mainlyfloating){
+		/*Get gauss points*/
+		GaussLegendreTria(&this->numgauss,&this->coords1,&this->coords2,&this->coords3,&this->weights,order);
+
+		xy_list[0][0]=0;  xy_list[0][1]=0; 
+		xy_list[1][0]=r1; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+		for(ig=0;ig<this->numgauss;ig++){
+			x = this->coords1[ig]*xy_list[0][0] + this->coords2[ig]*xy_list[1][0] + this->coords3[ig]*xy_list[2][0];
+			y = this->coords1[ig]*xy_list[0][1] + this->coords2[ig]*xy_list[1][1] + this->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					this->coords1[ig] = 1.-x-y;
+					this->coords2[ig] = x;
+					this->coords3[ig] = y;
+					break;
+				case 1:
+					this->coords1[ig] = y;
+					this->coords2[ig] = 1.-x-y;
+					this->coords3[ig] = x;
+					break;
+				case 2:
+					this->coords1[ig] = x;
+					this->coords2[ig] = y;
+					this->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			this->weights[ig] = this->weights[ig]*r1*r2;
+		}
+	}
+	else{
+		/*Double number of gauss points*/
+		GaussTria *gauss1    = NULL;
+		GaussTria *gauss2    = NULL;
+		gauss1=new GaussTria(order);
+		gauss2=new GaussTria(order);
+
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=0;  xy_list[1][1]=1.; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+			//gauss1->Echo();
+		for(ig=0;ig<gauss1->numgauss;ig++){
+			x = gauss1->coords1[ig]*xy_list[0][0] + gauss1->coords2[ig]*xy_list[1][0] + gauss1->coords3[ig]*xy_list[2][0];
+			y = gauss1->coords1[ig]*xy_list[0][1] + gauss1->coords2[ig]*xy_list[1][1] + gauss1->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss1->coords1[ig] = 1.-x-y;
+					gauss1->coords2[ig] = x;
+					gauss1->coords3[ig] = y;
+					break;
+				case 1:
+					gauss1->coords1[ig] = y;
+					gauss1->coords2[ig] = 1.-x-y;
+					gauss1->coords3[ig] = x;
+					break;
+				case 2:
+					gauss1->coords1[ig] = x;
+					gauss1->coords2[ig] = y;
+					gauss1->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss1->weights[ig] = gauss1->weights[ig]*r1*(1-r2);
+		}
+			//gauss1->Echo();
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=1.; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=1.; 
+
+			//gauss2->Echo();
+		for(ig=0;ig<gauss2->numgauss;ig++){
+			x = gauss2->coords1[ig]*xy_list[0][0] + gauss2->coords2[ig]*xy_list[1][0] + gauss2->coords3[ig]*xy_list[2][0];
+			y = gauss2->coords1[ig]*xy_list[0][1] + gauss2->coords2[ig]*xy_list[1][1] + gauss2->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss2->coords1[ig] = 1.-x-y;
+					gauss2->coords2[ig] = x;
+					gauss2->coords3[ig] = y;
+					break;
+				case 1:
+					gauss2->coords1[ig] = y;
+					gauss2->coords2[ig] = 1.-x-y;
+					gauss2->coords3[ig] = x;
+					break;
+				case 2:
+					gauss2->coords1[ig] = x;
+					gauss2->coords2[ig] = y;
+					gauss2->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss2->weights[ig] = gauss2->weights[ig]*(1-r1);
+		}
+
+		this->numgauss = gauss1->numgauss + gauss2->numgauss;
+		this->coords1=xNew<IssmDouble>(this->numgauss);
+		this->coords2=xNew<IssmDouble>(this->numgauss);
+		this->coords3=xNew<IssmDouble>(this->numgauss);
+		this->weights=xNew<IssmDouble>(this->numgauss);
+
+		for(ig=0;ig<gauss1->numgauss;ig++){ // Add the first triangle gauss points
+			this->coords1[ig]=gauss1->coords1[ig];
+			this->coords2[ig]=gauss1->coords2[ig];
+			this->coords3[ig]=gauss1->coords3[ig];
+			this->weights[ig]=gauss1->weights[ig];
+		}
+		for(ig=0;ig<gauss2->numgauss;ig++){ // Add the second triangle gauss points
+			this->coords1[gauss1->numgauss+ig]=gauss2->coords1[ig];
+			this->coords2[gauss1->numgauss+ig]=gauss2->coords2[ig];
+			this->coords3[gauss1->numgauss+ig]=gauss2->coords3[ig];
+			this->weights[gauss1->numgauss+ig]=gauss2->weights[ig];
+		}
+
+		/*Delete gauss points*/
+		delete gauss1;
+		delete gauss2;
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
+GaussTria::~GaussTria(){/*{{{*/
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords3);
+	xDelete<IssmDouble>(coords2);
+	xDelete<IssmDouble>(coords1);
+
+}
+/*}}}*/
+
+/*Methods*/
+void GaussTria::Echo(void){/*{{{*/
+
+	_printf_("GaussTria:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
+
+	if (weights){
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
+	if (coords1){
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords1 = NULL\n");
+	if (coords2){
+	 _printf_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords2[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords2 = NULL\n");
+	if (coords3){
+	 _printf_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords3[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords3 = NULL\n");
+
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+	_printf_("   coord2 = " << coord2 << "\n");
+	_printf_("   coord3 = " << coord3 << "\n");
+
+}
+/*}}}*/
+int GaussTria::Enum(void){/*{{{*/
+	return GaussTriaEnum;
+}
+/*}}}*/
+void GaussTria::GaussEdgeCenter(int index1,int index2){/*{{{*/
+
+	int     index3;
+
+	/*Reverse index1 and 2 if necessary*/
+	if (index1>index2){
+		index3=index1; index1=index2; index2=index3;
+	}
+
+	/*update static arrays*/
+	if (index1==0 && index2==1){
+		coord1=0.5;
+		coord2=0.5;
+		coord3=0.0;
+	}
+	else if (index1==0 && index2==2){
+		coord1=0.5;
+		coord2=0.0;
+		coord3=0.5;
+	}
+	else if (index1==1 && index2==2){
+		coord1=0.0;
+		coord2=0.5;
+		coord3=0.5;
+	}
+	else
+	 _error_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+
+}
+/*}}}*/
+void GaussTria::GaussPoint(int ig){/*{{{*/
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+
+}
+/*}}}*/
+void GaussTria::GaussFromCoords(IssmDouble x,IssmDouble y,IssmDouble* xyz_list){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble    area = 0;
+	IssmDouble    x1,y1,x2,y2,x3,y3;
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	x1=*(xyz_list+3*0+0); y1=*(xyz_list+3*0+1);
+	x2=*(xyz_list+3*1+0); y2=*(xyz_list+3*1+1);
+	x3=*(xyz_list+3*2+0); y3=*(xyz_list+3*2+1);
+
+	area=(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+
+	/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+	coord1=((x-x3)*(y2-y3)-(x2-x3)*(y-y3))/area;
+
+	/*Get second area coordinate = det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+	coord2=((x1-x3)*(y-y3)-(x-x3)*(y1-y3))/area;
+
+	/*Get third  area coordinate 1-area1-area2: */
+	coord3=1-coord1-coord2;
+
+}
+/*}}}*/
+void GaussTria::GaussVertex(int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0: coord1=1.; coord2=0.; coord3=0.; break;
+		case 1: coord1=0.; coord2=1.; coord3=0.; break;
+		case 2: coord1=0.; coord2=0.; coord3=1.; break;
+		default: _error_("vertex index should be in [0 2]");
+	}
+
+}
+/*}}}*/
+void GaussTria::GaussNode(int finiteelement,int iv){/*{{{*/
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(finiteelement){
+		case P0Enum:
+			switch(iv){
+				case 0: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be 0");
+			}
+			break;
+		case P1Enum: case P1DGEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; break;
+				default: _error_("node index should be in [0 2]");
+			}
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.;    coord2=0.;    coord3=0.;    break;
+				case 1: coord1=0.;    coord2=1.;    coord3=0.;    break;
+				case 2: coord1=0.;    coord2=0.;    coord3=1.;    break;
+				case 3: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be in [0 3]");
+			}
+			break;
+		case P2Enum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; break;
+				case 3: coord1=0.; coord2=.5; coord3=.5; break;
+				case 4: coord1=.5; coord2=0.; coord3=.5; break;
+				case 5: coord1=.5; coord2=.5; coord3=0.; break;
+				default: _error_("node index should be in [0 5]");
+			}
+			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; break;
+				case 3: coord1=0.; coord2=.5; coord3=.5; break;
+				case 4: coord1=.5; coord2=0.; coord3=.5; break;
+				case 5: coord1=.5; coord2=.5; coord3=0.; break;
+				case 6: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be in [0 6]");
+			}
+			break;
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
+	}
+
+}
+/*}}}*/
+int GaussTria::begin(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+int GaussTria::end(void){/*{{{*/
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+void GaussTria::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
+
+	_error_("not supported");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/GaussTria.h	(revision 18231)
@@ -0,0 +1,48 @@
+/*!\file GaussTria.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSTRIA_H_
+#define _GAUSSTRIA_H_
+
+/*Headers:*/
+#include "../../shared/Numerics/types.h"
+#include "./Gauss.h"
+
+class GaussTria: public Gauss{
+
+	private:
+		int numgauss;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+		IssmDouble* coords2;
+		IssmDouble* coords3;
+
+	public:
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble coord3;
+
+	public:
+
+		/*GaussTria constructors, destructors*/
+		GaussTria();
+		GaussTria(int order);
+		GaussTria(int index1,int index2,int order);
+		GaussTria(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
+		GaussTria(IssmDouble area_coordinates[2][3],int order);
+		~GaussTria();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		int  Enum(void);
+		void GaussFromCoords(IssmDouble x1,IssmDouble y1,IssmDouble* xyz_list);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussNode(int finitelement,int iv);
+		void GaussEdgeCenter(int index1,int index2);
+		void SynchronizeGaussBase(Gauss* gauss);
+};
+#endif  /* _GAUSSTRIA_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/gaussobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/gaussobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/gauss/gaussobjects.h	(revision 18231)
@@ -0,0 +1,14 @@
+/* \file gaussobjects.h
+ * \brief: prototype header for all gauss related objects
+ */
+
+#ifndef ALL_GAUSS_OBJECTS_H_
+#define ALL_GAUSS_OBJECTS_H_
+
+#include "./Gauss.h"
+#include "./GaussSeg.h"
+#include "./GaussTria.h"
+#include "./GaussTetra.h"
+#include "./GaussPenta.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 18231)
@@ -0,0 +1,85 @@
+/*!\file ExponentialVariogram.c
+ * \brief: implementation of the ExponentialVariogram object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*ExponentialVariogram constructors and destructor*/
+ExponentialVariogram::ExponentialVariogram(){/*{{{*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+ExponentialVariogram::ExponentialVariogram(Options* options){/*{{{*/
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+ExponentialVariogram::~ExponentialVariogram(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void ExponentialVariogram::Echo(void){/*{{{*/
+	_printf_("ExponentialVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
+}
+/*}}}*/
+
+/*Variogram function*/
+double ExponentialVariogram::Covariance(double deltax,double deltay){/*{{{*/
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,a,cova;
+
+	/*Calculate length*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*If h is too small, return sill*/
+	if(h<0.0000001) return sill;
+
+	/*compute covariance*/
+	a     = 1./3.;
+	cova = (sill-nugget)*exp(-h/(a*range));
+	return cova;
+}
+/*}}}*/
+double ExponentialVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,a,gamma;
+
+	/*Calculate length*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*return semi-variogram*/
+	a     = 1./3.;
+	gamma = (sill-nugget)*(1-exp(-h/(a*range))) + nugget;
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/ExponentialVariogram.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file ExponentialVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _EXPONENTIALVARIOGRAM_H_
+#define _EXPONENTIALVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class ExponentialVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*ExponentialVariogram constructors, destructors*/
+		ExponentialVariogram();
+		ExponentialVariogram(Options* options);
+		~ExponentialVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _EXPONENTIALVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file GaussianVariogram.c
+ * \brief: implementation of the GaussianVariogram object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*GaussianVariogram constructors and destructor*/
+GaussianVariogram::GaussianVariogram(){/*{{{*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+GaussianVariogram::GaussianVariogram(Options* options){/*{{{*/
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+GaussianVariogram::~GaussianVariogram(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void GaussianVariogram::Echo(void){/*{{{*/
+	_printf_("GaussianVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
+}
+/*}}}*/
+
+/*Variogram function*/
+double GaussianVariogram::Covariance(double deltax,double deltay){/*{{{*/
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h2,a,cova;
+
+	/*Calculate length square*/
+	h2=deltax*deltax + deltay*deltay;
+
+	/*If h is too small, return sill*/
+	if(h2<0.0000001) return sill;
+
+	/*compute covariance*/
+	a     = 1./3.;
+	cova = (sill-nugget)*exp(-h2/(a*range*range));
+
+	return cova;
+}
+/*}}}*/
+double GaussianVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h2,a,gamma;
+
+	/*Calculate length square*/
+	h2=deltax*deltax + deltay*deltay;
+
+	/*return semi-variogram*/
+	a     = 1./3.;
+	gamma = (sill-nugget)*(1.-exp(-h2/(a*range*range))) + nugget;
+
+	//if(h2>1000*1000) _printf_("gamma = " << gamma << " h= " << sqrt(h2) << "\n");
+	_printf_("h = " << sqrt(h2) << " gamma = " << gamma << "\n");
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/GaussianVariogram.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file GaussianVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _GAUSSIANVARIOGRAM_H_
+#define _GAUSSIANVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+class Options;
+
+class GaussianVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*GaussianVariogram constructors, destructors*/
+		GaussianVariogram();
+		GaussianVariogram(Options* options);
+		~GaussianVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _GAUSSIANVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.cpp	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file Observation.c
+ * \brief: implementation of the Observation object
+ */
+
+#include <stdlib.h>
+#include "../classes.h"
+
+/*Observation constructors and destructor*/
+Observation::Observation(){/*{{{*/
+	return;
+}
+/*}}}*/
+Observation::Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in){/*{{{*/
+
+	this->x      = x_in;
+	this->y      = y_in;
+	this->xi     = xi_in;
+	this->yi     = yi_in;
+	this->index  = index_in;
+	this->value  = value_in;
+	this->weight = 1.;
+
+}
+/*}}}*/
+Observation::~Observation(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void Observation::Echo(void){/*{{{*/
+
+	_printf_("Observation\n");
+	_printf_("   index : " << this->index << "\n");
+	_printf_("   x     : " << this->x << "\n");
+	_printf_("   y     : " << this->y << "\n");
+	_printf_("   xi    : \n"); printbinary(this->xi); _printf_("\n");
+	_printf_("   yi    : \n"); printbinary(this->yi); _printf_("\n");
+	_printf_("   weight: " << this->weight << "\n");
+	_printf_("   value : " << this->value << "\n");
+}
+/*}}}*/
+
+/*Observations functions*/
+void Observation::WriteXYObs(double* px,double* py,double* pobs){/*{{{*/
+	*px   = this->x;
+	*py   = this->y;
+	*pobs = this->value;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observation.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file Observation.h 
+ *  \brief: header file for Observation object
+ */
+
+#ifndef _OBSERVATION_H_
+#define _OBSERVATION_H_
+
+#include "../../datastructures/datastructures.h"
+
+class Observation: public Object{
+
+	public:
+		double x,y;
+		int    xi,yi;
+		int    index;
+		double weight;
+		double value;
+
+		/*Observation constructors, destructors*/
+		Observation();
+		Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in);
+		~Observation();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho()  {_error_("Not implemented yet"); };
+		int     Id()        {_error_("Not implemented yet"); };
+		int     ObjectEnum(){_error_("Not implemented yet"); };
+		Object *copy()      {_error_("Not implemented yet"); };
+
+		/*Management*/
+		void WriteXYObs(double* px,double* py,double* pobs);
+};
+#endif  /* _OBSERVATION_*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.cpp	(revision 18231)
@@ -0,0 +1,559 @@
+/*
+ * \file Observations.cpp
+ * \brief: Implementation of Observations class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "../Options/Options.h"
+#include "./Observations.h"
+#include "./Observation.h"
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+#include "./Quadtree.h"
+#include "./Variogram.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+Observations::Observations(){/*{{{*/
+	this->quadtree = NULL;
+	return;
+}
+/*}}}*/
+Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){/*{{{*/
+
+	/*Intermediaries*/
+	int          i,maxdepth,level,counter,index;
+	int          xi,yi;
+	IssmPDouble  xmin,xmax,ymin,ymax;
+	IssmPDouble  offset,minlength,minspacing,mintrimming,maxtrimming;
+	Observation *observation = NULL;
+
+	/*Check that observations is not empty*/
+	if(n==0) _error_("No observation found");
+
+	/*Get extrema*/
+	xmin=x[0]; ymin=y[0];
+	xmax=x[0]; ymax=y[0];
+	for(i=1;i<n;i++){
+		xmin=min(xmin,x[i]); ymin=min(ymin,y[i]);
+		xmax=max(xmax,x[i]); ymax=max(ymax,y[i]);
+	}
+	offset=0.05*(xmax-xmin); xmin-=offset; xmax+=offset;
+	offset=0.05*(ymax-ymin); ymin-=offset; ymax+=offset;
+
+	/*Get trimming limits*/
+	options->Get(&mintrimming,"mintrimming",-1.e+21);
+	options->Get(&maxtrimming,"maxtrimming",+1.e+21);
+	options->Get(&minspacing,"minspacing",0.01);
+	if(minspacing<=0) _error_("minspacing must > 0");
+
+	/*Get Minimum box size*/
+	if(options->GetOption("boxlength")){
+		options->Get(&minlength,"boxlength");
+		if(minlength<=0)_error_("boxlength should be a positive number");
+		maxdepth=reCast<int,IssmPDouble>(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
+	}
+	else{
+		maxdepth = 30;
+		minlength=max(xmax-xmin,ymax-ymin)/IssmPDouble((1L<<maxdepth)-1);
+	}
+
+	/*Initialize Quadtree*/
+	_printf0_("Generating quadtree with a maximum box size " << minlength << " (depth=" << maxdepth << ")... ");
+	this->quadtree = new Quadtree(xmin,xmax,ymin,ymax,maxdepth);
+
+	/*Add observations one by one*/
+	counter = 0;
+	for(i=0;i<n;i++){
+
+		/*First check limits*/
+		if(observations_list[i]>maxtrimming) continue;
+		if(observations_list[i]<mintrimming) continue;
+
+		/*First check that this observation is not too close from another one*/
+		this->quadtree->ClosestObs(&index,x[i],y[i]);
+		if(index>=0){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+			if(pow(observation->x-x[i],2)+pow(observation->y-y[i],2) < minspacing) continue;
+		}
+
+		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
+		this->quadtree->QuadtreeDepth2(&level,xi,yi);
+		if((int)level <= maxdepth){
+			observation = new Observation(x[i],y[i],xi,yi,counter++,observations_list[i]);
+			this->quadtree->Add(observation);
+			this->AddObject(observation);
+		}
+		else{
+			/*We need to average with the current observations*/
+			this->quadtree->AddAndAverage(x[i],y[i],observations_list[i]);
+		}
+	}
+	_printf0_("done\n");
+	_printf0_("Initial number of observations: " << n << "\n");
+	_printf0_("  Final number of observations: " << this->quadtree->NbObs << "\n");
+}
+/*}}}*/
+Observations::~Observations(){/*{{{*/
+	delete quadtree;
+	return;
+}
+/*}}}*/
+
+/*Methods*/
+void Observations::ClosestObservation(IssmPDouble *px,IssmPDouble *py,IssmPDouble *pobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){/*{{{*/
+
+	/*Output and Intermediaries*/
+	int          nobs,i,index;
+	IssmPDouble  hmin,h2,hmin2;
+	int         *indices      = NULL;
+	Observation *observation  = NULL;
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*First, find closest point in Quadtree (fast but might not be the true closest obs)*/
+	this->quadtree->ClosestObs(&index,x_interp,y_interp);
+	if(index>=0){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		hmin = sqrt((observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp));
+		if(hmin<radius) radius=hmin;
+	}
+
+	/*Find all observations that are in radius*/
+	this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,radius);
+	for (i=0;i<nobs;i++){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
+		if(i==0){
+			hmin2 = h2;
+			index = indices[i];
+		}
+		else{
+			if(h2<hmin2){
+				hmin2 = h2;
+				index = indices[i];
+			}
+		}
+	}  
+
+	/*Assign output pointer*/
+	if(nobs || hmin==radius){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		*px   = observation->x;
+		*py   = observation->y;
+		*pobs = observation->value;
+	}
+	else{
+		*px   = UNDEF;
+		*py   = UNDEF;
+		*pobs = UNDEF;
+	}
+	xDelete<int>(indices);
+
+}/*}}}*/
+void Observations::Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius){/*{{{*/
+
+	IssmPDouble xi,yi,obs;
+
+	for(int i=0;i<n;i++){
+		this->ClosestObservation(&xi,&yi,&obs,x[i],y[i],radius);
+		if(xi==UNDEF && yi==UNDEF){
+		 distances[i]=UNDEF;
+		}
+		else{
+		 distances[i]=sqrt( (x[i]-xi)*(x[i]-xi) + (y[i]-yi)*(y[i]-yi) );
+		}
+	}
+}/*}}}*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){/*{{{*/
+
+	/*Output and Intermediaries*/
+	bool         stop;
+	int          nobs,tempnobs,i,j,k,n,counter;
+	IssmPDouble  h2,radius2;
+	int         *indices      = NULL;
+	int         *tempindices  = NULL;
+	IssmPDouble *dists        = NULL;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
+	Observation *observation  = NULL;
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0.) radius=this->quadtree->root->length*2.;
+
+	/*Compute radius square*/
+	radius2 = radius*radius;
+
+	/*Find all observations that are in radius*/
+	this->quadtree->RangeSearch(&tempindices,&tempnobs,x_interp,y_interp,radius);
+	if(tempnobs){
+		indices = xNew<int>(tempnobs);
+		dists   = xNew<IssmPDouble>(tempnobs);
+	}
+	nobs = 0;
+	for(i=0;i<tempnobs;i++){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(tempindices[i]));
+		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
+
+		if(nobs==maxdata && h2>radius2) continue;
+		if(nobs<maxdata){
+			indices[nobs]   = tempindices[i];
+			dists[nobs]     = h2;
+			nobs++;
+		}
+		if(nobs==1) continue;
+
+		/*Sort all dists up to now*/
+		n=nobs-1;
+		stop = false;
+		for(k=0;k<n-1;k++){
+			if(h2<dists[k]){
+				counter=1;
+				for(int jj=k;jj<n;jj++){
+					j  = n-counter;
+					dists[j+1]   = dists[j];
+					indices[j+1] = indices[j];
+					counter++;
+				}
+				dists[k]   = h2;
+				indices[k] = tempindices[i];
+				stop = true;
+				break;
+			}
+			if(stop) break;
+		}
+	}  
+	xDelete<IssmPDouble>(dists);
+	xDelete<int>(tempindices);
+
+	if(nobs){
+		/*Allocate vectors*/
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
+
+		/*Loop over all observations and fill in x, y and obs*/
+		for(i=0;i<nobs;i++){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
+		}
+	}
+
+	/*Assign output pointer*/
+	xDelete<int>(indices);
+	*px=x;
+	*py=y;
+	*pobs=obs;
+	*pnobs=nobs;
+}/*}}}*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){/*{{{*/
+
+	/*Output and Intermediaries*/
+	int          nobs;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
+	Observation *observation  = NULL;
+
+	nobs = this->Size();
+
+	if(nobs){
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
+		for(int i=0;i<this->Size();i++){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
+		}
+	}
+
+	/*Assign output pointer*/
+	*px=x;
+	*py=y;
+	*pobs=obs;
+	*pnobs=nobs;
+}/*}}}*/
+void Observations::InterpolationIDW(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,IssmPDouble power){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,n_obs;
+	IssmPDouble prediction;
+	IssmPDouble numerator,denominator,h,weight;
+	IssmPDouble *x   = NULL;
+	IssmPDouble *y   = NULL;
+	IssmPDouble *obs = NULL;
+
+	/*Some checks*/
+	_assert_(maxdata>0);
+	_assert_(pprediction);
+	_assert_(power>0);
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata){
+		prediction = UNDEF; 
+	}
+	else{
+		numerator   = 0.;
+		denominator = 0.;
+		for(i=0;i<n_obs;i++){
+			h = sqrt( (x[i]-x_interp)*(x[i]-x_interp) + (y[i]-y_interp)*(y[i]-y_interp));
+			if (h<0.0000001){
+				numerator   = obs[i];
+				denominator = 1.;
+				break;
+			}
+			weight = 1./pow(h,power);
+			numerator   += weight*obs[i];
+			denominator += weight;
+		}
+		prediction = numerator/denominator; 
+	}
+
+	/*clean-up*/
+	*pprediction = prediction;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+}/*}}}*/
+void Observations::InterpolationKriging(IssmPDouble *pprediction,IssmPDouble *perror,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,Variogram* variogram){/*{{{*/
+
+	/*Intermediaries*/
+	int           i,j,n_obs;
+	IssmPDouble   prediction,error;
+	IssmPDouble  *x      = NULL;
+	IssmPDouble  *y      = NULL;
+	IssmPDouble  *obs    = NULL;
+	IssmPDouble  *Lambda = NULL;
+
+	/*Some checks*/
+	_assert_(mindata>0 && maxdata>0);
+	_assert_(pprediction && perror);
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata){
+		*pprediction = -999.0; 
+		*perror      = -999.0; 
+		return;
+	}
+
+	/*Allocate intermediary matrix and vectors*/
+	IssmPDouble* A = xNew<IssmPDouble>((n_obs+1)*(n_obs+1));
+	IssmPDouble* B = xNew<IssmPDouble>(n_obs+1);
+
+	IssmDouble unbias = variogram->Covariance(0.,0.);
+	/*First: Create semivariogram matrix for observations*/
+	for(i=0;i<n_obs;i++){
+		for(j=0;j<=i;j++){
+			A[i*(n_obs+1)+j] = variogram->Covariance(x[i]-x[j],y[i]-y[j]);
+			A[j*(n_obs+1)+i] = A[i*(n_obs+1)+j];
+		}
+		A[i*(n_obs+1)+n_obs] = unbias;
+		//A[i*(n_obs+1)+n_obs] = 1.;
+	}
+	for(i=0;i<n_obs;i++) A[n_obs*(n_obs+1)+i]=unbias;
+	//for(i=0;i<n_obs;i++) A[n_obs*(n_obs+1)+i]=1.;
+	A[n_obs*(n_obs+1)+n_obs] = 0.;
+
+	/*Get semivariogram vector associated to this location*/
+	for(i=0;i<n_obs;i++) B[i] = variogram->Covariance(x[i]-x_interp,y[i]-y_interp);
+	B[n_obs] = unbias;
+	//B[n_obs] = 1.;
+
+	/*Solve the three linear systems*/
+#if _HAVE_GSL_
+	DenseGslSolve(&Lambda,A,B,n_obs+1);    // Gamma^-1 Z
+#else
+	_error_("GSL is required");
+#endif
+
+	/*Compute predictor*/
+	prediction = 0.;
+	for(i=0;i<n_obs;i++) prediction += Lambda[i]*obs[i];
+
+	/*Compute error (GSLIB p15 eq II.14)*/
+	error = variogram->Covariance(0.,0.)*(1. - Lambda[n_obs]);;
+	for(i=0;i<n_obs;i++) error += -Lambda[i]*B[i];
+
+	/*clean-up*/
+	*pprediction = prediction;
+	*perror = error;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+	xDelete<IssmPDouble>(A);
+	xDelete<IssmPDouble>(B);
+	xDelete<IssmPDouble>(Lambda);
+
+}/*}}}*/
+void Observations::InterpolationNearestNeighbor(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){/*{{{*/
+
+	/*Intermediaries*/
+	IssmPDouble x,y,obs;
+
+	/*Get clostest observation*/
+	this->ClosestObservation(&x,&y,&obs,x_interp,y_interp,radius);
+
+	/*Assign output pointer*/
+	*pprediction = obs;
+}/*}}}*/
+void Observations::InterpolationV4(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata){/*{{{*/
+	/* Reference:  David T. Sandwell, Biharmonic spline interpolation of GEOS-3
+	 * and SEASAT altimeter data, Geophysical Research Letters, 2, 139-142,
+	 * 1987.  Describes interpolation using value or gradient of value in any
+	 * dimension.*/
+
+	/*Intermediaries*/
+	int         i,j,n_obs;
+	IssmPDouble prediction,h;
+	IssmPDouble *x       = NULL;
+	IssmPDouble *y       = NULL;
+	IssmPDouble *obs     = NULL;
+	IssmPDouble *Green   = NULL;
+	IssmPDouble *weights = NULL;
+	IssmPDouble *g       = NULL;
+
+	/*Some checks*/
+	_assert_(maxdata>0);
+	_assert_(pprediction);
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata || n_obs<2){
+		prediction = UNDEF; 
+	}
+	else{
+
+		/*Allocate intermediary matrix and vectors*/
+		Green = xNew<IssmPDouble>(n_obs*n_obs);
+		g     = xNew<IssmPDouble>(n_obs);
+
+		/*First: distance vector*/
+		for(i=0;i<n_obs;i++){
+			h = sqrt( (x[i]-x_interp)*(x[i]-x_interp) + (y[i]-y_interp)*(y[i]-y_interp) );
+			if(h>0){
+				g[i] = h*h*(log(h)-1.);
+			}
+			else{
+				g[i] = 0.;
+			}
+		}
+
+		/*Build Green function matrix*/
+		for(i=0;i<n_obs;i++){
+			for(j=0;j<=i;j++){
+				h = sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]) );
+				if(h>0){
+					Green[j*n_obs+i] = h*h*(log(h)-1.);
+				}
+				else{
+					Green[j*n_obs+i] = 0.;
+				}
+				Green[i*n_obs+j] = Green[j*n_obs+i];
+			}
+			/*Zero diagonal (should be done already, but just in case)*/
+			Green[i*n_obs+i] = 0.;
+		}
+
+		/*Compute weights*/
+#if _HAVE_GSL_
+		DenseGslSolve(&weights,Green,obs,n_obs); // Green^-1 obs
+#else
+		_error_("GSL is required");
+#endif
+
+		/*Interpolate*/
+		prediction = 0;
+		for(i=0;i<n_obs;i++) prediction += weights[i]*g[i];
+
+	}
+
+	/*clean-up*/
+	*pprediction = prediction;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+	xDelete<IssmPDouble>(Green);
+	xDelete<IssmPDouble>(g);
+	xDelete<IssmPDouble>(weights);
+}/*}}}*/
+void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){/*{{{*/
+
+	int xi,yi,level;
+
+	for(int i=0;i<n;i++){
+		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
+		this->quadtree->QuadtreeDepth(&level,xi,yi);
+		A[i]=(IssmPDouble)level;
+	}
+
+}/*}}}*/
+void Observations::Variomap(IssmPDouble* gamma,IssmPDouble *x,int n){/*{{{*/
+
+	/*Output and Intermediaries*/
+	int          i,j,k;
+	IssmPDouble  distance;
+	Observation *observation1 = NULL;
+	Observation *observation2 = NULL;
+
+	IssmPDouble *counter = xNew<IssmPDouble>(n);
+	for(j=0;j<n;j++) counter[j] = 0.0;
+	for(j=0;j<n;j++) gamma[j]   = 0.0;
+
+	for(i=0;i<this->Size();i++){
+		observation1=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+
+		for(j=i+1;j<this->Size();j++){
+			observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
+
+			distance=sqrt(pow(observation1->x - observation2->x,2) + pow(observation1->y - observation2->y,2));
+			if(distance>x[n-1]) continue;
+
+			int index = int(distance/(x[1]-x[0]));
+			if(index>n-1) index = n-1;
+			if(index<0)   index = 0;
+
+			gamma[index]   += 1./2.*pow(observation1->value - observation2->value,2);
+			counter[index] += 1.;
+		}
+	}
+
+	/*Normalize semivariogram*/
+	gamma[0]=0.;
+	for(k=0;k<n;k++){
+		if(counter[k]) gamma[k] = gamma[k]/counter[k];
+	}
+
+	/*Assign output pointer*/
+	xDelete<IssmPDouble>(counter);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Observations.h	(revision 18231)
@@ -0,0 +1,40 @@
+#ifndef _CONTAINER_OBSERVATIONS_H_
+#define  _CONTAINER_OBSERVATIONS_H_
+
+class Quadtree;
+class Variogram;
+class Options;
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*!\brief Declaration of Observations class.
+ *
+ * Declaration of Observations class.  Observations are vector lists (Containers) of Observation objects.
+ */ 
+
+class Observations: public DataSet{
+
+	private:
+		Quadtree* quadtree;
+
+	public:
+
+		/*constructors, destructors*/
+		Observations();
+		Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
+		~Observations();
+
+		/*Methods*/
+		void ClosestObservation(IssmDouble *px,IssmDouble *py,IssmDouble *pobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius);
+		void Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius);
+		void InterpolationIDW(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,IssmDouble power);
+		void InterpolationV4(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata);
+		void InterpolationKriging(IssmDouble *pprediction,IssmDouble *perror,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,Variogram* variogram);
+		void InterpolationNearestNeighbor(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius);
+		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs);
+		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata);
+		void QuadtreeColoring(IssmDouble* A,IssmDouble *x,IssmDouble *y,int n);
+		void Variomap(IssmDouble* gamma,IssmDouble *x,int n);
+
+};
+#endif //ifndef _OBSERVATIONS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.cpp	(revision 18231)
@@ -0,0 +1,84 @@
+/*!\file PowerVariogram.c
+ * \brief: implementation of the PowerVariogram object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*PowerVariogram constructors and destructor*/
+PowerVariogram::PowerVariogram(){/*{{{*/
+	this->nugget = 0.2;
+	this->slope  = 1.;
+	this->power  = 1.;
+	return;
+}
+/*}}}*/
+PowerVariogram::PowerVariogram(Options* options){/*{{{*/
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->slope  = 1.;
+	this->power  = 1.;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("slope"))  options->Get(&this->slope,"slope");
+	if(options->GetOption("power"))  options->Get(&this->power,"power");
+
+	/*Checks*/
+	if(power<=0 || power>=2) _error_("power must be betwwen 0 and 2 (0 < power < 2)");
+	if(slope<=0) _error_("slope must be positive");
+}
+/*}}}*/
+PowerVariogram::~PowerVariogram(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void PowerVariogram::Echo(void){/*{{{*/
+	_printf_("PowerVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   slope : " << this->slope << "\n");
+	_printf_("   power : " << this->power << "\n");
+}
+/*}}}*/
+
+/*Variogram function*/
+double PowerVariogram::Covariance(double deltax,double deltay){/*{{{*/
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,cova;
+
+	/*Calculate length square*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*return covariance*/
+	cova = 9999. - this->slope*pow(h,this->power);
+
+	return cova;
+}
+/*}}}*/
+double PowerVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,gamma;
+
+	/*Calculate length square*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*return semi-variogram*/
+	gamma = this->nugget + this->slope*pow(h,this->power);
+
+	//if(h>1000) _printf_("gamma = " << gamma << " h=" << h << "\n");
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/PowerVariogram.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file PowerVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _POWERVARIOGRAM_H_
+#define _POWERVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class PowerVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double slope;  
+		double power; 
+
+		/*PowerVariogram constructors, destructors*/
+		PowerVariogram();
+		PowerVariogram(Options* options);
+		~PowerVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _POWERVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.cpp	(revision 18231)
@@ -0,0 +1,583 @@
+#include "../classes.h"
+
+/*DOCUMENTATION What is a Quadtree? {{{
+ * A Quadtree is a very simple way to group vertices according
+ * to their locations. A square that holds all the points of the mesh
+ * (or the geometry) is divided into 4 boxes. As soon as one box
+ * hold more than 4 vertices, it is divided into 4 new boxes, etc...
+ * There cannot be more than MAXDEEP (=30) subdivision.
+ * This process is like a Dichotomy in dimension 2
+ *
+ *  + - -  -    - -    -    - - + -   - + - + - + - -     - - +
+ *  |                           |       |   | X |             |
+ *                                      + - + - +
+ *  |                           |       |   |   |             |
+ *                              + -   - + - + - +             +
+ *  |                           |       |       |             |
+ *                         
+ *  |                           |       |       |             |
+ *  + - -  -    - -    -    - - + -   - + -   - + - -     - - +
+ *  |                           |               |             |
+ *                         
+ *  |                           |               |             |
+ *                         
+ *  |                           |               |             |
+ *  |                           |               |             |
+ *  + - -  -    - -    -    - - + -   -   -   - + - -     - - +
+ *  |                           |                             |
+ *                         
+ *  |                           |                             |
+ *                         
+ *  |                           |                             |
+ *                         
+ *  |                           |                             |
+ *  |                           |                             |
+ *  |                           |                             |
+ *  |                           |                             |
+ *  |                           |                             |
+ *  + - -  -    - -    -    - - + -   -   -   -   - -     - - +
+ *
+ * The coordinate system used in a quadtree are integers to avoid
+ * round-off errors. The vertex in the lower left box has the coordinates
+ * (0 0) 
+ * The upper right vertex has the follwing coordinates:
+ * 2^30 -1           2^30 -1        in decimal
+ * 0 1 1 1 .... 1    0 1 1 1 .... 1 in binary
+ *  \--   29  --/     \--   29  --/
+ * Using binaries is therefore very easy to locate a vertex in a box:
+ * we just need to look at the bits from the left to the right (See ::Add)
+ }}}*/
+/*MACROS {{{*/
+/* 
+ * 
+ *    J    j
+ *    ^    ^
+ *    |    | +--------+--------+
+ *    |    | |        |        |
+ * 1X |    | |   2    |   3    |
+ *    |    | |        |        |
+ *    |    | +--------+--------+
+ *    |    | |        |        |
+ * 0X |    | |   0    |   1    |
+ *    |    | |        |        |
+ *    |    | +--------+--------+
+ *    |    +-----------------------> i
+ *    |         
+ *    |----------------------------> I
+ *              X0        X1  
+ *
+ * box 0 -> I=0 J=0 IJ=00  = 0
+ * box 1 -> I=1 J=0 IJ=01  = 1
+ * box 2 -> I=0 J=1 IJ=10  = 2
+ * box 3 -> I=1 J=1 IJ=11  = 3
+ */
+//IJ(i,j,l) returns the box number of i and j with respect to l
+//if !j&l and !i&l -> 0 (box zero: lower left )
+//if !j&l and  i&l -> 1 (box one:  lower right)
+//if  j&l and !i&l -> 2 (box two:  upper left )
+//if  j&l and  i&l -> 3 (box three:upper right)
+#define IJ(i,j,l)  ((j&l) ? ((i&l) ? 3:2 ) :((i&l) ? 1:0 ))
+/*}}}*/
+
+	/*Constructors/Destructors*/
+Quadtree::Quadtree(){/*{{{*/
+	_error_("Constructor not supported");
+
+}
+/*}}}*/
+Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){/*{{{*/
+
+	/*Intermediaries*/
+	double length;
+
+	/*Initialize fields*/
+	this->MaxDepth=maxdepth;
+	this->NbQuadtreeBox=0;
+	this->NbObs=0;
+
+	/*Create container*/
+	this->boxcontainer=new DataSet();
+
+	/*Create Root, pointer toward the main box*/
+	length=max(xmax-xmin,ymax-ymin);
+	this->root=NewQuadtreeBox(xmin+length/2,ymin+length/2,length);
+}
+/*}}}*/
+	Quadtree::~Quadtree(){/*{{{*/
+
+		delete boxcontainer;
+		root=NULL;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+void  Quadtree::Add(Observation* observation){/*{{{*/
+
+	/*Intermediaries*/
+	int          xi,yi,ij,level,levelbin;
+	QuadtreeBox **pbox    = NULL; // pointer toward current box b
+	QuadtreeBox **pmaster = NULL; // pointer toward master of b
+	QuadtreeBox  *box     = NULL; // current box b
+	QuadtreeBox  *slave   = NULL; // suslaveox of b (if necessary)
+	Observation  *obs[4];
+
+	/*Get integer coodinates*/
+	xi = observation->xi;
+	yi = observation->yi;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pmaster = &root;
+	pbox    = &root;
+
+	/*Find the smallest box where the observation is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		/*Go down one level (levelbin = 00100 -> 00010)*/
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		/*Get next box according to the bit value (levelbin)*/
+		pmaster = pbox;
+		pbox    = &box->box[IJ(xi,yi,levelbin)];
+	}
+	_assert_(levelbin>0);
+
+	/*Now, try to add the vertex, if the box is full (nbitems=4), we have to divide it in 4 new boxes*/
+	while((box=*pbox) && (box->nbitems==4)){
+
+		/*Copy the 4 observation in the current Quadtreebox*/
+		obs[0] = box->obs[0];
+		obs[1] = box->obs[1];
+		obs[2] = box->obs[2];
+		obs[3] = box->obs[3];
+
+		/*set nbitems as -1 (now holding boxes instead of observations)*/
+		box->nbitems = -1;
+		box->box[0]  = NULL;
+		box->box[1]  = NULL;
+		box->box[2]  = NULL;
+		box->box[3]  = NULL;
+
+		/*Go down one level (levelbin = 00010 -> 00001)*/
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		/*Put the four observations in the new boxes*/
+		for (int k=0;k<4;k++){
+
+			/*Get box for observation number k*/
+			ij    = IJ(obs[k]->xi,obs[k]->yi,levelbin);
+			slave = box->box[ij];
+			if(!slave){
+				box->box[ij] = NewQuadtreeBox(box,ij);
+				slave        = box->box[ij];
+			}
+			slave->obs[slave->nbitems++] = obs[k];
+		}
+
+		/*Get the suslaveox where the current observation is located*/
+		ij      = IJ(xi,yi,levelbin);
+		pmaster = pbox;
+		pbox    = &box->box[ij];
+	}
+
+	/*alloc the QuadtreeBox if necessary and add current observation*/
+	box = *pbox;
+	if(!box){
+		ij  = IJ(xi,yi,levelbin);
+		box = *pbox = NewQuadtreeBox(*pmaster,ij);
+	}
+	box->obs[box->nbitems++]=observation;
+	NbObs++;
+
+}/*}}}*/
+void Quadtree::AddAndAverage(double x,double y,double value){/*{{{*/
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           xi,yi;
+	int           levelbin;
+	int           index;
+	double        length,length2;
+
+	/*Get integer coodinates*/
+	this->IntergerCoordinates(&xi,&yi,x,y);
+
+	/*Initialize level*/
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+		levelbin>>=1;
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+
+	/*Add obervation in this box (should be full)*/
+	if(box && box->nbitems==4){
+		index  = 0;
+		length = pow(box->obs[0]->x - x,2) + pow(box->obs[0]->y - y,2);
+		for(int i=1;i<4;i++){
+			length2 = pow(box->obs[i]->x - x,2) + pow(box->obs[i]->y - y,2);
+			if(length2<length){
+				index  = i;
+				length = length2;
+			}
+		}
+
+		/*We found the closest observation, now average observation (do not change xi and yi to avoid round off errors*/
+		box->obs[index]->x = (box->obs[index]->weight*box->obs[index]->x + x)/(box->obs[index]->weight+1.);
+		box->obs[index]->y = (box->obs[index]->weight*box->obs[index]->y + y)/(box->obs[index]->weight+1.);
+		box->obs[index]->xi= int((box->obs[index]->weight*double(box->obs[index]->xi) + double(xi))/(box->obs[index]->weight+1.));
+		box->obs[index]->yi= int((box->obs[index]->weight*double(box->obs[index]->yi) + double(yi))/(box->obs[index]->weight+1.));
+		box->obs[index]->value   = (box->obs[index]->weight*box->obs[index]->value + value)/(box->obs[index]->weight+1.);
+		box->obs[index]->weight += 1.;
+	}
+	else{
+		_error_("Box is not full");
+	}
+}/*}}}*/
+void Quadtree::ClosestObs(int *pindex,double x,double y){/*{{{*/
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           xi,yi;
+	int           levelbin;
+	int           index = -1;
+	double        length,length2;
+
+	/*Get integer coodinates*/
+	this->IntergerCoordinates(&xi,&yi,x,y);
+
+	/*Initialize level*/
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+		levelbin>>=1;
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+
+	/*Add obervation in this box (should be full)*/
+	if(box && box->nbitems>0){
+		index  = box->obs[0]->index;
+		length = pow(box->obs[0]->x - x,2) + pow(box->obs[0]->y - y,2);
+		for(int i=1;i<box->nbitems;i++){
+			length2 = pow(box->obs[i]->x - x,2) + pow(box->obs[i]->y - y,2);
+			if(length2<length){
+				index  = box->obs[i]->index;
+				length = length2;
+			}
+		}
+	}
+
+	*pindex=index;
+}/*}}}*/
+void  Quadtree::Echo(void){/*{{{*/
+
+	_printf_("Quadtree:\n");
+	_printf_("   MaxDepth      = " << this->MaxDepth << "\n");
+	_printf_("   NbQuadtreeBox = " << this->NbQuadtreeBox << "\n");
+	_printf_("   NbObs         = " << this->NbObs << "\n");
+	_printf_("   root          = " << this->root << "\n");
+
+}/*}}}*/
+void  Quadtree::DeepEcho(void){/*{{{*/
+
+	_printf_("Quadtree:\n");
+	_printf_("   MaxDepth      = " << this->MaxDepth << "\n");
+	_printf_("   NbQuadtreeBox = " << this->NbQuadtreeBox << "\n");
+	_printf_("   NbObs         = " << this->NbObs << "\n");
+	_printf_("   root          = " << this->root << "\n");
+	boxcontainer->Echo();
+
+}/*}}}*/
+void  Quadtree::IntergerCoordinates(int *xi,int *yi,double x,double y){/*{{{*/
+
+	/*Intermediaries*/
+	double coefficient;
+	double xmin,ymin;
+
+	/*Checks in debugging mode*/
+	_assert_(xi && yi);
+	_assert_(this->root);
+
+	/*coeffIcoor is the coefficient used for integer coordinates:
+	 *                (x-xmin)
+	 * xi = (2^30 -1) --------- 
+	 *                 length
+	 * coefficient = (2^30 -1)/length
+	 */
+	coefficient = double((1L<<this->MaxDepth)-1)/(this->root->length);
+	xmin        = this->root->xcenter - this->root->length/2;
+	ymin        = this->root->ycenter - this->root->length/2;
+
+	*xi=int(coefficient*(x - xmin));
+	*yi=int(coefficient*(y - ymin));
+}/*}}}*/
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){/*{{{*/
+
+	/*Output*/
+	QuadtreeBox* newbox=NULL;
+
+	/*Create and initialize a new box*/
+	newbox=new QuadtreeBox();
+	newbox->nbitems=0;
+	newbox->xcenter=xcenter;
+	newbox->ycenter=ycenter;
+	newbox->length=length;
+	newbox->box[0]=NULL;
+	newbox->box[1]=NULL;
+	newbox->box[2]=NULL;
+	newbox->box[3]=NULL;
+
+	/*Add to container*/
+	this->boxcontainer->AddObject(newbox);
+	NbQuadtreeBox++;
+
+	/*currentbox now points toward next quadtree box*/
+	return newbox;
+}/*}}}*/
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index){/*{{{*/
+
+	/*Output*/
+	QuadtreeBox* newbox=NULL;
+
+	/*Checks in debugging mode*/
+	_assert_(master);
+
+	/*Create and initialize a new box*/
+	newbox=new QuadtreeBox();
+	newbox->nbitems=0;
+	newbox->box[0]=NULL;
+	newbox->box[1]=NULL;
+	newbox->box[2]=NULL;
+	newbox->box[3]=NULL;
+	switch(index){
+		case 0:
+			newbox->xcenter=master->xcenter - master->length/4;
+			newbox->ycenter=master->ycenter - master->length/4;
+			break;
+		case 1:
+			newbox->xcenter=master->xcenter + master->length/4;
+			newbox->ycenter=master->ycenter - master->length/4;
+			break;
+		case 2:
+			newbox->xcenter=master->xcenter - master->length/4;
+			newbox->ycenter=master->ycenter + master->length/4;
+			break;
+		case 3:
+			newbox->xcenter=master->xcenter + master->length/4;
+			newbox->ycenter=master->ycenter + master->length/4;
+			break;
+		default:
+			_error_("Case " << index << " not supported");
+	}
+	newbox->length=master->length/2;
+
+	/*Add to container*/
+	this->boxcontainer->AddObject(newbox);
+	NbQuadtreeBox++;
+
+	/*currentbox now points toward next quadtree box*/
+	return newbox;
+}/*}}}*/
+void Quadtree::QuadtreeDepth(int* A,int xi,int yi){/*{{{*/
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           level,levelbin;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+	if(box && box->nbitems>0){
+		/*This box is not empty, add one level*/
+		level+=1;
+	}
+
+	*A=level;
+}/*}}}*/
+void Quadtree::QuadtreeDepth2(int* A,int xi,int yi){/*{{{*/
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           level,levelbin;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; 
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+	if(box && box->nbitems>0){
+		/*This box is not empty, add one level*/
+		level+=1;
+	}
+
+	/*If we were to add the vertex, get level*/
+	if(box && box->nbitems==4){
+		int ij;
+		bool flag=true;
+		while(flag){
+
+			levelbin>>=1; level+=1;
+			if(level>this->MaxDepth){
+				level+=1;
+				break;
+			}
+
+			/*loop over the four observations*/
+			ij=IJ(box->obs[0]->xi,box->obs[0]->yi,levelbin);
+			for (int k=1;k<4;k++){
+				if(IJ(box->obs[k]->xi,box->obs[k]->yi,levelbin) != ij){
+					flag = false;
+				}
+			}
+			if(IJ(xi,yi,levelbin)!=ij){
+				flag = false;
+			}
+		}
+	}
+
+	*A=level;
+}/*}}}*/
+void Quadtree::RangeSearch(int **pindices,int *pnobs,double x,double y,double range){/*{{{*/
+
+	/*Intermediaries*/
+	int  nobs;
+	int *indices = NULL;
+
+	/*Allocate indices (maximum by default*/
+	if(this->NbObs) indices = xNew<int>(this->NbObs);
+	nobs = 0;
+
+	if(this->root) this->root->RangeSearch(indices,&nobs,x,y,range);
+
+	/*Clean-up and return*/
+	*pnobs=nobs;
+	*pindices=indices;
+
+}/*}}}*/
+
+/*QuadtreeBox methos*/
+void  Quadtree::QuadtreeBox::Echo(void){/*{{{*/
+
+	_printf_("QuadtreeBox:\n");
+	_printf_("   nbitems = " << this->nbitems << "\n");
+	_printf_("   xcenter = " << this->xcenter << "\n");
+	_printf_("   ycenter = " << this->ycenter << "\n");
+	_printf_("   length  = " << this->length << "\n");
+
+}/*}}}*/
+int Quadtree::QuadtreeBox::IsWithinRange(double x,double y,double range){/*{{{*/
+
+	/*Return 0 if the 2 boxes do not overlap*/
+	if(this->xcenter+this->length/2 < x-range) return 0;
+	if(this->xcenter-this->length/2 > x+range) return 0;
+	if(this->ycenter+this->length/2 < y-range) return 0;
+	if(this->ycenter-this->length/2 > y+range) return 0;
+
+	/*Return 2 if the this box is included in the range*/
+	if(this->xcenter+this->length/2 <= x+range &&
+		this->ycenter+this->length/2 <= y+range &&
+		this->xcenter-this->length/2 >= x-range &&
+		this->ycenter-this->length/2 >= y-range) return 2;
+
+	/*This is a simple overlap*/
+	return 1;
+
+}/*}}}*/
+void Quadtree::QuadtreeBox::RangeSearch(int* indices,int *pnobs,double x,double y,double range){/*{{{*/
+
+	/*Intermediaries*/
+	int i,nobs;
+
+	/*Recover current number of observations*/
+	nobs = *pnobs;
+
+	switch(this->IsWithinRange(x,y,range)){
+		case 0:
+			/*If this box is not within range, return*/
+			break;
+		case 2:
+			/*This box is included in range*/
+			this->WriteObservations(indices,&nobs);
+			break;
+		case 1:
+			/*This box is partly included*/
+			if(this->nbitems>0){
+				/*If this box has only observations, add indices that are within range*/
+				for(i=0;i<this->nbitems;i++){
+					if(fabs(this->obs[i]->x-x) <= range && fabs(this->obs[i]->y-y) <= range){
+						indices[nobs++]=this->obs[i]->index;
+					}
+				}
+			}
+			else{
+				/*This box points toward boxes*/
+				if(this->box[0]) this->box[0]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[1]) this->box[1]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[2]) this->box[2]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[3]) this->box[3]->RangeSearch(indices,&nobs,x,y,range);
+			}
+			break;
+		default:
+			_error_("Case " << this->IsWithinRange(x,y,range) << " not supported");
+	}
+
+	/*Assign output pointers: */
+	*pnobs=nobs;
+}/*}}}*/
+void Quadtree::QuadtreeBox::WriteObservations(int* indices,int *pnobs){/*{{{*/
+
+	/*Intermediaries*/
+	int i,nobs;
+
+	/*Recover current number of observations*/
+	nobs = *pnobs;
+
+	if(this->nbitems>0){
+		/*If this box has only observations, add all indices*/
+		for(i=0;i<this->nbitems;i++){
+			indices[nobs++]=this->obs[i]->index;
+		}
+	}
+	else{
+		/*This box points toward boxes, */
+		if(this->box[0]) this->box[0]->WriteObservations(indices,&nobs);
+		if(this->box[1]) this->box[1]->WriteObservations(indices,&nobs);
+		if(this->box[2]) this->box[2]->WriteObservations(indices,&nobs);
+		if(this->box[3]) this->box[3]->WriteObservations(indices,&nobs);
+	}
+
+	/*Assign output pointers: */
+	*pnobs=nobs;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Quadtree.h	(revision 18231)
@@ -0,0 +1,65 @@
+
+#ifndef _QUADTREE_H
+#define _QUADTREE_H
+
+class Observation;
+
+class Quadtree{
+
+	private:
+		/* A quadtree box contains up to 4 points (locations). 4 new quadtree boxes are
+		 * created if a fifth point is added to the same box. A Quadtree box is therefore
+		 * composed of EITHER:
+		 * - up to 4 vertices
+		 * - 4 "sub" quadtree boxes*/
+
+		class QuadtreeBox: public Object{ 
+			public:
+				int    nbitems; // number of current vertices in the box
+				double xcenter; // x position of the center (double)
+				double ycenter; // x position of the center (double)
+				double length;  // width of the box
+				union{
+					QuadtreeBox *box[4];
+					Observation *obs[4];
+				};
+
+				/*Object functions (Needed because the Quadtree uses a Container*/
+				void    Echo();
+				void    DeepEcho()  {_error_("not implemented yet"); };
+				int     Id()        {_error_("not implemented yet"); };
+				int     ObjectEnum(){_error_("not implemented yet"); };
+				Object *copy()      {_error_("not implemented yet"); };
+
+				/*Methods*/
+				int          IsWithinRange(double  x,double y,double range);
+				void         RangeSearch(int *indices,int *pnobs,double x,double y,double range);
+				void         WriteObservations(int *indices,int *pnobs);
+
+		};
+
+		/*Quadtree private Fields*/
+		DataSet* boxcontainer;
+
+	public:
+		int          MaxDepth;          // maximum number of subdivision
+		QuadtreeBox *root;              // main box
+		int          NbQuadtreeBox;     // total number of boxes
+		int          NbObs;             // number of points
+
+		Quadtree();
+		Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth_in);
+		~Quadtree();
+		void         Add(Observation *observation);
+		void         AddAndAverage(double x,double y,double value);
+		void         ClosestObs(int *pindex,double x,double y);
+		void         DeepEcho(void);
+		void         Echo(void);
+		void         IntergerCoordinates(int *xi,int *yi,double x,double y);
+		QuadtreeBox *NewQuadtreeBox(double xcenter,double ycenter,double length);
+		QuadtreeBox *NewQuadtreeBox(QuadtreeBox* master,int index);
+		void         QuadtreeDepth(int *A,int xi,int yi);
+		void         QuadtreeDepth2(int *A,int xi,int yi);
+		void         RangeSearch(int **pindices,int *pnobs,double x,double y,double range);
+};
+#endif //_QUADTREE_H
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.cpp	(revision 18231)
@@ -0,0 +1,88 @@
+/*!\file SphericalVariogram.c
+ * \brief: implementation of the SphericalVariogram object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*SphericalVariogram constructors and destructor*/
+SphericalVariogram::SphericalVariogram(){/*{{{*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+SphericalVariogram::SphericalVariogram(Options* options){/*{{{*/
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+SphericalVariogram::~SphericalVariogram(){/*{{{*/
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+void SphericalVariogram::Echo(void){/*{{{*/
+	_printf_("SphericalVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
+}
+/*}}}*/
+
+/*Variogram function*/
+double SphericalVariogram::Covariance(double deltax,double deltay){/*{{{*/
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,cova;
+
+	/*Calculate length square*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*return covariance*/
+	if(h<=range)
+	 cova = (sill-nugget)*(1 - (3*h)/(2*range) + pow(h,3)/(2*pow(range,3)) );
+	else
+	 cova = 0.;
+
+	return cova;
+}
+/*}}}*/
+double SphericalVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,gamma;
+
+	/*Calculate length square*/
+	h=sqrt(deltax*deltax + deltay*deltay);
+
+	/*return semi-variogram*/
+	if(h<=range)
+	 gamma = (sill-nugget)*( (3*h)/(2*range) - pow(h,3)/(2*pow(range,3)) ) + nugget;
+	else
+	 gamma = sill;
+
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/SphericalVariogram.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file SphericalVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _SPHERICALVARIOGRAM_H_
+#define _SPHERICALVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class SphericalVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*SphericalVariogram constructors, destructors*/
+		SphericalVariogram();
+		SphericalVariogram(Options* options);
+		~SphericalVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _SPHERICALVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Variogram.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Variogram.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/Variogram.h	(revision 18231)
@@ -0,0 +1,18 @@
+/*!\file:  Variogram.h
+ * \brief abstract class for Variogram object
+ */ 
+
+#ifndef _VARIOGRAM_H_
+#define _VARIOGRAM_H_
+
+#include "../../datastructures/datastructures.h"
+
+class Variogram: public Object{
+
+	public: 
+		virtual ~Variogram(){};
+		virtual double SemiVariogram(double deltax,double deltay)=0;
+		virtual double Covariance(double deltax,double deltay)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/krigingobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/krigingobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/kriging/krigingobjects.h	(revision 18231)
@@ -0,0 +1,18 @@
+/* \file krigingobjects.h
+ * \brief: prototype header for all kriging objects.
+ */
+
+#ifndef KRIGING_OBJECTS_H_
+#define KRIGING_OBJECTS_H_
+
+/*Kriging*/
+#include "./Variogram.h"
+#include "./GaussianVariogram.h"
+#include "./ExponentialVariogram.h"
+#include "./SphericalVariogram.h"
+#include "./PowerVariogram.h"
+#include "./Quadtree.h"
+#include "./Observation.h"
+#include "./Observations.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.cpp	(revision 18231)
@@ -0,0 +1,576 @@
+/*!\file ElementMatrix.cpp
+ * \brief: implementation of the ElementMatrix object, used to plug values from element into global stiffness matrix
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*ElementMatrix constructors and destructor*/
+ElementMatrix::ElementMatrix(){/*{{{*/
+
+	this->nrows=0;
+	this->ncols=0;
+	this->values=NULL;
+	this->dofsymmetrical=false;
+
+	this->row_fsize=0;
+	this->row_flocaldoflist=NULL;
+	this->row_fglobaldoflist=NULL;
+	this->row_ssize=0;
+	this->row_slocaldoflist=NULL;
+	this->row_sglobaldoflist=NULL;
+
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+}
+/*}}}*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke){/*{{{*/
+
+	if(!Ke) _error_("Input Element Matrix is a NULL pointer");
+	this->Init(Ke);
+	return;
+}
+/*}}}*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){/*{{{*/
+
+	/*intermediaries*/
+	int i,j,counter;
+	int gsize,fsize,ssize;
+	int* P=NULL;
+	bool found;
+
+	/*If one of the two matrix is NULL, we copy the other one*/
+	if(!Ke1 && !Ke2){
+		_error_("Two input element matrices are NULL");
+	}
+	else if(!Ke1){
+		this->Init(Ke2);
+		return;
+	}
+	else if(!Ke2){
+		this->Init(Ke1);
+		return;
+	}
+
+	/*General Case: Ke1 and Ke2 are not empty*/
+	if(!Ke1->dofsymmetrical || !Ke2->dofsymmetrical) _error_("merging 2 non dofsymmetrical matrices not implemented yet");
+
+	/*Initialize itransformation matrix Ke[P[i]] = Ke2[i]*/
+	P=xNew<int>(Ke2->nrows);
+
+	/*1: Get the new numbering of Ke2 and get size of the new matrix*/
+	gsize=Ke1->nrows;
+	for(i=0;i<Ke2->nrows;i++){
+		found=false;
+		for(j=0;j<Ke1->nrows;j++){
+			if(Ke2->gglobaldoflist[i]==Ke1->gglobaldoflist[j]){
+				found=true; P[i]=j; break;
+			}
+		}
+		if(!found){
+			P[i]=gsize; gsize++;
+		}
+	}
+
+	/*2: Initialize static fields*/
+	this->nrows=gsize;
+	this->ncols=gsize;
+	this->dofsymmetrical=true;
+
+	/*Gset and values*/
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	this->values=xNewZeroInit<IssmDouble>(this->nrows*this->ncols);
+	for(i=0;i<Ke1->nrows;i++){
+		for(j=0;j<Ke1->ncols;j++){
+			this->values[i*this->ncols+j] += Ke1->values[i*Ke1->ncols+j];
+		}
+		this->gglobaldoflist[i]=Ke1->gglobaldoflist[i];
+	}
+	for(i=0;i<Ke2->nrows;i++){
+		for(j=0;j<Ke2->ncols;j++){
+			this->values[P[i]*this->ncols+P[j]] += Ke2->values[i*Ke2->ncols+j];
+		}
+		this->gglobaldoflist[P[i]]=Ke2->gglobaldoflist[i];
+	}
+
+	/*Fset*/
+	fsize=Ke1->row_fsize;
+	for(i=0;i<Ke2->row_fsize;i++){
+		if(P[Ke2->row_flocaldoflist[i]] >= Ke1->nrows) fsize++;
+	}
+	this->row_fsize=fsize;
+	if(fsize){
+		this->row_flocaldoflist =xNew<int>(fsize);
+		this->row_fglobaldoflist=xNew<int>(fsize);
+		for(i=0;i<Ke1->row_fsize;i++){
+			this->row_flocaldoflist[i] =Ke1->row_flocaldoflist[i];
+			this->row_fglobaldoflist[i]=Ke1->row_fglobaldoflist[i];
+		}
+		counter=Ke1->row_fsize;
+		for(i=0;i<Ke2->row_fsize;i++){
+			if(P[Ke2->row_flocaldoflist[i]] >= Ke1->nrows){
+				this->row_flocaldoflist[counter] =P[Ke2->row_flocaldoflist[i]];
+				this->row_fglobaldoflist[counter]=Ke2->row_fglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->row_flocaldoflist=NULL;
+		this->row_fglobaldoflist=NULL;
+	}
+
+	/*Sset*/
+	ssize=Ke1->row_ssize;
+	for(i=0;i<Ke2->row_ssize;i++){
+		if(P[Ke2->row_slocaldoflist[i]] >= Ke1->nrows) ssize++;
+	}
+	this->row_ssize=ssize;
+	if(ssize){
+		this->row_slocaldoflist =xNew<int>(ssize);
+		this->row_sglobaldoflist=xNew<int>(ssize);
+		for(i=0;i<Ke1->row_ssize;i++){
+			this->row_slocaldoflist[i] =Ke1->row_slocaldoflist[i];
+			this->row_sglobaldoflist[i]=Ke1->row_sglobaldoflist[i];
+		}
+		counter=Ke1->row_ssize;
+		for(i=0;i<Ke2->row_ssize;i++){
+			if(P[Ke2->row_slocaldoflist[i]] >= Ke1->nrows){
+				this->row_slocaldoflist[counter] =P[Ke2->row_slocaldoflist[i]];
+				this->row_sglobaldoflist[counter]=Ke2->row_sglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->row_slocaldoflist=NULL;
+		this->row_sglobaldoflist=NULL;
+	}
+
+	/*don't do cols, we can pick them up from the rows: */
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+	/*clean-up*/
+	xDelete<int>(P);
+}
+/*}}}*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){/*{{{*/
+
+	/*Concatenate all matrices*/
+	ElementMatrix* Ke12 =new ElementMatrix(Ke1,Ke2);
+	ElementMatrix* Ke123=new ElementMatrix(Ke12,Ke3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(Ke123);
+
+	/*clean-up*/
+	delete Ke12;
+	delete Ke123;
+}
+/*}}}*/
+ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){/*{{{*/
+
+	/*get Matrix size and properties*/
+	this->dofsymmetrical=true;
+	this->nrows=GetNumberOfDofs(nodes,numnodes,GsetEnum,approximation);
+	this->ncols=this->nrows;
+
+	/*fill values with 0: */
+	this->values=xNewZeroInit<IssmDouble>(this->nrows*this->ncols);
+
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*get dof lists for f and s set: */
+	this->row_fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->row_flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->row_fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+	this->row_ssize=GetNumberOfDofs(nodes,numnodes,SsetEnum,approximation);
+	this->row_slocaldoflist =GetLocalDofList( nodes,numnodes,SsetEnum,approximation);
+	this->row_sglobaldoflist=GetGlobalDofList(nodes,numnodes,SsetEnum,approximation);
+
+	/*Because this matrix is "dofsymmetrical" don't do cols, we can pick them up from the rows: */
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+}
+/*}}}*/
+ElementMatrix::~ElementMatrix(){/*{{{*/
+
+	xDelete<IssmDouble>(this->values);
+	xDelete<int>(this->gglobaldoflist);
+	xDelete<int>(this->row_flocaldoflist);
+	xDelete<int>(this->row_fglobaldoflist);
+	xDelete<int>(this->row_slocaldoflist);
+	xDelete<int>(this->row_sglobaldoflist);
+	xDelete<int>(this->col_flocaldoflist);
+	xDelete<int>(this->col_fglobaldoflist);
+	xDelete<int>(this->col_slocaldoflist);
+	xDelete<int>(this->col_sglobaldoflist);
+}
+/*}}}*/
+
+/*ElementMatrix specific routines: */
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+
+	int i,j;
+	IssmDouble* localvalues=NULL;
+
+	/*Check that Kff has been alocated in debugging mode*/
+	_assert_(Kff);
+
+	/*If Kfs is not provided, call the other function*/
+	if(!Kfs){
+		this->AddToGlobal(Kff);
+		return;
+	}
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->dofsymmetrical){
+		/*only use row dofs to add values into global matrices: */
+
+		if(this->row_fsize){
+			/*first, retrieve values that are in the f-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_fsize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_fsize;j++){
+					localvalues[this->row_fsize*i+j]=this->values[this->ncols*this->row_flocaldoflist[i]+this->row_flocaldoflist[j]];
+				}
+			}
+
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Kff->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_fsize,this->row_fglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+
+		if((this->row_ssize!=0) && (this->row_fsize!=0)){
+			/*first, retrieve values that are in the f and s-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_ssize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_ssize;j++){
+					localvalues[this->row_ssize*i+j]=this->values[this->ncols*this->row_flocaldoflist[i]+this->row_slocaldoflist[j]];
+				}
+			}
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Kfs->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_ssize,this->row_sglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+	}
+	else{
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Jff){/*{{{*/
+
+	int i,j;
+	IssmDouble* localvalues=NULL;
+
+	/*Check that Jff is not NULL*/
+	_assert_(Jff); 
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->dofsymmetrical){
+		/*only use row dofs to add values into global matrices: */
+
+		if(this->row_fsize){
+			/*first, retrieve values that are in the f-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_fsize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_fsize;j++){
+					*(localvalues+this->row_fsize*i+j)=*(this->values+this->ncols*this->row_flocaldoflist[i]+this->row_flocaldoflist[j]);
+				}
+			}
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Jff->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_fsize,this->row_fglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+
+	}
+	else{
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+void ElementMatrix::CheckConsistency(void){/*{{{*/
+	/*Check element matrix values, only in debugging mode*/
+	#ifdef _ISSM_DEBUG_ 
+	for (int i=0;i<this->nrows;i++){
+		for(int j=0;j<this->ncols;j++){
+			if (xIsNan<IssmDouble>(this->values[i*this->ncols+j])) _error_("NaN found in Element Matrix");
+			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error_("Element Matrix values exceeds 1.e+50");
+		}
+	}
+	#endif
+}
+/*}}}*/
+void ElementMatrix::Transpose(void){/*{{{*/
+
+	/*Intermediaries*/
+	ElementMatrix* Ke_copy=new ElementMatrix(this);
+
+	/*Update sizes*/
+	this->nrows=Ke_copy->ncols;
+	this->ncols=Ke_copy->nrows;
+
+	/*Transpose values*/
+	for (int i=0;i<this->nrows;i++) for(int j=0;j<this->ncols;j++) this->values[i*this->ncols+j]=Ke_copy->values[j*Ke_copy->ncols+i];
+
+	/*Transpose indices*/
+	if(!dofsymmetrical){
+		_error_("not supported yet");
+	}
+
+	/*Clean up and return*/
+	delete Ke_copy;
+	return;
+}
+/*}}}*/
+void ElementMatrix::StaticCondensation(int bsize,int* bindices){/*{{{*/
+	/* 
+	 * | Kii  Kib | | Ui |    |Fi|
+	 * | Kbi  Kbb | | Ub |  = |Fb|
+	 *
+	 * Kii Ui + Kib Ub = Fi
+	 * Kbi Ui + Kbb Ub = Fb
+	 *
+	 * We want to remove Ub from the equation:
+	 *
+	 * Kii Ui + Kib inv(Kbb) (Fb - Kbi Ui) = Fi
+	 *
+	 * which gives:
+	 *
+	 * (Kii - Kib inv(Kbb) Kbi) Ui = Fi - Kib inv(Kbb) Fb
+	 */
+
+	/*Checks in debugging mode*/
+	_assert_(this->nrows==this->ncols && bsize>0 && bsize<this->ncols && this->values); 
+
+	/*Intermediaries*/
+	int         counter,i,j,isize;
+	IssmDouble *Kii         = NULL;
+	IssmDouble *Kib         = NULL;
+	IssmDouble *Kbi         = NULL;
+	IssmDouble *Kbb         = NULL;
+	IssmDouble *Kbbinv      = NULL;
+	IssmDouble *Ktemp       = NULL;
+	int        *iindices    = NULL;
+	bool        flag;
+
+	/*Get new sizes and indices*/
+	isize    = this->nrows - bsize;
+	iindices = xNew<int>(isize);
+	counter  = 0;
+	for(i=0;i<this->nrows;i++){
+		flag = true;
+		for(j=0;j<bsize;j++){
+			if(i==bindices[j]){
+				flag = false;
+				break;
+			}
+		}
+		if(flag){
+			_assert_(counter<isize);
+			iindices[counter++] = i;
+		}
+	}
+	_assert_(counter == isize);
+
+	/*Get submatrices*/
+	Kii = xNew<IssmDouble>(isize*isize);
+	Kib = xNew<IssmDouble>(isize*bsize);
+	Kbi = xNew<IssmDouble>(bsize*isize);
+	Kbb = xNew<IssmDouble>(bsize*bsize);
+	for(i=0;i<isize;i++) for(j=0;j<isize;j++) Kii[i*isize+j] = this->values[iindices[i]*this->ncols + iindices[j]];
+	for(i=0;i<isize;i++) for(j=0;j<bsize;j++) Kib[i*bsize+j] = this->values[iindices[i]*this->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<isize;j++) Kbi[i*isize+j] = this->values[bindices[i]*this->ncols + iindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<bsize;j++) Kbb[i*bsize+j] = this->values[bindices[i]*this->ncols + bindices[j]];
+
+	/*Invert Kbb*/
+	Kbbinv = xNew<IssmDouble>(bsize*bsize);
+	switch(bsize){
+		case 1:
+			Kbbinv[0] = 1./Kbb[0];
+			break;
+		case 2:
+			Matrix2x2Invert(Kbbinv,Kbb);
+			break;
+		case 3:
+			Matrix3x3Invert(Kbbinv,Kbb);
+			break;
+		default:
+			MatrixInverse(Kbbinv,bsize,bsize,NULL,0,NULL);
+			break;
+	}
+
+	/*Calculate  Kib inv(Kbb) Kbi*/
+	Ktemp = xNew<IssmDouble>(isize*isize);
+	TripleMultiply(Kib,isize,bsize,0, Kbbinv,bsize,bsize,0, Kbi,bsize,isize,0, Ktemp,0);
+
+	/*New Ke*/
+	for(i=0;i<isize*isize;i++) Ktemp[i] = Kii[i] - Ktemp[i];
+
+	/*Update matrix values*/
+	for(i=0;i<this->nrows*this->ncols;i++) this->values[i]=0.;
+	for(i=0;i<isize;i++){
+		for(j=0;j<isize;j++){
+			this->values[iindices[i]*this->ncols + iindices[j]] = Ktemp[i*isize+j];
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(Kii);
+	xDelete<IssmDouble>(Kib);
+	xDelete<IssmDouble>(Kbi);
+	xDelete<IssmDouble>(Kbb);
+	xDelete<IssmDouble>(Kbbinv);
+	xDelete<IssmDouble>(Ktemp);
+	xDelete<int>(iindices);
+	return;
+}
+/*}}}*/
+void ElementMatrix::Echo(void){/*{{{*/
+
+	int i,j;
+	_printf_("Element Matrix echo:\n");
+	_printf_("   nrows: " << this->nrows << "\n");
+	_printf_("   ncols: " << this->ncols << "\n");
+	_printf_("   dofsymmetrical: " << (dofsymmetrical?"true":"false") << "\n");
+
+	_printf_("   values:\n");
+	for(i=0;i<nrows;i++){
+		_printf_(setw(4) << right << i << ": ");
+		for(j=0;j<ncols;j++) _printf_( " " << setw(11) << setprecision (5) << right << values[i*ncols+j]);
+		_printf_("\n");
+	}
+
+	_printf_("   gglobaldoflist (" << gglobaldoflist << "): ");
+	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i]); _printf_("\n");
+
+	_printf_("   row_fsize: " << row_fsize << "\n");
+	_printf_("   row_flocaldoflist  (" << row_flocaldoflist << "): ");
+	if(row_flocaldoflist) for(i=0;i<row_fsize;i++) _printf_(" " << row_flocaldoflist[i] ); _printf_(" \n");
+	_printf_("   row_fglobaldoflist  (" << row_fglobaldoflist << "): ");
+	if(row_fglobaldoflist) for(i=0;i<row_fsize;i++)_printf_(" " << row_fglobaldoflist[i]); _printf_(" \n");
+
+	_printf_("   row_ssize: " << row_ssize << "\n");
+	_printf_("   row_slocaldoflist  (" << row_slocaldoflist << "): ");
+	if(row_slocaldoflist) for(i=0;i<row_ssize;i++) _printf_(" " << row_slocaldoflist[i] ); _printf_(" \n");
+	_printf_("   row_sglobaldoflist  (" << row_sglobaldoflist << "): ");
+	if(row_sglobaldoflist) for(i=0;i<row_ssize;i++)_printf_(" " << row_sglobaldoflist[i]); _printf_(" \n");
+
+	if(!dofsymmetrical){
+		_printf_("   col_fsize: " << col_fsize << "\n");
+		_printf_("   col_flocaldoflist  (" << col_flocaldoflist << "): ");
+		if(col_flocaldoflist) for(i=0;i<col_fsize;i++) _printf_(" " << col_flocaldoflist[i] ); _printf_(" \n");
+		_printf_("   col_fglobaldoflist  (" << col_fglobaldoflist << "): ");
+		if(col_fglobaldoflist) for(i=0;i<col_fsize;i++)_printf_(" " << col_fglobaldoflist[i]); _printf_(" \n");
+
+		_printf_("   col_ssize: " << col_ssize << "\n");
+		_printf_("   col_slocaldoflist  (" << col_slocaldoflist << "): ");
+		if(col_slocaldoflist) for(i=0;i<col_ssize;i++) _printf_(" " << col_slocaldoflist[i] ); _printf_(" \n");
+		_printf_("   col_sglobaldoflist  (" << col_sglobaldoflist << "): ");
+		if(col_sglobaldoflist) for(i=0;i<col_ssize;i++)_printf_(" " << col_sglobaldoflist[i]); _printf_(" \n");
+	}
+}
+/*}}}*/
+void ElementMatrix::Init(ElementMatrix* Ke){/*{{{*/
+
+	_assert_(Ke);
+	_assert_(this);
+
+	this->nrows =Ke->nrows;
+	this->ncols =Ke->ncols;
+	this->dofsymmetrical=Ke->dofsymmetrical;
+
+	this->values=xNew<IssmDouble>(this->nrows*this->ncols);
+	xMemCpy<IssmDouble>(this->values,Ke->values,this->nrows*this->ncols);
+
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	xMemCpy<int>(this->gglobaldoflist,Ke->gglobaldoflist,this->nrows);
+
+	this->row_fsize=Ke->row_fsize;
+	if(this->row_fsize){
+		this->row_flocaldoflist=xNew<int>(this->row_fsize);
+		xMemCpy<int>(this->row_flocaldoflist,Ke->row_flocaldoflist,this->row_fsize);
+		this->row_fglobaldoflist=xNew<int>(this->row_fsize);
+		xMemCpy<int>(this->row_fglobaldoflist,Ke->row_fglobaldoflist,this->row_fsize);
+	}
+	else{
+		this->row_flocaldoflist=NULL;
+		this->row_fglobaldoflist=NULL;
+	}
+
+	this->row_ssize=Ke->row_ssize;
+	if(this->row_ssize){
+		this->row_slocaldoflist=xNew<int>(this->row_ssize);
+		xMemCpy<int>(this->row_slocaldoflist,Ke->row_slocaldoflist,this->row_ssize);
+		this->row_sglobaldoflist=xNew<int>(this->row_ssize);
+		xMemCpy<int>(this->row_sglobaldoflist,Ke->row_sglobaldoflist,this->row_ssize);
+	}
+	else{
+		this->row_slocaldoflist=NULL;
+		this->row_sglobaldoflist=NULL;
+	}
+
+	this->col_fsize=Ke->col_fsize;
+	if(this->col_fsize){
+		this->col_flocaldoflist=xNew<int>(this->col_fsize);
+		xMemCpy<int>(this->col_flocaldoflist,Ke->col_flocaldoflist,this->col_fsize);
+		this->col_fglobaldoflist=xNew<int>(this->col_fsize);
+		xMemCpy<int>(this->col_fglobaldoflist,Ke->col_fglobaldoflist,this->col_fsize);
+	}
+	else{
+		this->col_flocaldoflist=NULL;
+		this->col_fglobaldoflist=NULL;
+	}
+
+	this->col_ssize=Ke->col_ssize;
+	if(this->col_ssize){
+		this->col_slocaldoflist=xNew<int>(this->col_ssize);
+		xMemCpy<int>(this->col_slocaldoflist,Ke->col_slocaldoflist,this->col_ssize);
+		this->col_sglobaldoflist=xNew<int>(this->col_ssize);
+		xMemCpy<int>(this->col_sglobaldoflist,Ke->col_sglobaldoflist,this->col_ssize);
+	}
+	else{
+		this->col_slocaldoflist=NULL;
+		this->col_sglobaldoflist=NULL;
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementMatrix.h	(revision 18231)
@@ -0,0 +1,68 @@
+/*!\file:  ElementMatrix.h
+ * \brief container for information needed to plug element matrix generated by elements 
+ * into the Kff and Kfs global matrices. 
+ * This object will hold the element matrix on the g-set, the local as well as global 
+ * dof lists in the f and s sets.
+ */ 
+
+#ifndef _ELEMENT_MATRIX_H_
+#define _ELEMENT_MATRIX_H_
+
+/*Headers:*/
+#include "../../datastructures/datastructures.h"
+#include "../../toolkits/toolkits.h"
+#include "../../shared/shared.h"
+class Node;
+template <class doublematrix> class Matrix;
+class Parameters;
+
+class ElementMatrix{
+
+	public:
+
+		int      nrows;
+		int      ncols;
+		bool     dofsymmetrical;
+		IssmDouble*  values;
+
+		//gset
+		int*     gglobaldoflist;
+
+		/*row wise: */
+		//fset
+		int      row_fsize;
+		int*     row_flocaldoflist;
+		int*     row_fglobaldoflist;
+		//sset
+		int      row_ssize;
+		int*     row_slocaldoflist;
+		int*     row_sglobaldoflist;
+
+		/*column wise: */
+		//fset
+		int      col_fsize;
+		int*     col_flocaldoflist;
+		int*     col_fglobaldoflist;
+		//sset
+		int      col_ssize;
+		int*     col_slocaldoflist;
+		int*     col_sglobaldoflist;
+
+		/*ElementMatrix constructors, destructors*/
+		ElementMatrix();
+		ElementMatrix(ElementMatrix* Ke);
+		ElementMatrix(ElementMatrix* Ke1,ElementMatrix* Ke2);
+		ElementMatrix(ElementMatrix* Ke1,ElementMatrix* Ke2,ElementMatrix* Ke3);
+		ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
+		~ElementMatrix();
+
+		/*ElementMatrix specific routines*/
+		void AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void AddToGlobal(Matrix<IssmDouble>* Jff);
+		void Echo(void);
+		void CheckConsistency(void);
+		void StaticCondensation(int numindices,int* indices);
+		void Transpose(void);
+		void Init(ElementMatrix* Ke);
+};
+#endif //#ifndef _ELEMENT_MATRIX_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.cpp	(revision 18231)
@@ -0,0 +1,366 @@
+/*!\file ElementVector.cpp
+ * \brief: implementation of the ElementVector object, used to plug values from element into global load
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*ElementVector constructors and destructor*/
+ElementVector::ElementVector(){/*{{{*/
+
+	this->nrows=0;
+	this->values=NULL;
+	this->fsize=0;
+	this->flocaldoflist=NULL;
+	this->fglobaldoflist=NULL;
+
+}
+/*}}}*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){/*{{{*/
+
+	/*intermediaries*/
+	int i,j,counter;
+	int gsize,fsize;
+	int* P=NULL;
+	bool found;
+
+	/*If one of the two matrix is NULL, we copy the other one*/
+	if(!pe1 && !pe2){
+		_error_("Two input element matrices are NULL");
+	}
+	else if(!pe1){
+		this->Init(pe2);
+		return;
+	}
+	else if(!pe2){
+		this->Init(pe1);
+		return;
+	}
+
+	/*Initialize itransformation matrix pe[P[i]] = pe2[i]*/
+	P=xNew<int>(pe2->nrows);
+
+	/*1: Get the new numbering of pe2 and get size of the new matrix*/
+	gsize=pe1->nrows;
+	for(i=0;i<pe2->nrows;i++){
+		found=false;
+		for(j=0;j<pe1->nrows;j++){
+			if(pe2->gglobaldoflist[i]==pe1->gglobaldoflist[j]){
+				found=true; P[i]=j; break;
+			}
+		}
+		if(!found){
+			P[i]=gsize; gsize++;
+		}
+	}
+
+	/*2: Initialize static fields*/
+	this->nrows=gsize;
+
+	/*Gset and values*/
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	this->values=xNewZeroInit<IssmDouble>(this->nrows);
+	for(i=0;i<pe1->nrows;i++){
+		this->values[i] += pe1->values[i];
+		this->gglobaldoflist[i]=pe1->gglobaldoflist[i];
+	}
+	for(i=0;i<pe2->nrows;i++){
+		this->values[P[i]] += pe2->values[i];
+		this->gglobaldoflist[P[i]]=pe2->gglobaldoflist[i];
+	}
+
+	/*Fset*/
+	fsize=pe1->fsize;
+	for(i=0;i<pe2->fsize;i++){
+		if(P[pe2->flocaldoflist[i]] >= pe1->nrows) fsize++;
+	}
+	this->fsize=fsize;
+	if(fsize){
+		this->flocaldoflist =xNew<int>(fsize);
+		this->fglobaldoflist=xNew<int>(fsize);
+		for(i=0;i<pe1->fsize;i++){
+			this->flocaldoflist[i] =pe1->flocaldoflist[i];
+			this->fglobaldoflist[i]=pe1->fglobaldoflist[i];
+		}
+		counter=pe1->fsize;
+		for(i=0;i<pe2->fsize;i++){
+			if(P[pe2->flocaldoflist[i]] >= pe1->nrows){
+				this->flocaldoflist[counter] =P[pe2->flocaldoflist[i]];
+				this->fglobaldoflist[counter]=pe2->fglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->flocaldoflist=NULL;
+		this->fglobaldoflist=NULL;
+	}
+
+	/*clean-up*/
+	xDelete<int>(P);
+}
+/*}}}*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){/*{{{*/
+
+	/*Concatenate all matrices*/
+	ElementVector* pe12 =new ElementVector(pe1,pe2);
+	ElementVector* pe123=new ElementVector(pe12,pe3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(pe123);
+
+	/*clean-up*/
+	delete pe12;
+	delete pe123;
+}
+/*}}}*/
+ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){/*{{{*/
+
+	/*get Vector size and properties*/
+	this->nrows=GetNumberOfDofs(nodes,numnodes,GsetEnum,approximation);
+
+	/*fill values with 0: */
+	this->values=xNewZeroInit<IssmDouble>(this->nrows);
+
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*Get fsize*/
+	this->fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+}
+/*}}}*/
+ElementVector::~ElementVector(){/*{{{*/
+
+	xDelete<IssmDouble>(this->values);
+	xDelete<int>(this->gglobaldoflist);
+	xDelete<int>(this->flocaldoflist);
+	xDelete<int>(this->fglobaldoflist);
+}
+/*}}}*/
+
+/*ElementVector specific routines: */
+void ElementVector::AddToGlobal(Vector<IssmDouble>* pf){/*{{{*/
+
+	int i;
+	IssmDouble* localvalues=NULL;
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=xNew<IssmDouble>(this->fsize);
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		pf->SetValues(this->fsize,this->fglobaldoflist,localvalues,ADD_VAL);
+
+		/*Free ressources:*/
+		xDelete<IssmDouble>(localvalues);
+	}
+
+}
+/*}}}*/
+void ElementVector::InsertIntoGlobal(Vector<IssmDouble>* pf){/*{{{*/
+
+	int i;
+	IssmDouble* localvalues=NULL;
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=xNew<IssmDouble>(this->fsize);
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		pf->SetValues(this->fsize,this->fglobaldoflist,localvalues,INS_VAL);
+
+		/*Free ressources:*/
+		xDelete<IssmDouble>(localvalues);
+	}
+
+}
+/*}}}*/
+void ElementVector::CheckConsistency(void){/*{{{*/
+	/*Check element matrix values, only in debugging mode*/
+#ifdef _ISSM_DEBUG_ 
+	for (int i=0;i<this->nrows;i++){
+		if (xIsNan<IssmDouble>(this->values[i])) _error_("NaN found in Element Vector");
+		if (fabs( this->values[i])>1.e+50) _error_("Element Vector values exceeds 1.e+50");
+	}
+#endif
+}
+/*}}}*/
+void ElementVector::Echo(void){/*{{{*/
+
+	int i;
+
+	_printf_("Element Vector echo:\n");
+	_printf_("   nrows: " << nrows << "\n");
+	_printf_("   values:\n");
+	for(i=0;i<nrows;i++){
+		_printf_(setw(4) << right << i << ": " << setw(10) << values[i] << "\n");
+	}
+
+	_printf_("   gglobaldoflist (" << gglobaldoflist << "): ");
+	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i] );
+	_printf_(" \n");
+
+	_printf_("   fsize: " << fsize << "\n");
+	_printf_("   flocaldoflist  (" << flocaldoflist << "): ");
+	if(flocaldoflist) for(i=0;i<fsize;i++) _printf_(" " << flocaldoflist[i] );
+	_printf_(" \n");
+	_printf_("   fglobaldoflist (" << fglobaldoflist << "): ");
+	if(fglobaldoflist) for(i=0;i<fsize;i++) _printf_(" " << fglobaldoflist[i] );
+	_printf_(" \n");
+}
+/*}}}*/
+void ElementVector::Init(ElementVector* pe){/*{{{*/
+
+	_assert_(pe);
+
+	this->nrows =pe->nrows;
+
+	this->values=xNew<IssmDouble>(this->nrows);
+	xMemCpy<IssmDouble>(this->values,pe->values,this->nrows);
+
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	xMemCpy<int>(this->gglobaldoflist,pe->gglobaldoflist,this->nrows);
+
+	this->fsize=pe->fsize;
+	if(this->fsize){
+		this->flocaldoflist=xNew<int>(this->fsize);
+		xMemCpy<int>(this->flocaldoflist,pe->flocaldoflist,this->fsize);
+		this->fglobaldoflist=xNew<int>(this->fsize);
+		xMemCpy<int>(this->fglobaldoflist,pe->fglobaldoflist,this->fsize);
+	}
+	else{
+		this->flocaldoflist=NULL;
+		this->fglobaldoflist=NULL;
+	}
+}
+/*}}}*/
+void ElementVector::SetValue(IssmDouble scalar){/*{{{*/
+
+	int i;
+
+	for(i=0;i<this->nrows;i++)this->values[i]=scalar;
+
+}
+/*}}}*/
+void ElementVector::StaticCondensation(ElementMatrix* Ke,int bsize,int* bindices){/*{{{*/
+	/* 
+	 * | Kii  Kib | | Ui |    |Fi|
+	 * | Kbi  Kbb | | Ub |  = |Fb|
+	 *
+	 * Kii Ui + Kib Ub = Fi
+	 * Kbi Ui + Kbb Ub = Fb
+	 *
+	 * We want to remove Ub from the equation:
+	 *
+	 * Kii Ui + Kib inv(Kbb) (Fb - Kbi Ui) = Fi
+	 *
+	 * which gives:
+	 *
+	 * (Kii - Kib inv(Kbb) Kbi) Ui = Fi - Kib inv(Kbb) Fb
+	 */
+
+	/*Checks in debugging mode*/
+	_assert_(bsize>0 && bsize<this->nrows && this->values && Ke); 
+	_assert_(Ke->nrows==Ke->ncols && this->nrows==Ke->nrows);
+
+	/*Intermediaries*/
+	int         counter,i,j,isize;
+	IssmDouble *Fb          = NULL;
+	IssmDouble *Fi          = NULL;
+	IssmDouble *Kib         = NULL;
+	IssmDouble *Kbb         = NULL;
+	IssmDouble *Kbbinv      = NULL;
+	IssmDouble *Ftemp       = NULL;
+	int        *iindices    = NULL;
+	bool        flag;
+
+	/*Get new sizes and indices*/
+	isize    = this->nrows - bsize;
+	iindices = xNew<int>(isize);
+	counter  = 0;
+	for(i=0;i<this->nrows;i++){
+		flag = true;
+		for(j=0;j<bsize;j++){
+			if(i==bindices[j]){
+				flag = false;
+				break;
+			}
+		}
+		if(flag){
+			_assert_(counter<isize);
+			iindices[counter++] = i;
+		}
+	}
+	_assert_(counter == isize);
+
+	/*Get submatrices*/
+	Kib = xNew<IssmDouble>(isize*bsize);
+	Kbb = xNew<IssmDouble>(bsize*bsize);
+	Fb  = xNew<IssmDouble>(bsize);
+	Fi  = xNew<IssmDouble>(isize);
+	for(i=0;i<isize;i++) for(j=0;j<bsize;j++) Kib[i*bsize+j] = Ke->values[iindices[i]*Ke->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<bsize;j++) Kbb[i*bsize+j] = Ke->values[bindices[i]*Ke->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) Fb[i] = this->values[bindices[i]];
+	for(i=0;i<isize;i++) Fi[i] = this->values[iindices[i]];
+
+	/*Invert Kbb*/
+	Kbbinv = xNew<IssmDouble>(bsize*bsize);
+	switch(bsize){
+		case 1:
+			Kbbinv[0] = 1./Kbb[0];
+			break;
+		case 2:
+			Matrix2x2Invert(Kbbinv,Kbb);
+			break;
+		case 3:
+			Matrix3x3Invert(Kbbinv,Kbb);
+			break;
+		default:
+			MatrixInverse(Kbbinv,bsize,bsize,NULL,0,NULL);
+			break;
+	}
+
+	/*Calculate  Kib inv(Kbb) Fb*/
+	Ftemp = xNew<IssmDouble>(isize);
+	TripleMultiply(Kib,isize,bsize,0, Kbbinv,bsize,bsize,0, Fb,bsize,1,0, Ftemp,0);
+
+	/*New Pe*/
+	for(i=0;i<isize;i++) Ftemp[i] = Fi[i] - Ftemp[i];
+
+	/*Update matrix values*/
+	for(i=0;i<this->nrows;i++) this->values[i]=0.;
+	for(i=0;i<isize;i++){
+		this->values[iindices[i]] = Ftemp[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(Kib);
+	xDelete<IssmDouble>(Kbb);
+	xDelete<IssmDouble>(Kbbinv);
+	xDelete<IssmDouble>(Fb);
+	xDelete<IssmDouble>(Fi);
+	xDelete<IssmDouble>(Ftemp);
+	xDelete<int>(iindices);
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/ElementVector.h	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file:  ElementVector.h
+ * \brief container for information needed to plug element vector generated by elements 
+ * into the pf global load vector. 
+ * This object will hold the element vector on the g-set, the local as well as global 
+ * dof lists in the f set
+ */ 
+
+#ifndef _ELEMENT_VECTOR_H_
+#define _ELEMENT_VECTOR_H_
+
+/*Headers:*/
+#include "../../datastructures/datastructures.h"
+#include "../../toolkits/toolkits.h"
+#include "../../shared/shared.h"
+class Node;
+template <class doubletype> class Vector;
+class Parameters;
+class ElementMatrix;
+
+class ElementVector{
+
+	public:
+		int         nrows;
+		IssmDouble* values;
+
+		//gset
+		int* gglobaldoflist;
+
+		//fset
+		int  fsize;
+		int* flocaldoflist;
+		int* fglobaldoflist;
+
+		/*ElementVector constructors, destructors*/
+		ElementVector();
+		ElementVector(ElementVector* pe1,ElementVector* pe2);
+		ElementVector(ElementVector* pe1,ElementVector* pe2,ElementVector* pe3);
+		ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
+		~ElementVector();
+
+		/*ElementVector specific routines*/
+		void AddToGlobal(Vector<IssmDouble>* pf);
+		void InsertIntoGlobal(Vector<IssmDouble>* pf);
+		void Echo(void);
+		void CheckConsistency(void);
+		void Init(ElementVector* pe);
+		void SetValue(IssmDouble scalar);
+		void StaticCondensation(ElementMatrix* Ke,int numindices,int* indices);
+};
+#endif //#ifndef _ELEMENT_VECTOR_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/matrixobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/matrixobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/classes/matrix/matrixobjects.h	(revision 18231)
@@ -0,0 +1,12 @@
+/* \file matrixobjects.h
+ * \brief: prototype header for all matrix objects.
+ */
+
+#ifndef ALL_MATRIX_OBJECTS_H_
+#define ALL_MATRIX_OBJECTS_H_
+
+/*Numerics:*/
+#include "./ElementMatrix.h"
+#include "./ElementVector.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AdjointCorePointerFromSolutionEnum.cpp	(revision 18231)
@@ -0,0 +1,49 @@
+/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype){
+
+	/*output: */
+	void (*adjointcore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			adjointcore=&adjointstressbalance_core;
+			break;
+		case SteadystateSolutionEnum:
+			adjointcore=&adjointstressbalance_core;
+			break;
+		case BalancethicknessSolutionEnum:
+			adjointcore=&adjointbalancethickness_core;
+			break;
+		case Balancethickness2SolutionEnum:
+			adjointcore=&adjointbalancethickness2_core;
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			adjointcore=&dummy_core;
+			break;
+		default:
+			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(padjointcore);
+	*padjointcore=adjointcore;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AnalysisConfiguration.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AnalysisConfiguration.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/AnalysisConfiguration.cpp	(revision 18231)
@@ -0,0 +1,159 @@
+/*!\file:  AnalysisConfiguration.cpp
+ * \brief: return type of analyses, number of analyses 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
+
+	/*output: */
+	int  numanalyses;
+	int* analyses=NULL;
+
+	/*Analyses lists*/
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			numanalyses=7;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			analyses[4]=ExtrudeFromBaseAnalysisEnum;
+			analyses[5]=DepthAverageAnalysisEnum;
+			analyses[6]=UzawaPressureAnalysisEnum;
+			break;
+
+		case SteadystateSolutionEnum:
+			numanalyses=7;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			analyses[4]=EnthalpyAnalysisEnum;
+			analyses[5]=ThermalAnalysisEnum;
+			analyses[6]=MeltingAnalysisEnum;
+			break;
+
+		case ThermalSolutionEnum:
+			numanalyses=3;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=ThermalAnalysisEnum;
+			analyses[1]=MeltingAnalysisEnum;
+			analyses[2]=EnthalpyAnalysisEnum;
+			break;
+
+		case HydrologySolutionEnum:
+			numanalyses=5;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=HydrologyShreveAnalysisEnum;
+			analyses[1]=HydrologyDCInefficientAnalysisEnum;
+			analyses[2]=HydrologyDCEfficientAnalysisEnum;
+			analyses[3]=L2ProjectionBaseAnalysisEnum;
+			analyses[4]=L2ProjectionEPLAnalysisEnum;
+			break;
+
+		case MasstransportSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=MasstransportAnalysisEnum;
+			break;
+
+		case BalancethicknessSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case Balancethickness2SolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=Balancethickness2AnalysisEnum;
+			break;
+
+		case BalancethicknessSoftSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancevelocitySolutionEnum:
+			numanalyses=3;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancevelocityAnalysisEnum;
+			analyses[1]=SmoothedSurfaceSlopeXAnalysisEnum;
+			analyses[2]=SmoothedSurfaceSlopeYAnalysisEnum;
+			break;
+
+		case SurfaceSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case BedSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case GiaSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=GiaAnalysisEnum;
+			break;
+		
+		case DamageEvolutionSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=DamageEvolutionAnalysisEnum;
+			break;
+
+		case TransientSolutionEnum:
+			numanalyses=20;
+			analyses=xNew<int>(numanalyses);
+			analyses[ 0]=StressbalanceAnalysisEnum;
+			analyses[ 1]=StressbalanceVerticalAnalysisEnum;
+			analyses[ 2]=StressbalanceSIAAnalysisEnum;
+			analyses[ 3]=L2ProjectionBaseAnalysisEnum;
+			analyses[ 4]=ThermalAnalysisEnum;
+			analyses[ 5]=MeltingAnalysisEnum;
+			analyses[ 6]=EnthalpyAnalysisEnum;
+			analyses[ 7]=MasstransportAnalysisEnum;
+			analyses[ 8]=FreeSurfaceBaseAnalysisEnum;
+			analyses[ 9]=FreeSurfaceTopAnalysisEnum;
+			analyses[10]=ExtrudeFromBaseAnalysisEnum;
+			analyses[11]=ExtrudeFromTopAnalysisEnum;
+			analyses[12]=LevelsetAnalysisEnum;
+			analyses[13]=ExtrapolationAnalysisEnum;
+			analyses[14]=LsfReinitializationAnalysisEnum;
+			analyses[15]=DamageEvolutionAnalysisEnum;
+			analyses[16]=HydrologyShreveAnalysisEnum;
+			analyses[17]=HydrologyDCInefficientAnalysisEnum;
+			analyses[18]=HydrologyDCEfficientAnalysisEnum;
+			analyses[19]=L2ProjectionEPLAnalysisEnum;
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointers:*/
+	if(pnumanalyses) *pnumanalyses=numanalyses;
+	if(panalyses)    *panalyses=analyses;
+	else              xDelete<int>(analyses);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file:  CorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:
+			solutioncore=&stressbalance_core;
+			break;
+		case SteadystateSolutionEnum:
+			solutioncore=&steadystate_core;
+			break;
+		case ThermalSolutionEnum:
+			solutioncore=&thermal_core;
+			break;
+		case BalancethicknessSolutionEnum:
+			solutioncore=&balancethickness_core;
+			break;
+		case Balancethickness2SolutionEnum:
+			solutioncore=&balancethickness2_core;
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			solutioncore=&dummy_core;
+			break;
+		case BalancevelocitySolutionEnum:
+			solutioncore=&balancevelocity_core;
+			break;
+		case HydrologySolutionEnum:
+			solutioncore=&hydrology_core;
+			break;
+		case SurfaceSlopeSolutionEnum:
+			solutioncore=&surfaceslope_core;
+			break;
+		case BedSlopeSolutionEnum:
+			solutioncore=&bedslope_core;
+			break;
+		case TransientSolutionEnum:
+			solutioncore=&transient_core;
+			break;
+		case MasstransportSolutionEnum:
+			solutioncore=&masstransport_core;
+			break;
+		case GiaSolutionEnum:
+			#if _HAVE_GIA_
+			solutioncore=&gia_core;
+			#else
+			_error_("ISSM not compiled with Gia capability");
+			#endif
+			break;
+		case DamageEvolutionSolutionEnum:
+			solutioncore=&damage_core;
+			break;
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.cpp	(revision 18231)
@@ -0,0 +1,187 @@
+/*!\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 "./cores.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses);
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses);
+/*}}}*/
+
+/*Notice the d_, which prefixes anything that is being provided to us by the Dakota pluggin. Careful. some things are ours, some are dakotas!: */
+int DakotaSpawnCore(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, void* void_femmodel,int counter){
+
+	char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
+	int        numresponsedescriptors;
+	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: */
+	ISSM_MPI_Bcast(&counter,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	if(counter==-1)return 0;
+
+	/*cast void_femmodel to FemModel: */
+	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+
+	if(VerboseQmu()) _printf0_("qmu iteration: " << counter << "\n");
+
+	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
+	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
+
+	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
+	InputUpdateFromDakotax(femmodel,d_variables,d_variables_descriptors,d_numvariables);
+
+	/*Determine solution sequence: */
+	if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
+	WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
+
+	/*Run the core solution sequence: */
+	solutioncore(femmodel);
+
+	/*compute responses: */
+	if(VerboseQmu()) _printf0_("compute dakota responses:\n");
+	femmodel->DakotaResponsesx(d_responses,responses_descriptors,numresponsedescriptors,d_numresponses);
+
+	/*Free ressources:*/
+	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+
+	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
+}
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){ /*{{{*/
+
+	/* * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
+	 * from cpu 0 to all other cpus.
+	 */ 
+
+	int i;
+	int my_rank;
+
+	/*inputs and outputs: */
+	double* variables=NULL;
+	char**  variables_descriptors=NULL;
+	int     numvariables;
+	int     numresponses;
+
+	/*intermediary: */
+	char* string=NULL;
+	int   string_length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*recover inputs from pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	numvariables=*pnumvariables;
+	numresponses=*pnumresponses;
+
+	/*numvariables: */
+	ISSM_MPI_Bcast(&numvariables,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+
+	/*variables:*/
+	if(my_rank!=0)variables=xNew<double>(numvariables);
+	ISSM_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);
+		}
+		ISSM_MPI_Bcast(&string_length,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+		if(my_rank!=0)string=xNew<char>(string_length);
+		ISSM_MPI_Bcast(string,string_length,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
+		if(my_rank!=0)variables_descriptors[i]=string;
+	}
+
+	/*numresponses: */
+	ISSM_MPI_Bcast(&numresponses,1,ISSM_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/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/DakotaSpawnCore.h	(revision 18231)
@@ -0,0 +1,4 @@
+#ifndef _DAKOTA_SPAWN_CORE_
+#define _DAKOTA_SPAWN_CORE_
+int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ProcessArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ProcessArguments.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ProcessArguments.cpp	(revision 18231)
@@ -0,0 +1,57 @@
+/*!\file:  ProcessArguments.cpp
+ * \brief: process arguments
+ */ 
+
+#include <stdio.h>
+#include <cstring>
+
+#include "../shared/shared.h"
+
+void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ptoolkitsfilename,char** plockfilename,char** prootpath, int argc,char **argv){
+
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *toolkitsfilename  = NULL;
+	char *lockfilename   = NULL;
+	char *rootpath       = NULL;
+	char *rootpatharg    = NULL;
+
+	/*Check input arguments*/
+	if(argc<2)_error_("Usage error: no solution requested");
+	if(argc<3)_error_("Usage error: missing execution directory");
+	if(argc<4)_error_("Usage error: missing model name");
+
+	/*Get requested solution*/
+	*solution_type=StringToEnumx(argv[1]);
+
+	rootpatharg=argv[2];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	}
+
+	modelname=argv[3];
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s%s",rootpath,modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s",modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*ptoolkitsfilename=toolkitsfilename;
+	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ResetBoundaryConditions.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ResetBoundaryConditions.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ResetBoundaryConditions.cpp	(revision 18231)
@@ -0,0 +1,27 @@
+/*!\file: ResetBoundaryConditions.cpp
+ * \brief: change boundary conditions of a model, using a solution vector from another analysis
+ */ 
+
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/io/io.h"
+
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
+
+	/*variables: */
+	Vector<IssmDouble>* yg = NULL;
+
+	if(VerboseSolution()) _printf0_("   updating boundary conditions...\n");
+
+	/*set current analysis: */
+	femmodel->SetCurrentConfiguration(analysis_type);
+
+	/*retrieve boundary conditions from element inputs :*/
+	GetSolutionFromInputsx(&yg,femmodel);
+
+	/*update spcs using this new vector of constraints: */
+	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
+
+	/*Free ressources:*/
+	delete yg;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 18231)
@@ -0,0 +1,58 @@
+/*!\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 "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	/*parameters: */
+	bool control_analysis;
+	bool dakota_analysis;
+	int  inversiontype;
+
+	/* 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(&inversiontype,InversionTypeEnum);
+
+	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){
+		switch(inversiontype){
+			case 0: solutioncore=control_core; break;
+			case 1: solutioncore=controltao_core; break;
+			case 2: solutioncore=controlm1qn3_core; break;
+			case 3: solutioncore=controlvalidation_core; break;
+			default: _error_("control type not supported");
+		}
+	}
+	else CorePointerFromSolutionEnum(&solutioncore,parameters,solutiontype);  /*This means we retrieve a core solution that is not a wrapper*/
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ad_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ad_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/ad_core.cpp	(revision 18231)
@@ -0,0 +1,356 @@
+/*!\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 "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+/*}}}*/
+
+void ad_core(FemModel* femmodel){
+
+	/*diverse: */
+	int     i;
+	int     dummy;
+	int     num_dependents=0;
+	int     num_independents=0;
+	bool    isautodiff       = false;
+	char   *driver           = NULL;
+	size_t  tape_stats[11];
+
+	/*state variables: */
+	IssmDouble *axp = NULL;
+	double     *xp  = NULL;
+	int my_rank=IssmComm::GetRank();
+
+	/*AD mode on?: */
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+
+		#ifdef _HAVE_ADOLC_
+			if(VerboseAutodiff())_printf0_("   start ad core\n");
+
+			/*First, stop tracing: */
+			trace_off();
+		
+			/*retrieve parameters: */
+			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+	
+			/*if no dependents, no point in running a driver: */
+			if(!(num_dependents*num_independents)) return;
+
+			/*for adolc to run in parallel, we 0 out on rank~=0:*/
+			if (my_rank!=0){
+				num_dependents=0; num_independents=0;
+			}
+			
+			/*Print tape statistics so that user can kill this run if something is off already:*/
+			tapestats(my_rank,tape_stats); //reading of tape statistics
+			if(VerboseAutodiff()){
+				int commSize=IssmComm::GetSize();
+				int *sstats=new int[7];
+				sstats[0]=tape_stats[NUM_OPERATIONS];
+				sstats[1]=tape_stats[OP_FILE_ACCESS];
+				sstats[2]=tape_stats[NUM_LOCATIONS];
+				sstats[3]=tape_stats[LOC_FILE_ACCESS];
+				sstats[4]=tape_stats[NUM_VALUES];
+				sstats[5]=tape_stats[VAL_FILE_ACCESS];
+				sstats[6]=tape_stats[TAY_STACK_SIZE];
+				int *rstats=NULL;
+				if (my_rank==0) rstats=new int[commSize*7];
+				ISSM_MPI_Gather(sstats,7,ISSM_MPI_INT,rstats,7,ISSM_MPI_INT,0,IssmComm::GetComm());
+				if (my_rank==0) {
+					int offset=50;
+					int rOffset=(commSize/10)+1;
+					_printf_("   ADOLC statistics: \n");
+					_printf_("     "<<setw(offset)<<left<<"#independents: " <<setw(12)<<right<<tape_stats[NUM_INDEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"#dependents: " <<setw(12)<<right<<tape_stats[NUM_DEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"max #live active variables: " <<setw(12)<<right<<tape_stats[NUM_MAX_LIVES] << "\n");
+					_printf_("     operations: entry size "<< sizeof(unsigned char) << " Bytes \n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffObufsizeEnum) " <<setw(12)<<right<<tape_stats[OP_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+0] << (rstats[r*7+1]?" ->file":"") << "\n");
+					_printf_("     locations: entry size " << sizeof(locint) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffLbufsizeEnum) " <<setw(12)<<right<<tape_stats[LOC_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+2] << (rstats[r*7+3]?" ->file":"") << "\n");
+					_printf_("     constant values: entry size " << sizeof(double) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffCbufsizeEnum) " <<setw(12)<<right<<tape_stats[VAL_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+4] << (rstats[r*7+5]?" ->file":"") << "\n");
+					_printf_("     Taylor stack: entry size " << sizeof(revreal) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffTbufsizeEnum) " <<setw(12)<<right<<tape_stats[TAY_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+6] << (rstats[r*7+6]>tape_stats[TAY_BUFFER_SIZE]?" ->file":"") << "\n");
+					delete []rstats;
+				}
+				delete [] sstats;
+			}
+
+			/*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: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
+				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(my_rank,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: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+#endif
+				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*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(my_rank,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);
+				aWeightVector=xNewZeroInit<double>(num_dependents);
+				if (my_rank==0) {
+					if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
+					aWeightVector[aDepIndex]=1.0;
+				}
+				weightVectorTimesJac=xNew<double>(num_independents);
+
+				/*set the forward method function pointer: */
+#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+#endif
+#ifdef _HAVE_MUMPS_
+				anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
+#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				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(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+				if(VerboseAutodiff())_printf0_("   done with fos_reverse\n");
+
+				/*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: */
+				#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+				#endif
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				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(my_rank,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);
+
+			if(VerboseAutodiff())_printf0_("   end AD core\n");
+
+			/*Free resources: */
+			xDelete(xp);
+			xDelete(axp); 
+			xDelete(driver);
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness2_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness2_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness2_core.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file:  adjointbalancethickness2_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointbalancethickness2_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*compute thickness2 */
+	if(VerboseSolution()) _printf0_("   computing thickness2\n");
+	femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum,AdjointBalancethickness2AnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results || true){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[1] = {AdjointEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointbalancethickness_core.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file:  adjointbalancethickness_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointbalancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*compute thickness */
+	if(VerboseSolution()) _printf0_("   computing thickness\n");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[1] = {AdjointEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointstressbalance_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointstressbalance_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/adjointstressbalance_core.cpp	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file:  adjointstressbalance_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointstressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool isFS;
+	bool save_results;
+	bool conserve_loads   = true;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*Compute velocities*/
+	if(VerboseSolution()) _printf0_("   computing velocities\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	solutionsequence_nonlinear(femmodel,conserve_loads); 
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*Compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum,AdjointHorizAnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results || true){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		if (isFS){
+			//int outputs[4] = {AdjointxEnum,AdjointyEnum,AdjointzEnum,AdjointpEnum};
+			//femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
+			int outputs[3] = {AdjointxEnum,AdjointyEnum,AdjointpEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+		}
+		else{
+			int outputs[2] = {AdjointxEnum,AdjointyEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness2_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness2_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness2_core.cpp	(revision 18231)
@@ -0,0 +1,32 @@
+/*!\file: balancethickness_core.cpp
+ * \brief: core of the balancethickness solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancethickness2_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[4] = {ThicknessEnum,PotentialEnum,VxEnum,VyEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancethickness_core.cpp	(revision 18231)
@@ -0,0 +1,32 @@
+/*!\file: balancethickness_core.cpp
+ * \brief: core of the balancethickness solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs = ThicknessEnum;
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancevelocity_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancevelocity_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/balancevelocity_core.cpp	(revision 18231)
@@ -0,0 +1,37 @@
+/*!\file: balancevelocity_core.cpp
+ * \brief: core of the balancevelocity solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancevelocity_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing smoothed slopes:\n");
+	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeXAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeYAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	//surfaceslope_core(femmodel);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	femmodel->SetCurrentConfiguration(BalancevelocityAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[3] = {SurfaceSlopeXEnum,SurfaceSlopeYEnum,VelEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/bedslope_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/bedslope_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/bedslope_core.cpp	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\file: bedslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void bedslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+	int  domaintype;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	if(VerboseSolution()) _printf0_("   computing slope\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(L2ProjectionBaseAnalysisEnum);
+
+	femmodel->parameters->SetParam(BedSlopeXEnum,InputToL2ProjectEnum);
+	solutionsequence_linear(femmodel);
+
+	if(domaintype!=Domain2DverticalEnum){
+		femmodel->parameters->SetParam(BedSlopeYEnum,InputToL2ProjectEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		if(domaintype!=Domain2DverticalEnum){
+			int outputs[2] = {BedSlopeXEnum,BedSlopeYEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+		}
+		else{
+			int outputs[1] = {BedSlopeXEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/control_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/control_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/control_core.cpp	(revision 18231)
@@ -0,0 +1,265 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+/*{{{*/
+IssmDouble FormFunction(IssmDouble* X,void* usr);
+IssmDouble FormFunctionGradient(IssmDouble** pG,IssmDouble* X,void* usr);
+typedef struct {
+	FemModel* femmodel;
+	int       nsize;
+} AppCtx;
+/*}}}*/
+
+void control_core(FemModel* femmodel){/*{{{*/
+
+	/*parameters: */
+	int         num_controls,nsize,nsteps;
+	int         solution_type;
+	bool        isFS,dakota_analysis;
+	int        *control_type  = NULL;
+	int        *maxiter       = NULL;
+	IssmDouble *cm_jump       = NULL;
+	IssmDouble *J             = NULL;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*) = NULL;
+	void (*adjointcore)(FemModel*)  = NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,NULL,InversionMaxiterPerStepEnum);
+	femmodel->parameters->FindParam(&cm_jump,NULL,InversionStepThresholdEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*out of solution_type, figure out solution core and adjoint function pointer*/
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+
+	/*Launch once a complete solution to set up all inputs*/
+	if(VerboseControl()) _printf0_("   preparing initial solution\n");
+	if(isFS) solutioncore(femmodel);
+
+	/*Get initial guess*/
+	Vector<IssmDouble> *Xpetsc = NULL;
+	GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	IssmDouble* X0 = Xpetsc->ToMPISerial();
+	Xpetsc->GetSize(&nsize);
+	delete Xpetsc;
+
+	/*Initialize some of the BrentSearch arguments: */
+	OptPars optpars;
+	optpars.xmin    = 0; 
+	optpars.xmax    = 1;
+	optpars.nsteps  = nsteps;
+	optpars.nsize   = nsize;
+	optpars.maxiter = maxiter;
+	optpars.cm_jump = cm_jump;
+
+	/*Initialize function argument*/
+	AppCtx usr;
+	usr.femmodel = femmodel;
+	usr.nsize    = nsize;
+
+	/*Call Brent optimization*/
+	BrentSearch(&J,optpars,X0,&FormFunction,&FormFunctionGradient,(void*)&usr);
+
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X0[i]>XU[i]) X0[i]=XU[i];
+		if(X0[i]<XL[i]) X0[i]=XL[i];
+	}
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	SetControlInputsFromVectorx(femmodel,X0);
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	solutioncore(femmodel);
+
+	/*some results not computed by steadystate_core or stressbalance_core: */
+	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
+		femmodel->OutputControlsx(&femmodel->results);
+
+		#ifdef _HAVE_ADOLC_
+		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
+		for(int i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
+		xDelete<IssmPDouble>(J_passive);
+		#else
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
+		#endif
+	}
+
+	/*Free ressources: */
+	xDelete<int>(control_type);
+	xDelete<int>(maxiter);
+	xDelete<IssmDouble>(cm_jump);
+	xDelete<IssmDouble>(J);
+	xDelete<IssmDouble>(X0);
+}/*}}}*/
+IssmDouble FormFunction(IssmDouble* X,void* usrvoid){/*{{{*/
+
+	/*output: */
+	IssmDouble J;
+
+	/*parameters: */
+	int        solution_type,analysis_type,num_responses;
+	bool       conserve_loads = true;
+	AppCtx*    usr = (AppCtx*)usrvoid;
+	FemModel  *femmodel  = usr->femmodel;
+	int        nsize     = usr->nsize;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Constrain input vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X[i]>XU[i]) X[i]=XU[i];
+		if(X[i]<XL[i]) X[i]=XL[i];
+	}
+
+	/*Update control input*/
+	SetControlInputsFromVectorx(femmodel,X);
+
+	/*solve forward: */
+	switch(solution_type){
+		case SteadystateSolutionEnum:
+			femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+			stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+			break;
+		case StressbalanceSolutionEnum:
+			femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+			solutionsequence_nonlinear(femmodel,conserve_loads); 
+			break;
+		case BalancethicknessSolutionEnum:
+			femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+			solutionsequence_linear(femmodel); 
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			/*NOTHING*/
+			break;
+		case Balancethickness2SolutionEnum:
+			femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
+			solutionsequence_linear(femmodel); 
+			break;
+		default:
+			_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	}
+
+	/*Compute misfit for this velocity field.*/
+	IssmDouble* Jlist = NULL;
+	femmodel->CostFunctionx(&J,&Jlist,NULL);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<J<<"  |  ");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	xDelete<IssmDouble>(Jlist);
+	return J;
+}/*}}}*/
+IssmDouble FormFunctionGradient(IssmDouble** pG,IssmDouble* X,void* usrvoid){/*{{{*/
+
+	/*output: */
+	IssmDouble J;
+
+	/*parameters: */
+	void (*adjointcore)(FemModel*)=NULL;
+	int         solution_type,analysis_type,num_responses,num_controls,numvertices;
+	bool        conserve_loads = true;
+	IssmDouble *scalar_list    = NULL;
+	IssmDouble *Jlist          = NULL;
+	IssmDouble *G              = NULL;
+	IssmDouble *norm_list      = NULL;
+	AppCtx     *usr            = (AppCtx*)usrvoid;
+	FemModel   *femmodel       = usr->femmodel;
+	int         nsize          = usr->nsize;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&scalar_list,NULL,NULL,InversionGradientScalingEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
+	numvertices=femmodel->vertices->NumberOfVertices();
+
+	/*Constrain input vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X[i]>XU[i]) X[i]=XU[i];
+		if(X[i]<XL[i]) X[i]=XL[i];
+	}
+
+	/*Update control input*/
+	SetControlInputsFromVectorx(femmodel,X);
+
+	/*Compute new temperature at this point*/
+	if(solution_type==SteadystateSolutionEnum) steadystate_core(femmodel);
+
+	/*Compute Adjoint*/
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	adjointcore(femmodel);
+
+	/*Compute gradient*/
+	Gradjx(&G,&norm_list,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+	/*Compute scaling factor*/
+	IssmDouble scalar = scalar_list[0]/norm_list[0];
+	for(int i=1;i<num_controls;i++) scalar=min(scalar,scalar_list[i]/norm_list[i]);
+
+	/*Constrain Gradient*/
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<numvertices;j++){
+			G[i*numvertices+j] = scalar*G[i*numvertices+j];
+		}
+	}
+
+	for(long i=0;i<nsize;i++){
+		if(X[i]>=XU[i]) G[i]=0.;
+		if(X[i]<=XL[i]) G[i]=0.;
+	}
+
+	/*Needed for output results*/
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+
+	/*Compute misfit for this velocity field.*/
+	femmodel->CostFunctionx(&J,&Jlist,NULL);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<J<<"  |  ");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	xDelete<IssmDouble>(norm_list);
+	xDelete<IssmDouble>(scalar_list);
+	xDelete<IssmDouble>(Jlist);
+	*pG = G;
+	return J;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlm1qn3_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlm1qn3_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlm1qn3_core.cpp	(revision 18231)
@@ -0,0 +1,201 @@
+/*!\file: controlm1qn3_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include <config.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_M1QN3_)
+/*m1qn3 prototypes*/
+extern "C" void *ctonbe_; // DIS mode : Conversion
+extern "C" void *ctcabe_; // DIS mode : Conversion
+extern "C" void *euclid_; // Scalar product
+typedef void (*SimulFunc) (long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs);
+extern "C" void m1qn3_ (void f(long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs),
+			void **, void **, void **,
+			long *, double [], double *, double [], double*, double *,
+			double *, char [], long *, long *, long *, long *, long *, long *, long [], double [], long *,
+			long *, long *, long [], float [],void* );
+
+/*Cost function prototype*/
+void simul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs);
+
+void controlm1qn3_core(FemModel* femmodel){
+
+	/*Intermediaries*/
+	long         omode;
+	double       f,dxmin,gttol; 
+	int          maxsteps,maxiter;
+	int          intn,num_controls,solution_type;
+	IssmDouble  *X  = NULL;
+	IssmDouble  *G  = NULL;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&maxsteps,InversionMaxstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,InversionMaxiterEnum);
+	femmodel->parameters->FindParam(&dxmin,InversionDxminEnum);
+	femmodel->parameters->FindParam(&gttol,InversionGttolEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*Initialize M1QN3 parameters*/
+	if(VerboseControl())_printf0_("   Initialize M1QN3 parameters\n");
+	SimulFunc costfuncion  = &simul;    /*Cost function address*/
+	void**    prosca       = &euclid_;  /*Dot product function (euclid is the default)*/
+	char      normtype[]   = "dfn";     /*Norm type: dfn = scalar product defined by prosca*/
+	long      izs[5];                   /*Arrays used by m1qn3 subroutines*/
+	long      iz[5];                    /*Integer m1qn3 working array of size 5*/
+	float     rzs[1];                   /*Arrays used by m1qn3 subroutines*/
+	long      impres       = 0;         /*verbosity level*/
+	long      imode[3]     = {0};       /*scaling and starting mode, 0 by default*/
+	long      indic        = 4;         /*compute f and g*/
+	long      reverse      = 0;         /*reverse or direct mode*/
+	long      io           = 6;         /*Channel number for the output*/
+
+	/*Optimization criterions*/
+	long      niter        = long(maxsteps); /*Maximum number of iterations*/
+	long      nsim         = long(maxiter);/*Maximum number of function calls*/
+
+	/*Get initial guess*/
+	Vector<IssmDouble> *Xpetsc = NULL;
+	GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	X = Xpetsc->ToMPISerial();
+	Xpetsc->GetSize(&intn);
+	delete Xpetsc;
+
+	/*Get problem dimension and initialize gradient and initial guess*/
+	long n = long(intn);
+	G = xNew<double>(n);
+
+	/*Allocate m1qn3 working arrays (see doc)*/
+	long      m   = 100;
+	long      ndz = 4*n+m*(2*n+1);
+	double*   dz  = xNew<double>(ndz);
+
+	if(VerboseControl())_printf0_("   Computing initial solution\n");
+	_printf0_("\n");
+	_printf0_("Cost function f(x)   |  List of contributions\n");
+	_printf0_("_____________________________________________\n");
+	indic = 0; //no adjoint required
+	simul(&indic,&n,X,&f,G,izs,rzs,(void*)femmodel);
+	double f1=f;
+
+	indic = 4; //adjoint and gradient required
+	m1qn3_(costfuncion,prosca,&ctonbe_,&ctcabe_,
+				&n,X,&f,G,&dxmin,&f1,
+				&gttol,normtype,&impres,&io,imode,&omode,&niter,&nsim,iz,dz,&ndz,
+				&reverse,&indic,izs,rzs,(void*)femmodel);
+
+	switch(int(omode)){
+		case 0:  _printf0_("   Stop requested (indic = 0)\n"); break;
+		case 1:  _printf0_("   Convergence reached (gradient satisfies stopping criterion)\n"); break;
+		case 2:  _printf0_("   Bad initialization\n"); break;
+		case 3:  _printf0_("   Line search failure\n"); break;
+		case 4:  _printf0_("   Maximum number of iterations exceeded\n");break;
+		case 5:  _printf0_("   Maximum number of function calls exceeded\n"); break;
+		case 6:  _printf0_("   stopped on dxmin during line search\n"); break;
+		case 7:  _printf0_("   <g,d> > 0  or  <y,s> <0\n"); break;
+		default: _printf0_("   Unknown end condition\n");
+	}
+
+	/*Get solution*/
+	SetControlInputsFromVectorx(femmodel,X);
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+	femmodel->OutputControlsx(&femmodel->results);
+	femmodel->results->AddObject(new GenericExternalResult<double>(JEnum,f,1,0));
+
+	/*Finalize*/
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Clean-up and return*/
+	xDelete<double>(G);
+	xDelete<double>(X);
+	xDelete<double>(dz);
+}
+
+/*Cost function definition*/
+void simul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){
+
+	/*Recover Femmodel*/
+	int         solution_type;
+	FemModel   *femmodel  = (FemModel*)dzs;
+
+	/*Recover number of cost functions responses*/
+	int num_responses;
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Constrain input vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<*n;i++){
+		if(X[i]>XU[i]) X[i]=XU[i];
+		if(X[i]<XL[i]) X[i]=XL[i];
+	}
+
+	/*Update control input*/
+	SetControlInputsFromVectorx(femmodel,X);
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute solution and adjoint*/
+	void (*solutioncore)(FemModel*)=NULL;
+	void (*adjointcore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Compute objective function*/
+	IssmDouble* Jlist = NULL;
+	femmodel->CostFunctionx(pf,&Jlist,NULL);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
+
+	/*Retrieve objective functions independently*/
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+	xDelete<IssmDouble>(Jlist);
+
+	if(indic==0){
+		/*dry run, no gradient required*/
+		xDelete<IssmDouble>(XU);
+		xDelete<IssmDouble>(XL);
+		return;
+	}
+
+	/*Compute Adjoint*/
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	adjointcore(femmodel);
+
+	/*Compute gradient*/
+	IssmDouble* G2 = NULL;
+	Gradjx(&G2,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	for(long i=0;i<*n;i++) G[i] = -G2[i];
+	xDelete<IssmDouble>(G2);
+
+	/*Constrain Gradient*/
+	for(long i=0;i<*n;i++){
+		if(X[i]>=XU[i]) G[i]=0.;
+		if(X[i]<=XL[i]) G[i]=0.;
+	}
+
+	/*Clean-up and return*/
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+}
+
+#else
+void controlm1qn3_core(FemModel* femmodel){
+	_error_("M1QN3 not installed");
+}
+#endif //_HAVE_M1QN3_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controltao_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controltao_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controltao_core.cpp	(revision 18231)
@@ -0,0 +1,186 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+#include <config.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
+#include <tao.h>
+
+/*Local prototype*/
+int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
+int IssmMonitor(TaoSolver,void*);
+typedef struct {
+	FemModel* femmodel;
+	double*   J;
+} AppCtx;
+
+void controltao_core(FemModel* femmodel){
+
+	/*TAO*/
+	int                 ierr;
+	int                 num_controls,solution_type;
+	int                 maxsteps,maxiter;
+	IssmDouble          fatol,frtol,gatol,grtol,gttol;
+	AppCtx              user;
+	TaoSolver           tao = 0;
+	int                *control_list = NULL;
+	char               *algorithm    = NULL;
+	Vector<IssmDouble> *X            = NULL;
+	Vector<IssmDouble> *G            = NULL;
+	Vector<IssmDouble> *XL           = NULL;
+	Vector<IssmDouble> *XU           = NULL;
+
+	/*Initialize TAO*/
+	int argc; char **args=NULL;
+	PetscGetArgs(&argc,&args);
+	ierr = TaoInitialize(&argc,&args,(char*)0,"");
+	if(ierr) _error_("Could not initialize Tao");
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_list,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&maxsteps,InversionMaxstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,InversionMaxiterEnum);
+	femmodel->parameters->FindParam(&fatol,InversionFatolEnum);
+	femmodel->parameters->FindParam(&frtol,InversionFrtolEnum);
+	femmodel->parameters->FindParam(&gatol,InversionGatolEnum);
+	femmodel->parameters->FindParam(&grtol,InversionGrtolEnum);
+	femmodel->parameters->FindParam(&gttol,InversionGttolEnum);
+	femmodel->parameters->FindParam(&algorithm,InversionAlgorithmEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*Prepare Toolkit*/
+	ToolkitsOptionsFromAnalysis(femmodel->parameters,DefaultAnalysisEnum);
+
+	/*Initialize TAO*/
+	TaoCreate(IssmComm::GetComm(),&tao);
+	if(VerboseControl()) _printf0_("   Initializing the Toolkit for Advanced Optimization (TAO)\n");
+	TaoSetFromOptions(tao);
+	TaoSetType(tao,algorithm);
+
+	/*Prepare all TAO parameters*/
+	TaoSetMonitor(tao,IssmMonitor,&user,NULL);
+	TaoSetMaximumFunctionEvaluations(tao,maxiter);
+	TaoSetMaximumIterations(tao,maxsteps);
+	TaoSetTolerances(tao,fatol,frtol,gatol,grtol,gttol);
+
+	GetVectorFromControlInputsx(&X, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	TaoSetInitialVector(tao,X->pvector->vector);
+	TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
+	delete XL;
+	delete XU;
+
+	user.J=xNewZeroInit<double>(maxiter+5);
+	user.femmodel=femmodel;
+	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
+
+	/*Solver optimization problem*/
+	if(VerboseControl()) _printf0_("   Starting optimization\n");
+	TaoSolve(tao);
+	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
+
+	/*Save results*/
+	TaoGetSolutionVector(tao,&X->pvector->vector);
+	G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
+	TaoGetGradientVector(tao,&G->pvector->vector);
+	SetControlInputsFromVectorx(femmodel,X);
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+	femmodel->OutputControlsx(&femmodel->results);
+	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
+
+	/*Finalize*/
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Clean up and return*/
+	xDelete<int>(control_list);
+	xDelete<char>(algorithm);
+	xDelete<double>(user.J);
+	delete X;
+	TaoDestroy(&tao);
+	TaoFinalize();
+}
+int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *uservoid){
+
+	/*Retreive arguments*/
+	int                  solution_type;
+	AppCtx              *user            = (AppCtx *)uservoid;
+	FemModel            *femmodel        = user->femmodel;
+	Vector<IssmDouble>  *gradient        = NULL;
+	Vector<IssmDouble>  *X               = NULL;
+
+	/*Convert input to Vec*/
+	X=new Vector<IssmDouble>(Xpetsc);
+
+	/*Set new variable*/
+	//VecView(X,PETSC_VIEWER_STDOUT_WORLD);
+	SetControlInputsFromVectorx(femmodel,X);
+	delete X;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute solution and adjoint*/
+	void (*solutioncore)(FemModel*)=NULL;
+	void (*adjointcore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	solutioncore(femmodel);
+	adjointcore(femmodel);
+
+	/*Compute objective function*/
+	femmodel->CostFunctionx(fcn,NULL,NULL);
+
+	/*Compute gradient*/
+	Gradjx(&gradient,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	VecCopy(gradient->pvector->vector,G); delete gradient;
+	VecScale(G,-1.);
+
+	/*Clean-up and return*/
+	return 0;
+}
+int IssmMonitor(TaoSolver tao, void *userCtx){
+
+	int         its,num_responses;
+	IssmDouble  f,gnorm,cnorm,xdiff;
+	AppCtx     *user      = (AppCtx *)userCtx;
+	FemModel   *femmodel  = user->femmodel;
+	int        *responses = NULL;
+
+	femmodel->parameters->FindParam(&responses,&num_responses,InversionCostFunctionsEnum);
+
+	TaoGetSolutionStatus(tao, &its, &f, &gnorm, &cnorm, &xdiff, NULL);
+	if(its==0) _printf0_("Iter       Function      Residual  |  List of contributions\n");
+	if(its==0) _printf0_("___________________________________________________________\n");
+	_printf0_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
+	user->J[its]=f;
+
+	/*Retrieve objective functions independently*/
+	for(int i=0;i<num_responses;i++){
+		femmodel->Responsex(&f,EnumToStringx(responses[i]));
+		_printf0_(" "<<setw(12)<<setprecision(7)<<f);
+	}
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<int>(responses);
+	return 0;
+}
+
+#else
+void controltao_core(FemModel* femmodel){
+	_error_("TAO not installed or PETSc version not supported");
+}
+#endif //_HAVE_TAO_ 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlvalidation_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlvalidation_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/controlvalidation_core.cpp	(revision 18231)
@@ -0,0 +1,102 @@
+/*!\file: controlvalidation_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void controlvalidation_core(FemModel* femmodel){
+
+	int         solution_type,n;
+	IssmDouble  j0,j;
+	IssmDouble  Ialpha,exponent,alpha;
+	IssmDouble *G = NULL;
+	IssmDouble *X = NULL;
+	IssmDouble *X0= NULL;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*) = NULL;
+	void (*adjointcore)(FemModel*)  = NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*Get initial guess*/
+	Vector<IssmDouble> *Xpetsc = NULL;
+	GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	Xpetsc->GetSize(&n);
+	X0 = Xpetsc->ToMPISerial();
+	delete Xpetsc;
+
+	/*Allocate Gradient and current vector*/
+	G = xNew<IssmDouble>(n);
+	X = xNew<IssmDouble>(n);
+
+	/*out of solution_type, figure out solution core and adjoint function pointer*/
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+
+	if(VerboseControl()) _printf0_("   Compute Initial solution\n");
+	solutioncore(femmodel);
+	if(VerboseControl()) _printf0_("   Compute Adjoint\n");
+	adjointcore(femmodel);
+	if(VerboseControl()) _printf0_("   Compute Initial cost function\n");
+	femmodel->CostFunctionx(&j0,NULL,NULL);
+	if(VerboseControl()) _printf0_("   Compute Gradient\n");
+	Gradjx(&G,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	for(int i=0;i<n;i++) G[i] = -G[i];
+
+	/*Range of tests*/
+	IssmDouble exp0 = 0.;
+	IssmDouble incr = -0.2;
+	IssmDouble exp1 = -10.;
+	int        num  = reCast<int,IssmDouble>((exp1-exp0)/incr);
+
+	/*Allocate output*/
+	IssmDouble* output = xNew<IssmDouble>(2*num);
+
+	/*Start loop*/
+	_printf0_("       alpha      Ialpha \n");
+	_printf0_("_________________________\n");
+	for(int m=0;m<num;m++){
+
+		/*Calculate alpha = 10^-exponent*/
+		exponent = exp0+m*incr;
+		alpha    = pow(10.,exponent);
+
+		/*Create new vector*/
+		for(int i=0;i<n;i++) X[i] = X0[i] + alpha;
+
+		/*Calculate j(k+alpha delta k) */
+		SetControlInputsFromVectorx(femmodel,X);
+		solutioncore(femmodel);
+		femmodel->CostFunctionx(&j,NULL,NULL);
+
+		IssmDouble Den = 0.;
+		for(int i=0;i<n;i++) Den += alpha * G[i] * 1.;
+		Ialpha = fabs((j - j0)/Den - 1.);
+
+		_printf0_(" " << setw(11) << setprecision (5)<<alpha<<" " << setw(11) << setprecision (5)<<Ialpha<<"\n");
+		output[m*2+0] = alpha;
+		output[m*2+1] = Ialpha;
+	}
+
+	/*output*/
+	#ifdef _HAVE_ADOLC_
+	IssmPDouble* J_passive=xNew<IssmPDouble>(2*num);
+	for(int i=0;i<2*num;i++) J_passive[i]=reCast<IssmPDouble>(output[i]);
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,num,2,1,0));
+	xDelete<IssmPDouble>(J_passive);
+	#else
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,output,num,2,1,0));
+	#endif
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(G);
+	xDelete<IssmDouble>(X);
+	xDelete<IssmDouble>(X0);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/cores.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/cores.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/cores.h	(revision 18231)
@@ -0,0 +1,64 @@
+/*
+ * cores.h: 
+ */
+
+#ifndef _CORES_H_
+#define _CORES_H_
+
+/*forward declarations: */
+class FemModel;
+class Parameters;
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+
+#include "../shared/io/Comm/IssmComm.h"
+#include "../shared/Numerics/types.h"
+
+/*cores: */
+void adjointstressbalance_core(FemModel* femmodel);
+void adjointbalancethickness_core(FemModel* femmodel);
+void adjointbalancethickness2_core(FemModel* femmodel);
+void stressbalance_core(FemModel* femmodel);
+void hydrology_core(FemModel* femmodel);
+void thermal_core(FemModel* femmodel);
+void surfaceslope_core(FemModel* femmodel);
+void levelsetfunctionslope_core(FemModel* femmodel);
+void bedslope_core(FemModel* femmodel);
+void meshdeformation_core(FemModel* femmodel);
+void control_core(FemModel* femmodel);
+void controltao_core(FemModel* femmodel);
+void controlm1qn3_core(FemModel* femmodel);
+void controlvalidation_core(FemModel* femmodel);
+void masstransport_core(FemModel* femmodel);
+void depthaverage_core(FemModel* femmodel);
+void extrudefrombase_core(FemModel* femmodel);
+void extrudefromtop_core(FemModel* femmodel);
+void balancethickness_core(FemModel* femmodel);
+void balancethickness2_core(FemModel* femmodel);
+void balancevelocity_core(FemModel* femmodel);
+void slopecompute_core(FemModel* femmodel);
+void steadystate_core(FemModel* femmodel);
+void transient_core(FemModel* femmodel);
+void dakota_core(FemModel* femmodel);
+void ad_core(FemModel* femmodel);
+void dummy_core(FemModel* femmodel);
+void gia_core(FemModel* femmodel);
+void damage_core(FemModel* femmodel);
+IssmDouble objectivefunction(IssmDouble search_scalar,FemModel* femmodel);
+
+//optimization
+int GradJSearch(IssmDouble* search_vector,FemModel* femmodel,int step);
+
+//diverse
+void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ptoolkitsname,char** plockname,char** prootpath,int argc,char **argv);
+void WriteLockFile(char* filename);
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
+void PrintBanner(void);
+
+//solution configuration
+void AnalysisConfiguration(int** pcores,int* pnumcores, int solutiontype);
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dakota_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dakota_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dakota_core.cpp	(revision 18231)
@@ -0,0 +1,230 @@
+/*!\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 (stressbalance_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
+ * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up DakotaSpawnCore.cpp, 
+ * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
+ * 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 "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+#include "../classes/classes.h"
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <ParallelLibrary.H>
+#include <ProblemDescDB.H>
+#include <DakotaStrategy.H>
+#include <DakotaModel.H>
+#include <DakotaInterface.H>
+#else
+#include <ParallelLibrary.hpp>
+#include <ProblemDescDB.hpp>
+#include <DakotaStrategy.hpp>
+#include <DakotaModel.hpp>
+#include <DakotaInterface.hpp>
+#endif
+#include "./DakotaSpawnCore.h"
+#endif
+/*}}}*/
+/*DakotaPlugin class {{{*/
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <DirectApplicInterface.H>
+#include <DakotaResponse.H>
+#include <ParamResponsePair.H>
+#include <system_defs.h>
+#include <ProblemDescDB.H>
+#include <ParallelLibrary.H>
+#else
+#include <DirectApplicInterface.hpp>
+#include <DakotaResponse.hpp>
+#include <ParamResponsePair.hpp>
+#include <ProblemDescDB.hpp>
+#include <ParallelLibrary.hpp>
+#endif
+namespace SIM {
+	class DakotaPlugin: public Dakota::DirectApplicInterface{
+		public:
+			/*these fields are used by core solutions: */
+			void *femmodel;
+			int   counter;
+			/*Constructors/Destructors*/
+			DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){/*{{{*/
+				femmodel = in_femmodel;
+				counter  = 0;
+			}/*}}}*/
+			~DakotaPlugin(){/*{{{*/
+				/* Virtual destructor handles referenceCount at Interface level. */ 
+			}/*}}}*/
+		protected:
+			/*execute the input filter portion of a direct evaluation invocation*/
+			//int derived_map_if(const Dakota::String& if_name);
+			/*execute an analysis code portion of a direct evaluation invocation*/
+			int derived_map_ac(const Dakota::String& driver){/*{{{*/
+
+				int i;
+				IssmDouble* variables=NULL;
+				char** variable_descriptors=NULL;
+				char*  variable_descriptor=NULL;
+				IssmDouble* responses=NULL;
+
+				/*increae counter: */
+				counter++;
+
+				/*Before launching analysis, we need to transfer the dakota inputs into Issm 
+				 *readable variables: */
+
+				/*First, the variables: */
+				variables=xNew<IssmDouble>(numACV);
+				for(i=0;i<numACV;i++){
+					variables[i]=xC[i];
+				}
+				/*The descriptors: */
+				variable_descriptors=xNew<char*>(numACV);
+				for(i=0;i<numACV;i++){
+					std::string label=xCLabels[i];
+					variable_descriptor=xNew<char>(strlen(label.c_str())+1);
+					memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
+
+					variable_descriptors[i]=variable_descriptor;
+				}
+
+				/*Initialize responses: */
+				responses=xNewZeroInit<IssmDouble>(numFns);
+
+				/*run core solution: */
+				DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
+
+				/*populate responses: */
+				for(i=0;i<numFns;i++){
+					fnVals[i]=responses[i];
+				}
+
+				/*Free ressources:*/
+				xDelete<IssmDouble>(variables);
+				for(i=0;i<numACV;i++){
+					variable_descriptor=variable_descriptors[i];
+					xDelete<char>(variable_descriptor);
+				}
+				xDelete<char*>(variable_descriptors);
+				xDelete<IssmDouble>(responses);
+
+				return 0;
+			}/*}}}*/
+			/*execute the output filter portion of a direct evaluation invocation*/
+			//int derived_map_of(const Dakota::String& of_name);
+			/*add for issm: */
+			int GetCounter(){/*{{{*/
+				return counter;
+			}/*}}}*/
+		private:
+	};
+} 
+#endif
+/*}}}*/
+
+void dakota_core(FemModel* femmodel){ 
+
+	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+	int                my_rank;
+	char              *dakota_input_file  = NULL;
+	char              *dakota_output_file = NULL;
+	char              *dakota_error_file  = NULL;
+	Dakota::ModelLIter ml_iter;
+
+	/*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.
+		char* dakotamode=xNew<char>(strlen("serial")+1);
+		xMemCpy<char>(dakotamode,"serial",strlen("serial")+1);
+		Dakota::ParallelLibrary parallel_lib(dakotamode); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
+		Dakota::ProblemDescDB problem_db(parallel_lib); 
+		xDelete<char>(dakotamode);
+
+		// Manage input file parsing, output redirection, and restart processing
+		// 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/branches/trunk-jpl-ad2-integrated/src/c/cores/damage_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/damage_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/damage_core.cpp	(revision 18231)
@@ -0,0 +1,50 @@
+/* 
+ * \brief: damgage_core.cpp: core for the damage solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void damage_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results;
+	bool   dakota_analysis     = false;
+	int    solution_type;
+	int    numoutputs          = 0; 
+	char   **requested_outputs = NULL;
+
+	
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,DamageEvolutionNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,DamageEvolutionRequestedOutputsEnum);
+
+	if(dakota_analysis && solution_type!=TransientSolutionEnum){
+		femmodel->SetCurrentConfiguration(DamageEvolutionAnalysisEnum);
+		ResetConstraintsx(femmodel);
+	}
+
+	if(VerboseSolution()) _printf0_("   computing damage\n");
+	femmodel->SetCurrentConfiguration(DamageEvolutionAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+	
+	/*Free resources:*/	
+	if(numoutputs){
+		for(int i=0;i<numoutputs;i++){
+			xDelete<char>(requested_outputs[i]);
+		} 
+		xDelete<char*>(requested_outputs);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/depthaverage_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/depthaverage_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/depthaverage_core.cpp	(revision 18231)
@@ -0,0 +1,20 @@
+/*!\file: depthaverage_core.cpp
+ * \brief: core of the extrusion solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void depthaverage_core(FemModel* femmodel){
+
+	if(VerboseSolution()) _printf0_("depth averaging...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(DepthAverageAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dummy_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dummy_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/dummy_core.cpp	(revision 18231)
@@ -0,0 +1,11 @@
+/*!\file: dummy_core.cpp
+ * \brief: dummy core (nothing done)
+ */ 
+
+class FemModel;
+
+void dummy_core(FemModel* femmodel){
+
+	/*We do not do anything*/
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefrombase_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefrombase_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefrombase_core.cpp	(revision 18231)
@@ -0,0 +1,37 @@
+/*!\file: extrudefrombase_core.cpp
+ * \brief: core of the extrusion solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void extrudefrombase_core(FemModel* femmodel){
+
+	/*Intermediaries*/
+	int elementtype,domaintype;
+
+	if(VerboseSolution()) _printf0_("extruding solution from base...\n");
+
+	/*Get parameters*/
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&elementtype,MeshElementtypeEnum);
+
+	/*If this is a 2D horizontal domain, return (no need to extrude)*/
+	if(domaintype==Domain2DhorizontalEnum) return;
+
+	/*Special method for Penta, otherwise call solution sequence*/
+	if(elementtype==PentaEnum){
+		int inputenum; femmodel->parameters->FindParam(&inputenum,InputToExtrudeEnum);
+		InputExtrudex(femmodel,inputenum);
+	}
+	else{
+		/*Call on core computations: */
+		femmodel->SetCurrentConfiguration(ExtrudeFromBaseAnalysisEnum);
+		femmodel->UpdateConstraintsExtrudeFromBasex();
+		solutionsequence_linear(femmodel);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefromtop_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefromtop_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/extrudefromtop_core.cpp	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file: extrudefromtop_core.cpp
+ * \brief: core of the extrusion solution
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void extrudefromtop_core(FemModel* femmodel){
+
+	if(VerboseSolution()) _printf0_("extruding solution from top...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(ExtrudeFromTopAnalysisEnum);
+	femmodel->UpdateConstraintsExtrudeFromTopx();
+	solutionsequence_linear(femmodel);
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/gia_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/gia_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/gia_core.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file: gia_core.cpp
+ * \brief: core of the GIA solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+void gia_core(FemModel* femmodel){
+
+	Vector<IssmDouble> *wg    = NULL;
+	Vector<IssmDouble> *dwdtg = NULL;
+	IssmDouble          *x    = NULL;
+	IssmDouble          *y    = NULL;
+
+	/*parameters: */
+	bool save_results;
+	int  gsize;
+	int  configuration_type;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	if(VerboseSolution()) _printf0_("   computing GIA\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(GiaAnalysisEnum);
+
+	/*Figure out size of g-set deflection vector and allocate solution vector: */
+	gsize      = femmodel->nodes->NumberOfDofs(configuration_type,GsetEnum);
+	wg = new Vector<IssmDouble>(gsize);
+	dwdtg = new Vector<IssmDouble>(gsize);
+
+	/*first, recover x and y vectors from vertices: */
+	VertexCoordinatesx(&x,&y,NULL,femmodel->vertices); //no need for z coordinate
+
+	/*call the main module: */
+	femmodel->Deflection(wg,dwdtg,x,y);
+
+	/*assemble vector: */
+	wg->Assemble();
+	dwdtg->Assemble();
+
+	InputUpdateFromVectorx(femmodel,wg,GiaWEnum,VertexSIdEnum);
+	InputUpdateFromVectorx(femmodel,dwdtg,GiadWdtEnum,VertexSIdEnum);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		int outputs[2] = {GiaWEnum,GiadWdtEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/hydrology_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/hydrology_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/hydrology_core.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file: hydrology_core.cpp
+ * \brief: core of the hydrology solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void hydrology_core(FemModel* femmodel){
+
+	/*intermediary*/
+	int        hydrology_model;
+	bool       save_results;
+	bool       modify_loads=true;
+	bool       isefficientlayer;
+
+	/*first recover parameters common to all solutions*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&hydrology_model,HydrologyModelEnum);
+
+	/*first compute slopes: */
+	if (hydrology_model==HydrologyshreveEnum){
+		surfaceslope_core(femmodel);
+		bedslope_core(femmodel);
+	}
+
+	/*Using the Shreve based Model*/
+	if (hydrology_model==HydrologyshreveEnum){
+		if(VerboseSolution()) _printf0_("   computing water column\n");
+		femmodel->SetCurrentConfiguration(HydrologyShreveAnalysisEnum);
+		solutionsequence_nonlinear(femmodel,modify_loads);
+		
+		/*transfer water column thickness to old water column thickness: */
+		InputDuplicatex(femmodel,WatercolumnEnum,WaterColumnOldEnum);
+		
+		if(save_results){
+			if(VerboseSolution()) _printf0_("   saving results \n");
+			int outputs[3] = {WatercolumnEnum,HydrologyWaterVxEnum,HydrologyWaterVyEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+			
+			/*unload results*/
+			if(VerboseSolution()) _printf0_("   saving temporary results\n");
+			OutputResultsx(femmodel);
+		}
+	}
+
+	/*Using the double continuum model*/
+	else if (hydrology_model==HydrologydcEnum){
+		InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+		femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+		if (isefficientlayer){
+			InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
+			InputDuplicatex(femmodel,HydrologydcEplThicknessEnum,HydrologydcEplThicknessOldEnum);
+		}
+		
+		/*Proceed now to heads computations*/
+		if(VerboseSolution()) _printf0_("   computing water head\n");
+		solutionsequence_hydro_nonlinear(femmodel);
+
+		if(save_results){
+			if(VerboseSolution()) _printf0_("   saving results \n");
+			if(isefficientlayer){
+				int outputs[9] = {SedimentHeadEnum,SedimentHeadResidualEnum,EplHeadEnum,HydrologydcMaskEplactiveNodeEnum,HydrologydcMaskEplactiveEltEnum,EplHeadSlopeXEnum,EplHeadSlopeYEnum,HydrologydcEplThicknessEnum,EffectivePressureEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],9);
+			}
+			else{
+				int outputs[3] = {SedimentHeadEnum,SedimentHeadResidualEnum,EffectivePressureEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+			}
+			/*unload results*/
+			if(VerboseSolution()) _printf0_("   saving temporary results\n");
+			OutputResultsx(femmodel);
+		}
+	}
+}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/levelsetfunctionslope_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/levelsetfunctionslope_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/levelsetfunctionslope_core.cpp	(revision 18231)
@@ -0,0 +1,52 @@
+/*!\file: levelsetfunctionslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void levelsetfunctionslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+	int  domaintype;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	if(VerboseSolution()) _printf0_("computing slope of levelset function...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(L2ProjectionBaseAnalysisEnum);
+
+	femmodel->parameters->SetParam(LevelsetfunctionSlopeXEnum,InputToL2ProjectEnum);
+	solutionsequence_linear(femmodel);
+
+	if(domaintype!=Domain2DverticalEnum){
+		femmodel->parameters->SetParam(LevelsetfunctionSlopeYEnum,InputToL2ProjectEnum);
+		solutionsequence_linear(femmodel);
+	}
+	if(domaintype==Domain2DverticalEnum){
+	      femmodel->parameters->SetParam(LevelsetfunctionSlopeXEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("saving results:\n");
+		if(domaintype!=Domain2DverticalEnum){
+			int outputs[2] = {LevelsetfunctionSlopeXEnum,LevelsetfunctionSlopeYEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+
+		}
+		else{
+			int outputs = LevelsetfunctionSlopeXEnum;
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/masstransport_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/masstransport_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/masstransport_core.cpp	(revision 18231)
@@ -0,0 +1,77 @@
+/*!\file: masstransport_core.cpp
+ * \brief: core of the masstransport solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void masstransport_core(FemModel* femmodel){
+
+	/*parameters: */
+	int    numoutputs,domaintype;
+	bool   save_results;
+	bool   isFS,isfreesurface,dakota_analysis;
+	int    solution_type;
+	char** requested_outputs = NULL;
+
+	/*activate configuration*/
+	femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&isfreesurface,MasstransportIsfreesurfaceEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==MasstransportSolutionEnum){
+		InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
+		InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
+		InputDuplicatex(femmodel,QmuBaseEnum,BaseEnum);
+	}
+
+	/*Calculate new Surface Mass Balance (SMB)*/
+	SurfaceMassBalancex(femmodel);
+
+	/*Transport mass or free surface*/
+	if(isFS && isfreesurface){
+		if(VerboseSolution()) _printf0_("   call free surface computational core\n");
+		femmodel->SetCurrentConfiguration(FreeSurfaceBaseAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+
+		femmodel->SetCurrentConfiguration(FreeSurfaceTopAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
+		extrudefromtop_core(femmodel);
+	}
+	else{
+		if(VerboseSolution()) _printf0_("   call computational core\n");
+		solutionsequence_linear(femmodel);
+		femmodel->parameters->SetParam(ThicknessEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+		femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+		femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	if(solution_type==MasstransportSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/meshdeformation_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/meshdeformation_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/meshdeformation_core.cpp	(revision 18231)
@@ -0,0 +1,30 @@
+/*!\file: meshdeformation_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void meshdeformation_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing mesh deformation (elasticity)...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(MeshdeformationAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("saving results:\n");
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/steadystate_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/steadystate_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/steadystate_core.cpp	(revision 18231)
@@ -0,0 +1,125 @@
+/*!\file: steadystate_core.cpp
+ * \brief: core of the steadystate solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol);
+
+void steadystate_core(FemModel* femmodel){
+
+	/*intermediary: */
+	int step; 
+	Vector<IssmDouble>* ug     = NULL;
+	Vector<IssmDouble>* ug_old = NULL;
+	Vector<IssmDouble>* tg     = NULL;
+	Vector<IssmDouble>* tg_old = NULL;
+
+	/*parameters: */
+	bool        save_results,isenthalpy;
+	int         maxiter;
+	IssmDouble  reltol;
+	int         numoutputs        = 0;
+	char** requested_outputs = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&maxiter,SteadystateMaxiterEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	femmodel->parameters->FindParam(&reltol,SteadystateReltolEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	femmodel->parameters->FindParam(&numoutputs,SteadystateNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,SteadystateRequestedOutputsEnum);
+
+	/*intialize counters: */
+	step=1;
+
+	for(;;){
+
+		if(VerboseSolution()) _printf0_("   computing temperature and velocity for step: " << step << "\n");
+		thermal_core(femmodel);
+		if(!isenthalpy)femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);/*Could be MeltingAnalysis...*/
+		GetSolutionFromInputsx(&tg,femmodel);
+
+		if(VerboseSolution()) _printf0_("   computing new velocity\n");
+		stressbalance_core(femmodel);
+		GetSolutionFromInputsx(&ug,femmodel);
+
+		if(step>1){
+			if(VerboseSolution()) _printf0_("   checking steadystate convergence\n");
+			if(steadystateconvergence(tg,tg_old,ug,ug_old,reltol)) break;
+		}
+		if(step>maxiter){
+			if(VerboseSolution()) _printf0_("   maximum number steadystate iterations " << maxiter << " reached\n");
+			break;
+		}
+
+		/*update results and increase counter*/
+		delete tg_old;tg_old=tg;
+		delete ug_old;ug_old=ug;
+		step++;
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/
+	delete tg_old;
+	delete ug_old;
+	delete tg;
+	delete ug;	
+	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
+}
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol){
+
+	/*Output*/
+	bool converged = true;
+
+	/*Intermediary*/
+	Vector<IssmDouble>* dug    = NULL;
+	Vector<IssmDouble>* dtg    = NULL;
+	IssmDouble          ndt,nt;
+	IssmDouble          ndu,nu;
+
+	/*compute norm(du)/norm(u)*/
+	dug=ug_old->Duplicate(); ug_old->Copy(dug); dug->AYPX(ug,-1.0);
+	ndu=dug->Norm(NORM_TWO); nu=ug_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+	if((ndu/nu)<reltol){
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*compute norm(dt)/norm(t)*/
+	dtg=tg_old->Duplicate(); tg_old->Copy(dtg); dtg->AYPX(tg,-1.0);
+	ndt=dtg->Norm(NORM_TWO); nt=tg_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndt) || xIsNan<IssmDouble>(nt)) _error_("convergence criterion is NaN!");
+	if((ndt/nt)<reltol){
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*clean up and return*/
+	delete dtg;
+	delete dug;
+	return converged;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/stressbalance_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/stressbalance_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/stressbalance_core.cpp	(revision 18231)
@@ -0,0 +1,92 @@
+/*!\file: stressbalance_core.cpp
+ * \brief: core of the stressbalance solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../analyses/analyses.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void stressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool       dakota_analysis;
+	int        domaintype;
+	bool       isSIA,isSSA,isL1L2,isHO,isFS;
+	bool       save_results;
+	int        solution_type;
+	int        numoutputs        = 0;
+	char     **requested_outputs = NULL;
+	Analysis  *analysis          = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&isSIA,FlowequationIsSIAEnum);
+	femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+	femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
+	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==StressbalanceSolutionEnum){
+		InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
+		InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
+		if(domaintype==Domain3DEnum) InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
+		if(isFS) InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
+	}
+
+	/*Compute slopes if necessary */
+	if(isSIA || (isFS && domaintype==Domain2DverticalEnum)) surfaceslope_core(femmodel);
+	if(isFS){
+		bedslope_core(femmodel);
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		ResetFSBasalBoundaryConditionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	/*Compute SIA velocities*/
+	if(isSIA){
+
+		/*Take the last velocity into account so that the velocity on the SSA domain is not zero*/
+		if(isSSA || isL1L2 || isHO ) ResetBoundaryConditions(femmodel,StressbalanceSIAAnalysisEnum);
+
+		analysis = new StressbalanceSIAAnalysis();
+		analysis->Core(femmodel);
+		delete analysis;
+
+		/*Reset velocities for other ice flow models*/
+		if(isSSA || isL1L2 || isHO) ResetBoundaryConditions(femmodel,StressbalanceAnalysisEnum);
+	}
+
+	/*Compute stressbalance for SSA L1L2 HO and FS*/
+	if(isSSA || isL1L2 || isHO || isFS){
+		analysis = new StressbalanceAnalysis();
+		analysis->Core(femmodel);
+		delete analysis;
+	}
+
+	/*Compute vertical velocities*/
+	if (domaintype==Domain3DEnum && (isSIA || isSSA || isL1L2 || isHO)){
+		analysis = new StressbalanceVerticalAnalysis();
+		analysis->Core(femmodel);
+		delete analysis;
+	}
+
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	if(solution_type==StressbalanceSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/	
+	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/surfaceslope_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/surfaceslope_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/surfaceslope_core.cpp	(revision 18231)
@@ -0,0 +1,52 @@
+/*!\file: surfaceslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void surfaceslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+	int  domaintype;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	if(VerboseSolution()) _printf0_("computing slope...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(L2ProjectionBaseAnalysisEnum);
+
+	femmodel->parameters->SetParam(SurfaceSlopeXEnum,InputToL2ProjectEnum);
+	solutionsequence_linear(femmodel);
+
+	if(domaintype!=Domain2DverticalEnum){
+		femmodel->parameters->SetParam(SurfaceSlopeYEnum,InputToL2ProjectEnum);
+		solutionsequence_linear(femmodel);
+	}
+	if(domaintype==Domain2DverticalEnum){
+		femmodel->parameters->SetParam(SurfaceSlopeXEnum,InputToExtrudeEnum);
+		extrudefrombase_core(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("saving results:\n");
+		if(domaintype!=Domain2DverticalEnum){
+			int outputs[2] = {SurfaceSlopeXEnum,SurfaceSlopeYEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+
+		}
+		else{
+			int outputs = SurfaceSlopeXEnum;
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/thermal_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/thermal_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/thermal_core.cpp	(revision 18231)
@@ -0,0 +1,75 @@
+/*!\file: thermal_core.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../analyses/analyses.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void thermal_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results,isenthalpy;
+	bool   dakota_analysis;
+	int    solution_type,numoutputs;
+	char** requested_outputs = NULL;
+	EnthalpyAnalysis * enthalpy_analysis = NULL;
+
+	/*first recover parameters common to all solutions*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	femmodel->parameters->FindParam(&numoutputs,ThermalNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,ThermalRequestedOutputsEnum);
+
+	if(dakota_analysis && solution_type!=TransientSolutionEnum){
+		InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
+		InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
+		InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
+		InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
+		InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsGroundediceMeltingRateEnum);
+		InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		ResetConstraintsx(femmodel);
+	}
+
+	if(isenthalpy){
+
+		if(VerboseSolution()) _printf0_("   computing enthalpy\n");
+		femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
+		solutionsequence_nonlinear(femmodel,true);
+
+		/*transfer enthalpy to enthalpy picard for the next step: */
+		InputDuplicatex(femmodel,EnthalpyEnum,EnthalpyPicardEnum);
+
+		if(solution_type!=SteadystateSolutionEnum){
+			/*Post process*/
+			enthalpy_analysis = new EnthalpyAnalysis();
+			enthalpy_analysis->PostProcessing(femmodel);
+			delete enthalpy_analysis;
+		}
+	}
+	else{
+		if(VerboseSolution()) _printf0_("   computing temperatures\n");
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		solutionsequence_thermal_nonlinear(femmodel);
+
+		if(VerboseSolution()) _printf0_("   computing melting\n");
+		femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/	
+	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/transient_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/transient_core.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/cores/transient_core.cpp	(revision 18231)
@@ -0,0 +1,216 @@
+/*!\file: transient_3d_core.cpp
+ * \brief: core of the transient_3d solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <float.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void transient_core(FemModel* femmodel){
+
+	/*parameters: */
+	IssmDouble starttime,finaltime,dt,yts;
+	bool       isstressbalance,ismasstransport,isFS,isthermal,isgroundingline,isgia,islevelset,isdamageevolution,ishydrology;
+	bool       save_results,dakota_analysis;
+	bool       time_adapt=false;
+	int        output_frequency;
+	int        domaintype,groundingline_migration;
+	int        numoutputs         = 0;
+	Analysis  *analysis = NULL;
+	char**     requested_outputs = NULL;
+
+
+	/*intermediary: */
+	int    step;
+	IssmDouble time;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
+	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
+	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
+	femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
+	femmodel->parameters->FindParam(&isgia,TransientIsgiaEnum);
+	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	femmodel->parameters->FindParam(&isdamageevolution,TransientIsdamageevolutionEnum);
+	femmodel->parameters->FindParam(&ishydrology,TransientIshydrologyEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
+	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
+
+	/*initialize: */
+	step=0;
+	time=starttime;
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis){
+		if(isstressbalance){
+			InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
+			InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
+			if(domaintype==Domain3DEnum){
+				InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
+				if(isFS)InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
+			}
+		}
+		if(ismasstransport || isgroundingline){
+			InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
+			InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
+			InputDuplicatex(femmodel,QmuBaseEnum,BaseEnum);
+			InputDuplicatex(femmodel,QmuMaskIceLevelsetEnum,MaskIceLevelsetEnum);
+		}
+		if(isgroundingline) InputDuplicatex(femmodel,QmuMaskGroundediceLevelsetEnum,MaskGroundediceLevelsetEnum);
+		if(isthermal && domaintype==Domain3DEnum){
+			//Update Vertex Position after updating Thickness and Bed
+			femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
+			femmodel->UpdateVertexPositionsx();
+			InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
+			InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
+			InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
+			InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
+			InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsGroundediceMeltingRateEnum);
+			InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
+			//Reset Thermal Constraints
+			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+			ResetConstraintsx(femmodel);
+		}
+	}
+
+	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
+		/*Increment*/
+		if(time_adapt){
+			femmodel->TimeAdaptx(&dt);
+			if(time+dt>finaltime) dt=finaltime-time;
+			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+		}
+		step+=1;
+		time+=dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+		femmodel->parameters->SetParam(step,StepEnum);
+
+		if(VerboseSolution()) _printf0_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << time/yts << " (time step: " << dt/yts << ")\n");
+		if(step%output_frequency==0 || (time >= finaltime - (yts*DBL_EPSILON)) || step==1)
+		 save_results=true;
+		else
+		 save_results=false;
+		femmodel->parameters->SetParam(save_results,SaveResultsEnum);
+
+		if(isthermal && domaintype==Domain3DEnum){
+			if(VerboseSolution()) _printf0_("   computing thermal regime\n");
+			thermal_core(femmodel);
+		}
+
+		if(ishydrology){
+			if(VerboseSolution()) _printf0_("   computing water heads\n");
+			hydrology_core(femmodel);
+		}
+
+		if(isstressbalance){
+			if(VerboseSolution()) _printf0_("   computing new velocity\n");
+			stressbalance_core(femmodel);
+		}
+
+		if(isdamageevolution){
+			if(VerboseSolution()) _printf0_("   computing damage\n");
+			damage_core(femmodel);
+		}
+
+		if(islevelset){
+			if(VerboseSolution()) _printf0_("   computing movement of ice boundaries\n");
+			/* smoothen slope of lsf for computation of normal on ice domain*/
+			levelsetfunctionslope_core(femmodel);
+
+			/* extrapolate velocities onto domain with no ice */
+			Analysis* extanalysis = new ExtrapolationAnalysis();
+			const int nvars=2;
+			int vars[nvars] = {VxEnum, VyEnum};
+			for(int iv=0;iv<nvars;iv++){
+				femmodel->parameters->SetParam(vars[iv],ExtrapolationVariableEnum); 
+				extanalysis->Core(femmodel);
+			}
+			delete extanalysis;	
+
+			/* solve level set equation */
+			analysis = new LevelsetAnalysis();
+			analysis->Core(femmodel);
+			delete analysis;
+
+			/* update vertices included for next calculation */
+			GetMaskOfIceVerticesLSMx(femmodel);
+
+			/* add computation domain mask to outputs */
+			int outputs[1] = {IceMaskNodeActivationEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
+		}
+
+		if(ismasstransport){
+			if(VerboseSolution()) _printf0_("   computing new thickness\n");
+			masstransport_core(femmodel);
+			if(VerboseSolution()) _printf0_("   updating vertices positions\n");
+			femmodel->UpdateVertexPositionsx();
+		}
+		
+		if(isgroundingline){
+			if(VerboseSolution()) _printf0_("   computing new grounding line position\n");
+			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+			if(groundingline_migration==ContactEnum){
+				femmodel->parameters->SetParam(MaskGroundediceLevelsetEnum,InputToExtrudeEnum);
+				extrudefrombase_core(femmodel);
+				femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
+				extrudefrombase_core(femmodel);
+			}
+			if(save_results){
+				int outputs[3] = {SurfaceEnum,BaseEnum,MaskGroundediceLevelsetEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+			}
+		}
+
+		/*Calculate new Basal melting on Floating ice*/
+		FloatingiceMeltingRatex(femmodel);
+		
+		if(isgia){
+			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
+			#ifdef _HAVE_GIA_
+			gia_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with gia capabilities. Exiting");
+			#endif
+		}
+
+		/*unload results*/
+		if(VerboseSolution()) _printf0_("   computing requested outputs\n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs,save_results);
+		if(isgroundingline && (groundingline_migration==SubelementMigrationEnum || groundingline_migration==SubelementMigration2Enum)){
+			int outputs[1] = {MaskGroundediceLevelsetEnum};
+			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1,save_results);
+		}
+
+		if(save_results){
+			if(VerboseSolution()) _printf0_("   saving temporary results\n");
+			OutputResultsx(femmodel);
+		}
+	}
+
+	femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/	
+	if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.cpp	(revision 18231)
@@ -0,0 +1,233 @@
+/*
+ * \file DataSet.cpp
+ * \brief: Implementation of DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Constructors/Destructors*/
+DataSet::DataSet(){/*{{{*/
+
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+DataSet::DataSet(int dataset_enum){/*{{{*/
+	enum_type=dataset_enum;
+
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+DataSet*   DataSet::Copy(void){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Object* object_copy=NULL;
+
+	DataSet* copy=new DataSet(enum_type);
+
+	copy->sorted=sorted;
+	copy->presorted=presorted;
+	if(sorted_ids){
+		copy->sorted_ids=xNew<int>(objects.size());
+		xMemCpy<int>(copy->sorted_ids,sorted_ids,objects.size());
+	}
+	if(id_offsets){
+		copy->id_offsets=xNew<int>(objects.size());
+		xMemCpy<int>(copy->id_offsets,id_offsets,objects.size());
+	}
+
+	/*Now we need to deep copy the objects: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		object_copy = (*object)->copy();
+		copy->AddObject(object_copy);
+	}
+	return copy;
+}
+/*}}}*/
+DataSet::~DataSet(){/*{{{*/
+	clear();
+	xDelete<int>(sorted_ids);
+	xDelete<int>(id_offsets);
+}
+/*}}}*/
+
+/*Specific methods*/
+int  DataSet::AddObject(Object* object){/*{{{*/
+
+	_assert_(this);
+	objects.push_back(object);
+
+	return 1;
+}
+/*}}}*/
+void  DataSet::clear(){/*{{{*/
+
+/*  use reverse_iterator for efficiency in matlab memory manager
+	(keeping old code in case it needs to revert back)  */
+
+//	vector<Object*>::iterator object;
+	vector<Object*>::reverse_iterator object;
+
+//	for ( object=objects.begin() ; object < objects.end(); object++ ){
+//		delete (*object);
+//	}
+	for ( object=objects.rbegin() ; object < objects.rend(); object++ ){
+		delete (*object);
+	}
+	objects.clear();
+}
+/*}}}*/
+int  DataSet::DeleteObject(Object* object){/*{{{*/
+
+	vector<Object*>::iterator iterator;
+
+	if(object){
+		iterator = find(objects.begin(), objects.end(),object);
+		delete *iterator;
+		objects.erase(iterator);
+	}
+
+	return 1;
+
+}
+/*}}}*/
+void DataSet::DeepEcho(){/*{{{*/
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_("trying to echo a NULL dataset");
+
+	_printf0_("DataSet echo: " << objects.size() << " objects\n");
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call deep echo on object: */
+		(*object)->DeepEcho();
+
+	}
+}
+/*}}}*/
+void DataSet::Echo(){/*{{{*/
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_("trying to echo a NULL dataset");
+
+	_printf0_("DataSet echo: " << objects.size() << " objects\n");
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		(*object)->Echo();
+
+	}
+	return;
+}
+/*}}}*/
+int  DataSet::GetEnum(){/*{{{*/
+	return enum_type;
+}
+/*}}}*/
+int   DataSet::GetEnum(int offset){/*{{{*/
+
+	return objects[offset]->ObjectEnum();
+
+}
+/*}}}*/
+Object* DataSet::GetObjectByOffset(int offset){/*{{{*/
+
+	/*Check index in debugging mode*/
+	_assert_(this!=NULL);
+	_assert_(offset>=0);
+	_assert_(offset<this->Size());
+
+	return objects[offset];
+
+}
+/*}}}*/
+Object* DataSet::GetObjectById(int* poffset,int eid){/*{{{*/
+
+	int id_offset;
+	int offset;
+
+	_assert_(this);
+	if(!sorted)_error_("trying to binary search on a non-sorted dataset!");
+
+	/*Carry out a binary search on the sorted_ids: */
+	if(!binary_search(&id_offset,eid,sorted_ids,objects.size())){
+		_error_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
+	}
+
+	/*Convert  the id offset into sorted offset: */
+	offset=id_offsets[id_offset];
+
+	/*Assign output pointers if requested:*/
+	if(poffset)*poffset=offset;
+
+	/*Return object at offset position in objects :*/
+	return objects[offset];
+}
+/*}}}*/
+void DataSet::Presort(){/*{{{*/
+
+	/*vector of objects is already sorted, just allocate the sorted ids and their
+	 * offsets:*/
+	if(objects.size()){
+
+		/*Delete existing ids*/
+		xDelete<int>(sorted_ids);
+		xDelete<int>(id_offsets);
+
+		/*Allocate new ids*/
+		sorted_ids=xNew<int>(objects.size());
+		id_offsets=xNew<int>(objects.size());
+
+		/*Build id_offsets and sorted_ids*/
+		for(int i=0;i<objects.size();i++){
+			id_offsets[i]=i;
+			sorted_ids[i]=objects[i]->Id();
+		}
+	}
+
+	/*set sorted flag: */
+	sorted=1;
+}
+/*}}}*/
+int  DataSet::Size(void){/*{{{*/
+	_assert_(this!=NULL);
+
+	return objects.size();
+}
+/*}}}*/
+void DataSet::Sort(){/*{{{*/
+
+	/*Only sort if we are not already sorted: */
+	if(!sorted){
+		_error_("not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/DataSet.h	(revision 18231)
@@ -0,0 +1,53 @@
+#ifndef _CONTAINER_DATASET_H_
+#define _CONTAINER_DATASET_H_
+
+#include <vector>
+#include <cstring>
+
+/*forward declarations */
+class Object;
+
+/*! \brief Declaration of DataSet class
+ *
+ * Declaration of DataSet class.  A DataSet is a Container of Objects.
+ */
+class DataSet{
+
+	public: 
+
+		/*internals: */
+		std::vector<Object*> objects;
+
+		/*type of dataset: */
+		int             enum_type;
+
+		/*sorting: */
+		int             sorted;
+		int             presorted;
+		int*            sorted_ids;
+		int*            id_offsets;
+
+		/*constructors, destructors*/
+		DataSet();
+		DataSet(int enum_type);
+		~DataSet();
+
+		/*management*/
+		int      GetEnum();
+		int      GetEnum(int offset);
+		void     Echo();
+		void     DeepEcho();
+		int      AddObject(Object *object);
+		int      DeleteObject(int id);
+		int      Size();
+		void     clear();
+		Object  *GetObjectByOffset(int  offset);
+		Object  *GetObjectById(int *poffset,int eid);
+		void     Presort();
+		void     Sort();
+		DataSet *Copy(void);
+		int      DeleteObject(Object *object);
+
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/Object.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/Object.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/Object.h	(revision 18231)
@@ -0,0 +1,25 @@
+/*
+ * Object.h:
+ * \brief prototype for abstract Object class
+ * \file Object.h
+ * This prototype describes the Object class. This is an abstract class, parent 
+ * to any other objects (Quad, Tria, Node , etc ...), that can be included in a 
+ * DataSet.
+ */
+
+#ifndef _OBJECT_H_
+#define _OBJECT_H_
+
+class Object {
+
+	public: 
+
+		virtual       ~Object(){};
+		virtual void  Echo()=0;
+		virtual void  DeepEcho()=0;
+		virtual int   Id()=0;
+		virtual int   ObjectEnum()=0;
+		virtual Object* copy()=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/datastructures.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/datastructures.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/datastructures/datastructures.h	(revision 18231)
@@ -0,0 +1,11 @@
+/* \file datastructures.h
+ * \brief: header file for all datastructures  routines.
+ */
+
+#ifndef _DATA_STRUCTURES_H_
+#define _DATA_STRUCTURES_H_
+
+#include "./DataSet.h"
+#include "./Object.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.cpp	(revision 18231)
@@ -0,0 +1,711 @@
+/*!\file KMLFileUtils.cpp
+ * \brief: utilities for kml file reading.
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+char* KMLFileToken(FILE* fid,/*{{{*/
+				   int* pncom=NULL,char*** ppcom=NULL){
+
+/*  get the next token (tag or field) in the file  */
+
+	bool    inew=1,itag=0,ifield=0;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char    *buffer=NULL,*bufferc=NULL,**pcom2=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+//  note that fgets includes newline
+//	fgets(buffer,buflen,fid);
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		/*  distinguish between tag or field  */
+		if (!itag && !ifield) {
+
+			/*  distinguish between tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid))) {
+					c=getc(fid);
+					itag=1;
+				}
+				else {
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+					inew=1;
+					continue;
+				}
+			}
+			else
+				ifield=1;
+			inew=0;
+			KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+							   c,
+							   bufblk);
+		}
+
+		/*  accumulate tag, not including newlines  */
+		else if (itag) {
+			if (c != '\n') {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '>')
+					break;
+			}
+			else
+				inew=1;
+		}
+
+		/*  accumulate field, including newlines  */
+		else if (ifield) {
+			/*  distinguish between another tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid)))
+					break;
+				else
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+			}
+			else {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '\n')
+					inew=1;
+			}
+		}
+
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	if      (itag)
+//		_printf0_("tag buffer (length=" << ibuf << "):\n");
+//	else if (ifield)
+//		_printf0_("field buffer (length=" << ibuf << "):\n");
+//	_printf0_(buffer << "\n");
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+char* KMLFileTokenComment(FILE* fid){/*{{{*/
+
+/*  check for comment in the file and read it  */
+
+	bool    inew=1;
+	int     i;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char*   buffer=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		inew=0;
+		KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+						   c,
+						   bufblk);
+
+		/*  check for comment  */
+		if (ibuf <= 4) {
+			if ((ibuf == 1 && buffer[0] != '<') ||
+				(ibuf == 2 && buffer[1] != '!') ||
+				(ibuf == 3 && buffer[2] != '-') ||
+				(ibuf == 4 && buffer[3] != '-')) {
+				for (i=ibuf-1; i>=0; i--)
+					ungetc(buffer[i],fid);
+				xDelete<char>(buffer);
+				return(buffer);
+			}
+		}
+
+		/*  accumulate comment, including newlines  */
+		else
+			if (buffer[ibuf-3]=='-' && buffer[ibuf-2]=='-' && buffer[ibuf-1]=='>')
+				break;
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	_printf0_("comment buffer (length=" << ibuf << "):\n");
+//	_printf0_(buffer << "\n");
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,/*{{{*/
+						int c,
+						int bufblk){
+
+/*  add the specified character to the token buffer  */
+
+	char*   buffer2=NULL;
+
+/*  check buffer length and realloc if necessary  */
+
+	if (*pibuf+2 > *pbuflen) {
+		*pbuflen+=bufblk;
+		buffer2=xNew<char>(*pbuflen);
+		memcpy(buffer2,*pbuffer,(*pbuflen-bufblk)*sizeof(char));
+		xDelete<char>(*pbuffer);
+		*pbuffer=buffer2;
+		buffer2=NULL;
+//		*pbuffer=(char *) xrealloc(*pbuffer,*pbuflen*sizeof(char));
+	}
+
+/*  add character and terminator  */
+
+	(*pbuffer)[(*pibuf)++]=c;
+	(*pbuffer)[ *pibuf   ]='\0';
+
+	return;
+}
+/*}}}*/
+char* KMLFileTagName(char* pname,/*{{{*/
+					 char* ktag){
+
+	return(KMLFileTagName(pname,NULL,0,
+						  ktag));
+}
+/*}}}*/
+char* KMLFileTagName(char* pname,int *m,int maxlen,/*{{{*/
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the name  */
+
+	char*   ktagi;
+	char*   ktokn;
+
+	if (strncmp(&ktag[0],"<"        ,1) || strncmp(&ktag[strlen(ktag)-1],">",1))
+		_error_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  skip opening delimeter and find subsequent blank or closing delimiter  */
+
+	ktokn=strtok(ktagi,"< >");
+//	_printf0_("KMLFileTagName -- initial token=\"" << ktokn << "\".\n");
+
+	if (!pname) {
+		if (maxlen)
+			pname=xNew<char>(maxlen       +1);
+		else
+			pname=xNew<char>(strlen(ktokn)+1);
+	}
+
+	if (maxlen && (maxlen < strlen(ktokn))) {
+		_printf0_("KMLFileTagName -- string field too short for " << ktag << ".\n");
+		_printf0_("KMLFileTagName -- \"" << ktokn << "\" truncated to " << maxlen << " characters.\n");
+		strncpy(pname,ktokn,maxlen);
+	}
+	else
+		memcpy(pname,ktokn,(strlen(ktokn)+1)*sizeof(char));
+
+	xDelete<char>(ktagi);
+
+	if (m)
+		*m=strlen(pname);
+
+	return(pname);
+}
+/*}}}*/
+int KMLFileTagAttrib(KML_Object* kobj,/*{{{*/
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the attributes  */
+
+	char*   ktagi;
+	char*   ktokn;
+	char*   ktokv;
+	char    quote[]={'\"','\0'};
+	int     isolo=0;
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  loop through tag to find all attributes  */
+
+	/*  return first non blank and move past subsequent blank  */
+	ktokn=strtok(ktagi," ");
+//	_printf0_("KMLFileTagAttrib -- initial token=\"" << ktokn << "\".\n");
+
+	/*  return next non " =?/>" and move past subsequent " =?/>"  */
+	while((ktokn=strtok(NULL," =?/>"))){
+
+		/*  return next non quote and move past subsequent quote  */
+		ktokv=strtok(NULL,quote);
+//		_printf0_("KMLFileTagAttrib -- attribute " << ktokn << "=\"" << ktokv << "\".\n");
+
+/*  add the attribute to the dataset  */
+
+		if (kobj)
+			kobj->AddAttrib(ktokn,ktokv);
+	}
+
+	xDelete<char>(ktagi);
+
+/*  check for xml declaration, dtd declaration, or solo tag  */
+
+	if ((!strncmp(&ktag[0],"<?"       ,2) && !strncmp(&ktag[strlen(ktag)-2],"?>",2)) ||
+		(!strncmp(&ktag[0],"<!DOCTYPE",9) && !strncmp(&ktag[strlen(ktag)-1], ">",1)) ||
+		(!strncmp(&ktag[0],"<"        ,1) && !strncmp(&ktag[strlen(ktag)-2],"/>",2)))
+		isolo=1;
+//	_printf0_("KMLFileTagAttrib -- isolo=" << isolo << ".\n");
+
+	return(isolo);
+}
+/*}}}*/
+int KMLFileTokenParse(int* pival,/*{{{*/
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%d",pival);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else{
+			xDelete<char>(kstr);
+		}
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pival << ".\n");
+
+	return(0);
+}
+/*}}}*/
+int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid){/*{{{*/
+
+	int     ival;
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%d",&ival);
+	*pbval=(bool)ival;
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << (*pbval ? "true" : "false") << ".\n");
+
+	return(0);
+}
+/*}}}*/
+char* KMLFileTokenParse(char* pstr,/*{{{*/
+						char* ktag,
+						FILE* fid){
+
+	return(KMLFileTokenParse(pstr,NULL,0,
+							 ktag,
+							 fid));
+}
+/*}}}*/
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen,/*{{{*/
+						char* ktag,
+						FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
+
+	if (!pstr) {
+		if (maxlen)
+			pstr=xNew<char>(maxlen      +1);
+		else
+			pstr=xNew<char>(strlen(kstr)+1);
+	}
+
+	if (maxlen && (maxlen < strlen(kstr))) {
+		_printf0_("KMLFileTokenParse -- string field too short for " << ktag << ".\n");
+		_printf0_("KMLFileTokenParse -- \"" << kstr << "\" truncated to " << maxlen << " characters.\n");
+		strncpy(pstr,kstr,maxlen);
+	}
+	else
+		memcpy(pstr,kstr,(strlen(kstr)+1)*sizeof(char));
+
+	xDelete<char>(kstr);
+
+	if (m)
+		*m=strlen(pstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=\"" << pstr << "\".\n");
+
+	return(pstr);
+}
+/*}}}*/
+int KMLFileTokenParse(float* pfval,/*{{{*/
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%g",pfval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pfval << ".\n");
+
+	return(0);
+}
+/*}}}*/
+int KMLFileTokenParse(double* pdval,/*{{{*/
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%lg",pdval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pdval << ".\n");
+
+	return(0);
+}
+/*}}}*/
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,/*{{{*/
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1;
+	char*   kstr;
+	char*   ktok;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
+
+	if(!*pdval){
+		if (maxlen)
+			*pdval=xNew<IssmPDouble>(maxlen            );
+		else
+			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
+	}
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen < i+1))
+			_error_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>(i+1);
+		memcpy(dval2,*pdval,(i+1)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,(i+1)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
+//	for (j=0; j<=i; j++)
+//		_printf0_("   [" << j << "]: " << (*pdval)[j] << "g\n");
+
+	return(0);
+}
+/*}}}*/
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen,/*{{{*/
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1,j=-1;
+	char*   kstr;
+	char*   ktok;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
+
+	if(!*pdval){
+		if (maxlen)
+			*pdval=xNew<IssmPDouble>(maxlen*n          );
+		else
+			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
+	}
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen*n < i+1))
+			_error_("KMLFileTokenParse -- Double [m x n] field too short for " << ktag << ".\n");
+		j=(j+1) % n;
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>((i+1)*n);
+		memcpy(dval2,*pdval,((i+1)*n)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,((i+1)*n)*sizeof(double));
+
+	if (m)
+		*m=((i+1)+(n-1))/n;
+
+	if ((i+1) % n)
+		_printf0_("KMLFileTokenParse -- Double [m x n] field for " << ktag << " does not have multiple of n values.\n");
+
+/*  get additional token and compare to closing tag  */
+
+	if(ktag){
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+	}
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
+//	for (j=0; j<=i; j++)
+//		_printf0_("   [" << j << "]: " << (*pdval)[j] << "g\n");
+
+	return(0);
+}
+/*}}}*/
+int KMLFileTagSkip(char* ktag, FILE* fid){/*{{{*/
+
+	char*   kstr;
+
+/*  note that tags of the same type can be nested inside each other, so for each
+	opening tag, must find corresponding closing tag  */
+
+	_printf0_("KMLFileTagSkip -- input tag " << ktag << ".\n");
+
+/*  if next token is a closing tag, compare to input  */
+
+	while((kstr=KMLFileToken(fid,NULL,NULL))){
+		if((kstr[0] == '<') && (kstr[1] == '/') && (!strncmp(&(kstr[2]),&(ktag[1]),(strcspn(ktag," >")-1)/sizeof(char)))){
+			_printf0_("KMLFileTagSkip -- closing tag " << kstr << ".\n");
+			xDelete<char>(kstr);
+			return(0);
+		}
+
+/*  if next token is an opening tag, call recursively  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] != '/')) {
+			_printf0_("KMLFileTagSkip -- opening tag " << kstr << ".\n");
+			KMLFileTagSkip(kstr,
+						   fid);
+		}
+
+/*  if next token is a closing tag, error out  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] == '/')) {
+			_error_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
+		}
+
+		xDelete<char>(kstr);
+	}
+
+	_error_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
+
+	return(0);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KMLFileReadUtils.h	(revision 18231)
@@ -0,0 +1,31 @@
+/*!\file:  KMLFileReadUtils.h
+ * \brief: header file for kml file reading utilities.
+ */ 
+
+#ifndef _KMLFILEREADUTILS_H
+#define _KMLFILEREADUTILS_H
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+class KML_Object;
+/*}}}*/
+
+/* local prototypes: */
+char* KMLFileToken(FILE* fid, int* pncom,char*** ppcom);
+char* KMLFileTokenComment(FILE* fid);
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen, int c, int bufblk);
+char* KMLFileTagName(char* pname, char* ktag);
+char* KMLFileTagName(char* pname,int *m,int maxlen, char* ktag);
+int KMLFileTagAttrib(KML_Object* kobj, char* ktag);
+int KMLFileTokenParse(int* pival, char* ktag, FILE* fid);
+int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid);
+char* KMLFileTokenParse(char* pstr, char* ktag, FILE* fid);
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen, char* ktag, FILE* fid);
+int KMLFileTokenParse(float* pfval, char* ktag, FILE* fid);
+int KMLFileTokenParse(double* pdval, char* ktag, FILE* fid);
+int KMLFileTokenParse(double **pdval,int* m,int maxlen, char* ktag, FILE* fid);
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen, char* ktag, FILE* fid);
+int KMLFileTagSkip(char* ktag, FILE* fid);
+
+#endif  /* _KMLFILEREADUTILS_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.cpp	(revision 18231)
@@ -0,0 +1,118 @@
+/*!\file KML_Attribute.cpp
+ * \brief: implementation of the kml_attribute object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Attribute.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Attribute::KML_Attribute(){/*{{{*/
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+KML_Attribute::~KML_Attribute(){/*{{{*/
+
+	if (name      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Attribute::Echo(){/*{{{*/
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_("    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _printf0_(" ");
+	if(flag) _printf0_(name << ": \"" << value << "\"\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Attribute::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _printf0_(" ");
+	if(flag) _printf0_(name << ": \"" << value << "\"\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::Write(FILE* filout,const char* indent){/*{{{*/
+
+//  attributes always written in keyword line of kml_object
+
+	fprintf(filout,"%s%s=\"%s\"",indent,name,value);
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::Read(FILE* fid,char* kstr){/*{{{*/
+
+//  attributes always read in keyword line of kml_object
+
+	;
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::Alloc(const char* namei,const char* valuei){/*{{{*/
+
+	name =xNew<char>(strlen(namei )+1);
+	memcpy(name,namei,(strlen(namei)+1)*sizeof(char));
+
+	value=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::Add(DataSet* attrib){/*{{{*/
+
+	attrib->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+void  KML_Attribute::Get(char** pvalueo,char* deflt){/*{{{*/
+
+	if (!value || !strlen(value)) {
+		*pvalueo=xNew<char>(strlen(deflt)+1);
+		memcpy(*pvalueo,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+	else {
+		*pvalueo=xNew<char>(strlen(value)+1);
+		memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Attribute.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file KML_Attribute.h 
+ *  \brief: header file for kml_attribute object
+ */
+
+#ifndef _KML_ATTRIBUTE_H_
+#define _KML_ATTRIBUTE_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+class KML_Attribute: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Attribute constructors, destructors {{{*/
+		KML_Attribute();
+		~KML_Attribute();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* namei,const char* valuei);
+		void  Add(DataSet* attrib);
+		void  Get(char** pvalueo,char* deflt);
+
+};
+#endif  /* _KML_ATTRIBUTE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.cpp	(revision 18231)
@@ -0,0 +1,99 @@
+/*!\file KML_ColorStyle.cpp
+ * \brief: implementation of the kml_colorstyle abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_ColorStyle.h"
+#include "./KML_SubStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_ColorStyle::KML_ColorStyle(){/*{{{*/
+
+	strcpy(color     ,"ffffffff");
+	strcpy(colormode ,"normal");
+
+}
+/*}}}*/
+KML_ColorStyle::~KML_ColorStyle(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_ColorStyle::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	KML_SubStyle::Echo();
+
+	if(flag) _printf0_("         color: " << color << "\n");
+	if(flag) _printf0_("     colormode: " << colormode << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_ColorStyle::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_ColorStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_ColorStyle::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	KML_SubStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "         color: " << color << "\n");
+	if(flag) _printf0_(indent << "     colormode: " << colormode << "\n");
+}
+/*}}}*/
+void  KML_ColorStyle::Write(FILE* filout,const char* indent){/*{{{*/
+
+	KML_SubStyle::Write(filout,indent);
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	if (colormode && strlen(colormode))
+		fprintf(filout,"%s  <colorMode>%s</colorMode>\n",indent,colormode);
+
+	return;
+}
+/*}}}*/
+void  KML_ColorStyle::Read(FILE* fid,char* kstr){/*{{{*/
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</ColorStyle",12))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_ColorStyle::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_COLORSTYLE_COLOR_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<colorMode>"))
+		KMLFileTokenParse( colormode ,NULL,KML_COLORSTYLE_COLORMODE_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_SubStyle::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_ColorStyle.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file KML_ColorStyle.h 
+ *  \brief: header file for kml_colorstyle abstract object
+ */
+
+#ifndef _KML_COLORSTYLE_H_
+#define _KML_COLORSTYLE_H_
+
+#define KML_COLORSTYLE_COLOR_LENGTH      8
+#define KML_COLORSTYLE_COLORMODE_LENGTH  6
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_SubStyle.h"
+/*}}}*/
+
+class KML_ColorStyle: public KML_SubStyle {
+
+	public:
+
+		char  color[KML_COLORSTYLE_COLOR_LENGTH+1];
+		char  colormode[KML_COLORSTYLE_COLORMODE_LENGTH+1];
+
+		/*KML_ColorStyle constructors, destructors {{{*/
+		KML_ColorStyle();
+		~KML_ColorStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_COLORSTYLE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.cpp	(revision 18231)
@@ -0,0 +1,103 @@
+/*!\file KML_Comment.cpp
+ * \brief: implementation of the kml_comment object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Comment.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Comment::KML_Comment(){/*{{{*/
+
+	value     =NULL;
+
+}
+/*}}}*/
+KML_Comment::~KML_Comment(){/*{{{*/
+
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Comment::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("    ");
+	if(flag) _printf0_(value << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Comment::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "    ");
+	if(flag) _printf0_(value << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::Write(FILE* filout,const char* indent){/*{{{*/
+
+	if (strncmp(&value[0]              ,"<!--",4))
+		fprintf(filout,"%s<!--\n",indent);
+	fprintf(filout,"%s  %s\n",indent,value);
+	if (strncmp(&value[strlen(value)-3],"-->" ,3))
+		fprintf(filout,"%s-->\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::Read(FILE* fid,char* kstr){/*{{{*/
+
+//  comments always read as part of KMLFileToken
+
+	;
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::Alloc(const char* valuei){/*{{{*/
+
+	value=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::Add(DataSet* commnt){/*{{{*/
+
+	commnt->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+void  KML_Comment::Get(char** pvalueo){/*{{{*/
+
+	*pvalueo=xNew<char>(strlen(value)+1);
+	memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Comment.h	(revision 18231)
@@ -0,0 +1,42 @@
+/*! \file KML_Comment.h 
+ *  \brief: header file for kml_comment object
+ */
+
+#ifndef _KML_COMMENT_H_
+#define _KML_COMMENT_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+class DataSet;
+/*}}}*/
+
+class KML_Comment: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Comment constructors, destructors {{{*/
+		KML_Comment();
+		~KML_Comment();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* valuei);
+		void  Add(DataSet* commnt);
+		void  Get(char** pvalueo);
+
+};
+#endif  /* _KML_COMMENT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.cpp	(revision 18231)
@@ -0,0 +1,160 @@
+/*!\file KML_Container.cpp
+ * \brief: implementation of the kml_container abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Placemark.h"
+#include "./KML_Document.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Folder.h"
+#include "./KML_Object.h"
+#include "./KML_Container.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Container::KML_Container(){/*{{{*/
+
+	feature   =new DataSet;
+
+}
+/*}}}*/
+KML_Container::~KML_Container(){/*{{{*/
+
+	if (feature) {
+		delete feature;
+		feature   =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Container::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	KML_Feature::Echo();
+
+	if(flag) _printf0_("       feature: (size=" << feature->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Container::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Container::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Feature::DeepEcho(indent);
+
+/*  loop over the features for the container  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (feature->Size())
+		for (i=0; i<feature->Size(); i++) {
+			if(flag) _printf0_(indent << "       feature: -------- begin [" << i << "] --------\n");
+			((KML_Feature *)feature->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "       feature: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "       feature: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Container::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the features for the container  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Feature *)feature->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+void  KML_Container::Read(FILE* fid,char* kstr){/*{{{*/
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Container",11)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Container::Read -- Unexpected closing tag " << kstr );}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Container::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int   i;
+
+/*  loop over the features for the container  */
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Object *)feature->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Container.h	(revision 18231)
@@ -0,0 +1,38 @@
+/*! \file KML_Container.h 
+ *  \brief: header file for kml_container abstract object
+ */
+
+#ifndef _KML_CONTAINER_H_
+#define _KML_CONTAINER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_Container: public KML_Feature {
+
+	public:
+
+		DataSet* feature;
+
+		/*KML_Container constructors, destructors {{{*/
+		KML_Container();
+		~KML_Container();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_CONTAINER_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.cpp	(revision 18231)
@@ -0,0 +1,114 @@
+/*!\file KML_Document.cpp
+ * \brief: implementation of the kml_document object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Document.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Document::KML_Document(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_Document::~KML_Document(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Document::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Document:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_Document::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Document::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Document::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Document:\n");
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Document::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<Document",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Document>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Document::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))) {
+		if      (!strncmp(kstri,"</Document",10)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Document.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file KML_Document.h 
+ *  \brief: header file for kml_document object
+ */
+
+#ifndef _KML_DOCUMENT_H_
+#define _KML_DOCUMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Document: public KML_Container {
+
+	public:
+
+		/*KML_Document constructors, destructors {{{*/
+		KML_Document();
+		~KML_Document();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_DOCUMENT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.cpp	(revision 18231)
@@ -0,0 +1,178 @@
+/*!\file KML_Feature.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../shared/shared.h"
+/*}}}*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Feature.h"
+#include "./KML_Style.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Feature::KML_Feature(){/*{{{*/
+
+	memcpy(name,"",(strlen("")+1)*sizeof(char));
+
+	visibility=true;
+	open      =false;
+	memcpy(snippet,"",(strlen("")+1)*sizeof(char));
+	memcpy(descript,"",(strlen("")+1)*sizeof(char));
+	memcpy(styleurl,"",(strlen("")+1)*sizeof(char));
+	style     =new DataSet;
+
+}
+/*}}}*/
+KML_Feature::~KML_Feature(){/*{{{*/
+
+	if (style) {
+		delete style;
+		style     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Feature::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	KML_Object::Echo();
+
+	if(flag) _printf0_("          name: \"" << name << "\"\n");
+	if(flag) _printf0_("    visibility: " << (visibility ? "true" : "false") << "\n");
+	if(flag) _printf0_("          open: " << (open ? "true" : "false") << "\n");
+	if(flag) _printf0_("       snippet: \"" << snippet << "\"\n");
+	if(flag) _printf0_("      descript: \"" << descript << "\"\n");
+	if(flag) _printf0_("      styleurl: \"" << styleurl << "\"\n");
+	if(flag) _printf0_("         style: (size=" << style->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Feature::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Feature::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Feature::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Object::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          name: \"" << name << "\"\n");
+	if(flag) _printf0_(indent << "    visibility: " << (visibility ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "          open: " << (open ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       snippet: \"" << snippet << "\"\n");
+	if(flag) _printf0_(indent << "      descript: \"" << descript << "\"\n");
+	if(flag) _printf0_(indent << "      styleurl: \"" << styleurl << "\"\n");
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (style->Size())
+		for (i=0; i<style->Size(); i++) {
+			if(flag) _printf0_(indent << "         style: -------- begin [" << i << "] --------\n");
+			((KML_Style *)style->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         style: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         style: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Feature::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+
+	KML_Object::Write(filout,indent);
+
+	if (name     && strlen(name))
+		fprintf(filout,"%s  <name>%s</name>\n",indent,name);
+	fprintf(filout,"%s  <visibility>%d</visibility>\n",indent,(visibility ? 1 : 0));
+	fprintf(filout,"%s  <open>%d</open>\n",indent,(open ? 1 : 0));
+	if (snippet  && strlen(snippet))
+		fprintf(filout,"%s  <Snippet maxLines=\"2\">%s</Snippet>\n",indent,snippet);
+	if (descript && strlen(descript))
+		fprintf(filout,"%s  <description>%s</description>\n",indent,descript);
+	if (styleurl && strlen(styleurl))
+		fprintf(filout,"%s  <styleUrl>%s</styleUrl>\n",indent,styleurl);
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+    for (i=0; i<style->Size(); i++)
+        ((KML_Style *)style->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+void  KML_Feature::Read(FILE* fid,char* kstr){/*{{{*/
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Feature", 9))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Feature::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Style", 6)) {
+		kobj=(KML_Object*)new KML_Style();
+		kobj->Read(fid,kstr);
+		style     ->AddObject((Object*)kobj);
+	}
+
+	else if (!strcmp(kstr,"<name>"))
+		KMLFileTokenParse( name      ,NULL,KML_FEATURE_NAME_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<visibility>"))
+		KMLFileTokenParse(&visibility, kstr, fid);
+	else if (!strcmp(kstr,"<open>"))
+		KMLFileTokenParse(&open      , kstr, fid);
+	else if (!strncmp(kstr,"<snippet", 8))
+		KMLFileTokenParse( snippet   ,NULL,KML_FEATURE_SNIPPET_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<description>"))
+		KMLFileTokenParse( descript  ,NULL,KML_FEATURE_DESCRIPT_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<styleUrl>"))
+		KMLFileTokenParse( styleurl  ,NULL,KML_FEATURE_STYLEURL_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Feature.h	(revision 18231)
@@ -0,0 +1,49 @@
+/*! \file KML_Feature.h 
+ *  \brief: header file for kml_feature abstract object
+ */
+
+#ifndef _KML_FEATURE_H_
+#define _KML_FEATURE_H_
+
+#define KML_FEATURE_NAME_LENGTH         80
+#define KML_FEATURE_SNIPPET_LENGTH     160
+#define KML_FEATURE_DESCRIPT_LENGTH   3200
+#define KML_FEATURE_STYLEURL_LENGTH     80
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+class KML_Style;
+class DataSet;
+/*}}}*/
+
+class KML_Feature: public KML_Object {
+
+	public:
+
+		char  name[KML_FEATURE_NAME_LENGTH+1];
+		bool  visibility;
+		bool  open;
+		char  snippet[KML_FEATURE_SNIPPET_LENGTH+1];
+		char  descript[KML_FEATURE_DESCRIPT_LENGTH+1];
+		char  styleurl[KML_FEATURE_STYLEURL_LENGTH+1];
+		DataSet* style;
+
+		/*KML_Feature constructors, destructors {{{*/
+		KML_Feature();
+		~KML_Feature();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FEATURE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.cpp	(revision 18231)
@@ -0,0 +1,126 @@
+/*!\file KML_File.cpp
+ * \brief: implementation of the kml_file object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_File.h" 
+#include "./KML_Object.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_File::KML_File(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_File::~KML_File(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_File::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_File:\n");
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_File::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_File::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_File::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_File:\n");
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_File::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<kml",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s</kml>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_File::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</kml", 5)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(; ncom>0; ncom--) xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int   i;
+
+/*  loop over the kml objects for the file  */
+
+	for (i=0; i<kmlobj->Size(); i++)
+		((KML_Object *)kmlobj->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_File.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file KML_File.h 
+ *  \brief: header file for kml_file object
+ */
+
+#ifndef _KML_FILE_H_
+#define _KML_FILE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_File: public KML_Object {
+
+	public:
+
+		/*KML_File constructors, destructors {{{*/
+		KML_File();
+		~KML_File();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FILE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.cpp	(revision 18231)
@@ -0,0 +1,113 @@
+/*!\file KML_Folder.cpp
+ * \brief: implementation of the kml_folder object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Folder.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Folder::KML_Folder(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_Folder::~KML_Folder(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Folder::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Folder:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_Folder::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Folder::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Folder::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Folder:\n");
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Folder::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<Folder",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Folder>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Folder::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Folder", 8)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom=ncom; ncom>0; ncom--) xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Folder.h	(revision 18231)
@@ -0,0 +1,35 @@
+/*! \file KML_Folder.h 
+ *  \brief: header file for kml_folder object
+ */
+
+#ifndef _KML_FOLDER_H_
+#define _KML_FOLDER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Folder: public KML_Container {
+
+	public:
+
+		/*KML_Folder constructors, destructors {{{*/
+		KML_Folder();
+		~KML_Folder();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FOLDER_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file KML_Geometry.cpp
+ * \brief: implementation of the kml_geometry abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Geometry.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Geometry::KML_Geometry(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_Geometry::~KML_Geometry(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Geometry::Echo(){/*{{{*/
+
+	this->KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_Geometry::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Geometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Geometry::DeepEcho(const char* indent){/*{{{*/
+
+	this->KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Geometry::Write(FILE* filout,const char* indent){/*{{{*/
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Geometry::Read(FILE* fid,char* kstr){/*{{{*/
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Geometry",10))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Geometry.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file KML_Geometry.h 
+ *  \brief: header file for kml_geometry abstract object
+ */
+
+#ifndef _KML_GEOMETRY_H_
+#define _KML_GEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Geometry: public KML_Object {
+
+	public:
+
+		/*KML_Geometry constructors, destructors {{{*/
+		KML_Geometry();
+		~KML_Geometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GEOMETRY_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.cpp	(revision 18231)
@@ -0,0 +1,154 @@
+/*!\file KML_GroundOverlay.cpp
+ * \brief: implementation of the kml_groundoverlay object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_GroundOverlay.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_GroundOverlay::KML_GroundOverlay(){/*{{{*/
+
+	altitude  = 0.;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	llbox     =NULL;
+
+}
+/*}}}*/
+KML_GroundOverlay::~KML_GroundOverlay(){/*{{{*/
+
+	if (llbox) {
+		delete llbox;
+		llbox     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_GroundOverlay::Echo(){/*{{{*/
+
+	_printf_("KML_GroundOverlay:\n");
+	KML_Overlay::Echo();
+
+	_printf_("         altitude: " << altitude << "\n");
+	_printf_("          altmode: " << altmode << "\n");
+	_printf_("            llbox: " << llbox << "\n");
+}
+/*}}}*/
+void  KML_GroundOverlay::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_GroundOverlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_GroundOverlay::DeepEcho(const char* indent){/*{{{*/
+
+	char  indent2[81];
+
+	_printf_(indent << "KML_GroundOverlay:\n");
+	KML_Overlay::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	_printf_(indent<<"      altitude: " << altitude << "\n");
+	_printf_(indent<<"       altmode: " << altmode << "\n");
+	if (llbox)
+	 llbox->DeepEcho(indent2);
+	else
+	 _printf_(indent<<"         llbox: " << llbox << "\n");
+}
+/*}}}*/
+void  KML_GroundOverlay::Write(FILE* filout,const char* indent){/*{{{*/
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<GroundOverlay",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Overlay::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	fprintf(filout,"%s  <altitude>%0.16g</altitude>\n",indent,altitude);
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	if (llbox)
+		llbox->Write(filout,indent2);
+
+	fprintf(filout,"%s</GroundOverlay>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_GroundOverlay::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</GroundOverlay",15)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<altitude>"))
+			KMLFileTokenParse(&altitude  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_GROUNDOVERLAY_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strncmp(kstri,"<LatLonBox",10)) {
+			llbox     =new KML_LatLonBox();
+			llbox     ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Overlay::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_GroundOverlay.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file KML_GroundOverlay.h 
+ *  \brief: header file for kml_groundoverlay object
+ */
+
+#ifndef _KML_GROUNDOVERLAY_H_
+#define _KML_GROUNDOVERLAY_H_
+
+#define KML_GROUNDOVERLAY_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Overlay.h"
+class KML_LatLonBox;
+/*}}}*/
+
+class KML_GroundOverlay: public KML_Overlay {
+
+	public:
+
+		double altitude;
+		char  altmode[KML_GROUNDOVERLAY_ALTMODE_LENGTH+1];
+		KML_LatLonBox* llbox;
+
+		/*KML_GroundOverlay constructors, destructors {{{*/
+		KML_GroundOverlay();
+		~KML_GroundOverlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GROUNDOVERLAY_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.cpp	(revision 18231)
@@ -0,0 +1,170 @@
+/*!\file KML_Icon.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Icon.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Icon::KML_Icon(){/*{{{*/
+
+	strcpy(href      ,"");
+	strcpy(refmode   ,"onChange");
+	refint    = 4.;
+	strcpy(vrefmode  ,"never");
+	vreftime  = 4.;
+	vboundsc  = 1.;
+	strcpy(vformat   ,"");
+	strcpy(hquery    ,"");
+
+}
+/*}}}*/
+KML_Icon::~KML_Icon(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Icon::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Icon:\n");
+	KML_Object::Echo();
+
+	if(flag) _printf0_("          href: \"" << href << "\"\n");
+	if(flag) _printf0_("       refmode: \"" << refmode << "\"\n");
+	if(flag) _printf0_("        refint: " << refint << "\n");
+	if(flag) _printf0_("      vrefmode: \"" << vrefmode << "\"\n");
+	if(flag) _printf0_("      vreftime: " << vreftime << "\n");
+	if(flag) _printf0_("      vboundsc: " << vboundsc << "\n");
+	if(flag) _printf0_("       vformat: \"" << vformat << "\"\n");
+	if(flag) _printf0_("        hquery: \"" << hquery << "\"\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Icon::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Icon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Icon::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Icon:\n");
+	KML_Object::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          href: \"" << href << "\"\n");
+	if(flag) _printf0_(indent << "       refmode: \"" << refmode << "\"\n");
+	if(flag) _printf0_(indent << "        refint: " << refint << "\n");
+	if(flag) _printf0_(indent << "      vrefmode: \"" << vrefmode << "\"\n");
+	if(flag) _printf0_(indent << "      vreftime: " << vreftime << "\n");
+	if(flag) _printf0_(indent << "      vboundsc: " << vboundsc << "\n");
+	if(flag) _printf0_(indent << "       vformat: \"" << vformat << "\"\n");
+	if(flag) _printf0_(indent << "        hquery: \"" << hquery << "\"\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Icon::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<Icon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	if (href     && strlen(href))
+		fprintf(filout,"%s  <href>%s</href>\n",indent,href);
+	if (refmode  && strlen(refmode))
+		fprintf(filout,"%s  <refreshMode>%s</refreshMode>\n",indent,refmode);
+	fprintf(filout,"%s  <refreshInterval>%g</refreshInterval>\n",indent,refint);
+	if (vrefmode && strlen(vrefmode))
+		fprintf(filout,"%s  <viewRefreshMode>%s</viewRefreshMode>\n",indent,vrefmode);
+	fprintf(filout,"%s  <viewRefreshTime>%g</viewRefreshTime>\n",indent,vreftime);
+	fprintf(filout,"%s  <viewBoundScale>%g</viewBoundScale>\n",indent,vboundsc);
+	if (vformat  && strlen(vformat))
+		fprintf(filout,"%s  <viewFormat>%s</viewFormat>\n",indent,vformat);
+	if (hquery   && strlen(hquery))
+		fprintf(filout,"%s  <httpQuery>%s</httpQuery>\n",indent,hquery);
+
+	fprintf(filout,"%s</Icon>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Icon::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Icon", 6)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Icon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<href>"))
+			KMLFileTokenParse( href      ,NULL,KML_ICON_HREF_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshMode>"))
+			KMLFileTokenParse( refmode   ,NULL,KML_ICON_REFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshInterval>"))
+			KMLFileTokenParse(&refint    , kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshMode>"))
+			KMLFileTokenParse( vrefmode  ,NULL,KML_ICON_VREFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshTime>"))
+			KMLFileTokenParse(&vreftime  , kstri, fid);
+		else if (!strcmp(kstri,"<viewBoundScale>"))
+			KMLFileTokenParse(&vboundsc  , kstri, fid);
+		else if (!strcmp(kstri,"<viewFormat>"))
+			KMLFileTokenParse( vformat   ,NULL,KML_ICON_VFORMAT_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<httpQuery>"))
+			KMLFileTokenParse( hquery    ,NULL,KML_ICON_HQUERY_LENGTH, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Icon.h	(revision 18231)
@@ -0,0 +1,49 @@
+/*! \file KML_Icon.h 
+ *  \brief: header file for kml_icon object
+ */
+
+#ifndef _KML_ICON_H_
+#define _KML_ICON_H_
+
+#define KML_ICON_HREF_LENGTH      800
+#define KML_ICON_REFMODE_LENGTH    10
+#define KML_ICON_VREFMODE_LENGTH    9
+#define KML_ICON_VFORMAT_LENGTH   800
+#define KML_ICON_HQUERY_LENGTH    800
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Icon: public KML_Object {
+
+	public:
+
+		char  href[KML_ICON_HREF_LENGTH+1];
+		char  refmode[KML_ICON_REFMODE_LENGTH+1];
+		float refint;
+		char  vrefmode[KML_ICON_VREFMODE_LENGTH+1];
+		float vreftime;
+		float vboundsc;
+		char  vformat[KML_ICON_VFORMAT_LENGTH+1];
+		char  hquery[KML_ICON_HQUERY_LENGTH+1];
+
+		/*KML_Icon constructors, destructors {{{*/
+		KML_Icon();
+		~KML_Icon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_ICON_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.cpp	(revision 18231)
@@ -0,0 +1,149 @@
+/*!\file KML_LatLonBox.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LatLonBox.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_LatLonBox::KML_LatLonBox(){/*{{{*/
+
+	north     = 0.;
+	south     = 0.;
+	east      = 0.;
+	west      = 0.;
+	rotation  = 0.;
+
+}
+/*}}}*/
+KML_LatLonBox::~KML_LatLonBox(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_LatLonBox::Echo(){/*{{{*/
+
+	_printf_("KML_LatLonBox:\n");
+	KML_Object::Echo();
+
+	_printf_("         north: " << north << "\n");
+	_printf_("         south: " << south << "\n");
+	_printf_("          east: " << east << "\n");
+	_printf_("          west: " << west << "\n");
+	_printf_("      rotation: " << rotation << "\n");
+}
+/*}}}*/
+void  KML_LatLonBox::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_LatLonBox::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LatLonBox::DeepEcho(const char* indent){/*{{{*/
+
+	_printf_(indent << "KML_LatLonBox:\n");
+	KML_Object::DeepEcho(indent);
+
+	_printf_("         north: " << north << "\n");
+	_printf_("         south: " << south << "\n");
+	_printf_("          east: " << east << "\n");
+	_printf_("          west: " << west << "\n");
+	_printf_("      rotation: " << rotation << "\n");
+}
+/*}}}*/
+void  KML_LatLonBox::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<LatLonBox",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s  <north>%0.16g</north>\n",indent,north);
+	fprintf(filout,"%s  <south>%0.16g</south>\n",indent,south);
+	fprintf(filout,"%s  <east>%0.16g</east>\n",indent,east);
+	fprintf(filout,"%s  <west>%0.16g</west>\n",indent,west);
+	fprintf(filout,"%s  <rotation>%0.16g</rotation>\n",indent,rotation);
+
+	fprintf(filout,"%s</LatLonBox>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LatLonBox::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</LatLonBox",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LatLonBox::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<north>"))
+			KMLFileTokenParse(&north     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<south>"))
+			KMLFileTokenParse(&south     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<east>"))
+			KMLFileTokenParse(&east      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<west>"))
+			KMLFileTokenParse(&west      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<rotation>"))
+			KMLFileTokenParse(&rotation  ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LatLonBox.h	(revision 18231)
@@ -0,0 +1,40 @@
+/*! \file KML_LatLonBox.h 
+ *  \brief: header file for kml_latlonbox object
+ */
+
+#ifndef _KML_LATLONBOX_H_
+#define _KML_LATLONBOX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_LatLonBox: public KML_Object {
+
+	public:
+
+		double north;
+		double south;
+		double east;
+		double west;
+		double rotation;
+
+		/*KML_LatLonBox constructors, destructors {{{*/
+		KML_LatLonBox();
+		~KML_LatLonBox();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LATLONBOX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.cpp	(revision 18231)
@@ -0,0 +1,222 @@
+/*!\file KML_LineString.cpp
+ * \brief: implementation of the kml_linestring object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LineString.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_LineString::KML_LineString(){/*{{{*/
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+KML_LineString::~KML_LineString(){/*{{{*/
+
+	if (coords) xDelete<double>(coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_LineString::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LineString:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (ncoord=" << ncoord << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LineString::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_LineString::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LineString::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LineString:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (ncoord=" << ncoord << ")\n");
+	for (i=0; i<ncoord; i++)
+		if(flag) _printf0_(indent << "                (" << coords[3*i+0] << "," << coords[3*i+1] << "," << coords[3*i+2] << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LineString::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+
+	fprintf(filout,"%s<LineString",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>\n",indent);
+
+/*  loop over the coordinates for the linestring  */
+
+	for (i=0; i<ncoord; i++)
+		fprintf(filout,"%s    %0.16g,%0.16g,%0.16g\n",indent, coords[3*i+0],coords[3*i+1],coords[3*i+2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LineString>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LineString::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</LineString",12)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineString::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_LINESTRING_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords    ,&ncoord    ,0,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmPDouble>(ncoord);
+	lon=xNew<IssmPDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmPDouble>(ncoord);
+	y  =xNew<IssmPDouble>(ncoord);
+	if (sgn) {
+		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+	}
+	else {
+		memcpy(x,lon,ncoord*sizeof(IssmDouble));
+		memcpy(y,lat,ncoord*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",ncoord  ,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertices  */
+
+	for (i=0; i<ncoord; i++)
+	    fprintf(fid,"%lf\t%lf\n",x[i],y[i]);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(lon);
+	xDelete<IssmPDouble>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineString.h	(revision 18231)
@@ -0,0 +1,43 @@
+/*! \file KML_LineString.h 
+ *  \brief: header file for kml_linestring object
+ */
+
+#ifndef _KML_LINESTRING_H_
+#define _KML_LINESTRING_H_
+
+#define KML_LINESTRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LineString: public KML_Geometry {
+
+	public:
+
+		bool    extrude;
+		bool    tessellate;
+		char    altmode[KML_LINESTRING_ALTMODE_LENGTH+1];
+		int     ncoord;
+		double *coords;
+
+		/*KML_LineString constructors, destructors {{{*/
+		KML_LineString();
+		~KML_LineString();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTRING_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.cpp	(revision 18231)
@@ -0,0 +1,125 @@
+/*!\file KML_LineStyle.cpp
+ * \brief: implementation of the kml_linestyle object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LineStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_LineStyle::KML_LineStyle(){/*{{{*/
+
+	width     =1.;
+
+}
+/*}}}*/
+KML_LineStyle::~KML_LineStyle(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_LineStyle::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LineStyle:\n");
+	KML_ColorStyle::Echo();
+
+	if(flag) _printf0_("         width: " << width << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LineStyle::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_LineStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LineStyle::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LineStyle:\n");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "         width: " << width << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LineStyle::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<LineStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <width>%g</width>\n",indent,width);
+
+	fprintf(filout,"%s</LineStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LineStyle::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</LineStyle",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<width>"))
+			KMLFileTokenParse(&width     ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LineStyle.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*! \file KML_LineStyle.h 
+ *  \brief: header file for kml_linestyle object
+ */
+
+#ifndef _KML_LINESTYLE_H_
+#define _KML_LINESTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_LineStyle: public KML_ColorStyle {
+
+	public:
+
+		float width;
+
+		/*KML_LineStyle constructors, destructors {{{*/
+		KML_LineStyle();
+		~KML_LineStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTYLE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.cpp	(revision 18231)
@@ -0,0 +1,216 @@
+/*!\file KML_LinearRing.cpp
+ * \brief: implementation of the kml_linearring object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_LinearRing::KML_LinearRing(){/*{{{*/
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+KML_LinearRing::~KML_LinearRing(){/*{{{*/
+
+	if (coords) xDelete<double>(coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_LinearRing::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LinearRing:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (ncoord=" << ncoord << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LinearRing::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_LinearRing::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LinearRing::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LinearRing:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (ncoord=" << ncoord << ")\n");
+	for (i=0; i<ncoord; i++)
+		if(flag)_printf_(indent << "                (" <<coords[3*i+0] << "," <<coords[3*i+1] << "," <<coords[3*i+2] << ")\n\n");
+
+	return;
+}
+/*}}}*/
+void  KML_LinearRing::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+
+	fprintf(filout,"%s<LinearRing",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>\n",indent);
+
+/*  loop over the coordinates for the linearring  */
+
+	for (i=0; i<ncoord; i++)
+		fprintf(filout,"%s    %0.16g,%0.16g,%0.16g\n",indent,coords[3*i+0],coords[3*i+1],coords[3*i+2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LinearRing>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_LinearRing::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char  *kstri = NULL;
+	int    ncom  = 0;
+	char **pcom  = NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,kstr)) return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid,&ncom,&pcom))){
+		if (!strncmp(kstri,"</LinearRing",12)){
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LinearRing::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude,kstri,fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,kstri,fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse(altmode,NULL,KML_LINEARRING_ALTMODE_LENGTH,kstri,fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords,&ncoord,3,0,kstri,fid);
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_LinearRing::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmPDouble>(ncoord);
+	lon=xNew<IssmPDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmPDouble>(ncoord);
+	y  =xNew<IssmPDouble>(ncoord);
+	if (sgn) {
+		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+	}
+	else {
+		memcpy(x,lon,ncoord*sizeof(IssmDouble));
+		memcpy(y,lat,ncoord*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+	if ((lat[ncoord-1] != lat[0]) || (lon[ncoord-1] != lon[0]))
+	    fprintf(fid,"%u	%s\n",ncoord+1,"1.");
+	else
+	    fprintf(fid,"%u	%s\n",ncoord  ,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertices, making sure ring is closed  */
+
+	for (i=0; i<ncoord; i++)
+	    fprintf(fid,"%lf\t%lf\n",x[i],y[i]);
+	if ((lat[ncoord-1] != lat[0]) || (lon[ncoord-1] != lon[0]))
+	    fprintf(fid,"%lf\t%lf\n",x[0],y[0]);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	xDelete<double>(y);
+	xDelete<double>(x);
+	xDelete<double>(lon);
+	xDelete<double>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_LinearRing.h	(revision 18231)
@@ -0,0 +1,43 @@
+/*! \file KML_LinearRing.h 
+ *  \brief: header file for kml_linearring object
+ */
+
+#ifndef _KML_LINEARRING_H_
+#define _KML_LINEARRING_H_
+
+#define KML_LINEARRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LinearRing: public KML_Geometry {
+
+	public:
+
+		bool     extrude;
+		bool     tessellate;
+		char     altmode[KML_LINEARRING_ALTMODE_LENGTH+1];
+		int      ncoord;
+		double  *coords;
+
+		/*KML_LinearRing constructors, destructors {{{*/
+		KML_LinearRing();
+		~KML_LinearRing();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINEARRING_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.cpp	(revision 18231)
@@ -0,0 +1,195 @@
+/*!\file KML_MultiGeometry.cpp
+ * \brief: implementation of the kml_multigeometry object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_Point.h"
+#include "./KML_Polygon.h"
+#include "./KML_LineString.h"
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "./KML_MultiGeometry.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_MultiGeometry::KML_MultiGeometry(){/*{{{*/
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+KML_MultiGeometry::~KML_MultiGeometry(){/*{{{*/
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_MultiGeometry::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Multigeometry:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("      geometry: (size=" << geometry->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_MultiGeometry::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_MultiGeometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_MultiGeometry::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Multigeometry:\n");
+	KML_Geometry::DeepEcho(indent);
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (geometry->Size())
+		for (i=0; i<geometry->Size(); i++) {
+			if(flag) _printf0_(indent << "      geometry: -------- begin [" << i << "] --------\n");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "      geometry: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "      geometry: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_MultiGeometry::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<MultiGeometry",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</MultiGeometry>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_MultiGeometry::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</MultiGeometry",15)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int   i;
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_MultiGeometry.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file KML_MultiGeometry.h 
+ *  \brief: header file for kml_multigeometry object
+ */
+
+#ifndef _KML_MULTIGEOMETRY_H_
+#define _KML_MULTIGEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_MultiGeometry: public KML_Geometry {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_MultiGeometry constructors, destructors {{{*/
+		KML_MultiGeometry();
+		~KML_MultiGeometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_MULTIGEOMETRY_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.cpp	(revision 18231)
@@ -0,0 +1,340 @@
+/*!\file KML_Object.cpp
+ * \brief: implementation of the kml_object abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_Attribute.h"
+#include "./KML_Comment.h"
+#include "./KML_Unknown.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_Icon.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_Document.h"
+#include "./KML_LinearRing.h"
+#include "./KML_LineStyle.h"
+#include "./KML_LineString.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Polygon.h"
+#include "./KML_Point.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Placemark.h"
+#include "./KML_Folder.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Object::KML_Object(){/*{{{*/
+
+	attrib    =new DataSet;
+	commnt    =new DataSet;
+	kmlobj    =new DataSet;
+
+}
+/*}}}*/
+KML_Object::~KML_Object(){/*{{{*/
+
+	if (attrib) {
+		delete attrib;
+		attrib    =NULL;
+	}
+	if (commnt) {
+		delete commnt;
+		commnt    =NULL;
+	}
+	if (kmlobj) {
+		delete kmlobj;
+		kmlobj    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Object::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("        attrib: (size=" << attrib->Size() << ")\n");
+	if(flag) _printf0_("        commnt: (size=" << commnt->Size() << ")\n");
+	if(flag) _printf0_("        kmlobj: (size=" << kmlobj->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Object::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Object::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+/*  loop over the attributes for the object  */
+
+	if (attrib->Size())
+		for (i=0; i<attrib->Size(); i++) {
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->DeepEcho(indent);
+		}
+	else
+		if(flag) _printf0_(indent << "        attrib: [empty]\n");
+
+/*  loop over the comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++) {
+			((KML_Comment *)commnt->GetObjectByOffset(i))->DeepEcho(indent);
+		}
+	else
+		if(flag) _printf0_(indent << "        commnt: [empty]\n");
+
+/*  loop over the unknown objects for the object  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (kmlobj->Size())
+		for (i=0; i<kmlobj->Size(); i++) {
+            if(flag) _printf0_(indent << "        kmlobj: -------- begin [" << i << "] --------\n");
+			((KML_Unknown *)kmlobj->GetObjectByOffset(i))->DeepEcho(indent2);
+            if(flag) _printf0_(indent << "        kmlobj: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "        kmlobj: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Object::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+
+//  attributes always written in keyword line of derived classes
+//  comments always written after keyword line of derived classes
+
+/*  loop over the unknown objects for the object  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (kmlobj->Size())
+		for (i=0; i<kmlobj->Size(); i++) {
+			((KML_Unknown *)kmlobj->GetObjectByOffset(i))->Write(filout,indent2);
+		}
+
+	return;
+}
+/*}}}*/
+void  KML_Object::Read(FILE* fid,char* kstr){/*{{{*/
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Object", 8))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Object::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LatLonBox",10)) {
+		kobj=(KML_Object*)new KML_LatLonBox();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		kobj=(KML_Object*)new KML_Icon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Point", 6)) {
+		kobj=(KML_Object*)new KML_Point();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LineString",11)) {
+		kobj=(KML_Object*)new KML_LineString();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LinearRing",11)) {
+		kobj=(KML_Object*)new KML_LinearRing();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Polygon", 8)) {
+		kobj=(KML_Object*)new KML_Polygon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<MultiGeometry",14)) {
+		kobj=(KML_Object*)new KML_MultiGeometry();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<IconStyle",10)) {
+//		kobj=(KML_Object*)new KML_IconStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<LabelStyle",11)) {
+//		kobj=(KML_Object*)new KML_LabelStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<LineStyle",10)) {
+		kobj=(KML_Object*)new KML_LineStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<PolyStyle",10)) {
+		kobj=(KML_Object*)new KML_PolyStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<BalloonStyle",13)) {
+//		kobj=(KML_Object*)new KML_BalloonStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<ListStyle",10)) {
+//		kobj=(KML_Object*)new KML_ListStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<",1)) {
+		_printf0_("KML_Object::Read -- Unrecognized opening tag " << kstr << ".\n");
+//		KMLFileTagSkip(kstr,
+//					   fid);
+		kobj=(KML_Object*)new KML_Unknown();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	return;
+}
+/*}}}*/
+void  KML_Object::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	;
+
+	return;
+}
+/*}}}*/
+void  KML_Object::AddAttrib(const char* name,const char* value){/*{{{*/
+
+	KML_Attribute* katt=NULL;
+
+	katt=new KML_Attribute();
+	katt->Alloc(name,value);
+	katt->Add(attrib);
+
+	return;
+}
+/*}}}*/
+void  KML_Object::WriteAttrib(FILE* filout,const char* indent){/*{{{*/
+
+//  attributes always written in keyword line of kml_object
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (int i=0; i<attrib->Size(); i++)
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Object::AddCommnt(int ncom,char** pcom){/*{{{*/
+
+	int   i;
+	KML_Comment* kcom=NULL;
+
+	for (i=0; i<ncom; i++) {
+		kcom=new KML_Comment();
+		kcom->Alloc(pcom[i]);
+		kcom->Add(commnt);
+	}
+
+	return;
+}
+/*}}}*/
+void  KML_Object::AddCommnt(char* value){/*{{{*/
+
+	KML_Comment* kcom=NULL;
+
+	kcom=new KML_Comment();
+	kcom->Alloc(value);
+	kcom->Add(commnt);
+
+	return;
+}
+/*}}}*/
+void  KML_Object::WriteCommnt(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+
+//  comments always written after keyword line of kml_object
+
+/*  loop over any comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++)
+			((KML_Comment *)commnt->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Object.h	(revision 18231)
@@ -0,0 +1,45 @@
+/*! \file KML_Object.h 
+ *  \brief: header file for kml_object abstract object
+ */
+
+#ifndef _KML_OBJECT_H_
+#define _KML_OBJECT_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+class KML_Object: public Object {
+
+	public:
+
+		DataSet* attrib;
+		DataSet* commnt;
+		DataSet* kmlobj;
+
+		/*KML_Object constructors, destructors {{{*/
+		KML_Object();
+		~KML_Object();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual void  Write(FILE* fid,const char* indent)=0;
+		virtual void  Read(FILE* fid,char* kstr)=0;
+		virtual void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		virtual void  AddAttrib(const char* name,const char* value);
+		virtual void  WriteAttrib(FILE* fid,const char* indent);
+		virtual void  AddCommnt(int ncom,char** pcom);
+		virtual void  AddCommnt(char* value);
+		virtual void  WriteCommnt(FILE* fid,const char* indent);
+
+};
+#endif  /* _KML_OBJECT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.cpp	(revision 18231)
@@ -0,0 +1,125 @@
+/*!\file KML_Overlay.cpp
+ * \brief: implementation of the kml_overlay abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Overlay.h"
+#include "./KML_Icon.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Overlay::KML_Overlay(){/*{{{*/
+
+	strcpy(color     ,"ffffffff");
+	memcpy(color,"ffffffff",(strlen("ffffffff")+1)*sizeof(char));
+
+	draword   = 0;
+	icon      =NULL;
+
+}
+/*}}}*/
+KML_Overlay::~KML_Overlay(){/*{{{*/
+
+	if (icon) {
+		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Overlay::Echo(){/*{{{*/
+
+	KML_Feature::Echo();
+	_printf0_("         color: \"" << color << "\"\n");
+	_printf0_("       draword: " << draword << "\n");
+	_printf0_("          icon: " << icon << "\n");
+}
+/*}}}*/
+void  KML_Overlay::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Overlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Overlay::DeepEcho(const char* indent){/*{{{*/
+
+	char  indent2[81];
+	KML_Feature::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	_printf0_(indent << "         color: " << color << "\n");
+	_printf0_(indent << "       draword: " << draword << "\n");
+	if (icon)
+		icon->DeepEcho(indent2);
+	else
+		_printf0_(indent << "          icon: " << icon << "\n");
+}
+/*}}}*/
+void  KML_Overlay::Write(FILE* filout,const char* indent){/*{{{*/
+
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	fprintf(filout,"%s  <drawOrder>%d</drawOrder>\n",indent,draword);
+	if (icon)
+		icon->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+void  KML_Overlay::Read(FILE* fid,char* kstr){/*{{{*/
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Overlay", 9)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Overlay::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_OVERLAY_COLOR_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<drawOrder>"))
+		KMLFileTokenParse(&draword   ,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		icon      =new KML_Icon();
+		icon      ->Read(fid,kstr);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Overlay.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file KML_Overlay.h 
+ *  \brief: header file for kml_overlay abstract object
+ */
+
+#ifndef _KML_OVERLAY_H_
+#define _KML_OVERLAY_H_
+
+#define KML_OVERLAY_COLOR_LENGTH  8
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class KML_Icon;
+/*}}}*/
+
+class KML_Overlay: public KML_Feature {
+
+	public:
+
+		char  color[KML_OVERLAY_COLOR_LENGTH+1];
+		int   draword;
+		KML_Icon* icon;
+
+		/*KML_Overlay constructors, destructors {{{*/
+		KML_Overlay();
+		~KML_Overlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_OVERLAY_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.cpp	(revision 18231)
@@ -0,0 +1,203 @@
+/*!\file KML_Placemark.cpp
+ * \brief: implementation of the kml_placemark object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Geometry.h"
+#include "./KML_Point.h"
+#include "./KML_LineString.h"
+#include "./KML_Polygon.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_LinearRing.h"
+#include "./KML_Placemark.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Placemark::KML_Placemark(){/*{{{*/
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+KML_Placemark::~KML_Placemark(){/*{{{*/
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Placemark::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Placemark:\n");
+	KML_Feature::Echo();
+
+	if(flag) _printf0_("      geometry: (size=" << geometry->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Placemark::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Placemark::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Placemark::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Placemark:\n");
+	KML_Feature::DeepEcho(indent);
+
+/*  loop over the geometry elements for the placemark  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (geometry->Size())
+		for (i=0; i<geometry->Size(); i++) {
+			if(flag) _printf0_(indent << "      geometry: -------- begin [" << i << "] --------\n");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "      geometry: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "      geometry: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Placemark::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<Placemark",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the geometry elements for the placemark  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</Placemark>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Placemark::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Placemark",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Placemark::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Feature::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int   i;
+	char  nstr2[81];
+
+/*  loop over the geometry elements for the placemark  */
+
+	for (i=0; i<geometry->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s %s",nstr,name);
+		else
+			sprintf(nstr2,"%s",name);
+
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Placemark.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*! \file KML_Placemark.h 
+ *  \brief: header file for kml_placemark object
+ */
+
+#ifndef _KML_PLACEMARK_H_
+#define _KML_PLACEMARK_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_Placemark: public KML_Feature {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_Placemark constructors, destructors {{{*/
+		KML_Placemark();
+		~KML_Placemark();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_PLACEMARK_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.cpp	(revision 18231)
@@ -0,0 +1,185 @@
+/*!\file KML_Point.cpp
+ * \brief: implementation of the kml_point object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Point.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Point::KML_Point(){/*{{{*/
+
+	extrude   =false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	coords[0] = 0.;
+	coords[1] = 0.;
+	coords[2] = 0.;
+
+}
+/*}}}*/
+KML_Point::~KML_Point(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Point::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Point:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Point::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Point::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Point::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Point:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Point::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<Point",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>%0.16g,%0.16g,%0.16g</coordinates>\n",
+			indent,coords[0],coords[1],coords[2]);
+
+	fprintf(filout,"%s</Point>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Point::Read(FILE* fid,char* kstr){/*{{{*/
+
+	double*      pcoords=&coords[0];
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Point", 7)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Point::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   , kstri, fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POINT_ALTMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&pcoords   ,NULL,3, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int     i;
+	double  lat,lon,x,y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude  */
+
+	lon=coords[0];
+	lat=coords[1];
+
+/*  convert latitude and longitude to x and y  */
+
+	if (sgn) {
+		Ll2xyx(&x,&y,&lat,&lon,1,sgn,cm,sp);
+	}
+	else {
+		memcpy(&x,&lon,1*sizeof(IssmDouble));
+		memcpy(&y,&lat,1*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",1,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertex  */
+
+    fprintf(fid,"%lf\t%lf\n",x,y);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Point.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*! \file KML_Point.h 
+ *  \brief: header file for kml_point object
+ */
+
+#ifndef _KML_POINT_H_
+#define _KML_POINT_H_
+
+#define KML_POINT_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_Point: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		char  altmode[KML_POINT_ALTMODE_LENGTH+1];
+		double coords[3];
+
+		/*KML_Point constructors, destructors {{{*/
+		KML_Point();
+		~KML_Point();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POINT_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.cpp	(revision 18231)
@@ -0,0 +1,135 @@
+/*!\file KML_PolyStyle.cpp
+ * \brief: implementation of the kml_polystyle object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_ColorStyle.h"
+#include "./KML_PolyStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_PolyStyle::KML_PolyStyle(){/*{{{*/
+
+	fill      =true;
+	outline   =true;
+
+}
+/*}}}*/
+KML_PolyStyle::~KML_PolyStyle(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_PolyStyle::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_PolyStyle:\n");
+	KML_ColorStyle::Echo();
+
+	if(flag) _printf0_("          fill: " << fill << "\n");
+	if(flag) _printf0_("       outline: " << outline << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_PolyStyle::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_PolyStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_PolyStyle::DeepEcho(const char* indent){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_PolyStyle:\n");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          fill: " << fill << "\n");
+	if(flag) _printf0_(indent << "       outline: " << outline << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_PolyStyle::Write(FILE* filout,const char* indent){/*{{{*/
+
+	fprintf(filout,"%s<PolyStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <fill>%d</fill>\n",indent,fill);
+	fprintf(filout,"%s  <outline>%d</outline>\n",indent,outline);
+
+	fprintf(filout,"%s</PolyStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_PolyStyle::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</PolyStyle",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_PolyStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<fill>"))
+			KMLFileTokenParse(&fill      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<outline>"))
+			KMLFileTokenParse(&outline   ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_PolyStyle.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file KML_PolyStyle.h 
+ *  \brief: header file for kml_polystyle object
+ */
+
+#ifndef _KML_POLYSTYLE_H_
+#define _KML_POLYSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_PolyStyle: public KML_ColorStyle {
+
+	public:
+
+		int   fill;
+		int   outline;
+
+		/*KML_PolyStyle constructors, destructors {{{*/
+		KML_PolyStyle();
+		~KML_PolyStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYSTYLE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.cpp	(revision 18231)
@@ -0,0 +1,283 @@
+/*!\file KML_Polygon.cpp
+ * \brief: implementation of the kml_polygon object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "./KML_Polygon.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Polygon::KML_Polygon(){/*{{{*/
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	outer     =new DataSet;
+	inner     =new DataSet;
+
+}
+/*}}}*/
+KML_Polygon::~KML_Polygon(){/*{{{*/
+
+	if (inner) {
+		delete inner;
+		inner     =NULL;
+	}
+
+	if (outer) {
+		delete outer;
+		outer     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Polygon::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Polygon:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("         outer: (size=" << outer->Size() << ")\n");
+	if(flag) _printf0_("         inner: (size=" << inner->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Polygon::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Polygon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Polygon::DeepEcho(const char* indent){/*{{{*/
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Polygon:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (outer->Size())
+		for (i=0; i<outer->Size(); i++) {
+			if(flag) _printf0_(indent << "         outer: -------- begin [" << i << "] --------\n");
+			((KML_LinearRing *)outer->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         outer: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         outer: [empty]\n");
+
+	if (inner->Size())
+		for (i=0; i<inner->Size(); i++) {
+			if(flag) _printf0_(indent << "         inner: -------- begin [" << i << "] --------\n");
+			((KML_LinearRing *)inner->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         inner: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         inner: [empty]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Polygon::Write(FILE* filout,const char* indent){/*{{{*/
+
+	int   i;
+	char  indent4[81];
+
+	fprintf(filout,"%s<Polygon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+
+	memcpy(indent4,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent4,"    ");
+
+/*  check outer boundary for the polygon  */
+
+	fprintf(filout,"%s  <outerBoundaryIs>\n",indent);
+	if (outer->Size())
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->Write(filout,indent4);
+	fprintf(filout,"%s  </outerBoundaryIs>\n",indent);
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		fprintf(filout,"%s  <innerBoundaryIs>\n",indent);
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->Write(filout,indent4);
+		fprintf(filout,"%s  </innerBoundaryIs>\n",indent);
+	}
+
+	fprintf(filout,"%s</Polygon>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Polygon::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	char*        kstrj;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Polygon", 9)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POLYGON_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+
+		else if (!strcmp(kstri,"<outerBoundaryIs>"))
+
+/*  loop over and process fields within outer boundary  */
+
+			while((kstrj=KMLFileToken(fid, &ncom,&pcom))){
+				if      (!strncmp(kstrj,"</outerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					outer     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+		else if (!strcmp(kstri,"<innerBoundaryIs>"))
+
+/*  loop over and process fields within inner boundaries  */
+
+			while((kstrj=KMLFileToken(fid, &ncom,&pcom))){
+				if      (!strncmp(kstrj,"</innerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					inner     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
+
+	int   i;
+	char  nstr2[81];
+
+/*  check outer boundary for the polygon  */
+
+	if (outer->Size()) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (outer)",nstr);
+		else
+			sprintf(nstr2,"(outer)");
+
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (inner %d of %d)",nstr,i+1,inner->Size());
+		else
+			sprintf(nstr2,"(inner %d of %d)",i+1,inner->Size());
+
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Polygon.h	(revision 18231)
@@ -0,0 +1,45 @@
+/*! \file KML_Polygon.h 
+ *  \brief: header file for kml_polygon object
+ */
+
+#ifndef _KML_POLYGON_H_
+#define _KML_POLYGON_H_
+
+#define KML_POLYGON_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+class KML_LinearRing;
+class DataSet;
+/*}}}*/
+
+class KML_Polygon: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		bool  tessellate;
+		char  altmode[KML_POLYGON_ALTMODE_LENGTH+1];
+		DataSet* outer;
+		DataSet* inner;
+
+		/*KML_Polygon constructors, destructors {{{*/
+		KML_Polygon();
+		~KML_Polygon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYGON_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.cpp	(revision 18231)
@@ -0,0 +1,229 @@
+/*!\file KML_Style.cpp
+ * \brief: implementation of the kml_style object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_LineStyle.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Style.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Style::KML_Style(){/*{{{*/
+
+	icon      =NULL;
+	label     =NULL;
+	line      =NULL;
+	poly      =NULL;
+	balloon   =NULL;
+	list      =NULL;
+
+}
+/*}}}*/
+KML_Style::~KML_Style(){/*{{{*/
+
+	if (list) {
+//		delete list;
+		list      =NULL;
+	}
+	if (balloon) {
+//		delete balloon;
+		balloon   =NULL;
+	}
+	if (poly) {
+		delete poly;
+		poly      =NULL;
+	}
+	if (line) {
+		delete line;
+		line      =NULL;
+	}
+	if (label) {
+//		delete label;
+		label     =NULL;
+	}
+	if (icon) {
+//		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Style::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Style:\n");
+	KML_StyleSelector::Echo();
+
+	if(flag) _printf0_("          icon: " << icon << "\n");
+	if(flag) _printf0_("         label: " << label << "\n");
+	if(flag) _printf0_("          line: " << line << "\n");
+	if(flag) _printf0_("          poly: " << poly << "\n");
+	if(flag) _printf0_("       balloon: " << balloon << "\n");
+	if(flag) _printf0_("          list: " << list << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Style::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Style::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Style::DeepEcho(const char* indent){/*{{{*/
+
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Style:\n");
+	KML_StyleSelector::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "          icon: " << icon << "\n");
+//	if (label)
+//		label->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "         label: " << label << "\n");
+	if (line)
+		line->DeepEcho(indent2);
+	else
+		if(flag) _printf0_(indent << "          line: " << line << "\n");
+	if (poly)
+		poly->DeepEcho(indent2);
+	else
+		if(flag) _printf0_(indent << "          poly: " << poly << "\n");
+//	if (balloon)
+//		balloon->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "       balloon: " << balloon << "\n");
+//	if (list)
+//		list->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "          list: " << list << "\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Style::Write(FILE* filout,const char* indent){/*{{{*/
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<Style",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_StyleSelector::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->Write(filout,indent2);
+//	if (label)
+//		label->Write(filout,indent2);
+	if (line)
+		line->Write(filout,indent2);
+	if (poly)
+		poly->Write(filout,indent2);
+//	if (balloon)
+//		balloon->Write(filout,indent2);
+//	if (list)
+//		list->Write(filout,indent2);
+
+	fprintf(filout,"%s</Style>\n",indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Style::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+		if      (!strncmp(kstri,"</Style", 7)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Style::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+//		else if (!strncmp(kstri,"<IconStyle",10)) {
+//			icon      =new KML_IconStyle();
+//			icon      ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<LabelStyle",11)) {
+//			label     =new KML_LabelStyle();
+//			label     ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<LineStyle",10)) {
+			line      =new KML_LineStyle();
+			line      ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<PolyStyle",10)) {
+			poly      =new KML_PolyStyle();
+			poly      ->Read(fid,kstri);
+		}
+
+//		else if (!strncmp(kstri,"<BalloonStyle",13)) {
+//			balloon   =new KML_BalloonStyle();
+//			balloon   ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<ListStyle",10)) {
+//			list      =new KML_ListStyle();
+//			list      ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_StyleSelector::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Style.h	(revision 18231)
@@ -0,0 +1,43 @@
+/*! \file KML_Style.h 
+ *  \brief: header file for kml_style object
+ */
+
+#ifndef _KML_STYLE_H_
+#define _KML_STYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_StyleSelector.h"
+class KML_LineStyle;
+class KML_PolyStyle;
+/*}}}*/
+
+class KML_Style: public KML_StyleSelector {
+
+	public:
+
+		void* icon;
+		void* label;
+		KML_LineStyle* line;
+		KML_PolyStyle* poly;
+		void* balloon;
+		void* list;
+
+		/*KML_Style constructors, destructors {{{*/
+		KML_Style();
+		~KML_Style();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file KML_StyleSelector.cpp
+ * \brief: implementation of the kml_styleselector abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_StyleSelector.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_StyleSelector::KML_StyleSelector(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_StyleSelector::~KML_StyleSelector(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_StyleSelector::Echo(){/*{{{*/
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_StyleSelector::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_StyleSelector::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_StyleSelector::DeepEcho(const char* indent){/*{{{*/
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_StyleSelector::Write(FILE* filout,const char* indent){/*{{{*/
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+void  KML_StyleSelector::Read(FILE* fid,char* kstr){/*{{{*/
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</StyleSelector",15))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_StyleSelector.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file KML_StyleSelector.h 
+ *  \brief: header file for kml_styleselector abstract object
+ */
+
+#ifndef _KML_STYLESELECTOR_H_
+#define _KML_STYLESELECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_StyleSelector: public KML_Object {
+
+	public:
+
+		/*KML_StyleSelector constructors, destructors {{{*/
+		KML_StyleSelector();
+		~KML_StyleSelector();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLESELECTOR_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file KML_SubStyle.cpp
+ * \brief: implementation of the kml_substyle abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_SubStyle.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_SubStyle::KML_SubStyle(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+KML_SubStyle::~KML_SubStyle(){/*{{{*/
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_SubStyle::Echo(){/*{{{*/
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+void  KML_SubStyle::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_SubStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_SubStyle::DeepEcho(const char* indent){/*{{{*/
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_SubStyle::Write(FILE* filout,const char* indent){/*{{{*/
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+void  KML_SubStyle::Read(FILE* fid,char* kstr){/*{{{*/
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</SubStyle",10))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_SubStyle.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file KML_SubStyle.h 
+ *  \brief: header file for kml_substyle abstract object
+ */
+
+#ifndef _KML_SUBSTYLE_H_
+#define _KML_SUBSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_SubStyle: public KML_Object {
+
+	public:
+
+		/*KML_SubStyle constructors, destructors {{{*/
+		KML_SubStyle();
+		~KML_SubStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_SUBSTYLE_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.cpp	(revision 18231)
@@ -0,0 +1,185 @@
+/*!\file KML_Unknown.cpp
+ * \brief: implementation of the kml_unknown object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Unknown.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+KML_Unknown::KML_Unknown(){/*{{{*/
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+KML_Unknown::~KML_Unknown(){/*{{{*/
+
+	if (name      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+void  KML_Unknown::Echo(){/*{{{*/
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Unknown " << name << ":\n");
+	KML_Object::Echo();
+
+	if(value){
+		if(flag) _printf0_("         value: \"" << value << "\"\n");
+	}
+	else{
+		if(flag) _printf0_("         value: [none]\n");
+	}
+
+	return;
+}
+/*}}}*/
+void  KML_Unknown::DeepEcho(){/*{{{*/
+
+	char  indent[81]="";
+
+	KML_Unknown::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+void  KML_Unknown::DeepEcho(const char* indent){/*{{{*/
+
+	char*        valuei;
+	char*        vtoken;
+	char         nl[]={'\n','\0'};
+	bool         flag=true;
+
+	if(flag) _printf0_(indent << "KML_Unknown " << name << ":\n");
+	KML_Object::DeepEcho(indent);
+
+	if (value     ) {
+		valuei=xNew<char>(strlen(value)+1);
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+
+		vtoken=strtok(valuei,nl);
+		if(flag) _printf0_(indent << "         value: \"" << vtoken);
+
+		while((vtoken=strtok(NULL,nl)))
+			if(flag) _printf0_("\n" << indent << "                 " << vtoken);
+		if(flag) _printf0_("\"\n");
+
+		xDelete<char>(valuei);
+	}
+    else
+        if(flag) _printf0_(indent << "         value: [none]\n");
+
+	return;
+}
+/*}}}*/
+void  KML_Unknown::Write(FILE* filout,const char* indent){/*{{{*/
+
+	char*        valuei;
+	char*        vtoken;
+	char         nl[]={'\n','\0'};
+
+	fprintf(filout,"%s<%s",indent,name);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	if (value     ) {
+		valuei=xNew<char>(strlen(value)+1);
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+
+		vtoken=strtok(valuei,nl);
+		fprintf(filout,"%s  %s\n",indent,vtoken);
+
+		while((vtoken=strtok(NULL,nl)))
+			fprintf(filout,"%s  %s\n",indent,vtoken);
+
+		xDelete<char>(valuei);
+	}
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s</%s>\n",indent,name);
+
+	return;
+}
+/*}}}*/
+void  KML_Unknown::Read(FILE* fid,char* kstr){/*{{{*/
+
+	char*        kstri;
+	char*        value2=NULL;
+	int          ncom=0;
+	char**       pcom=NULL;
+	char         nl[]={'\n','\0'};
+
+/*  get object name  */
+
+	name=KMLFileTagName(NULL,
+						kstr);
+//	_printf0_("KML_Unknown::Read -- opening name=" << name << ".\n");
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while((kstri=KMLFileToken(fid, &ncom,&pcom))){
+//		_printf0_("KML_Unknown::Read -- kstri=" << kstri << ".\n");
+		if      (!strncmp(&kstri[0],"</", 2) &&
+				 !strncmp(&kstri[2],name,strlen(name))) {
+//			_printf0_("KML_Unknown::Read -- closing name=" << name << ".\n");
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
+
+		else if (strncmp(kstri,"<",1)) {
+			if (value) {
+				value2=xNew<char>(strlen(value)+1+strlen(kstri)+1);
+				memcpy(value2,value,(strlen(value)+1)*sizeof(char));
+				xDelete<char>(value);
+				value=value2;
+				value2=NULL;
+//				value=(char *) xrealloc(value,(strlen(value)+1+strlen(kstri)+1)*sizeof(char));
+				strcat(value,nl);
+				strcat(value,kstri);
+			}
+			else {
+				value=xNew<char>(strlen(kstri)+1);
+				memcpy(value,kstri,(strlen(kstri)+1)*sizeof(char));
+			}
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom=ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/KML_Unknown.h	(revision 18231)
@@ -0,0 +1,37 @@
+/*! \file KML_Unknown.h 
+ *  \brief: header file for kml_unknown object
+ */
+
+#ifndef _KML_UNKNOWN_H_
+#define _KML_UNKNOWN_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Unknown: public KML_Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Unknown constructors, destructors {{{*/
+		KML_Unknown();
+		~KML_Unknown();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_UNKNOWN_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/kmlobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/kmlobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/kml/kmlobjects.h	(revision 18231)
@@ -0,0 +1,37 @@
+/* \file kmlobjects.h
+ * \brief: prototype header for all kml related objects.
+ */
+
+#ifndef KML_OBJECTS_H_
+#define KML_OBJECTS_H_
+
+/*KML parsing objects: */
+#include "./KML_Attribute.h"
+#include "./KML_Comment.h"
+#include "./KML_ColorStyle.h"
+#include "./KML_Container.h"
+#include "./KML_Document.h"
+#include "./KML_Feature.h"
+#include "./KML_File.h"
+#include "./KML_Folder.h"
+#include "./KML_Geometry.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Icon.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_LinearRing.h"
+#include "./KML_LineString.h"
+#include "./KML_LineStyle.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_Object.h"
+#include "./KML_Overlay.h"
+#include "./KML_Point.h"
+#include "./KML_Placemark.h"
+#include "./KML_Polygon.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Style.h"
+#include "./KML_StyleSelector.h"
+#include "./KML_SubStyle.h"
+#include "./KML_Unknown.h"
+#include "./KMLFileReadUtils.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentFinalize.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentFinalize.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentFinalize.cpp	(revision 18231)
@@ -0,0 +1,25 @@
+/*!\file:  EnvironmentFinalize.cpp
+ * \brief: finalize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+
+void EnvironmentFinalize(void){
+
+	int my_rank;
+
+	/*Make sure we are all here*/
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD);
+
+	/*Print closing statement*/
+	ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&my_rank);
+	if(!my_rank) printf("closing MPI\n");
+
+	/*Finalize: */
+	ISSM_MPI_Finalize();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentInit.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentInit.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/EnvironmentInit.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*!\file:  EnvironmentInit.cpp
+ * \brief: initialize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include "../toolkits/toolkits.h"
+
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv){
+
+	/*Output*/
+	ISSM_MPI_Comm comm = 0;
+
+	/*Initialize MPI environment: */
+	#if defined(_HAVE_MPI_)
+	ISSM_MPI_Init(&argc,&argv);
+	comm = ISSM_MPI_COMM_WORLD;
+	#else
+	comm = 1; //bogus number for comm, which does not exist anyway.
+	#endif
+
+	/*Print Banner*/
+	int my_rank = 0;
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	if(!my_rank) printf("\n");
+	if(!my_rank) printf("%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/branches/trunk-jpl-ad2-integrated/src/c/main/globals.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/globals.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/globals.h	(revision 18231)
@@ -0,0 +1,20 @@
+/*!\file global.h:
+ * \brief: these are the global variables always needed. 
+ */
+
+#ifndef _GLOBALS_H_
+#define _GLOBALS_H_
+
+#include "../shared/io/Comm/IssmComm.h"
+#include "../toolkits/ToolkitOptions.h"
+
+/*Communicators: */
+ISSM_MPI_Comm IssmComm::comm;
+bool IssmComm::parallel;
+
+/*String that is used to characterize our toolkits, ends up in Petsc Options
+ * database if we use Petsc. Can also be used to characterize the ISSM toolkit,
+ * often used when Petsc is not allowed*/
+char* ToolkitOptions::toolkitoptions;
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*!\file:  issm.cpp
+ * \brief: ISSM main program
+ */ 
+
+#include "./issm.h"
+
+int main(int argc,char **argv){
+
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
+
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	ISSM_MPI_Comm comm_init=EnvironmentInit(argc,argv);
+
+	/*Initialize femmodel from arguments provided command line: */
+	FemModel *femmodel = new FemModel(argc,argv,comm_init);
+
+	/*Solve: */
+	femmodel->Solve();
+
+	/*Output results: */
+	OutputResultsx(femmodel);
+
+	/*Wrap up: */
+	delete femmodel;
+
+	/*Finalize environment:*/
+	EnvironmentFinalize();
+
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
+
+	/*Return unix success: */
+	return 0; 
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/issm.h	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file: issm.h
+ * \brief prototype wrapper for issm.h
+ */ 
+
+#ifndef _ISSM_H_
+#define _ISSM_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./globals.h" //only include this header file once!
+#include "../shared/shared.h"
+#include "../classes/classes.h"
+#include "../toolkits/toolkits.h"
+#include "../cores/cores.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+/*Environment*/
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv);
+void EnvironmentFinalize(void);
+
+#endif //ifndef _ISSM_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/main/kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/main/kriging.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/main/kriging.cpp	(revision 18231)
@@ -0,0 +1,174 @@
+/*!\file:  kriging.cpp
+ * \brief: kriging main parallel program
+ */ 
+
+#include "./issm.h"
+
+/*Local prototypes*/
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv);
+void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid);
+
+int main(int argc,char **argv){
+
+	/*I/O: */
+	FILE *output_fid = NULL;
+	FILE *input_fid  = NULL;
+
+	/*File names*/
+	char *lockfilename   = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *rootpath       = NULL;
+
+	/*Input*/
+	int         ninterp,nobs;
+	IssmDouble *x        = NULL;
+	IssmDouble *y        = NULL;
+	IssmDouble *data     = NULL;
+	IssmDouble *x_interp = NULL;
+	IssmDouble *y_interp = NULL;
+	Options    *options  = NULL;
+
+	/*Output*/
+	IssmDouble *predictions = NULL;
+	IssmDouble *error       = NULL;
+
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
+
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	ISSM_MPI_Comm comm=EnvironmentInit(argc,argv);
+	IssmComm::SetComm(comm);
+
+	ProcessArguments2(&binfilename,&outbinfilename,&lockfilename,&rootpath,argc,argv);
+
+	/*Process input files*/
+	input_fid=pfopen(binfilename,"rb");
+	ProcessInputfile(&x,&y,&data,&nobs,&x_interp,&y_interp,&ninterp,&options,input_fid);
+	pfclose(input_fid,binfilename);
+
+	_printf0_("call computational core:\n");
+	pKrigingx(&predictions,&error,x,y,data,nobs,x_interp,y_interp,ninterp,options);
+
+	_printf0_("write results to disk:\n");
+	Results *results = new Results();
+	if(IssmComm::GetRank()==0){
+		output_fid=pfopen0(outbinfilename,"wb");
+		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,0,predictions,ninterp,1,1,0));
+		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
+		for(int i=0;i<results->Size();i++){
+			ExternalResult* result=dynamic_cast<ExternalResult*>(results->GetObjectByOffset(i));
+			result->WriteData(output_fid,1);
+		}
+		pfclose(output_fid,outbinfilename);
+	}
+
+	/*Close output and toolkits options file and write lock file if requested*/
+	_printf0_("write lock file:\n");
+	WriteLockFile(lockfilename);
+
+	/*Free ressources */
+	xDelete<char>(lockfilename);
+	xDelete<char>(binfilename);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(rootpath);
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(data);
+	xDelete<IssmDouble>(x_interp);
+	xDelete<IssmDouble>(y_interp);
+	xDelete<IssmDouble>(predictions);
+	xDelete<IssmDouble>(error);
+	delete options;
+	delete results;
+
+	/*Finalize environment:*/
+	EnvironmentFinalize();
+
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
+
+	return 0; //unix success return;
+}
+
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv){
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *lockfilename   = NULL;
+	char *rootpatharg    = NULL;
+	char *rootpath       = NULL;
+
+	if(argc<1)_error_("Usage error: no execution path provided");
+	if(argc<2)_error_("Usage error: missing model name");
+
+	rootpatharg=argv[1];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}  
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	} 
+
+	modelname=argv[2];
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+}
+
+void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid){
+
+	int      ninterp,nobs,numoptions;
+	IssmDouble  *x        = NULL;
+	IssmDouble  *y        = NULL;
+	IssmDouble  *data     = NULL;
+	IssmDouble  *x_interp = NULL;
+	IssmDouble  *y_interp = NULL;
+	Options *options  = NULL;
+	Option  *option   = NULL;
+
+	int      M,N;
+	IoModel* iomodel = new IoModel();
+	iomodel->fid=fid;
+	iomodel->CheckEnumSync();
+	iomodel->independents=xNew<bool>(MaximumNumberOfDefinitionsEnum); for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++) iomodel->independents[i]=false;
+	iomodel->FetchData(&x,&M,&N,0);        nobs=M*N;
+	iomodel->FetchData(&y,&M,&N,1);        _assert_(M*N==nobs);
+	iomodel->FetchData(&data,&M,&N,2);     _assert_(M*N==nobs);
+	iomodel->FetchData(&x_interp,&M,&N,3); ninterp=M*N;
+	iomodel->FetchData(&y_interp,&M,&N,4); _assert_(M*N==ninterp);
+
+	/*Read options*/
+	options = new Options();
+	iomodel->LastIndex(&N);
+	numoptions=(int)((N-4)/2);
+	for(int i=0;i<numoptions;i++){
+		iomodel->FetchData(&option,5+2*i);
+		options->AddOption(option);
+		option=NULL;
+	}
+
+	/*Assign output pointer*/
+	*px        = x;
+	*py        = y;
+	*pdata     = data;
+	*pnobs     = nobs;
+	*px_interp = x_interp;
+	*py_interp = y_interp;
+	*pninterp  = ninterp;
+	*poptions  = options;
+	delete iomodel;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 18231)
@@ -0,0 +1,282 @@
+/*!\file AllocateSystemMatricesx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./AllocateSystemMatricesx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void AllocateSystemMatricesx(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf,FemModel* femmodel){
+
+	/*Intermediary*/
+	int  fsize,ssize,flocalsize,slocalsize;
+	int  connectivity, numberofdofspernode;
+	int  configuration_type;
+	int  m,n,M,N;
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*output*/
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+
+	bool oldalloc=false;
+	char* toolkittype=NULL;
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+
+	/*retrieve node info*/
+	fsize      = femmodel->nodes->NumberOfDofs(configuration_type,FsetEnum);
+	ssize      = femmodel->nodes->NumberOfDofs(configuration_type,SsetEnum);
+	flocalsize = femmodel->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
+	slocalsize = femmodel->nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
+
+	numberofdofspernode=femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	/*if our matrices are coming from issm, we don't do dynamic allocation like Petsc 
+	 * does, and this routine is essentially useless. Force standard alloc in this case: */
+	toolkittype=ToolkitOptions::GetToolkitType();
+
+	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*/
+			if(strcmp(toolkittype,"issm")==0){
+				Kff=new Matrix<IssmDouble>(m,n,M,N,NULL,NULL);
+			}
+			else{
+				MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,FsetEnum);
+				Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+				xDelete<int>(d_nnz);
+				xDelete<int>(o_nnz);
+			}
+		}
+		if(pKfs){
+			m=flocalsize; n=slocalsize; /*local  sizes*/
+			M=fsize;      N=ssize;      /*global sizes*/
+			if(strcmp(toolkittype,"issm")==0){
+				Kfs=new Matrix<IssmDouble>(m,n,M,N,NULL,NULL);
+			}
+			else{
+				MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,SsetEnum);
+				Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+				xDelete<int>(d_nnz);
+				xDelete<int>(o_nnz);
+			}
+		}
+		if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
+		if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
+	}
+	
+	/*Free ressources: */
+	xDelete<char>(toolkittype);
+
+	/*Allocate output pointers*/
+	if(pKff) *pKff = Kff;
+	if(pKfs) *pKfs = Kfs;
+	if(pdf)  *pdf  = df;
+	if(ppf)  *ppf  = pf;
+}
+
+void MatrixNonzeros(int** pd_nnz,int** po_nnz,FemModel* femmodel,int set1enum,int set2enum){
+
+	/*Intermediary*/
+	int      i,j,k,index,offset,count;
+	int      configuration_type;
+	int      d_nz,o_nz;
+	Element *element            = NULL;
+	Load    *load               = NULL;
+	int     *head_e             = NULL;
+	int     *next_e             = NULL;
+	int     *count2offset_e     = NULL;
+	int     *head_l             = NULL;
+	int     *next_l             = NULL;
+	int     *count2offset_l     = NULL;
+	int     *lidlist            = NULL;
+
+	/*output*/
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*retrive parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*Get vector size and number of nodes*/
+	int numnodes            = femmodel->nodes->NumberOfNodes(configuration_type);
+	int localnumnodes       = femmodel->nodes->Size();
+	int numberofdofspernode = femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
+	int M                   = femmodel->nodes->NumberOfDofs(configuration_type,set1enum);
+	int N                   = femmodel->nodes->NumberOfDofs(configuration_type,set2enum);
+	int m                   = femmodel->nodes->NumberOfDofsLocal(configuration_type,set1enum);
+	int n                   = femmodel->nodes->NumberOfDofsLocal(configuration_type,set2enum);
+	int numnodesperelement  = femmodel->elements->MaxNumNodes();
+	int numnodesperload     = femmodel->loads->MaxNumNodes(configuration_type);
+
+	/*First, we are building chaining vectors so that we know what nodes are
+	 * connected to what elements. These vectors are such that:
+	 *   for(int i=head[id];i!=-1;i=next[i])
+	 * will loop over all the elements that are connected to the node number
+	 * id*/
+	head_e         = xNew<int>(localnumnodes); for(i=0;i<localnumnodes;i++) head_e[i]=-1;
+	next_e         = xNew<int>(femmodel->elements->Size()*numnodesperelement);
+	count2offset_e = xNew<int>(femmodel->elements->Size()*numnodesperelement);
+
+	k=0;
+	for(i=0;i<femmodel->elements->Size();i++){
+		element = dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		lidlist = xNew<int>(element->GetNumberOfNodes());
+		element->GetNodesLidList(lidlist);
+
+		for(j=0;j<element->GetNumberOfNodes();j++){
+			index = lidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_e[k]=i;
+			next_e[k]=head_e[index];
+			head_e[index]=k++;
+		}
+		for(j=0;j<numnodesperelement-element->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(lidlist);
+	}
+
+	/*Chain for loads*/
+	head_l         = xNew<int>(localnumnodes); for(i=0;i<localnumnodes;i++) head_l[i]=-1;
+	next_l         = xNew<int>(femmodel->loads->Size(configuration_type)*numnodesperload);
+	count2offset_l = xNew<int>(femmodel->loads->Size(configuration_type)*numnodesperload);
+	k=0;
+	for(i=0;i<femmodel->loads->Size();i++){
+		load = dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		if(!load->InAnalysis(configuration_type)) continue;
+		lidlist = xNew<int>(load->GetNumberOfNodes());
+		load->GetNodesLidList(lidlist);
+
+		for(j=0;j<load->GetNumberOfNodes();j++){
+			index = lidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_l[k]=i;
+			next_l[k]=head_l[index];
+			head_l[index]=k++;
+		}
+		for(j=0;j<numnodesperload-load->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(lidlist);
+	}
+
+	/*OK now count number of dofs and flag each nodes for each node i*/
+	bool *flags                  = xNew<bool>(localnumnodes);
+	int  *flagsindices           = xNew<int>(localnumnodes);
+	int  *d_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *o_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *connectivity_clone     = xNewZeroInit<int>(numnodes);
+	int  *all_connectivity_clone = xNewZeroInit<int>(numnodes);
+
+	/*Resetting flags to false at eahc iteration takes a lot of time, so we keep track of the flags
+	 * to reset in flagsindices, initialized with -1*/
+	for(i = 0;i<localnumnodes;i++) flags[i]        = false;
+	for(i = 0;i<localnumnodes;i++) flagsindices[i] = -1;
+
+	/*Create connectivity vector*/
+	for(i=0;i<femmodel->nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(configuration_type)){
+
+			/*Reinitialize flags to false*/
+			j=0;
+			while(true){
+				if(flagsindices[j]>=0){
+					flags[flagsindices[j]] = false;
+					flagsindices[j]        = -1;
+					j++;
+				}
+				else{
+					break;
+				}
+			}
+
+			//for(j=0;j<localnumnodes;j++) flags[j]=false;
+
+			/*Loop over elements that hold node number i*/
+			//if(head_e[node->Lid()]==-1 && head_l[node->Lid()]==-1){
+			//	printf("[%i] vertex %i\n",IssmComm::GetRank(),node->Lid()+1);
+			//}
+			for(j=head_e[node->Lid()];j!=-1;j=next_e[j]){
+				offset=count2offset_e[j];
+				element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(offset));
+				element->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+			for(j=head_l[node->Lid()];j!=-1;j=next_l[j]){
+				offset=count2offset_l[j];
+				load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(offset));
+				load->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+		}
+	}
+	xDelete<bool>(flags);
+	xDelete<int>(flagsindices);
+	xDelete<int>(count2offset_e);
+	xDelete<int>(head_e);
+	xDelete<int>(next_e);
+	xDelete<int>(count2offset_l);
+	xDelete<int>(head_l);
+	xDelete<int>(next_l);
+
+	/*sum over all cpus*/
+	ISSM_MPI_Allreduce((void*)connectivity_clone,(void*)all_connectivity_clone,numnodes,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	xDelete<int>(connectivity_clone);
+
+	if(set1enum==FsetEnum){
+		count=0;
+		d_nnz=xNew<int>(m);
+		o_nnz=xNew<int>(m);
+		for(i=0;i<femmodel->nodes->Size();i++){
+			Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+			if(node->InAnalysis(configuration_type) && !node->IsClone()){
+				for(j=0;j<node->indexing.fsize;j++){
+					_assert_(count<m);
+					d_nnz[count]=numberofdofspernode*(d_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					o_nnz[count]=numberofdofspernode*(o_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					if(d_nnz[count]>n)   d_nnz[count]=n;
+					if(o_nnz[count]>N-n) o_nnz[count]=N-n;
+					count++;
+				}
+			}
+		}
+		_assert_(m==count);
+	}
+	else{
+		_error_("STOP not implemented");
+	}
+	xDelete<int>(d_connectivity);
+	xDelete<int>(o_connectivity);
+	xDelete<int>(all_connectivity_clone);
+
+	/*Allocate ouptput pointer*/
+	*pd_nnz=d_nnz;
+	*po_nnz=o_nnz;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  AllocateSystemMatricesx.h
+*/ 
+
+#ifndef _ALLOCATESYSTEMMATRICESX_H
+#define _ALLOCATESYSTEMMATRICESX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void AllocateSystemMatricesx(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf,FemModel* femmodel);
+void MatrixNonzeros(int** pd_nnz,int** po_nnz,FemModel* femmodel,int set1enum,int set2enum);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 18231)
@@ -0,0 +1,65 @@
+/*!\file AverageOntoPartitionx
+ * \brief: average vertex vector values onto a sub-partition of the vertices
+ * used by scaled responses in Qmu analysis. See DakotaResponses module.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./AverageOntoPartitionx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void AverageOntoPartitionx(double** paverage, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response){
+
+	int     dummy;
+	int     npart;
+	double *qmu_part  = NULL;
+
+	/*output: */
+	Vector<IssmDouble>* partition_contributions=NULL;
+	Vector<IssmDouble>* partition_areas=NULL;
+	Vector<IssmDouble>* vec_average=NULL;
+	double* average=NULL;
+
+	/*First, recover qmu partition of vertices: */
+	parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
+
+	/*Some parameters: */
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+
+	/*average onto the separate areas. The result will be a npart sized vector. */
+
+	/*allocate: */
+	partition_contributions=new Vector<IssmDouble>(npart);
+	partition_areas=new Vector<IssmDouble>(npart);
+	vec_average=new Vector<IssmDouble>(npart);
+
+	/*loop on each element, and add contribution of the element to the partition (surface weighted average): */
+	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);
+	}
+
+	/*Assemble: */
+	partition_contributions->Assemble();
+	partition_areas->Assemble();
+
+	/*We have the partition_areas and the partition_contributions for each partition -> compute the surfae weighted average: */
+	vec_average->PointwiseDivide(partition_contributions,partition_areas);
+
+	/*serialize:*/
+	average=vec_average->ToMPISerial();
+
+	/*Free ressources:*/
+	xDelete<double>(qmu_part);
+	delete partition_contributions;
+	delete partition_areas;
+	delete vec_average;
+
+	/*Assign output pointers:*/
+	*paverage=average;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  AverageOntoPartitionx.h
+ * \brief header file for averaging  dakota responses onto a vertices partition
+ */ 
+
+#ifndef _AVERAGEONTOPARTITIONXX_H
+#define _AVERAGEONTOPARTITIONXX_H
+
+#include "../../classes/classes.h"
+
+void AverageOntoPartitionx(double** average, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response);
+
+#endif  /* _AVERAGEONTOPARTITIONXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 18231)
@@ -0,0 +1,29 @@
+/*!\file BamgConvertMeshx
+ */
+
+#include "./BamgConvertMeshx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../bamg/bamgobjects.h"
+
+using namespace bamg;
+using namespace std;
+
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,int* index,double* x,double* y,int nods,int nels){
+
+	/*Options*/
+	BamgOpts* bamgopts=new BamgOpts();
+
+	/*read mesh*/
+	Mesh Th(index,x,y,nods,nels); 
+
+	/*write mesh and geometry*/
+	Th.Gh.WriteGeometry(bamggeom,bamgopts);
+	Th.WriteMesh(bamgmesh,bamgopts);
+
+	/*clean up and return*/
+	delete bamgopts;
+	return 1;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  BamgConvertMeshx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGCONVERTMESHX_H
+#define _BAMGCONVERTMESHX_H
+
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
+
+/* local prototypes: */
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,int* index,double* x,double* y,int nods,int nels);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file BamgTriangulatex
+ */
+
+#include "./BamgTriangulatex.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
+
+using namespace bamg;
+using namespace std;
+
+int BamgTriangulatex(int** pindex,int* pnels,double* x,double* y,int nods){
+
+	Mesh Th(x,y,nods);
+	Th.WriteIndex(pindex,pnels);
+	//delete &Th;
+	return 0;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  BamgTriangulatex.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGTRIANGULATEX_H
+#define _BAMGTRIANGULATEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int BamgTriangulatex(int** pindex,int* pnels,double* x,double* y,int nods);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.cpp	(revision 18231)
@@ -0,0 +1,211 @@
+/*!\file Bamgx
+ * \brief: use Bamg capabilities.
+ */
+#include "./Bamgx.h"
+#include "../../bamg/bamgobjects.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace bamg;
+using namespace std;
+
+int Bamgx(BamgMesh* bamgmesh_out,BamgGeom* bamggeom_out,BamgMesh* bamgmesh_in,BamgGeom* bamggeom_in,BamgOpts* bamgopts){
+
+	/*Bamg options*/
+	int    maxnbv;
+	double coef;
+	int    verbosity;
+	int    nbsmooth;
+
+	/*intermediary*/
+	int i;
+	int noerr=1;
+	double costheta=2;
+	double hminaniso=1e-100; 
+	Mesh* Thr=NULL;
+	Mesh* Thb=NULL;
+
+	/*Bamg options*/
+	nbsmooth =bamgopts->nbsmooth;
+	coef     =bamgopts->coeff;
+	maxnbv   =bamgopts->maxnbv;
+	verbosity=bamgopts->verbose;
+
+	// no metric -> no smoothing 
+	if (bamgopts->metric==NULL) nbsmooth=0; 
+
+	/*If no mesh in input, generate one*/
+	if(bamgmesh_in->TrianglesSize[0]==0){
+		/*Mesh generation {{{*/
+
+		//Step1: generate geometry Gh
+		if (verbosity>0) _printf_("Construction of a mesh from a given geometry\n");
+		if (verbosity>1) _printf_("   Processing geometry...\n");
+		Geometry Gh(bamggeom_in,bamgopts);
+
+		//get hmin and hmax from geometry to generate the metric
+		bamgopts->hmin = Max(bamgopts->hmin,Gh.MinimalHmin());
+		bamgopts->hmax = Min(bamgopts->hmax,Gh.MaximalHmax());
+
+		//build metric using geometry
+		if (verbosity>1) _printf_("   Generating Metric...\n");
+		for(i=0;i<Gh.nbv;i++){
+			Metric M=Gh[i];
+			EigenMetric Vp(M/coef);
+			Vp.Maxh(bamgopts->hmax);
+			Vp.Minh(bamgopts->hmin);
+			Gh.vertices[i].m = Vp;
+		}
+
+		//generate mesh
+		if (verbosity>1) _printf_("   Generating Mesh...\n");
+		Mesh Th(maxnbv,Gh,bamgopts);
+
+		//Split corners if requested
+		if(bamgopts->splitcorners) Th.SplitInternalEdgeWithBorderVertices();
+
+		//Renumbering
+		Th.TrianglesRenumberBySubDomain();
+
+		//Crack mesh if requested
+		if(bamgopts->Crack) Th.CrackMesh(bamgopts);
+
+		//Build output
+		if (verbosity>1) _printf_("   Write Mesh...\n");
+		Th.WriteMesh(bamgmesh_out,bamgopts);
+		if (verbosity>1) _printf_("   Write Geometry...\n");
+		Gh.WriteGeometry(bamggeom_out,bamgopts);
+
+		//clean up
+	//	delete &Th;
+	//	delete &Gh;
+		/*}}}*/
+	}
+	else{
+		/*Anisotropic mesh adaptation {{{*/
+
+		// read background mesh 
+		if (verbosity>0) _printf_("Anisotropic mesh adaptation\n");
+		if (verbosity>1) _printf_("   Processing initial mesh and geometry...\n");
+		Mesh BTh(bamggeom_in,bamgmesh_in,bamgopts); 
+
+		//Make Quadtree from background mesh
+		BTh.MakeBamgQuadtree();
+
+		//Bound hmin and hmax
+		bamgopts->hmin=Max(bamgopts->hmin,BTh.MinimalHmin());
+		bamgopts->hmax=Min(bamgopts->hmax,BTh.MaximalHmax());
+
+		//Generate initial metric
+		if (bamgopts->metric){
+			if (verbosity>1) _printf_("   Processing Metric...\n");
+			BTh.ReadMetric(bamgopts);
+		}
+		else { 
+			if (verbosity>1) _printf_("   Generating initial Metric...\n");
+			Metric Mhmax(bamgopts->hmax);
+			for (int iv=0;iv<BTh.nbv;iv++) BTh[iv].m = Mhmax;
+		}
+
+		//use present fields to generate metric if present
+		if (bamgopts->field){
+			if (verbosity>1) _printf_("   Merge metric with field provided...\n");
+			BTh.AddMetric(bamgopts);
+		}
+
+		// change using hVertices if provided
+		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==BTh.nbv){
+			if (verbosity>1) _printf_("   Merging Metric with hVertices...\n");
+			for (i=0;i<BTh.nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
+					BTh[i].m=Metric((float)bamgopts->hVertices[i]);
+				}
+			}
+		}
+
+		// change using hminVertices if provided
+		if (bamgopts->hminVertices){
+			if (verbosity>1) _printf_("   Merging Metric with hminVertices...\n");
+			for (i=0;i<BTh.nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hminVertices[i])){
+					Metric M=BTh.vertices[i].m;
+					EigenMetric Vp(M/coef);
+					Vp.Minh(bamgopts->hminVertices[i]);
+					BTh.vertices[i].m=Vp;
+				}
+			}
+		}
+
+		// change using hmaxVertices if provided
+		if (bamgopts->hmaxVertices){
+			if (verbosity>1) _printf_("   Merging Metric with hmaxVertices...\n");
+			for (i=0;i<BTh.nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hmaxVertices[i])){
+					Metric M=BTh.vertices[i].m;
+					EigenMetric Vp(M/coef);
+					Vp.Maxh(bamgopts->hmaxVertices[i]);
+					BTh.vertices[i].m=Vp;
+				}
+			}
+		}
+
+		//Add geometry metric if provided
+		if(bamgopts->geometricalmetric) BTh.AddGeometryMetric(bamgopts);
+
+		//Smoothe metric
+		BTh.SmoothMetric(bamgopts->gradation);
+
+		//Control element subdivision
+		BTh.MaxSubDivision(bamgopts->maxsubdiv);
+
+		//Bound anisotropy
+		BTh.BoundAnisotropy(bamgopts->anisomax,hminaniso);
+
+		//Build new mesh
+		if (verbosity>1) _printf_("   Generating Mesh...\n");
+		Thr=&BTh,Thb=0;
+		Mesh & Th( *(0 ?  new Mesh(*Thr,&Thr->Gh,Thb,maxnbv) :  new Mesh(maxnbv,BTh,bamgopts,bamgopts->KeepVertices)));
+		if (Thr != &BTh) delete Thr;
+
+		//Make quadrangle if requested
+		if(costheta<=1.0) Th.MakeQuadrangles(costheta);
+		//if () Th.SplitElement(2);
+
+		//Split corners if requested
+		if(bamgopts->splitcorners) Th.SplitInternalEdgeWithBorderVertices();
+
+		//Renumber by subdomain
+		Th.TrianglesRenumberBySubDomain();
+
+		//Smooth vertices
+		if(nbsmooth>0) Th.SmoothingVertex(nbsmooth,bamgopts->omega);
+
+		//display info
+		if(verbosity>0) {
+			if (Th.nbt-Th.nbtout-Th.nbq*2){
+				_printf_("   new number of triangles = " << (Th.nbt-Th.nbtout-Th.nbq*2) << "\n");
+			}
+			if (Th.nbq ){
+				_printf_("   new number of quads = " << Th.nbq << "\n");
+			}
+		}
+
+		//Build output
+		if (verbosity>1) _printf_("   Write Mesh...\n");
+		Th.WriteMesh(bamgmesh_out,bamgopts);
+		if (verbosity>1) _printf_("   Write Geometry...\n");
+		Th.Gh.WriteGeometry(bamggeom_out,bamgopts);
+		if (verbosity>1) _printf_("   Write Metric...\n");
+		BTh.WriteMetric(bamgopts);
+
+		/*clean up*/
+		delete &Th;
+		//delete &BTh;
+		/*}}}*/
+	}
+
+	/*No error return*/
+	if (verbosity>1) _printf_("   Exiting Bamg.\n");
+	return noerr;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Bamgx/Bamgx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  Bamgx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGX_H
+#define _BAMGX_H
+
+#include "../../bamg/bamgobjects.h"
+
+/* local prototypes: */
+int     Bamgx(BamgMesh* bamgmesh_out,BamgGeom* bamggeom_out,BamgMesh* bamgmesh_in,BamgGeom* bamggeom_in,BamgOpts* bamgopts);
+
+#endif  /* _BAMGX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.cpp	(revision 18231)
@@ -0,0 +1,184 @@
+/* This software was developed by Bruce Hendrickson and Robert Leland   *
+ * at Sandia National Laboratories under US Department of Energy        *
+ * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+
+#include "./Chacox.h"
+
+int Chacox(
+	int       nvtxs,		/* number of vertices in graph */
+	int      *start,		/* start of edge list for each vertex */
+	int      *adjacency,	/* edge list data */
+	int      *vwgts,		/* weights for all vertices */
+	float    *ewgts,		/* weights for all edges */
+	float    *x,
+	float    *y,
+	float    *z,			/* coordinates for inertial method */
+	short    *assignment,	/* set number of each vtx (length nvtxs+1) */
+	double   options[10],	/* architecture and partitioning options */
+	int      *nparts,		/* number of parts options */
+	double   *goal			/* desired set sizes */
+)
+{
+	#ifdef _HAVE_CHACO_ //only works if Chaco library has been compiled in.
+
+	extern int     Using_Main;                   /* is main routine being called?                */
+	extern char   *PARAMS_FILENAME;              /* name of file with parameter updates          */
+	extern double  EIGEN_TOLERANCE;              /* tolerance for eigen calculations             */
+	extern int     OUTPUT_ASSIGN;                /* whether to write assignment to file          */
+	extern int     DEBUG_MEMORY;                 /* debug memory allocation and freeing?         */
+	extern int     DEBUG_TRACE;                  /* trace main execution path                    */
+	extern int     DEBUG_PARAMS;                 /* debug flag for reading parameters            */
+	extern long    RANDOM_SEED;                  /* seed for random number generators            */
+	extern int     ECHO;                         /* controls amount of output                    */
+	extern int     PROMPT;                       /* prompt for input or not?                     */
+	extern int     PRINT_HEADERS;                /* print lines for output sections?             */
+	extern int     MATCH_TYPE;                   /* matching routine to call                     */
+	extern double  input_time;                   /* times data file input                        */
+	extern double  start_time;                   /* time partitioning starts                     */
+	FILE          *params_file;                  /* file with parameter value updates            */
+	int            global_method;                /* global partitioning method                   */
+	int            local_method;                 /* local partitioning method                    */
+	double         eigtol;                       /* tolerance in eigenvector calculation         */
+	int            ndims;                        /* dimension of recursive partitioning          */
+	int            architecture;                 /* 0 => hypercube, d => d-dimensional mesh      */
+	int            ndims_tot;                    /* total number of cube dimensions to divide    */
+	int            mesh_dims[3];                 /* dimensions of mesh of processors             */
+	long           seed;                         /* for random graph mutations                   */
+	int            rqi_flag;                     /* use RQI/Symmlq eigensolver?                  */
+	int            vmax;                         /* if so, how many vertices to coarsen down to? */
+	char           outassignname[NAME_LENGTH];   /* assignment output file name                  */
+	char           outfilename[NAME_LENGTH];     /* name of output file                          */
+	char          *outassignptr;                 /* name or null pointer for output assignment   */
+	char          *outfileptr;                   /* name or null pointer for output file         */
+	int            nprocs;                       /* number of processors being divided into      */
+	double         time;                         /* timing marker                                */
+	int            flag;                         /* return code from input routines              */
+	double        *smalloc();                    /* safe version of malloc                       */
+	//double       seconds();                    /* returns elapsed time in seconds              */
+	/*int sfree(), interface(), affirm();
+	void input_queries()  , smalloc_stats(), read_params(), clear_timing();  */
+
+	int i,tvwgt;
+	double tgoal;
+
+	if (DEBUG_TRACE > 0) {
+		_printf_("<Entering main>\n");
+	}
+
+	if (PRINT_HEADERS) {
+		_printf_("\n                    Chaco 2.0\n");
+		_printf_("          Sandia National Laboratories\n\n");
+	}
+
+	Using_Main = TRUE;
+	params_file = fopen(PARAMS_FILENAME, "r");
+	if (params_file == NULL && DEBUG_PARAMS > 1) {
+		printf("Parameter file `%s' not found; using default parameters.\n",PARAMS_FILENAME);
+	}
+
+	start_time = time = chaco_seconds();
+
+	read_params(params_file);
+
+	flag = input_parse(outassignname, outfilename,
+			  &architecture, &ndims_tot, mesh_dims,
+			  &global_method, &local_method, &rqi_flag, &vmax, &ndims, &nprocs,
+			  options, nparts);
+	if (flag)
+		return(flag);
+
+	if (OUTPUT_ASSIGN > 0)
+		outassignptr = outassignname;
+	else
+		outassignptr = NULL;
+
+	if (ECHO < 0)
+		outfileptr = outfilename;
+	else
+		outfileptr = NULL;
+
+	if ((int)options[OPT_VWGTS] && vwgts) {
+		printf("%s -- Applying weights for %d vertices.\n",__FUNCT__,nvtxs);
+		tvwgt = 0;
+		for (i=0; i<nvtxs; i++)
+			tvwgt += vwgts[i];
+	}
+	else {
+		tvwgt = nvtxs;
+		if      ( (int)options[OPT_VWGTS] && !vwgts)
+			printf("%s -- Vertex weight flag=%d, but no vertex weights specified.\n",__FUNCT__,(int)options[OPT_VWGTS]);
+		else if (!(int)options[OPT_VWGTS] &&  vwgts)
+			printf("%s -- Vertex weight flag=%d, so specified vertex weights ignored.\n",__FUNCT__,(int)options[OPT_VWGTS]);
+	}
+
+	if ((int)options[OPT_EWGTS] && ewgts) {
+		printf("%s -- Applying weights for %d edges.\n",
+			   __FUNCT__,start[nvtxs]/2);
+	}
+	else {
+		if      ( (int)options[OPT_EWGTS] && !ewgts)
+			printf("%s -- Edge weight flag=%d, but no edge weights specified.\n",__FUNCT__,(int)options[OPT_EWGTS]);
+		else if (!(int)options[OPT_EWGTS] &&  ewgts)
+			printf("%s -- Edge weight flag=%d, so specified edge weights ignored.\n",__FUNCT__,(int)options[OPT_EWGTS]);
+	}
+
+    if (goal) {
+        printf("%s -- Applying goals for %d sets.\n",
+               __FUNCT__,nprocs);
+        tgoal = 0.;
+        for (i=0; i<nprocs; i++)
+            tgoal += goal[i];
+        for (i=0; i<nprocs; i++)
+            goal[i] *= (double)tvwgt/tgoal;
+    }
+
+	input_time += chaco_seconds() - time;
+
+	if (options[OPT_EIGTOL] > 0)
+		eigtol = options[OPT_EIGTOL];
+	else
+		eigtol = EIGEN_TOLERANCE;
+	if ((int)options[OPT_SEED] > 0)
+		seed = (int)options[OPT_SEED];
+	else
+		seed = RANDOM_SEED;
+
+/*  Chaco numbers vertices from 1 and the Matlab sparse data structure
+	numbers rows from 0, so increment the row indices for each column. */
+
+	for (i=0; i<start[nvtxs]; adjacency[i++]++);
+
+	printf("\n%s -- Calling Chaco interface:\n\n",__FUNCT__);
+	flag = interface(nvtxs, start, adjacency,
+		  ((int)options[OPT_VWGTS] && vwgts ? vwgts : NULL),
+		  ((int)options[OPT_EWGTS] && ewgts ? ewgts : NULL),
+		  x, y, z,
+		  outassignptr, outfileptr,
+		  assignment,
+		  architecture, ndims_tot, mesh_dims, goal,
+		  global_method, local_method, rqi_flag, vmax, ndims,
+		  eigtol, seed);
+	printf("\n%s -- Chaco interface returning flag=%d.\n",__FUNCT__,flag);
+
+/*  Reset adjacency matrix in case calling function needs it.  */
+
+	for (i=0; i<start[nvtxs]; adjacency[i++]--);
+
+	if (DEBUG_MEMORY > 0) {
+		_printf_("\n");
+		smalloc_stats();
+	}
+
+	if (params_file != NULL)
+		fclose(params_file);
+
+	if (DEBUG_TRACE > 1) {
+		_printf_("<Leaving main>\n");
+	}
+
+	return(0);
+
+	#else //ifdef _HAVE_CHACO_
+	return (0);
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/Chacox.h	(revision 18231)
@@ -0,0 +1,45 @@
+/*!\file:  Chacoxx.h
+ * \brief header file for Chaco partitioner
+ */ 
+
+#ifndef _CHACOX_H
+#define _CHACOX_H
+
+#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>
+
+#ifdef _HAVE_CHACO_ //only works if dakota library has been compiled in.
+
+#include "chaco.h"
+
+#define    OPT_GLOBAL    0
+#define    OPT_LOCAL     1
+#define    OPT_VWGTS     2
+#define    OPT_EWGTS     3
+#define    OPT_ARCH      4
+#define    OPT_NDIMS     5
+#define    OPT_VMAX      6
+#define    OPT_RQI       7
+#define    OPT_EIGTOL    8
+#define    OPT_SEED      9
+
+#endif
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int Chacox( int nvtxs, int *start, int *adjacency,int *vwgts, float *ewgts, float *x, float *y, float *z, short *assignment, double  options[10], int *nparts, double *goal);
+int input_parse( char *outassignname, char *outfilename, int *architecture, int *ndims_tot, int mesh_dims[3], int *global_method, int *local_method, 
+		int *rqi_flag, int *vmax, int *ndims, int *nprocs, double options[10], int *nparts);
+double    chaco_seconds(void);
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Chacox"
+
+#endif  /* _CHACOX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/chaco_seconds.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/chaco_seconds.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/chaco_seconds.cpp	(revision 18231)
@@ -0,0 +1,36 @@
+/*This is needed, because the chaco library defines a "C" function seconds that conflicts with the Metis version.: */
+
+#ifdef _INTEL_WIN_
+#include   <time.h>
+#else
+#include   <sys/time.h>
+#include   <sys/resource.h>
+#endif
+
+double chaco_seconds(void){
+
+	double    curtime;
+
+#ifdef RUSAGE_SELF
+
+/* This timer is faster and more robust (if it exists). */
+    struct rusage rusage;
+    /*int getrusage(); commenting this out. not sure why it's there anymore
+	 *as it clobbers the prototype int getrusag(int target,rusage* results) which 
+	 *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) +
+	    1.0e-6 * (rusage.ru_utime.tv_usec + rusage.ru_stime.tv_usec));
+
+#else
+
+/* ANSI timer, but lower resolution & wraps around after ~36 minutes. */
+
+    curtime = clock()/((double) CLOCKS_PER_SEC);
+
+#endif
+
+    return (curtime);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/input_parse.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/input_parse.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/input_parse.cpp	(revision 18231)
@@ -0,0 +1,258 @@
+/*!\file:  input_parse.cpp
+ * \brief  needed by Chacox.cpp
+ */ 
+
+#include "./Chacox.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "input_parse"
+
+int      input_parse(
+	char     *outassignname,	/* name of assignment output file */
+	char     *outfilename,		/* name of file for outputing run results */
+	int      *architecture,		/* 0=> hypercube, d=> d-dimensional mesh */
+	int      *ndims_tot,		/* target number of hypercube dimensions */
+	int       mesh_dims[3],		/* mesh dimensions */
+	int      *global_method,	/* what global partitioning strategy to use? */
+	int      *local_method,		/* what local refinement strategy to use? */
+	int      *rqi_flag,		/* should I use multilevel eigensolver? */
+	int      *vmax,			/* if so, how far should I coarsen? */
+	int      *ndims,		/* number of divisions at each stage */
+	int      *nprocs,		/* number of processors being divided into */
+	double   options[10],	/* architecture and partitioning options */
+	int      *nparts		/* number of parts options */
+)
+{
+
+	#ifdef _HAVE_CHACO_ //only works if Chaco library has been compiled in.
+
+	extern int SEQUENCE;	/* sequence instead of partition graph? */
+	extern int ARCHITECTURE;	/* 0=> hypercube, d=> d-dimensional mesh */
+	extern int OUTPUT_ASSIGN;	/* write assignments to file? */
+	extern int ECHO;		/* copy input to screen? results to file? */
+	extern int DEBUG_TRACE;	/* trace main execution path */
+	extern int PROMPT;		/* prompt for input? */
+	extern int MATCH_TYPE;      /* max-matching routine to call */
+	int       eigensolver;	/* which kind of eigensolver to use */
+
+	if (DEBUG_TRACE > 0) {
+		_printf_("<Entering input_parse>\n");
+	}
+
+	if (PROMPT) {
+		_printf_("Parallel machine architecture:\n");
+		_printf_("  (0) Hypercube\n");
+		_printf_("  (1) One-dimensional mesh\n");
+		_printf_("  (2) Two-dimensional mesh\n");
+		_printf_("  (3) Three-dimensional mesh\n");
+	}
+	*architecture = (int)options[OPT_ARCH];
+	if (*architecture < 0 || *architecture > 3) {
+		printf("%s -- Architecture %d must be between 0 and 3.\n",__FUNCT__,*architecture);
+		return(-1);
+	}
+
+	/* Name output assignment file. */
+	if (PROMPT)
+		_printf_("Assignment output file: ");
+	outassignname = NULL;
+
+	/* Name output results file. */
+	if (PROMPT)
+		_printf_("File name for saving run results: ");
+	outfilename = NULL;
+
+	/* Initialize the method flags */
+	*rqi_flag = 0;
+	*global_method = 0;
+
+	/* Get global method, if any. */
+	if (SEQUENCE) {
+		*global_method = 2;
+	}
+	else {
+		if (PROMPT) {
+			_printf_("Global partitioning method:\n");
+			_printf_("  (1) Multilevel-KL\n");
+			_printf_("  (2) Spectral\n");
+			_printf_("  (3) Inertial\n");
+			_printf_("  (4) Linear\n");
+			_printf_("  (5) Random\n");
+			_printf_("  (6) Scattered\n");
+			_printf_("  (7) Read-from-file\n");
+		}
+		*global_method = (int)options[OPT_GLOBAL];
+		if (*global_method < 1 || *global_method > 7) {
+			printf("%s -- Global method %d must be between 1 and 7.\n",__FUNCT__,*global_method);
+			return(-1);
+		}
+	}
+
+	if (*global_method == 7) {	/* Name and open input assignment file. */
+		if (PROMPT)
+			_printf_("Assignment input file: ");
+	}
+
+	else if (*global_method == 3) {
+		if (PROMPT)
+			_printf_("Geometry input file name: ");
+	}
+
+	else if (*global_method == 2) {
+		if (PROMPT) {
+			_printf_("Eigensolver:\n");
+			_printf_("  (1) Multilevel RQI/Symmlq\n");
+			_printf_("  (2) Lanczos\n"); 
+		}
+		eigensolver = (int)options[OPT_RQI];
+		if (eigensolver < 0 || eigensolver > 2) {
+			printf("%s -- RQI/Symmlq flag %d must be between 0 and 2.\n",__FUNCT__,eigensolver);
+			return(-1);
+		}
+		if (eigensolver == 1) {
+			if (MATCH_TYPE == 5) {	/* geometric matching */
+				if (PROMPT)
+					_printf_("Geometry input file name: ");
+			}
+			*rqi_flag = 1;
+			if (PROMPT)
+				_printf_("Number of vertices to coarsen down to: ");
+			*vmax = (int)options[OPT_VMAX];
+			if (*vmax <= 0) {
+				printf("%s -- Vmax %d must be greater then 0.\n",__FUNCT__,*vmax);
+				return(-1);
+			}
+		}
+		else if (eigensolver == 0 || eigensolver == 2) {
+			*rqi_flag = 0;
+		}
+	}
+
+	else if (*global_method == 1) {
+		if (MATCH_TYPE == 5) {		/* geometric matching */
+			if (PROMPT)
+				_printf_("Geometry input file name: ");
+		}
+		if (PROMPT)
+			_printf_("Number of vertices to coarsen down to: ");
+		*vmax = (int)options[OPT_VMAX];
+		if (*vmax <= 0) {
+			printf("%s -- Vmax %d must be greater then 0.\n",__FUNCT__,*vmax);
+			return(-1);
+		}
+	}
+
+	if (SEQUENCE) {
+		*local_method = 2;
+		if (*architecture == 0) {
+			*ndims_tot = 1;
+		}
+		else if (*architecture > 0) {
+			mesh_dims[0] = 2;
+			mesh_dims[1] = mesh_dims[2] = 1;
+		}
+		*ndims = 1;
+		goto End_Label;
+	}
+
+	/* Get local method, if any */
+	*local_method = 0;
+	if (*global_method == 1)
+		*local_method = 1;
+	else {
+		if (PROMPT) {
+			_printf_("Local refinement method:\n");
+			_printf_("  (1) Kernighan-Lin\n");
+			_printf_("  (2) None\n");
+		}
+		*local_method = (int)options[OPT_LOCAL];
+		if (*local_method < 1 || *local_method > 2) {
+			printf("%s -- Local method %d must be 1 and 2.\n",__FUNCT__,*local_method);
+			return(-1);
+		}
+	}
+
+	/* Now learn about the parallel architecture. */
+	if (*architecture == 0) {
+	/* Get total number of hypercube dimensions in which to partition. */
+		*ndims_tot = 0;
+		if (PROMPT)
+			_printf_("Total number of target hypercube dimensions: ");
+		*ndims_tot = nparts[0];
+		if (*ndims_tot < 1) {
+			_printf_(" Number of divisions must be at least 1\n");
+			printf("%s -- Number of divisions %d must be at least 1.\n",
+				   __FUNCT__,nparts[0]);
+			return(-1);
+		}
+		*nprocs = 1 << (*ndims_tot);
+	}
+
+	else {			/* Get dimensions of mesh. */
+		mesh_dims[1] = mesh_dims[2] = 1;
+		if (*architecture == 2) {
+			if (PROMPT)
+				_printf_("X and Y extent of of 2-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			mesh_dims[1] = nparts[1];
+		}
+		else if (*architecture == 3) {
+			if (PROMPT)
+				_printf_("X, Y and Z extent of 3-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			mesh_dims[1] = nparts[1];
+			mesh_dims[2] = nparts[2];
+		}
+		else {			/* Anything else => 1-D mesh */
+			if (PROMPT)
+				_printf_("Size of 1-D mesh: ");
+			mesh_dims[0] = nparts[0];
+			*architecture = 1;
+		}
+		*nprocs = mesh_dims[0] * mesh_dims[1] * mesh_dims[2];
+	}
+
+	/* Get number of dimensions in which to partition at each level. */
+	*ndims = 0;
+	if (*nprocs <= 3) {
+		*ndims = 1;
+	}
+	else if (*nprocs <= 7) {
+		if (PROMPT) {
+			_printf_("Partitioning dimension: \n");
+			_printf_("  (1) Bisection\n");
+			_printf_("  (2) Quadrisection\n");
+		}
+		*ndims = (int)options[OPT_NDIMS];
+		if (*ndims < 1 || *ndims > 2) {
+			printf("%s -- Ndims %d must be 1 or 2 for %d processors.\n",__FUNCT__,*ndims,*nprocs);
+			return(-1);
+		}
+	}
+	else {
+		if (PROMPT) {
+			_printf_("Partitioning dimension: \n");
+			_printf_("  (1) Bisection\n");
+			_printf_("  (2) Quadrisection\n");
+			_printf_("  (3) Octasection\n");
+		}
+		*ndims = (int)options[OPT_NDIMS];
+		if (*ndims < 1 || *ndims > 3) {
+			printf("%s -- Ndims %d must be between 1 and 3 for %d processors.\n",__FUNCT__,*ndims,*nprocs);
+			return(-1);
+		}
+	}
+End_Label: 
+
+	if (*global_method == 1 || *rqi_flag) {
+		if (*vmax < 2 * (1 << *ndims)) {
+			*vmax = 2 * (1 << *ndims);
+		}
+	}
+
+	return(0);
+
+	#else //#ifdef _HAVE_CHACO_ 
+	return(0);
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/user_params.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/user_params.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Chacox/user_params.cpp	(revision 18231)
@@ -0,0 +1,144 @@
+/* This software was developed by Bruce Hendrickson and Robert Leland   *
+ * at Sandia National Laboratories under US Department of Energy        *
+ * contract DE-AC04-76DP00789 and is copyrighted by Sandia Corporation. */
+
+/* Modified by John Gilbert 25 Aug 1995 for Matlab mex-file interface   */
+/* Modified by Tim Davis, July 6, 1998, for Matlab 5.1 interface, and */
+/* a more picky compiler (cc) that complains about duplicate global */
+/* declarations. */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_CHACO_ //only works if dakota library has been compiled in.
+
+#include "params.h"
+
+#define  TRUE  1
+#define  FALSE 0
+
+/* Input and ouput control parameters */
+
+int       CHECK_INPUT = TRUE;	 /* Check input for consistency? (TRUE/FALSE) */
+int       ECHO = 0;		 /* Print input/param options? to file? (-2..2) */
+int       OUTPUT_METRICS = 0;	 /* Controls displaying of results (-2..2) */
+int       OUTPUT_TIME = 0;	 /* At what level to display timings (0..2) */
+int       OUTPUT_ASSIGN = FALSE; /* Write assignments to file? (TRUE/FALSE) */
+int       OUT_ASSIGN_INV = FALSE;/* If so, use inverse form? (TRUE/FALSE) */
+int       IN_ASSIGN_INV = FALSE; /* Input file in inverse form? (TRUE/FALSE) */
+int       PROMPT = FALSE;	 /* Prompt for input? (TRUE/FALSE) */
+int       PRINT_HEADERS = FALSE; /* Print pretty output headers (TRUE/FALSE) */
+
+/* Eigenvector calculation parameters */
+
+int       LANCZOS_TYPE = 3;	/* type of Lanczos to use */
+				/* 1 => full orthog, 2 => full inverse operator */
+				/* 3 =>  selective orthogonalization */
+double    EIGEN_TOLERANCE = 1e-3;	/* Numerical eigen-tolerance */
+double    SRESTOL = -1.;		/* Rel resid tol on T evec; autoset if <= 0 */
+int       LANCZOS_SO_INTERVAL = 10;	/* Itns. between SO orthog checks; set >= 2 */
+int       LANCZOS_MAXITNS = -1;		/* Max Lanczos its; autoset if <= 0 */
+double    BISECTION_SAFETY = 10;	/* Divides Lanczos bisection tol */
+int       LANCZOS_CONVERGENCE_MODE = 0;	/* Lanczos convergence test type: */
+					/* 0=> residual,  1=> partition */
+int       RQI_CONVERGENCE_MODE = 1;	/* RQI convergence test type: */
+					/* 0=> residual,  1=> partition */
+int       LANCZOS_SO_PRECISION = 2;	/* 2 => double Lanczos, 1 => float */
+int       WARNING_EVECS = 2;	/* Warnings in eigenvector generation (0..3) */
+double    WARNING_ORTHTOL = 2;	/* Warning if Ares and bjitol have this ratio */
+double    WARNING_MISTOL = 100;	/* Warning if Ares and bjitol have this ratio */
+int       LANCZOS_TIME = FALSE;	/* Detailed Lanczos times? (TRUE/FALSE) */
+int       TIME_KERNELS = FALSE;	/* Time numerical kernels? (TRUE/FALSE) */
+
+/* Other parameters for spectral methods */
+
+int       MAKE_CONNECTED = TRUE;/* Connect graph if using spectral method? */
+int       PERTURB = TRUE;	/* Randomly perturb matrix in spectral method? */
+int       NPERTURB = 2;		/* If so, how many edges to modify? */
+double    PERTURB_MAX = 3.0e-3;	/* Largest value for perturbation */
+int       MAPPING_TYPE = 1;	/* How to map from eigenvectors to partition */
+				/* 0 => cut at origin, 1 => min-cost assign */
+int       COARSE_NLEVEL_RQI = 2;/* # levels between RQI calls in uncoarsening */
+int       OPT3D_NTRIES = 5;	/* # local opts to look for global min in opt3d */
+
+/* Kernighan--Lin/Fiduccia--Mattheyses parameters */
+
+int       KL_METRIC = 2;	/* KL interset cost: 1=>cuts, 2=>hops */
+int       KL_RANDOM = TRUE;	/* Use randomness in Kernighan-Lin? (TRUE/FALSE)*/
+int       KL_BAD_MOVES = 20;	/* Number of unhelpful moves in a row allowed */
+int       KL_NTRIES_BAD = 1;	/* # unhelpful passes before quitting KL */
+int       KL_UNDO_LIST = TRUE;	/* Only resort changed vtxs? (TRUE/FALSE) */
+double    KL_IMBALANCE = 0.0;	/* Fractional imbalance allowed by KL */
+
+/* Coarsening parameters */
+
+double    COARSEN_RATIO_MIN = .7;  /* Min vtx reduction each coarsen stage */
+int       COARSE_NLEVEL_KL = 2;	   /* # levels between KL calls in uncoarsening */
+int       MATCH_TYPE = 1;	   /* Type of contraction matching (1..4) */
+int       HEAVY_MATCH = FALSE;	   /* Encourage heavy match edges? (TRUE/FALSE) */
+int       COARSE_KL_BOTTOM = TRUE; /* Force KL at lowest level (TRUE/FALSE) */
+int       COARSEN_VWGTS = TRUE;	   /* Sum vtx weights in coarsening? (TRUE/FALSE) */
+int       COARSEN_EWGTS = TRUE;	   /* Sum edge weights in coarsening? (TRUE/FALSE) */
+int       KL_ONLY_BNDY = TRUE;	   /* Start moving vtxs on boundary? (TRUE/FALSE) */
+
+/* Parameters for post-processing options */
+
+int       REFINE_PARTITION = FALSE;	/* Postprocess to improve cuts? */
+int       INTERNAL_VERTICES = FALSE;	/* ... to up internal vtxs? (TRUE/FALSE) */
+int       REFINE_MAP = FALSE;		/* ... to reduce hops? (TRUE/FALSE) */
+
+/* Architecture and simulator parameters */
+
+int       ARCHITECTURE = 0;	/* 0=> hypercube, d=> d-dimensional mesh (0..3)*/
+
+/* Modified by Tim Davis:  remove duplicate definitions */
+#ifdef DUPLICATE_DEFINITIONS_REMOVED
+int       SIMULATOR = 0;	/* Run simulator? In what mode? */
+int       SIMULATION_ITNS = 1;	/* # iterations simulator is to imitate. */
+int       PERCENTAGE_OUTPUT = FALSE;	/* Output in percent? (TRUE/FALSE) */
+double    CUT_COST = 0.0;	/* Communication cost of a cut-edge. */
+double    HOP_COST = 0.0;	/* Communication cost of a hop. */
+double    BDY_COST = 0.0;	/* Cost associated with boundary vertices.  */
+double    BDY_HOP_COST = 0.0;	/* Cost associated with boundary hops. */
+double    STARTUP_COST = 0.0;	/* Communication cost of a message startup. */
+	/* Note: nCUBE2 startup: 112e-6, per byte: 4.6e-6, buffering 5.6e-6 */
+	/* Intel Paragon startup: 70e-6, per byte: 5.3e-8 */
+#endif
+
+/* Miscellaneous parameters */
+
+int       TERM_PROP = FALSE;	/* Invoke terminal propagation? (TRUE/FALSE) */
+double    CUT_TO_HOP_COST = 1;	/* ..if so, relative importance of cuts/hops */
+int       SEQUENCE = FALSE;	/* Only do spectral ordering? (TRUE/FALSE) */
+char      SEQ_FILENAME[NAME_LENGTH] = "Sequence.out";	/* If so, file name */
+long      RANDOM_SEED = 7654321L;	/* Seed for random number generator */
+int       NSQRTS = 1000;	/* # square roots to precompute if coarsening */
+int       MAKE_VWGTS = FALSE;	/* Make vtx weights degrees+1? (TRUE/FALSE) */
+int       FREE_GRAPH = FALSE;	/* Free input graph data? (TRUE/FALSE) */
+char     *PARAMS_FILENAME = "User_Params";	/* File of parameter changes */
+
+/* Parameters that control debugging output */
+
+int       DEBUG_EVECS = 0;	/* Debug flag for eigenvector generation (0..5) */
+int       DEBUG_KL = 0;		/* Debug flag for Kernighan-Lin (0..3) */
+int       DEBUG_INERTIAL = 0;	/* Debug flag for inertial method (0..1) */
+int       DEBUG_CONNECTED = 0;	/* Debug flag for connected components (0..1) */
+int       DEBUG_PERTURB = 0;	/* Debug flag for matrix perturbation (0..1) */
+int       DEBUG_ASSIGN = 0;	/* Debug flag for assignment to sets (0..1) */
+int       DEBUG_OPTIMIZE = 0;	/* Debug flag for optimization/rotation (0..2) */
+int       DEBUG_BPMATCH = 0;	/* Debug flag for bipartite matching code (0..2) */
+int       DEBUG_COARSEN = 0;	/* Debug flag for coarsening/uncoarsening (0..1) */
+int       DEBUG_MEMORY = 0;	/* Debug flag for smalloc/sfree (0..3) */
+int       DEBUG_INPUT = 0;	/* Debug flag for having read input files (0..1) */
+int       DEBUG_PARAMS = 1;	/* Debug flag for reading parameter file (0..2) */
+int       DEBUG_INTERNAL = 0;	/* Debug flag for internal vertices (0..2) */
+int       DEBUG_REFINE_PART = 0;/* Debug flag for refine partition (0..1) */
+int       DEBUG_REFINE_MAP = 0;	/* Debug flag for refining mapping (0..1) */
+int       DEBUG_SIMULATOR = 0;	/* Debug flag for comm simulator (0..2) */
+int       DEBUG_TRACE = 0;	/* Trace main execution path (0..2) */
+int       DEBUG_MACH_PARAMS = 0;/* Print computed machine params? (0..1) */
+
+#endif //ifdef _HAVE_CHACO_ 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 18231)
@@ -0,0 +1,42 @@
+/*!\file ConfigureObjectsx
+ * \brief: configure objects in elements and loads to link in with nodes
+ */
+
+#include "./ConfigureObjectsx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+
+int	ConfigureObjectsx( Elements* elements, Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	/*Intermediary*/
+	int       i;
+	int       noerr = 1;
+	int       configuration_type;
+	Element  *element            = NULL;
+	Load     *load               = NULL;
+	Material *material           = NULL;
+
+	/*Get analysis type: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	if(VerboseMProcessor()) _printf0_("      Configuring elements...\n");
+	for(i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->Configure(elements,loads,nodes,vertices,materials,parameters);
+	}
+	if(VerboseMProcessor()) _printf0_("      Configuring loads...\n");
+	for(i=0;i<loads->Size();i++){
+		load=(Load*)loads->GetObjectByOffset(i);
+		if (load->InAnalysis(configuration_type)){
+			load->Configure(elements,loads,nodes,vertices,materials,parameters);
+		}
+	}
+	if(VerboseMProcessor()) _printf0_("      Configuring materials...\n");
+	for(i=0;i<materials->Size();i++){
+		material=(Material*)materials->GetObjectByOffset(i);
+		material->Configure(elements);
+	}
+	return noerr;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  ConfigureObjectsx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _CONFIGUREOBJECTSX_H
+#define _CONFIGUREOBJECTSX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int ConfigureObjectsx( Elements* elements, Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials, Parameters* parameters);
+
+#endif  /* _CONFIGUREOBJECTSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 18231)
@@ -0,0 +1,23 @@
+/*!\file:  ConstraintsStateLocal.h
+ * \brief local header files
+ */ 
+
+#ifndef _CONSTRAINTSSTATELOCAL_H
+#define _CONSTRAINTSSTATELOCAL_H
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../classes/classes.h"
+
+/*rifts module: */
+void RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int analysis_type);
+void RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int analysis_type);
+int  RiftIsFrozen(Loads* loads,int analysis_type);
+void RiftFreezeConstraints(Loads* loads,int analysis_type);
+
+#endif  /* _CONSTRAINTSSTATEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\file ConstraintsStatex
+ * \brief: set up penalty constraints on loads
+ */
+
+#include "./ConstraintsStatex.h"
+#include "./ConstraintsStateLocal.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints,FemModel* femmodel){
+
+	/*output: */
+	int converged                     = 1;
+	int num_unstable_constraints      = 0;
+	int min_mechanical_constraints    = 0;
+	int  unstable                     = 0;
+	int  sum_num_unstable_constraints = 0;
+	int analysis_type;
+
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Constraining penalties\n");
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Rift penalties first*/
+	if(RiftIsPresent(femmodel->loads,analysis_type)){
+		RiftConstraintsState(&converged,&num_unstable_constraints,femmodel->loads,min_mechanical_constraints,analysis_type);
+	}
+
+	/*Deal with pengrid*/
+	for(int i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(analysis_type)){
+			if(load->ObjectEnum()==PengridEnum){
+				Pengrid* pengrid=(Pengrid*)load;
+				pengrid->ConstraintActivate(&unstable);
+				num_unstable_constraints += unstable;
+			}
+		}
+	}
+	ISSM_MPI_Reduce(&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	num_unstable_constraints=sum_num_unstable_constraints;
+
+	/*Have we converged? : */
+	if(num_unstable_constraints) converged=0;
+
+	/*Assign output pointers: */
+	*pconverged                = converged;
+	*pnum_unstable_constraints = num_unstable_constraints;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  ConstraintsStatex.h
+ * \brief header file for penalty constraints module
+ */ 
+
+#ifndef _CONSTRAINTSSTATEX_H
+#define _CONSTRAINTSSTATEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int  RiftIsPresent(Loads* loads,int analysis_type);
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints,FemModel* femmodel);
+
+#endif  /* _CONSTRAINTSSTATEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 18231)
@@ -0,0 +1,160 @@
+/*!\file RiftConstraintsState.cpp
+ * \brief: manage penalties for rifts 
+ */
+
+#include "./ConstraintsStateLocal.h"
+#include "../../shared/shared.h"
+
+#define _ZIGZAGCOUNTER_
+
+/*current module: */
+/*RiftIsPresent(Loads* loads,int configuration_type){{{*/
+int RiftIsPresent(Loads* loads,int configuration_type){
+
+	int i;
+
+	int found=0;
+	int mpi_found=0;
+
+	/*go though loads, and figure out if one of the loads is a Riftfront: */
+	for (i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		if(load->InAnalysis(configuration_type)){
+			if(RiftfrontEnum==loads->GetEnum(i)){
+				found=1;
+				break;
+			}
+		}
+	}
+
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	found=mpi_found;
+
+	return found;
+}
+/*}}}*/
+/*RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){{{*/
+void RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){
+
+	int num_unstable_constraints=0;
+	int converged=0;
+
+	RiftConstrain(&num_unstable_constraints,loads,configuration_type);
+	if(num_unstable_constraints==0)converged=1;
+
+	if(RiftIsFrozen(loads,configuration_type)){
+		converged=1;
+		num_unstable_constraints=0;
+	}
+	else if(num_unstable_constraints<=min_mechanical_constraints){
+		if(VerboseModule()) _printf0_("   freezing constraints\n");
+		RiftFreezeConstraints(loads,configuration_type);
+	}
+
+	/*Assign output pointers: */
+	*pconverged=converged;
+	*pnum_unstable_constraints=num_unstable_constraints;
+}
+/*}}}*/
+/*RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int configuration_type){{{*/
+void RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int configuration_type){
+
+	int			i;
+
+	/* generic object pointer: */
+	Riftfront* riftfront=NULL;
+	Load*      load=NULL;
+
+	int unstable;
+	int sum_num_unstable_constraints;
+	int num_unstable_constraints=0;	
+
+	/*Enforce constraints: */
+	for (i=0;i<loads->Size();i++){
+
+		if (RiftfrontEnum==loads->GetEnum(i)){
+
+			load=(Load*)loads->GetObjectByOffset(i);
+			if(load->InAnalysis(configuration_type)){
+
+				riftfront=(Riftfront*)load;
+
+				riftfront->Constrain(&unstable);
+
+				num_unstable_constraints+=unstable;
+			}
+		}
+	}
+
+	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	num_unstable_constraints=sum_num_unstable_constraints;
+
+	/*Assign output pointers: */
+	*pnum_unstable_constraints=num_unstable_constraints;
+
+}
+/*}}}*/
+/*RiftIsFrozen(Loads* loads,int configuration_type){{{*/
+int RiftIsFrozen(Loads* loads,int configuration_type){
+
+	int			i;
+
+	/* generic object pointer: */
+	Load*      load=NULL;
+	Riftfront* riftfront=NULL;
+	int found=0;
+	int mpi_found=0;
+
+	/*Enforce constraints: */
+	for (i=0;i<loads->Size();i++){
+
+		if (RiftfrontEnum==loads->GetEnum(i)){
+
+			load=(Load*)loads->GetObjectByOffset(i);
+			if(load->InAnalysis(configuration_type)){
+
+				riftfront=(Riftfront*)load;
+				if (riftfront->IsFrozen()){
+					found=1;
+					break;
+				}
+			}
+		}
+	}
+
+	/*Is there just one found? that would mean we have frozen! : */
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	found=mpi_found;
+
+	return found;
+}
+/*}}}*/
+/*RiftFreezeConstraints(Loads* loads,int configuration_type){{{*/
+void RiftFreezeConstraints(Loads* loads,int configuration_type){
+
+	int			i;
+
+	/* generic object pointer: */
+	Load*      load=NULL;
+	Riftfront* riftfront=NULL;
+
+	/*Enforce constraints: */
+	for (i=0;i<loads->Size();i++){
+
+		if (RiftfrontEnum==loads->GetEnum(i)){
+
+			load=(Load*)loads->GetObjectByOffset(i);
+			if(load->InAnalysis(configuration_type)){
+
+				riftfront=(Riftfront*)load;
+				riftfront->FreezeConstraints();
+			}
+
+		}
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 18231)
@@ -0,0 +1,49 @@
+/*! \file  ContourToMeshx.c
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ContourToMeshx.h"
+
+int ContourToMeshx(double** pin_nod,double** pin_elem, double* index, double* x, double* y,Contours* contours,char* interptype,int nel,int nods, int edgevalue) {
+
+	/*Contour:*/
+	double value;
+
+	/*output: */
+	double*  in_nod;
+	double*  in_elem;
+	in_nod   = xNewZeroInit<double>(nods);
+	in_elem  = xNewZeroInit<double>(nel);
+
+	/*initialize thread parameters: */
+	ContourToMeshxThreadStruct gate;
+	gate.contours  = contours;
+	gate.nods      = nods;
+	gate.edgevalue = edgevalue;
+	gate.in_nod    = in_nod;
+	gate.x         = x;
+	gate.y         = y;
+
+	/*launch the thread manager with ContourToMeshxt as a core: */
+	LaunchThread(ContourToMeshxt,(void*)&gate,_NUMTHREADS_);
+
+	/*Take care of the case where an element interpolation has been requested: */
+	if ((strcmp(interptype,"element")==0) || (strcmp(interptype,"element and node")==0)){
+		for(int n=0;n<nel;n++){
+			if ( (in_nod[ (int)*(index+3*n+0) -1] == 1) && (in_nod[ (int)*(index+3*n+1) -1] == 1) && (in_nod[ (int)*(index+3*n+2) -1] == 1) ){
+				value=1.; in_elem[n]=value;
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pin_nod=in_nod;
+	*pin_elem=in_elem;
+
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 18231)
@@ -0,0 +1,28 @@
+/*
+	ContourToMeshx.h
+*/
+
+#ifndef _CONTOURTOMESHX_H
+#define _CONTOURTOMESHX_H
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+
+/*threading: */
+typedef struct{
+
+	Contours *contours;
+	int       nods;
+	int       edgevalue;
+	double   *in_nod;
+	double   *x;
+	double   *y;
+
+} ContourToMeshxThreadStruct;
+
+/* local prototypes: */
+int ContourToMeshx(double** pin_nods,double** pin_elem, double* index, double* x, double* y,Contours* contours,char* interptype,int nel,int nods, int edgevalue);
+
+void* ContourToMeshxt(void* vContourToMeshxThreadStruct);
+
+#endif /* _CONTOURTOMESHX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 18231)
@@ -0,0 +1,44 @@
+/*!\file:  ContourToMeshxt.cpp
+ * \brief  "thread" core code for interpolating values from a structured grid.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ContourToMeshx.h"
+
+void* ContourToMeshxt(void* vpthread_handle){
+
+	/*gate variables :*/
+	ContourToMeshxThreadStruct *gate        = NULL;
+	pthread_handle             *handle      = NULL;
+	int  i,i1,i0;
+
+	/*recover handle and gate: */
+	handle          = (pthread_handle*)vpthread_handle;
+	gate            = (ContourToMeshxThreadStruct*)handle->gate;
+	int my_thread   = handle->id;
+	int num_threads = handle->num;
+
+	/*recover parameters :*/
+	Contours* contours  = gate->contours;
+	int       nods      = gate->nods;
+	int       edgevalue = gate->edgevalue;
+	double   *in_nod    = gate->in_nod;
+	double   *x         = gate->x;
+	double   *y         = gate->y;
+
+	/*distribute indices across threads :*/
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+
+	/*Loop through all contours: */
+	for (i=0;i<contours->Size();i++){
+		Contour<double>* contour=(Contour<double>*)contours->GetObjectByOffset(i);
+		IsInPoly(in_nod,contour->x,contour->y,contour->nods,x,y,i0,i1,edgevalue);
+	}
+
+	return NULL;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+/*! \file  ContourToNodesx.c
+ */
+
+#include "./ContourToNodesx.h"
+
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue){
+
+	int i;
+
+	/*Contour:*/
+	Contour<IssmPDouble>* contouri=NULL;
+	int      numnodes;
+	double*  xc=NULL;
+	double*  yc=NULL;
+
+	/*output: */
+	IssmPDouble* flags=NULL;
+	flags=xNew<IssmPDouble>(nods);
+
+	/*Loop through all contours: */
+	for (i=0;i<numcontours;i++){
+		contouri=*(contours+i);
+		numnodes=contouri->nods;
+		xc=contouri->x;
+		yc=contouri->y;
+		IsInPoly(flags,xc,yc,numnodes,x,y,0,nods,edgevalue);
+	}
+
+	/*Assign output pointers: */
+	*pflags=flags;
+	return 1;
+}
+
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contours* contours, int edgevalue){
+
+	/*output: */
+	IssmPDouble* flags=NULL;
+	flags=xNewZeroInit<IssmPDouble>(nods);
+
+	/*Loop through all contours: */
+	if(contours){
+		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);
+		}
+	}
+
+	/*Assign output pointers: */
+	*pflags=flags;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*
+	ContourToNodesx.h
+*/
+
+#ifndef _CONTOURTONODESX_H
+#define _CONTOURTONODESX_H
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue);
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contours* contours, int edgevalue);
+
+#endif /* _CONTOURTONODESX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file ControlInputSetGradientx
+ * \brief retrieve gradient from inputs in elements
+ */
+
+#include "./ControlInputSetGradientx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* gradient){
+
+	/*Intermediaries*/
+	int  num_controls;
+	int *control_type = NULL;
+
+	/*Retrieve some parameters*/
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<elements->Size();j++){
+			Element* element=(Element*)elements->GetObjectByOffset(j);
+			element->ControlInputSetGradient(gradient,control_type[i],i);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+
+}
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* gradient){
+
+	/*Serialize gradient*/
+	IssmDouble* serial_gradient=NULL;
+	serial_gradient=gradient->ToMPISerial();
+
+	ControlInputSetGradientx(elements,nodes,vertices, loads, materials, parameters,serial_gradient);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(serial_gradient);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  ControlInputSetGradientx.h
+ */ 
+
+#ifndef _CONTROLINPUTSSETGRADIENTX_H
+#define _CONTROLINPUTSSETGRADIENTX_H
+
+#include "../../classes/classes.h"
+
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* gradient);
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* gradient);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\file CreateJacobianMatrixx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./CreateJacobianMatrixx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../AllocateSystemMatricesx/AllocateSystemMatricesx.h"
+
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,FemModel* femmodel,IssmDouble kmax){
+
+	int      i;
+	int      configuration_type,analysisenum;
+	Element *element = NULL;
+	Load    *load    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+
+	/*Checks*/
+	_assert_(femmodel && femmodel->nodes && femmodel->elements);
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+
+	/*Initialize Jacobian Matrix*/
+	AllocateSystemMatricesx(&Jff,NULL,NULL,NULL,femmodel);
+
+	/*Create and assemble matrix*/
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ElementMatrix* Je = analysis->CreateJacobianMatrix(element);
+		if(Je) Je->AddToGlobal(Jff);
+		delete Je;
+	}
+	for (i=0;i<femmodel->loads->Size();i++){
+		load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(configuration_type)) load->CreateJacobianMatrix(Jff);
+		if(load->InAnalysis(configuration_type)) load->PenaltyCreateJacobianMatrix(Jff,kmax);
+	}
+	Jff->Assemble();
+
+	/*Assign output pointer*/
+	delete analysis;
+	*pJff=Jff;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  CreateJacobianMatrixx.h
+*/ 
+
+#ifndef _CREATEJACOBIANMATRIXX_H
+#define _CREATEJACOBIANMATRIXX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,FemModel* femmodel,IssmDouble kmax);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 18231)
@@ -0,0 +1,45 @@
+/*!\file CreateNodalConstraintsx
+ * \brief: establish degrees of freedom for all nodes, and return partitioning vector. Do only once.
+ */
+
+#include "./CreateNodalConstraintsx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type){
+
+	bool  oldalloc  = false;
+
+	/*output: */
+	Vector<IssmDouble>* ys=NULL;
+	int ssize;
+	int slocalsize;
+
+	if(VerboseModule()) _printf0_("   Create nodal constraints\n");
+
+	/*figure out how many dofs we have: */
+	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+	slocalsize = nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
+
+	/*allocate:*/
+	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(int i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		if (node->InAnalysis(configuration_type)){
+			node->CreateNodalConstraints(ys);
+		}
+	}
+
+	/*Assemble: */
+	ys->Assemble();
+
+	/*Assign output pointers: */
+	*pys=ys;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  CreateNodalConstraintsx.h
+ */ 
+
+#ifndef _CREATENODALCONSTRAINTSX_H
+#define _CREATENODALCONSTRAINTSX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type);
+
+#endif  /* _CREATENODALCONSTRAINTSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 18231)
@@ -0,0 +1,88 @@
+/*!\file DragCoefficientAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./DragCoefficientAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=DragCoefficientAbsGradient(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble DragCoefficientAbsGradient(Element* element){
+
+	int         domaintype,numcomponents;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble  dp[2],weight;
+	IssmDouble* xyz_list      = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn basal element*/
+	Element* basalelement = element->SpawnBasalElement();
+
+	/* Get node coordinates*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=basalelement->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* drag_input   =basalelement->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
+		drag_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		/*Compute Tikhonov regularization J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */
+		Jelem+=weight*.5*dp[0]*dp[0]*Jdet*gauss->weight;
+		if(numcomponents==2) Jelem+=weight*.5*dp[1]*dp[1]*Jdet*gauss->weight;
+
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  DragCoefficientAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _DRAGCOEFFABSGRADX_H
+#define _DRAGCOEFFABSGRADX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble DragCoefficientAbsGradient(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file ElementConnectivityx
+ * \brief: compute element connectivity table, using node connectivity table and elements.
+ *
+ * For each element, we want to know which neighbouring elements it connects to (fully, via an entire segment, not by a node).
+ * We use the nodeconnectivity to speed up the computation. The nodeconnectivity gives us for each node of the element, 
+ * all the neighbouring elements of this node, which are good candidates to be neighbours of the element itself.
+ * For now, only triangular elements, ie 3 neighbours max per element.
+ */
+
+#include "./ElementConnectivityx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+int hascommondedge(int* element1,int* element2);
+
+void ElementConnectivityx(int** pelementconnectivity,int* elements, int nels,int* nodeconnectivity, int nods, int width){
+
+	int i,j,k,n;
+
+	/*intermediary: */
+	int    maxels;
+	int  connectedelement;
+	int    connectedelementindex;
+	int    node;
+	int    index;
+	int    num_elements;
+
+	/*maxels: */
+	maxels=width-1;
+
+	/*Allocate connectivity: */
+	int* elementconnectivity=xNewZeroInit<int>(nels*3);
+
+	/*Go through all elements, and for each element, go through its nodes, to get the neighbouring elements. 
+	 * 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<nels;n++){
+
+		//element=n+1; //matlab indexing
+
+		for(i=0;i<3;i++){
+
+			node=elements[n*3+i]; //already matlab indexed, elements comes directly from the workspace.
+			index=node-1;
+
+			num_elements=nodeconnectivity[width*index+maxels]; //retrieve number of elements already  plugged into the connectivity of this node.
+
+			for(j=0;j<num_elements;j++){
+
+				/*for each element connected to node, figure out if it has a commond edge with element: */
+				connectedelement=nodeconnectivity[width*index+j];
+				connectedelementindex=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 
+					 *it is already there: */
+
+					for(k=0;k<3;k++){
+						if(elementconnectivity[3*n+k]==0){
+							elementconnectivity[3*n+k]=connectedelement;
+							break;
+						}
+						else{
+							if(connectedelement==elementconnectivity[3*n+k]) break;
+						}
+					}
+				}
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pelementconnectivity=elementconnectivity;
+}
+
+int hascommondedge(int* el1,int* el2){
+
+	int count=0;
+	for(int i=0;i<3;i++){
+		for(int j=0;j<3;j++){
+			if(el1[i]==el2[j]) count++;
+		}
+	}
+	if(count==2)
+	 return 1;
+	else
+	 return 0;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 18231)
@@ -0,0 +1,11 @@
+/*!\file:  ElementConnectivityx.h
+ * \brief header file for element connectivity computation
+ */ 
+
+#ifndef _ELEMENTCONNECTIVITYX_H
+#define _ELEMENTCONNECTIVITYX_H
+
+/* local prototypes: */
+void	ElementConnectivityx(int** pelementconnectivity,int* elements,int nels,int* nodeconnectivity, int nods, int width);
+
+#endif  /* _ELEMENTCONNECTIVITYX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 18231)
@@ -0,0 +1,292 @@
+/*!\file Exp2Kmlx
+ * \brief exp to kml conversion routines.
+ */
+
+#include "./Exp2Kmlx.h"
+#include "../../shared/shared.h"
+#include "../../kml/kmlobjects.h"
+#include "../../toolkits/toolkits.h"
+
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,bool holes){
+
+	double  cm,sp;
+
+	Xy2lldef(&cm,&sp,sgn);
+	return(Exp2Kmlx(filexp,filkml,sgn,cm,sp,holes));
+}
+
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,double cm,double sp,bool holes){
+
+	int      i        ,j,iret=0;
+	int      lwidth = 1;
+	double   popac  = 0.50;
+	int      nprof;
+	int     *pnvert = NULL;
+	double **pprofx = NULL,**pprofy=NULL;
+	bool    *closed = NULL;
+	double  *lat    = NULL, *lon=NULL;
+
+	char    indent[81]="";
+	KML_File*          kfile =NULL;
+	KML_Document*      kdoc  =NULL;
+	KML_Style*         kstyle=NULL;
+	KML_LineStyle*     klsty =NULL;
+	KML_PolyStyle*     kpsty =NULL;
+	KML_Folder*        kfold =NULL;
+	KML_Placemark*     kplace=NULL;
+	KML_Polygon*       kpoly =NULL;
+	KML_LinearRing*    kring =NULL;
+	KML_LineString*    kline =NULL;
+	KML_Point*         kpoint=NULL;
+
+	FILE*   fid=NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nExp2Kmlx Module -- " << ctime(&time0));
+
+	/*read exp file  */
+
+	if (!ExpRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
+		_error_("Error reading exp file.");
+	_printf0_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".\n");
+//	for (i=0; i<nprof; i++)
+//		_printf_("i=" << i << "; nvert=" << pnvert[i] << ", closed=" << closed[i] << "\n");
+
+/*  construct kml file  */
+
+	kfile =new KML_File();
+	kfile->AddAttrib("xmlns","http://www.opengis.net/kml/2.2");
+
+/*  construct kml document  */
+
+	kdoc  =new KML_Document();
+	sprintf(kdoc->name      ,"Exp2Kmlx Module -- %s",ctime(&time0));
+	kdoc->open      =1;
+
+/*  construct style templates for defaults  */
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"%02xffffff",(int)floor(popac*255+0.5));
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineRandomPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"00ffffff");
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineEmptyPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"%02xffffff",(int)floor(popac*255+0.5));
+	sprintf(klsty->colormode ,"random");
+	klsty->width     =lwidth*2;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"00ffffff");
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","RandomLineEmptyPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+/*  construct kml folder for polygons  */
+
+	kfold =new KML_Folder();
+	sprintf(kfold->name      ,"Profiles translated from file \"%s\".",filexp);
+	kfold->open      =1;
+
+/*  polygon with multiple holes  */
+
+	if (holes && nprof && (pnvert[0] <= 1 || pprofx[0][pnvert[0]-1] != pprofx[0][0] || pprofy[0][pnvert[0]-1] != pprofy[0][0])) {
+		_printf0_("Warning -- Outer profile is not closed, so \"holes\" option will be ignored.\n");
+		holes=false;
+	}
+
+	if (holes) {
+		i=0;
+		kplace=new KML_Placemark();
+		sprintf(kplace->name      ,"Polygon with Holes");
+		kplace->visibility=true;
+		sprintf(kplace->styleurl  ,"#BlackLineRandomPoly");
+
+		kpoly =new KML_Polygon();
+		kring =new KML_LinearRing();
+
+		kring->ncoord    =pnvert[i]-1;
+		lat=xNew<double>(kring->ncoord);
+		lon=xNew<double>(kring->ncoord);
+		Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
+		kring->coords=xNew<double>(kring->ncoord*3);
+		for (j=0; j<kring->ncoord; j++) {
+			kring->coords[3*j+0]=lon[j];
+			kring->coords[3*j+1]=lat[j];
+			kring->coords[3*j+2]=0.;
+		}
+		xDelete<double>(lon);
+		xDelete<double>(lat);
+
+		(kpoly ->outer     )->AddObject((Object*)kring);
+		kring =NULL;
+
+		for (i=1; i<nprof; i++) {
+			if (pnvert[i] <= 1 || pprofx[i][pnvert[i]-1] != pprofx[i][0] || pprofy[i][pnvert[i]-1] != pprofy[i][0]) {
+				_printf0_("Warning -- Inner profile " << i+1 << " is not closed with \"holes\" specified, so it will be ignored.\n");
+				continue;
+			}
+
+			kring =new KML_LinearRing();
+
+			kring->ncoord    =pnvert[i]-1;
+			lat=xNew<double>(kring->ncoord);
+			lon=xNew<double>(kring->ncoord);
+			Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
+			kring->coords    =xNew<double>(kring->ncoord*3);
+			for (j=0; j<kring->ncoord; j++) {
+				kring->coords[3*j+0]=lon[j];
+				kring->coords[3*j+1]=lat[j];
+				kring->coords[3*j+2]=0.;
+			}
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kpoly ->inner     )->AddObject((Object*)kring);
+			kring =NULL;
+		}
+
+		(kplace->geometry  )->AddObject((Object*)kpoly);
+		kpoly =NULL;
+		(kfold ->feature   )->AddObject((Object*)kplace);
+		kplace=NULL;
+	}
+
+/*  multiple polygons or linestrings  */
+
+	else {
+		for (i=0; i<nprof; i++) {
+			kplace=new KML_Placemark();
+
+			if     (pnvert[i] > 1 && pprofx[i][pnvert[i]-1] == pprofx[i][0] && pprofy[i][pnvert[i]-1] == pprofy[i][0]) {
+				sprintf(kplace->name      ,"Polygon %d",i+1);
+				kplace->visibility=true;
+				sprintf(kplace->styleurl  ,"#BlackLineRandomPoly");
+
+				kpoly =new KML_Polygon();
+				kring =new KML_LinearRing();
+
+				kring->ncoord    =pnvert[i]-1;
+				lat=xNew<double>(kring->ncoord);
+				lon=xNew<double>(kring->ncoord);
+				Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
+				kring->coords    =xNew<double>(kring->ncoord*3);
+				for (j=0; j<kring->ncoord; j++) {
+					kring->coords[3*j+0]=lon[j];
+					kring->coords[3*j+1]=lat[j];
+					kring->coords[3*j+2]=0.;
+				}
+				xDelete<double>(lon);
+				xDelete<double>(lat);
+
+				(kpoly ->outer     )->AddObject((Object*)kring);
+				kring =NULL;
+
+				(kplace->geometry  )->AddObject((Object*)kpoly);
+				kpoly =NULL;
+			}
+
+			else if (pnvert[i] > 1) {
+				sprintf(kplace->name      ,"LineString %d",i+1);
+				kplace->visibility=true;
+				sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+
+				kline =new KML_LineString();
+
+				kline->ncoord    =pnvert[i];
+				lat=xNew<double>(kline->ncoord);
+				lon=xNew<double>(kline->ncoord);
+				Xy2llx(lat,lon,pprofx[i],pprofy[i],kline->ncoord,sgn,cm,sp);
+				kline->coords    =xNew<double>(kline->ncoord*3);
+				for (j=0; j<kline->ncoord; j++) {
+					kline->coords[3*j+0]=lon[j];
+					kline->coords[3*j+1]=lat[j];
+					kline->coords[3*j+2]=0.;
+				}
+				xDelete<double>(lon);
+				xDelete<double>(lat);
+
+				(kplace->geometry  )->AddObject((Object*)kline);
+				kline =NULL;
+			}
+
+			else if (pnvert[i]) {
+				sprintf(kplace->name      ,"Point %d",i+1);
+				kplace->visibility=true;
+				sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+				int one=1;
+
+				kpoint=new KML_Point();
+
+				lat=xNew<double>(one);
+				lon=xNew<double>(one);
+				Xy2llx(lat,lon,pprofx[i],pprofy[i],1,sgn,cm,sp);
+				kpoint->coords[0]=lon[0];
+				kpoint->coords[1]=lat[0];
+				kpoint->coords[2]=0.;
+				xDelete<double>(lon);
+				xDelete<double>(lat);
+
+				(kplace->geometry  )->AddObject((Object*)kpoint);
+				kpoint =NULL;
+			}
+
+			(kfold ->feature   )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+	}
+
+/*  assemble the rest of the kml hierarchy  */
+
+	(kdoc ->feature   )->AddObject((Object*)kfold);
+	kfold=NULL;
+	(kfile->kmlobj    )->AddObject((Object*)kdoc);
+	kdoc =NULL;
+
+/*  write kml file  */
+
+	_printf0_("Exp2Kmlx -- Writing kml document to file \"" << filkml << "\".\n");
+	fid=fopen(filkml,"w");
+	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+	kfile->Write(fid,indent);
+	fclose(fid);
+
+	delete kfile;
+	for (i=nprof-1; i>=0; i--) {
+		xDelete<double>(pprofy[i]);
+		xDelete<double>(pprofx[i]);
+	}
+	xDelete<int>(pnvert);
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("Exp2Kmlx Module -- " <<((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " <<difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return(iret);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file:  Exp2Kmlx.h
+ * \brief header file for exp to kml conversion routines.
+ */ 
+
+#ifndef _EXP2KMLX_H
+#define _EXP2KMLX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,bool holes);
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,double cm,double sp,bool holes);
+
+#endif  /* _EXP2KMLX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file FloatingiceMeltingRatex
+ * \brief: calculates Floating ice melting rate
+ */
+
+#include "./FloatingiceMeltingRatex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void FloatingiceMeltingRatex(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaties*/
+	int  basalforcing_model;
+
+	/*First, get SMB model from parameters*/
+	femmodel->parameters->FindParam(&basalforcing_model,BasalforcingsEnum);
+
+	/*branch to correct module*/
+	switch(basalforcing_model){
+		case FloatingMeltRateEnum:
+			/*Nothing to be done*/
+			break;
+		case LinearFloatingMeltRateEnum:
+			if(VerboseSolution())_printf_("	call Linear Floating melting rate module\n");
+			LinearFloatingiceMeltingRatex(femmodel);
+			break;
+		default:
+			_error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
+	}
+
+}/*}}}*/
+
+void LinearFloatingiceMeltingRatex(FemModel* femmodel){/*{{{*/
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->LinearFloatingiceMeltingRate();
+	}
+
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  FloatingiceMeltingRatex.h
+ * \brief header file for Floatingice melting rate
+ */ 
+
+#ifndef _FloatingiceMeltingRatex_H
+#define _FloatingiceMeltingRatex_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void FloatingiceMeltingRatex(FemModel* femmodel);
+void LinearFloatingiceMeltingRatex(FemModel* femmodel);
+
+#endif  /* _FloatingiceMeltingRatex_H*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 18231)
@@ -0,0 +1,44 @@
+/*!\file GetSolutionFromInputsx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./GetSolutionFromInputsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void GetSolutionFromInputsx(Vector<IssmDouble>** psolution,FemModel* femmodel){
+
+	/*intermediary: */
+	int      gsize;
+	int      configuration,analysisenum;
+
+	/*output: */
+	Vector<IssmDouble>* solution=NULL;
+
+	if(VerboseModule()) _printf0_("   Get solution from inputs\n");
+
+	/*retrive parameters: */
+	femmodel->parameters->FindParam(&configuration,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+
+	/*Get size of vector: */
+	gsize=femmodel->nodes->NumberOfDofs(configuration,GsetEnum);
+	if(gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration "<<EnumToStringx(configuration));
+
+	/*Initialize solution: */
+	solution=new Vector<IssmDouble>(gsize);
+
+	/*Go through elements and plug solution: */
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		analysis->GetSolutionFromInputs(solution,element);
+	}
+	delete analysis;
+
+	/*Assemble vector: */
+	solution->Assemble();
+
+	/*Assign output pointers:*/
+	*psolution=solution;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  GetSolutionFromInputsx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _GETSOLUTIONFROMINPUTSXX_H
+#define _GETSOLUTIONFROMINPUTSXX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void GetSolutionFromInputsx(Vector<IssmDouble>** psolution,FemModel* femmodel);
+
+#endif  /* _GETSOLUTIONFROMINPUTSXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 18231)
@@ -0,0 +1,52 @@
+/*!\file GetVectorFromControlInputsx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./GetVectorFromControlInputsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){
+
+	int  num_controls;
+	int *control_type = NULL;
+	Vector<IssmDouble>*  vector=NULL;
+
+	/*Retrieve some parameters*/
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	/*Allocate and populate gradient*/
+	vector=new Vector<IssmDouble>(num_controls*vertices->NumberOfVertices());
+
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<elements->Size();j++){
+			Element* element=(Element*)elements->GetObjectByOffset(j);
+			element->GetVectorFromControlInputs(vector,control_type[i],i,data);
+		}
+	}
+
+	vector->Assemble();
+
+	/*Assign output pointers:*/
+	xDelete<int>(control_type);
+	*pvector=vector;
+}
+
+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;
+
+	GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data);
+	vector=vec_vector->ToMPISerial();
+
+	/*Free ressources:*/
+	delete vec_vector;
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  GetVectorFromControlInputsx.h
+ */ 
+
+#ifndef _GETVECTORFROMCONTROLINPUTSXX_H
+#define _GETVECTORFROMCONTROLINPUTSXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	GetVectorFromControlInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+
+#endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\file GetVectorFromInputsx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./GetVectorFromInputsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){
+
+	int i;
+	Vector<IssmDouble>* vector=NULL;
+
+	if(type==VertexEnum){
+
+		/*Allocate vector*/
+		vector=new Vector<IssmDouble>(femmodel->vertices->NumberOfVertices());
+
+		/*Look up in elements*/
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			element->GetVectorFromInputs(vector,name);
+		}
+	}
+	else{
+		_error_("vector type: " << EnumToStringx(type) << " not supported yet!");
+	}
+
+	vector->Assemble();
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
+
+void GetVectorFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name, int type){
+
+	/*output: */
+	IssmDouble* vector=NULL;
+
+	/*intermediary: */
+	Vector<IssmDouble>* vec_vector=NULL;
+
+	GetVectorFromInputsx(&vec_vector,femmodel,name,type);
+	vector=vec_vector->ToMPISerial();
+
+	/*Free ressources:*/
+	delete vec_vector;
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  GetVectorFromInputsx.h
+ */ 
+
+#ifndef _GETVECTORFROMINPUTSXX_H
+#define _GETVECTORFROMINPUTSXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
+void	GetVectorFromInputsx( IssmDouble** pvector,FemModel* femmodel,int name,int type);
+
+#endif  /* _GETVECTORFROMINPUTSXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 18231)
@@ -0,0 +1,171 @@
+/*!\file GiaDeflectionCorex
+ * \brief: GIA solution from Erik Ivins. 
+ * Compute deflection wi from a single disk of radius re, load history hes for 
+ * numtimes time steps. 
+ */
+
+#include "./GiaDeflectionCorex.h"
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+
+/*External blocks: {{{*/
+struct blockp{
+	double pset[7];
+};
+
+struct blocko{
+	double rhoi;
+};
+
+struct blockrad{
+	double distrad; 
+};
+
+struct blocks{
+	double aswokm_w; 
+	double aswokm_dwdt; 
+};
+
+extern "C" { 
+	int distme_(int* pNtime,int* pNtimp,int* pNtimm,double* time,double* bi,double* dmi,double* zhload);
+
+	int what0_(int* piedge,int* pNtimp,int* pNtimm,double* time,double* bi,double* dmi);
+	extern struct blockp blockp_;
+	extern struct blocko blocko_;
+	extern struct blockrad blockrad_;
+	extern struct blocks blocks_;
+}
+
+/*}}}*/
+
+void GiaDeflectionCorex( IssmDouble* pwi, IssmDouble* pdwidt, GiaDeflectionCoreArgs* arguments){
+
+	/*intermediary: */
+	int i;
+
+	/*output: */
+	IssmDouble wi=0;
+	IssmDouble dwidt=0;
+
+	/*inputs: {{{*/
+	/*constant: */
+	int idisk=1; // disk #
+	IssmDouble yts;
+
+	/*coming from the model structure, runtime configurable:*/
+	/*gia solution parameters: */
+	int iedge=0; 
+
+	/*gia inputs: */
+	IssmDouble ri; //radial distance from center of disk to vertex  i
+	IssmDouble re; //radius of disk
+	IssmDouble* hes; //loading history (in ice thickness)
+	IssmDouble* times; //loading history times
+	int numtimes; //loading history length
+	IssmDouble currenttime;
+	int Ntime; // number of times with load history 
+	int Ntimm; // Ntime-1 : for slope/y-cept of load segments 
+	int Ntimp; // Ntime+1 : for evaluation time  
+	IssmDouble* blockt_time=NULL;
+	IssmDouble* blockt_bi=NULL;
+	IssmDouble* blockt_dmi=NULL;
+	IssmDouble* blocky_zhload=NULL;
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_viscosity;
+	IssmDouble mantle_density;
+	IssmDouble lithosphere_thickness;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*some debug info: */
+	int disk_id;
+
+/*}}}*/
+
+	/*Recover material parameters and loading history: see GiaDeflectionCoreArgs for more details {{{*/
+	ri                        = arguments->ri;
+	re                        = arguments->re;
+	hes                       = arguments->hes;
+	times                     = arguments->times;
+	numtimes                  = arguments->numtimes;
+	currenttime               = arguments->currenttime;
+	lithosphere_shear_modulus = arguments->lithosphere_shear_modulus;
+	lithosphere_density       = arguments->lithosphere_density;
+	mantle_shear_modulus      = arguments->mantle_shear_modulus;
+	mantle_viscosity          = arguments->mantle_viscosity;
+	mantle_density            = arguments->mantle_density;
+	lithosphere_thickness     = arguments->lithosphere_thickness;
+	rho_ice                   = arguments->rho_ice;
+	disk_id                   = arguments->idisk;
+	iedge                     = arguments->iedge;
+	yts                       = arguments->yts;
+
+	/*}}}*/
+
+	/*Modify inputs to match naruse code: */
+	Ntime=numtimes;
+	Ntimm=Ntime-1;
+	Ntimp=Ntime+1;
+
+	/*Prepare block inputs for fortran distme and what0 routines of the naruse code: {{{*/
+	/*Now, let's set pset from the data that we got in input to GiaDeflectionCorex: */
+	blockp_.pset[0]=lithosphere_thickness;
+	blockp_.pset[1]=mantle_viscosity;
+	blockp_.pset[2]=lithosphere_shear_modulus;
+	blockp_.pset[3]=mantle_shear_modulus;
+	blockp_.pset[4]=lithosphere_density;
+	blockp_.pset[5]=mantle_density;
+	blockp_.pset[6]=re;
+	blocko_.rhoi=rho_ice; 
+
+	/*loading history: */
+	blocky_zhload=xNew<IssmDouble>(Ntime);
+	for(i=0;i<Ntime;i++){
+	blocky_zhload[i]=hes[i];
+	}
+
+	/*times in kyr: */
+	blockt_time=xNew<IssmDouble>(Ntimp);
+	for (i=0;i<Ntimp;i++){
+		blockt_time[i]=times[i]/1000.0/yts; 
+		if(i==numtimes-1)blockt_time[i]=times[numtimes-1]/1000.0/yts; // final loading time, same as evaluation time
+		if(i==numtimes)blockt_time[i]=times[numtimes-1]/1000.0/yts;   // evaluation time
+	}
+
+	/*bi: */
+	blockt_bi=xNew<IssmDouble>(Ntimm);
+
+	/*dmi: */
+	blockt_dmi=xNew<IssmDouble>(Ntimm);
+
+	/*radial distance of i-th element: */
+	blockrad_.distrad=ri/1000.0; // in km
+	/*}}}*/
+
+	/*Call distme driver: */
+	distme_(&Ntime,&Ntimp,&Ntimm,blockt_time,blockt_bi,blockt_dmi,blocky_zhload); 
+
+	/*Call what0 driver: */
+	what0_(&iedge,&Ntimp,&Ntimm,blockt_time,blockt_bi,blockt_dmi); 
+
+	/*output solution: */
+	wi = blocks_.aswokm_w;
+	dwidt = blocks_.aswokm_dwdt;
+	*pwi=wi;
+	*pdwidt=dwidt;
+
+	/*Free ressources: */
+	xDelete<IssmDouble>(blockt_time);
+	xDelete<IssmDouble>(blockt_bi);
+	xDelete<IssmDouble>(blockt_dmi);
+	xDelete<IssmDouble>(blocky_zhload);
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  GiaDeflectionCorex.h
+ * \brief header file for ...
+ */ 
+
+#ifndef _GIADEFLECTIONCOREX_H
+#define _GIADEFLECTIONCOREX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void GiaDeflectionCorex( IssmDouble* pwi, IssmDouble* pdwidt, GiaDeflectionCoreArgs* arguments);
+
+#endif  /* _GIADEFLECTIONCOREX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/distme.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/distme.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/distme.f	(revision 18231)
@@ -0,0 +1,73 @@
+      subroutine distme(Ntime,Ntimp,Ntimm,time,bi,dmi,zhload)
+      implicit double precision (a-h,o-y)
+      integer Ntime,Ntimp,Ntimm
+      parameter (Nafter=1)
+      double precision pset(7)
+      double precision time(Ntimp),dmi(Ntimm),bi(Ntimm),dumbt(Ntimp)
+      double precision hload(Ntime),qpat(Ntime),qt(Ntime)
+      double precision zhload(Ntime),rhoi,distrad
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockp/ pset
+      common /blockrad/ distrad 
+      common /blocko/ rhoi
+      data g /9.832186d0/, yearco /3.15576d7/, eradm/6.371d6/
+      data dpi /3.1415926535897932d0/, dzero/0.0d0/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c The units of time(Ntimp) are ka and the height of the load in meters.
+c The slope, then for example, is in units of meters per ka.
+c Note that "dumbt( )" is designed to perserve the initial "time( )" variable.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 776 k = 1, Ntimp
+      dumbt(k) = time(k)
+  776 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 39 itime = 1, Ntime
+      hload(itime) = dble( zhload(itime) )
+   39 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c now set up a piece-wise history: bi() = y-intercept 
+c                                 dmi() = slope 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 70 i = 2, Ntime
+      dmi(i-1) = ( hload(i) - hload(i-1) )/( dumbt(i)  - dumbt(i-1) )
+      bi(i-1) = hload(i-1) - ( dmi(i)*dumbt(i-1) )  
+   70 continue
+c      write(6,*) zhload(1,1), zhload(1,2) 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c With pset(6) in mks units, lets convert the piecewise linear formulas
+c for the time-dependent ice load heights to dimensionless values w.r.t. time.
+c (tfact is in seconds)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      tfact = pset(2)/pset(4)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c get all times as dimensionless 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 20 jt = 1, Nafter
+      time(Ntime + jt) = ( dumbt(Ntime + jt) * yearco * 1.0d3 ) / tfact
+   20 continue
+      do 75 ind = 1, Ntimm 
+      dmi(ind) =  dmi(ind) / (( yearco * 1.0d3 ) / tfact )
+   75 continue
+      do 77 j = 1, Ntime 
+      time(j) = ( dumbt(j) * yearco * 1.0d3 ) / tfact
+   77 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c create an incremental load in Pa and non-dimensionalized:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 80 iq = 1, Ntime
+      qpat(iq) = hload(iq)*rhoi*g
+      qt(iq) = qpat(iq) / pset(4)
+   80 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c As the final step in this routine, create a dimensionless stress load from
+c qp.  Here we'll use bi( ) and dmi( ) vectors with dimensionless time.  Then
+c qp (and it's piece-wise decomposition) is ready for the direct dimensionless
+c integrals for the inverse Laplace transform and inverse Hankel transform
+c without further mutiplicative factors.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 85 i = 2, Ntime
+      dmi(i-1) = ( qt(i) - qt(i-1) )/( time(i)  - time(i-1) )
+      bi(i-1) = qt(i-1) - ( dmi(i-1)*time(i-1) )  
+   85 continue
+  999 return
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/freed.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/freed.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/freed.f	(revision 18231)
@@ -0,0 +1,222 @@
+      subroutine freed(r2,u2,r1,u1,h,zk,e1,e2,e4,b0,b1,a2,a1,a0,decay
+     1,amps)        
+      implicit double precision (a-h,o-z)
+      double precision decay(2),amps(5)
+      double precision ac0,ac1,ac2,ac3,ac4,ac5,ac6,ac7,ac8,ac9,ac10,
+     1ac11
+      common /blockz/ zkp
+      data zero /0.0d0/, g /9.832186d0/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Given the inputs to this subroutine(r2 through zk in the call
+c statement above), the outputs are coefficients of "s" that
+c are crucial to the Laplace transform inversion. From b0 and b1
+c we can compute the decay poles (or eigenvalues).    
+c 
+c  This is NOT true in our case, though. - SA
+c  NOTE IN THE CODE THAT A CALL TO THIS SUBROUTINE NEED NOT
+c  BE MADE AT EACH TIME STEP --- BUT WILL HAVE TO BE CALLED
+c  IN THE NUMERICAL INTEGRATION FOR COMPUTING THE INVERSE HANKEL
+c  TRANSFORM  ****
+c
+c Each term should be returned as dimensionless 
+c h => length   u2 => stress     taumx2 => time
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      zkp2 = zkp*zkp
+      ur = u1/u2
+      ghu2 = (g*h) / u2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac0 dimensional units are stress times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac0 = 4.0d0*ur*zkp2*( 1.0d0 + e4 +
+     1    2.0d0*e2*(1.0d0 + 2.0d0*zkp2) )
+c    DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac1 dimensional units are stress times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac1 = 2.0d0*r1*ghu2*zkp*(1.0d0 - e4 + 4.0d0*zkp*e2)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac2 dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac2 = 8.0d0*ur*ur*(-1.0d0 + e1)*
+     1                     (1.0d0 + e1)*(1.0d0 + e2)*zkp2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac3  dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac3 =
+     1   2.0d0*zkp*ghu2*ur*((r1 + r2)*(1.0d0 + e4) + 
+     2       2.0d0*(r2 - r1)*e2*( 1.0d0 + 2.0d0*zkp2 ))
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac4 dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac4 = ghu2*ghu2*r1*(r2 - r1)*
+     1      (1.0d0 - e4 + 4.0d0*zkp*e2)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac5 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac5 = 
+     1    4.0d0*zkp2*ur*ur*ur*(1.0d0 - e2 - 2.0d0*e1*zkp)*
+     2                (1.0d0 - e2 + 2.0d0*e1*zkp)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac6 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac6 =
+     1   2.0d0*zkp*ur*ur*(1.0d0 - e4
+     2               - 4.0d0*e2*zkp)*ghu2*r2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac7 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac7 =
+     1 ur * ( ( (1.0d0 - e1)*(1.0d0 + e1) )**2)*r1*(r2 - r1)
+     2 * ( ghu2*ghu2 )
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac8 dimensional units are stress^0 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac8 = -2.0d0*zkp*(1.0d0 + e2*(1.0d0 + 2.0d0*zkp*(1.0d0 + zkp))) 
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac9 dimensional units are stress^1 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac9 = 
+     1  ( 4.0d0*zkp*u1 -
+     2 g*h*(r2 - r1)*(1.0d0 + e2*(1.0d0 + 2.0d0*zkp*(1.0d0 + zkp)))
+     3    ) / u2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac10 dimensional units are stress^2 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac10 =
+     1   -2.0d0*zkp*ur*ur*( 1.0d0 - e2
+     2  - 2.0d0*zkp*e2*(1.0d0 + zkp) )
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac11 dimensional units are stress^2 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac11 =
+     1 ghu2*ur*(r2 - r1)*(1.0d0 - e2*(1.0d0 + 2.0d0*zkp))
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Other functions may be found in file "apcw0.record"
+c (Nov. 9 1996)
+c The following is a Mathematica version of the isolation of the
+c  coefficeints of the L transform variable s in the denominator.  
+c  Here is where the set-up is performed to obtain the "free decay"
+c  times (with the Hankel transform variable "zk" embedded.  Note that
+c  some greater efficency could be achieved by further simplifying the
+c  combinations of "acn" functions which are now a series of function
+c  subroutines in the fortran code.  The corresponding Mathematica
+c  session is "twolayer.Linversion" dated Nov. 23, 1996.
+c
+c In[59]:=
+c Together[%]
+c Out[59]=
+c    ac2 + ac3 - ac4 + 2 ac5 - 2 ac6 + 2 ac7
+c ---------------------------------------------
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c In[61]:=
+c Simplify[Coefficient[els,s^2]]
+c Out[61]=
+c 1
+c In[65]:=
+c eslnos =
+c ac5/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7) - 
+c    ac6/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7) + 
+c 
+c   ac7/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7)
+c    
+c Out[65]=
+c                      ac5
+c --------------------------------------------- - 
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c 
+c                        ac6
+c  --------------------------------------------- + 
+c   ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c 
+c                        ac7
+c  ---------------------------------------------
+c  ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c In[66]:=
+c Simplify[%]
+c Out[66]=
+c                ac5 - ac6 + ac7
+c ---------------------------------------------
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c a common denominator factor is: bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bc =  (   ac0 - ac1 +
+     1                     ac2 + ac3
+     2                                 - ac4 + ac5 -
+     3           ac6 + ac7  )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c b1: Denominator coefficent of s:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      b1 =
+     1  (  ac2 + ac3
+     2               - ac4 + ( 2.0d0 * ac5 )
+     3                                       - ( 2.0d0 * ac6 )
+     4                                       + ( 2.0d0 * ac7 )   ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c b0: Denominator coefficent of s^0:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      b0 =
+     1 (  ac5 - ac6 +
+     2                 ac7  ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c the eigenvaules are just the solution of the quadratic in s:
+c so return as "decay"
+c  *** Note that the decay times are defined as positive ***
+c      if a negative inverse decay time is returned there is an error!
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      sb1 = b1*b1
+      fb0 = 4.0d0*b0
+      diff =  sb1 - fb0          
+      if(diff.le.zero) go to 25
+      rs =  dsqrt( diff )          
+      decay(1) = -( - b1 - rs ) / 2.0d0
+      decay(2) = -( - b1 + rs ) / 2.0d0          
+      go to 26
+   25 idgen = 100
+      go to 9990
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c and for the numerator part of the quadratic s dependence
+c the Mathematica session is:
+c
+c Out[14]=
+c                                                                      2
+c ac10 + ac11 + (2 ac10 + 2 ac11 + ac9) s + (ac10 + ac11 + ac8 + ac9) s
+c----------------------------------------------------------------------
+c            ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   26 a0 = ( ac10 + ac11 ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      a1 = ( 2.0d0*( ac10 + ac11 )
+     1                             + ac9 )  / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      a2 =  (ac10 + ac11
+     1                   + ac8 + ac9) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c and the following terms are the amplitudes of the inverse Laplace
+c transform solution for the non-q part.  (See the boxed equation on
+c page 4 of the Nov. 23 1996 notes.)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decdif = 1.0d0/(decay(2) - decay(1))
+      amps(1) = -decdif*( decay(1) * ( a1 - a2*decay(1) ) - a0 )
+      amps(2) =  decdif*( decay(2) * ( a1 - a2*decay(2) ) - a0 )
+      amps(3) = a2
+      amps(4) = - decay(1) * amps(1) 
+      amps(5) = - decay(2) * amps(2)
+      go to 999
+ 9990 write(6,998) idgen
+  998 format(' idgen val ** fatal error ** degenerate e.v.'/1h ,1p,1i12) 
+  999 return
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/ojrule.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/ojrule.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/ojrule.f	(revision 18231)
@@ -0,0 +1,63 @@
+      subroutine ojrule(dk,bcin_w,bcin_dwdt)
+      implicit double precision(a-h,o-z)
+      parameter (nhank = 1024)
+      double precision yvalue_w(nhank),yvalue_dwdt(nhank)
+      double precision bcin_w(nhank),bcin_dwdt(nhank)
+      double precision wok_w,wok_dwdt,rpos
+      double precision swok_w,swok_dwdt
+      double precision pset(7)
+      double precision aswokm_w,aswokm_dwdt,distrad
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockrad/ distrad
+      common /blockp/ pset
+      common /blocks/ aswokm_w,aswokm_dwdt
+      data zero /0.0d0/, one /1.0d0/, two /2.0d0/, three /3.0d0/,
+     1rescal/ 1.0d0/
+      data yearco /3.15576d7/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bath = dk / three
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c rpos should be normalized wrt lithosphere thickness 
+c give r is normalized dist_rad :: r == dist_rad / h
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      r = distrad / (pset(1) / 1.0d3)
+      rpos = r 
+      ak = zero
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c form the yvalue's for the Simpson's rule formulas
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 425 ik = 1, nhank
+      ak = ak + dk
+      rak = ak * r
+      rarg = dbesj0( rak )
+      yvalue_w(ik) = bcin_w(ik) * rarg
+      yvalue_dwdt(ik) = bcin_dwdt(ik) * rarg
+  425 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c correct to end point val. in Simp. Rule
+c      yvalue(nhank) = bcin(nhank) * rarg / two
+c find the area under the curve using the Simpson's rule formulas
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      sumde_w = zero
+      sumde_dwdt = zero
+      do 300 int = 1, nhank
+      intp1 = int + 1
+      ide = 2 + ( (-1)**intp1 + 1 )
+      fide = dfloat(ide)
+      sumde_w = ( fide * yvalue_w(int) ) + sumde_w
+      sumde_dwdt = ( fide * yvalue_dwdt(int) ) + sumde_dwdt
+  300 continue
+      wok_w = bath * sumde_w
+      wok_dwdt = bath * sumde_dwdt
+      
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      hscale = sngl(pset(1))
+      hsckm = hscale / 1.0e3
+      swok_w = hscale * sngl(wok_w)
+      aswokm_w = swok_w
+      swok_dwdt = (hscale * yearco * 1.0e3 * sngl(wok_dwdt))
+     1                  * ( sngl(pset(4))/ sngl(pset(2)) )
+      aswokm_dwdt = swok_dwdt
+      return
+
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/pwise.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/pwise.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/pwise.f	(revision 18231)
@@ -0,0 +1,42 @@
+      subroutine pwise(t,ta,tb,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+      implicit double precision (a-h,o-z)
+      double precision decay(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c This subroutine retrieves the convolution for the ith linear piece-wise
+c q hat function (the load shape or Bessel function part having
+c been removed) with the free-decay solution. (see notes of
+c 12-31-96 "Convolution in time").  The convolution is returned as "bhaq".
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      tbt = tb - t
+      tat = ta - t
+      gat1 = tat * decay(1)
+      gat2 = tat * decay(2)
+      gbt1 = tbt * decay(1)
+      gbt2 = tbt * decay(2)
+      ea1 = dexp(gat1)
+      ea2 = dexp(gat2)
+      eb1 = dexp(gbt1)
+      eb2 = dexp(gbt2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit1 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit1 =(ycept/decay(1)) * (eb1 - ea1) -
+     1(slope/(decay(1)*decay(1))) *
+     2                            ( (1.0d0 - tb*decay(1))*eb1 
+     3                            - (1.0d0 - ta*decay(1))*ea1 )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit2 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit2 =(ycept/decay(2)) * (eb2 - ea2) -
+     1(slope/(decay(2)*decay(2))) *
+     2                            ( (1.0d0 - tb*decay(2))*eb2 
+     3                            - (1.0d0 - ta*decay(2))*ea2 )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c add terms for the i-th interval contribution. 
+c ABOVE IS THE NON-DEGENERATE CASE
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bhaq_w = (xi1 * xit1) + (xi2 * xit2)    
+      bhaq_dwdt = (xi3 * xit1) + (xi4 * xit2)    
+      return
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/qwise.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/qwise.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/qwise.f	(revision 18231)
@@ -0,0 +1,65 @@
+      subroutine qwise(t,ta,qjadon,xi0,xi1,xi2,xi3,xi4,slope,ycept,
+     1decay,bhaq_w,bhaq_dwdt)
+      implicit double precision (a-h,o-z)
+      double precision decay(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c This subroutine retrieves the convolution for the J-th linear piece-wise
+c q hat function (the load shape or Bessel function part having been removed)
+c with the free-decay solution. (see notes of 3-27-97 "convo.ice" Mathematica
+c session).  The convolution is returned as "bhaq".
+c
+c  THIS ROUTINE REPLACES pwise.f ONLY FOR t <  time(Ntime) *
+c  (such that the load is still in place at time t).       *
+c
+c Note irate = 1 case has to be applied to the linear term only (freed.f applies
+c this correction to exponential terms)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xg1 = xi1/(decay(1)*decay(1))
+      xg2 = xi2/(decay(2)*decay(2))
+      xg3 = xi3/(decay(1)*decay(1))
+      xg4 = xi4/(decay(2)*decay(2))
+      gb1 = decay(1)*ycept
+      gb2 = decay(2)*ycept
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit0 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit0_w = (xi0 + qjadon) * ( ( slope * t ) + ycept )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit1 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit1_w = xg1 * (
+     1              gb1 + slope * ( ( t * decay(1) ) - 1.0d0 )
+     2          - ( gb1 + slope * ( ( ta * decay(1) ) - 1.0d0 ))
+     3                                   * dexp( decay(1) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit2 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit2_w = xg2 * (
+     1              gb2 + slope * ( ( t * decay(2) ) - 1.0d0 )
+     2          - ( gb2 + slope * ( ( ta * decay(2) ) - 1.0d0 ) )
+     3                                   * dexp( decay(2) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c And the rate equivalents:
+c (sign switch due to freed.f already
+c having corrected in x1t, x2t pass).
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit0_dwdt = (xi0 + qjadon) * slope 
+      xit1_dwdt =-xg3 * (
+     1              slope  
+     2     + ( gb1 + slope * ( ( ta * decay(1) ) - 1.0d0 ))
+     3                                   * dexp( decay(1) * (ta - t) )
+     4                       )
+      xit2_dwdt =-xg4 * (
+     1              slope 
+     2     + ( gb2 + slope * ( ( ta * decay(2) ) - 1.0d0 ))
+     3                                   * dexp( decay(2) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c add terms for the J-th (and final) interval contribution.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bhaq_w = xit0_w + xit1_w + xit2_w
+      bhaq_dwdt = xit0_dwdt + xit1_dwdt + xit2_dwdt
+      return
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/stot.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/stot.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/stot.f	(revision 18231)
@@ -0,0 +1,79 @@
+      subroutine stot(ikval,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,
+     1time,bi,dmi)
+      implicit double precision (a-h,o-z)
+      integer Ntimp,Ntimm
+      parameter (Nafter = 1)
+      parameter (nhank = 1024)
+      double precision decay(2)
+      double precision pset(7)
+      double precision time(Ntimp),bi(Ntimm),dmi(Ntimm)
+      double precision dekay1(nhank),dekay2(nhank),amp0(nhank),
+     1amp1(nhank),amp2(nhank),amp3(nhank),amp4(nhank)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockm/ dekay1,dekay2,amp0,amp1,amp2,amp3,amp4
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c  This subroutine returns the inverse Laplace transform to the
+c  time-domain for the vertical displacement at time t for Hankel wavenumber
+c  ikval.  (In general this routine needs to be called nhank times).
+c  The main derivation uses the Faltung theorem of Laplace transforms.
+c  (1-1-97)  NEW CASE OF 3-27-97 IS FOR t(Ntime + i) < t(Ntime) OR IN OTHER
+c  WORDS, THE LOAD STILL IN PLACE AT t.  OPTION CALL to qwise.f
+c  PERFORMS THIS. 
+c 
+c  A theory for the degenerate case was worked out but has been removed
+c  as an option from this code.
+c
+c  Definition of tspan: nondimensional time span backwards form present
+c                       when this routine is first called the dimensional
+c                       equivalent might be say tspan = 12 ka, then 11 and
+c                       then finally tspan = 0.
+c  Additional note for r.s.l calculations: the routines qwise and pwise
+c  are identical to the previous case for computations of present-day only
+c  vertical deformation field.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decay(1) = dekay1(ikval)
+      decay(2) = dekay2(ikval)
+      xi0 = amp0(ikval)
+      xi1 = amp1(ikval)
+      xi2 = amp2(ikval)
+      xi3 = amp3(ikval)
+      xi4 = amp4(ikval)
+
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c note that tspan must be updated in the calling routine "what0.f"
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      t = time(Ntimp)
+      sumb_w = 0.0d0
+      sumb_dwdt = 0.0d0
+      ta = time(1)
+      tb = time(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 97 i = 1,Ntimm
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c note that this "if" prevents adding load
+c segments of "future" times when computing
+c an r.s.l. history (10-06-98).
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      if(t.lt.ta) go to 97
+      slope=dmi(i)
+      ycept=bi(i)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      if( t . gt . ta . and . t . le . tb) go to 38
+      call pwise(t,ta,tb,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+      go to 39
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Note that qwise is employed only for the J-th Q hat term when t for
+c evaluation still has to consider the load itself
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   38 call qwise(t,ta,qjadon,xi0,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+   39 sumb_w = bhaq_w + sumb_w
+      sumb_dwdt = bhaq_dwdt + sumb_dwdt
+      ta = time(i + 1)
+      tb = time(i + 2)
+   97 continue
+      fltng_w = sumb_w
+      fltng_dwdt = sumb_dwdt
+      return
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/what0.f
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/what0.f	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GiaDeflectionCorex/what0.f	(revision 18231)
@@ -0,0 +1,127 @@
+      subroutine what0(iedge,Ntimp,Ntimm,time,bi,dmi)
+      implicit double precision (a-h,o-z)
+      integer Ntimp,Ntimm
+      parameter (nhank = 1024)
+      parameter (N = nhank/2)
+      double precision dekay1(nhank),dekay2(nhank),amp0(nhank),
+     1amp1(nhank),amp2(nhank),amp3(nhank),amp4(nhank),
+     1zksam(nhank),zksamp(nhank)
+      double precision decay(2),pset(7),amps(5),
+     1decta(2),dyri1(nhank),dyri2(nhank),sna(nhank)
+      double precision cinner_w(nhank),cinner_dwdt(nhank)
+      double precision bcin_w(nhank),bcin_dwdt(nhank)
+      double precision time(Ntimp),bi(Ntimm),dmi(Ntimm)
+      integer maxk
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockp/ pset
+      common /blockz/ zkp
+      common /blockm/ dekay1,dekay2,amp0,amp1,amp2,amp3,amp4
+      data yearco /3.15576d7/, pi /3.1415926535897932384d0/
+      data g /9.832186d0/, four /4.d0/, two /2.0d0/,
+     1 one /1.0d0/, zero/0.0d0/ , maxk/64/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      twopi = two * pi
+      r2 = pset(6)
+      u2 = pset(4)
+      r1 = pset(5)
+      u1 = pset(3)
+      h  = pset(1)
+      urat = u1/u2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c  alphap is dimensionless disk radius
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      alphap = pset(7)/pset(1)
+      twoap = two * alphap
+      rghm = ( r1 * g * h * alphap ) / (two * u2)
+      taumx = pset(2)/pset(4)
+      tmxyr = taumx / yearco
+c
+      dfac = dfloat(nhank)/dfloat(maxk)
+      endk = dfloat(nhank)/dfac
+      dk = endk/dfloat(nhank)
+c
+      ak = zero
+      do 7000 ik = 1,nhank
+      ak = ak + dk
+      zkp = ak
+      pikn = (6.371d6 * zkp) / h
+      zkd = pikn / 6.371d6
+c
+      zkp2 = 2.0d0 * zkp
+      zkp4 = 4.0d0 * zkp
+      e1 = dexp(zkp)
+      e2 = dexp(zkp2)
+      e4 = dexp(zkp4)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      call freed(r2,u2,r1,u1,h,zkd,e1,e2,e4,b0,b1,a2,a1,a0,decay,amps)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decta(1) = decay(1)/tmxyr
+      decta(2) = decay(2)/tmxyr
+      dyri1(ik) = decta(1)
+      dyri2(ik) = decta(2)
+      sna(ik) = pikn
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Form vectors for full construction in pwise.f and stot.f
+c Note that freed will produce decay spectra defined as positive, 
+c ie. negative decay must reinsert a minus sign.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      dekay1(ik) = decay(1)
+      dekay2(ik) = decay(2)
+      amp0(ik) = amps(3)  
+      amp1(ik) = amps(1)  
+      amp2(ik) = amps(2)  
+      amp3(ik) = amps(4)  
+      amp4(ik) = amps(5)  
+      zksam(ik) = zkd
+      zksamp(ik) = zkp
+ 7000 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c The following looped call sets up the free solution convolved with the
+c load function q hat.  Note that the returned vector set "cinner" is the
+c inner-most part of the arguement of the inverse Hankel trans. integral.
+c It is time-dependent and the loop is for the k-dependancy. The time for
+c calculation is given in the vector "time(Ntimp)" in the routine stot.f that is
+c called below. Note that the sign on cinner(ik) below is for a load directed
+c downward.   ** For iedge = 1 assume sq. edge load and for iedge = 2 assume an
+c elliptical cross section.  Note loops 8500,8000 and 9500,9000 for the two
+c cases, respectively.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   49 go to (8499,9499), iedge
+ 8499 do 8000 ik = 1, nhank
+      xakap = zksamp(ik)*alphap
+      diku = xakap * urat
+      pref = diku / ( diku + rghm )
+      qjadon = one / ( four * zksamp(ik) * urat )
+      call stot(ik,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,time,bi,dmi)
+      cinner_w(ik) = - fltng_w * pref * twoap
+      cinner_dwdt(ik) = - fltng_dwdt * pref * twoap
+      bcin_w(ik) = cinner_w(ik) * dbesj1(xakap)
+      bcin_dwdt(ik) = cinner_dwdt(ik) * dbesj1(xakap)
+ 8000 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c "ojrule.f" computes the inverse Hankel trasform with a simple
+c Simpson's rule.  The routine "ojrule" is buliding a set of solutions stored
+c in common "blocks" in r or "asrpos(nrv) ", and computed rate or displacement
+c for each of N3G disks in "aswokm(nrv,N3G)" . 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      call ojrule(dk,bcin_w,bcin_dwdt)
+      go to 999
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+ 9499 do 9000 ik = 1, nhank
+      xakap = zksamp(ik)*alphap
+      oxakap = one/xakap
+      diku = xakap * urat
+      pref = diku / ( diku + rghm )
+      qjadon = one / ( four * zksamp(ik) * urat )
+      call stot(ik,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,time,bi,dmi)
+      cinner_w(ik) = - fltng_w * pref * twoap
+      cinner_dwdt(ik) = - fltng_dwdt * pref * twoap
+      bcin_w(ik) = cinner_w(ik) * oxakap * ( dsin(xakap) * oxakap
+     1 - dcos(xakap) )
+      bcin_dwdt(ik) = cinner_dwdt(ik) * oxakap * ( dsin(xakap) * oxakap
+     1 - dcos(xakap) )
+ 9000 continue
+      call ojrule(dk,bcin_w,bcin_dwdt)
+  999 return
+
+      end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.cpp	(revision 18231)
@@ -0,0 +1,86 @@
+/*!\file Gradjx
+ * \brief: compute inverse method gradient
+ */
+
+#include "./Gradjx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void Gradjx(Vector<IssmDouble>** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+
+	int          numberofvertices;
+	int          num_controls,analysisenum;
+	IssmDouble   norm_inf;
+	IssmDouble  *norm_list     = NULL;
+	int     *control_type  = NULL;
+	Vector<IssmDouble>  *gradient      = NULL;
+	Vector<IssmDouble> **gradient_list = NULL;
+
+	/*retrieve some parameters: */
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
+	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	numberofvertices=vertices->NumberOfVertices();
+
+	/*Get current analysis*/
+	parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+
+	/*Allocate gradient_list */
+	gradient_list = xNew<Vector<IssmDouble>*>(num_controls);
+	norm_list = xNew<IssmDouble>(num_controls);
+	for(int i=0;i<num_controls;i++){
+		gradient_list[i]=new Vector<IssmDouble>(num_controls*numberofvertices);
+	}
+	gradient=new Vector<IssmDouble>(num_controls*numberofvertices);
+
+	/*Compute all gradient_list*/
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<elements->Size();j++){
+			Element* element=(Element*)elements->GetObjectByOffset(j);
+			analysis->GradientJ(gradient_list[i],element,control_type[i],i);
+		}
+		gradient_list[i]->Assemble();
+		norm_list[i]=gradient_list[i]->Norm(NORM_INF);
+	}
+
+	/*Add all gradient_list together*/
+	for(int i=0;i<num_controls;i++){
+		gradient->AXPY(gradient_list[i],1.0);
+		delete gradient_list[i];
+	}
+
+	/*Check that gradient is clean*/
+	norm_inf=gradient->Norm(NORM_INF);
+	if(norm_inf<=0)                 _error_("||dJ/dk|| = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||dJ/dk|| = NaN  gradient norm is NaN");
+
+	/*Clean-up and assign output pointer*/
+	delete analysis;
+	xDelete<Vector<IssmDouble>*>(gradient_list);
+	xDelete<int>(control_type);
+	if(pnorm_list){
+		*pnorm_list=norm_list;
+	}
+	else{
+		xDelete<IssmDouble>(norm_list);
+	}
+	if(pgradient)  *pgradient=gradient;
+
+}
+void Gradjx(IssmDouble** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+
+	/*output: */
+	IssmDouble* gradient=NULL;
+
+	/*intermediary: */
+	Vector<IssmDouble>* vec_gradient=NULL;
+
+	Gradjx(&vec_gradient,pnorm_list,elements,nodes, vertices,loads,materials,parameters);
+	gradient=vec_gradient->ToMPISerial();
+
+	/*Free ressources:*/
+	delete vec_gradient;
+
+	/*Assign output pointers:*/
+	*pgradient=gradient;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Gradjx/Gradjx.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file:  Gradjx.h
+ * \brief header file for inverse methods gradient computation
+ */ 
+
+#ifndef _GRADJX_H
+#define _GRADJX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void Gradjx(Vector<IssmDouble>** pgrad_g,IssmDouble** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
+void Gradjx(IssmDouble** pgrad_g,IssmDouble** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
+
+#endif  /* _GRADJX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 18231)
@@ -0,0 +1,200 @@
+/*!\file GroundinglineMigrationx
+ * \brief: migration grounding line position.
+ */
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "./GroundinglineMigrationx.h"
+
+void GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
+
+	int                 migration_style,analysis_type;
+	IssmDouble         *vertices_potentially_ungrounding = NULL;
+	IssmDouble         *phi_ungrounding                  = NULL;
+	Element            *element                          = NULL;
+
+	if(VerboseModule()) _printf0_("   Migrating grounding line\n");
+
+	/*retrieve parameters: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if(migration_style==NoneEnum) return;
+
+	/*Set toolkit to default*/
+	ToolkitsOptionsFromAnalysis(parameters,DefaultAnalysisEnum);
+
+	switch(migration_style){
+		case SoftMigrationEnum:
+			/*Create flag for grounded vertices above the hydrostatic equilibrium: */
+			vertices_potentially_ungrounding=PotentialUngrounding(elements,vertices,parameters);
+			/*propagate ice shelf into connex areas of the ice sheet that potentially want to unground: */
+			phi_ungrounding=PropagateFloatingiceToGroundedNeighbors(elements,nodes,vertices,parameters,vertices_potentially_ungrounding);
+			break;
+		case ContactEnum:
+			phi_ungrounding=ContactFSLevelset(elements,vertices);
+			break;
+		case AggressiveMigrationEnum:
+		case SubelementMigrationEnum:
+		case SubelementMigration2Enum:
+			/*Nothing additional to do here, MigrateGroundingLine takes care of everything*/
+			break;
+		default:
+			_error_("Grounding line migration "<<EnumToStringx(migration_style) << " not supported yet!");
+	}
+
+	/*Migrate grounding line : */
+	for(int i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->MigrateGroundingLine(phi_ungrounding);
+	}
+
+	/*free ressouces: */
+	xDelete<IssmDouble>(vertices_potentially_ungrounding);
+	xDelete<IssmDouble>(phi_ungrounding);
+}
+
+IssmDouble*    ContactFSLevelset(Elements* elements,Vertices* vertices){ /*{{{*/
+
+	Vector<IssmDouble>* vertexgrounded = NULL;
+	Vector<IssmDouble>* vertexfloating = NULL;
+	IssmDouble*  serial_vertexgrounded = NULL;
+	IssmDouble*  serial_vertexfloating = NULL;
+	IssmDouble*  phi                   = NULL;
+
+	/*Initialize vector with number of vertices*/
+	int numberofvertices = vertices->NumberOfVertices();
+	vertexgrounded = new Vector<IssmDouble>(numberofvertices);
+	vertexfloating = new Vector<IssmDouble>(numberofvertices);
+	phi            = xNew<IssmDouble>(numberofvertices);
+
+	/*Fill vector vertices_potentially_floating: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->FSContactMigration(vertexgrounded,vertexfloating);
+	}
+
+	/*Assemble vector and serialize */
+	vertexgrounded->Assemble();
+	vertexfloating->Assemble();
+	serial_vertexgrounded=vertexgrounded->ToMPISerial();
+	serial_vertexfloating=vertexfloating->ToMPISerial();
+
+	/*find vertices on GL */
+	for(int i=0;i<numberofvertices;i++){
+		if(serial_vertexgrounded[i]==1. && serial_vertexfloating[i]==1.){
+			phi[i]=0.;
+		}
+		else if(serial_vertexgrounded[i]==1.){
+			phi[i]=1.;
+		}
+		else if(serial_vertexfloating[i]==1.){
+			phi[i]=-1.;
+		}
+		else{
+			phi[i]=9999.;
+		}
+	}
+
+	/*free ressouces and return: */
+	delete vertexgrounded;
+	delete vertexfloating;
+	xDelete<IssmDouble>(serial_vertexgrounded);
+	xDelete<IssmDouble>(serial_vertexfloating);
+
+	return phi;
+}
+/*}}}*/
+IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ /*{{{*/
+
+	int                 i,numberofvertices;
+	IssmDouble*         vertices_potentially_ungrounding      = NULL;
+	Vector<IssmDouble>* vec_vertices_potentially_ungrounding  = NULL;
+	Element*            element                               = NULL;
+
+	/*Initialize vector with number of vertices*/
+	numberofvertices=vertices->NumberOfVertices();
+	vec_vertices_potentially_ungrounding=new Vector<IssmDouble>(numberofvertices); //grounded vertex that could start floating
+
+	/*Fill vector vertices_potentially_floating: */
+	for(i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->PotentialUngrounding(vec_vertices_potentially_ungrounding);
+	}
+
+	/*Assemble vector and serialize */
+	vec_vertices_potentially_ungrounding->Assemble();
+	vertices_potentially_ungrounding=vec_vertices_potentially_ungrounding->ToMPISerial();
+
+	/*free ressouces and return: */
+	delete vec_vertices_potentially_ungrounding;
+	return vertices_potentially_ungrounding;
+}
+/*}}}*/
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ /*{{{*/
+	int                 i,analysis_type;
+	int                 nflipped,local_nflipped;
+	IssmDouble*         phi                                  = NULL;
+	IssmDouble*         elements_neighboring_floatingce      = NULL;
+	Vector<IssmDouble>* vec_elements_neighboring_floatingice = NULL;
+	Vector<IssmDouble>* vec_phi                              = NULL;
+	Element*            element                               = NULL;
+
+	/*recover parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*recover vec_phi*/
+	vec_phi=new Vector<IssmDouble>(vertices->NumberOfVertices());
+	for(i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->GetVectorFromInputs(vec_phi,MaskGroundediceLevelsetEnum);
+	}
+	vec_phi->Assemble();
+	phi=vec_phi->ToMPISerial();
+
+	nflipped=1; //bootstrap
+	while(nflipped){
+
+		/*Vector of size number of elements*/
+		vec_elements_neighboring_floatingice=new Vector<IssmDouble>(elements->NumberOfElements(),true);
+
+		/*Figure out if any of the nodes of the element will be floating -> elements neighbouting the floating ice*/
+		for(i=0;i<elements->Size();i++){
+			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+			vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(phi)?1.0:0.0,INS_VAL);
+		}
+
+		/*Assemble vector and serialize: */
+		vec_elements_neighboring_floatingice->Assemble();
+		elements_neighboring_floatingce=vec_elements_neighboring_floatingice->ToMPISerial();
+
+		/*Go through elements_neighboring_floatingce, and update vector of the nodes that will start floating*/
+		local_nflipped=0;
+		for(i=0;i<elements->Size();i++){
+			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
+				local_nflipped+=element->UpdatePotentialUngrounding(vertices_potentially_ungrounding,vec_phi,phi);
+			}
+		}
+		vec_phi->Assemble();
+
+		ISSM_MPI_Allreduce(&local_nflipped,&nflipped,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+		if(VerboseConvergence()) _printf0_("   Additional number of vertices allowed to unground: " << nflipped << "\n");
+
+		/*Avoid leaks: */
+		xDelete<IssmDouble>(elements_neighboring_floatingce);
+		xDelete<IssmDouble>(phi);
+
+		/*Assemble and serialize:*/
+		delete vec_elements_neighboring_floatingice;
+		phi=vec_phi->ToMPISerial();
+	}
+
+	/*Free ressources:*/
+	delete vec_phi;
+	xDelete<IssmDouble>(elements_neighboring_floatingce);
+
+	return phi;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 18231)
@@ -0,0 +1,18 @@
+/*!\file:  GroundinglineMigrationx.h
+ * \brief header file for Grounding Line Migration
+ */ 
+
+#ifndef _GROUNDINGLINEMIGRATIONX_H
+#define _GROUNDINGLINEMIGRATIONX_H
+
+class Elements;
+class Vertices;
+class Nodes;
+class Parameters;
+
+/* local prototypes: */
+void         GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
+IssmDouble*  ContactFSLevelset(Elements* elements,Vertices* vertices);
+IssmDouble*  PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
+IssmDouble*  PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding);
+#endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 18231)
@@ -0,0 +1,17 @@
+/*!\file InputControlUpdatex
+ * \brief: Y=Y+aX operation on inputs.
+ */
+
+#include "./InputControlUpdatex.h"
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,IssmDouble scalar,bool save_parameter){
+
+	/*Go through elemnets, and ask to carry out the operation on inputs: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->InputControlUpdate(scalar,save_parameter);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputControlUpdatex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTCONTROLUPDATEX_H
+#define _INPUTCONTROLUPDATEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, IssmDouble scalar,bool save_parameter);
+
+#endif 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file InputDepthAverageAtBasex
+ * \brief: extrude input
+ */
+
+#include "./InputDepthAverageAtBasex.h"
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+void InputDepthAverageAtBasex(FemModel* femmodel,int original_enum, int new_enum){
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputDepthAverageAtBase(original_enum,new_enum);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputDepthAverageAtBasex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTDEPTHAVERAGEATBASEX_H
+#define _INPUTDEPTHAVERAGEATBASEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputDepthAverageAtBasex(FemModel* femmodel,int reinitialized_enum, int original_enum);
+
+#endif  /* _INPUTDUPLICATEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 18231)
@@ -0,0 +1,16 @@
+/*!\file InputDuplicatex
+ * \brief: duplicte  an input inside the elements, onto another, and wipe it off.
+ */
+
+#include "./InputDuplicatex.h"
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+void InputDuplicatex(FemModel* femmodel,int original_enum, int new_enum){
+	/*Go through elemnets, and ask to reinitialie the input: */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputDuplicate(original_enum,new_enum);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputDuplicatex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTDUPLICATEX_H
+#define _INPUTDUPLICATEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputDuplicatex(FemModel* femmodel,int reinitialized_enum, int original_enum);
+
+#endif  /* _INPUTDUPLICATEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.cpp	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file InputExtrudex
+ * \brief: extrude input
+ */
+
+#include "./InputExtrudex.h"
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+void InputExtrudex(FemModel* femmodel,int input_enum){
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputExtrude(input_enum);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputExtrudex/InputExtrudex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputExtrudex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTEXTRUDEX_H
+#define _INPUTEXTRUDEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputExtrudex(FemModel* femmodel,int input_enum);
+
+#endif  /* _INPUTDUPLICATEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.cpp	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file InputScalex
+ * \brief: duplicte  an input inside the elements, onto another, and wipe it off.
+ */
+
+#include "./InputScalex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, IssmDouble scale_factor){
+
+	/*intermediary:*/
+	int      i;
+
+	/*Go through elemnets, and ask to reinitialie the input: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->InputScale(enum_type,scale_factor);
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputScalex/InputScalex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputScalex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _SCALEINPUTX_H
+#define _SCALEINPUTX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, IssmDouble scale_factor);
+
+#endif  /* _SCALEINPUTX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 18231)
@@ -0,0 +1,83 @@
+/*!\file InputUpdateFromConstantx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromConstantx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void InputUpdateFromConstantx(FemModel* femmodel,bool constant, int name){
+
+	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+}
+void InputUpdateFromConstantx(FemModel* femmodel,int constant, int name){
+
+	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+}
+void InputUpdateFromConstantx(FemModel* femmodel,IssmDouble constant, int name){
+
+	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+
+}
+void InputUpdateFromConstantx(Elements* elements,IssmDouble constant, int name){
+
+	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->InputUpdateFromConstant(constant,name);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 18231)
@@ -0,0 +1,16 @@
+/*!\file:  InputUpdateFromConstantx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMCONSTANTXX_H
+#define _UPDATEINPUTSFROMCONSTANTXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputUpdateFromConstantx(FemModel* femmodel,bool       constant,int name);
+void InputUpdateFromConstantx(FemModel* femmodel,int        constant,int name);
+void InputUpdateFromConstantx(FemModel* femmodel,IssmDouble constant,int name);
+void InputUpdateFromConstantx(Elements* elements,IssmDouble constant,int name);
+
+#endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 18231)
@@ -0,0 +1,108 @@
+/*!\file InputUpdateFromDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromDakotax.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+#include "../InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
+
+void InputUpdateFromDakotax(FemModel* femmodel,double* variables,char* *variables_descriptors,int numvariables){
+
+	int     i,j,k,l;
+	int     dummy;
+
+	int     numberofvertices;
+	int     nrows;
+	int     ncols;
+	int     npart;
+	double *qmu_part  = NULL;
+
+	double *distributed_values = NULL;
+	double *parameter          = NULL;
+	char   *descriptor         = NULL;
+	char    root[50]; //root name of variable, ex: DragCoefficent, RhoIce, etc ...
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+	femmodel->parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
+
+	/*Go through all dakota descriptors, ex: "rho_ice","thermal_conductivity","thickness1","thickness2", etc ..., and 
+	 * for each descriptor, take the variable value and plug it into the inputs: */
+
+	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);
+			for(j=0;j<npart;j++){
+				distributed_values[j]=variables[i+j];
+			}
+
+			/*Now, pick up the parameter corresponding to root: */
+			femmodel->parameters->FindParam(&parameter,&nrows,&ncols,StringToEnumx(root));
+
+			/*We've got the parameter, we need to update it using qmu_part (a partitioning vector), 
+			 * and the distributed_values. Two cases: we either have a nrows=numberofvertices, in 
+			 * which case our parameter is a vector, or nrows=numberofvertices+1, in which case, 
+			 * our parameter is a transient vector. Deal with both cases accordingly: */
+			for(k=0;k<numberofvertices;k++){
+				for(l=0;l<ncols;l++){
+					*(parameter+ncols*k+l)=*(parameter+ncols*k+l)*distributed_values[(int)qmu_part[k]];
+				}
+			}
+
+			#ifdef _DEBUG_
+				PetscSynchronizedPrintf(IssmComm::GetComm(),"Parameter matrix:");
+				PetscSynchronizedFlush(IssmComm::GetComm());
+				for(l=0;l<ncols;l++){
+					PetscSynchronizedPrintf(IssmComm::GetComm()," time %i\n",l);
+					PetscSynchronizedFlush(IssmComm::GetComm());
+
+					for(k=0;k<numberofvertices;k++){
+						PetscSynchronizedPrintf(IssmComm::GetComm()," node %i value %g\n",k+1,*(parameter+k*ncols+l));
+						PetscSynchronizedFlush(IssmComm::GetComm());
+					}
+				}
+				PetscSynchronizedPrintf(IssmComm::GetComm()," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
+				PetscSynchronizedFlush(IssmComm::GetComm());
+			#endif
+
+			/*Update inputs using the parameter matrix: */
+			InputUpdateFromMatrixDakotax(femmodel, parameter, nrows,ncols,StringToEnumx(root), VertexEnum);
+
+			/*increment i to skip the distributed values just collected: */
+			i+=npart-1; //careful, the for loop will add 1.
+
+			/*Free allocations: */
+			xDelete<double>(parameter);
+			xDelete<double>(distributed_values);
+		}
+		else if (strncmp(descriptor,"indexed_",8)==0){
+			_error_("indexed variables not supported yet!");
+		}
+		else if (strncmp(descriptor,"nodal_",8)==0){
+			_error_("nodal variables not supported yet!");
+		}
+		else{
+			/*Ok, standard variable, just update inputs using the variable: */
+			InputUpdateFromConstantx(femmodel,variables[i],StringToEnumx(descriptor));
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<double>(qmu_part);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  InputUpdateFromDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _INPUTUPDATEFROMDAKOTAXX_H
+#define _INPUTUPDATEFROMDAKOTAXX_H
+
+#include "../../classes/classes.h"
+
+void  InputUpdateFromDakotax(FemModel* femmodel,double* variables,char* *variables_descriptors,int numvariables);
+
+#endif  /* _INPUTUPDATEFROMDAKOTAXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 18231)
@@ -0,0 +1,34 @@
+/*!\file InputUpdateFromMatrixDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromMatrixDakotax.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
+
+void InputUpdateFromMatrixDakotax(FemModel* femmodel,double* matrix,int nrows,int ncols, int name, int type){
+
+	int i;
+	int numberofvertices;
+
+	numberofvertices=femmodel->vertices->NumberOfVertices();
+
+	if((ncols==1) && (nrows==numberofvertices)) InputUpdateFromVectorDakotax(femmodel,matrix,name,type);
+	else{
+
+		/*Update elements, nodes, loads and materials from inputs: */
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+		for(i=0;i<femmodel->loads->Size();i++){
+			Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+			load->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+		for(i=0;i<femmodel->materials->Size();i++){
+			Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+			material->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InputUpdateFromMatrixDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
+#define _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void InputUpdateFromMatrixDakotax(FemModel* femmodel,double* matrix,int nrows,int ncols, int name, int type);
+
+#endif  /* _UPDATEINPUTSFROMMATRIXDAKOTAXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file InputUpdateFromSolutionx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromSolutionx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void InputUpdateFromSolutionx(FemModel* femmodel,Vector<IssmDouble>* solution){
+
+	/*Serialize solution, so that elements can index into it on every CPU: */
+	IssmDouble* serial_solution=solution->ToMPISerial();
+
+	/*Call overloaded form of InputUpdateFromSolutionx: */
+	InputUpdateFromSolutionx(femmodel,serial_solution);
+
+	/*cleanup and return*/
+	xDelete<IssmDouble>(serial_solution);
+}
+
+void InputUpdateFromSolutionx(FemModel* femmodel,IssmDouble* solution){
+
+	/*retrive parameters: */
+	int analysisenum;
+	femmodel->parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		analysis->InputUpdateFromSolution(solution,element);
+	}
+	delete analysis;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file:  InputUpdateFromSolutionx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMSOLUTIONXX_H
+#define _UPDATEINPUTSFROMSOLUTIONXX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void	InputUpdateFromSolutionx(FemModel* femmodel,Vector<IssmDouble>* solution);
+void  InputUpdateFromSolutionx(FemModel* femmodel,IssmDouble* solution);
+
+#endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*!\file InputUpdateFromVectorDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromVectorDakotax.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void InputUpdateFromVectorDakotax(FemModel* femmodel,Vector<IssmDouble>* vector, int name, int type){
+
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	InputUpdateFromVectorDakotax(femmodel,serial_vector,name, type);
+
+	/*Free ressources:*/
+	xDelete<double>(serial_vector);
+}
+
+void InputUpdateFromVectorDakotax(FemModel* femmodel,IssmDouble* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		load->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+		material->InputUpdateFromVectorDakota(vector,name,type);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  InputUpdateFromVectorDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMVECTORDAKOTAXX_H
+#define _UPDATEINPUTSFROMVECTORDAKOTAXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	InputUpdateFromVectorDakotax(FemModel* femmodel,Vector<IssmDouble>* vector, int name,int type);
+void	InputUpdateFromVectorDakotax(FemModel* femmodel,IssmDouble* vector, int name,int type);
+
+#endif  /* _UPDATEINPUTSFROMVECTORDAKOTAXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file InputUpdateFromVectorx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromVectorx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void InputUpdateFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector, int name, int type){
+
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,serial_vector,name,type);
+	xDelete<IssmDouble>(serial_vector);
+}
+
+void InputUpdateFromVectorx(FemModel* femmodel,IssmDouble* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		load->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
+		material->InputUpdateFromVector(vector,name,type);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  InputUpdateFromVectorx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMVECTORXX_H
+#define _UPDATEINPUTSFROMVECTORXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	InputUpdateFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector, int name,int type);
+void	InputUpdateFromVectorx(FemModel* femmodel,IssmDouble* vector, int name,int type);
+
+#endif  /* _UPDATEINPUTSFROMVECTORXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 18231)
@@ -0,0 +1,317 @@
+/*!\file:  InterpFromGridToMeshx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+/*Include {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./InterpFromGridToMeshx.h"
+#include "../../shared/shared.h"
+#include "../../shared/io/io.h"
+/*}}}*/
+
+/*InterpFromGridToMeshx{{{*/
+int InterpFromGridToMeshx(IssmSeqVec<IssmPDouble>** pdata_mesh,double* x_in, int x_rows, double* y_in, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods,double default_value, int interpenum){
+
+	/*output: */
+	IssmSeqVec<IssmPDouble>* data_mesh=NULL;
+
+	/*Intermediary*/
+	double* x=NULL;
+	double* y=NULL;
+	int     i;
+
+	/*Some checks on arguments: */
+	if ((M<2) || (N<2) || (nods<=0)){
+		_error_("nothing to be done according to the dimensions of input matrices and vectors.");
+	}
+	if (x_in[1]-x_in[0]<0){
+		_error_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
+	}
+	if (y_in[1]-y_in[0]<0){
+		_error_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
+	}
+
+	/*Allocate output vector: */
+	data_mesh=new IssmSeqVec<IssmPDouble>(nods);
+
+	/*Find out what kind of coordinates (x_in,y_in) have been given is input*/
+	if(N==(x_rows-1) && M==(y_rows-1)){
+
+		/*The coordinates given in input describe the contour of each pixel. Take the center of each pixel*/
+		x=xNew<double>(N);
+		y=xNew<double>(M);
+		for(i=0;i<N;i++) x[i]=(x_in[i]+x_in[i+1])/2.;
+		for(i=0;i<M;i++) y[i]=(y_in[i]+y_in[i+1])/2.;
+		x_rows=x_rows-1;
+		y_rows=y_rows-1;
+	}
+	else if (N==x_rows && M==y_rows){
+
+		/*The coordinates given in input describe the center each pixel. Keep them*/
+		x=xNew<double>(N);
+		y=xNew<double>(M);
+		for(i=0;i<N;i++) x[i]=x_in[i];
+		for(i=0;i<M;i++) y[i]=y_in[i];
+	}
+	else{
+		_error_("x and y vectors length should be 1 or 0 more than data number of rows.");
+	}
+
+	/*initialize thread parameters: */
+	InterpFromGridToMeshxThreadStruct gate;
+	gate.x_mesh        = x_mesh;
+	gate.y_mesh        = y_mesh;
+	gate.x_rows        = x_rows;
+	gate.y_rows        = y_rows;
+	gate.x             = x;
+	gate.y             = y;
+	gate.nods          = nods;
+	gate.data_mesh     = data_mesh;
+	gate.data          = data;
+	gate.default_value = default_value;
+	gate.interp        = interpenum;
+	gate.M             = M;
+	gate.N             = N;
+
+	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
+	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,_NUMTHREADS_);
+	_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+
+	/*Assign output pointers:*/
+	*pdata_mesh=data_mesh;
+	return 1;
+}
+/*}}}*/
+/*InterpFromGridToMeshxt {{{*/
+void* InterpFromGridToMeshxt(void* vpthread_handle){
+
+	/*gate variables :*/
+	InterpFromGridToMeshxThreadStruct *gate    = NULL;
+	pthread_handle                    *handle  = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*intermediary: */
+	int    i,m,n;
+	double x_grid;
+	double y_grid;
+	double data_value;
+	double x1,x2,y1,y2;
+	double Q11,Q12,Q21,Q22;
+
+	/*recover handle and gate: */
+	handle=(pthread_handle*)vpthread_handle;
+	gate=(InterpFromGridToMeshxThreadStruct*)handle->gate;
+	my_thread=handle->id;
+	num_threads=handle->num;
+
+	/*recover parameters :*/
+	double *x_mesh                = gate->x_mesh;
+	double *y_mesh                = gate->y_mesh;
+	int     x_rows                = gate->x_rows;
+	int     y_rows                = gate->y_rows;
+	double *x                     = gate->x;
+	double *y                     = gate->y;
+	int     nods                  = gate->nods;
+	IssmSeqVec<IssmPDouble>*data_mesh = gate->data_mesh;
+	double *data                  = gate->data;
+	double  default_value         = gate->default_value;
+	int     interpenum            = gate->interp;
+	int     M                     = gate->M;
+	int     N                     = gate->N;
+
+	bool debug = M*N>1? true:false;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+	for (i=i0;i<i1;i++) {
+
+		if(debug && my_thread==0)
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
+		x_grid=*(x_mesh+i);
+		y_grid=*(y_mesh+i);
+
+		/*Find indices m and n into y and x, for which  y(m)<=y_grids<=y(m+1) and x(n)<=x_grid<=x(n+1)*/
+		if(findindices(&n,&m,x,x_rows, y,y_rows, x_grid,y_grid)){
+
+			/*    Q12             Q22
+			 * y2 x---------+-----x
+			 *    |         |     |
+			 *    |         |P    |
+			 *    |---------+-----|
+			 *    |         |     |
+			 *    |         |     |
+			 * y1 x---------+-----x Q21
+			 *    x1                 x2       
+			 *
+			 */
+			x1=x[n]; x2=x[n+1];
+			y1=y[m]; y2=y[m+1];
+			Q11=data[m*N+n];
+			Q12=data[(m+1)*N+n];
+			Q21=data[m*N+n+1];
+			Q22=data[(m+1)*N+n+1];
+
+			switch(interpenum){
+				case TriangleInterpEnum:
+					data_value=triangleinterp(x1,x2,y1,y2,Q11,Q12,Q21,Q22,x_grid,y_grid);
+					break;
+				case BilinearInterpEnum:
+					data_value=bilinearinterp(x1,x2,y1,y2,Q11,Q12,Q21,Q22,x_grid,y_grid);
+					break;
+				case NearestInterpEnum:
+					data_value=nearestinterp(x1,x2,y1,y2, Q11,Q12,Q21,Q22,x_grid,y_grid);
+					break;
+				default:
+					_printf_("Interpolation " << EnumToStringx(interpenum) << " not supported yet\n");
+					return NULL; /*WARNING: no error because it would blow up the multithreading!*/
+			}
+			if(xIsNan<IssmPDouble>(data_value)) data_value=default_value;
+		}
+		else{
+			data_value=default_value;
+		}
+
+		data_mesh->SetValue(i,data_value,INS_VAL);
+	}
+
+	return NULL;
+}/*}}}*/
+
+/*findindices {{{*/
+bool findindices(int* pn,int* pm,double* x,int x_rows, double* y,int y_rows, double xgrid,double ygrid){
+
+	bool foundx=false,foundy=false;
+	int m=-1,n=-1;
+	int i;
+
+	for (i=0;i<x_rows-1;i++){
+		if ((x[i]<=xgrid) && (xgrid<x[i+1])){
+			n=i;
+			foundx=true;
+			break;
+		}
+	}
+	if(xgrid==x[x_rows-1]){
+		n=x_rows-2;
+		foundx=true;
+	}
+
+	for (i=0;i<y_rows-1;i++){
+		if ((y[i]<=ygrid) && (ygrid<y[i+1])){
+			m=i;
+			foundy=true;
+			break;
+		}
+	}
+	if(ygrid==y[y_rows-1]){
+		m=y_rows-2;
+		foundy=true;
+	}
+
+	/*Assign output pointers:*/
+	*pm=m; *pn=n;
+	return (foundx && foundy);
+}/*}}}*/
+/*triangleinterp{{{*/
+double triangleinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
+	/*split the rectangle in 2 triangle and
+	 * use Lagrange P1 interpolation
+	 *       
+	 *   +3----+2,3' Q12----Q22
+	 *   |    /|     |    /|
+	 *   |   / |     |   / |
+	 *   |  /  |     |  /  |
+	 *   | /   |     | /   |
+	 *   |/    |     |/    |
+	 *   1-----2'    Q11---Q21        */
+
+	/*Intermediaries*/
+	double area,area_1,area_2,area_3;
+
+	/*Checks*/
+	_assert_(x2>x1 && y2>y1);
+	_assert_(x<=x2 && x>=x1 && y<=y2 && y>=y1);
+
+	/*area of the rectangle*/
+	area=(x2-x1)*(y2-y1);
+
+	/*is it the upper left triangle?*/
+	if ((x-x1)/(x2-x1)<(y-y1)/(y2-y1)){
+
+		area_1=((y2-y)*(x2-x1))/area;
+		area_2=((x-x1)*(y2-y1))/area;
+		area_3=1-area_1-area_2;
+
+		return area_1*Q11+area_2*Q22+area_3*Q12;
+	}
+	else {
+
+		area_1=((y-y1)*(x2-x1))/area;
+		area_2=((x2-x)*(y2-y1))/area;
+		area_3=1-area_1-area_2;
+
+		return area_1*Q22+area_2*Q11+area_3*Q21;
+	}
+}/*}}}*/
+/*bilinearinterp{{{*/
+double bilinearinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
+	/*Bilinear  interpolation: (http://en.wikipedia.org/wiki/Bilinear_interpolation) */
+
+	/*    Q12    R2        Q22
+	 * y2 x------x---------x
+	 *    |      |         |
+	 *    |      |         |
+	 *    |      +P        |
+	 *    |      |         |
+	 *    |Q11   R1        Q21
+	 * y1 x------x---------x
+	 *    x1               x2
+	 *
+	 */
+
+	/*Checks*/
+	_assert_(x2>x1 && y2>y1);
+	_assert_(x<=x2 && x>=x1 && y<=y2 && y>=y1);
+
+	return 
+	  +Q11*(x2-x)*(y2-y)/((x2-x1)*(y2-y1))
+	  +Q21*(x-x1)*(y2-y)/((x2-x1)*(y2-y1))
+	  +Q12*(x2-x)*(y-y1)/((x2-x1)*(y2-y1))
+	  +Q22*(x-x1)*(y-y1)/((x2-x1)*(y2-y1));
+}
+/*}}}*/
+/*nearestinterp{{{*/
+double nearestinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
+	/*Nearest neighbor interpolation*/
+
+	/*    Q12             Q22
+	 * y2 x--------x---------x
+	 *    |        |         |
+	 *    |        |  xP     |
+	 * ym |--------+---------|
+	 *    |        |         |
+	 *    |        |         |
+	 * y1 x--------x---------x Q21
+	 *    x1       xm        x2 
+	 *
+	 */
+	/*Checks*/
+	_assert_(x2>x1 && y2>y1);
+	_assert_(x<=x2 && x>=x1 && y<=y2 && y>=y1);
+
+	double xm=(x2-x1)/2;
+	double ym=(y2-y1)/2;
+
+	if (x<xm && y<ym) return Q11;
+	if (x<xm && y>ym) return Q12;
+	if (x>xm && y<ym) return Q21;
+	else return Q22;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*!\file InterpFromGridToMeshx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMGRIDTOMESHX_H
+#define _INTERPFROMGRIDTOMESHX_H
+
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+#include "../../shared/shared.h"
+
+/*threading: */
+typedef struct{
+	double*             x;
+	int                 x_rows;
+	double*             y;
+	int                 y_rows;
+	double*             data;
+	double              default_value;
+	int                 interp;
+	int                 M;
+	int                 N;
+	int                 nods;
+	double*             x_mesh;
+	double*             y_mesh;
+	IssmSeqVec<IssmPDouble>* data_mesh;
+} InterpFromGridToMeshxThreadStruct;
+
+int    InterpFromGridToMeshx(IssmSeqVec<IssmPDouble>** pdata_mesh,double* x, int x_rows, double* y, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods, double default_value, int interpenum=BilinearInterpEnum);
+void*  InterpFromGridToMeshxt(void* vInterpFromGridToMeshxThreadStruct);
+bool   findindices(int* pn,int* pm,double* x,int x_rows, double* y,int y_rows, double xgrid,double ygrid);
+double triangleinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y);
+double bilinearinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y);
+double nearestinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y);
+
+#endif /* _INTERPFROMGRIDTOMESHX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 18231)
@@ -0,0 +1,105 @@
+/*!\file:  InterpFromMesh2dx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMesh2dx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../ContourToNodesx/ContourToNodesx.h"
+
+int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,
+			double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length,
+			double* x_prime, double* y_prime, int nods_prime,
+			double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours){
+
+	/*Output*/
+	IssmSeqVec<IssmPDouble>* data_prime=NULL;
+
+	/*Intermediary*/
+	int    i;
+	int    interpolation_type;
+	bool   debug;
+	double xmin,xmax;
+	double ymin,ymax;
+
+	/*contours: */
+	double *incontour     = NULL;
+
+	/*some checks*/
+	if (nels_data<1 || nods_data<3 || nods_prime==0){
+		_error_("nothing to be done according to the mesh given in input");
+	}
+
+	/*Set debug to 1 if there are lots of elements*/
+	debug=(bool)((double)nels_data*(double)nods_prime >= pow((double)10,(double)9));
+
+	/*figure out what kind of interpolation is needed*/
+	if (data_length==nods_data){
+		interpolation_type=1;
+	}
+	else if (data_length==nels_data){
+		interpolation_type=2;
+	}
+	else{
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+	}
+
+	if((numcontours) && (interpolation_type==2)){
+		_error_("element interpolation_type with contours not supported yet!");
+	}
+
+	/*Get prime mesh extrema coordinates*/
+	xmin=x_prime[0]; xmax=x_prime[0];ymin=y_prime[0]; ymax=y_prime[0];
+	for (i=1;i<nods_prime;i++){
+		if (x_prime[i]<xmin) xmin=x_prime[i];
+		if (x_prime[i]>xmax) xmax=x_prime[i];
+		if (y_prime[i]<ymin) ymin=y_prime[i];
+		if (y_prime[i]>ymax) ymax=y_prime[i];
+	}
+
+	/*Initialize output*/
+	data_prime=new IssmSeqVec<IssmPDouble>(nods_prime);
+	if(num_default_values){
+		if(num_default_values==1)for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_values[0],INS_VAL);
+		else for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_values[i],INS_VAL);
+	}
+
+	/*Build indices of contour: */
+	if(numcontours){
+		ContourToNodesx( &incontour,x_prime,y_prime,nods_prime,contours,numcontours,1);
+	}
+	else{
+		 incontour=xNew<double>(nods_prime);
+		 for (i=0;i<nods_prime;i++) incontour[i]=1.0;
+	}
+
+	/*initialize thread parameters: */
+	InterpFromMesh2dxThreadStruct gate;
+	gate.interpolation_type = interpolation_type;
+	gate.debug              = debug;
+	gate.nels_data          = nels_data;
+	gate.index_data         = index_data;
+	gate.x_data             = x_data;
+	gate.y_data             = y_data;
+	gate.data               = data;
+	gate.xmin               = xmin;
+	gate.xmax               = xmax;
+	gate.ymin               = ymin;
+	gate.ymax               = ymax;
+	gate.nods_prime         = nods_prime;
+	gate.data_prime         = data_prime;
+	gate.x_prime            = x_prime;
+	gate.y_prime            = y_prime;
+	gate.default_values     = default_values;
+	gate.num_default_values = num_default_values;
+	gate.incontour          = incontour;
+
+	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
+	LaunchThread(InterpFromMesh2dxt,(void*)&gate,_NUMTHREADS_);
+
+	/*Assign output pointers:*/
+	 xDelete<double>(incontour);
+	*pdata_prime=data_prime;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 18231)
@@ -0,0 +1,38 @@
+/*!\file InterpFromMesh2dx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMMESH2DX_H
+#define _INTERPFROMMESH2DX_H
+
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+/*threading: */
+typedef struct{
+
+	int                 interpolation_type;
+	bool                debug;
+	int                 nels_data;
+	double              *index_data;
+	double              *x_data;
+	double              *y_data;
+	double              *data;
+	double              xmin,xmax;
+	double              ymin,ymax;
+	int                 nods_prime;
+	IssmSeqVec<IssmPDouble> *data_prime;
+	double              *x_prime;
+	double              *y_prime;
+	double              *default_values;
+	int                 num_default_values;
+	double              *incontour;
+
+} InterpFromMesh2dxThreadStruct;
+
+int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+		double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours);
+
+void* InterpFromMesh2dxt(void* vInterpFromMesh2dxThreadStruct);
+
+#endif /* _INTERPFROMMESH2DX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 18231)
@@ -0,0 +1,103 @@
+/*!\file:  InterpFromMesh2dxt.cpp
+ * \brief  thread core for InterpFromMesh2dxt code
+ */ 
+
+#include "./InterpFromMesh2dx.h"
+#include "../../shared/shared.h"
+
+void* InterpFromMesh2dxt(void* vpthread_handle){
+
+	/*intermediary: */
+	int     i0,i1,i,j;
+	double  area,area_1,area_2,area_3;
+	double  data_value;
+
+	/*recover handle and gate: */
+	pthread_handle                *handle      = (pthread_handle*)vpthread_handle;
+	InterpFromMesh2dxThreadStruct *gate        = (InterpFromMesh2dxThreadStruct*)handle->gate;
+	int                            my_thread   = handle->id;
+	int                            num_threads = handle->num;
+
+	/*recover parameters :*/
+	int     interpolation_type      = gate->interpolation_type;
+	bool    debug                   = gate->debug;
+	int     nels_data               = gate->nels_data;
+	double *index_data              = gate->index_data;
+	double *x_data                  = gate->x_data;
+	double *y_data                  = gate->y_data;
+	double *data                    = gate->data;
+	double  xmin                    = gate->xmin;
+	double  xmax                    = gate->xmax;
+	double  ymin                    = gate->ymin;
+	double  ymax                    = gate->ymax;
+	int     nods_prime              = gate->nods_prime;
+	IssmSeqVec<IssmPDouble>* data_prime = gate->data_prime;
+	double *x_prime                 = gate->x_prime;
+	double *y_prime                 = gate->y_prime;
+	double *default_values          = gate->default_values;
+	int     num_default_values      = gate->num_default_values;
+	double *incontour               = gate->incontour;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nels_data,num_threads,my_thread);
+
+	/*Loop over the elements*/
+	for(i=i0;i<i1;i++){
+
+		/*display current iteration*/
+		if (debug && my_thread==0 && fmod((double)i,(double)100)==0)
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
+
+		/*if there is no point inside the domain, go to next iteration*/
+		if ( (x_data[(int)index_data[3*i+0]-1]<xmin) && (x_data[(int)index_data[3*i+1]-1]<xmin) && (x_data[(int)index_data[3*i+2]-1]<xmin)) continue;
+		if ( (x_data[(int)index_data[3*i+0]-1]>xmax) && (x_data[(int)index_data[3*i+1]-1]>xmax) && (x_data[(int)index_data[3*i+2]-1]>xmax)) continue;
+		if ( (y_data[(int)index_data[3*i+0]-1]<ymin) && (y_data[(int)index_data[3*i+1]-1]<ymin) && (y_data[(int)index_data[3*i+2]-1]<ymin)) continue;
+		if ( (y_data[(int)index_data[3*i+0]-1]>ymax) && (y_data[(int)index_data[3*i+1]-1]>ymax) && (y_data[(int)index_data[3*i+2]-1]>ymax)) continue;
+
+		/*get area of the current element (Jacobian = 2 * area)*/
+		//area =x2 * y3 - y2*x3 + x1 * y2 - y1 * x2 + x3 * y1 - y3 * x1;
+		area=x_data[(int)index_data[3*i+1]-1]*y_data[(int)index_data[3*i+2]-1]-y_data[(int)index_data[3*i+1]-1]*x_data[(int)index_data[3*i+2]-1]
+		  +  x_data[(int)index_data[3*i+0]-1]*y_data[(int)index_data[3*i+1]-1]-y_data[(int)index_data[3*i+0]-1]*x_data[(int)index_data[3*i+1]-1]
+		  +  x_data[(int)index_data[3*i+2]-1]*y_data[(int)index_data[3*i+0]-1]-y_data[(int)index_data[3*i+2]-1]*x_data[(int)index_data[3*i+0]-1];
+
+		/*loop over the prime nodes*/
+		for (j=0;j<nods_prime;j++){
+
+			if(incontour[j]){
+
+				/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+				area_1=((x_prime[j]-x_data[(int)index_data[3*i+2]-1])*(y_data[(int)index_data[3*i+1]-1]-y_data[(int)index_data[3*i+2]-1]) 
+						-  (y_prime[j]-y_data[(int)index_data[3*i+2]-1])*(x_data[(int)index_data[3*i+1]-1]-x_data[(int)index_data[3*i+2]-1]))/area;
+				/*Get second area coordinate =det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+				area_2=((x_data[(int)index_data[3*i+0]-1]-x_data[(int)index_data[3*i+2]-1])*(y_prime[j]-y_data[(int)index_data[3*i+2]-1]) 
+						- (y_data[(int)index_data[3*i+0]-1]-y_data[(int)index_data[3*i+2]-1])*(x_prime[j]-x_data[(int)index_data[3*i+2]-1]))/area;
+				/*Get third area coordinate = 1-area1-area2*/
+				area_3=1-area_1-area_2;
+
+				/*is the current point in the current element?*/
+				if (area_1>=0 && area_2>=0 && area_3>=0){
+
+					/*Yes ! compute the value on the point*/
+					if (interpolation_type==1){
+						/*nodal interpolation*/
+						data_value=area_1*data[(int)index_data[3*i+0]-1]+area_2*data[(int)index_data[3*i+1]-1]+area_3*data[(int)index_data[3*i+2]-1];
+					}
+					else{
+						/*element interpolation*/
+						data_value=data[i];
+					}
+					if (xIsNan<IssmPDouble>(data_value)){
+						if(num_default_values==1) data_value=default_values[0];
+						else data_value=default_values[j];
+					}
+
+					/*insert value and go to the next point*/
+					data_prime->SetValue(j,data_value,INS_VAL);
+				}
+			}
+		}
+	}
+	if(debug && my_thread==0)
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+	return NULL;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 18231)
@@ -0,0 +1,178 @@
+/*!\file:  InterpFromMeshToGridx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMeshToGridx.h"
+#include "../../shared/shared.h"
+
+void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value) {
+
+	/*Output*/
+	double* griddata=NULL;
+	double* x_grid=NULL;
+	double* y_grid=NULL;
+
+	/*Intermediary*/
+	int    i,j,n;
+	int    i1,i2,j1,j2;
+	int    interpolation_type;
+	bool   debug;
+	int    xflip,yflip;
+	double area;
+	double area_1,area_2,area_3;
+	double x_tria_min,y_tria_min;
+	double x_tria_max,y_tria_max;
+	double x_grid_min,y_grid_min;
+	double x_grid_max,y_grid_max;
+	double data_value;
+
+	/*some checks*/
+	if (nels<1 || nods<3 || nlines<1 || ncols<1 || xposting==0 || yposting==0){
+		_error_("nothing to be done according to the mesh given in input");
+	}
+
+	/*figure out what kind of interpolation is needed*/
+	if (data_length==nods){
+		interpolation_type=1;
+	}
+	else if (data_length==nels){
+		interpolation_type=2;
+	}
+	else{
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+	}
+
+	/*First, allocate pointers: */
+	griddata=xNewZeroInit<double>(nlines*ncols);
+	x_grid=xNewZeroInit<double>(ncols);
+	y_grid=xNewZeroInit<double>(nlines);
+
+	/*Set debug to 1 if there are lots of elements*/
+	debug=(bool)((double)ncols*nlines*nels >= 5*pow(10.,10.));
+
+	/*Initialize coordintes and griddata*/
+	for(i=0;i<nlines;i++){
+		for(j=0;j<ncols; j++){
+			griddata[i*ncols+j]=default_value;
+		}
+	}
+	/*figure out if x or y are flipped*/
+	if (xposting<0) xflip=1;
+	else xflip=0;
+	if (yposting<0) yflip=1;
+	else yflip=0;
+
+	/*Get extreme coordinates of the grid*/
+	if (xflip){
+		for(i=0;i<ncols; i++) x_grid[ncols-1-i] = xmin - xposting*i;
+		x_grid_min=x_grid[ncols-1];
+		x_grid_max=x_grid[0];
+	}
+	else{
+		for(i=0;i<ncols; i++) x_grid[i]= xmin + xposting*i;
+		x_grid_min=x_grid[0];
+		x_grid_max=x_grid[ncols-1];
+	}
+	if (yflip){
+		for(i=0;i<nlines;i++) y_grid[i] = ymax + yposting*i;
+		y_grid_min=y_grid[nlines-1];
+		y_grid_max=y_grid[0];
+	}
+	else{
+		for(i=0;i<nlines;i++) y_grid[nlines-1-i]= ymax - yposting*i;
+		y_grid_min=y_grid[0];
+		y_grid_max=y_grid[nlines-1];
+	}
+
+	/*Loop over the elements*/
+	for (n=0;n<nels;n++){
+
+		/*display current iteration*/
+		if (debug && fmod((double)n,(double)100)==0)
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(n)/double(nels)*100<<"%   ");
+
+		/*Get extrema coordinates of current elements*/
+		x_tria_min=x_mesh[(int)index_mesh[3*n+0]-1]; x_tria_max=x_tria_min;
+		y_tria_min=y_mesh[(int)index_mesh[3*n+0]-1]; y_tria_max=y_tria_min;
+		for (i=1;i<3;i++){
+			if(x_mesh[(int)index_mesh[3*n+i]-1]<x_tria_min) x_tria_min=x_mesh[(int)index_mesh[3*n+i]-1];
+			if(x_mesh[(int)index_mesh[3*n+i]-1]>x_tria_max) x_tria_max=x_mesh[(int)index_mesh[3*n+i]-1];
+			if(y_mesh[(int)index_mesh[3*n+i]-1]<y_tria_min) y_tria_min=y_mesh[(int)index_mesh[3*n+i]-1];
+			if(y_mesh[(int)index_mesh[3*n+i]-1]>y_tria_max) y_tria_max=y_mesh[(int)index_mesh[3*n+i]-1];
+		}
+
+		/*if the current triangle is not in the grid, continue*/
+		if ( (x_tria_min>x_grid_max) || (x_tria_max<x_grid_min) || (y_tria_min>y_grid_max) || (y_tria_max<y_grid_min) ) continue;
+
+		/*Get indices i and j that form a square around the currant triangle*/
+		if (yflip){
+			i1=max(0,       (int)floor((y_tria_max-y_grid_max)/yposting)-1);
+			i2=min(nlines-1,(int)ceil((y_tria_min-y_grid_max)/yposting));
+		}
+		else{
+			i1=max(0,       (int)floor((y_tria_min-y_grid_min)/yposting)-1);
+			i2=min(nlines-1,(int)ceil((y_tria_max-y_grid_min)/yposting));
+		}
+		if (xflip){
+			j1=max(0,      (int)floor((x_tria_max-x_grid_max)/xposting)-1);
+			j2=min(ncols-1,(int)ceil((x_tria_min-x_grid_max)/xposting));
+		}
+		else{
+			j1=max(0,      (int)floor((x_tria_min-x_grid_min)/xposting)-1);
+			j2=min(ncols-1,(int)ceil((x_tria_max-x_grid_min)/xposting));
+		}
+
+		/*get area of the current element (Jacobian = 2 * area)*/
+		//area =x2 * y3 - y2*x3 + x1 * y2 - y1 * x2 + x3 * y1 - y3 * x1;
+		area=x_mesh[(int)index_mesh[3*n+1]-1]*y_mesh[(int)index_mesh[3*n+2]-1]-y_mesh[(int)index_mesh[3*n+1]-1]*x_mesh[(int)index_mesh[3*n+2]-1]
+		  +  x_mesh[(int)index_mesh[3*n+0]-1]*y_mesh[(int)index_mesh[3*n+1]-1]-y_mesh[(int)index_mesh[3*n+0]-1]*x_mesh[(int)index_mesh[3*n+1]-1]
+		  +  x_mesh[(int)index_mesh[3*n+2]-1]*y_mesh[(int)index_mesh[3*n+0]-1]-y_mesh[(int)index_mesh[3*n+2]-1]*x_mesh[(int)index_mesh[3*n+0]-1];
+
+		/*Go through x_grid and y_grid and interpolate if necessary*/
+		for (i=i1;i<=i2;i++){
+
+			//exit if y not between y_tria_min and y_tria_max
+			if((y_grid[i]>y_tria_max) || (y_grid[i]<y_tria_min)) continue;
+
+			for(j=j1;j<=j2; j++){
+
+				//exit if x not between x_tria_min and x_tria_max
+				if((x_grid[j]>x_tria_max) || (x_grid[j]<x_tria_min)) continue;
+
+				/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+				area_1=((x_grid[j]-x_mesh[(int)index_mesh[3*n+2]-1])*(y_mesh[(int)index_mesh[3*n+1]-1]-y_mesh[(int)index_mesh[3*n+2]-1]) 
+							-  (y_grid[i]-y_mesh[(int)index_mesh[3*n+2]-1])*(x_mesh[(int)index_mesh[3*n+1]-1]-x_mesh[(int)index_mesh[3*n+2]-1]))/area;
+				/*Get second area coordinate =det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+				area_2=((x_mesh[(int)index_mesh[3*n+0]-1]-x_mesh[(int)index_mesh[3*n+2]-1])*(y_grid[i]-y_mesh[(int)index_mesh[3*n+2]-1]) 
+							- (y_mesh[(int)index_mesh[3*n+0]-1]-y_mesh[(int)index_mesh[3*n+2]-1])*(x_grid[j]-x_mesh[(int)index_mesh[3*n+2]-1]))/area;
+				/*Get third area coordinate = 1-area1-area2*/
+				area_3=1-area_1-area_2;
+
+				/*is the current point in the current element?*/
+				if (area_1>-10e-12 && area_2>-10e-12 && area_3>-10e-12){
+
+					/*Yes ! compute the value on the point*/
+					if (interpolation_type==1){
+						/*nodal interpolation*/
+						data_value=area_1*data_mesh[(int)index_mesh[3*n+0]-1]+area_2*data_mesh[(int)index_mesh[3*n+1]-1]+area_3*data_mesh[(int)index_mesh[3*n+2]-1];
+					}
+					else{
+						/*element interpolation*/
+						data_value=data_mesh[n];
+					}
+					if (xIsNan<IssmDouble>(data_value)) data_value=default_value;
+
+					/*insert value and go to the next point*/
+					griddata[i*ncols+j]=data_value;
+				}
+			}
+		}
+	}
+	if (debug)
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+
+	/*Assign output pointers:*/
+	*pgriddata=griddata;
+	*px_m=x_grid;
+	*py_m=y_grid;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file InterpFromMeshToGridx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMMESHTOGRIDX_H
+#define _INTERPFROMMESHTOGRIDX_H
+
+#include "../../toolkits/toolkits.h"
+
+void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value);
+
+#endif /* _INTERPFROMMESHTOGRIDX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 18231)
@@ -0,0 +1,150 @@
+/*!\file InterpFromMeshToMesh2dx
+ */
+
+#include "./InterpFromMeshToMesh2dx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
+
+using namespace bamg;
+using namespace std;
+
+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;
+
+	/*Intermediary*/
+	double xmin,xmax,ymin,ymax;
+	bool   isdefault;
+	double defaultvalue;
+	R2     r;
+	I2     I;
+	int    i,j;
+	int    it;
+	int    i0,i1,i2;
+	double areacoord[3];
+	double aa,bb;
+	Icoor2 dete[3];
+
+	/*Checks*/
+	if (M_data!=nods_data && M_data!=nels_data){
+		_error_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
+	}
+
+	/*Get default*/
+	if(options->GetOption("default")){
+		isdefault=true;
+		options->Get(&defaultvalue,"default");
+	}
+	else{
+		isdefault=false;
+	}
+
+	/*Initialize output*/
+	data_interp=xNew<double>(N_interp*N_data);
+
+	/*read background mesh*/
+	Mesh Th(index_data,x_data,y_data,nods_data,nels_data); 
+
+	/*Get reference number (for subdomains)*/
+	long* reft = xNew<long>(Th.nbt);
+	Th.TriangleReferenceList(reft);
+	Th.CreateSingleVertexToTriangleConnectivity();
+
+	/*Get domain boundaries*/
+	xmin=x_data[0]; ymin=y_data[0];
+	xmax=x_data[0]; ymax=y_data[0];
+	for(i=1;i<nods_data;i++){
+		if(x_data[i]<xmin) xmin=x_data[i];
+		if(x_data[i]>xmax) xmax=x_data[i];
+		if(y_data[i]<ymin) ymin=y_data[i];
+		if(y_data[i]>ymax) ymax=y_data[i];
+	}
+
+	/*Loop over output nodes*/
+	for(i=0;i<N_interp;i++){
+		//if(i%100==0) _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(N_interp)*100.<<"%   ");
+
+		if(isdefault){
+			if(x_interp[i]<xmin || x_interp[i]>xmax || y_interp[i]<ymin || y_interp[i]>ymax){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
+			}
+		}
+
+		/*Get current point coordinates*/
+		r.x=x_interp[i]; r.y=y_interp[i];
+		I2 I=Th.R2ToI2(r);
+
+		/*Find triangle holding r/I*/
+		Triangle &tb=*Th.TriangleFindFromCoord(I,dete);
+
+		/*point inside convex*/
+		if (tb.det>0){ 
+
+			/*Area coordinates*/
+			areacoord[0]= (double) dete[0]/tb.det;
+			areacoord[1]= (double) dete[1]/tb.det;
+			areacoord[2]= (double) dete[2]/tb.det;
+			/*3 vertices of the triangle*/
+			i0=Th.GetId(tb[0]);
+			i1=Th.GetId(tb[1]);
+			i2=Th.GetId(tb[2]);
+			/*triangle number*/
+			it=Th.GetId(tb);
+
+			/*Inside convex but outside mesh*/
+			if (reft[it]<0 && isdefault){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
+			}
+		}
+		//external point
+		else{
+			if(isdefault){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
+			}
+			else{
+				//Get closest adjacent triangle (inside the mesh)
+				AdjacentTriangle ta=CloseBoundaryEdge(I,&tb,aa,bb).Adj();
+				int k=ta;
+				Triangle &tc=*(Triangle*)ta;
+				//Area coordinate
+				areacoord[VerticesOfTriangularEdge[k][1]] = aa;
+				areacoord[VerticesOfTriangularEdge[k][0]] = bb;
+				areacoord[OppositeVertex[k]] = 1 - aa -bb;
+				//3 vertices of the triangle
+				i0=Th.GetId(tc[0]);
+				i1=Th.GetId(tc[1]);
+				i2=Th.GetId(tc[2]);
+				//triangle number
+				it=Th.GetId(tc);
+			}
+		}
+
+		if (M_data==nods_data){
+			for (j=0;j<N_data;j++){
+				data_interp[i*N_data+j]=areacoord[0]*data[N_data*i0+j]+areacoord[1]*data[N_data*i1+j]+areacoord[2]*data[N_data*i2+j];
+			}
+		}
+		else{
+			for (j=0;j<N_data;j++){
+				if (it<0 || it>=nels_data){
+					_error_("Triangle number " << it << " not in [0 " << nels_data << "], report bug to developers");
+				}
+				data_interp[i*N_data+j]=data[N_data*it+j];
+			}
+		}
+	}
+	//if(N_interp>=100) _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+
+	/*clean-up and return*/
+	xDelete<long>(reft);
+	*pdata_interp=data_interp;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  InterpFromMeshToMesh2dx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _INTERPFROMMESHTOMESH2DX_H
+#define _INTERPFROMMESHTOMESH2DX_H
+
+#include "../../classes/classes.h"
+
+int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
+			double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 18231)
@@ -0,0 +1,139 @@
+/*!\file:  InterpFromMeshToMesh3dx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMeshToMesh3dx.h"
+#include "../../shared/shared.h"
+
+int InterpFromMeshToMesh3dx( IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value) {
+
+	/*Output*/
+	IssmSeqVec<IssmPDouble>* data_prime=NULL;
+
+	/*Intermediary*/
+	int i,j;
+	int interpolation_type;
+	bool debug;
+	double area;
+	double area_1,area_2,area_3;
+	double zeta,bed,surface;
+	double data_value;
+	double x_prime_min,x_prime_max;
+	double y_prime_min,y_prime_max;
+	double x_tria_min,y_tria_min;
+	double x_tria_max,y_tria_max;
+
+	/*some checks*/
+	if (nels_data<1 || nods_data<6 || nods_prime==0){
+		_error_("nothing to be done according to the mesh given in input");
+	}
+
+	/*Set debug to 1 if there are lots of elements*/
+	debug=(bool)((double)nels_data*(double)nods_prime >= pow((double)10,(double)9));
+
+	/*figure out what kind of interpolation is needed*/
+	if (data_length==nods_data){
+		interpolation_type=1;
+	}
+	else if (data_length==nels_data){
+		interpolation_type=2;
+	}
+	else{
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+	}
+
+	/*Get prime mesh extrema coordinates*/
+	x_prime_min=x_prime[0]; x_prime_max=x_prime[0];y_prime_min=y_prime[0]; y_prime_max=y_prime[0];
+	for (i=1;i<nods_prime;i++){
+		if (x_prime[i]<x_prime_min) x_prime_min=x_prime[i];
+		if (x_prime[i]>x_prime_max) x_prime_max=x_prime[i];
+		if (y_prime[i]<y_prime_min) y_prime_min=y_prime[i];
+		if (y_prime[i]>y_prime_max) y_prime_max=y_prime[i];
+	}
+
+	/*Initialize output*/
+	data_prime=new IssmSeqVec<IssmPDouble>(nods_prime);
+	for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_value,INS_VAL);
+
+	/*Loop over the elements*/
+	for (i=0;i<nels_data;i++){
+
+		/*display current iteration*/
+		if (debug && fmod((double)i,(double)100)==0)
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(nels_data)*100<<"%   ");
+
+		/*Get extrema coordinates of current elements*/
+		x_tria_min=x_data[(int)index_data[6*i+0]-1]; x_tria_max=x_tria_min;
+		y_tria_min=y_data[(int)index_data[6*i+0]-1]; y_tria_max=y_tria_min;
+		for (j=1;j<3;j++){
+			if(x_data[(int)index_data[6*i+j]-1]<x_tria_min) x_tria_min=x_data[(int)index_data[6*i+j]-1];
+			if(x_data[(int)index_data[6*i+j]-1]>x_tria_max) x_tria_max=x_data[(int)index_data[6*i+j]-1];
+			if(y_data[(int)index_data[6*i+j]-1]<y_tria_min) y_tria_min=y_data[(int)index_data[6*i+j]-1];
+			if(y_data[(int)index_data[6*i+j]-1]>y_tria_max) y_tria_max=y_data[(int)index_data[6*i+j]-1];
+		}
+
+		/*if there is no point inside the domain, go to next iteration*/
+		if ( x_prime_max < x_tria_min ) continue; 
+		if ( x_prime_min > x_tria_max ) continue; 
+		if ( y_prime_max < y_tria_min ) continue; 
+		if ( y_prime_min > y_tria_max ) continue; 
+
+		/*get area of the current element (Jacobian = 2 * area)*/
+		//area =x2 * y3 - y2*x3 + x1 * y2 - y1 * x2 + x3 * y1 - y3 * x1;
+		area=x_data[(int)index_data[6*i+1]-1]*y_data[(int)index_data[6*i+2]-1]-y_data[(int)index_data[6*i+1]-1]*x_data[(int)index_data[6*i+2]-1]
+		  +  x_data[(int)index_data[6*i+0]-1]*y_data[(int)index_data[6*i+1]-1]-y_data[(int)index_data[6*i+0]-1]*x_data[(int)index_data[6*i+1]-1]
+		  +  x_data[(int)index_data[6*i+2]-1]*y_data[(int)index_data[6*i+0]-1]-y_data[(int)index_data[6*i+2]-1]*x_data[(int)index_data[6*i+0]-1];
+
+		/*loop over the prime nodes*/
+		for (j=0;j<nods_prime;j++){
+
+			/*if the current point is not in the triangle, continue*/
+			if ( x_prime[j] < x_tria_min ) continue; 
+			if ( x_prime[j] > x_tria_max ) continue; 
+			if ( y_prime[j] < y_tria_min ) continue; 
+			if ( y_prime[j] > y_tria_max ) continue; 
+
+			/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+			area_1=((x_prime[j]-x_data[(int)index_data[6*i+2]-1])*(y_data[(int)index_data[6*i+1]-1]-y_data[(int)index_data[6*i+2]-1]) 
+						-  (y_prime[j]-y_data[(int)index_data[6*i+2]-1])*(x_data[(int)index_data[6*i+1]-1]-x_data[(int)index_data[6*i+2]-1]))/area;
+			/*Get second area coordinate =det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+			area_2=((x_data[(int)index_data[6*i+0]-1]-x_data[(int)index_data[6*i+2]-1])*(y_prime[j]-y_data[(int)index_data[6*i+2]-1]) 
+						- (y_data[(int)index_data[6*i+0]-1]-y_data[(int)index_data[6*i+2]-1])*(x_prime[j]-x_data[(int)index_data[6*i+2]-1]))/area;
+			/*Get third area coordinate = 1-area1-area2*/
+			area_3=1-area_1-area_2;
+
+			/*is the current point in the current 2d element?*/
+			if (area_1>=0 && area_2>=0 && area_3>=0){
+
+				/*compute bottom and top height of the element at this 2d position*/
+				bed    =area_1*z_data[(int)index_data[6*i+0]-1]+area_2*z_data[(int)index_data[6*i+1]-1]+area_3*z_data[(int)index_data[6*i+2]-1];
+				surface=area_1*z_data[(int)index_data[6*i+3]-1]+area_2*z_data[(int)index_data[6*i+4]-1]+area_3*z_data[(int)index_data[6*i+5]-1];
+
+				/*Compute zeta*/
+				zeta=2*(z_prime[j]-bed)/(surface-bed)-1;
+
+				if (zeta >=-1 && zeta<=1){
+					if (interpolation_type==1){
+						/*nodal interpolation*/
+						data_value=(1-zeta)/2*(area_1*data[(int)index_data[6*i+0]-1]+area_2*data[(int)index_data[6*i+1]-1]+area_3*data[(int)index_data[6*i+2]-1]) 
+						  +        (1+zeta)/2*(area_1*data[(int)index_data[6*i+3]-1]+area_2*data[(int)index_data[6*i+4]-1]+area_3*data[(int)index_data[6*i+5]-1]);
+					}
+					else{
+						/*element interpolation*/
+						data_value=data[i];
+					}
+					if (xIsNan<IssmPDouble>(data_value)) data_value=default_value;
+
+					/*insert value and go to the next point*/
+					data_prime->SetValue(j,data_value,INS_VAL);
+				}
+			}
+		}
+	}
+	if (debug)
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+
+	/*Assign output pointers:*/
+	*pdata_prime=data_prime;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file InterpFromMeshToMesh3dx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMMESHTOMESH3DX_H
+#define _INTERPFROMMESHTOMESH3DX_H
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+
+int InterpFromMeshToMesh3dx(IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value);
+
+#endif /* _INTERPFROMMESHTOMESH3DX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 18231)
@@ -0,0 +1,539 @@
+/*!\file IoModelToConstraintsx
+ * \brief: used in ModelProcessor, to retrieve a nodal vector  and to create corresponding constraints using Constraints objects
+ */
+
+#include "./IoModelToConstraintsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type,int finite_element,int dof){
+
+	/*intermediary: */
+	int         code,vector_layout;
+	IssmDouble *spcdata = NULL;
+	int         M,N;
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
+	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
+
+	/*Fetch vector:*/
+	iomodel->FetchData(&spcdata,&M,&N,vector_enum);
+
+	/*Call IoModelToConstraintsx*/
+	IoModelToConstraintsx(constraints,iomodel,spcdata,M,N,analysis_type,finite_element,dof);
+
+	/*Clean up*/
+	xDelete<IssmDouble>(spcdata);
+}
+
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,IssmDouble* spcdata,int M,int N,int analysis_type,int finite_element,int dof){
+
+	/*intermediary: */
+	int         i,j,count,elementnbv,numfacevertices;
+	IssmDouble  value;
+	IssmDouble *times            = NULL;
+	IssmDouble *values           = NULL;
+	bool        spcpresent       = false;
+
+	/*Higher-order finite elements*/
+	int   v1,v2;
+	bool *my_edges = NULL;
+	bool *my_faces = NULL;
+	bool *boundaryedge = NULL;
+
+	switch(finite_element){
+		case P1Enum: 
+			/*Nothing else to do*/
+			break;
+		case P1bubbleEnum:
+			switch(iomodel->meshelementtype){
+				case TriaEnum:  elementnbv = 3; break;
+				case TetraEnum: elementnbv = 4; break;
+				case PentaEnum: elementnbv = 6; break;
+				default: _error_("mesh type not supported yet");
+			}
+			break;
+		case P1bubblecondensedEnum: 
+			/*Nothing else to do*/
+			break;
+		case P1xP2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		case P1xP3Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		case P2xP1Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		case P2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+	      if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+			}
+			EdgeOnBoundaryFlags(&boundaryedge,iomodel);
+			break;
+		case P2bubbleEnum:
+			EdgesPartitioning(&my_edges,iomodel);
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+			}
+			EdgeOnBoundaryFlags(&boundaryedge,iomodel);
+			switch(iomodel->meshelementtype){
+				case TriaEnum:  elementnbv = 3; break;
+				case TetraEnum: elementnbv = 4; break;
+				case PentaEnum: elementnbv = 6; break;
+				default: _error_("mesh type not supported yet");
+			}
+			break;
+		case P2xP4Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			FacesPartitioning(&my_faces,iomodel);
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+	}
+
+	count=0;
+	if(M==iomodel->numberofvertices){
+		switch(finite_element){
+			case P1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i] && boundaryedge[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+							count++;
+						}
+					}
+				}
+				if(iomodel->meshelementtype==PentaEnum){
+					for(i=0;i<iomodel->numberoffaces;i++){
+						if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+							if(my_faces[i]){
+								numfacevertices = iomodel->faces[i*iomodel->facescols+3];
+								value=0.;
+								for(j=0;j<numfacevertices;j++){
+									value += spcdata[iomodel->faces[i*iomodel->facescols+4+j] -1];
+								}
+								value = value/reCast<IssmDouble>(numfacevertices);
+								if(!xIsNan<IssmDouble>(value)){
+									constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,
+													iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,
+													dof,value,analysis_type));
+									count++;
+								}
+							}
+						}
+					}
+				}
+				break;
+			case P2bubbleEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i] && boundaryedge[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+							count++;
+						}
+					}
+				}
+				if(iomodel->meshelementtype==PentaEnum){
+					for(i=0;i<iomodel->numberoffaces;i++){
+						if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+							if(my_faces[i]){
+								numfacevertices = iomodel->faces[i*iomodel->facescols+3];
+								value=0.;
+								for(j=0;j<numfacevertices;j++){
+									value += spcdata[iomodel->faces[i*iomodel->facescols+4+j] -1];
+								}
+								value = value/reCast<IssmDouble>(numfacevertices);
+								if(!xIsNan<IssmDouble>(value)){
+									constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,
+													iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,
+													dof,value,analysis_type));
+									count++;
+								}
+							}
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofelements;i++){
+					if(iomodel->my_elements[i]){
+						value = spcdata[iomodel->elements[i*elementnbv+0]-1];
+						for(j=1;j<elementnbv;j++) value += spcdata[iomodel->elements[i*elementnbv+j]-1];
+						value = value/reCast<IssmDouble,int>(elementnbv+0);
+						if(!xIsNan<IssmDouble>(value)){
+							int nodeid = iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1;
+							if(iomodel->meshelementtype==PentaEnum){
+								nodeid += iomodel->numberoffaces;
+							}
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,nodeid,dof,value,analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P2xP4Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){/*Vertical edges*/
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+3*i+1,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+2,iomodel->nodecounter+iomodel->numberofvertices+3*i+2,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+3,iomodel->nodecounter+iomodel->numberofvertices+3*i+3,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								count=count+3;
+							}
+						}
+					}
+					if(iomodel->edges[i*3+2]==1){/*Horizontal edges*/
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+3*i+1,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								count=count+1;
+							}
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							numfacevertices = iomodel->faces[i*iomodel->facescols+3];
+							value=0.;
+							for(j=0;j<numfacevertices;j++){
+								value += spcdata[iomodel->faces[i*iomodel->facescols+4+j] -1];
+							}
+							value = value/reCast<IssmDouble>(numfacevertices);
+							if(!xIsNan<IssmDouble>(value)){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,
+												iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*i+1,
+												dof,value,analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+2,
+												iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*i+2,
+												dof,value,analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+3,
+												iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*i+3,
+												dof,value,analysis_type));
+								count=count+3;
+							}
+						}
+					}
+				}
+				break;
+			case P1bubbleEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofelements;i++){
+					if(iomodel->my_elements[i]){
+						value = spcdata[iomodel->elements[i*elementnbv+0]-1];
+						for(j=1;j<elementnbv;j++) value += spcdata[iomodel->elements[i*elementnbv+j]-1];
+						value = value/reCast<IssmDouble,int>(elementnbv+0);
+						if(!xIsNan<IssmDouble>(value)){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,value,analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P1bubblecondensedEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P1xP2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+												dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+								count++;
+							}
+						}
+					}
+				}
+				break;
+			case P1xP3Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+2*i+1,
+												dof,2./3.*spcdata[v1]+1./3.*spcdata[v2],analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+2,iomodel->nodecounter+iomodel->numberofvertices+2*i+2,
+												dof,1./3.*spcdata[v1]+2./3.*spcdata[v2],analysis_type));
+								count=count+2;
+							}
+						}
+					}
+				}
+				break;
+			case P2xP1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]!=2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+												dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+								count++;
+							}
+						}
+					}
+				}
+				break;
+			default:
+				_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+		}
+	}
+	else if (M==(iomodel->numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+
+		/*figure out times: */
+		times=xNew<IssmDouble>(N);
+		for(j=0;j<N;j++) times[j]=spcdata[(M-1)*N+j];
+
+		switch(finite_element){
+			case P1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				break;
+			case P2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+							if(!xIsNan<IssmDouble>(values[j])) spcpresent=true; //NaN means no spc by default
+						}
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,dof,
+											N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				break;
+			case P1xP2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							values=xNew<IssmDouble>(N);
+							spcpresent=false;
+							for(j=0;j<N;j++){
+								values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+								if(!xIsNan<IssmDouble>(values[j])) spcpresent=true; //NaN means no spc by default
+							}
+							if(spcpresent){
+								constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,dof,
+												N,times,values,analysis_type));
+								count++;
+							}
+							xDelete<IssmDouble>(values);
+						}
+					}
+				}
+				break;
+			case P2xP1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]!=2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							values=xNew<IssmDouble>(N);
+							spcpresent=false;
+							for(j=0;j<N;j++){
+								values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+								if(!xIsNan<IssmDouble>(values[j])) spcpresent=true; //NaN means no spc by default
+							}
+							if(spcpresent){
+								constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,dof,
+												N,times,values,analysis_type));
+								count++;
+							}
+							xDelete<IssmDouble>(values);
+						}
+					}
+				}
+				break;
+			default:
+				_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+		}
+	}
+	else{
+		_error_("Size of spc field not supported");
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+	xDelete<bool>(my_edges);
+	xDelete<bool>(my_faces);
+	xDelete<bool>(boundaryedge);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  IoModelToConstraintsx.h
+ */ 
+
+#ifndef _IOMODEL_TO_CONSTRAINTS_H_
+#define _IOMODEL_TO_CONSTRAINTS_H_
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type,int finite_element,int dof=0);
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,IssmDouble* spcdata,int M,int N,int analysis_type,int finite_element,int dof=0);
+
+#endif  /* _IOMODELTOELEMENTINPUTX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 18231)
@@ -0,0 +1,61 @@
+/*!\file KMLFileReadx.cpp
+ */
+
+#include "./KMLFileReadx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+KML_Object* KMLFileReadx(FILE* fid){
+
+	char*   kstr;
+	KML_File*      kxml=NULL;
+	KML_File*      kdtd=NULL;
+	KML_File*      kfil=NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nKMLFileReadx Module -- " << ctime(&time0));
+
+/*  read kml file  */
+
+	while((kstr=KMLFileToken(fid, NULL,NULL))){
+		if      (!strncmp(kstr,"<?xml"    ,5)) {
+			kxml=new KML_File();
+			KMLFileTagAttrib(kxml,
+							 kstr);
+		}
+		else if (!strncmp(kstr,"<!DOCTYPE",9)) {
+			kdtd=new KML_File();
+			KMLFileTagAttrib(kdtd,
+							 kstr);
+		}
+		else if (!strncmp(kstr,"<kml"     ,4)) {
+			kfil=new KML_File();
+			kfil->Read(fid,kstr);
+//			kfil->DeepEcho();
+		}
+
+//		_printf0_(kstr << "\n");
+		xDelete<char>(kstr);
+	}
+
+	if (kxml) {
+		_printf0_("XML declaration:\n");
+		kxml->DeepEcho("  ");
+		delete kxml;
+	}
+	if (kdtd) {
+		_printf0_("DTD declaration (not yet implemented):\n");
+		kdtd->DeepEcho("  ");
+		delete kdtd;
+	}
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("KMLFileReadx Module -- " <<((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " <<difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return(kfil);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  KMLFileReadx.h
+ * \brief header file for kml mesh writer routines.
+ */ 
+
+#ifndef _KMLFILEREADX_H
+#define _KMLFILEREADX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../kml/kmlobjects.h"
+
+/* local prototypes: */
+KML_Object* KMLFileReadx(FILE* fid);
+
+#endif  /* _KMLFILEREADX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 18231)
@@ -0,0 +1,356 @@
+/*!\file KMLMeshWritex
+ */
+
+#include "./KMLMeshWritex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void KMLMeshWritex(int* ierror,char* name,char* notes,int* elem,int melem,int nelem,int* nodecon,int mncon,int nncon,double* lat, double* lng,int* part,double* data, int mdata, int ndata,double* cmap, int mcmap, int ncmap,FILE* fid){
+
+	int                 i,j,k,ipt=0,jpt=0,nnodes;
+	int                 mxepg      = 25;
+	int                 lwidth     = 1;
+	double              popac      = 0.50;
+	char                indent[81] = " ";
+	char                cstr[81];
+	double             *edata = NULL;
+	bool ncfree=false, edfree=false;
+	KML_Document       *kdoc = NULL;
+	KML_Style          *kstyle;
+	KML_LineStyle      *klsty;
+	KML_PolyStyle      *kpsty;
+
+	clock_t clock0,clock1,clock0a,clock0b,clock0c;
+	time_t  time0, time1, time0a, time0b, time0c;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nKMLMeshWritex Module -- " << ctime(&time0));
+
+/*  construct kml document  */
+
+	kdoc=new KML_Document();
+	sprintf(kdoc->name      ,"ISSM Mesh: %s",name);
+	kdoc->open      =1;
+	sprintf(kdoc->descript  ,"%s",notes);
+
+/*  write style templates for defaults and for each color of the matlab
+	colormap (note that matlab colormap format is rgb, where each varies
+	from 0 to 1, whereas the kml color format is aabbggrr, where each
+	varies from 00 to ff.)  */
+
+	klsty=new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty=new KML_PolyStyle();
+	sprintf(kpsty->color     ,"%02xffffff",(int)floor(popac*255+0.5));
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineRandomPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty=new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty=new KML_PolyStyle();
+	sprintf(kpsty->color     ,"00ffffff");
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineEmptyPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty=new KML_LineStyle();
+	sprintf(klsty->color     ,"ff0000ff");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty=new KML_PolyStyle();
+	sprintf(kpsty->color     ,"%02x0000ff",(int)floor(popac*255+0.5));
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","RedLineRedPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	if (cmap) {
+		_printf0_("Writing " << mcmap << " Matlab colors as KML style templates.\n");
+		ipt=0;
+		for (i=0; i<mcmap; i++) {
+			klsty=new KML_LineStyle();
+//			sprintf(klsty->color     ,"ff000000");
+			sprintf(klsty->color     ,"%02x%02x%02x%02x",
+					(int)255,
+					(int)floor(cmap[ipt+2]*255+0.5),
+					(int)floor(cmap[ipt+1]*255+0.5),
+					(int)floor(cmap[ipt  ]*255+0.5));
+			sprintf(klsty->colormode ,"normal");
+			klsty->width     =lwidth;
+			kpsty=new KML_PolyStyle();
+			sprintf(kpsty->color     ,"%02x%02x%02x%02x",
+					(int)floor(popac*255+0.5),
+					(int)floor(cmap[ipt+2]*255+0.5),
+					(int)floor(cmap[ipt+1]*255+0.5),
+					(int)floor(cmap[ipt  ]*255+0.5));
+			sprintf(kpsty->colormode ,"normal");
+			kstyle=new KML_Style();
+			sprintf(cstr,"MatlabColor%d",i+1);
+			kstyle->AddAttrib("id",cstr);
+			kstyle->line      =klsty;
+			kstyle->poly      =kpsty;
+			(kdoc->style     )->AddObject((Object*)kstyle);
+			ipt+=ncmap;
+		}
+	}
+//	kdoc->DeepEcho();
+
+/*  create the node connectivity table, if necessary
+	(noting that rows do not need to be sorted, since the elements
+	are consecutively numbered)  */
+
+	if (!nodecon) {
+		_printf0_("Creating the node connectivity table.\n");
+		nncon=mxepg+1;
+		nodecon=xNewZeroInit<int>(mncon*nncon);
+		ncfree=true;
+
+		jpt=0;
+		for (i=0; i<melem; i++) {
+			for (j=0; j<nelem; j++) {
+				if (elem[jpt]) {
+					ipt=(elem[jpt]-1)*nncon;
+					if (nodecon[ipt+(nncon-1)] < mxepg) {
+						nodecon[ipt+nodecon[ipt+(nncon-1)]]=i+1;
+						nodecon[ipt+(nncon-1)]++;
+					}
+					else
+						_error_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
+				}
+				jpt++;
+			}
+		}
+	}
+
+/*  average nodal data to element data, if necessary
+	(noting that multiple columns of data are handled here, but not
+	yet below)  */
+
+	if (data) {
+		if      (mdata == melem)
+			edata=data;
+
+		else if (mdata == mncon) {
+			_printf0_("Averaging nodal data to element data.\n");
+			edata=xNewZeroInit<double>(melem*ndata);
+			edfree=true;
+
+			ipt=0;
+			jpt=0;
+			for (i=0; i<melem; i++) {
+				nnodes=0;
+				for (j=0; j<nelem; j++) {
+					if (elem[jpt]) {
+						for (k=0; k<ndata; k++)
+							edata[ipt+k]+=data[(elem[jpt]-1)*ndata+k];
+						nnodes++;
+					}
+					jpt++;
+				}
+				if (nnodes)
+					for (k=0; k<ndata; k++)
+						edata[ipt+k]/=(double)nnodes;
+				ipt+=ndata;
+			}
+		}
+
+		else
+			_error_("Data matrix has incorrect number of " << mdata << " rows.\n");
+	}
+
+/*  write folder for mesh  */
+
+	(kdoc ->feature   )->AddObject((Object*)KMLMeshElem(elem,melem,nelem,
+														nodecon,mncon,nncon,
+														lat,lng,
+														edata,
+														cmap,mcmap,ncmap));
+
+	if(edfree) xDelete<double>(edata);
+	if(ncfree) xDelete<int>(nodecon);
+	clock0a=clock();
+	time0a =time(NULL);
+	_printf_("  Constructed kml document -- " << ((double)(clock0a-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0a,time0) << " elapsed seconds.\n\n\n");
+
+/*  write kml file  */
+
+	_printf0_("Writing kml document to file.\n");
+	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+	fprintf(fid,"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");
+	kdoc->Write(fid,indent);
+	fprintf(fid,"</kml>\n");
+	clock0b=clock();
+	time0b =time(NULL);
+	_printf_("  Wrote kml file -- " << ((double)(clock0b-clock0a))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0b,time0a) << " elapsed seconds.\n\n\n");
+
+	_printf0_("Deleting kml document.\n");
+	delete kdoc;
+	clock0c=clock();
+	time0c =time(NULL);
+	_printf_("  Deleted kml document -- " << ((double)(clock0c-clock0b))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0c,time0b) << " elapsed seconds.\n\n\n");
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("KMLMeshWritex Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return;
+}
+
+KML_Folder* KMLMeshElem(int* elem,int melem,int nelem,
+						int* nodecon,int mncon,int nncon,
+						double* lat, double* lng,
+						double* edata,
+						double* cmap, int mcmap, int ncmap){
+
+	int     i,j,ipt=0;
+	double  alt=0;
+	double  cmin= DBL_MAX,
+			cmax=-DBL_MAX;
+	int     imap;
+	KML_Folder*     kfold =NULL;
+	KML_Placemark*  kplace=NULL;
+	KML_Polygon*    kpoly =NULL;
+	KML_LinearRing* kring =NULL;
+
+/*  write folder for mesh  */
+
+	kfold=new KML_Folder();
+//	sprintf(kfold->name      ,"Mesh");
+	sprintf(kfold->name      ,"ISSM Targets");
+	kfold->visibility=1;
+//	sprintf(kfold->descript  ,"Elements=%d, Nodes=%d",melem,mncon);
+	sprintf(kfold->descript  ,"campaign{\n");
+	strcat(kfold->descript  ,"  evaluator ClaspTargetEvaluator;\n");
+	strcat(kfold->descript  ,"  solver IssmSolver;\n");
+	strcat(kfold->descript  ,"  spacecraft airplane ClaspSpacecraft(\n");
+	strcat(kfold->descript  ,"    dutyCycleDuration=0,\n");
+	strcat(kfold->descript  ,"    dutyCycleOnDuration=0,\n");
+	strcat(kfold->descript  ,"    memoryInit=15000,\n");
+	strcat(kfold->descript  ,"    memoryLimit=40000000,\n");
+	strcat(kfold->descript  ,"    maxDataCollectionRate=27,\n");
+	strcat(kfold->descript  ,"    maxDataDownlinkRate=10);\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //sensor names\n");
+	strcat(kfold->descript  ,"  sensor qqp_swath = 2,102,1002,1102;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //sensor ids to modes\n");
+	strcat(kfold->descript  ,"  low_bandwidth_single_pol = 2,102,1002,1102;\n");
+	strcat(kfold->descript  ,"  single_pol = 2,102,1002,1102;\n");
+	strcat(kfold->descript  ,"  dual_pol = 2,102,1002,1102;\n");
+	strcat(kfold->descript  ,"  quad_pol = 2,102,1002,1102;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //LRAD\n");
+	strcat(kfold->descript  ,"  //Note all targets are \"ascending right\"-- i.e. mode=2\n");
+	strcat(kfold->descript  ,"  left = 1002,1102;\n");
+	strcat(kfold->descript  ,"  right = 2,102;\n");
+	strcat(kfold->descript  ,"  ascending = 2,1002;\n");
+	strcat(kfold->descript  ,"  descending = 102,1102;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //data rates\n");
+	strcat(kfold->descript  ,"  low_bandwidth_single_pol datarate = 0.896;\n");
+	strcat(kfold->descript  ,"  single_pol datarate = 4.214;\n");
+	strcat(kfold->descript  ,"  dual_pol datarate = 8.428;\n");
+	strcat(kfold->descript  ,"  quad_pol datarate = 16.856;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //mode domination relationships\n");
+	strcat(kfold->descript  ,"  quad_pol dominates low_bandwidth_single_pol;\n");
+	strcat(kfold->descript  ,"  quad_pol dominates single_pol;\n");
+	strcat(kfold->descript  ,"  quad_pol dominates dual_pol;\n");
+	strcat(kfold->descript  ,"  dual_pol dominates low_bandwidth_single_pol;\n");
+	strcat(kfold->descript  ,"  dual_pol dominates single_pol;\n");
+	strcat(kfold->descript  ,"  single_pol dominates low_bandwidth_single_pol;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //sensor styles\n");
+	strcat(kfold->descript  ,"  2 0xff00ffff 0xff000000;\n");
+	strcat(kfold->descript  ,"  102 0x7f00ffff 0xff00ffff;\n");
+	strcat(kfold->descript  ,"  1002 0xffffff00 0xffffff00;\n");
+	strcat(kfold->descript  ,"  1102 0x7fffff00 0xffffff00;\n");
+	strcat(kfold->descript  ,"\n");
+	strcat(kfold->descript  ,"  //discipline styles\n");
+	strcat(kfold->descript  ,"  deformation 0xff006090 0xff006090 0xff0000ff 0xff1010ff;\n");
+	strcat(kfold->descript  ,"  vegetation  0xff00ff00 0xff00ff00 0xff0000ff 0xff0020ff;\n");
+	strcat(kfold->descript  ,"  ice         0xffff0000 0xffff0000 0xff0000ff 0xff2000ff;\n");
+	strcat(kfold->descript  ,"}");
+
+	if (edata)
+		for (i=0; i<melem; i++) {
+			if (edata[i] < cmin)
+				cmin=edata[i];
+			if (edata[i] > cmax)
+				cmax=edata[i];
+		}
+
+/*  write each element as a polygon placemark  */
+
+	_printf0_("Writing " << melem << " tria elements as KML polygons.\n");
+
+	for (i=0; i<melem; i++) {
+		kplace=new KML_Placemark();
+		sprintf(kplace->name      ,"Element %d",(i+1));
+		kplace->visibility=1;
+		if (edata) {
+//			sprintf(kplace->descript  ,"Element data: %g",edata[i]);
+			sprintf(kplace->descript  ,"campaign{\n  deformation 1 %g quad_pol ascending right asap;\n}",edata[i]);
+			imap = (int)floor((edata[i]-cmin)/(cmax-cmin)*mcmap+0.5)+1;
+			if      ((imap >= 1) && (imap <= mcmap))
+				sprintf(kplace->styleurl  ,"#MatlabColor%d",imap);
+			else if (edata[i] == cmax)
+				sprintf(kplace->styleurl  ,"#MatlabColor%d",mcmap);
+			else
+				sprintf(kplace->styleurl  ,"#BlackLineEmptyPoly");
+		}
+		else {
+			sprintf(kplace->descript  ,"");
+			sprintf(kplace->styleurl  ,"#BlackLineRandomPoly");
+		}
+//		kplace->DeepEcho();
+
+		kpoly=new KML_Polygon();
+		kpoly->extrude   =1;
+		sprintf(kpoly->altmode   ,"clampToGround");
+//		kpoly->DeepEcho();
+
+		kring=new KML_LinearRing();
+		kring->ncoord    =nelem+1;
+		kring->coords =xNew<double>((nelem+1)*3);
+
+/*  write the nodal coordinates as a linear ring  */
+
+		for (j=0; j<nelem; j++) {
+			kring->coords[3*j+0]=lng[elem[ipt]-1];
+			kring->coords[3*j+1]=lat[elem[ipt]-1];
+			kring->coords[3*j+2]=alt;
+			ipt++;
+		}
+		kring->coords[3*nelem+0]=kring->coords[3*0+0];
+		kring->coords[3*nelem+1]=kring->coords[3*0+1];
+		kring->coords[3*nelem+2]=kring->coords[3*0+2];
+//		kring->DeepEcho();
+
+/*  assemble the linear ring into polygon into placemark into folder  */
+
+		(kpoly ->outer   )->AddObject((Object*)kring);
+		(kplace->geometry)->AddObject((Object*)kpoly);
+		(kfold ->feature )->AddObject((Object*)kplace);
+
+//		if (!(int)fmod((double)(i+1),1000))
+//			_printf0_("  " << (i+1) << " tria elements written.\n");
+	}
+	_printf0_("  " << melem << " tria elements written.\n");
+
+	return(kfold);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 18231)
@@ -0,0 +1,29 @@
+/*!\file:  KMLMeshWritex.h
+ * \brief header file for kml mesh writer routines.
+ */ 
+
+#ifndef _KMLMESHWRITEX_H
+#define _KMLMESHWRITEX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../kml/kmlobjects.h"
+
+/* local prototypes: */
+void KMLMeshWritex(int* ierror,
+				   char* name,
+				   char* notes,
+				   int* elem,int melem,int nelem,
+				   int* nodecon,int mncon,int nncon,
+				   double* lat, double* lng,
+				   int* part,
+				   double* data, int mdata, int ndata,
+				   double* cmap, int mcmap, int ncmap,
+				   FILE* fid);
+
+KML_Folder* KMLMeshElem(int* elem,int melem,int nelem,
+						int* nodecon,int mncon,int nncon,
+						double* lat, double* lng,
+						double* edata,
+						double* cmap, int mcmap, int ncmap);
+
+#endif  /* _KMLMESHWRITEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 18231)
@@ -0,0 +1,92 @@
+/*!\file KMLOverlayx
+ */
+
+#include "./KMLOverlayx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../kml/kmlobjects.h"
+
+void KMLOverlayx(int* ierror,
+				 double* lataxis, double* longaxis,
+				 int nimages, char** pimages,
+				 FILE* fid){
+
+	int     i;
+	char    indent[81]="";
+	KML_File*          kfile=NULL;
+	KML_Document*      kdoc=NULL;
+	KML_Folder*        kfold=NULL;
+	KML_GroundOverlay* kgover=NULL;
+	KML_Icon*          kicon=NULL;
+	KML_LatLonBox*     kllbox=NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nKMLOverlayx Module -- " << ctime(&time0));
+
+/*  construct kml file  */
+
+	kfile=new KML_File();
+	kfile->AddAttrib("xmlns","http://www.opengis.net/kml/2.2");
+
+/*  construct kml document  */
+
+	kdoc=new KML_Document();
+	sprintf(kdoc->name      ,"Ground Overlays from ISSM");
+	kdoc->open      =1;
+
+/*  construct kml folder for overlays  */
+
+	kfold=new KML_Folder();
+	sprintf(kfold->name      ,"Ground Overlays");
+	kfold->open      =1;
+
+/*  construct ground overlay, icon, and lat/long box for each image  */
+
+	for (i=0; i<nimages; i++) {
+		kgover=new KML_GroundOverlay();
+		sprintf(kgover->name      ,"%s",pimages[i]);
+		kgover->visibility=0;
+
+		kicon=new KML_Icon();
+		sprintf(kicon->href      ,"%s",pimages[i]);
+		kgover->icon      =kicon;
+		kicon=NULL;
+
+		kllbox=new KML_LatLonBox();
+		kllbox->north     =lataxis[1];
+		kllbox->south     =lataxis[0];
+		kllbox->east      =longaxis[1];
+		kllbox->west      =longaxis[0];
+		kllbox->rotation  = 0.;
+		kgover->llbox     =kllbox;
+		kllbox=NULL;
+
+		(kfold->feature   )->AddObject((Object*)kgover);
+		kgover=NULL;
+	}
+
+/*  assemble the rest of the kml hierarchy  */
+
+	(kdoc->feature   )->AddObject((Object*)kfold);
+	kfold=NULL;
+	(kfile->kmlobj    )->AddObject((Object*)kdoc);
+	kdoc=NULL;
+
+/*  write kml file  */
+
+	_printf0_("Writing kml document to file.\n");
+	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+	kfile->Write(fid,indent);
+
+	delete kfile;
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("KMLOverlayx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 18231)
@@ -0,0 +1,17 @@
+/*!\file:  KMLOverlayx.h
+ * \brief header file for kml file overlay routines.
+ */ 
+
+#ifndef _KMLOVERLAYX_H
+#define _KMLOVERLAYX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void KMLOverlayx(int* ierror,
+				 double* lataxis, double* longaxis,
+				 int nimages, char** pimages,
+				 FILE* fid);
+
+#endif  /* _KMLOVERLAYX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\file Kml2Expx
+ * \brief kml to exp conversion routines.
+ */
+
+#include "./Kml2Expx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../KMLFileReadx/KMLFileReadx.h"
+
+int Kml2Expx(char* filkml,char* filexp,int sgn){
+
+	double  cm,sp;
+	Ll2xydef(&cm,&sp,sgn);
+
+	return(Kml2Expx(filkml,filexp,sgn,cm,sp));
+}
+
+int Kml2Expx(char* filkml,char* filexp,int sgn,double cm,double sp){
+
+	int         iret   = 0;
+	KML_Object *kobj   = NULL;
+	FILE       *fidi   = NULL;
+	FILE       *fido   = NULL;
+	clock_t     clock0,clock1;
+	time_t      time0 ,time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nKml2Expx Module -- " << ctime(&time0));
+
+	/*read kml file*/
+	fidi=fopen(filkml,"r");
+	if (!(kobj=KMLFileReadx(fidi)))
+	 _error_("Error reading kml file.");
+	fclose(fidi);
+
+	/*open exp file*/
+	_printf0_("Writing exp profiles to file.\n");
+	fido=fopen(filexp,"w");
+
+	/*write the polygons and linestrings  */
+	kobj->WriteExp(fido,"",sgn,cm,sp);
+
+	/*close exp file  */
+	fclose(fido);
+	delete kobj;
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("Kml2Expx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return(iret);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 18231)
@@ -0,0 +1,17 @@
+/*!\file:  Kml2Expx.h
+ * \brief header file for kml to exp conversion routines.
+ */ 
+
+#ifndef _KML2EXPX_H
+#define _KML2EXPX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int Kml2Expx(char* filkml,char* filexp,
+			 int sgn);
+int Kml2Expx(char* filkml,char* filexp,
+			 int sgn,double cm,double sp);
+
+#endif  /* _KML2EXPX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.cpp	(revision 18231)
@@ -0,0 +1,423 @@
+/*!\file:  Kriging.cpp
+ * \brief  "c" core code for Kriging
+ */ 
+
+#include "./Krigingx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../modules.h"
+#ifdef _HAVE_GSL_
+#include <gsl/gsl_linalg.h>
+#endif
+int   Krigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){/*{{{*/
+
+	/*output*/
+	double *predictions = NULL;
+	double *error       = NULL;
+
+	/*Intermediaries*/
+	int           mindata,maxdata;
+	double        dmindata,dmaxdata,dnumthreads; //FIXME (Options come as double but we want to retrive integers)
+	double        radius;
+	char         *output       = NULL;
+	Variogram    *variogram    = NULL;
+	Observations *observations = NULL;
+
+	/*threading: */
+	KrigingxThreadStruct gate;
+	int num = _NUMTHREADS_;
+
+	/*Get Variogram from Options*/
+	ProcessVariogram(&variogram,options);
+	options->Get(&radius,"searchradius",0.);
+	options->Get(&dmindata,"mindata",1.);  mindata=int(dmindata);//FIXME (Options come as double but we want to retrive integers)
+	options->Get(&dmaxdata,"maxdata",50.); maxdata=int(dmaxdata);//FIXME (Options come as double but we want to retrive integers)
+	options->Get(&dnumthreads,"numthreads",double(num)); num=int(dnumthreads);//FIXME (Options come as double but we want to retrive integers)
+
+	/*Process observation dataset*/
+	observations=new Observations(obs_list,obs_x,obs_y,obs_length,options);
+
+	/*Allocate output*/
+	predictions =xNewZeroInit<double>(n_interp);
+	error       =xNewZeroInit<double>(n_interp);
+
+	/*Get output*/
+	options->Get(&output,"output",(char*)"prediction");
+
+	if(strcmp(output,"quadtree")==0){
+		observations->QuadtreeColoring(predictions,x_interp,y_interp,n_interp);
+	}
+	else if(strcmp(output,"variomap")==0){
+		observations->Variomap(predictions,x_interp,n_interp);
+	}
+	else if(strcmp(output,"distance")==0){
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.numdone      = xNewZeroInit<int>(num);
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(Distancest,(void*)&gate,num);
+		xDelete<int>(gate.numdone);
+	}
+	else if(strcmp(output,"delaunay")==0){
+		int nobs,nel;
+		double *x     = NULL;
+		double *y     = NULL;
+		double *data  = NULL;
+		int    *index = NULL;
+
+		observations->ObservationList(&x,&y,&data,&nobs);
+
+		_printf_("Generation Delaunay Triangulation\n");
+		BamgTriangulatex(&index,&nel,x,y,nobs);
+
+		_printf_("Interpolating\n");
+		xDelete<double>(predictions);
+		InterpFromMeshToMesh2dx(&predictions,index,x,y,nobs,nel,data,nobs,1,x_interp,y_interp,n_interp,options);
+		xDelete<double>(x);
+		xDelete<double>(y);
+		xDelete<double>(data);
+		xDelete<int>(index);
+	}
+	else if(strcmp(output,"nearestneighbor")==0){
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.numdone      = xNewZeroInit<int>(num);
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(NearestNeighbort,(void*)&gate,num);
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+		xDelete<int>(gate.numdone);
+	}
+	else if(strcmp(output,"idw")==0){ //Inverse distance weighting
+		double power;
+		options->Get(&power,"power",2.);
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.numdone      = xNewZeroInit<int>(num);
+		gate.power        = power;
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(idwt,(void*)&gate,num);
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+		xDelete<int>(gate.numdone);
+	}
+	else if(strcmp(output,"v4")==0){ //Inverse distance weighting
+#if !defined(_HAVE_GSL_)
+		_error_("GSL is required for v4 interpolation");
+#endif
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.numdone      = xNewZeroInit<int>(num);
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(v4t,(void*)&gate,num);
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+		xDelete<int>(gate.numdone);
+	}
+	else if(strcmp(output,"prediction")==0){
+#if !defined(_HAVE_GSL_)
+		_error_("GSL is required for v4 interpolation");
+#endif
+
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.numdone      = xNewZeroInit<int>(num);
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(Krigingxt,(void*)&gate,num);
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+		xDelete<int>(gate.numdone);
+	}
+	else{
+		_error_("output '" << output << "' not supported yet");
+	}
+
+	/*clean-up and Assign output pointer*/
+	delete variogram;
+	delete observations;
+	xDelete<char>(output);
+	*ppredictions = predictions;
+	*perror       = error;
+	return 1;
+}/*}}}*/
+void* Krigingxt(void* vpthread_handle){/*{{{*/
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	int          *numdone      = gate->numdone;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		numdone[my_thread]=idx-i0;
+		if(my_thread==0){
+			int alldone=numdone[0];
+			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
+		}
+
+		/*Kriging interpolation*/
+		observations->InterpolationKriging(&predictions[idx],&error[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,variogram);
+	}
+
+	return NULL;
+}/*}}}*/
+void* NearestNeighbort(void* vpthread_handle){/*{{{*/
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	int          *numdone      = gate->numdone;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		numdone[my_thread]=idx-i0;
+		if(my_thread==0){
+			int alldone=numdone[0];
+			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
+		}
+
+		observations->InterpolationNearestNeighbor(&predictions[idx],x_interp[idx],y_interp[idx],radius);
+	}
+
+	return NULL;
+}/*}}}*/
+void* idwt(void* vpthread_handle){/*{{{*/
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	int          *numdone      = gate->numdone;
+	double        power        = gate->power;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		numdone[my_thread]=idx-i0;
+		if(my_thread==0){
+			int alldone=numdone[0];
+			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
+		}
+
+		observations->InterpolationIDW(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,power);
+	}
+	return NULL;
+}/*}}}*/
+void* v4t(void* vpthread_handle){/*{{{*/
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	int          *numdone      = gate->numdone;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		numdone[my_thread]=idx-i0;
+		if(my_thread==0){
+			int alldone=numdone[0];
+			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
+		}
+
+		observations->InterpolationV4(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata);
+	}
+	return NULL;
+}/*}}}*/
+void* Distancest(void* vpthread_handle){/*{{{*/
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	int          *numdone      = gate->numdone;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	observations->Distances(&predictions[i0],&x_interp[i0],&y_interp[i0],i1-i0,radius);
+	return NULL;
+}/*}}}*/
+
+void ProcessVariogram(Variogram **pvariogram,Options* options){/*{{{*/
+
+	/*Intermediaries*/
+	Variogram* variogram = NULL;
+	char      *model     = NULL;
+
+	if(options->GetOption("model")){
+		options->Get(&model,"model");
+		if     (strcmp(model,"gaussian")==0)    variogram = new GaussianVariogram(options);
+		else if(strcmp(model,"exponential")==0) variogram = new ExponentialVariogram(options);
+		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
+		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
+		else _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
+	}
+	else variogram = new GaussianVariogram(options);
+
+	/*Assign output pointer*/
+	xDelete<char>(model);
+	*pvariogram = variogram;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/Krigingx.h	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file Kriging.h
+ * \brief: header file for Kriging
+ */
+
+#ifndef _KRIGINGX_H
+#define _KRIGINGX_H
+
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+class Observations;
+class Variogram;
+
+int  Krigingx(double** ppredictions,double **perror,double* x, double* y, double* observations, int n_obs,double* x_interp,double* y_interp,int n_interp,Options* options);
+int  pKrigingx(double** ppredictions,double **perror,double* x, double* y, double* observations, int n_obs,double* x_interp,double* y_interp,int n_interp,Options* options);
+void ProcessVariogram(Variogram **pvariogram,Options* options);
+void ProcessVariogram2(Variogram **pvariogram,Options* options);
+
+/*threading: */
+typedef struct{
+	int           n_interp;
+	double       *x_interp;
+	double       *y_interp;
+	double        radius;
+	int           mindata;
+	int           maxdata;
+	Variogram    *variogram;
+	Observations *observations;
+	double       *predictions;
+	double       *error;
+	int          *numdone;
+	double        power;//for idw
+}KrigingxThreadStruct;
+
+void* Krigingxt(void*);
+void* NearestNeighbort(void*);
+void* idwt(void*);
+void* v4t(void*);
+void* Distancest(void*);
+#endif /* _KRIGINGX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/pKrigingx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Krigingx/pKrigingx.cpp	(revision 18231)
@@ -0,0 +1,177 @@
+/*!\file:  Kriging.cpp
+ * \brief  "c" core code for Kriging
+ */ 
+
+#include "./Krigingx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/io/io.h"
+
+int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){/*{{{*/
+
+#ifdef _HAVE_MPI_
+	int num_procs;
+	int my_rank;
+
+	/*output*/
+	double *predictions = NULL;
+	double *error       = NULL;
+
+	/*Intermediaries*/
+	int           mindata,maxdata;
+	double        dmindata,dmaxdata;
+	double        radius;
+	char         *output       = NULL;
+	Variogram    *variogram    = NULL;
+	Observations *observations = NULL;
+
+	/*timing*/
+	double   start, finish;
+	double   start_core, finish_core;
+	double   start_init, finish_init;
+
+	/*Get my_rank: */
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
+	/*Get some Options*/
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start=ISSM_MPI_Wtime();
+	options->Get(&radius,"searchradius",0.);
+
+	options->Get(&dmindata,"mindata",1.);  mindata=int(dmindata);//FIXME (Options come as double but we want to retrive integers)
+	options->Get(&dmaxdata,"maxdata",50.); maxdata=int(dmaxdata);//FIXME (Options come as double but we want to retrive integers)
+
+	/*Process observation dataset*/
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start_init=ISSM_MPI_Wtime();
+	observations=new Observations(obs_list,obs_x,obs_y,obs_length,options);
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish_init=ISSM_MPI_Wtime();
+
+	/*Allocate output*/
+	predictions =xNewZeroInit<double>(n_interp);
+	error       =xNewZeroInit<double>(n_interp);
+
+	/*Get output*/
+	options->Get(&output,"output",(char*)"prediction");
+
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start_core=ISSM_MPI_Wtime( );
+	if(strcmp(output,"quadtree")==0){
+		observations->QuadtreeColoring(predictions,x_interp,y_interp,n_interp);
+	}
+	else if(strcmp(output,"variomap")==0){
+		observations->Variomap(predictions,x_interp,n_interp);
+	}
+	else if(strcmp(output,"prediction")==0){
+
+		/*Process Variogram*/
+		ProcessVariogram2(&variogram,options);
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
+			observations->InterpolationKriging(&predictions[idx],&error[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,variogram);
+		}
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
+
+		double *sumpredictions =xNew<double>(n_interp);
+		double *sumerror       =xNew<double>(n_interp);
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(error,sumerror,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		xDelete<double>(error); error=sumerror;
+		xDelete<double>(predictions); predictions=sumpredictions;
+	}
+	else if(strcmp(output,"v4")==0){
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
+			observations->InterpolationV4(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata);
+		}
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
+
+		double *sumpredictions =xNew<double>(n_interp);
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		xDelete<double>(predictions); predictions=sumpredictions;
+	}
+	else if(strcmp(output,"nearestneighbor")==0){
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
+			observations->InterpolationNearestNeighbor(&predictions[idx],x_interp[idx],y_interp[idx],radius);
+		}
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
+
+		double *sumpredictions =xNew<double>(n_interp);
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		xDelete<double>(predictions); predictions=sumpredictions;
+	}
+	else if(strcmp(output,"distance")==0){
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
+			observations->Distances(&predictions[idx],&x_interp[idx],&y_interp[idx],1,radius);
+		}
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
+
+		double *sumpredictions =xNew<double>(n_interp);
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		xDelete<double>(predictions); predictions=sumpredictions;
+	}
+	else if(strcmp(output,"idw")==0){
+		double power;
+		options->Get(&power,"power",2.);
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
+			observations->InterpolationIDW(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,power);
+		}
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
+
+		double *sumpredictions =xNew<double>(n_interp);
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		xDelete<double>(predictions); predictions=sumpredictions;
+	}
+	else{
+		_error_("output '" << output << "' not supported yet");
+	}
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish_core=ISSM_MPI_Wtime( );
+
+	/*clean-up and Assign output pointer*/
+	delete variogram;
+	delete observations;
+	xDelete<char>(output);
+	*ppredictions = predictions;
+	*perror       = error;
+
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish=ISSM_MPI_Wtime( );
+	_printf0_("\n   " << setw(34) << left << "Observation fitering elapsed time: " << finish_init-start_init << " seconds  \n\n");
+	_printf0_("   " << setw(34) << left << "Kriging prediction elapsed time: " << finish_core-start_core << " seconds  \n\n");
+	_printf0_("\n   " << "Total elapsed time " << int((finish-start)/3600) << " hrs " << int(int(finish-start)%3600/60) << " min " << int(finish-start)%60 << " sec\n\n\n");
+	return 1;
+#else
+	_error_("MPI not available");
+#endif
+}/*}}}*/
+void ProcessVariogram2(Variogram **pvariogram,Options* options){/*{{{*/
+
+	/*Intermediaries*/
+	Variogram* variogram = NULL;
+	char      *model     = NULL;
+
+	if(options->GetOption("model")){
+		options->Get(&model,"model");
+		if     (strcmp(model,"gaussian")==0)    variogram = new GaussianVariogram(options);
+		else if(strcmp(model,"exponential")==0) variogram = new ExponentialVariogram(options);
+		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
+		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
+		else _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
+	}
+	else variogram = new GaussianVariogram(options);
+
+	/*Assign output pointer*/
+	xDelete<char>(model);
+	*pvariogram = variogram;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file Mergesolutionfromftogx
+ * \brief merge solution back from f set into g set
+ */
+
+#include "../VecMergex/VecMergex.h"
+#include "../../shared/io/io.h"
+#include "./Mergesolutionfromftogx.h"
+
+void	Mergesolutionfromftogx( Vector<IssmDouble>** pug, Vector<IssmDouble>* uf, Vector<IssmDouble>* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0){
+
+	/*output: */
+	Vector<IssmDouble>* ug=NULL;
+
+	/*intermediary: */
+	int configuration_type;
+	int gsize,fsize,ssize;
+
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Merging solution vector from fset to gset\n");
+
+	/*first, get gsize, fsize and ssize: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
+	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+
+	/*serialize uf and ys: those two vectors will be indexed by the nodes, who are the only ones 
+	 *that know which values should be plugged into ug and where: */
+	if(ssize){
+		if(flag_ys0){
+			ys->Set(0.0);
+		}
+	}
+
+	/*initialize ug: */
+	ug=new Vector<IssmDouble>(gsize);
+
+	/*Merge f set back into g set: */
+	if(fsize){
+		VecMergex(ug,uf,nodes,parameters,FsetEnum);
+	}
+
+	/*Merge s set back into g set: */
+	if(ssize){
+		VecMergex(ug,ys,nodes,parameters,SsetEnum);
+	}
+
+	/*Assign correct pointer*/
+	*pug=ug;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  Mergesolutionfromftogx.h
+ * \brief merge solution back from f set into g set
+ */ 
+
+#ifndef _MERGESOLUTIONFROMFTOGX_H
+#define _MERGESOLUTIONFROMFTOGX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	Mergesolutionfromftogx( Vector<IssmDouble>** pug, Vector<IssmDouble>* uf, Vector<IssmDouble>* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0=false);
+
+#endif  /* _MERGESOLUTIONFROMFTOGX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 18231)
@@ -0,0 +1,126 @@
+/*!\file:  MeshPartitionx.h
+ * \brief  header file for partitioning module.
+ */ 
+
+#ifndef _MESHPARTITIONX_H
+#define _MESHPARTITIONX_H
+
+#include "../../shared/shared.h"
+
+/* local prototypes: */
+template <class doubletype> 
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,int* elements,
+		int numberofelements2d,int numberofnodes2d,doubletype* elements2d,int numlayers,int elements_width, int meshelementtype,int num_procs){
+
+	int noerr=1;
+	int i,j;
+
+	/*Metis partitioning: */
+	int* epart=NULL;
+	int* npart=NULL;
+	int* index=NULL;
+
+	int* epart2d=NULL;
+	int* npart2d=NULL;
+	int* index2d=NULL;
+	int  count=0;
+
+	int  etype=1; //tria mesh see metis/Programs/Io.c
+	int  etype2d=1; //tria mesh see metis/Programs/Io.c
+	int  numflag=0;
+	int  edgecut=1;
+
+	switch(meshelementtype){
+		case TriaEnum:
+		case TetraEnum:
+			epart=xNew<int>(numberofelements);
+			npart=xNew<int>(numberofnodes);
+			index=xNew<int>(elements_width*numberofelements);
+			for (i=0;i<numberofelements;i++){
+				for (j=0;j<elements_width;j++){
+					*(index+elements_width*i+j)=(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+				}
+			}
+
+			/*Partition using Metis:*/
+			if (num_procs>1){
+#ifdef _HAVE_METIS_
+				METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
+#else
+				_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+#endif
+			}
+			else if (num_procs==1){
+				/*METIS does not know how to deal with one cpu only!*/
+				for (i=0;i<numberofelements;i++) epart[i]=0;
+				for (i=0;i<numberofnodes;i++)    npart[i]=0;
+			}
+			else _error_("At least one processor is required");
+			break;
+		case PentaEnum:
+			/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
+
+			/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
+			epart2d=xNew<int>(numberofelements2d);
+			npart2d=xNew<int>(numberofnodes2d); 
+			index2d=xNew<int>(3*numberofelements2d);
+
+			for (i=0;i<numberofelements2d;i++){
+				for (j=0;j<3;j++){
+					*(index2d+3*i+j)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
+				}
+			}
+
+			/*Partition using Metis:*/
+			if (num_procs>1){
+#ifdef _HAVE_METIS_
+				METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
+#else
+				_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+#endif
+			}
+			else if (num_procs==1){
+				/*METIS does not know how to deal with one cpu only!*/
+				for (i=0;i<numberofelements2d;i++) epart2d[i]=0;
+				for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
+			}
+			else _error_("At least one processor is required");
+
+			/*Extrude epart2d to epart, using numlayers: */
+			epart=xNew<int>(numberofelements);
+
+			count=0;
+			for(i=0;i<(numlayers-1);i++){
+				for(j=0;j<numberofelements2d;j++){
+					epart[count]=epart2d[j];
+					count++;
+				}
+			}
+
+			/*Extrude npart2d to npart, using numlayers: */
+			npart=xNew<int>(numberofnodes);
+
+			count=0;
+			for(i=0;i<(numlayers);i++){
+				for(j=0;j<numberofnodes2d;j++){
+					npart[count]=npart2d[j];
+					count++;
+				}
+			}
+			break;
+		default:
+			_error_("mesh type "<<EnumToStringx(meshelementtype)<<" not supported yet");
+	}
+
+	/*Assign output pointer:*/
+	*pepart=epart;
+	*pnpart=npart;
+
+	/*Free ressources: */
+	xDelete<int>(index);
+	xDelete<int>(epart2d);
+	xDelete<int>(npart2d);
+	xDelete<int>(index2d);
+	return noerr;
+}
+#endif /* _MESHPARTITIONX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 18231)
@@ -0,0 +1,345 @@
+/*! \file  MeshProfileIntersectionx.c
+ */
+
+#include "./MeshProfileIntersectionx.h"
+
+void MeshProfileIntersectionx(double** psegments, int* pnumsegs, int* index, double* x, double* y, int nel, int nods,  Contour<IssmPDouble>** contours,int numcontours){/*{{{*/
+
+	int i,j,k;
+
+	/*Contour:*/
+	Contour<IssmPDouble>* contouri=NULL;
+	int      numnodes;
+	double*  xc=NULL;
+	double*  yc=NULL;
+
+	/*output: */
+	double* segments=NULL;
+	int     numsegs;
+
+	/*intermediary: */
+	double** allsegments=NULL;
+	double*  segmentsi=NULL;
+	int*     allnumsegs=NULL;
+	int      numsegsi;
+	int      count;
+
+	/*Allocate: */
+	allsegments=xNew<double*>(numcontours);
+	allnumsegs=xNew<int>(numcontours);
+
+	/*Loop through all contours: */
+	for (i=0;i<numcontours;i++){
+
+		/*retrieve contour info: */
+		contouri=*(contours+i);
+		numnodes=contouri->nods;
+		xc=contouri->x;
+		yc=contouri->y;
+
+		/*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;
+		allnumsegs[i]=numsegsi;
+	}
+
+	/*total number of segments? */
+	numsegs=0;
+	for(i=0;i<numcontours;i++)numsegs+=allnumsegs[i];
+
+	/*Out of all segments, create one common array of segments: */
+	segments=xNew<double>(5*numsegs);
+	count=0;
+	for(i=0;i<numcontours;i++){
+
+		segmentsi=allsegments[i];
+		numsegsi=allnumsegs[i];
+
+		for(j=0;j<numsegsi;j++){
+			for(k=0;k<5;k++){
+				*(segments+count*5+k)=*(segmentsi+j*5+k);
+			}
+			count++;
+		}
+	}
+
+	/*Assign output pointers:*/
+	*psegments=segments;
+	*pnumsegs=numsegs;
+}/*}}}*/
+void MeshSegmentsIntersection(double** psegments, int* pnumsegs,int* index, double* x, double* y, int nel, int nods, double* xc, double* yc, int numnodes){/*{{{*/
+
+	int      i,j;
+
+	/*output: */
+	double* segments=NULL;
+	int     numsegs;
+
+	/*intermediary: */
+	DataSet* segments_dataset=NULL;
+	double   xnodes[3];
+	double   ynodes[3];
+
+	/*We don't know how many segments  we are going to get, so have a dynamic container: */
+	segments_dataset=new DataSet();
+
+	/*Go through elements, and call ElementSegmentsIntersection routine: */
+	for(i=0;i<nel;i++){
+		for(j=0;j<3;j++){
+			xnodes[j]=x[*(index+3*i+j)];
+			ynodes[j]=y[*(index+3*i+j)];
+		}
+		ElementSegmentsIntersection(segments_dataset,i,xnodes,ynodes,xc,yc,numnodes);
+	}
+
+	/*Using the segments_dataset dataset, create segments: */
+	numsegs=segments_dataset->Size();
+	segments=xNew<double>(5*numsegs);
+	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;
+		segments[5*i+1]=segment->y1;
+		segments[5*i+2]=segment->x2;
+		segments[5*i+3]=segment->y2;
+		segments[5*i+4]=(double)segment->eid;
+	}
+
+	/*Free ressources:*/
+	delete segments_dataset;
+
+	/*Assign output pointers:*/
+	*psegments=segments;
+	*pnumsegs=numsegs;
+}/*}}}*/
+
+/*Utilities*/
+void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes){/*{{{*/
+
+	double xsegment[2];
+	double ysegment[2];
+
+	/*Loop through contour: */
+	for(int i=0;i<numnodes-1;i++){
+		xsegment[0]=xc[i];
+		xsegment[1]=xc[i+1];
+		ysegment[0]=yc[i];
+		ysegment[1]=yc[i+1];
+		ElementSegment(segments_dataset,el, xnodes,ynodes,xsegment,ysegment);
+	}
+}/*}}}*/
+void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment){/*{{{*/
+
+	/*We have a tria element (xnodes,ynodes) and a segment (xsegment,ysegment). Find whether they intersect. 
+	 * If they do, create a Segment object with the intersection, and add to segments_dataset dataset: */
+
+	double alpha1,alpha2;
+	double beta1,beta2;
+	double gamma1,gamma2;
+
+	int    edge1,edge2,edge3;
+
+	double xel[2],yel[2];
+	double coord1,coord2;
+	double xfinal[2],yfinal[2];
+
+	/*edge 1: */
+	xel[0]=xnodes[0];  yel[0]=ynodes[0]; xel[1]=xnodes[1];  yel[1]=ynodes[1];
+	edge1=SegmentIntersect(&alpha1,&alpha2, xel,yel,xsegment,ysegment); //alpha1: segment coordinate of intersection. alpha2: same thing for second interesection if it exists (colinear edges)
+
+	/*edge 2: */
+	xel[0]=xnodes[1];  yel[0]=ynodes[1]; xel[1]=xnodes[2];  yel[1]=ynodes[2];
+	edge2=SegmentIntersect(&beta1,&beta2, xel,yel,xsegment,ysegment);
+
+	/*edge 3: */
+	xel[0]=xnodes[2];  yel[0]=ynodes[2]; xel[1]=xnodes[0];  yel[1]=ynodes[0];
+	edge3=SegmentIntersect(&gamma1,&gamma2, xel,yel,xsegment,ysegment);
+
+	/*edge can be either IntersectEnum (one iand only one intersection between the edge and the segment), ColinearEnum (edge and segment are collinear) and SeparateEnum (no intersection): */
+
+	if(    (edge1==IntersectEnum) && (edge2==IntersectEnum) && (edge3==IntersectEnum)   ){
+		/*This case is impossible: */
+		_error_("error: a line cannot go through 3 different vertices!");
+	}
+	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);}
+		if((edge2==IntersectEnum) && (edge3==IntersectEnum)) {coord1=min(beta1,gamma1); coord2=max(beta1,gamma1);}
+		if((edge3==IntersectEnum) && (edge1==IntersectEnum)) {coord1=min(gamma1,alpha1); coord2=max(gamma1,alpha1);}
+
+		/*check this segment did not intersect at a vertex of the tria: */
+		if(coord1!=coord2){
+
+			xfinal[0]=xsegment[0]+coord1*(xsegment[1]-xsegment[0]);
+			xfinal[1]=xsegment[0]+coord2*(xsegment[1]-xsegment[0]);
+			yfinal[0]=ysegment[0]+coord1*(ysegment[1]-ysegment[0]);
+			yfinal[1]=ysegment[0]+coord2*(ysegment[1]-ysegment[0]);
+
+			segments_dataset->AddObject(new  Segment<double>(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+		}
+		else{
+			/*the segment intersected at the vertex, do not bother with this "0" length segment!:*/
+		}
+	}
+	else if(  (edge1==IntersectEnum) || (edge2==IntersectEnum) || (edge3==IntersectEnum)   ){
+
+		/*segment intersect only 1 edge. Figure out where the first point in the segment is, inside or outside the element, 
+		 * this will decide the coordinate: */
+		if (NodeInElement(xnodes,ynodes,xsegment[0],ysegment[0])){
+			coord1=0;
+			if(edge1==IntersectEnum){coord2=alpha1;}
+			if(edge2==IntersectEnum){coord2=beta1;}
+			if(edge3==IntersectEnum){coord2=gamma1;}
+		}
+		else{
+			if(edge1==IntersectEnum){coord1=alpha1;}
+			if(edge2==IntersectEnum){coord1=beta1;}
+			if(edge3==IntersectEnum){coord1=gamma1;}
+			coord2=1.0;
+		}
+
+		xfinal[0]=xsegment[0]+coord1*(xsegment[1]-xsegment[0]);
+		xfinal[1]=xsegment[0]+coord2*(xsegment[1]-xsegment[0]);
+		yfinal[0]=ysegment[0]+coord1*(ysegment[1]-ysegment[0]);
+		yfinal[1]=ysegment[0]+coord2*(ysegment[1]-ysegment[0]);
+
+		segments_dataset->AddObject(new  Segment<double>(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+	}
+	else{
+		/*No interesections, but the segment might be entirely inside this triangle!: */
+		if ( (NodeInElement(xnodes,ynodes,xsegment[0],ysegment[0])) && (NodeInElement(xnodes,ynodes,xsegment[1],ysegment[1])) ){
+			segments_dataset->AddObject(new  Segment<double>(el+1,xsegment[0],ysegment[0],xsegment[1],ysegment[1]));
+		}
+	}
+}/*}}}*/
+bool NodeInElement(double* xnodes, double* ynodes, double x, double y){/*{{{*/
+
+	double x1,y1;
+	double x2,y2;
+	double x3,y3;
+	double lambda1,lambda2,lambda3;
+	double det;
+
+	x1=xnodes[0];
+	x2=xnodes[1];
+	x3=xnodes[2];
+	y1=ynodes[0];
+	y2=ynodes[1];
+	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;
+	lambda2=((y3-y1)*(x-x3)+(x1-x3)*(y-y3))/det;
+	lambda3=1-lambda1-lambda2;
+
+	if( ((lambda1<=1) && (lambda1>=0)) && ((lambda2<=1) && (lambda2>=0)) && ((lambda3<=1) && (lambda3>=0))  )return true;
+	else return false;
+
+}/*}}}*/
+int SegmentIntersect(double* palpha, double* pbeta, double* x1, double* y1, double* x2, double* y2){/*{{{*/
+
+	/*See ISSM_DIR/src/m/utils/Geometry/SegIntersect.m for matlab routine from which we take this routine: */
+
+	/*output: */
+	double alpha=-1;
+	double beta=-1;
+
+	double xA,xB,xC,xD,yA,yB,yC,yD;
+	double O2A[2],O2B[2],O1C[2],O1D[2];
+	double n1[2],n2[2];
+	double test1, test2, test3, test4;
+	double det;
+	double O2O1[2];
+	double pO1A,pO1B,pO1C,pO1D;
+
+	xA=x1[0]; yA=y1[0];
+	xB=x1[1]; yB=y1[1];
+	xC=x2[0]; yC=y2[0];
+	xD=x2[1]; yD=y2[1];
+
+	O2A[0]=xA -(xD/2+xC/2); O2A[1]=yA -(yD/2+yC/2);
+	O2B[0]=xB -(xD/2+xC/2); O2B[1]=yB -(yD/2+yC/2);
+	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
+	n2[0]=yC-yD; n2[1]=xD-xC;  //normal vector to segB
+
+	test1=n2[0]*O2A[0]+n2[1]*O2A[1];
+	test2=n2[0]*O2B[0]+n2[1]*O2B[1];
+
+	if (test1*test2>0){
+		return SeparateEnum;
+	}
+
+	test3=n1[0]*O1C[0]+n1[1]*O1C[1];
+	test4=n1[0]*O1D[0]+n1[1]*O1D[1];
+
+	if (test3*test4>0){
+		return SeparateEnum;
+	}
+
+	/*If colinear: */
+	det=n1[0]*n2[1]-n2[0]*n1[1];
+
+	if(test1*test2==0 && test3*test4==0 && det==0){
+
+		//projection on the axis O1O2
+		O2O1[0]=(xA/2+xB/2)-(xD/2+xC/2);
+		O2O1[1]=(yA/2+yB/2)-(yD/2+yC/2);
+
+		pO1A=O2O1[0]*(O2A[0]-O2O1[0])+O2O1[1]*(O2A[1]-O2O1[1]);
+		pO1B=O2O1[0]*(O2B[0]-O2O1[0])+O2O1[1]*(O2B[1]-O2O1[1]);
+		pO1C=O2O1[0]*O1C[0]+O2O1[1]*O1C[1];
+		pO1D=O2O1[0]*O1D[0]+O2O1[1]*O1D[1];
+
+		//test if one point is included in the other segment (->intersects=true)
+		if ((pO1C-pO1A)*(pO1D-pO1A)<0){
+			alpha=0; beta=0;
+			*palpha=alpha;*pbeta=beta;
+			return ColinearEnum;
+		}
+		if ((pO1C-pO1B)*(pO1D-pO1B)<0){
+			alpha=0; beta=0;
+			*palpha=alpha;*pbeta=beta;
+			return ColinearEnum;
+		}
+		if ((pO1A-pO1C)*(pO1B-pO1C)<0){
+			alpha=0; beta=0;
+			*palpha=alpha;*pbeta=beta;
+			return ColinearEnum;
+		}
+		if ((pO1A-pO1D)*(pO1B-pO1D)<0){
+			alpha=0; beta=0;
+			*palpha=alpha;*pbeta=beta;
+			return ColinearEnum;
+		}
+
+		//test if the 2 segments have the same middle (->intersects=true)
+		if (O2O1==0){
+			alpha=0; beta=0;
+			*palpha=alpha;*pbeta=beta;
+			return ColinearEnum;
+		}
+
+		//if we are here, both segments are colinear, but do not interset:
+		alpha=-1; beta=-1;
+		*palpha=alpha;*pbeta=beta;
+		return SeparateEnum;
+	}
+
+	/*if we are here, both segments intersect. Determine where in the segment coordinate 
+	 * system: */
+	beta=-1;
+	alpha=-(xA*yB-xC*yB+yC*xB-yC*xA+xC*yA-yA*xB)/(-xD*yB+xD*yA+xC*yB-xC*yA-yD*xA+yD*xB+yC*xA-yC*xB); //from intersect.m in formal calculus
+
+	*palpha=alpha;*pbeta=beta;
+	return IntersectEnum;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 18231)
@@ -0,0 +1,19 @@
+/*
+	MeshProfileIntersectionx.h
+*/
+
+#ifndef _MESHPROFILEINTERSECTIONX_H
+#define _MESHPROFILEINTERSECTIONX_H
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void MeshProfileIntersectionx(double** psegments, int* pnumseg, int* index, double* x, double* y, int nel, int nods,  Contour<IssmPDouble>** contours,int numcontours);
+void MeshSegmentsIntersection(double** psegments, int* pnumsegs,int* index, double* x, double* y, int nel, int nods, double* xc, double* yc, int numnodes);
+void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes);
+void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment);
+int  SegmentIntersect(double* palpha, double* pbeta, double* x1, double* y1, double* x2, double* y2);
+bool NodeInElement(double* xnodes, double* ynodes, double x, double y);
+
+#endif /* _MESHPROFILEINTERSECTIONX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 18231)
@@ -0,0 +1,162 @@
+/*!\file: CreateParametersAutodiff.cpp
+ * \brief driver for creating parameters dataset, for autodiff analysis.
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersAutodiff(Parameters* parameters,IoModel* iomodel){
+
+	int         i;
+	bool        autodiff_analysis;
+	int         num_dependent_objects;
+	int         num_dep=0;
+	char**      names=NULL;
+	int*        types=NULL;
+	int         dummy;
+	char*       autodiff_driver=NULL;
+	int*        indices=NULL;
+	int         num_indices;
+	char* options=NULL;
+
+	IssmDouble* xp=NULL;
+	IssmDouble* xp_backup=NULL;
+	int         num_ind,local_num_ind;
+	DataSet*    dependent_objects=NULL;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&autodiff_analysis,AutodiffIsautodiffEnum);
+
+	if(autodiff_analysis){
+
+		#ifdef _HAVE_ADOLC_
+
+		/*Copy some parameters from IoModel to parameters dataset: {{{*/
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffKeepEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffObufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffCbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffLbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffTbufsizeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffGcTriggerRatioEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffGcTriggerMaxSizeEnum));
+		/*}}}*/
+		/*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);
+		}
+		xDelete<char>(autodiff_driver);
+		/*}}}*/
+		/*Deal with dependents first: {{{*/
+		iomodel->Constant(&num_dependent_objects,AutodiffNumDependentObjectsEnum);
+		dependent_objects=new DataSet();
+		num_dep=0;
+
+		if(num_dependent_objects){
+			iomodel->FetchData(&names,&dummy,AutodiffDependentObjectNamesEnum);
+			iomodel->FetchData(&types,&dummy,&dummy,AutodiffDependentObjectTypesEnum);
+			iomodel->FetchData(&indices,&dummy,&dummy,AutodiffDependentObjectIndicesEnum);
+
+			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();
+			}
+
+			/*Free ressources:*/
+			for(i=0;i<num_dependent_objects;i++){
+				char* string=names[i]; xDelete<char>(string);
+			}
+			xDelete<char*>(names);
+			xDelete<int>(types);
+			xDelete<int>(indices);
+		}
+		parameters->AddObject(new DataSetParam(AutodiffDependentObjectsEnum,dependent_objects));
+		parameters->AddObject(new IntParam(AutodiffNumDependentsEnum,num_dep));
+
+		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));
+			xDelete<IssmDouble>(xp);
+		}
+		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);
+
+		/*Solver pointers depend on what type of solver we are implementing: */
+		options=OptionsFromAnalysis(parameters,DefaultAnalysisEnum); //options database is not filled in yet, use default.
+		ToolkitOptions::Init(options);
+
+		switch(IssmSolverTypeFromToolkitOptions()){
+			case MumpsEnum:{
+				#ifdef _HAVE_MUMPS_
+				theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(mumpsSolveEDF);
+				#else
+				_error_("requesting mumps solver without MUMPS being compiled in!");
+				#endif
+				break;
+							}
+			case GslEnum: {
+				#ifdef _HAVE_GSL_
+				theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
+				#endif
+			    break;
+						  }
+			default:
+				_error_("solver type not supported yet!");
+		}
+
+		// 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 meaningful prior value
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_y_priorRequired=false;
+		// the solver wrapper makes sure the matrix and the right hand side don't change
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_x_changes=false;
+		parameters->AddObject(theAdolcEDF_p);
+
+		/*Free ressources: */
+		xDelete<char>(options);
+		/*}}}*/
+	#endif
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file: CreateParametersControl.cpp
+ * \brief driver for creating parameters dataset, for control analysis.
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type){
+
+	bool        control_analysis;
+	int         inversiontype;
+	int         nsteps;
+	int         num_control_type;
+	int         num_cm_responses;
+	int        *control_type     = NULL;
+	int        *maxiter          = NULL;
+	int        *cm_responses     = NULL;
+	IssmDouble *cm_jump          = NULL;
+	IssmDouble *optscal          = NULL;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&inversiontype,InversionTypeEnum);
+
+	if(control_analysis){
+
+		/*How many controls and how many responses?*/
+		parameters->AddObject(iomodel->CopyConstantObject(InversionNumControlParametersEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionNumCostFunctionsEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
+
+		/*What solution type?*/
+		if(solution_type==SteadystateSolutionEnum){
+			parameters->AddObject(new BoolParam(ControlSteadyEnum,true));
+		}
+		else{
+			parameters->AddObject(new BoolParam(ControlSteadyEnum,false));
+		}
+
+		/*Now, recover fit, optscal and maxiter as vectors: */
+		iomodel->FetchData(&control_type,NULL,&num_control_type,InversionControlParametersEnum);
+		iomodel->FetchData(&cm_responses,NULL,&num_cm_responses,InversionCostFunctionsEnum);
+		parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_control_type));
+		parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,cm_responses,num_cm_responses));
+
+		/*Inversion type specifics*/
+		switch(inversiontype){
+			case 0:/*Brent Search*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionNstepsEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionCostFunctionThresholdEnum));
+				iomodel->FetchData(&cm_jump,&nsteps,NULL,InversionStepThresholdEnum);
+				iomodel->FetchData(&optscal,NULL,NULL,InversionGradientScalingEnum);
+				iomodel->FetchData(&maxiter,NULL,NULL,InversionMaxiterPerStepEnum);
+				parameters->AddObject(new DoubleMatParam(InversionGradientScalingEnum,optscal,nsteps,num_control_type));
+				parameters->AddObject(new DoubleVecParam(InversionStepThresholdEnum,cm_jump,nsteps));
+				parameters->AddObject(new IntVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
+				break;
+			case 1:/*TAO*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionFatolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionFrtolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionGatolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionGrtolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionGttolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxstepsEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxiterEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionAlgorithmEnum));
+				break;
+			case 2:/*M1QN3*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionDxminEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionGttolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxstepsEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxiterEnum));
+				break;
+			case 3:/*Validation*/
+				break;
+			default:
+				_error_("not supported");
+
+		}
+
+		xDelete<int>(control_type);
+		xDelete<int>(cm_responses);
+		xDelete<int>(maxiter);
+		iomodel->DeleteData(cm_jump,InversionStepThresholdEnum);
+		iomodel->DeleteData(optscal,InversionGradientScalingEnum);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*
+ * UpdateElementsAndMaterialsControl:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel){
+
+	/*Intermediary*/
+	int       control;
+	Element  *element = NULL;
+	Material *material = NULL;
+	int       num_control_type;
+	bool      control_analysis;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+
+	/*Now, return if no control*/
+	if (!control_analysis) return;
+
+	/*Fetch data needed: */
+	iomodel->FetchDataToInput(elements,InversionVxObsEnum,0.);
+	iomodel->FetchDataToInput(elements,InversionVyObsEnum,0.); 
+	iomodel->FetchDataToInput(elements,InversionThicknessObsEnum,0.);
+
+	iomodel->FetchData(5,InversionControlParametersEnum,InversionCostFunctionsEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+
+	for(int i=0;i<num_control_type;i++){
+		control = reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i]);
+		switch(control){
+			/*List of supported controls*/
+			case BalancethicknessThickeningRateEnum: 
+			case VxEnum:
+			case VyEnum:
+			case ThicknessEnum:
+			case FrictionCoefficientEnum:
+			case BalancethicknessNuxEnum:
+			case BalancethicknessNuyEnum:
+			case BalancethicknessApparentMassbalanceEnum:
+				iomodel->FetchData(1,control); 
+				break;
+
+			/*Special cases*/
+			case MaterialsRheologyBbarEnum: iomodel->FetchData(1,MaterialsRheologyBEnum); break;
+			case DamageDbarEnum:            iomodel->FetchData(1,DamageDEnum);            break;
+			default:
+				_error_("Control " << EnumToStringx(control) << " not implemented yet");
+		}
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			element=(Element*)elements->GetObjectByOffset(counter);
+			element->InputUpdateFromIoModel(i,iomodel); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	/*Free data: */
+	for(int i=0;i<num_control_type;i++){
+		control = reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i]);
+		switch(control){
+			case MaterialsRheologyBbarEnum: iomodel->DeleteData(1,MaterialsRheologyBEnum); break;
+			case DamageDbarEnum:            iomodel->DeleteData(1,DamageDEnum);            break;
+			default:                        iomodel->DeleteData(1,control); 
+		}
+	}
+	iomodel->DeleteData(5,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionCostFunctionsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateEdges.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 18231)
@@ -0,0 +1,234 @@
+/*!\file:  CreateEdges.cpp
+ * \brief: create edges from 2d mesh
+ */ 
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void CreateEdges(IoModel* iomodel){/*{{{*/
+
+	/*If edges are already present, exit*/
+	if(iomodel->edges) return;
+
+	/*Check Iomodel properties*/
+	if(iomodel->numberofvertices<3) _error_("not enough elements in mesh");
+	_assert_(iomodel->elements);
+
+	/*Intermediaries*/
+	bool exist;
+	int  i,j,v1,v2,v3;
+	int  maxnbe,nbe,elementnbe,elementnbv;
+	int *elementedges         = NULL;
+	int *elementedges_markers = NULL;
+
+	/*Mesh dependent variables*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:
+			elementnbv = 3;
+			elementnbe = 3;
+			elementedges         = xNew<int>(elementnbe*2);
+			elementedges_markers = xNew<int>(elementnbe);
+			elementedges[2*0+0] = 1; elementedges[2*0+1] = 2; elementedges_markers[0] = 1;
+			elementedges[2*1+0] = 2; elementedges[2*1+1] = 0; elementedges_markers[1] = 1;
+			elementedges[2*2+0] = 0; elementedges[2*2+1] = 1; elementedges_markers[2] = 1;
+			break;
+		case TetraEnum:
+			elementnbv = 4;
+			elementnbe = 6;
+			elementedges         = xNew<int>(elementnbe*2);
+			elementedges_markers = xNew<int>(elementnbe);
+			elementedges[2*0+0] = 1; elementedges[2*0+1] = 2; elementedges_markers[0] = 1;
+			elementedges[2*1+0] = 0; elementedges[2*1+1] = 2; elementedges_markers[1] = 1;
+			elementedges[2*2+0] = 0; elementedges[2*2+1] = 1; elementedges_markers[2] = 1;
+			elementedges[2*3+0] = 1; elementedges[2*3+1] = 3; elementedges_markers[3] = 1;
+			elementedges[2*4+0] = 2; elementedges[2*4+1] = 3; elementedges_markers[4] = 1;
+			elementedges[2*5+0] = 0; elementedges[2*5+1] = 3; elementedges_markers[5] = 1;
+			break;
+		case PentaEnum:
+			elementnbv = 6;
+			elementnbe = 9;
+			elementedges         = xNew<int>(elementnbe*2);
+			elementedges_markers = xNew<int>(elementnbe);
+			elementedges[2*0+0] = 0; elementedges[2*0+1] = 3; elementedges_markers[0] = 2;
+			elementedges[2*1+0] = 1; elementedges[2*1+1] = 4; elementedges_markers[1] = 2;
+			elementedges[2*2+0] = 2; elementedges[2*2+1] = 5; elementedges_markers[2] = 2;
+			elementedges[2*3+0] = 1; elementedges[2*3+1] = 2; elementedges_markers[3] = 1;
+			elementedges[2*4+0] = 2; elementedges[2*4+1] = 0; elementedges_markers[4] = 1;
+			elementedges[2*5+0] = 0; elementedges[2*5+1] = 1; elementedges_markers[5] = 1;
+			elementedges[2*6+0] = 4; elementedges[2*6+1] = 5; elementedges_markers[6] = 1;
+			elementedges[2*7+0] = 5; elementedges[2*7+1] = 3; elementedges_markers[7] = 1;
+			elementedges[2*8+0] = 3; elementedges[2*8+1] = 4; elementedges_markers[8] = 1;
+			break;
+		default:
+		_error_("mesh dimension not supported yet");
+	}
+
+	/*Maximum number of edges*/
+	maxnbe = elementnbe*iomodel->numberofelements;
+
+	/*Initialize intermediaries*/
+	int *edgestemp                 = xNew<int>(maxnbe*3);                             /*format: [vertex1 vertex2 marker]       */
+	int *element_edge_connectivity = xNew<int>(iomodel->numberofelements*elementnbe); /*format: [edge1 edge2 ... edgen] */
+
+	/*Initialize chain*/
+	int* head_minv = xNew<int>(iomodel->numberofvertices);
+	int* next_edge = xNew<int>(maxnbe);
+	for(i=0;i<iomodel->numberofvertices;i++) head_minv[i]=-1;
+
+	/*Initialize number of edges*/
+	nbe = 0;
+
+	for(i=0;i<iomodel->numberofelements;i++){
+		for(j=0;j<elementnbe;j++){
+
+			/*Get the two indices of the edge number j of the ith element*/
+			v1 = iomodel->elements[i*elementnbv+elementedges[2*j+0]]-1; _assert_(v1>=0 & v1<iomodel->numberofvertices);
+			v2 = iomodel->elements[i*elementnbv+elementedges[2*j+1]]-1; _assert_(v2>=0 & v2<iomodel->numberofvertices);
+
+			/*v1 and v2 must be sorted*/
+			if(v2<v1){
+				v3=v2; v2=v1; v1=v3;
+			}
+
+			/*This edge a priori has not been processed yet*/
+			exist = false;
+
+			/*Go through all processed edges connected to v1 and check whether we have seen this edge yet*/
+			for(int e=head_minv[v1]; e!=-1; e=next_edge[e]){
+				if(edgestemp[e*3+1]==v2+1){
+					exist = true;
+					element_edge_connectivity[i*elementnbe+j]=e;
+					break;
+				}
+			}
+
+			/*If this edge is new, add it to the lists*/
+			if(!exist){
+				_assert_(nbe<maxnbe);
+
+				/*Update edges*/
+				edgestemp[nbe*3+0] = v1+1;
+				edgestemp[nbe*3+1] = v2+1;
+				edgestemp[nbe*3+2] = elementedges_markers[j];
+
+				/*Update Connectivity*/
+				element_edge_connectivity[i*elementnbe+j]=nbe;
+
+				/*Update chain*/
+				next_edge[nbe] = head_minv[v1];
+				head_minv[v1]  = nbe;
+
+				/*Increase number of edges*/
+				nbe++;
+			}
+		}
+	}
+
+	/*Clean up*/
+	xDelete<int>(head_minv);
+	xDelete<int>(next_edge);
+	xDelete<int>(elementedges_markers);
+
+	/*Create final edges*/
+	int* edges = xNew<int>(nbe*3); /*format: [vertex1 vertex2 marker]*/
+	for(int i=0;i<3*nbe;i++) edges[i] = edgestemp[i];
+
+	/*Clean up*/
+	xDelete<int>(edgestemp);
+	xDelete<int>(elementedges);
+
+	/*Assign output pointers*/
+	iomodel->edges                     = edges;
+	iomodel->elementtoedgeconnectivity = element_edge_connectivity;
+	iomodel->numberofedges             = nbe;
+}/*}}}*/
+void EdgeOnBoundaryFlags(bool** pflags,IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool isv1,isv2;
+	int  facenbv,v1,v2;
+	int  id_edge,id_element;
+	int  elementnbe;
+
+	/*Mesh dependent variables*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:  elementnbe = 3; break;
+		case TetraEnum: elementnbe = 6; break;
+		case PentaEnum: elementnbe = 9; break;
+		default:        _error_("mesh dimension not supported yet");
+	}
+
+	/*Get edges and allocate output*/
+	if(!iomodel->edges) CreateEdges(iomodel);
+	bool* flags = xNewZeroInit<bool>(iomodel->numberofedges);
+
+	if(iomodel->domaindim==2){
+
+		/*Count how many times an edge is found in elementtoedgeconnectivity*/
+		int* counter = xNewZeroInit<int>(iomodel->numberofedges);
+		for(int i=0;i<iomodel->numberofelements;i++){
+			for(int j=0;j<elementnbe;j++){
+				counter[iomodel->elementtoedgeconnectivity[elementnbe*i+j]] += 1;
+			}
+		}
+
+		/*Now, loop over the egdes, whenever it is not connected to a second element, the edge is on boundary*/
+		for(int i=0;i<iomodel->numberofedges;i++){
+			if(counter[i]==1) flags[i]=true;
+		}
+
+		/*Clean up*/
+		xDelete<int>(counter);
+	}
+	else if(iomodel->domaindim==3){
+
+		/*Get faces*/
+		if(!iomodel->faces) CreateFaces(iomodel);
+
+		/*Now, loop over the faces, whenever it is not connected to a second element, all edges are on boundary*/
+		for(int id_face=0;id_face<iomodel->numberoffaces;id_face++){
+
+			if(iomodel->faces[id_face*iomodel->facescols+1]==-1){
+
+				/*The face is connected to the element e only*/
+				id_element = iomodel->faces[id_face*iomodel->facescols+0]-1;
+				facenbv    = iomodel->faces[id_face*iomodel->facescols+3];
+
+				/*Get all edges for this element*/
+				for(int edge = 0; edge<elementnbe; edge++){
+
+					id_edge     = iomodel->elementtoedgeconnectivity[elementnbe*id_element+edge];
+					v1          = iomodel->edges[id_edge*3+0];
+					v2          = iomodel->edges[id_edge*3+1];
+
+					/*Test if v1 is in the face*/
+					isv1=false;
+					for(int i=0;i<facenbv;i++){
+						if(iomodel->faces[id_face*iomodel->facescols+4+i] == v1){
+							isv1 = true; break;
+						}
+					}
+					if(!isv1) continue;
+
+					/*test if v2 is in the face*/
+					isv2=false;
+					for(int i=0;i<facenbv;i++){
+						if(iomodel->faces[id_face*iomodel->facescols+4+i] == v2){
+							isv2 = true; break;
+						}
+					}
+
+					/*If v1 and v2 are found, this edge is on boundary*/
+					if(isv2) flags[id_edge] = true;
+				}
+			}
+		}
+	}
+	else{
+		_error_("dimension not supported");
+	}
+
+	/*Clean up and return*/
+	*pflags = flags;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 18231)
@@ -0,0 +1,109 @@
+/*
+ * CreateElementsNodesAndMaterialsStressbalanceHoriz.c:
+ */
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials,IoModel* iomodel,const int nummodels){
+
+	/*Intermediary*/
+	int i;
+	int materials_type;
+	bool control_analysis;
+	bool dakota_analysis;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
+
+	/*Did we already create the elements? : */
+	_assert_(elements->Size()==0);
+
+	/*Create elements*/
+	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	switch(iomodel->meshelementtype){
+		case TriaEnum:
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		case TetraEnum:
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Tetra(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		case PentaEnum:
+			iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]) elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
+			}
+			break;
+		default:
+			_error_("Mesh not supported yet");
+	}
+
+	/*Create materials*/
+	switch(materials_type){
+		case MaticeEnum:
+			iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+			iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+			switch(iomodel->domaindim){
+				case 2:
+					elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
+					break;
+				case 3:
+					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
+					break;
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		case MatdamageiceEnum:
+			iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+			iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+			iomodel->FetchDataToInput(elements,DamageDEnum);
+			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+			switch(iomodel->domaindim){
+				case 2:
+					elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+					elements->InputDuplicate(DamageDEnum,DamageDbarEnum);
+					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
+					break;
+				case 3:
+					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
+					break;
+				default:
+					_error_("Mesh not supported yet");
+			}
+			break;
+		default:
+			_error_("Materials "<<EnumToStringx(materials_type)<<" not supported");
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(8,MeshUpperelementsEnum,MeshLowerelementsEnum,
+				MaterialsRheologyBEnum,MaterialsRheologyNEnum,DamageDEnum,InversionControlParametersEnum,InversionMinParametersEnum,
+				InversionMaxParametersEnum);
+
+	/*Add new constant material property to materials, at the end: */
+	materials->AddObject(new Matpar(iomodel->numberofelements+1,iomodel));//put it at the end of the materials
+
+	/*Create vertices: */
+
+	/*Fetch data:*/
+	iomodel->FetchData(6,MeshXEnum,MeshYEnum,MeshZEnum,BaseEnum,ThicknessEnum,MaskIceLevelsetEnum);
+	CreateNumberNodeToElementConnectivity(iomodel);
+
+	for(i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]) vertices->AddObject(new Vertex(i+1,i,i,iomodel));
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(6,MeshXEnum,MeshYEnum,MeshZEnum,BaseEnum,ThicknessEnum,MaskIceLevelsetEnum);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateFaces.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 18231)
@@ -0,0 +1,262 @@
+/*!\file:  CreateFaces.cpp
+ * \brief: create faces from 2d mesh
+ */ 
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void CreateFaces(IoModel* iomodel){/*{{{*/
+
+	/*If faces are already present, exit*/
+	if(iomodel->faces) return;
+
+	/*Some checks*/
+	if(iomodel->numberofvertices<3) _error_("not enough elements in mesh");
+	_assert_(iomodel->elements);
+
+	/*Check Iomodel properties*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum || iomodel->domaintype==Domain2DverticalEnum){
+		/*Keep going*/
+	}
+	else if(iomodel->domaintype==Domain3DEnum){
+		CreateFaces3d(iomodel);
+		return;
+	}
+	else{
+		_error_("mesh dimension not supported yet");
+	}
+
+	/*Intermediaries*/
+	bool exist;
+	int  i,j,v1,v2,v3;
+	int  maxnbf,nbf;
+
+	/*Maximum number of faces*/
+	maxnbf = 3*iomodel->numberofelements;
+
+	/*Initialize intermediaries*/
+	int*  facestemp = xNew<int>(maxnbf*4);         /*format: [vertex1 vertex2 element1 element2]                */
+	bool* exchange  = xNewZeroInit<bool>(maxnbf);  /*Faces are ordered, we need to keep track of vertex swapping*/
+	for(i=0;i<maxnbf;i++) facestemp[i*4+3]=-1;     /*Initialize last column of faces as -1 (boundary edge)      */
+
+	/*Initialize chain*/
+	int* head_minv = xNew<int>(iomodel->numberofvertices);
+	int* next_face = xNew<int>(maxnbf);
+	for(i=0;i<iomodel->numberofvertices;i++) head_minv[i]=-1;
+
+	/*Initialize number of faces*/
+	nbf = 0;
+
+	for(i=0;i<iomodel->numberofelements;i++){
+		for(j=0;j<3;j++){
+
+			/*Get the two indices of the edge number j of the ith triangle*/
+			v1 = iomodel->elements[i*3+j];
+			if(j==2)
+			 v2 = iomodel->elements[i*3+0];
+			else
+			 v2 = iomodel->elements[i*3+j+1];
+
+			/*v1 and v2 must be sorted*/
+			if(v2<v1){
+				v3=v2; v2=v1; v1=v3;
+			}
+
+			/*This edge a priori has not been processed yet*/
+			exist = false;
+
+			/*Go through all processed faces connected to v1 and check whether we have seen this edge yet*/
+			_assert_(v1>=0 && v1<iomodel->numberofvertices);
+			for(int e=head_minv[v1]; e!=-1; e=next_face[e]){
+				if(facestemp[e*4+1]==v2){
+					exist = true;
+					facestemp[e*4+3]=i+1;
+					break;
+				}
+			}
+
+			/*If this edge is new, add it to the lists*/
+			if(!exist){
+				_assert_(nbf<maxnbf);
+
+				/*Update faces*/
+				facestemp[nbf*4+0] = v1;
+				facestemp[nbf*4+1] = v2;
+				facestemp[nbf*4+2] = i+1;
+				if(v1!=iomodel->elements[i*3+j]) exchange[nbf]=true;
+
+				/*Update chain*/
+				next_face[nbf] = head_minv[v1];
+				head_minv[v1]  = nbf;
+
+				/*Increase number of faces*/
+				nbf++;
+			}
+		}
+	}
+
+	/*Clean up*/
+	xDelete<int>(head_minv);
+	xDelete<int>(next_face);
+
+	/*Create final faces*/
+	int* faces = xNew<int>(nbf*4); /*vertex1 vertex2 element1 element2*/
+	for(int i=0;i<nbf;i++){
+		if(exchange[i]){
+			faces[i*4+0]=facestemp[i*4+1];
+			faces[i*4+1]=facestemp[i*4+0];
+		}
+		else{
+			faces[i*4+0]=facestemp[i*4+0];
+			faces[i*4+1]=facestemp[i*4+1];
+		}
+		faces[i*4+2]=facestemp[i*4+2];
+		faces[i*4+3]=facestemp[i*4+3];
+	}
+	xDelete<int>(facestemp);
+	xDelete<bool>(exchange);
+
+	/*Assign output pointers*/
+	iomodel->faces         = faces;
+	iomodel->numberoffaces = nbf;
+}/*}}}*/
+void CreateFaces3d(IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool exist;
+	int  i,j,k,v0,cols,facescols;
+	int  maxnbf,nbf,elementnbf,elementnbv,facenbv,facemaxnbv;
+	int *elementfaces         = NULL;
+	int *elementfaces_markers = NULL;
+
+	/*Mesh specific face indexing per element*/
+	switch(iomodel->meshelementtype){
+		case PentaEnum:
+			elementnbv = 6; /*Number of vertices per element*/
+			elementnbf = 5; /*Number of faces per element*/
+			facemaxnbv = 4; /*Maximum number of vertices per face*/
+			cols       = facemaxnbv + 1;
+			elementfaces         = xNew<int>(elementnbf*cols);
+			elementfaces_markers = xNew<int>(elementnbf);
+			/*2 triangles*/
+			elementfaces_markers[0] = 1;
+			elementfaces_markers[1] = 1;
+			elementfaces[cols*0+0] = 3; elementfaces[cols*0+1] = 0;  elementfaces[cols*0+2] = 1; elementfaces[cols*0+3] = 2;
+			elementfaces[cols*1+0] = 3; elementfaces[cols*1+1] = 3;  elementfaces[cols*1+2] = 4; elementfaces[cols*1+3] = 5;
+			/*3 quads*/
+			elementfaces_markers[2] = 2;
+			elementfaces_markers[3] = 2;
+			elementfaces_markers[4] = 2;
+			elementfaces[cols*2+0] = 4; elementfaces[cols*2+1] = 1;  elementfaces[cols*2+2] = 2; elementfaces[cols*2+3] = 5;  elementfaces[cols*2+4] = 4;
+			elementfaces[cols*3+0] = 4; elementfaces[cols*3+1] = 2;  elementfaces[cols*3+2] = 0; elementfaces[cols*3+3] = 3;  elementfaces[cols*3+4] = 5;
+			elementfaces[cols*4+0] = 4; elementfaces[cols*4+1] = 0;  elementfaces[cols*4+2] = 1; elementfaces[cols*4+3] = 4;  elementfaces[cols*4+4] = 3;
+			break;
+		case TetraEnum:
+			elementnbv = 4; /*Number of vertices per element*/
+			elementnbf = 4; /*Number of faces per element*/
+			facemaxnbv = 3; /*Maximum number of vertices per face*/
+			cols       = facemaxnbv + 1;
+			elementfaces         = xNew<int>(elementnbf*cols);
+			elementfaces_markers = xNew<int>(elementnbf);
+			/*4 triangles*/
+			elementfaces_markers[0] = 1;
+			elementfaces_markers[1] = 1;
+			elementfaces_markers[2] = 1;
+			elementfaces_markers[3] = 1;
+			elementfaces[cols*0+0] = 3; elementfaces[cols*0+1] = 0;  elementfaces[cols*0+2] = 1; elementfaces[cols*0+3] = 2;
+			elementfaces[cols*1+0] = 3; elementfaces[cols*1+1] = 0;  elementfaces[cols*1+2] = 3; elementfaces[cols*1+3] = 1;
+			elementfaces[cols*2+0] = 3; elementfaces[cols*2+1] = 1;  elementfaces[cols*2+2] = 3; elementfaces[cols*2+3] = 2;
+			elementfaces[cols*3+0] = 3; elementfaces[cols*3+1] = 0;  elementfaces[cols*3+2] = 2; elementfaces[cols*3+3] = 3;
+			break;
+		default:
+		_error_("mesh "<< EnumToStringx(iomodel->meshelementtype) <<" not supported");
+	}
+
+	/*Allocate connectivity*/
+	int *element_face_connectivity = xNew<int>(iomodel->numberofelements*elementnbf); /*format: [face1 face2 ...] */
+
+	/*Maximum number of faces for initial allocation*/
+	maxnbf     = elementnbf*iomodel->numberofelements;
+	facescols  = 4+facemaxnbv; _assert_(facescols>6);
+
+	/*Initialize intermediaries*/
+	int* facestemp = xNew<int>(maxnbf*facescols);        /*format: [element1 element2 marker nbv vertex1 vertex2 vertex3 ...]    */
+	for(i=0;i<maxnbf;i++) facestemp[i*facescols+1]=-1;   /*Initialize second column of faces as -1 (boundary face)               */
+
+	/*Initialize chain*/
+	int* head_minv = xNew<int>(iomodel->numberofvertices);
+	int* next_face = xNew<int>(maxnbf);
+	for(i=0;i<iomodel->numberofvertices;i++) head_minv[i]=-1;
+
+	/*Initialize number of faces and list of vertex indices*/
+	nbf = 0;
+	int* v = xNew<int>(facemaxnbv);
+
+	for(i=0;i<iomodel->numberofelements;i++){
+		for(j=0;j<elementnbf;j++){
+
+			/*Get indices of current face*/
+			facenbv = elementfaces[cols*j+0];
+			for(k=0;k<facenbv;k++){
+				v[k] = iomodel->elements[i*elementnbv + elementfaces[cols*j+k+1]] - 1;
+			}
+
+			/*Sort list of vertices*/
+			HeapSort(v,elementfaces[cols*j+0]);
+			v0 = v[0]; _assert_(v0>=0 && v0<iomodel->numberofvertices);
+
+			/*This face a priori has not been processed yet*/
+			exist = false;
+
+			/*Go through all processed faces connected to v0 and check whether we have seen this face yet*/
+			for(int f=head_minv[v0]; f!=-1; f=next_face[f]){
+				if(facestemp[f*facescols+5]==v[1]+1 && facestemp[f*facescols+6]==v[2]+1){
+					exist = true;
+					facestemp[f*facescols+1]=i+1;
+					element_face_connectivity[i*elementnbf+j]=f;
+					break;
+				}
+			}
+
+			/*If this face is new, add it to the lists*/
+			if(!exist){
+				_assert_(nbf<maxnbf);
+
+				/*Update faces*/
+				facestemp[nbf*facescols+0] = i+1;
+				facestemp[nbf*facescols+2] = elementfaces_markers[j];
+				facestemp[nbf*facescols+3] = facenbv;
+				for(k=0;k<facenbv;k++) facestemp[nbf*facescols+4+k] = v[k]+1;
+
+				/*Update Connectivity*/
+				element_face_connectivity[i*elementnbf+j]=nbf;
+
+				/*Update chain*/
+				next_face[nbf] = head_minv[v0];
+				head_minv[v0]  = nbf;
+
+				/*Increase number of faces*/
+				nbf++;
+			}
+		}
+	}
+
+	/*Clean up*/
+	xDelete<int>(head_minv);
+	xDelete<int>(next_face);
+	xDelete<int>(v);
+	xDelete<int>(elementfaces);
+	xDelete<int>(elementfaces_markers);
+
+	/*Create final faces (now that we have the correct size)*/
+	int* faces = xNew<int>(nbf*facescols);
+	xMemCpy<int>(faces,facestemp,nbf*facescols);
+	xDelete<int>(facestemp);
+
+	/*Assign output pointers*/
+	iomodel->faces                     = faces;
+	iomodel->numberoffaces             = nbf;
+	iomodel->facescols                 = facescols;
+	iomodel->elementtofaceconnectivity = element_face_connectivity;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 18231)
@@ -0,0 +1,544 @@
+/*
+ * CreateNodes.c:
+ */
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "./ModelProcessorx.h"
+
+void CreateNodes(Nodes* nodes, IoModel* iomodel,int analysis,int finite_element,int approximation){
+
+	/*Intermediaries*/
+	int   i,j,counter,vnodes,lid=0;
+	int   numberoffaces,elementnbv;
+	int   id0 = iomodel->nodecounter;
+	bool *my_faces = NULL;
+	bool *my_edges = NULL;
+	bool *my_nodes = NULL;
+	Node *node     = NULL;
+
+	switch(finite_element){
+		case P1Enum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			break;
+
+		case P1DGEnum:
+			NodesPartitioning(&my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,false);
+			for(i=0;i<iomodel->numberofelements;i++){
+				for(j=0;j<3;j++){
+					if(my_nodes[3*i+j]){ 
+						nodes->AddObject(new Node(id0+3*i+j+1,id0+3*i+j,lid++,iomodel->elements[+3*i+j]-1,iomodel,analysis,approximation));
+
+					}
+				}
+			}
+			break;
+
+		case P1bubbleEnum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			break;
+
+		case P1bubblecondensedEnum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					node = new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			break;
+
+		case P1xP2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter++;
+				}
+			}
+			break;
+
+		case P1xP3Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+2*i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+2*i+2,counter+2,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter=counter+2;
+				}
+			}
+			break;
+
+		case P2xP1Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]!=2){
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter++;
+				}
+			}
+			break;
+
+		case P2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+	      if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,approximation);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+			}
+			break;
+		case P2bubbleEnum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,approximation);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+				id0 = id0+iomodel->numberoffaces;
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+i+1,id0-iomodel->nodecounter+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			break;
+		case P2xP4Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			FacesPartitioning(&my_faces,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){/*Vertical edges*/
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+3*i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+2,counter+2,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+3,counter+3,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter=counter+3;
+				}
+				else if(iomodel->edges[i*3+2]==1){/*Horizontal edges*/
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+3*i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter=counter+1;
+				}
+				else{
+					_error_("not supported");
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+3*iomodel->numberofedges;
+			for(i=0;i<iomodel->numberoffaces;i++){
+				if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+					if(my_faces[i]){
+						node = new Node(id0+3*i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+3*i+2,counter+2,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+3*i+3,counter+3,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter=counter+3;
+				}
+				else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+					/*Nothing*/
+				}
+				else{
+					_error_("not supported");
+				}
+			}
+			break;
+
+		/*Stokes elements*/
+		case P1P1Enum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1 velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			vnodes = id0+iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,iomodel->numberofvertices+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case P1P1GLSEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1 velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			vnodes = id0+iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,iomodel->numberofvertices+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case MINIcondensedEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1+ velocity (bubble statically condensed)*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					node = new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			/*P1 pressure*/
+			vnodes = id0+iomodel->numberofvertices+iomodel->numberofelements;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case MINIEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1+ velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			vnodes = id0+iomodel->numberofvertices+iomodel->numberofelements;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case TaylorHoodEnum:
+		case XTaylorHoodEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2 velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+	      if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+			}
+
+			/*P1 pressure*/
+	      if(iomodel->meshelementtype==PentaEnum){
+				numberoffaces=iomodel->numberoffaces;
+			}
+			else{
+				numberoffaces=0;
+			}
+			vnodes = id0+numberoffaces;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,iomodel->numberofvertices+iomodel->numberofedges+numberoffaces+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case LATaylorHoodEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2 velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+	      if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+			}
+
+			/*No pressure*/
+			break;
+		case OneLayerP4zEnum:
+			_assert_(approximation==FSApproximationEnum);
+			EdgesPartitioning(&my_edges,iomodel);
+			FacesPartitioning(&my_faces,iomodel);
+			/*P2xP4 velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){/*Vertical edges*/
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+3*i+1,counter+1,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+2,counter+2,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+3,counter+3,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+					}
+					counter=counter+3;
+				}
+				else if(iomodel->edges[i*3+2]==1){/*Horizontal edges*/
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+3*i+1,counter+1,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+					}
+					counter=counter+1;
+				}
+				else{
+					_error_("not supported");
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+3*iomodel->numberofedges;
+			for(i=0;i<iomodel->numberoffaces;i++){
+				if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+					if(my_faces[i]){
+						node = new Node(id0+3*i+1,counter+1,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+						node = new Node(id0+3*i+2,counter+2,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+						node = new Node(id0+3*i+3,counter+3,lid++,0,iomodel,analysis,FSvelocityEnum);
+						nodes->AddObject(node);
+					}
+					counter=counter+3;
+				}
+				else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+					/*Nothing*/
+				}
+				else{
+					_error_("not supported");
+				}
+			}
+
+			/*P1 pressure*/
+			vnodes = id0+3*iomodel->numberoffaces;
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(vnodes+i+1,counter+1,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+				counter++;
+			}
+			break;
+		case CrouzeixRaviartEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2b velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+				id0 = id0+iomodel->numberoffaces;
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+i+1,id0-iomodel->nodecounter+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+
+			/*P1 DG pressure*/
+			vnodes = id0+iomodel->numberofelements;
+			switch(iomodel->meshelementtype){
+				case TriaEnum:  elementnbv = 3; break;
+				case TetraEnum: elementnbv = 4; break;
+				case PentaEnum: elementnbv = 6; break;
+				default:        _error_("mesh dimension not supported yet");
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					for(j=0;j<elementnbv;j++){
+						nodes->AddObject(new Node(vnodes+elementnbv*i+j+1,vnodes-iomodel->nodecounter+elementnbv*i+j,lid++,iomodel->elements[+elementnbv*i+j]-1,iomodel,analysis,FSpressureEnum));
+
+					}
+				}
+			}
+			break;
+
+		default:
+			_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+	}
+
+	/*Clean up*/
+	xDelete<bool>(my_faces);
+	xDelete<bool>(my_edges);
+	xDelete<bool>(my_nodes);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file:  CreateNumberNodeToElementConnectivity.cpp
+ * \brief: create connectivity table
+ */ 
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+#include "../../shared/io/io.h"
+#include "./ModelProcessorx.h"
+
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel){
+
+	/*Intermediary*/
+	int i,j;
+	int vertexid;
+	int elementswidth;
+
+	/*output*/
+	int* connectivity=NULL;
+
+	/*Check that this has not been done yet*/
+	if(iomodel->numbernodetoelementconnectivity) return;
+
+	/*Some checks if debugging*/
+	_assert_(iomodel->numberofvertices);
+	_assert_(iomodel->numberofelements);
+	_assert_(iomodel->elements);
+
+	/*Allocate ouput*/
+	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
+
+	/*Get element width*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:  elementswidth=3; break;
+		case TetraEnum: elementswidth=4; break;
+		case PentaEnum: elementswidth=6; break;
+		default:                   _error_("mesh not supported yet");
+	}
+
+	/*Create connectivity table*/
+	for (i=0;i<iomodel->numberofelements;i++){
+		for (j=0;j<elementswidth;j++){
+			vertexid=iomodel->elements[elementswidth*i+j];
+			_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
+			connectivity[vertexid-1]+=1;
+		}
+	}
+
+	/*Assign to iomodel*/
+	iomodel->numbernodetoelementconnectivity=connectivity;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 18231)
@@ -0,0 +1,125 @@
+/*!\file: CreateParametersOutputDefinitions.cpp
+ * \brief driver for creating output definitions dataset, and including it into the parameters dataset
+ */ 
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void CreateOutputDefinitions(Elements* elements, Parameters* parameters,IoModel* iomodel){
+
+	int i,j;
+	
+	DataSet*     output_definitions      = NULL;
+	int*         output_definition_enums = NULL;
+	int          num_output_definitions;
+
+	/*Create output_definitions dataset: */
+	output_definitions=new DataSet();
+	
+	iomodel->FetchData(&output_definition_enums,&num_output_definitions,NULL,OutputdefinitionListEnum);
+	if(num_output_definitions){
+		for (i=0;i<num_output_definitions;i++){
+
+			if (output_definition_enums[i]==MassfluxatgateEnum){
+
+				/*Deal with mass flux gates:{{{ */
+				
+				/*massfluxatgate variables: */
+				int          numgates;
+				char       **gatenames               = NULL;
+				IssmDouble **gatesegments            = NULL;
+				int         *gatesegments_M          = NULL;
+
+
+				/*Fetch segments and names: */
+				iomodel->FetchMultipleData(&gatenames,&numgates,MassfluxatgateNameEnum);
+				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&numgates,MassfluxatgateSegmentsEnum);
+
+				for(j=0;j<numgates;j++){
+					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],gatesegments_M[j],gatesegments[j]));
+				}
+				/*Free ressources:*/
+				for(j=0;j<numgates;j++){
+					char*       string = gatenames[j];    xDelete<char>(string);
+					IssmDouble* gate   = gatesegments[j]; xDelete<IssmDouble>(gate);
+				}
+				xDelete<char*>(gatenames);
+				xDelete<IssmDouble*>(gatesegments);
+				xDelete<int>(gatesegments_M);
+				/*}}}*/
+			}
+			else if (output_definition_enums[i]==MisfitEnum){
+				/*Deal with misfits: {{{*/
+				
+				/*misfit variables: */
+				int          nummisfits;
+				char**       misfit_name_s             = NULL;    
+				int*         misfit_model_enum_s        = NULL;
+				IssmDouble** misfit_observation_s      = NULL;
+				int*         misfit_observation_enum_s  = NULL;
+				int*         misfit_observation_M_s    = NULL;
+				int*         misfit_observation_N_s    = NULL;
+				char**       misfit_timeinterpolation_s = NULL;
+				IssmDouble** misfit_weights_s           = NULL;
+				int*         misfit_weights_M_s    = NULL;
+				int*         misfit_weights_N_s    = NULL;
+				int*         misfit_weights_enum_s= NULL;
+
+				/*Fetch name, model_enum, observation, observation_enum, etc ... (see src/m/classes/misfit.m): */
+				iomodel->FetchMultipleData(&misfit_name_s,&nummisfits,MisfitNameEnum);
+				iomodel->FetchMultipleData(&misfit_model_enum_s,&nummisfits,MisfitModelEnumEnum);
+				iomodel->FetchMultipleData(&misfit_observation_s,&misfit_observation_M_s,&misfit_observation_N_s,&nummisfits,MisfitObservationEnum);
+				iomodel->FetchMultipleData(&misfit_observation_enum_s,&nummisfits,MisfitObservationEnumEnum);
+				iomodel->FetchMultipleData(&misfit_timeinterpolation_s,&nummisfits,MisfitTimeinterpolationEnum);
+				iomodel->FetchMultipleData(&misfit_weights_s,&misfit_weights_M_s,&misfit_weights_N_s,&nummisfits,MisfitWeightsEnum);
+				iomodel->FetchMultipleData(&misfit_weights_enum_s,&nummisfits,MisfitWeightsEnumEnum);
+
+				for(j=0;j<nummisfits;j++){
+
+					/*First create a misfit object for that specific enum (misfit_model_enum_s[j]):*/
+					output_definitions->AddObject(new Misfit(misfit_name_s[j],misfit_model_enum_s[j],misfit_observation_enum_s[j],misfit_timeinterpolation_s[j],misfit_weights_enum_s[j]));
+
+					/*Now, for this particular misfit object, make sure we plug into the elements: the observation, and the weights.*/
+					for(i=0;i<elements->Size();i++){
+						Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+						element->InputCreate(misfit_observation_s[j], iomodel,misfit_observation_M_s[j],misfit_observation_N_s[j],1,misfit_observation_enum_s[j],7);
+						element->InputCreate(misfit_weights_s[j], iomodel,misfit_weights_M_s[j],misfit_weights_N_s[j],1,misfit_weights_enum_s[j],7);
+					}
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<nummisfits;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = misfit_name_s[j];    xDelete<char>(string);
+					string = misfit_timeinterpolation_s[j];    xDelete<char>(string);
+					matrix = misfit_observation_s[j]; xDelete<IssmDouble>(matrix);
+					matrix = misfit_weights_s[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(misfit_name_s);
+				xDelete<int>(misfit_model_enum_s);
+				xDelete<IssmDouble*>(misfit_observation_s);
+				xDelete<int>(misfit_observation_enum_s);
+				xDelete<int>(misfit_observation_M_s);
+				xDelete<int>(misfit_observation_N_s);
+				xDelete<char*>(misfit_timeinterpolation_s);
+				xDelete<IssmDouble*>(misfit_weights_s);
+				xDelete<int>(misfit_weights_M_s);
+				xDelete<int>(misfit_weights_N_s);
+				xDelete<int>(misfit_weights_enum_s);
+				/*}}}*/
+			}
+
+			else _error_("output definition enum " << output_definition_enums[i] << "not supported yet!");
+		}
+	}
+	parameters->AddObject(new DataSetParam(OutputdefinitionEnum,output_definitions));
+
+	/*Free ressources:*/
+	delete output_definitions;
+	xDelete<int>(output_definition_enums);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 18231)
@@ -0,0 +1,255 @@
+/*!\file: CreateParameters.cpp
+ * \brief general driver for creating parameters dataset
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
+#include "./ModelProcessorx.h"
+
+void CreateParameters(Parameters* parameters,IoModel* iomodel,char* rootpath,FILE* toolkitsoptionsfid,const int solution_type){
+
+	int         i,j,m,k;
+	int         numoutputs,materialtype,smb_model,basalforcing_model;
+	char**      requestedoutputs = NULL;
+	IssmDouble  time;
+	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;
+
+	/*Make sure current dataset is empty*/
+	_assert_(parameters->Size()==0); 
+
+	/*Copy some constants from iomodel */
+	parameters->AddObject(iomodel->CopyConstantObject(DomainTypeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DomainDimensionEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshElementtypeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ConstantsYtsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingStartTimeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingFinalTimeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeAdaptEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeStepEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingCflCoefficientEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingInterpForcingsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsLowmemEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DebugProfilingEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshAverageVertexConnectivityEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofverticesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsOnNodesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsIoGatherEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsstressbalanceEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsmasstransportEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgiaEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIslevelsetEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsdamageevolutionEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIshydrologyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(QmuIsdakotaEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(InversionIscontrolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(InversionTypeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(GiaCrossSectionShapeEnum));
+
+	/*For stress balance only*/
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+	if(iomodel->domaintype==Domain3DEnum)
+	 parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
+
+	/*Surface mass balance parameters*/
+	parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsEnum));
+	iomodel->Constant(&smb_model,SurfaceforcingsEnum);
+	switch(smb_model){
+		case SMBEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case SMBpddEnum:
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIsdelta18oEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsDesfacEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsS0pEnum));
+			iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			if(isdelta18o){
+				IssmDouble *temp = NULL;
+				IssmDouble  yts;
+				int         N,M;
+				iomodel->Constant(&yts,ConstantsYtsEnum);
+				iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oEnum); _assert_(N==2);
+				for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
+				parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oEnum,&temp[0],&temp[M],M));
+				iomodel->DeleteData(temp,SurfaceforcingsDelta18oEnum);
+
+				iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oSurfaceEnum); _assert_(N==2);
+				for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
+				parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oSurfaceEnum,&temp[0],&temp[M],M));
+				iomodel->DeleteData(temp,SurfaceforcingsDelta18oSurfaceEnum);
+			}
+			break;
+		case SMBgradientsEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case SMBhenningEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case SMBcomponentsEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case SMBmeltcomponentsEnum:
+			/*Nothing to add to parameters*/
+			break;
+		default:
+			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+
+	/*Basal forcing parameters*/
+	parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsEnum));
+	iomodel->Constant(&basalforcing_model,BasalforcingsEnum);
+	switch(basalforcing_model){
+		case FloatingMeltRateEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case LinearFloatingMeltRateEnum:
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsDeepwaterMeltingRateEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsDeepwaterElevationEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsUpperwaterElevationEnum));
+			break;
+		default:
+			_error_("Basal forcing model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+
+	/*some parameters that did not come with the iomodel: */
+	parameters->AddObject(new IntParam(SolutionTypeEnum,solution_type));
+
+	iomodel->Constant(&time,TimesteppingStartTimeEnum);
+	parameters->AddObject(new DoubleParam(TimeEnum,time));  
+	parameters->AddObject(new IntParam(StepEnum,1));  
+
+	/*By default, save all results*/
+	parameters->AddObject(new BoolParam(SaveResultsEnum,true));
+
+	/*Requested outputs */
+	iomodel->FetchData(&requestedoutputs,&numoutputs,TransientRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,TransientRequestedOutputsEnum);
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,SteadystateRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,SteadystateRequestedOutputsEnum);
+
+	iomodel->Constant(&materialtype,MaterialsEnum);
+	if(materialtype==MatdamageiceEnum){
+		iomodel->FetchData(&requestedoutputs,&numoutputs,DamageEvolutionRequestedOutputsEnum);
+		parameters->AddObject(new IntParam(DamageEvolutionNumRequestedOutputsEnum,numoutputs));
+		if(numoutputs)parameters->AddObject(new StringArrayParam(DamageEvolutionRequestedOutputsEnum,requestedoutputs,numoutputs));
+		iomodel->DeleteData(&requestedoutputs,numoutputs,DamageEvolutionRequestedOutputsEnum);
+	}
+
+	/*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];
+			_assert_(temp_n==5);
+
+			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: */
+	CreateParametersControl(parameters,iomodel,solution_type);
+
+	#ifdef _HAVE_DAKOTA_
+	CreateParametersDakota(parameters,iomodel,rootpath);
+	#endif
+
+	/*Now, deal with toolkits options, which need to be put into the parameters dataset: */
+	ParseToolkitsOptionsx(parameters,toolkitsoptionsfid);
+
+ 	#ifdef _HAVE_ADOLC_
+	CreateParametersAutodiff(parameters,iomodel);
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\file:  CreateSingleNodeToElementConnectivity.cpp
+ * \brief: create connectivity table
+ */ 
+
+#include "../../shared/shared.h"
+#include "../../shared/io/io.h"
+#include "../../classes/classes.h"
+#include "./ModelProcessorx.h"
+
+void CreateSingleNodeToElementConnectivity(IoModel* iomodel){
+
+	/*Intermediary*/
+	int vertexid;
+	int elementswidth;
+
+	/*output*/
+	int* connectivity=NULL;
+
+	/*Return if connectivity already present*/
+	if(iomodel->singlenodetoelementconnectivity) return;
+
+	/*Some checks if debugging*/
+	_assert_(iomodel->numberofvertices);
+	_assert_(iomodel->numberofelements);
+	_assert_(iomodel->my_elements);
+	_assert_(iomodel->elements);
+
+	/*Allocate ouput*/
+	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
+
+	/*Get element width*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:  elementswidth=3; break;
+		case PentaEnum: elementswidth=6; break;
+		case TetraEnum: elementswidth=4; break;
+		default:  _error_("mesh type "<<EnumToStringx(iomodel->domaintype)<<" not supported yet");
+	}
+
+	/*Create connectivity table*/
+	for(int i=0;i<iomodel->numberofelements;i++){
+		/*!! in parallel we do not want the vertex to be connected to an element that is not in its partition!!*/
+		if(iomodel->my_elements[i]){
+			for(int j=0;j<elementswidth;j++){
+				vertexid=iomodel->elements[elementswidth*i+j];
+				_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
+				connectivity[vertexid-1]=i+1;
+			}
+		}
+	}
+
+	/*Assign to iomodel*/
+	iomodel->singlenodetoelementconnectivity=connectivity;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 18231)
@@ -0,0 +1,122 @@
+/*!\file: CreateParametersDakota.cpp
+ * \brief general driver for creating parameters dataset
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersDakota(Parameters* parameters,IoModel* iomodel,char* rootpath){
+
+	/*variable declarations*/
+	int          i;
+	int         *part                   = NULL;
+	double      *dpart                  = NULL;
+	char       **responsedescriptors    = NULL;
+	int          numresponsedescriptors;
+	char       **variabledescriptors    = NULL;
+	int          numvariabledescriptors;
+	char        *descriptor             = NULL;
+	double      *dakota_parameter       = NULL;
+
+	//qmu files
+	char *qmuinname  = NULL;
+	char *qmuerrname = NULL;
+	char *qmuoutname = NULL;
+
+	//descriptors:
+	char tag[50];
+
+	bool  dakota_analysis   = false;
+	char *name              = NULL;
+	int   numberofresponses;
+	int   nrows,ncols;
+
+	/*recover parameters: */
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	if(dakota_analysis){
+
+		iomodel->Constant(&name,MiscellaneousNameEnum);
+		iomodel->Constant(&numberofresponses,QmuNumberofresponsesEnum);
+
+		/*name of qmu input, error and output files*/
+		qmuinname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.in")+1));
+		sprintf(qmuinname,"%s%s%s",rootpath,name,".qmu.in");
+		parameters->AddObject(new   StringParam(QmuInNameEnum,qmuinname));
+
+		qmuoutname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.out")+1));
+		sprintf(qmuoutname,"%s%s%s",rootpath,name,".qmu.out");
+		parameters->AddObject(new   StringParam(QmuOutNameEnum,qmuoutname));
+
+		qmuerrname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.err")+1));
+		sprintf(qmuerrname,"%s%s%s",rootpath,name,".qmu.err");
+		parameters->AddObject(new   StringParam(QmuErrNameEnum,qmuerrname));
+
+		/*Fetch variable descriptors*/
+		iomodel->FetchData(&variabledescriptors,&numvariabledescriptors,QmuVariabledescriptorsEnum);
+
+		/*Ok, we have all the variable descriptors. Build a parameter with it: */
+		parameters->AddObject(new StringArrayParam(QmuVariabledescriptorsEnum,variabledescriptors,numvariabledescriptors));
+
+		/*Fetch response descriptors*/
+		iomodel->FetchData(&responsedescriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+
+		/*Ok, we have all the response descriptors. Build a parameter with it: */
+		parameters->AddObject(new StringArrayParam(QmuResponsedescriptorsEnum,responsedescriptors,numresponsedescriptors));
+		parameters->AddObject(new    IntParam(QmuNumberofresponsesEnum,numberofresponses));
+
+		/*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);
+		if(!dpart){
+			/*Partition elements and vertices and nodes: */
+			ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
+
+			dpart=xNew<double>(iomodel->numberofvertices);
+			for(i=0;i<iomodel->numberofvertices;i++)dpart[i]=iomodel->my_vertices[i];
+		}
+		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,iomodel->numberofvertices));
+
+		/*Deal with data needed because of qmu variables*/
+		for(i=0;i<numvariabledescriptors;i++){
+			if (strncmp(variabledescriptors[i],"scaled_",7)==0){
+				/*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));
+				if(nrows==iomodel->numberofvertices){
+					parameters->AddObject(new DoubleMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
+				}
+				else{
+					parameters->AddObject(new DoubleTransientMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
+				}
+				xDelete<double>(dakota_parameter);
+			}
+		}
+
+		/*clean-up*/
+		for(i=0;i<numresponsedescriptors;i++){
+			descriptor=responsedescriptors[i];
+			xDelete<char>(descriptor);
+		}
+		xDelete<char*>(responsedescriptors);
+		for(i=0;i<numvariabledescriptors;i++){
+			descriptor=variabledescriptors[i];
+			xDelete<char>(descriptor);
+		}
+		xDelete<char*>(variabledescriptors);
+		xDelete<int>(part);
+		xDelete<double>(dpart);
+		xDelete<char>(qmuinname);
+		xDelete<char>(qmuerrname);
+		xDelete<char>(qmuoutname);
+	}
+
+	/*Free data*/
+	xDelete<char>(name);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp	(revision 18231)
@@ -0,0 +1,20 @@
+/*
+ * UpdateElementsAndMaterialsControl:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel){
+
+	/*recover parameters: */
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	if(dakota_analysis){
+		iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum,0.);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file:  EdgesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void EdgesPartitioning(bool** pmy_edges,IoModel* iomodel){
+
+	/*Intermediaries*/
+	int elementnbe;
+
+	/*Get edges and elements*/
+	CreateEdges(iomodel);
+	_assert_(iomodel->elementtoedgeconnectivity);
+
+	/*Mesh dependent variables*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:  elementnbe = 3; break;
+		case TetraEnum: elementnbe = 6; break;
+		case PentaEnum: elementnbe = 9; break;
+		default: _error_("mesh dimension not supported yet");
+	}
+
+	/*output: */
+	bool* my_edges=xNewZeroInit<bool>(iomodel->numberofedges);
+
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			for(int j=0;j<elementnbe;j++){
+				my_edges[iomodel->elementtoedgeconnectivity[i*elementnbe+j]] = true;
+			}
+		}
+	}
+
+	/*Free data and assign output pointers */
+	*pmy_edges=my_edges;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 18231)
@@ -0,0 +1,138 @@
+/*!\file:  ElementsAndVerticesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+void  ElementsAndVerticesPartitioning(bool** pmy_elements, int** pmy_vertices, IoModel* iomodel){
+
+	int i,j;
+
+	const int RIFTINFOSIZE = 12;
+	int numberofelements2d;
+	int numberofvertices2d;
+	int numlayers;
+	int numrifts;
+	int numvertex_pairing;
+
+	/*output: */
+	bool *my_elements = NULL;
+	int  *my_vertices = NULL;
+
+	/*intermediary: */
+	int        *epart          = NULL; //element partitioning.
+	int        *npart          = NULL; //node partitioning.
+	int         elements_width;        //number of columns in elements (2d->3, 3d->6)
+	int         el1,el2;
+	int        *elements2d     = NULL;
+	int        *vertex_pairing = NULL;
+	IssmDouble *riftinfo       = NULL;
+
+	/*Get my_rank:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
+
+	/*First, check that partitioning has not yet been carryed out. Just check whether my_elements pointers is not already assigned a value: */
+	if(*pmy_elements)return;
+
+	/*Number of vertices per elements, needed to correctly retrieve data: */
+	/*Determine parallel partitioning of elements: we use Metis for now. First load the data, then partition*/
+	switch(iomodel->meshelementtype){
+		case TriaEnum:
+			elements_width=3;
+			numberofelements2d = 0;
+			numberofvertices2d = 0;
+			numlayers          = 0;
+			break;
+		case TetraEnum:
+			elements_width=4;
+			numberofelements2d = 0;
+			numberofvertices2d = 0;
+			numlayers          = 0;
+			break;
+		case PentaEnum:
+			elements_width=6;
+			iomodel->FetchData(&elements2d,NULL,NULL,MeshElements2dEnum);
+			iomodel->Constant(&numberofelements2d,MeshNumberofelements2dEnum);
+			iomodel->Constant(&numberofvertices2d,MeshNumberofvertices2dEnum);
+			iomodel->Constant(&numlayers,MeshNumberoflayersEnum);
+			break;
+		default:
+			_error_("mesh not supported yet");
+	}
+
+	MeshPartitionx(&epart,&npart,iomodel->numberofelements,iomodel->numberofvertices,iomodel->elements,numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width,iomodel->meshelementtype,num_procs);
+
+	/*Free elements2d: */
+	xDelete<int>(elements2d);
+
+	/*Deal with rifts, they have to be included into one partition only, not several: */
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numrifts,NULL,RiftsRiftstructEnum);
+		for(i=0;i<numrifts;i++){
+			el1=reCast<int>(*(riftinfo+RIFTINFOSIZE*i+2))-1; //matlab indexing to c indexing
+			el2=reCast<int>(*(riftinfo+RIFTINFOSIZE*i+3))-1; //matlab indexing to c indexing
+			epart[el2]=epart[el1]; //ensures that this pair of elements will be in the same partition, as well as the corresponding vertices;
+		}
+		iomodel->DeleteData(riftinfo,RiftsRiftstructEnum);
+	}
+
+	/*Used later on: */
+	my_vertices=xNewZeroInit<int>(iomodel->numberofvertices);
+	my_elements=xNewZeroInit<bool>(iomodel->numberofelements);
+
+	/*Start figuring out, out of the partition, which elements belong to this cpu: */
+	for(i=0;i<iomodel->numberofelements;i++){
+
+		/*!All elements have been partitioned above, only deal with elements for this cpu: */
+		if(my_rank==epart[i]){ 
+			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) 
+			 into the vertices coordinates. If we start plugging 1 into my_vertices for each index[n][i] (i=0:2), then my_vertices 
+			 will hold which vertices belong to this partition*/
+			for(j=0;j<elements_width;j++){
+				my_vertices[iomodel->elements[elements_width*i+j]-1]=1;
+			}
+		}
+	}
+
+	/*We might have vertex_pairing in which case, some vertices have to be cloned:
+	 * penpair has 2 nodes that are poointing toward 2 vertices.
+	 * The 2 vertices must be in the same cpu as the penpair*/
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,StressbalanceVertexPairingEnum);
+	for(i=0;i<numvertex_pairing;i++){
+		if(my_vertices[vertex_pairing[2*i+0]-1] && !my_vertices[vertex_pairing[2*i+1]-1]){
+			my_vertices[vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		}
+	}
+	xDelete<int>(vertex_pairing);
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	for(i=0;i<numvertex_pairing;i++){
+		if(my_vertices[vertex_pairing[2*i+0]-1] && !my_vertices[vertex_pairing[2*i+1]-1]){
+			my_vertices[vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		}
+	}
+	xDelete<int>(vertex_pairing);
+
+	/*Free ressources:*/
+	xDelete<int>(npart);
+	xDelete<int>(epart);
+
+	/*Assign output pointers:*/
+	*pmy_elements=my_elements;
+	*pmy_vertices=my_vertices;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/FacesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\file:  FacesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void FacesPartitioning(bool** pmy_faces,IoModel* iomodel){
+
+	/*Intermediaries*/
+	int elementnbf;
+
+	/*Get faces and elements*/
+	CreateFaces(iomodel);
+	_assert_(iomodel->elementtofaceconnectivity);
+
+	/*Mesh dependent variables*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum){
+		elementnbf = 3;
+	}
+	else if(iomodel->domaintype==Domain2DverticalEnum){
+		elementnbf = 3;
+	}
+	else if(iomodel->domaintype==Domain3DEnum){
+		elementnbf = 5;
+	}
+	else{
+		_error_("mesh dimension not supported yet");
+	}
+	/*output: */
+	bool* my_faces=xNewZeroInit<bool>(iomodel->numberoffaces);
+
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			for(int j=0;j<elementnbf;j++){
+				_assert_(iomodel->elementtofaceconnectivity[i*elementnbf+j] >= 0);
+				_assert_(iomodel->elementtofaceconnectivity[i*elementnbf+j] <  iomodel->numberoffaces);
+				my_faces[iomodel->elementtofaceconnectivity[i*elementnbf+j]] = true;
+			}
+		}
+	}
+
+	/*Free data and assign output pointers */
+	*pmy_faces=my_faces;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 18231)
@@ -0,0 +1,141 @@
+/*!\file ModelProcessorx
+ * \brief: create datasets using input binary file and a set of requested analyses
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,FILE* toolkitfile, char* rootpath,const int solution_enum,const int nummodels,const int* analysis_enum_list){
+
+	int   i,analysis_enum,verbose;
+	bool  isthermal,ismasstransport,isstressbalance,isgroundingline,isenthalpy,islevelset,isdamage,ishydrology;
+
+	/*Initialize datasets*/
+	Elements    *elements    = new Elements();
+	Nodes       *nodes       = new Nodes();
+	Vertices    *vertices    = new Vertices();
+	Materials   *materials   = new Materials();
+	Constraints *constraints = new Constraints();
+	Loads       *loads       = new Loads();
+	Parameters  *parameters  = new Parameters();
+
+	/*Initialize IoModel from input file*/
+	IoModel* iomodel = new IoModel(IOMODEL);
+
+	/*Fetch parameters: */
+	iomodel->Constant(&verbose,VerboseEnum);
+	iomodel->Constant(&isthermal,TransientIsthermalEnum);
+	iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	iomodel->Constant(&ismasstransport,TransientIsmasstransportEnum);
+	iomodel->Constant(&isstressbalance,TransientIsstressbalanceEnum);
+	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
+	iomodel->Constant(&isdamage,TransientIsdamageevolutionEnum);
+	iomodel->Constant(&ishydrology,TransientIshydrologyEnum);
+
+	SetVerbosityLevel(verbose);
+
+	if(VerboseMProcessor()) _printf0_("   starting model processor \n");
+
+	/*Partition Elements and Nodes*/
+	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
+
+	/*Create elements, vertices and materials, independent of analysis_enum: */
+	CreateElementsVerticesAndMaterials(elements,vertices,materials,iomodel,nummodels);
+
+	/*Create Parameters*/
+	CreateParameters(parameters,iomodel,rootpath,toolkitfile,solution_enum);
+
+	for(i=0;i<nummodels;i++){
+
+		analysis_enum=analysis_enum_list[i];
+		parameters->AddObject(new IntParam(AnalysisCounterEnum,i));
+
+		/*Hack for trasient runs (FIXME: to be improved)*/
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum  && iomodel->domaintype==Domain2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum  && iomodel->domaintype==Domain2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && iomodel->domaintype==Domain2DhorizontalEnum) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isthermal==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==MasstransportAnalysisEnum && ismasstransport==false && isgroundingline==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceVerticalAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceSIAAnalysisEnum && isstressbalance==false) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
+		if(solution_enum==SteadystateSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==LevelsetAnalysisEnum && islevelset==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==ExtrapolationAnalysisEnum && islevelset==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==LsfReinitializationAnalysisEnum && islevelset==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyShreveAnalysisEnum && ishydrology==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyDCEfficientAnalysisEnum && ishydrology==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyDCInefficientAnalysisEnum && ishydrology==false) continue;
+		if(solution_enum==TransientSolutionEnum && analysis_enum==DamageEvolutionAnalysisEnum && isdamage==false) continue;
+
+		if(VerboseMProcessor()) _printf0_("   creating datasets for analysis " << EnumToStringx(analysis_enum) << "\n");
+		Analysis* analysis = EnumToAnalysis(analysis_enum);
+		analysis->UpdateParameters(parameters,iomodel,solution_enum,analysis_enum);
+		analysis->CreateNodes(nodes,iomodel);
+		analysis->CreateConstraints(constraints,iomodel);
+		analysis->CreateLoads(loads,iomodel);
+		analysis->UpdateElements(elements,iomodel,i,analysis_enum);
+		delete analysis;
+
+
+		/* Update counters, because we have created more nodes, loads and
+		 * constraints, and ids for objects created in next call to CreateDataSets
+		 * will need to start at the end of the updated counters: */
+		iomodel->nodecounter       = nodes->MaximumId();
+		iomodel->loadcounter       = loads->NumberOfLoads();
+		iomodel->constraintcounter = constraints->NumberOfConstraints();
+	}
+
+	/*Solution specific updates*/
+	UpdateElementsAndMaterialsControl(elements,materials,iomodel);
+	#ifdef _HAVE_DAKOTA_
+	UpdateElementsAndMaterialsDakota(elements,materials,iomodel);
+	#endif
+	if(solution_enum==TransientSolutionEnum){
+		UpdateElementsTransient(elements,parameters,iomodel,analysis_enum);
+	}
+
+	/*Output definitions dataset: */
+	CreateOutputDefinitions(elements,parameters,iomodel);
+
+	/* Sort datasets:
+	 * All our datasets are already ordered by ids. Set presort flag so that
+	 * later on, when sorting is requested on these datasets, it will not be
+	 * redone: */
+	elements->Presort();
+	nodes->Presort();
+	vertices->Presort();
+	loads->Presort();
+	materials->Presort();
+
+	constraints->Presort();
+	parameters->Presort();
+	if(VerboseMProcessor()) _printf0_("   done with model processor \n");
+
+	/*Free resources:*/
+	delete iomodel;
+
+	/*Assign output pointers:*/
+	*pelements    = elements;
+	*pnodes       = nodes;
+	*pvertices    = vertices;
+	*pmaterials   = materials;
+	*pconstraints = constraints;
+	*ploads       = loads;
+	*pparameters  = parameters;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 18231)
@@ -0,0 +1,40 @@
+/* \file ModelProcessorx.h
+ * \brief  Header file for model processor
+ */
+
+#ifndef _MODEL_PROCESSORX_H_
+#define _MODEL_PROCESSORX_H_
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,FILE* toolkitfile, char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
+
+/*Creation of fem datasets: general drivers*/
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials, IoModel* iomodel,const int nummodels);
+void CreateParameters(Parameters*parameters,IoModel* iomodel,char* rootpath,FILE* toolkitfile,const int solution_type);
+void CreateParametersAutodiff(Parameters* parameters,IoModel* iomodel);
+void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type);
+void CreateParametersDakota(Parameters* parameters,IoModel* iomodel,char* rootpath);
+void CreateOutputDefinitions(Elements* elements, Parameters* parameters,IoModel* iomodel);
+void UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
+void UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel);
+void UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_type);
+void CreateNodes(Nodes*nodes, IoModel* iomodel,int analysis,int finite_element,int approximation=NoneApproximationEnum);
+
+/*partitioning: */
+void ElementsAndVerticesPartitioning(bool** pmy_elements, int** pmy_vertices, IoModel* iomodel);
+void NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices,  IoModel* iomodel, bool continuous);
+void FacesPartitioning(bool** pmy_faces,IoModel* iomodel);
+void EdgesPartitioning(bool** pmy_edges,IoModel* iomodel);
+
+/*Mesh properties*/
+void CreateEdges(IoModel* iomodel);
+void CreateFaces(IoModel* iomodel);
+void CreateFaces3d(IoModel* iomodel);
+void EdgeOnBoundaryFlags(bool** pflags,IoModel* iomodel);
+
+/*Connectivity*/
+void CreateSingleNodeToElementConnectivity(IoModel* iomodel);
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel);
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 18231)
@@ -0,0 +1,131 @@
+/*!\file:  NodesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel);
+void  ContinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel);
+
+void  NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel, bool continuous){
+
+	if(continuous==true)
+		ContinuousGalerkinNodesPartitioning(pmy_nodes,my_elements, my_vertices, iomodel);
+	else
+		DiscontinuousGalerkinNodesPartitioning(pmy_nodes,my_elements, my_vertices, iomodel);
+}
+
+void  ContinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
+
+	/*output: */
+	bool* my_nodes=xNew<bool>(iomodel->numberofvertices);
+	for(int i=0;i<iomodel->numberofvertices;i++) my_nodes[i]=(bool)my_vertices[i];
+
+	/*Assign output pointers:*/
+	*pmy_nodes=my_nodes;
+}
+
+void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
+
+	/* Each element has it own nodes (as many as vertices) + additional nodes
+	 * from neighboring elements for each face. This yields to a very different
+	 * partition for the nodes and the vertices. The vertices are similar to
+	 * continuous galerkin, but the nodes partitioning involves faces, which
+	 * messes up sorting of ids. */
+
+	/*Intermediaries*/
+	int  i,i1,i2;
+	int  e1,e2;
+	int  pos;
+
+	/*Get faces and elements*/
+	CreateEdges(iomodel);
+
+	/*Build discontinuous node partitioning
+	 *  - there are three nodes per element (discontinous)
+	 *  - for each element present of each partition, its three nodes will be in this partition
+	 *  - the faces require the dofs of the 2 nodes of each elements sharing the face.
+	 *    if the 2 elements sharing the face are on 2 different cpus, we must duplicate
+	 *    the two nodes that are not on the cpus so that the face can access the dofs of
+	 *    all its 4 nodes
+	 */
+
+	/*Allocate*/
+	bool* my_nodes=xNewZeroInit<bool>(3*iomodel->numberofelements);
+
+	/*First: add all the nodes of all the elements belonging to this cpu*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum){
+		for (i=0;i<iomodel->numberofelements;i++){
+			if (my_elements[i]){
+				my_nodes[3*i+0]=true;
+				my_nodes[3*i+1]=true;
+				my_nodes[3*i+2]=true;
+			}
+		}
+	}
+	else{
+		_error_("not implemented yet");
+	}
+
+	/*Second: add all missing nodes*/
+
+	/*Get faces and elements*/
+	CreateFaces(iomodel);
+
+	/*!All elements have been partitioned above, only create elements for this CPU: */
+	for(int i=0;i<iomodel->numberoffaces;i++){
+
+		/*Get left and right elements*/
+		e1=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+		e2=iomodel->faces[4*i+3]-1; //faces are [node1 node2 elem1 elem2]
+
+		/* 1) If the element e1 is in the current partition
+		 * 2) and if the face of the element is shared by another element (internal face)
+		 * 3) and if this element is not in the same partition:
+		 * we must clone the nodes on this partition so that the loads (Numericalflux)
+		 * will have access to their properties (dofs,...)*/
+		if(my_elements[e1] && e2!=-2 && !my_elements[e2]){
+
+			/*1: Get vertices ids*/
+			i1=iomodel->faces[4*i+0];
+			i2=iomodel->faces[4*i+1];
+
+			/*2: Get the column where these ids are located in the index*/
+			pos=UNDEF;
+			for(int j=0;j<3;j++){
+				if(iomodel->elements[3*e2+j]==i1) pos=j;
+			}
+
+			/*3: We have the id of the elements and the position of the vertices in the index
+			 * we can now create the corresponding nodes:*/
+			if(pos==0){
+				my_nodes[e2*3+0]=true;
+				my_nodes[e2*3+2]=true;
+			}
+			else if(pos==1){
+				my_nodes[e2*3+1]=true;
+				my_nodes[e2*3+0]=true;
+			}
+			else if(pos==2){
+				my_nodes[e2*3+2]=true;
+				my_nodes[e2*3+1]=true;
+			}
+			else{
+				_error_("Problem in faces creation");
+			}
+		}
+	}
+
+	/*Free data and assign output pointers */
+	*pmy_nodes=my_nodes;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 18231)
@@ -0,0 +1,19 @@
+/*
+ * UpdateElementsTransient:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_type){
+
+	bool isgroundingline;
+	parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+
+	if(isgroundingline){
+		iomodel->FetchDataToInput(elements,BedEnum);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file NodalValuex
+ * \brief: compute value at certain node
+ */
+
+#include "./NodalValuex.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+
+	IssmDouble value;
+	int        index;
+	int        found,sumfound,cpu_found;
+
+	/*retrieve element we are interested in: */
+	parameters->FindParam(&index,IndexEnum);
+
+	/*This is the vertex id for which we want to collect the data. Go through elements, and for each 
+	 *element, figure out  if they hold the vertex, and the data. If so, return it: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		found=element->NodalValue(&value,index,natureofdataenum);
+		if(found){
+			cpu_found=IssmComm::GetRank();
+			break;
+		}
+	}
+
+	/*Broadcast whether we found the element: */
+	ISSM_MPI_Allreduce(&found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
+
+	/*Broadcast and plug into response: */
+	ISSM_MPI_Allreduce ( &cpu_found,&cpu_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&value,1,ISSM_MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
+
+	*pnodalvalue=value;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodalValuex/NodalValuex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  NodalValuex.h
+ * \brief header file for NodalValuex
+ */ 
+
+#ifndef _NODALVALUEX_H
+#define _NODALVALUEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+
+#endif  /* _NODALVALUEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 18231)
@@ -0,0 +1,73 @@
+/*!\file NodeConnectivityx
+ * \brief: compute node connectivity table, using elements connectivity table.
+ *
+ * For each node, we want to know how many elements are connected to this element, and which they are. 
+ * Given that the 2d meshes we create in ISSM are triangular for now, and they are delaunay conforming, 
+ * each triangle has a minimum angle of 30 degrees, which implies a connectivity <=6. We therefore return 
+ * a nods x 7 connectivity table, with the 7'th column giving us the number of elements connected to each 
+ * row node, and the first 6 columns giving us the elements numbers. 
+ * Amend that: sounds like some triangles get up to 9 connectivity. Take 10 to be on the safe side.
+ * In order to be compatible with matlab output, the connectivity table is given in matlab indexing (starts at 1).
+ */
+
+#include "./NodeConnectivityx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void	NodeConnectivityx(int** pconnectivity,int* pwidth,int* elements, int nels, int nods){
+
+	int i,j,n;
+	const int maxels=50;
+	const int width=maxels+1;
+
+	/*intermediary: */
+	int     node;
+	int     index;
+	int     num_elements;
+	int     already_plugged=0;
+	int element;
+
+	/*Allocate connectivity: */
+	int* connectivity=xNewZeroInit<int>(nods*width);
+
+	/*Go through all elements, and for each elements, plug into the connectivity, all the nodes. 
+	 * If nodes are already plugged into the connectivity, skip them.: */
+	for(n=0;n<nels;n++){
+
+		element=n+1; //matlab indexing
+
+		for(i=0;i<3;i++){
+
+			node=elements[n*3+i]; //already matlab indexed, elements comes directly from the workspace.
+			index=node-1;
+
+			num_elements=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++){
+				if (element==*(connectivity+width*index+j)){
+					already_plugged=1;
+					break;
+				}
+			}
+			if(already_plugged)break;
+
+			/*this elements is not yet plugged  into the connectivity for this node, do it, and increase counter: */
+			connectivity[width*index+num_elements]=element;
+			connectivity[width*index+maxels]=num_elements+1;
+
+		}
+	}
+
+	/*Last check: is the number of elements on last column of the connectivity superior to maxels? If so, then error out and 
+	 * warn the user to increase the connectivity width: */
+	for(i=0;i<nods;i++){
+		if (*(connectivity+width*i+maxels)>maxels)
+		 _error_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
+	}
+
+	/*Assign output pointers: */
+	*pconnectivity=connectivity;
+	*pwidth=width;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 18231)
@@ -0,0 +1,11 @@
+/*!\file:  NodeConnectivityx.h
+ * \brief header file for node connectivity computation
+ */ 
+
+#ifndef _NODECONNECTIVITYX_H
+#define _NODECONNECTIVITYX_H
+
+/* local prototypes: */
+void	NodeConnectivityx(int** pconnectivity,int* pwidth,int* elements,int nels, int nods);
+
+#endif  /* _NODECONNECTIVITYX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 18231)
@@ -0,0 +1,31 @@
+/*!\file NodesDofx
+ * \brief: establish degrees of freedom for all nodes
+ */
+
+#include "./NodesDofx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void NodesDofx(Nodes* nodes, Parameters* parameters,int configuration_type){
+
+	/*Do we have any nodes for this analysis type? :*/
+	if(!nodes->NumberOfNodes(configuration_type)) return;
+
+	/*Do we really need to update dof indexings*/
+	if(!nodes->RequiresDofReindexing(configuration_type)) return;
+
+	if(VerboseModule()) _printf0_("   Renumbering degrees of freedom\n");
+
+	/*Ensure that only for each cpu, the partition border nodes only will be taken into account once 
+	 * across the cluster. To do so, we flag all the clone nodes: */
+	nodes->FlagClones(configuration_type);
+
+	/*Go through all nodes, and build degree of freedom lists. Each node gets a fixed number of dofs. When 
+	 *a  node has already been distributed dofs on one cpu, all other cpus with the same node cannot distribute it 
+	 *anymore. Use clone field to be sure of that: */
+	nodes->DistributeDofs(configuration_type,GsetEnum);
+	nodes->DistributeDofs(configuration_type,FsetEnum);
+	nodes->DistributeDofs(configuration_type,SsetEnum);
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/NodesDofx/NodesDofx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  NodesDofx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _NODESDOFX_H
+#define _NODESDOFX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void NodesDofx(Nodes* nodes, Parameters* parameters,int analysis_type);
+
+#endif  /* _NODESDOFX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 18231)
@@ -0,0 +1,42 @@
+/*!\file OutputDefinitionsResponsex
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./OutputDefinitionsResponsex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string){
+
+	Definition *definition         = NULL;
+	DataSet    *output_definitions = NULL;
+	IssmDouble  return_value;
+
+	/*Ok, go find the output definitions dataset in the parameters, where our responses are hiding: */
+	output_definitions=((DataSetParam*)femmodel->parameters->FindParamObject(OutputdefinitionEnum))->value;
+
+	/*Now, go through the output definitions, and retrieve the object which corresponds to our requested response, output_string: */
+	for(int i=0;i<output_definitions->Size();i++){
+		
+		definition=dynamic_cast<Definition*>(output_definitions->GetObjectByOffset(i));
+
+		char* name = definition->Name();
+		if (strcmp(name,output_string)==0){
+
+			/*This is the object that we have been chasing for. compute the response and return: */
+			return_value=definition->Response(femmodel);
+		
+			/*cleanup: */
+			xDelete<char>(name);
+
+			/*return:*/
+			return return_value;
+		}
+		xDelete<char>(name);
+	}
+	
+	/*If we are here, did not find the definition for this response, not good!: */
+	_error_("Could not find the response for output definition " << output_string << " because could not find the definition itself!");
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  OutputDefinitionsResponsexx.h
+*/ 
+
+#ifndef _OUTPUTDEFINITIONSRESPONSEXX_H
+#define _OUTPUTDEFINITIONSRESPONSEXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string);
+
+#endif  /* _OUTPUTDEFINITIONSRESPONSEXX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 18231)
@@ -0,0 +1,88 @@
+/*!\file:  OutputResultsx.cpp
+ * \brief: go through our finite elements, and see what results they have stored within. 
+ * Then output them into serialized patch arrays, and dump to disk.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "./OutputResultsx.h"
+#include "../../shared/io/io.h"
+#include "../../classes/classes.h"
+
+void OutputResultsx(FemModel* femmodel){
+
+	int         my_rank;
+	FILE       *fid                     = NULL;
+	char       *outputfilename          = NULL;
+	char        cpu_outputfilename[100];        //easier to convert an integer with sprintf
+	bool        io_gather;
+	int         solutiontype;
+	char*       solutiontypestring      = NULL;
+	bool        dakota_analysis         = false;
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(dakota_analysis){
+		//no need to output anything, Dakota analysis has different outputs
+		return; 
+	}
+
+	/*Results do not include the type of solution being run	. In parallel, we output results to a filename, 
+	 *therefore, we need to include the solutiontype into the filename: */
+	if(my_rank==0){
+		femmodel->parameters->FindParam(&solutiontype,SolutionTypeEnum);
+		EnumToStringx(&solutiontypestring,solutiontype);
+		femmodel->results->AddResult(new GenericExternalResult<char*>(femmodel->results->Size()+1,SolutionTypeEnum,solutiontypestring,1));
+		xDelete<char>(solutiontypestring);
+	}
+
+	/*Now, open file for writing, if not already done: */
+	if(!femmodel->parameters->Exist(OutputFilePointerEnum)){
+
+		/*We don't have a file pointer. Retrieve the output file name and open it for writing:*/
+		femmodel->parameters->FindParam(&outputfilename,OutputFileNameEnum);
+
+		/*What strategy? : */
+		femmodel->parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+
+		if(io_gather){
+			/*Just open the file for output on cpu 0. We are gathering the data on cpu 0 from all other cpus: */
+			if(my_rank==0) fid=pfopen0(outputfilename ,"wb");
+		}
+		else{
+			/*We are opening different  files for output on all cpus. Append the  rank to the filename, and open: */
+			femmodel->parameters->FindParam(&fid,OutputFilePointerEnum);
+			sprintf(cpu_outputfilename,"%s.%i",outputfilename,my_rank);
+			fid=pfopen(cpu_outputfilename ,"wb");
+		}
+		xDelete<char>(outputfilename);
+
+		/*Add file pointer in parameters for further calls to OutputResultsx: */
+		femmodel->parameters->SetParam(fid,OutputFilePointerEnum);
+	}
+
+	/*Write results to disk: */
+	femmodel->results->Write(femmodel->parameters);
+
+	/*Delete and reinitialize results, in parallel: */
+	femmodel->results->clear();
+
+	/*Close output file? :*/
+	/*FIXME WARNING: issm.cpp is taking care of it for now (quick fix)
+	  if((step==1) && (time==0)){
+	  if(io_gather){
+	  if(my_rank==0) pfclose(fid,outputfilename);
+	  }
+	  else pfclose(fid,cpu_outputfilename);
+	  }
+	*/
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 18231)
@@ -0,0 +1,18 @@
+/*!\file:  OutputResultsx.h
+ * \brief header file for outputing results
+ */ 
+
+#ifndef _OUTPUTRESULTSX_H
+#define _OUTPUTRESULTSX_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../classes/classes.h"
+
+void OutputResultsx(FemModel* femmodel);
+
+#endif  /* _OUTPUTRESULTS_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 18231)
@@ -0,0 +1,124 @@
+/*!\file ParseToolkitsOptionsx
+ * * \brief: parse options present in a petsc file, and create petsc options 
+ * objects accordingly. This will be used to drive the behaviour of Toolkits for 
+ * each analysis type.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+
+#include "./ParseToolkitsOptionsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ParseToolkitsOptionsx(Parameters* parameters,FILE* fid){
+
+	char line [1000];
+	int my_rank;
+	int i;
+
+	/*intermediary: */
+	IssmDouble* analyses=NULL;
+	char** strings=NULL;
+	int numanalyses;
+	char* string=NULL;
+	char* newstring=NULL;
+	char* catstring=NULL;
+	int   stringlength;
+
+	/*Get my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+
+		/*Now, go through lines and figure out how many analyses we have: */
+		numanalyses=0;
+		while ( fgets(line, sizeof line, fid) ){
+			/*skip comments and empty lines: */
+			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
+			/*ok, first time, we should get an analysis enum, starting with a +: */
+			if (line[0]=='+')numanalyses++;
+			else continue;
+		}
+
+		/*Now, allocate analyses and strings: */
+		analyses=xNew<IssmDouble>(numanalyses);
+		strings=xNew<char*>(numanalyses);
+		for(i=0;i<numanalyses;i++)strings[i]=NULL; 
+
+		/*Go back to beginning of file:*/
+		fseek(fid,0,SEEK_SET);
+		numanalyses=0;
+		while ( fgets(line, sizeof line, fid) ){
+
+			/*skip comments and empty lines: */
+			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
+
+			/*Get rid of end of line: */
+			line[strlen(line)-1]='\0';
+
+			if (line[0]=='+'){ /*this is the analysis line: */
+				analyses[numanalyses]=StringToEnumx(&line[1]);  //skip the '+'
+				numanalyses++;
+			}
+			else{ /*this is an option corresponding to analysis numanalyses-1. Add it 
+			to the already existing options*/
+				if(strings[numanalyses-1]==NULL){
+					string=xNew<char>((strlen(line)+1)); 
+					xMemCpy<char>(string,line,(strlen(line)+1));
+
+					strings[numanalyses-1]=string;
+				}
+				else{
+					string=strings[numanalyses-1];
+					newstring=xNew<char>((strlen(line)+1));
+					xMemCpy<char>(newstring,line,(strlen(line)+1));
+
+					/*concatenate:*/
+					catstring=xNew<char>(strlen(string)+1+strlen(newstring)+1+1); //fit in a space " "
+					xMemCpy<char>(catstring,string,(strlen(string)+1));
+
+					strcat(catstring," ");
+					strcat(catstring,newstring);
+					strings[numanalyses-1]=catstring;
+					xDelete<char>(newstring);
+					xDelete<char>(string);
+				}
+			}
+		}
+	}
+
+	/*Ok, broadcast to other cpus: */
+	ISSM_MPI_Bcast(&numanalyses,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	if(my_rank!=0){
+		analyses=xNew<IssmDouble>(numanalyses);
+		strings=xNew<char*>(numanalyses);
+	}
+	ISSM_MPI_Bcast(analyses,numanalyses,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	for(i=0;i<numanalyses;i++){
+		char* string=strings[i];
+		if(my_rank==0){
+			if(string==NULL) _error_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
+		}
+		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
+		ISSM_MPI_Bcast(&stringlength,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+		if(my_rank!=0)string=xNew<char>(stringlength);
+		ISSM_MPI_Bcast(string,stringlength,ISSM_MPI_CHAR,0,IssmComm::GetComm());
+		if(my_rank!=0)strings[i]=string;
+	}
+
+	/*Ok, out of strings and analyses and numanalyses, create parameters, and plug them into parameters container: */
+	parameters->AddObject(new StringArrayParam(ToolkitsOptionsStringsEnum,strings,numanalyses));
+	parameters->AddObject(new DoubleVecParam(ToolkitsOptionsAnalysesEnum,analyses,numanalyses));
+
+	/*Clean up and return*/
+	for(i=0;i<numanalyses;i++) xDelete<char>(strings[i]);
+	xDelete<char*>(strings);
+	xDelete<IssmDouble>(analyses);
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  ParseToolkitsOptionsx.h
+ * \brief header file for parsing petsc options file
+ */ 
+
+#ifndef _PARSEPETSCOPTIONSX_H
+#define _PARSEPETSCOPTIONSX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ParseToolkitsOptionsx(Parameters* parameters, FILE* petscoptionsfid);
+
+#endif  /* _PARSEPETSCOPTIONSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 18231)
@@ -0,0 +1,34 @@
+/*! \file  PointCloudFindNeighborsx.c
+ */
+
+#include "./PointCloudFindNeighborsx.h"
+
+int PointCloudFindNeighborsx(IssmSeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread){
+
+	/*output: */
+	IssmSeqVec<IssmPDouble>* flags=NULL;
+	flags=new IssmSeqVec<IssmPDouble>(nods);
+
+	/*threading: */
+	int num=_NUMTHREADS_;
+	if(!multithread)num=1;
+
+	/*initialize thread parameters: */
+	PointCloudFindNeighborsThreadStruct gate;
+	gate.x           = x;
+	gate.y           = y;
+	gate.nods        = nods;
+	gate.mindistance = mindistance;
+	gate.flags       = flags;
+
+	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
+	LaunchThread(PointCloudFindNeighborsxt,(void*)&gate,num);
+
+	/*Assemble vector: */
+	flags->Assemble();
+
+	/*Assign output pointers: */
+	*pflags=flags;
+
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 18231)
@@ -0,0 +1,27 @@
+/*
+	PointCloudFindNeighborsx.h
+*/
+
+#ifndef _POINTCLOUDFLAGNEIGHBORSX_H
+#define _POINTCLOUDFLAGNEIGHBORSX_H
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int PointCloudFindNeighborsx(IssmSeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread);
+
+/*threading: */
+typedef struct{
+
+	double* x;
+	double* y;
+	int nods;
+	double mindistance;
+	IssmSeqVec<IssmPDouble>* flags;
+
+} PointCloudFindNeighborsThreadStruct;
+
+void* PointCloudFindNeighborsxt(void* vPointCloudFindNeighborsThreadStruct);
+
+#endif /* _POINTCLOUDFLAGNEIGHBORSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 18231)
@@ -0,0 +1,78 @@
+/*!\file:  PointCloudFindNeighborst.cpp
+ * \brief  thread core for PointCloudFindNeighborst code
+ */ 
+
+#include "./PointCloudFindNeighborsx.h"
+#include "../../shared/shared.h"
+
+void* PointCloudFindNeighborsxt(void* vpthread_handle){
+
+	/*gate variables :*/
+	PointCloudFindNeighborsThreadStruct* gate=NULL;
+	pthread_handle* handle=NULL;
+	int     my_thread;
+	int     num_threads;
+	double* x;
+	double* y;
+	int     nods;
+	double  mindistance;
+	IssmSeqVec<IssmPDouble>*     flags;
+
+	/*recover handle and gate: */
+	handle=(pthread_handle*)vpthread_handle;
+	gate=(PointCloudFindNeighborsThreadStruct*)handle->gate;
+	my_thread=handle->id;
+	num_threads=handle->num;
+
+	/*recover parameters :*/
+	x=gate->x;
+	y=gate->y;
+	nods=gate->nods;
+	mindistance=gate->mindistance;
+	flags=gate->flags;
+
+	/*intermediary: */
+	int i,j;
+	int i0,i1;
+	double distance;
+	bool* already=NULL;
+
+	/*allocate: */
+	already=xNewZeroInit<bool>(nods);
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+
+	/*Loop over the nodes*/
+	for (i=i0;i<i1;i++){
+
+		/*display current iteration*/
+		if (my_thread==0 && fmod((double)i,(double)100)==0)
+		 _printf_("\r      loop progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
+
+		distance=mindistance+100; //make sure initialization respects min distance criterion.
+		for (j=0;j<nods;j++){
+
+			/*skip himself: */
+			if (j==i)continue;
+			distance=sqrt(pow(x[i]-x[j],2)+ pow(y[i]-y[j],2));
+
+			if(distance<=mindistance){
+
+				/*insert value and go to the next point*/
+				if(!already[i]) flags->SetValue(i,1,INS_VAL);
+				if(!already[j]) flags->SetValue(j,2,INS_VAL);
+				already[i]=true;
+				already[j]=true;
+				break;
+			}
+		}
+	}
+	if (my_thread==0)
+	 _printf_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+
+	/*Free ressources:*/
+	xDelete<bool>(already);
+
+	return NULL;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 18231)
@@ -0,0 +1,36 @@
+/*!\file PropagateFlagsFromConnectivityx
+ */
+
+#include "./PropagateFlagsFromConnectivityx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void RecursivePropagation(double* pool, double* connectivity,int index, double* flags);
+
+void PropagateFlagsFromConnectivityx( double* pool, double* connectivity,int index, double* flags){
+
+	/*Call recursive propagation routine: */
+	RecursivePropagation(pool, connectivity,index, flags);
+}
+
+void RecursivePropagation(double* pool, double* connectivity, int index, double* flags){
+
+	int i;
+	int newel;
+
+	/*if this element (index) belongs to the pool already, skip: */
+	if(pool[index-1])return;
+
+	/*if this element does not belong to the flags set, skip: */
+	if(flags[index-1]==0)return;
+
+	/*put this element (index), which belongs to the flags, into the pool: */
+	pool[index-1]=1;
+
+	/*now, propagate recursively using connectivity of this element: */
+	for(i=0;i<3;i++){
+		newel=(int)*(connectivity+(index-1)*3+i);
+		RecursivePropagation(pool, connectivity, newel, flags);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  PropagateFlagsFromConnectivityx.h
+ */ 
+
+#ifndef _PROPAGATEFLAGSFROMCONNECTIVITYX_H
+#define _PROPAGATEFLAGSFROMCONNECTIVITYX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void PropagateFlagsFromConnectivityx( double* pool, double* connectivity,int index, double* flags);
+
+#endif  /* _PROPAGATEFLAGSFROMCONNECTIVITYX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 18231)
@@ -0,0 +1,59 @@
+/*!\file Reduceloadx
+ * \brief reduce loads (wring out boundary conditions)
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Reduceloadx.h"
+#include "../../shared/io/io.h"
+
+void	Reduceloadx( Vector<IssmDouble>* pf, Matrix<IssmDouble>* Kfs, Vector<IssmDouble>* y_s,bool flag_ys0){
+
+	/*intermediary*/
+	Vector<IssmDouble>*     y_s0   = NULL;
+	Vector<IssmDouble>*     Kfsy_s = NULL;
+	int         Kfsm,Kfsn;
+	int         global_m,global_n;
+	bool        fromlocalsize = true;
+	bool        oldalloc  = false;
+
+	if(VerboseModule()) _printf0_("   Dirichlet lifting applied to load vector\n");
+
+	Kfs->GetSize(&global_m,&global_n);
+	if(pf && global_m*global_n){
+
+		/*Some checks in debugging mode*/
+		_assert_(y_s);
+
+		/*pf = pf - Kfs * y_s;*/
+		Kfs->GetLocalSize(&Kfsm,&Kfsn);
+		if(oldalloc)
+		 Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
+		else
+		 Kfsy_s=new Vector<IssmDouble>(Kfsm,global_m);
+
+		if (flag_ys0){
+
+			/*Create y_s0, full of 0: */
+			y_s0=y_s->Duplicate();
+			y_s0->Set(0.0);
+			y_s0->Assemble();
+
+			Kfs->MatMult(y_s0,Kfsy_s);
+		}
+		else{
+			Kfs->MatMult(y_s,Kfsy_s);
+		}
+
+		pf->AXPY(Kfsy_s,-1.);
+	}
+
+	/*Free ressources and return*/
+	delete y_s0;
+	delete Kfsy_s;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  Reduceloadx.h
+ * \brief reduce loads (wring out boundary conditions)
+ */ 
+
+#ifndef _REDUCELOADX_H
+#define _REDUCELOADX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void	Reduceloadx( Vector<IssmDouble>* pf, Matrix<IssmDouble>* Kfs, Vector<IssmDouble>* ys,bool flag_ys0=false);
+
+#endif  /* _REDUCELOADX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 18231)
@@ -0,0 +1,66 @@
+/*!\file Reducevectorgtofx
+ * \brief reduce petsc vector from g set to s set (free dofs), using the nodeset partitioning 
+ * vectors.
+ */
+
+#include "./Reducevectorgtofx.h"
+
+void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters){
+
+	/*output: */
+	Vector<IssmDouble>* uf=NULL;
+
+	/*variables: */
+	int         configuration_type;
+	int         fsize;
+	IssmDouble *ug_serial = NULL;
+	bool        oldalloc  = false;
+
+	if(VerboseModule()) _printf0_("   Reduce vector from g to f set\n");
+
+	/*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){
+		uf=NULL;
+	}
+	else{
+		/*allocate: */
+		if(oldalloc)
+		 uf=new Vector<IssmDouble>(fsize);
+		else
+		 uf=new Vector<IssmDouble>(flocalsize,fsize);
+
+		if(nodes->NumberOfNodes(configuration_type)){ 
+
+			/*serialize ug, so nodes can index into it: */
+			ug_serial=ug->ToMPISerial();
+
+			/*Go through all nodes, and ask them to retrieve values from ug, and plug them into uf: */
+			for(int i=0;i<nodes->Size();i++){
+
+				Node* node=(Node*)nodes->GetObjectByOffset(i);
+
+				/*Check that this node corresponds to our analysis currently being carried out: */
+				if (node->InAnalysis(configuration_type)){
+
+					/*For this object, reduce values for enum set Fset: */
+					node->VecReduce(uf,ug_serial,FsetEnum);
+				}
+			}
+		}
+		/*Assemble vector: */
+		uf->Assemble();
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(ug_serial);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  Reducevectorgtofx.h
+ * \brief reduce petsc vector from g set to f set (free dofs), using the nodeset partitioning 
+ * vectors.
+ */ 
+
+#ifndef _REDUCEVECTORGTOFX_H
+#define _REDUCEVECTORGTOFX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters);
+
+#endif  /* _REDUCEVECTORGTOFX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 18231)
@@ -0,0 +1,40 @@
+/*!\file ResetConstraintsx
+ * \brief: reset thermal penalties
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ResetConstraintsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../ConstraintsStatex/ConstraintsStatex.h"
+
+void ResetConstraintsx(FemModel* femmodel){
+
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Resetting penalties\n");
+
+	/*recover parameters: */
+	int analysis_type;
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Deal with rift first*/
+	if(RiftIsPresent(femmodel->loads,analysis_type)){
+		_error_("rift constraints reset not supported yet!");
+	}
+
+	/*Reset pengrid to inactive mode*/
+	for(int i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(analysis_type)){
+			if(load->ObjectEnum()==PengridEnum){
+				Pengrid* pengrid=(Pengrid*)load;
+				pengrid->ResetConstraint();
+			}
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  ResetConstraintsx.h
+ * \brief header file for penalty constraints module
+ */ 
+
+#ifndef _RESETCONSTRAINTSX_H
+#define _RESETCONSTRAINTSX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ResetConstraintsx(FemModel* femmodel);
+
+#endif  /* _RESETCONSTRAINTSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp	(revision 18231)
@@ -0,0 +1,18 @@
+/*!\file ResetFSBasalBoundaryConditionx
+ * \brief: reset coordinate system for full-FS: tangential to the bedrock
+ */
+
+#include "./ResetFSBasalBoundaryConditionx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ResetFSBasalBoundaryConditionx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,Parameters* parameters){
+
+	Element *element = NULL;
+
+	for (int i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->ResetFSBasalBoundaryCondition();
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  ResetFSBasalBoundaryConditionx.h
+ * \brief header file for reset coordinate system module
+ */ 
+
+#ifndef _RESETFSBASALBOUNDARYCONDITIONX_H
+#define _RESETFSBASALBOUNDARYCONDITIONX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ResetFSBasalBoundaryConditionx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+
+#endif  /* _RESETFSBASALBOUNDARYCONDITIONX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 18231)
@@ -0,0 +1,86 @@
+/*!\file RheologyBbarAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./RheologyBbarAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=RheologyBbarAbsGradient(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble RheologyBbarAbsGradient(Element* element){
+
+	int         domaintype,numcomponents;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble  dp[2],weight;
+	IssmDouble* xyz_list      = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn basal element*/
+	Element* basalelement = element->SpawnBasalElement();
+
+	/* Get node coordinates*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* rheologyb_input=basalelement->GetInput(MaterialsRheologyBbarEnum);                  _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
+		rheologyb_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		Jelem+=weight*1/2*(dp[0]*dp[0] + dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  RheologyBbarAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _RHEOLOGYBBARGRADIENTX_H
+#define _RHEOLOGYBBARGRADIENTX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble RheologyBbarAbsGradient(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.cpp	(revision 18231)
@@ -0,0 +1,344 @@
+/* Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS
+**
+** This file is part of the Scotch software package for static mapping,
+** graph partitioning and sparse matrix ordering.
+**
+** This software is governed by the CeCILL-C license under French law
+** and abiding by the rules of distribution of free software. You can
+** use, modify and/or redistribute the software under the terms of the
+** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
+** URL: "http://www.cecill.info".
+** 
+** As a counterpart to the access to the source code and rights to copy,
+** modify and redistribute granted by the license, users are provided
+** only with a limited warranty and the software's author, the holder of
+** the economic rights, and the successive licensors have only limited
+** liability.
+** 
+** In this respect, the user's attention is drawn to the risks associated
+** with loading, using, modifying and/or developing or reproducing the
+** software by the user in light of its specific status of free software,
+** that may mean that it is complicated to manipulate, and that also
+** therefore means that it is reserved for developers and experienced
+** professionals having in-depth computer knowledge. Users are therefore
+** encouraged to load and test the software's suitability as regards
+** their requirements in conditions enabling the security of their
+** systems and/or data to be ensured and, more generally, to use and
+** operate it in the same conditions as regards security.
+** 
+** The fact that you are presently reading this means that you have had
+** knowledge of the CeCILL-C license and that you accept its terms.
+*/
+/************************************************************/
+/**                                                        **/
+/**   NAME       : gmap.c                                  **/
+/**                                                        **/
+/**   AUTHOR     : Francois PELLEGRINI                     **/
+/**                                                        **/
+/**   FUNCTION   : Part of a graph mapping software.       **/
+/**                This module contains the main function. **/
+/**                                                        **/
+/**   DATES      : # Version 0.0  : from : 05 jan 1993     **/
+/**                                 to     12 may 1993     **/
+/**                # Version 1.1  : from : 15 oct 1993     **/
+/**                                 to     15 oct 1993     **/
+/**                # Version 1.3  : from : 06 apr 1994     **/
+/**                                 to     18 may 1994     **/
+/**                # Version 2.0  : from : 06 jun 1994     **/
+/**                                 to     17 nov 1994     **/
+/**                # Version 2.1  : from : 07 apr 1995     **/
+/**                                 to     18 jun 1995     **/
+/**                # Version 3.0  : from : 01 jul 1995     **/
+/**                                 to     02 oct 1995     **/
+/**                # Version 3.1  : from : 07 nov 1995     **/
+/**                                 to     25 apr 1996     **/
+/**                # Version 3.2  : from : 24 sep 1996     **/
+/**                                 to     26 may 1998     **/
+/**                # Version 3.3  : from : 19 oct 1998     **/
+/**                                 to   : 30 mar 1999     **/
+/**                # Version 3.4  : from : 03 feb 2000     **/
+/**                                 to   : 03 feb 2000     **/
+/**                # Version 4.0  : from : 16 jan 2004     **/
+/**                                 to   : 27 dec 2004     **/
+/**                # Version 5.0  : from : 23 dec 2007     **/
+/**                                 to   : 18 jun 2008     **/
+/**                                                        **/
+/************************************************************/
+
+#include "./Scotchx.h"
+
+int
+gmapx (
+  int                 (**pmaptabi)[2],
+  int                 argcm,
+  char                *argvm[],
+  int                 nvi,
+  int                 ne2i,
+  int                 *ir,
+  int                 *jc,
+  int                 *vli,
+  int                 *vwi,
+  int                 *ewi,
+  char                archtyp[],
+  int                 nai,
+  int                 *api)
+{ 
+#ifdef _HAVE_SCOTCH_ //only works if Scotch library has been compiled in.
+
+  SCOTCH_Graph        grafdat;                    /* Source graph            */
+  SCOTCH_Num          grafflag;                   /* Source graph properties */
+  SCOTCH_Arch         archdat;                    /* Target architecture     */
+  SCOTCH_Strat        stradat;                    /* Mapping strategy        */
+  SCOTCH_Mapping      mapdat;                     /* Mapping data            */
+  Clock               runtime[2];                 /* Timing variables        */
+  SCOTCH_Num          nvert =0;
+  SCOTCH_Num          nedge2=0;
+  SCOTCH_Num*         adjir  =NULL;
+  SCOTCH_Num*         adjjc  =NULL;
+  SCOTCH_Num*         vertlab=NULL;
+  SCOTCH_Num*         vertwgt=NULL;
+  SCOTCH_Num*         edgewgt=NULL;
+  SCOTCH_Num          napar =0;
+  SCOTCH_Num*         archpar=NULL;
+  SCOTCH_Num          (*maptab)[2]=NULL;
+  int                 (*maptabi)[2]=NULL;
+  int                 flagval;
+  int                 i,j,k;
+
+/*  reset static variables from previous runs (jes, 4/27/10)  */
+
+  C_partNbr = 2;        /* Default number of parts     */
+  C_paraNum = 0;        /* Number of parameters        */
+  C_paraNbr = 0;        /* No parameters for mapping   */
+  C_fileNum = 0;        /* Number of file in arg list  */
+  C_fileNbr = 4;        /* Number of files for mapping */
+  for (i=0; i<C_FILENBR; i++) {
+    C_fileTab[i].name = "-";
+    C_fileTab[i].pntr = NULL;
+    if (i < 2)
+      C_fileTab[i].mode = "r";
+    else
+      C_fileTab[i].mode = "w";
+  }
+
+/*  convert input arguments to scotch data types  */
+
+  nvert =(SCOTCH_Num)nvi;
+  nedge2=(SCOTCH_Num)ne2i;
+
+  if (ir && jc) {
+    adjir = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      adjir[i]=(SCOTCH_Num)ir[i];
+    adjjc = (SCOTCH_Num *) malloc((nvert+1)*sizeof(SCOTCH_Num));
+    for (i=0; i<(nvert+1); i++)
+      adjjc[i]=(SCOTCH_Num)jc[i];
+  }
+
+  if (vli) {
+    vertlab = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertlab[i]=(SCOTCH_Num)vli[i];
+  }
+
+  if (vwi) {
+    vertwgt = (SCOTCH_Num *) malloc(nvert*sizeof(SCOTCH_Num));
+    for (i=0; i<nvert; i++)
+      vertwgt[i]=(SCOTCH_Num)vwi[i];
+  }
+
+  if (ewi) {
+    edgewgt = (SCOTCH_Num *) malloc(nedge2*sizeof(SCOTCH_Num));
+    for (i=0; i<nedge2; i++)
+      edgewgt[i]=(SCOTCH_Num)ewi[i];
+  }
+
+  napar =(SCOTCH_Num)nai;
+
+  if (api) {
+    archpar = (SCOTCH_Num *) malloc(nai*sizeof(SCOTCH_Num));
+    for (i=0; i<nai; i++)
+      archpar[i]=(SCOTCH_Num)api[i];
+  }
+
+/*  start scotch processing  */
+
+  flagval = C_FLAGNONE;                           /* Default behavior */
+  i = strlen (argvm[0]);
+  if ((i >= 5) && (strncmp (argvm[0] + i - 5, "gpart", 5) == 0)) {
+    flagval |= C_FLAGPART;
+    C_paraNbr = 1;                                /* One more parameter       */
+    C_fileNbr = 3;                                /* One less file to provide */
+    errorProg ("gpart");
+  }
+  else
+    errorProg ("gmap");
+
+  intRandResetStatic ();
+  intRandInit ();
+
+  if ((argcm >= 2) && (argvm[1][0] == '?')) {       /* If need for help */
+    usagePrint (stdout, C_usageList);
+    return     (0);
+  }
+
+  grafflag = 0;                                   /* Use vertex and edge weights  */
+  SCOTCH_stratInit (&stradat);                    /* Set default mapping strategy */
+
+  for (i = 0; i < C_FILENBR; i ++)                /* Set default stream pointers */
+    C_fileTab[i].pntr = (C_fileTab[i].mode[0] == 'r') ? stdin : stdout;
+  for (i = 1; i < argcm; i ++) {                   /* Loop for all option codes                        */
+    if ((argvm[i][0] != '-') || (argvm[i][1] == '\0') || (argvm[i][1] == '.')) { /* If found a file name */
+      if (C_paraNum < C_paraNbr) {                /* If number of parameters not reached              */
+        if ((C_partNbr = atoi (argvm[i])) < 1)     /* Get the number of parts                          */
+          errorPrint ("main: invalid number of parts (\"%s\")", argvm[i]);
+        C_paraNum ++;
+        continue;                                 /* Process the other parameters */
+      }
+      if (C_fileNum < C_fileNbr)                  /* A file name has been given */
+        C_fileTab[C_fileNum ++].name = argvm[i];
+      else
+        errorPrint ("main: too many file names given");
+    }
+    else {                                        /* If found an option name */
+      switch (argvm[i][1]) {
+        case 'H' :                                /* Give the usage message */
+        case 'h' :
+          usagePrint (stdout, C_usageList);
+          return     (0);
+        case 'M' :
+        case 'm' :
+          SCOTCH_stratExit (&stradat);
+          SCOTCH_stratInit (&stradat);
+          SCOTCH_stratGraphMap (&stradat, &argvm[i][2]);
+          break;
+        case 'S' :
+        case 's' :                                /* Source graph parameters */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'E' :
+              case 'e' :
+                grafflag |= 2;                    /* Do not load edge weights */
+                break;
+              case 'V' :
+              case 'v' :
+                grafflag |= 1;                    /* Do not load vertex weights */
+                break;
+              default :
+                errorPrint ("main: invalid source graph option (\"%c\")", argvm[i][j]);
+            }
+          }
+          break;
+        case 'V' :
+          fprintf (stderr, "gmap/gpart, version %s - F. Pellegrini\n", SCOTCH_VERSION);
+          fprintf (stderr, "Copyright 2004,2007,2008 ENSEIRB, INRIA & CNRS, France\n");
+          fprintf (stderr, "This software is libre/free software under CeCILL-C -- see the user's manual for more information\n");
+          return  (0);
+        case 'v' :                                /* Output control info */
+          for (j = 2; argvm[i][j] != '\0'; j ++) {
+            switch (argvm[i][j]) {
+              case 'M' :
+              case 'm' :
+                flagval |= C_FLAGVERBMAP;
+                break;
+              case 'S' :
+              case 's' :
+                flagval |= C_FLAGVERBSTR;
+                break;
+              case 'T' :
+              case 't' :
+                flagval |= C_FLAGVERBTIM;
+                break;
+              default :
+                errorPrint ("main: unprocessed parameter \"%c\" in \"%s\"", argvm[i][j], argvm[i]);
+            }
+          }
+          break;
+        default :
+          errorPrint ("main: unprocessed option (\"%s\")", argvm[i]);
+      }
+    }
+  }
+  if ((flagval && C_FLAGPART) != 0) {              /* If program run as the partitioner            */
+    C_fileTab[3].name = C_fileTab[2].name;        /* Put provided file names at their right place */
+    C_fileTab[2].name = C_fileTab[1].name;
+    C_fileTab[1].name = "-";
+  }
+
+  fileBlockOpen (C_fileTab, C_FILENBR);           /* Open all files */
+
+  clockInit  (&runtime[0]);
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphInit (&grafdat);                    /* Create graph structure         */
+  SCOTCH_graphLoad (&grafdat, C_filepntrsrcinp, -1, grafflag, nvert, nedge2, adjir, adjjc, vertlab, vertwgt, edgewgt); /* Read source graph */
+
+  SCOTCH_archInit (&archdat);                     /* Create architecture structure          */
+  if ((flagval & C_FLAGPART) != 0)                /* If program run as the partitioner      */
+    SCOTCH_archCmplt (&archdat, C_partNbr);       /* Create a complete graph of proper size */
+  else
+    SCOTCH_archLoad (&archdat, C_filepntrtgtinp, archtyp, napar, archpar); /* Read target architecture */
+
+  clockStop  (&runtime[0]);                       /* Get input time */
+  clockInit  (&runtime[1]);
+  clockStart (&runtime[1]);
+
+  SCOTCH_graphMapInit    (&grafdat, &mapdat, &archdat, NULL);
+  SCOTCH_graphMapCompute (&grafdat, &mapdat, &stradat); /* Perform mapping */
+
+  clockStop  (&runtime[1]);                       /* Get computation time */
+  clockStart (&runtime[0]);
+
+  SCOTCH_graphMapSave (&nvert, &maptab, &grafdat, &mapdat, C_filepntrmapout); /* Write mapping */
+
+/*  convert output arguments from scotch data types  */
+
+  if (maptab) {
+    *pmaptabi = (int (*)[2]) malloc(nvert*2*sizeof(int));
+    maptabi  = *pmaptabi;
+    for (j=0; j<2; j++)
+      for (i=0; i<nvert; i++)
+          maptabi[i][j]=(int)maptab[i][j];
+    free(maptab);
+  }
+
+  clockStop (&runtime[0]);                        /* Get output time */
+
+  if (flagval && C_FLAGVERBSTR) {
+    fprintf (C_filepntrlogout, "S\tStrat=");
+    SCOTCH_stratSave (&stradat, C_filepntrlogout);
+    putc ('\n', C_filepntrlogout);
+  }
+  if (flagval && C_FLAGVERBTIM) {
+    fprintf (C_filepntrlogout, "T\tMapping\t\t%g\nT\tI/O\t\t%g\nT\tTotal\t\t%g\n",
+             (double) clockVal (&runtime[1]),
+             (double) clockVal (&runtime[0]),
+             (double) clockVal (&runtime[0]) +
+             (double) clockVal (&runtime[1]));
+  }
+  if (flagval && C_FLAGVERBMAP)
+    SCOTCH_graphMapView (&grafdat, &mapdat, C_filepntrlogout);
+
+  fileBlockClose (C_fileTab, C_FILENBR);          /* Always close explicitely to end eventual (un)compression tasks */
+
+  SCOTCH_graphMapExit (&grafdat, &mapdat);
+  SCOTCH_graphExit    (&grafdat);
+  SCOTCH_stratExit    (&stradat);
+  SCOTCH_archExit     (&archdat);
+
+  if (archpar) free(archpar);
+  if (edgewgt) free(edgewgt);
+  if (vertwgt) free(vertwgt);
+  if (vertlab) free(vertlab);
+  if (adjjc) free(adjjc);
+  if (adjir) free(adjir);
+
+#ifdef COMMON_PTHREAD
+  pthread_exit ((void *) 0);                      /* Allow potential (un)compression tasks to complete */
+#endif /* COMMON_PTHREAD */
+  return (0);
+
+#else //#ifdef _HAVE_SCOTCH_ 
+  return(0);
+#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Scotchx/Scotchx.h	(revision 18231)
@@ -0,0 +1,67 @@
+/*!\file:  Scotchxx.h
+ * \brief header file for Scotch partitioner
+ */ 
+
+#ifndef _SCOTCHX_H
+#define _SCOTCHX_H
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Scotchx"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../../classes/classes.h"
+
+#ifdef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
+
+	#define GMAP
+
+	#include "scotch_module.h"
+	#include "scotch_common.h"
+	#include "scotch.h"
+	#include "scotch_gmap.h"
+
+	/*
+	**  The static variables.
+	*/
+
+	static int                  C_partNbr = 2;        /* Default number of parts     */
+	static int                  C_paraNum = 0;        /* Number of parameters        */
+	static int                  C_paraNbr = 0;        /* No parameters for mapping   */
+	static int                  C_fileNum = 0;        /* Number of file in arg list  */
+	static int                  C_fileNbr = 4;        /* Number of files for mapping */
+	static File                 C_fileTab[C_FILENBR] = { /* File array               */
+								  { "-", NULL, "r" },
+								  { "-", NULL, "r" },
+								  { "-", NULL, "w" },
+								  { "-", NULL, "w" } };
+
+	static const char *         C_usageList[] = {     /* Usage */
+	  "gmap [<input source file> [<input target file> [<output mapping file> [<output log file>]]]] <options>",
+	  "gpart [<nparts>] [<input source file> [<output mapping file> [<output log file>]]] <options>",
+	  "  -h         : Display this help",
+	  "  -m<strat>  : Set mapping strategy (see user's manual)",
+	  "  -s<obj>    : Force unity weights on <obj>:",
+	  "                 e  : edges",
+	  "                 v  : vertices",
+	  "  -V         : Print program version and copyright",
+	  "  -v<verb>   : Set verbose mode to <verb>:",
+	  "                 m  : mapping information",
+	  "                 s  : strategy information",
+	  "                 t  : timing information",
+	  "",
+	  "See default strategy with option '-vs'",
+	  NULL };
+
+#endif
+
+/* local prototypes: */
+int gmapx ( int (**pmaptabi)[2], int argcm, char *argvm[], int nvi, int ne2i, int *ir, int *jc, int *vli, int *vwi, int *ewi, char archtyp[], int nai, int *api);
+
+#endif  /* _SCOTCHX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 18231)
@@ -0,0 +1,130 @@
+/*!\file GetMaskOfIceVerticesLSMx 
+ * \brief: Return a mask for all the vertices determining whether the node should be active or not. 
+ */
+
+#include "./SetActiveNodesLSMx.h"
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../modules.h"
+
+void SetActiveNodesLSMx(FemModel* femmodel){/*{{{*/
+	/* activate/deactivate nodes for levelset method according to IceMaskNodeActivation */
+
+	/* intermediaries */
+	bool solvein2d=false;
+	int i,in,domaintype,analysis_type;
+	Elements* elements = femmodel->elements;
+
+	/* find parameters */
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	for(i=0;i<elements->Size();i++){
+		Element    *element  = dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		int         numnodes = element->GetNumberOfNodes();
+		IssmDouble *mask     = xNew<IssmDouble>(numnodes);
+		// include switch for elements with multiple different sets of nodes
+		switch(element->GetElementType()){
+			case MINIEnum:case TaylorHoodEnum:{
+				Input* input=element->GetInput(IceMaskNodeActivationEnum);
+				if(!input) _error_("Input " << EnumToStringx(IceMaskNodeActivationEnum) << " not found in element");
+
+				/* Start looping on the number of vertices: */
+				Gauss* gauss=element->NewGauss();
+				for(int iv=0;iv<element->NumberofNodesVelocity();iv++){
+					gauss->GaussNode(element->VelocityInterpolation(),iv);
+					input->GetInputValue(&mask[iv],gauss);
+				}
+				for(int iv=0;iv<element->NumberofNodesPressure();iv++){
+					gauss->GaussNode(element->PressureInterpolation(),iv);
+					input->GetInputValue(&mask[element->NumberofNodesVelocity()+iv],gauss);
+				}
+				delete gauss;
+				break;
+			}
+			default:
+				element->GetInputListOnNodes(&mask[0],IceMaskNodeActivationEnum);
+				break;
+		}
+
+		/* if solving 2d problem on vertically extende mesh, solve on basal layer only*/
+		if(domaintype!=Domain2DhorizontalEnum){
+			femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+			if(
+					analysis_type==FreeSurfaceBaseAnalysisEnum || 
+					analysis_type==MasstransportAnalysisEnum || 
+					analysis_type==MeltingAnalysisEnum || 
+					analysis_type==L2ProjectionBaseAnalysisEnum || 
+					analysis_type==BalancethicknessAnalysisEnum ||
+					analysis_type==HydrologyDCInefficientAnalysisEnum ||
+					analysis_type==DamageEvolutionAnalysisEnum || 
+					analysis_type==HydrologyDCEfficientAnalysisEnum ||
+					analysis_type==LevelsetAnalysisEnum ||
+					analysis_type==ExtrapolationAnalysisEnum
+					){ solvein2d=true;}
+
+			if(analysis_type==StressbalanceAnalysisEnum){
+				bool isSIA,isSSA;
+				femmodel->parameters->FindParam(&isSIA,FlowequationIsSIAEnum);
+				femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+				if(isSIA || isSSA)
+					solvein2d=true;
+			}
+
+			if(solvein2d){
+				IssmDouble *mask_isonbase = xNew<IssmDouble>(numnodes);
+				element->GetInputListOnNodes(&mask_isonbase[0],MeshVertexonbaseEnum);
+				for(in=0;in<numnodes;in++)	 mask[in]*=mask_isonbase[in];
+				xDelete<IssmDouble>(mask_isonbase);
+			}
+		}
+
+		for(in=0;in<numnodes;in++){
+			Node* node=element->GetNode(in);
+			if(mask[in]==1.){
+				node->Activate();
+			}
+			else {
+				node->Deactivate();
+			}
+		}
+
+		xDelete<IssmDouble>(mask);
+	}
+}/*}}}*/
+void GetMaskOfIceVerticesLSMx(FemModel* femmodel){/*{{{*/
+
+	/* Intermediaries */
+	int i;
+
+	/*Initialize vector with number of vertices*/
+	int numvertices=femmodel->vertices->NumberOfVertices();
+	Vector<IssmDouble>* vec_mask_ice=new Vector<IssmDouble>(numvertices); //vertices that have ice at next time step
+	/*Fill vector with values: */
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		SetMaskOfIceElement(vec_mask_ice, element);
+	}
+
+	/*Assemble vector and serialize */
+	vec_mask_ice->Assemble();
+	IssmDouble* mask_ice=vec_mask_ice->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,mask_ice,IceMaskNodeActivationEnum,VertexSIdEnum);
+
+	/*Clean up and return*/
+	delete vec_mask_ice;
+	delete mask_ice;
+
+}/*}}}*/
+void SetMaskOfIceElement(Vector<IssmDouble>* vec_mask_ice, Element* element){/*{{{*/
+
+	/* Intermediaries */
+	int numvertices = element->GetNumberOfVertices();
+	
+	if(element->IsIceInElement()){
+		for(int i = 0;i<numvertices;i++){
+			vec_mask_ice->SetValue(element->vertices[i]->Sid(),1.,INS_VAL);
+		}
+	}
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  SetActiveNodesLSMx.h
+ * \brief header file for updating single point constraints  for next time step
+ */ 
+
+#ifndef _SETACTIVENODESLSMX_H
+#define _SETACTIVENODESLSMX_H
+
+#include "../../classes/classes.h"
+
+void SetActiveNodesLSMx(FemModel* femmodel);
+void GetMaskOfIceVerticesLSMx(FemModel* femmodel);
+void SetMaskOfIceElement(Vector<IssmDouble>* vec_mask_ice, Element* element);
+#endif  /* _UPDATESPCSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file SetControlInputsFromVectorx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./SetControlInputsFromVectorx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector){
+
+	int  num_controls;
+	int *control_type = NULL;
+
+	/*Retrieve some parameters*/
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<femmodel->elements->Size();j++){
+			Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
+			element->SetControlInputsFromVector(vector,control_type[i],i);
+		}
+	}
+
+	xDelete<int>(control_type);
+}
+
+void SetControlInputsFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector){
+
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	SetControlInputsFromVectorx(femmodel,serial_vector);
+	xDelete<IssmDouble>(serial_vector);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  SetControlInputsFromVectorx.h
+ */ 
+
+#ifndef _SETCONTROLINPUTSXFROMVECTOR_H
+#define _SETCONTROLINPUTSXFROMVECTOR_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SetControlInputsFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector);
+void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector);
+
+#endif 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 18231)
@@ -0,0 +1,594 @@
+/*!\file Shp2Kmlx
+ * \brief shp to kml conversion routines.
+ */
+
+#include "./Shp2Kmlx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../kml/kmlobjects.h"
+
+int Shp2Kmlx(char* filshp,char* filkml,int sgn){
+
+	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+
+	double  cm,sp;
+	Xy2lldef(&cm,&sp,sgn);
+
+	return(Shp2Kmlx(filshp,filkml,sgn,cm,sp));
+
+	#else //ifdef _HAVE_SHAPELIB_
+	return 0;
+	#endif
+}
+
+int Shp2Kmlx(char* filshp,char* filkml,int sgn,double cm,double sp){
+
+	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+
+	int     i,j,k,iret=0;
+	int     lwidth=1;
+	double  popac=0.50;
+	int     nshape,ncoord;
+	double  cpsum;
+	int     *pstype = NULL, *pnpart=NULL,**ppstrt=NULL,**pptype=NULL,*pnvert=NULL;
+	double **pshapx = NULL,**pshapy=NULL,**pshapz=NULL,**pshapm=NULL;
+	double  *lat    = NULL, *lon=NULL;
+
+	SHPHandle   hSHP;
+	int     nShapeType, nEntities, iPart, bValidate = 0,nInvalidCount=0;
+	const char  *pszPlus;
+	double  adfMinBound[4], adfMaxBound[4];
+
+	char    indent[81]="";
+	KML_File          *kfile  = NULL;
+	KML_Document      *kdoc   = NULL;
+	KML_Style         *kstyle = NULL;
+	KML_LineStyle     *klsty  = NULL;
+	KML_PolyStyle     *kpsty  = NULL;
+	KML_Folder        *kfold  = NULL;
+	KML_Placemark     *kplace = NULL;
+	KML_MultiGeometry *kmulti = NULL;
+	KML_Polygon       *kpoly  = NULL;
+	KML_LinearRing    *kring  = NULL;
+	KML_LineString    *kline  = NULL;
+	KML_Point         *kpoint = NULL;
+	FILE              *fid    = NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf0_("\nShp2Kmlx Module -- " << ctime(&time0));
+
+/*  note that much of the following code is taken from shpdump.c in shapelib.  */
+
+/*  open shp/shx files  */
+
+	hSHP = SHPOpen( filshp, "rb" );
+	if (!hSHP) _error_("Error opening shp/shx files.");
+
+/*  read header and print out file bounds  */
+
+	SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );
+
+	printf( "Shapefile Type: %s   # of Shapes: %d\n\n",
+			SHPTypeName( nShapeType ), nEntities );
+
+	printf( "File Bounds: (%12.3f,%12.3f,%g,%g)\n"
+			"         to  (%12.3f,%12.3f,%g,%g)\n",
+			adfMinBound[0],
+			adfMinBound[1],
+			adfMinBound[2],
+			adfMinBound[3],
+			adfMaxBound[0],
+			adfMaxBound[1],
+			adfMaxBound[2],
+			adfMaxBound[3] );
+
+	nshape=nEntities;
+	pstype=xNew<int>(nshape);
+	pnpart=xNew<int>(nshape);
+	ppstrt=xNew<int*>(nshape);
+	pptype=xNew<int*>(nshape);
+	pnvert=xNew<int>(nshape);
+	pshapx=xNew<double*>(nshape);
+	pshapy=xNew<double*>(nshape);
+	pshapz=xNew<double*>(nshape);
+	pshapm=xNew<double*>(nshape);
+
+	/* loop over the list of shapes  */
+	for(i=0;i<nEntities;i++ ){
+		SHPObject   *psShape;
+
+	psShape = SHPReadObject( hSHP, i );
+
+	printf( "\nShape:%d (%s)  nVertices=%d, nParts=%d\n"
+				"  Bounds:(%12.3f,%12.3f, %g, %g)\n"
+				"      to (%12.3f,%12.3f, %g, %g)\n",
+			i, SHPTypeName(psShape->nSHPType),
+				psShape->nVertices, psShape->nParts,
+				psShape->dfXMin, psShape->dfYMin,
+				psShape->dfZMin, psShape->dfMMin,
+				psShape->dfXMax, psShape->dfYMax,
+				psShape->dfZMax, psShape->dfMMax );
+
+	pstype[i]=psShape->nSHPType;
+	pnpart[i]=psShape->nParts;
+	if (pnpart[i]) {
+		ppstrt[i]=xNew<int>(pnpart[i]);
+		pptype[i]=xNew<int>(pnpart[i]);
+	}
+	else {
+		ppstrt[i]=NULL;
+		pptype[i]=NULL;
+	}
+	pnvert[i]=psShape->nVertices;
+	if (pnvert[i]) {
+		pshapx[i]=xNew<double>(pnvert[i]);
+		pshapy[i]=xNew<double>(pnvert[i]);
+		pshapz[i]=xNew<double>(pnvert[i]);
+		pshapm[i]=xNew<double>(pnvert[i]);
+	}
+	else {
+		pshapx[i]=NULL;
+		pshapy[i]=NULL;
+		pshapz[i]=NULL;
+		pshapm[i]=NULL;
+	}
+
+	for( j = 0, iPart = 1; j < psShape->nVertices; j++ )
+	{
+			const char  *pszPartType = "";
+
+			if( j == 0 && psShape->nParts > 0 )
+			{
+				pszPartType = SHPPartTypeName( psShape->panPartType[0] );
+				ppstrt[i][0]=psShape->panPartStart[0];
+				pptype[i][0]=psShape->panPartType[0];
+			}
+
+		if( iPart < psShape->nParts
+				&& psShape->panPartStart[iPart] == j )
+		{
+				pszPartType = SHPPartTypeName( psShape->panPartType[iPart] );
+				ppstrt[i][iPart]=psShape->panPartStart[iPart];
+				pptype[i][iPart]=psShape->panPartType[iPart];
+		iPart++;
+		pszPlus = "+";
+		}
+		else
+			pszPlus = " ";
+
+//		printf("   %s (%12.3f,%12.3f, %g, %g) %s \n",
+//				   pszPlus,
+//				   psShape->padfX[j],
+//				   psShape->padfY[j],
+//				   psShape->padfZ[j],
+//				   psShape->padfM[j],
+//				   pszPartType );
+
+		pshapx[i][j]=psShape->padfX[j];
+		pshapy[i][j]=psShape->padfY[j];
+		pshapz[i][j]=psShape->padfZ[j];
+		pshapm[i][j]=psShape->padfM[j];
+	}
+
+		if( bValidate )
+		{
+			int nAltered = SHPRewindObject( hSHP, psShape );
+
+			if( nAltered > 0 )
+			{
+				printf( "  %d rings wound in the wrong direction.\n",
+						nAltered );
+				nInvalidCount++;
+			}
+		}
+
+		SHPDestroyObject( psShape );
+	}
+
+/*  close shp/shx files  */
+
+	SHPClose( hSHP );
+
+/*  construct kml file  */
+
+	kfile =new KML_File();
+	kfile->AddAttrib("xmlns","http://www.opengis.net/kml/2.2");
+
+/*  construct kml document  */
+
+	kdoc  =new KML_Document();
+	sprintf(kdoc->name      ,"Shp2Kmlx Module -- %s",ctime(&time0));
+	kdoc->open      =1;
+
+/*  construct style templates for defaults  */
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"%02xffffff",(int)floor(popac*255+0.5));
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineRandomPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"ff000000");
+	sprintf(klsty->colormode ,"normal");
+	klsty->width     =lwidth;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"00ffffff");
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","BlackLineEmptyPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+	klsty =new KML_LineStyle();
+	sprintf(klsty->color     ,"%02xffffff",(int)floor(popac*255+0.5));
+	sprintf(klsty->colormode ,"random");
+	klsty->width     =lwidth*2;
+	kpsty =new KML_PolyStyle();
+	sprintf(kpsty->color     ,"00ffffff");
+	sprintf(kpsty->colormode ,"random");
+	kstyle=new KML_Style();
+	kstyle->AddAttrib("id","RandomLineEmptyPoly");
+	kstyle->line      =klsty;
+	kstyle->poly      =kpsty;
+	(kdoc->style     )->AddObject((Object*)kstyle);
+
+/*  construct kml folder for shapes  */
+
+	kfold =new KML_Folder();
+	sprintf(kfold->name      ,"Shapefile: %s  Type: %s  nShapes: %d",
+			filshp, SHPTypeName( nShapeType ), nEntities );
+	kfold->open      =1;
+
+/*  loop over the list of shapes  */
+
+	for (i=0; i<nshape; i++) {
+
+/*  null type  */
+
+		if      (pstype[i] == SHPT_NULL) {
+			;
+		}
+
+/*  point types  */
+
+		else if (pstype[i] == SHPT_POINT ||
+			  	 pstype[i] == SHPT_POINTZ ||
+			 	 pstype[i] == SHPT_POINTM) {
+			kplace=new KML_Placemark();
+
+			sprintf(kplace->name      ,"Shape:%d (%s)  nVertices=%d, nParts=%d",
+					i,SHPTypeName(pstype[i]),pnvert[i],pnpart[i]);
+			kplace->visibility=true;
+			sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+
+			if (pnpart[i] > 0)
+				_printf_("Warning -- Shape "<< i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
+			if (pnvert[i] > 1)
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 1 vertices.\n\n");
+
+			kpoint=new KML_Point();
+
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
+			if (sgn) {
+				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
+			}
+			else  {
+				memcpy(lon,pshapx[i],pnvert[i]*sizeof(double));
+				memcpy(lat,pshapy[i],pnvert[i]*sizeof(double));
+			}
+
+			kpoint->coords[0]=lon      [0];
+			kpoint->coords[1]=lat      [0];
+			kpoint->coords[2]=pshapz[i][0];
+
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kplace->geometry  )->AddObject((Object*)kpoint);
+			kpoint=NULL;
+			(kfold ->feature   )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+
+/*  polyline types  */
+
+		else if (pstype[i] == SHPT_ARC ||
+				 pstype[i] == SHPT_ARCZ ||
+				 pstype[i] == SHPT_ARCM) {
+			kplace=new KML_Placemark();
+
+			sprintf(kplace->name      ,"Shape:%d (%s)  nVertices=%d, nParts=%d",
+					i,SHPTypeName(pstype[i]),pnvert[i],pnpart[i]);
+			kplace->visibility=true;
+			sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+
+/*  create a multigeometry to hold all the lines  */
+
+			kmulti=new KML_MultiGeometry();
+
+/*  convert to lat/lon, if necessary  */
+
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
+			if (sgn) {
+				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
+			}
+			else  {
+				memcpy(lon,pshapx[i],pnvert[i]*sizeof(double));
+				memcpy(lat,pshapy[i],pnvert[i]*sizeof(double));
+			}
+
+/*  loop over the lines  */
+
+			for (j=0; j<pnpart[i]; j++) {
+				kline =new KML_LineString();
+
+				kline->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
+				kline->coords    =xNew<double>(kline->ncoord*3);
+				for (k=0; k<kline->ncoord; k++) {
+					kline->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+					kline->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+					kline->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
+				}
+				(kmulti->geometry  )->AddObject((Object*)kline);
+				kline = NULL;
+			}
+
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kplace->geometry)->AddObject((Object*)kmulti);
+			kmulti=NULL;
+			(kfold ->feature )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+
+/*  polygon types  */
+
+		else if (pstype[i] == SHPT_POLYGON ||
+				 pstype[i] == SHPT_POLYGONZ ||
+				 pstype[i] == SHPT_POLYGONM) {
+
+/*  the shp format specifies that outer rings are cw, while inner rings are ccw.  there
+	may be multiple outer rings and inner rings in any order.  the kml format specifies
+	all rings are ccw (right-hand rule).  there may be only one outer ring with multiple
+	inner rings, and rings are differentiated by keyword.
+
+	at least for now, assume that each cw ring forms a new kml polygon, and each ccw
+	ring forms an inner ring for the most recent outer ring.  a more elaborate solution
+	would be for each inner ring to search in which outer ring it occurs.  */
+
+			kplace=new KML_Placemark();
+
+			sprintf(kplace->name      ,"Shape:%d (%s)  nVertices=%d, nParts=%d",
+					i,SHPTypeName(pstype[i]),pnvert[i],pnpart[i]);
+			kplace->visibility=true;
+			sprintf(kplace->styleurl  ,"#BlackLineRandomPoly");
+
+/*  create a multigeometry to hold all the polygons  */
+
+			kmulti=new KML_MultiGeometry();
+
+/*  convert to lat/lon, if necessary  */
+
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
+			if (sgn) {
+				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
+			}
+			else  {
+				memcpy(lon,pshapx[i],pnvert[i]*sizeof(double));
+				memcpy(lat,pshapy[i],pnvert[i]*sizeof(double));
+			}
+
+/*  loop over the polygons  */
+
+			for (j=0; j<pnpart[i]; j++) {
+
+/*  check if polygon is ccw or cw by computing sum of cross products (twice the area)  */
+
+				ncoord=(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
+				cpsum =0.;
+
+				for (k=ppstrt[i][j]; k<ppstrt[i][j]+ncoord-1; k++)
+					cpsum +=pshapx[i][k]*pshapy[i][k+1         ]-pshapy[i][k]*pshapx[i][k+1         ];
+				cpsum +=pshapx[i][k]*pshapy[i][ppstrt[i][j]]-pshapy[i][k]*pshapx[i][ppstrt[i][j]];
+
+/*  outer ring (cw) (allow exception for single-part shapes)  */
+
+				if (cpsum < 0 || pnpart[i] == 1) {
+					if (kpoly) {
+						(kmulti->geometry  )->AddObject((Object*)kpoly);
+						kpoly =NULL;
+					}
+
+/*  create a new polygon from the outer ring (reversing cw to ccw)  */
+
+					kpoly =new KML_Polygon();
+					kring =new KML_LinearRing();
+
+					kring->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
+					kring->coords    =xNew<double>(kring->ncoord*3);
+					if (cpsum < 0)
+						for (k=0; k<kring->ncoord; k++) {
+							kring->coords[3*(kring->ncoord-1-k)+0]=lon      [ppstrt[i][j]+k];
+							kring->coords[3*(kring->ncoord-1-k)+1]=lat      [ppstrt[i][j]+k];
+							kring->coords[3*(kring->ncoord-1-k)+2]=pshapz[i][ppstrt[i][j]+k];
+						}
+					else
+						for (k=0; k<kring->ncoord; k++) {
+							kring->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+							kring->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+							kring->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
+						}
+
+					(kpoly ->outer     )->AddObject((Object*)kring);
+					kring =NULL;
+				}
+
+/*  inner ring (ccw)  */
+
+				else {
+					if (!kpoly) {
+						_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\", part " << j << ", expected to be outer loop (cw).\n\n");
+						continue;
+					}
+
+/*  add the inner ring to the current polygon  */
+
+					kring =new KML_LinearRing();
+
+					kring->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
+					kring->coords    =xNew<double>(kring->ncoord*3);
+					for (k=0; k<kring->ncoord; k++) {
+						kring->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+						kring->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+						kring->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
+					}
+
+					(kpoly ->inner     )->AddObject((Object*)kring);
+					kring =NULL;
+				}
+			}
+
+			if (kpoly) {
+				(kmulti->geometry  )->AddObject((Object*)kpoly);
+				kpoly =NULL;
+			}
+
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kplace->geometry  )->AddObject((Object*)kmulti);
+			kmulti=NULL;
+			(kfold ->feature   )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+
+/*  multipoint types  */
+
+		else if (pstype[i] == SHPT_MULTIPOINT ||
+				 pstype[i] == SHPT_MULTIPOINTZ ||
+				 pstype[i] == SHPT_MULTIPOINTM) {
+			kplace=new KML_Placemark();
+
+			sprintf(kplace->name      ,"Shape:%d (%s)  nVertices=%d, nParts=%d",
+					i,SHPTypeName(pstype[i]),pnvert[i],pnpart[i]);
+			kplace->visibility=true;
+			sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+
+			if (pnpart[i] > 0)
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
+
+/*  create a multigeometry to hold all the points  */
+
+			kmulti=new KML_MultiGeometry();
+
+/*  convert to lat/lon, if necessary  */
+
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
+			if (sgn) {
+				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
+			}
+			else  {
+				memcpy(lon,pshapx[i],pnvert[i]*sizeof(double));
+				memcpy(lat,pshapy[i],pnvert[i]*sizeof(double));
+			}
+
+/*  loop over the points  */
+
+			for (j=0; j<pnvert[i]; j++) {
+				kpoint=new KML_Point();
+
+				kpoint->coords[0]=lon      [j];
+				kpoint->coords[1]=lat      [j];
+				kpoint->coords[2]=pshapz[i][j];
+
+				(kmulti->geometry  )->AddObject((Object*)kpoint);
+				kpoint=NULL;
+			}
+
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kplace->geometry  )->AddObject((Object*)kmulti);
+			kmulti=NULL;
+			(kfold ->feature   )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+
+/*  multipatch types  */
+
+		else if (pstype[i] == SHPT_MULTIPATCH) {
+			_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
+			continue;
+		}
+
+/*  unknown type  */
+
+		else {
+			_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
+		}
+	}
+
+/*  assemble the rest of the kml hierarchy  */
+
+	(kdoc ->feature   )->AddObject((Object*)kfold);
+	kfold=NULL;
+	(kfile->kmlobj    )->AddObject((Object*)kdoc);
+	kdoc =NULL;
+
+/*  write kml file  */
+
+	_printf0_("Writing kml document to file.\n");
+	fid=fopen(filkml,"w");
+	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+	kfile->Write(fid,indent);
+	fclose(fid);
+
+	delete kfile;
+	for (i=nshape-1; i>=0; i--) {
+		xDelete<double>((pshapm[i]));
+		xDelete<double>((pshapz[i]));
+		xDelete<double>((pshapy[i]));
+		xDelete<double>((pshapx[i]));
+	}
+	xDelete<double*>(pshapm);
+	xDelete<double*>(pshapz);
+	xDelete<double*>(pshapy);
+	xDelete<double*>(pshapx);
+	xDelete<int>(pnvert);
+	for (i=nshape-1; i>=0; i--) {
+		xDelete<int>((pptype[i]));
+		xDelete<int>((ppstrt[i]));
+	}
+	xDelete<int*>(pptype);
+	xDelete<int*>(ppstrt);
+	xDelete<int>(pnpart);
+	xDelete<int>(pstype);
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_("Shp2Kmlx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
+
+	return(iret);
+
+	#else //ifdef _HAVE_SHAPELIB_
+	return 0;
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file:  Shp2Kmlx.h
+ * \brief header file for shp to kml conversion routines.
+ */ 
+
+#ifndef _SHP2KMLX_H
+#define _SHP2KMLX_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+
+#include "shapefil.h"
+
+#endif
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+int Shp2Kmlx(char* filshp,char* filkml, int sgn);
+int Shp2Kmlx(char* filshp,char* filkml, int sgn,double cm,double sp);
+
+#endif  /* _SHP2KMLX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file Solverx
+ * \brief solver
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Solverx.h"
+#include "../../shared/shared.h"
+
+void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters){
+
+	/*intermediary: */
+	Solver<IssmDouble> *solver=NULL;
+
+	/*output: */
+	Vector<IssmDouble> *uf=NULL;
+
+	if(VerboseModule()) _printf0_("   Solving matrix system\n");
+
+	/*Initialize solver: */
+	solver=new Solver<IssmDouble>(Kff,pf,uf0,df,parameters);
+
+	/*Solve:*/
+	uf=solver->Solve();
+
+	/*clean up and assign output pointers:*/
+	delete solver;
+	*puf=uf;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/Solverx/Solverx.h	(revision 18231)
@@ -0,0 +1,19 @@
+/*!\file:  Solverx.h
+ * \brief solver
+ */ 
+
+#ifndef _SOLVERX_H
+#define _SOLVERX_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../toolkits/toolkits.h"
+
+/* local prototypes: */
+void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters);
+
+#endif  /* _SOLVERX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 18231)
@@ -0,0 +1,24 @@
+/*!\file SpcNodesx
+ * \brief: establish single point constraints on all nodes, as well as constraints vector.
+ */
+
+#include "./SpcNodesx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SpcNodesx(Nodes* nodes,Constraints* constraints,Parameters* parameters, int analysis_type){
+
+	for(int i=0;i<constraints->Size();i++){
+
+		Constraint* constraint=(Constraint*)constraints->GetObjectByOffset(i);
+
+		/*Check this constraint belongs to this analysis: */
+		if(constraint->InAnalysis(analysis_type)){
+
+			/*Ok, apply constraint onto corresponding node: */
+			constraint->ConstrainNode(nodes,parameters);
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SpcNodesx.h
+ * \brief header file for node single point constraints
+ */ 
+
+#ifndef _SPCNODESX_H
+#define _SPCNODESX_H
+
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+/* local prototypes: */
+void SpcNodesx(Nodes* nodes, Constraints* constraints,Parameters* parameters,int analysis_type);
+
+#endif  /* _SPCNODESX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 18231)
@@ -0,0 +1,108 @@
+/*!\file SurfaceAbsVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceAbsVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=SurfaceAbsVelMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble SurfaceAbsVelMisfit(Element* element){
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble misfit,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=topelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vxobs_input  =topelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vy_input     = NULL;
+	Input* vyobs_input  = NULL;
+	if(numcomponents==2){
+		vy_input    =topelement->GetInput(VyEnum);              _assert_(vy_input);
+		vyobs_input =topelement->GetInput(InversionVyObsEnum);  _assert_(vyobs_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,SurfaceAbsVelMisfitEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
+
+		/*Compute SurfaceAbsVelMisfitEnum:
+		 *
+		 *      1  [           2              2 ]
+		 * J = --- | (u - u   )  +  (v - v   )  |
+		 *      2  [       obs            obs   ]
+		 *
+		 */
+		misfit=0.5*(vx-vxobs)*(vx-vxobs);
+		if(numcomponents==2) misfit+=0.5*(vy-vyobs)*(vy-vyobs);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceAbsVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACEABSVELMISFITX_H
+#define _SURFACEABSVELMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble SurfaceAbsVelMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 18231)
@@ -0,0 +1,36 @@
+/*!\file SurfaceAreax
+ * \brief: compute Surface area
+ */
+
+#include "./SurfaceAreax.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+
+void SurfaceAreax(IssmDouble* pS,FemModel* femmodel){
+
+	/*Intermediary*/
+	Element* element=NULL;
+
+	/*output: */
+	IssmDouble S = 0.;
+	IssmDouble S_sum;
+
+	/*Compute gradients: */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		S+=element->SurfaceArea();
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+ 	ISSM_MPI_Reduce (&S,&S_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&S_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
+	S=S_sum;
+
+	/*add surface area to element inputs:*/
+	InputUpdateFromConstantx(femmodel,S,SurfaceAreaEnum);
+
+	/*Assign output pointers: */
+	if(pS) *pS=S;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceAreax.h
+ * \brief header file for ...
+ */ 
+
+#ifndef _SURFACEAREAX_H
+#define _SURFACEAREAX_H
+
+#include "../../shared/shared.h"
+class FemModel;
+
+/* local prototypes: */
+void SurfaceAreax(IssmDouble* pS,FemModel* femmodel);
+
+#endif  /* _SURFACEAREAX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 18231)
@@ -0,0 +1,119 @@
+/*!\file SurfaceAverageVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceAverageVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../SurfaceAreax/SurfaceAreax.h"
+
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		J+=SurfaceAverageVelMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble SurfaceAverageVelMisfit(Element* element){
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble misfit,S,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:
+			numcomponents   = 1;
+			break;
+		case Domain3DEnum:
+			numcomponents   = 2;
+			break;
+		case Domain2DhorizontalEnum:
+			numcomponents   = 2;
+			break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	topelement->GetInputValue(&S,SurfaceAreaEnum);
+	Input* weights_input=topelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vxobs_input  =topelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vy_input     = NULL;
+	Input* vyobs_input  = NULL;
+	if(numcomponents==2){
+		vy_input    =topelement->GetInput(VyEnum);              _assert_(vy_input);
+		vyobs_input =topelement->GetInput(InversionVyObsEnum);  _assert_(vyobs_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,SurfaceAverageVelMisfitEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
+
+		/*Compute SurfaceAverageVelMisfitEnum:
+		 *
+		 *      1                    2              2
+		 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+		 *      S                obs            obs
+		 */
+		if(numcomponents==1){
+			misfit=1/S*(vx-vxobs)*(vx-vxobs);
+		}
+		else{
+			misfit=1/S*sqrt( pow(vx-vxobs,2) + pow(vy-vyobs,2));
+		}
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceAverageVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACEAVERAGEVELMISFITX_H
+#define _SURFACEAVERAGEVELMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel);
+IssmDouble SurfaceAverageVelMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 18231)
@@ -0,0 +1,118 @@
+/*!\file SurfaceLogVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceLogVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=SurfaceLogVelMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble SurfaceLogVelMisfit(Element* element){
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble velocity_mag,obs_velocity_mag;
+	IssmDouble misfit,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=topelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vxobs_input  =topelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vy_input     = NULL;
+	Input* vyobs_input  = NULL;
+	if(numcomponents==2){
+		vy_input    =topelement->GetInput(VyEnum);              _assert_(vy_input);
+		vyobs_input =topelement->GetInput(InversionVyObsEnum);  _assert_(vyobs_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,SurfaceLogVelMisfitEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
+
+		/*Compute SurfaceLogVelMisfit:
+		 *                 [        vel + eps     ] 2
+		 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+		 *                 [       vel   + eps    ]
+		 *                            obs
+		 */
+		if(numcomponents==1){
+			velocity_mag    =fabs(vx)+epsvel;
+			obs_velocity_mag=fabs(vxobs)+epsvel;
+		}
+		else{
+			velocity_mag    =sqrt(vx*vx+vy*vy)+epsvel;
+			obs_velocity_mag=sqrt(vxobs*vxobs+vyobs*vyobs)+epsvel;
+		}
+
+		misfit=4*pow(meanvel,2)*pow(log(velocity_mag/obs_velocity_mag),2);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceLogVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACELOGVELMISFITX_H
+#define _SURFACELOGVELMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble SurfaceLogVelMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 18231)
@@ -0,0 +1,117 @@
+/*!\file SurfaceLogVxVyMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceLogVxVyMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=SurfaceLogVxVyMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble SurfaceLogVxVyMisfit(Element* element){
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=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 = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=topelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vxobs_input  =topelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vy_input     = NULL;
+	Input* vyobs_input  = NULL;
+	if(numcomponents==2){
+		vy_input    =topelement->GetInput(VyEnum);              _assert_(vy_input);
+		vyobs_input =topelement->GetInput(InversionVyObsEnum);  _assert_(vyobs_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,SurfaceLogVxVyMisfitEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
+
+		/*Compute SurfaceRelVelMisfit:
+		 *
+		 *      1            [        |u| + eps     2          |v| + eps     2  ]
+		 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+		 *      2            [       |u    |+ eps              |v    |+ eps     ]
+		 *                              obs                       obs
+		 */
+
+		if(numcomponents==1){
+			misfit=0.5*meanvel*meanvel*pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2);
+		}
+		else{
+			misfit=0.5*meanvel*meanvel*(
+						pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2) +
+						pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2) );
+		}
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceLogVxVyMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACELOGVXVYMISFITX_H
+#define _SURFACELOGVXVYMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble SurfaceLogVxVyMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 18231)
@@ -0,0 +1,368 @@
+/*!\file SurfaceMassBalancex
+ * \brief: calculates SMB 
+ */
+
+#include "./SurfaceMassBalancex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SurfaceMassBalancex(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaties*/
+	int  smb_model;
+	bool isdelta18o;
+
+	/*First, get SMB model from parameters*/
+	femmodel->parameters->FindParam(&smb_model,SurfaceforcingsEnum);
+
+	/*branch to correct module*/
+	switch(smb_model){
+		case SMBEnum:
+			/*Nothing to be done*/
+			break;
+		case SMBpddEnum:
+			femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			if(isdelta18o){
+				if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
+				Delta18oParameterizationx(femmodel);
+			} 
+			if(VerboseSolution()) _printf0_("   call positive degree day module\n");
+			PositiveDegreeDayx(femmodel);
+			break;
+		case SMBgradientsEnum:
+			if(VerboseSolution())_printf_("	call smb gradients module\n");
+			SmbGradientsx(femmodel);
+			break;
+		case SMBhenningEnum:
+			if(VerboseSolution())_printf_("  call smb Henning module\n");
+			SmbHenningx(femmodel);
+			break;
+		case SMBcomponentsEnum:
+			if(VerboseSolution())_printf_("  call smb Components module\n");
+			SmbComponentsx(femmodel);
+			break;
+		case SMBmeltcomponentsEnum:
+			if(VerboseSolution())_printf_("  call smb Melt Components module\n");
+			SmbMeltComponentsx(femmodel);
+			break;
+		default:
+			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+
+}/*}}}*/
+
+void SmbGradientsx(FemModel* femmodel){/*{{{*/
+
+	// void SurfaceMassBalancex(hd,agd,ni){
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface elevation (m): hd(NA)
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	int v;
+	IssmDouble rho_water;                   // density of fresh water
+	IssmDouble rho_ice;                     // density of ice
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* Href        = xNew<IssmDouble>(numvertices); // reference elevation from which deviations are used to calculate the SMB adjustment
+		IssmDouble* Smbref      = xNew<IssmDouble>(numvertices); // reference SMB to which deviations are added
+		IssmDouble* b_pos       = xNew<IssmDouble>(numvertices); // Hs-SMB relation parameter
+		IssmDouble* b_neg       = xNew<IssmDouble>(numvertices); // Hs-SMB relation paremeter
+		IssmDouble* h           = xNew<IssmDouble>(numvertices); // ice thickness (m)
+		IssmDouble* s           = xNew<IssmDouble>(numvertices); // surface elevation (m)
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover SmbGradients*/
+		element->GetInputListOnVertices(Href,SurfaceforcingsHrefEnum);
+		element->GetInputListOnVertices(Smbref,SurfaceforcingsSmbrefEnum);
+		element->GetInputListOnVertices(b_pos,SurfaceforcingsBPosEnum);
+		element->GetInputListOnVertices(b_neg,SurfaceforcingsBNegEnum);
+
+		/*Recover surface elevatio at vertices: */
+		element->GetInputListOnVertices(h,ThicknessEnum);
+		element->GetInputListOnVertices(s,SurfaceEnum);
+
+		/*Get material parameters :*/
+		rho_ice=element->matpar->GetRhoIce();
+		rho_water=element->matpar->GetRhoFreshwater();
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			if(Smbref[v]>0){
+				smb[v]=Smbref[v]+b_pos[v]*(s[v]-Href[v]);
+			}
+			else{
+				smb[v]=Smbref[v]+b_neg[v]*(s[v]-Href[v]);
+			}
+			smb[v]=smb[v]/rho_ice;      // SMB in m/y ice
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(Href);
+		xDelete<IssmDouble>(Smbref);
+		xDelete<IssmDouble>(b_pos);
+		xDelete<IssmDouble>(b_neg);
+		xDelete<IssmDouble>(h);
+		xDelete<IssmDouble>(s);
+		xDelete<IssmDouble>(smb);
+	}
+
+}/*}}}*/
+void Delta18oParameterizationx(FemModel* femmodel){/*{{{*/
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->Delta18oParameterization();
+	}
+
+}/*}}}*/
+void PositiveDegreeDayx(FemModel* femmodel){/*{{{*/
+
+	// void PositiveDegreeDayx(hd,vTempsea,vPrec,agd,Tsurf,ni){
+	//    note "v" prefix means 12 monthly means, ie time dimension
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface elevation (m): hd(NA)
+	//    monthly mean surface sealevel temperature (degrees C): vTempsea(NA
+	//    ,NTIME) 
+	//    monthly mean precip rate (m/yr water equivalent): vPrec(NA,NTIME)
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	//    mean annual surface temperature (degrees C): Tsurf(NA)
+
+	int    i, it, jj, itm;
+	IssmDouble DT = 0.02, sigfac, snormfac;
+	IssmDouble signorm = 5.5;      // signorm : sigma of the temperature distribution for a normal day 
+	IssmDouble siglim;       // sigma limit for the integration which is equal to 2.5 sigmanorm
+	IssmDouble signormc = signorm - 0.5;     // sigma of the temperature distribution for cloudy day
+	IssmDouble siglimc, siglim0, siglim0c;
+	IssmDouble tstep, tsint, tint, tstepc;
+	int    NPDMAX = 1504, NPDCMAX = 1454;
+	//IssmDouble pdds[NPDMAX]={0}; 
+	//IssmDouble pds[NPDCMAX]={0};
+	IssmDouble pddt, pd ; // pd : snow/precip fraction, precipitation falling as snow
+	IssmDouble PDup, PDCUT = 2.0;    // PDcut: rain/snow cutoff temperature (C)
+	IssmDouble tstar; // monthly mean surface temp
+
+	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;
+	tsint    = tstep*0.5;
+	sigfac   = -1.0/(2.0*pow(signorm,2));
+	snormfac = 1.0/(signorm*sqrt(2.0*acos(-1.0)));
+	siglim   = 2.5*signorm;
+	siglimc  = 2.5*signormc;
+	siglim0  = siglim/DT + 0.5;
+	siglim0c = siglimc/DT + 0.5;
+	PDup     = siglimc+PDCUT;
+
+	itm = reCast<int,IssmDouble>((2*siglim/DT + 1.5));
+
+	if(itm >= NPDMAX) _error_("increase NPDMAX in massBalance.cpp");
+	for(it = 0; it < itm; it++){  
+		//    tstar = REAL(it)*DT-siglim;
+		tstar = it*DT-siglim;
+		tint = tsint;
+		pddt = 0.;
+		for ( jj = 0; jj < 600; jj++){
+			if (tint > (tstar+siglim)){break;}
+			pddt = pddt + tint*exp(sigfac*(pow((tint-tstar),2)))*tstep;
+			tint = tint+tstep;
+		}
+		pdds[it] = pddt*snormfac;
+	}
+	pdds[itm+1] = siglim + DT;
+
+	//*********compute PD(T) : snow/precip fraction. precipitation falling as snow
+	tstepc   = 0.1;
+	tsint    = PDCUT-tstepc*0.5;
+	signormc = signorm - 0.5;
+	sigfac   = -1.0/(2.0*pow(signormc,2));
+	snormfac = 1.0/(signormc*sqrt(2.0*acos(-1.0)));
+	siglimc  = 2.5*signormc ;
+	itm = reCast<int,IssmDouble>((PDCUT+2.*siglimc)/DT + 1.5);
+	if(itm >= NPDCMAX) _error_("increase NPDCMAX in p35com");
+	for(it = 0; it < itm; it++ ){
+		tstar = it*DT-siglimc;
+		//    tstar = REAL(it)*DT-siglimc;
+		tint = tsint;          // start against upper bound
+		pd = 0.;
+		for (jj = 0; jj < 600; jj++){
+			if (tint<(tstar-siglimc)) {break;}
+			pd = pd + exp(sigfac*(pow((tint-tstar),2)))*tstepc;
+			tint = tint-tstepc;
+		}
+		pds[it] = pd*snormfac;  // gaussian integral lookup table for snow fraction
+	}
+	pds[itm+1] = 0.;
+	//     *******END initialize PDD
+
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->PositiveDegreeDay(pdds,pds,signorm);
+	}
+
+	/*free ressouces: */
+	xDelete<IssmDouble>(pdds);
+	xDelete<IssmDouble>(pds);
+}/*}}}*/
+void SmbHenningx(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble  z_critical = 1675.;
+	IssmDouble  dz = 0;
+	IssmDouble  a = -15.86;
+	IssmDouble  b = 0.00969;
+	IssmDouble  c = -0.235;
+	IssmDouble  f = 1.;
+	IssmDouble  g = -0.0011;
+	IssmDouble  h = -1.54e-5;
+	IssmDouble  smb,smbref,anomaly,yts,z;
+    
+    /* Get constants */
+    femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+    /*iomodel->Constant(&yts,ConstantsYtsEnum);*/
+    /*this->parameters->FindParam(&yts,ConstantsYtsEnum);*/
+    /*Mathieu original*/
+    /*IssmDouble  smb,smbref,z;*/
+    
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Get reference SMB (uncorrected) and allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* surfacelist = xNew<IssmDouble>(numvertices);
+		IssmDouble* smblistref  = xNew<IssmDouble>(numvertices);
+		IssmDouble* smblist     = xNew<IssmDouble>(numvertices);
+		element->GetInputListOnVertices(surfacelist,SurfaceEnum);
+		element->GetInputListOnVertices(smblistref,SurfaceforcingsSmbrefEnum);
+
+		/*Loop over all vertices of element and correct SMB as a function of altitude z*/
+		for(int v=0;v<numvertices;v++){
+
+			/*Get vertex elevation, anoma smb*/
+			z      = surfacelist[v];
+			anomaly = smblistref[v];
+
+            /* Henning edited acc. to Riannes equations*/
+            /* Set SMB maximum elevation, if dz = 0 -> z_critical = 1675 */
+            z_critical = z_critical + dz;
+            
+            /* Calculate smb acc. to the surface elevation z */
+            if(z<z_critical){
+				smb = a + b*z + c;
+			}
+			else{
+			  smb = (a + b*z)*(f + g*(z-z_critical) + h*(z-z_critical)*(z-z_critical)) + c;
+			}
+            
+            /* Compute smb including anomaly,
+             correct for number of seconds in a year [s/yr]*/
+            smb = smb + anomaly*yts;
+            
+			/*Update array accordingly*/
+			smblist[v] = smb;
+
+		}
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smblist,P1Enum);
+		xDelete<IssmDouble>(surfacelist);
+		xDelete<IssmDouble>(smblistref);
+		xDelete<IssmDouble>(smblist);
+	}
+
+}/*}}}*/
+void SmbComponentsx(FemModel* femmodel){/*{{{*/
+
+	// void SmbComponentsx(acc,evap,runoff,ni){
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface accumulation (m/yr water equivalent): acc
+	//    surface evaporation (m/yr water equivalent): evap
+	//    surface runoff (m/yr water equivalent): runoff
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	int v;
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* acc         = xNew<IssmDouble>(numvertices); 
+		IssmDouble* evap        = xNew<IssmDouble>(numvertices);
+		IssmDouble* runoff      = xNew<IssmDouble>(numvertices); 
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover Smb Components*/
+		element->GetInputListOnVertices(acc,SurfaceforcingsAccumulationEnum);
+		element->GetInputListOnVertices(evap,SurfaceforcingsEvaporationEnum);
+		element->GetInputListOnVertices(runoff,SurfaceforcingsRunoffEnum);
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			smb[v]=acc[v]-evap[v]-runoff[v];
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(acc);
+		xDelete<IssmDouble>(evap);
+		xDelete<IssmDouble>(runoff);
+		xDelete<IssmDouble>(smb);
+	}
+
+}/*}}}*/
+void SmbMeltComponentsx(FemModel* femmodel){/*{{{*/
+
+	// void SmbMeltComponentsx(acc,evap,melt,refreeze,ni){
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface accumulation (m/yr water equivalent): acc
+	//    surface evaporation (m/yr water equivalent): evap
+	//    surface melt (m/yr water equivalent): melt
+	//    refreeze of surface melt (m/yr water equivalent): refreeze
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	int v;
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* acc         = xNew<IssmDouble>(numvertices);
+		IssmDouble* evap        = xNew<IssmDouble>(numvertices); 
+		IssmDouble* melt        = xNew<IssmDouble>(numvertices);
+		IssmDouble* refreeze    = xNew<IssmDouble>(numvertices);
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover Smb Components*/
+		element->GetInputListOnVertices(acc,SurfaceforcingsAccumulationEnum);
+		element->GetInputListOnVertices(evap,SurfaceforcingsEvaporationEnum);
+		element->GetInputListOnVertices(melt,SurfaceforcingsMeltEnum);
+		element->GetInputListOnVertices(refreeze,SurfaceforcingsRefreezeEnum);
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			smb[v]=acc[v]-evap[v]-melt[v]+refreeze[v];
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(acc);
+		xDelete<IssmDouble>(evap);
+		xDelete<IssmDouble>(melt);
+		xDelete<IssmDouble>(refreeze);
+		xDelete<IssmDouble>(smb);
+	}
+
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 18231)
@@ -0,0 +1,19 @@
+/*!\file:  SurfaceMassBalancex.h
+ * \brief header file for SMB
+ */ 
+
+#ifndef _SurfaceMassBalancex_H
+#define _SurfaceMassBalancex_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceMassBalancex(FemModel* femmodel);
+void SmbGradientsx(FemModel* femmodel);
+void Delta18oParameterizationx(FemModel* femmodel);
+void PositiveDegreeDayx(FemModel* femmodel);
+void SmbHenningx(FemModel* femmodel);
+void SmbComponentsx(FemModel* femmodel);
+void SmbMeltComponentsx(FemModel* femmodel);
+
+#endif  /* _SurfaceMassBalancex_H*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 18231)
@@ -0,0 +1,118 @@
+/*!\file SurfaceRelVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceRelVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=SurfaceRelVelMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble SurfaceRelVelMisfit(Element* element){
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble misfit,Jdet,scalex,scaley;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=topelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vxobs_input  =topelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vy_input     = NULL;
+	Input* vyobs_input  = NULL;
+	if(numcomponents==2){
+		vy_input    =topelement->GetInput(VyEnum);              _assert_(vy_input);
+		vyobs_input =topelement->GetInput(InversionVyObsEnum);  _assert_(vyobs_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,SurfaceRelVelMisfitEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
+
+		/*Compute SurfaceRelVelMisfit:
+		 *                        
+		 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+		 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+		 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+		 *              obs                        obs                      
+		 */
+
+		if(numcomponents==2){
+			scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+			scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+			misfit=0.5*(scalex*pow((vx-vxobs),2)+scaley*pow((vy-vyobs),2));
+		}
+		else{
+			scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+			misfit=0.5*(scalex*pow((vx-vxobs),2));
+		}
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceRelVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACERELVELMISFITX_H
+#define _SURFACERELVELMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble SurfaceRelVelMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 18231)
@@ -0,0 +1,134 @@
+/*!\file SystemMatricesx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./SystemMatricesx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../AllocateSystemMatricesx/AllocateSystemMatricesx.h"
+
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax,FemModel* femmodel){
+
+	/*intermediary: */
+	int      i,M,N;
+	int      configuration_type,analysisenum;
+	Element *element = NULL;
+	Load    *load    = NULL;
+
+	/*output: */
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+	IssmDouble          kmax = 0;
+
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Generating matrices");
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+
+	/*First, we might need to do a dry run to get kmax if penalties are employed*/
+	if(femmodel->loads->IsPenalty(configuration_type)){
+
+		/*Allocate Kff_temp*/
+		Matrix<IssmDouble> *Kff_temp = NULL;
+		AllocateSystemMatricesx(&Kff_temp,NULL,NULL,NULL,femmodel);
+
+		/*Get complete stiffness matrix without penalties*/
+		for (i=0;i<femmodel->elements->Size();i++){
+			element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			ElementMatrix* Ke = analysis->CreateKMatrix(element);
+			ElementVector* pe = analysis->CreatePVector(element);
+			element->ReduceMatrices(Ke,pe);
+			if(Ke) Ke->AddToGlobal(Kff_temp,NULL);
+			delete Ke;
+			delete pe;
+		}
+
+		for (i=0;i<femmodel->loads->Size();i++){
+			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
+		}
+		Kff_temp->Assemble();
+
+		/*Now, figure out maximum value of stiffness matrix, so that we can penalize it correctly: */
+		kmax=Kff_temp->Norm(NORM_INF);
+		delete Kff_temp;
+	}
+
+	/*Allocate stiffness matrices and load vector*/
+	AllocateSystemMatricesx(&Kff,&Kfs,&df,&pf,femmodel);
+
+	/*Display size*/
+	if(VerboseModule()){
+		Kff->GetSize(&M,&N);
+		_printf0_(" (Kff stiffness matrix size: "<<M<<" x "<<N<<")\n");
+	}
+
+	/*Fill stiffness matrix and load vector from elements*/
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ElementMatrix* Ke = analysis->CreateKMatrix(element);
+		ElementVector* pe = analysis->CreatePVector(element);
+		element->ReduceMatrices(Ke,pe);
+		if(Ke) Ke->AddToGlobal(Kff,Kfs);
+		if(pe){
+			pe->AddToGlobal(pf);
+		}
+		delete Ke;
+		delete pe;
+	}
+
+	/*Fill stiffness matrix and load vector from loads*/
+	for(i=0;i<femmodel->loads->Size();i++){
+		load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		if(load->InAnalysis(configuration_type)){
+			load->CreateKMatrix(Kff,Kfs);
+			load->CreatePVector(pf);
+		}
+	}
+
+	/*Now deal with penalties (only in loads)*/
+	if(femmodel->loads->IsPenalty(configuration_type)){
+		for (i=0;i<femmodel->loads->Size();i++){
+			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)){
+				load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
+				load->PenaltyCreatePVector(pf,kmax);
+			}
+		}
+	}
+
+	/*Create dof vector for stiffness matrix preconditioning*/
+	if(pdf){
+		for(i=0;i<femmodel->elements->Size();i++){
+			element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			ElementVector* de=analysis->CreateDVector(element);
+			if(de) de->InsertIntoGlobal(df);
+			delete de;
+		}
+	}
+
+	/*Assemble matrices and vector*/
+	Kff->Assemble();
+	Kfs->Assemble();
+	pf->Assemble();
+	df->Assemble();
+	//Kff->AllocationInfo();
+	//Kfs->AllocationInfo();
+
+	/*cleanu up and assign output pointers: */
+	delete analysis;
+	if(pKff) *pKff=Kff;
+	else      delete Kff;
+	if(pKfs) *pKfs=Kfs;
+	else      delete Kfs;
+	if(ppf)  *ppf=pf;
+	else      delete pf;
+	if(pdf)  *pdf=df;
+	else      delete df;
+	if(pkmax) *pkmax=kmax;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  SystemMatricesx.h
+*/ 
+
+#ifndef _SYSTEMMATRICESX_H
+#define _SYSTEMMATRICESX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax,FemModel* femmodel);
+
+#endif  /* _SYSTEMMATRICESX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 18231)
@@ -0,0 +1,71 @@
+/*!\file ThicknessAbsMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAbsMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=ThicknessAbsMisfit(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble ThicknessAbsMisfit(Element* element){
+
+	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/* Get node coordinates*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input     =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input   =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* thicknessobs_input=element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,ThicknessAbsMisfitEnum);
+		thickness_input->GetInputValue(&thickness,gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs,gauss);
+
+		/*Compute ThicknessAbsMisfitEnum*/
+		Jelem+=0.5*(thickness-thicknessobs)*(thickness-thicknessobs)*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAbsMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSABSMISFITX_H
+#define _THICKNESSABSMISFITX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble ThicknessAbsMisfit(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file ThicknessAcrossGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAcrossGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=ThicknessAcrossGradient(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble ThicknessAcrossGradient(Element* element){
+
+	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  dp[3];
+	IssmDouble  vx,vy,vel;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/* Get node coordinates*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input   =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input        =element->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input        =element->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,ThicknessAcrossGradientEnum);
+		thickness_input->GetInputValue(&thickness,gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( -vy*dH/dx + vx*dH/dy )^2 */
+		Jelem+=weight*1/2*(-vy*dp[0] + vx*dp[1])*(-vy*dp[0] + vx*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAcrossGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSACROSSGRADIENT_H
+#define _THICKNESSACROSSGRADIENT_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble ThicknessAcrossGradient(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*!\file ThicknessAlongGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAlongGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=ThicknessAlongGradient(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble ThicknessAlongGradient(Element* element){
+
+	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  dp[3];
+	IssmDouble  vx,vy,vel;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/* Get node coordinates*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input   =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input        =element->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input        =element->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,ThicknessAlongGradientEnum);
+		thickness_input->GetInputValue(&thickness,gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( vx*dH/dx + vy*dH/dy )^2 */
+		Jelem+=weight*1/2*(vx*dp[0] + vy*dp[1])*(vx*dp[0] + vy*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 18231)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAlongGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSALONGGRADIENT_H
+#define _THICKNESSALONGGRADIENT_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble ThicknessAlongGradient(Element* element);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 18231)
@@ -0,0 +1,78 @@
+/*!\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 "../../toolkits/toolkits.h"
+
+void TriMeshProcessRiftsx(int** pindex, int* pnel,double** px,double** py,int* pnods,int** psegments,int** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct){
+
+	/*Output*/
+	int      numrifts,numrifts0;
+	int     *riftsnumsegments     = NULL;
+	int    **riftssegments        = NULL;
+	int     *riftsnumpairs        = NULL;
+	int    **riftspairs           = NULL;
+	int     *riftstips            = NULL;
+	double **riftspenaltypairs    = NULL;
+	int     *riftsnumpenaltypairs = NULL;
+
+	/*Recover initial mesh*/
+	int     nel            = *pnel;
+	int    *index          = *pindex;
+	double *x              = *px;
+	double *y              = *py;
+	int     nods           = *pnods;
+	int    *segments       = *psegments;
+	int    *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/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  TriMeshProcessRiftsx.h
+ * \brief header file for TriMeshProcessRifts module
+ */ 
+
+#ifndef _TRIMESHPROCESSRIFTX_H
+#define _TRIMESHPROCESSRIFTX_H
+
+class RiftStruct;
+
+void TriMeshProcessRiftsx(int** pindex,int* pnel,double** px,double** py,int* pnods,int** psegments,int** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct);
+
+#endif  /* _TRIMESHPROCESSRIFTX_H*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 18231)
@@ -0,0 +1,203 @@
+/*!\file TriMeshx
+ * \brief: x code for TriMesh mesher
+ */
+
+/*Header files: {{{*/
+#include "./TriMeshx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+/*ANSI_DECLARATORS needed to call triangle library: */
+#if defined(_HAVE_TRIANGLE_)
+	#ifndef ANSI_DECLARATORS
+	#define ANSI_DECLARATORS
+	#include "triangle.h"
+	#undef ANSI_DECLARATORS
+	#else
+	#include "triangle.h"
+	#endif
+#endif
+/*}}}*/
+
+void TriMeshx(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnsegs,Contours* domain,Contours* rifts,double area){
+
+#if !defined(_HAVE_TRIANGLE_)
+	_error_("triangle has not been installed");
+#else
+	/*indexing: */
+	int i,j;
+
+	/*output: */
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
+
+	/*intermediary: */
+	int counter,counter2,backcounter;
+	Contour<IssmPDouble> *contour = NULL;
+
+	/* Triangle structures needed to call Triangle library routines: */
+	struct triangulateio in,out;
+	char   options[256];
+
+	/*Create initial triangulation to call triangulate(). First number of points:*/
+	in.numberofpoints=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		in.numberofpoints+=contour->nods-1;
+	}
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		in.numberofpoints+=contour->nods;
+	}
+
+	/*number of point attributes: */
+	in.numberofpointattributes=1;
+
+	/*fill in the point list: */
+	in.pointlist = xNew<REAL>(in.numberofpoints*2);
+
+	counter=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		for (j=0;j<contour->nods-1;j++){
+			in.pointlist[2*counter+0]=contour->x[j];
+			in.pointlist[2*counter+1]=contour->y[j];
+			counter++;
+		}
+	}
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		for (j=0;j<contour->nods;j++){
+			in.pointlist[2*counter+0]=contour->x[j];
+			in.pointlist[2*counter+1]=contour->y[j];
+			counter++;
+		}
+	}
+
+	/*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);
+	for(i=0;i<in.numberofpoints;i++) in.pointmarkerlist[i] = 0;
+
+	/*Build segments. First figure out number of segments: holes and closed outlines have as many segments as vertices: */
+	in.numberofsegments=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		in.numberofsegments+=contour->nods-1;
+	}
+	for(i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		/*for rifts, we have one less segment as we have vertices*/
+		in.numberofsegments+=contour->nods-1;
+	}
+
+	in.segmentlist = xNew<int>(in.numberofsegments*2);
+	in.segmentmarkerlist = xNewZeroInit<int>(in.numberofsegments);
+	counter=0;
+	backcounter=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		for (j=0;j<contour->nods-2;j++){
+			in.segmentlist[2*counter+0]=counter;
+			in.segmentlist[2*counter+1]=counter+1;
+			in.segmentmarkerlist[counter]=0;
+			counter++;
+		}
+		/*Close this profile: */
+		 in.segmentlist[2*counter+0]=counter;
+		 in.segmentlist[2*counter+1]=backcounter;
+		 in.segmentmarkerlist[counter]=0;
+		 counter++;
+		 backcounter=counter;
+	}
+	counter2=counter;
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		for (j=0;j<(contour->nods-1);j++){
+			in.segmentlist[2*counter2+0]=counter;
+			in.segmentlist[2*counter2+1]=counter+1;
+			in.segmentmarkerlist[counter2]=2+i;
+			counter2++;
+			counter++;
+		}
+		counter++;
+	}
+
+	/*Build regions: */
+	in.numberofregions = 0;
+
+	/*Build holes: */
+	in.numberofholes = domain->Size()-1; /*everything is a hole, but for the first profile.*/
+	if(in.numberofholes){
+		in.holelist = xNew<REAL>(in.numberofholes*2);
+		for (i=0;i<domain->Size()-1;i++){
+			contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i+1);
+			GridInsideHole(&in.holelist[2*i+0],&in.holelist[2*i+1],contour->nods-1,contour->x,contour->y);
+		}
+	}
+
+	/* Make necessary initializations so that Triangle can return a triangulation in `out': */
+	out.pointlist             = (REAL*)NULL;
+	out.pointattributelist    = (REAL*)NULL;
+	out.pointmarkerlist       = (int *)NULL;
+	out.trianglelist          = (int *)NULL;
+	out.triangleattributelist = (REAL*)NULL;
+	out.neighborlist          = (int *)NULL;
+	out.segmentlist           = (int *)NULL;
+	out.segmentmarkerlist     = (int *)NULL;
+	out.edgelist              = (int *)NULL;
+	out.edgemarkerlist        = (int *)NULL;
+
+	/* Triangulate the points:.  Switches are chosen to read and write a  */
+	/*   PSLG (p), preserve the convex hull (c), number everything from  */
+	/*   zero (z), assign a regional attribute to each element (A), and  */
+	/*   produce an edge list (e), a Voronoi diagram (v), and a triangle */
+	/*   neighbor list (n).                                              */
+	sprintf(options,"%s%lf","pQzDq30ia",area); /*replace V by Q to quiet down the logging*/
+	triangulate(options, &in, &out, NULL);
+	/*report(&out, 0, 1, 1, 1, 1, 0);*/
+
+	/*Allocate index, x and y: */
+	index=xNew<int>(3*out.numberoftriangles);
+	x=xNew<double>(out.numberofpoints);
+	y=xNew<double>(out.numberofpoints);
+	segments=xNew<int>(3*out.numberofsegments);
+	segmentmarkerlist=xNew<int>(out.numberofsegments);
+
+	for (i = 0; i< out.numberoftriangles; i++) {
+		for (j = 0; j < out.numberofcorners; j++) {
+			index[3*i+j]=(int)out.trianglelist[i*out.numberofcorners+j]+1;
+		}
+	}
+	for (i = 0; i< out.numberofpoints; i++){
+		x[i]=(double)out.pointlist[i*2+0];
+		y[i]=(double)out.pointlist[i*2+1];
+	}
+	for (i = 0; i<out.numberofsegments;i++){
+		segments[3*i+0]=(int)out.segmentlist[i*2+0]+1;
+		segments[3*i+1]=(int)out.segmentlist[i*2+1]+1;
+		segmentmarkerlist[i]=(int)out.segmentmarkerlist[i];
+	}
+
+	/*Associate elements with segments: */
+	AssociateSegmentToElement(&segments,out.numberofsegments,index,out.numberoftriangles);
+
+	/*Order segments so that their normals point outside the domain: */
+	OrderSegments(&segments,out.numberofsegments, index,out.numberoftriangles);
+
+	/*Output : */
+	*pindex=index;
+	*px=x;
+	*py=y;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnels=out.numberoftriangles;
+	*pnods=out.numberofpoints;
+	*pnsegs=out.numberofsegments;
+#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriMeshx/TriMeshx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  TriMeshx.h
+ * \brief header file for TriMeshx module
+ */ 
+
+#ifndef _TRIMESHX_H_
+#define _TRIMESHX_H_
+
+#include <string.h>
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void TriMeshx(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnseg,Contours* domain,Contours* rifts,double area);
+#endif  /* _TRIMESHX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 18231)
@@ -0,0 +1,49 @@
+/*!\file TriaSearchx
+ */
+
+#include "./TriaSearchx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../../bamg/bamgobjects.h"
+
+using namespace bamg;
+using namespace std;
+
+void TriaSearchx(double** ptria,int* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes){
+
+	/*Output*/
+	double* tria=NULL;
+
+	/*allocate: */
+	tria=xNew<double>(numberofnodes);
+
+	/*Intermediary*/
+	R2     r;
+	I2     I;
+	int    i;
+	Icoor2 dete[3];
+
+	/* read background mesh */
+	Mesh Th(index,x,y,nods,nel); 
+	Th.CreateSingleVertexToTriangleConnectivity();
+
+	for(i=0;i<numberofnodes;i++){
+
+		//Get current point coordinates
+		r.x=x0[i]; r.y=y0[i];
+
+		I=Th.R2ToI2(r);
+
+		//Find triangle holding r/I
+		Triangle &tb=*Th.TriangleFindFromCoord(I,dete);
+
+		// internal point 
+		if (Th.GetId(tb)<nel)tria[i]=(double)Th.GetId(tb);
+		//external point
+		else tria[i]=NAN;
+	}
+
+	/*Assign output pointers:*/
+	*ptria=tria;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  TriaSearchx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _TRIASEARCHX_H
+#define _TRIASEARCHX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void TriaSearchx(double** ptria,int* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*!\file UpdateDynamicConstraintsx
+ * \brief module to update single point constraints  out of new spc vector, for next time step.
+ */
+
+#include "./UpdateDynamicConstraintsx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg){
+
+	int configuration_type;
+	IssmDouble* yg_serial=NULL;
+
+	/*Get current configuration*/
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*serialize yg, so nodes can index into it: */
+	yg_serial=yg->ToMPISerial();
+
+	for(int i=0;i<constraints->Size();i++){
+
+		Constraint* constraint=(Constraint*)constraints->GetObjectByOffset(i);
+
+		/*Check this constraint belongs to this analysis: */
+		if(constraint->InAnalysis(configuration_type) && constraint->ObjectEnum()==SpcDynamicEnum){
+
+			((SpcDynamic*)constraint)->SetDynamicConstraint(nodes,yg_serial);
+
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(yg_serial);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  UpdateDynamicConstraintsx.h
+ * \brief header file for updating single point constraints  for next time step
+ */ 
+
+#ifndef _UPDATEDYNAMICCONSTRAINTSXX_H
+#define _UPDATEDYNAMICCONSTRAINTSXX_H
+
+#include "../../classes/classes.h"
+
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg);
+
+#endif  /* _UPDATESPCSX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.cpp	(revision 18231)
@@ -0,0 +1,43 @@
+/*!\file VecMergex
+ * \brief: merge one vector into another
+ */
+
+#include "./VecMergex.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+void VecMergex(Vector<IssmDouble>* ug, Vector<IssmDouble>* uf, Nodes* nodes, Parameters* parameters, int SetEnum){
+
+	/*variables: */
+	int i;
+	int configuration_type;
+	IssmDouble* uf_serial=NULL;
+
+	/*retrieve parameters: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*serialize uf: */
+	uf_serial=uf->ToMPISerial();
+
+	/*Do we have any nodes for this configuration? :*/
+	if(nodes->NumberOfNodes(configuration_type)){ 
+
+		/*yes. Go through all nodes, and ask them to retrieve values from uf, and plug them into ug: */
+		for(i=0;i<nodes->Size();i++){
+
+			Node* node=(Node*)nodes->GetObjectByOffset(i);
+
+			/*Check that this node corresponds to our configuration currently being carried out: */
+			if (node->InAnalysis(configuration_type)){
+
+				/*For this object, merge values for enum set SetEnum: */
+				node->VecMerge(ug,uf_serial,SetEnum);
+			}
+		}
+	}
+	/*Free ressources:*/
+	xDelete<IssmDouble>(uf_serial);
+
+	/*Assemble vector: */
+	ug->Assemble();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VecMergex/VecMergex.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  VecMergex.h
+ * \brief header file for merging one vector into another
+ */ 
+
+#ifndef _VECMERGEX_H
+#define _VECMERGEX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void VecMergex(Vector<IssmDouble>* ug, Vector<IssmDouble>* uf, Nodes* nodes, Parameters* parameters, int SetEnum);
+
+#endif  /* _VECMERGEX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 18231)
@@ -0,0 +1,61 @@
+/*!\file VertexCoordinatesx
+ * \brief: compute a vector x,y and z of vertex coordinates by 
+ * marching through all our vertices. 
+ */
+
+#include "./VertexCoordinatesx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void VertexCoordinatesx( IssmDouble** px, IssmDouble** py, IssmDouble** pz, Vertices* vertices) {
+
+	/*output: */
+	IssmDouble* x=NULL;
+	IssmDouble* y=NULL;
+	IssmDouble* z=NULL;
+
+	Vector<IssmDouble>* vx=NULL;
+	Vector<IssmDouble>* vy=NULL;
+	Vector<IssmDouble>* vz=NULL;
+
+	/*intermediary: */
+	int  numberofvertices;
+	int  i;
+
+	/*figure out how many vertices we have: */
+	numberofvertices=vertices->NumberOfVertices();
+
+	vx=new Vector<IssmDouble>(numberofvertices);
+	vy=new Vector<IssmDouble>(numberofvertices);
+	vz=new Vector<IssmDouble>(numberofvertices);
+
+	/*march through our vertices: */
+	for(i=0;i<vertices->Size();i++){
+		Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		vertex->VertexCoordinates(vx,vy,vz);
+	}
+
+	/*Assemble*/
+	vx->Assemble();
+	vy->Assemble();
+	vz->Assemble();
+
+	/*serialize: */
+	x=vx->ToMPISerial();
+	y=vy->ToMPISerial();
+	z=vz->ToMPISerial();
+
+	/*Free ressources: */
+	delete vx;
+	delete vy;
+	delete vz;
+
+	/*output: */
+	if (px)*px=x;
+	else xDelete<IssmDouble>(x);
+	if (py)*py=y;
+	else xDelete<IssmDouble>(y);
+	if (pz)*pz=z;
+	else xDelete<IssmDouble>(z);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*!\file:  VertexCoordinatesx.h
+ */ 
+
+#ifndef _VERTEX_COORDINATESX_H
+#define _VERTEX_COORDINATESX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void VertexCoordinatesx( IssmDouble** px, IssmDouble** py, IssmDouble** pz, Vertices* vertices);
+
+#endif  /* _VERTEX_COORDINATESX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 18231)
@@ -0,0 +1,25 @@
+/*!\file VerticesDofx
+ * \brief: establish degrees of freedom for all vertices: */
+
+#include "./VerticesDofx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void VerticesDofx( Vertices* vertices, Parameters* parameters) {
+
+	/*intermediary: */
+	int  numberofvertices;
+
+	/*figure out how many vertices we have: */
+	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: */
+	vertices->FlagClones(numberofvertices);
+
+	/*Go through all vertices and distribute pids*/
+	vertices->DistributePids(numberofvertices); 
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 18231)
@@ -0,0 +1,13 @@
+/*!\file:  VerticesDofx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _VERTICESDOFX_H
+#define _VERTICESDOFX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void VerticesDofx( Vertices* vertices, Parameters* parameters);
+
+#endif  /* _VERTICESDOFX_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/modules.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/modules.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/modules/modules.h	(revision 18231)
@@ -0,0 +1,95 @@
+/*! \file modules.h: 
+ *  \brief header file for all the ISSM modules
+ */
+
+#ifndef _ISSM_MODULES_H_
+#define _ISSM_MODULES_H_
+
+/*Modules: */
+#include "./AllocateSystemMatricesx/AllocateSystemMatricesx.h"
+#include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
+#include "./Bamgx/Bamgx.h"
+#include "./BamgConvertMeshx/BamgConvertMeshx.h"
+#include "./BamgTriangulatex/BamgTriangulatex.h"
+#include "./Chacox/Chacox.h"
+#include "./ConfigureObjectsx/ConfigureObjectsx.h"
+#include "./ContourToMeshx/ContourToMeshx.h"
+#include "./ContourToNodesx/ContourToNodesx.h"
+#include "./ControlInputSetGradientx/ControlInputSetGradientx.h"
+#include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
+#include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
+#include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+#include "./ElementConnectivityx/ElementConnectivityx.h"
+#include "./GetSolutionFromInputsx/GetSolutionFromInputsx.h"
+#include "./GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "./GetVectorFromControlInputsx/GetVectorFromControlInputsx.h"
+#include "./GiaDeflectionCorex/GiaDeflectionCorex.h"
+#include "./SetControlInputsFromVectorx/SetControlInputsFromVectorx.h"
+#include "./SetActiveNodesLSMx/SetActiveNodesLSMx.h"
+#include "./Gradjx/Gradjx.h"
+#include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
+#include "./InputControlUpdatex/InputControlUpdatex.h"
+#include "./InputDepthAverageAtBasex/InputDepthAverageAtBasex.h"
+#include "./InputDuplicatex/InputDuplicatex.h"
+#include "./InputExtrudex/InputExtrudex.h"
+#include "./InputScalex/InputScalex.h"
+#include "./InterpFromMesh2dx/InterpFromMesh2dx.h"
+#include "./InterpFromGridToMeshx/InterpFromGridToMeshx.h"
+#include "./InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h"
+#include "./InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h"
+#include "./InterpFromMeshToGridx/InterpFromMeshToGridx.h"
+#include "./InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+#include "./InputUpdateFromSolutionx/InputUpdateFromSolutionx.h"
+#include "./InputUpdateFromDakotax/InputUpdateFromDakotax.h"
+#include "./InputUpdateFromVectorx/InputUpdateFromVectorx.h"
+#include "./InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
+#include "./InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h"
+#include "./IoModelToConstraintsx/IoModelToConstraintsx.h"
+#include "./KMLFileReadx/KMLFileReadx.h"
+#include "./KMLMeshWritex/KMLMeshWritex.h"
+#include "./KMLOverlayx/KMLOverlayx.h"
+#include "./Exp2Kmlx/Exp2Kmlx.h"
+#include "./Kml2Expx/Kml2Expx.h"
+#include "./Krigingx/Krigingx.h"
+#include "./FloatingiceMeltingRatex/FloatingiceMeltingRatex.h"
+#include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
+#include "./MeshPartitionx/MeshPartitionx.h"
+#include "./MeshProfileIntersectionx/MeshProfileIntersectionx.h"
+#include "./SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
+#include "./SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
+#include "./SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h"
+#include "./SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h"
+#include "./SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h"
+#include "./ModelProcessorx/ModelProcessorx.h"
+#include "./ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
+#include "./NodalValuex/NodalValuex.h"
+#include "./NodeConnectivityx/NodeConnectivityx.h"
+#include "./NodesDofx/NodesDofx.h"
+#include "./OutputDefinitionsResponsex/OutputDefinitionsResponsex.h"
+#include "./OutputResultsx/OutputResultsx.h"
+#include "./ConstraintsStatex/ConstraintsStatex.h"
+#include "./PointCloudFindNeighborsx/PointCloudFindNeighborsx.h"
+#include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
+#include "./Reduceloadx/Reduceloadx.h"
+#include "./Reducevectorgtofx/Reducevectorgtofx.h"
+#include "./ResetConstraintsx/ResetConstraintsx.h"
+#include "./ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h"
+#include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "./Scotchx/Scotchx.h"
+#include "./Shp2Kmlx/Shp2Kmlx.h"
+#include "./SurfaceMassBalancex/SurfaceMassBalancex.h"
+#include "./Solverx/Solverx.h"
+#include "./SystemMatricesx/SystemMatricesx.h"
+#include "./SpcNodesx/SpcNodesx.h"
+#include "./SurfaceAreax/SurfaceAreax.h"
+#include "./TriaSearchx/TriaSearchx.h"
+#include "./TriMeshx/TriMeshx.h"
+#include "./TriMeshProcessRiftsx/TriMeshProcessRiftsx.h"
+#include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
+#include "./ThicknessAlongGradientx/ThicknessAlongGradientx.h"
+#include "./ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
+#include "./UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h"
+#include "./VerticesDofx/VerticesDofx.h"
+#include "./VertexCoordinatesx/VertexCoordinatesx.h"
+#include "./VecMergex/VecMergex.h"
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Abs.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Abs.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Abs.h	(revision 18231)
@@ -0,0 +1,9 @@
+#ifndef _BAMGABS_H_
+#define _BAMGABS_H_
+
+namespace bamg {
+
+	template<class T> inline T Abs (const T &a){return a <0 ? -a : a;}
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 18231)
@@ -0,0 +1,34 @@
+#include "./Abs.h"
+#include "./extrema.h"
+
+namespace bamg {
+
+	long BigPrimeNumber(long n){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/AGoodNumberPrimeWith)*/
+
+		/*list of big prime numbers*/
+		const long BigPrimeNumber[] ={ 567890359L,
+			567890431L,  567890437L,  567890461L,  567890471L,
+			567890483L,  567890489L,  567890497L,  567890507L,
+			567890591L,  567890599L,  567890621L,  567890629L , 0};
+
+		/*initialize o and pi*/
+		long o  = 0;
+		long pi = BigPrimeNumber[1];
+
+		/*loop until BigPrimeNumber[i]==0 (end of BigPrimeNumber)*/
+		for (int i=0; BigPrimeNumber[i]; i++){
+
+			/*compute r, remainder of the division of BigPrimeNumber[i] by n*/
+			long r = BigPrimeNumber[i] % n;
+
+			/*compute oo = min ( r , n-r , |n - 2r|, |n-3r|)*/
+			long oo = Min(Min(r,n-r),Min(Abs(n-2*r),Abs(n-3*r)));
+			if(o < oo){
+				o  = oo;
+				pi = BigPrimeNumber[i];
+			}
+		}
+		return pi; 
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BigPrimeNumber.h	(revision 18231)
@@ -0,0 +1,9 @@
+#ifndef _BIGPRIMENUMBER_H_
+#define _BIGPRIMENUMBER_H_
+
+namespace bamg {
+
+	long BigPrimeNumber(long n);
+
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BinaryRand.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BinaryRand.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/BinaryRand.h	(revision 18231)
@@ -0,0 +1,18 @@
+#ifndef _BINARYRAND_H_
+#define _BINARYRAND_H_
+
+#include <cstdlib>
+
+/*Return 1 or 0 randomly*/
+inline int BinaryRand(){
+	#ifdef RAND_MAX
+		/*RAND_MAX is defined by stdlib.h and is usually 32767*/
+		const long HalfRandMax = RAND_MAX/2;
+		return rand() < HalfRandMax;
+	#else
+		/*For sun machines, RAND_MAX is not defined, use 2^24*/
+		return rand() & 16384;
+	#endif
+} 
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Exchange.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Exchange.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/Exchange.h	(revision 18231)
@@ -0,0 +1,6 @@
+#ifndef _EXCHANGE_H_
+#define _EXCHANGE_H_
+
+template<class T> inline void Exchange (T &a,T &b) {T c=a;a=b;b=c;}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/HeapSort.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/HeapSort.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/HeapSort.h	(revision 18231)
@@ -0,0 +1,92 @@
+#ifndef _HEAPSORT_H_
+#define _HEAPSORT_H_
+
+/*Sort a list of size n*/
+template<class T> inline void  HeapSort(T *c,long n){ /*{{{*/
+
+	/*Intermediaries*/
+	int i,j,l,r;
+	T   crit;
+
+	/*return if size <=1*/
+	if(n<=1) return;
+
+	/*Initialize variables*/
+	l=n/2+1; 
+	r=n;
+	c--; //the array must starts at 1 and not 0 
+
+	/*Sorting algorithm*/
+	for(;;){
+		if(l<=1){
+			crit   = c[r];
+			c[r--] = c[1];
+			if(r==1){
+				c[1]=crit; 
+				return;
+			}
+		}
+		else{
+			crit = c[--l]; 
+		}
+		j=l;
+		for(;;){
+			i = j;
+			j = 2*j;
+			if  (j>r){c[i]=crit;break;}
+			if ((j<r) && (c[j] < c[j+1])) j++;//c[j+1]> c[j] -> take j+1 instead of j (larger value)
+			if (crit < c[j]) c[i]=c[j];       //c[j]  > crit -> put this large value in i(<j)
+			else{c[i]=crit;break;}            //c[j]  < crit -> put crit in i (<j)
+		}
+	}
+}
+/*}}}*/
+
+/*Sort a list of size n and returns ordering*/
+template<class T> inline void  HeapSort(int** porder,T* c,int n){ /*{{{*/
+
+	/*Intermediaries*/
+	int  i,j,l,r;
+	T    crit;
+	int  pos;
+	int* order = NULL;
+
+	/*return if size <=1*/
+	if(n<=1) return;
+
+	/*Initialize variables*/
+	l=n/2+1; 
+	r=n;
+	c--; //the array must starts at 1 and not 0 
+	order = new int[n];
+	for(i=0;i<n;i++) order[i]=i+1;
+
+	/*Sorting algorithm*/
+	for(;;){
+		if(l<=1){
+			crit  =c[r]; pos=order[r];
+			c[r--]=c[1]; order[r+1]=order[1];
+			if (r==1){
+				c[1]=crit; order[1]=pos;
+				order++;
+				*porder=order;
+				return;
+			}
+		}
+		else  {crit=c[--l]; pos=order[l];}
+		j=l;
+		for(;;){
+			i=j;
+			j=2*j;
+			if  (j>r) {c[i]=crit;order[i]=pos;break;}
+			if ((j<r) && (c[j] < c[j+1]))j++;
+			if (crit < c[j]) {c[i]=c[j];order[i]=order[j];}
+			else{c[i]=crit;order[i]=pos;break;}
+		}
+	}
+
+	/*Make cppcheck happy*/
+	*porder=order;
+}/*}}}*/
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/OppositeAngle.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/OppositeAngle.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/OppositeAngle.h	(revision 18231)
@@ -0,0 +1,12 @@
+#ifndef _OPPOSITEANGLE_H_
+#define _OPPOSITEANGLE_H_
+
+#include "../Numerics/constants.h"
+
+/*Return the opposite angle modulo 2 Pi*/
+namespace bamg {
+	inline float  OppositeAngle(float  a){return a<0 ? PI+a:a-PI;}
+	inline double OppositeAngle(double a){return a<0 ?  PI+a:a- PI;}
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/extrema.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/extrema.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/extrema.h	(revision 18231)
@@ -0,0 +1,13 @@
+#ifndef _EXTREMA_H_
+#define _EXTREMA_H_
+
+namespace bamg {
+
+	template<class T> inline T Min (const T &a,const T &b){return a < b ? a : b;}
+	template<class T> inline T Max (const T &a,const T & b){return a > b ? a : b;}
+	template<class T> inline T Max3 (const T &a,const T & b,const T & c){return Max(Max(a,b),c);}
+	template<class T> inline T Min3 (const T &a,const T & b,const T & c){return Min(Min(a,b),c);}
+
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/shared.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/shared.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Bamg/shared.h	(revision 18231)
@@ -0,0 +1,16 @@
+/* \file shared.h
+ * \brief: header file for all shared  routines.
+ */
+
+#ifndef _SHAREDBamg_H_
+#define _SHAREDBamg_H_
+
+#include "Abs.h"
+#include "BigPrimeNumber.h"
+#include "BinaryRand.h"
+#include "Exchange.h"
+#include "extrema.h"
+#include "HeapSort.h"
+#include "OppositeAngle.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Arrhenius.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Arrhenius.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Arrhenius.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+/* \file Arrhenius.cpp
+ * \brief figure out B of ice for a certain temperature
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
+
+IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n){
+	/*Use EISMINT Parameterization for the rheology: Payne2000
+	 *
+	 *  A(T*) = A0 exp(-Q/RT*)
+	 *
+	 *  A0 constant of proportionality
+	 *     = 3.61 * 10^-13   if T*<263.15K
+	 *     = 1.73 * 10^3     if T*>263.15K
+	 *  Q  Activation energy for creep
+	 *     = 6.0  * 10^4     if T*<263.15K
+	 *     = 13.9 * 10^4     if T*>263.15K
+	 *  R  Universal gas constant
+	 *     = 8.314
+	 *  T* Absolute temperature corrected for the dependence of Tpmp on P
+	 *     = T - beta (s-z)
+	 *
+	 *  Convert A to B :  B = A^(-1/n) */
+
+	/*Some physical constants (Payne2000)*/
+	IssmDouble beta=8.66*1.e-4;
+	IssmDouble R=8.314;
+
+	/*Intermediaries*/
+	IssmDouble A,B,Tstar;
+
+	/*convert temperature to absolute temperature*/
+	_assert_(depth>0);
+	Tstar=temperature-beta*depth;
+	_assert_(Tstar>0);
+
+	/*Get A*/
+	if(Tstar<263.15){
+		A=3.61e-13*exp(  -6.e+4/(R*Tstar));
+	}
+	else{
+		A=1.73e+3 *exp(-13.9e+4/(R*Tstar));
+	}
+
+	/*Convert to B*/
+	B=pow(A,-1./n);
+
+	return B;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 18231)
@@ -0,0 +1,32 @@
+/* file:  ComputeTemperaturePrecipitation.cpp
+   Compute the temperature and precipitation at time t from 
+   the data at present day and delta18O
+ */
+
+#include "./elements.h"
+#include "../Numerics/numerics.h"
+
+void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
+				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
+				     IssmDouble* PrecipitationsPresentday,
+				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
+				     IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout){
+
+  IssmDouble monthlytemperaturestmp[12],monthlyprectmp[12];
+  IssmDouble delta18oLapseRate=-6.2*pow(10.,-3);
+  IssmDouble glacialindex; // used to vary present day temperature
+
+  glacialindex = 0.;//(Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
+  //  /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent));
+
+  for (int imonth = 0; imonth<12; imonth++){  
+    monthlytemperaturestmp[imonth] = glacialindex*TemperaturesLgm[imonth] + (1.-glacialindex)*TemperaturesPresentday[imonth];
+    //monthlyprectmp[imonth] = 1.5*pow(2,((monthlytemperaturestmp[imonth]-273.15-0)/10)); //equation from rob's paper
+    monthlyprectmp[imonth] = PrecipitationsPresentday[imonth];
+
+    /*Assign output pointer*/
+    *(monthlytemperaturesout+imonth) = monthlytemperaturestmp[imonth];
+    *(monthlyprecout+imonth) = monthlyprectmp[imonth];
+  }
+  // printf(" tempera %f\n",monthlytemperaturestmp[1]);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Cuffey.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Cuffey.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Cuffey.cpp	(revision 18231)
@@ -0,0 +1,57 @@
+/* \file Cuffey.cpp
+ * \brief figure out B of ice for a certain temperature
+ *	  INPUT function B=Cuffey(temperature)
+ *    where rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Cuffey, p75). 
+ */
+
+#include <math.h>
+
+#include "../Numerics/types.h"
+
+IssmDouble Cuffey(IssmDouble temperature){
+
+	/*output: */
+	IssmDouble B,T;
+
+	/*Switch to celsius from Kelvin: */
+	T=temperature-273.15;
+
+	if(T<=-45.0){
+		B=1.e+8*(-0.000396645116301*pow(T+50.,3)+ 0.013345579471334*pow(T+50.,2) -0.356868703259105*(T+50.)+7.272363035371383);
+	}
+	else if((T>=-45.0) && (T<=-40.0)){
+		B=1.e+8*(-0.000396645116301*pow(T+45.,3)+ 0.007395902726819*pow(T+45.,2) -0.253161292268336*(T+45.)+5.772078366321591);
+	}
+	else if((T>=-40.0) && (T<=-35.0)){
+		B=1.e+8*(0.000408322072669*pow(T+40.,3)+  0.001446225982305*pow(T+40.,2)  -0.208950648722716*(T+40.)+4.641588833612773);
+	}
+	else if((T>=-35.0) && (T<=-30.0)){
+		B=1.e+8*(-0.000423888728124*pow(T+35.,3)+ 0.007571057072334*pow(T+35.,2)  -0.163864233449525*(T+35.)+3.684031498640382);
+	}
+	else if((T>=-30.0) && (T<=-25.0)){
+		B=1.e+8*(0.000147154327025*pow(T+30.,3)+ 0.001212726150476*pow(T+30.,2) -0.119945317335478*(T+30.)+3.001000667185614);
+	}
+	else if((T>=-25.0) && (T<=-20.0)){
+		B=1.e+8*(-0.000193435838672*pow(T+25.,3)+ 0.003420041055847*pow(T+25.,2)  -0.096781481303861*(T+25.)+2.449986525148220);
+	}
+	else if((T>=-20.0) && (T<=-15.0)){
+		B=1.e+8*(0.000219771255067*pow(T+20.,3)+  0.000518503475772*pow(T+20.,2)  -0.077088758645767*(T+20.)+2.027400665191131);
+	}
+	else if((T>=-15.0) && (T<=-10.0)){
+		B=1.e+8*(-0.000653438900191*pow(T+15.,3)+ 0.003815072301777*pow(T+15.,2)  -0.055420879758021*(T+15.)+1.682390865739973);
+	}
+	else if((T>=-10.0) && (T<=-5.0)){
+		B=1.e+8*(0.000692439419762*pow(T+10.,3) -0.005986511201093 *pow(T+10.,2) -0.066278074254598*(T+10.)+1.418983411970382);
+	}
+	else if((T>=-5.0) && (T<=-2.0)){
+		B=1.e+8*(-0.000132282004110*pow(T+5.,3) +0.004400080095332*pow(T+5.,2)    -0.074210229783403*(T+5.)+ 1.024485188140279);
+	}
+	else{
+		B=1.e+8*(-0.000132282004110*pow(T+2.,3) +0.003209542058346*pow(T+2.,2)    -0.051381363322371*(T+2.)+ 0.837883605537096);
+	}
+
+	/*B cannot be negative!*/
+	if(B<0) B=1.e+6;
+
+	return B;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 18231)
@@ -0,0 +1,44 @@
+/*!\file DrainageFunctionWaterfraction.cpp
+ * \brief: drain excess water fraction
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
+
+IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.){
+	/* DrainageFunctionWaterfraction returns how much of the waterfraction is drained per year */
+	_assert_(waterfraction>=0.);
+	_assert_(dt>=0.);
+
+	IssmDouble w0=0.01, w1=0.02, w2=0.03;
+	IssmDouble yts=365.*24.*60.*60.;
+	IssmDouble Dret, D0=0., D1=0.005/yts, D2=0.05/yts;
+
+	/*get drainage function value*/
+	if((w0==w1)||(w1==w2)||(w0==w2))
+		_error_("Error: equal ordinates in DrainageFunctionWaterfraction -> division by zero. Abort");
+	
+	if(waterfraction<=w0)
+		Dret=D0;
+	else if((waterfraction>w0) && (waterfraction<=w1))
+		Dret=(D1-D0)/(w1-w0)*(waterfraction-w0)+D0;
+	else if((waterfraction>w1) && (waterfraction<=w2))
+		Dret=(D2-D1)/(w2-w1)*(waterfraction-w1)+D1;
+	else 
+		Dret=D2;
+
+	/*drain only up to w0*/
+	if(dt==0.){
+		if((waterfraction>w0) && (waterfraction-Dret*yts<w0))
+			return waterfraction-w0;
+		else
+			return Dret*yts;
+	}
+	else{
+		if((waterfraction>w0) && (waterfraction-dt*Dret<w0))
+			return (waterfraction-w0)/dt;
+		else
+			return Dret;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/LliboutryDuval.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/LliboutryDuval.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/LliboutryDuval.cpp	(revision 18231)
@@ -0,0 +1,77 @@
+/* \file LliboutryDuval.cpp
+ * \brief figure out B of ice for a certain temperature and water fraction or enthalpy
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
+
+/* get ice stiffness B from enthalpy, pressure and flow law exponent*/
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure, IssmDouble n, IssmDouble betaCC, IssmDouble referencetemperature, IssmDouble heatcapacity, IssmDouble latentheat){
+  /*Use parameterization for the rheology: Grewe/Blatter 2009, Aschwanden 2012
+   *
+   *  A(H,p) = A0 exp(-Q/RT(H,p)), if H < H_s(p)
+   *         = A0 exp(-Q/RTpmp) (1+181.25w(H,p)), if H_s(p) \le H < H_l(p)
+   *  
+   *  T(H,p) = Tref + H/c_i, if H < H_s(p)
+   *         = Tpmp , if H_s(p) \le H \le H_l(p)
+   *
+   *  w(H,p) = 0, if H < H_s(p)
+   *         = (H - H_s(p))/L
+   *
+   *  H_s(p) = c_i (Tpmp - Tref)
+   *
+   *  Tpmp   = T - betaCC p;
+   *
+   *  A0 constant of proportionality
+   *     = 3.61 * 10^-13   if T*<263.15K
+   *     = 1.73 * 10^3     if T*>263.15K
+   *  Q  Activation energy for creep
+   *     = 6.0  * 10^4     if T*<263.15K
+   *     = 13.9 * 10^4     if T*>263.15K
+   *  R  Universal gas constant
+   *     = 8.314
+   *  
+   *  Convert A to B :  B = A^(-1/n) */
+
+	/*check feasibility*/
+  _assert_(pressure>=0);
+  _assert_(n>0);
+  _assert_(betaCC>=0);
+  _assert_(referencetemperature>=0);
+  _assert_(heatcapacity>0);
+  _assert_(latentheat>0);
+
+  /*Some physical constants*/
+  IssmDouble R=8.314; 
+
+  /*Intermediaries*/
+  IssmDouble A,B,Tstar,Tpmp,H_sp,waterfraction;
+
+  Tpmp=273.15-betaCC*pressure; 
+  H_sp=heatcapacity*(Tpmp - referencetemperature);
+  if (enthalpy < H_sp){
+    Tstar = referencetemperature + enthalpy/heatcapacity - betaCC*pressure;	
+    waterfraction = 0.;
+  }
+  else{
+    Tstar=Tpmp;
+    waterfraction=(enthalpy - H_sp)/latentheat;
+		if (waterfraction > 0.01)
+			waterfraction = 0.01;
+  }
+
+  /*Get A*/
+  if(Tstar<=263.15){
+    A=3.61e-13 * exp(  -6.e+4/(R*Tstar));
+  }
+  else{
+    A=1.73e3   * exp(-13.9e+4/(R*Tstar));
+  }
+  A*=(1. + 181.25*waterfraction);
+
+  /*Convert to B*/
+  B=pow(A,-1./n);
+
+  return B;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Paterson.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Paterson.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/Paterson.cpp	(revision 18231)
@@ -0,0 +1,57 @@
+/* \file Paterson.cpp
+ * \brief figure out B of ice for a certain temperature
+ *	  INPUT function B=Paterson(temperature)
+ *    where rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+ */
+
+#include <math.h>
+
+#include "../Numerics/types.h"
+
+IssmDouble Paterson(IssmDouble temperature){
+
+	IssmDouble B,T;
+
+	/*Switch to celsius from Kelvin: */
+	T=temperature-273.15;
+
+
+	if(T<=-45.0){
+		B=1.e+8*(-0.000292866376675*pow(T+50.,3)+ 0.011672640664130*pow(T+50.,2)  -0.325004442485481*(T+50.)+  6.524779401948101);
+	}
+	else if((T>=-45.0) && (T<=-40.0)){
+		B=1.e+8*(-0.000292866376675*pow(T+45.,3)+ 0.007279645014004*pow(T+45.,2)  -0.230243014094813*(T+45.)+  5.154964909039554);
+	}
+	else if((T>=-40.0) && (T<=-35.0)){
+		B=1.e+8*(0.000072737147457*pow(T+40.,3)+  0.002886649363879*pow(T+40.,2)  -0.179411542205399*(T+40.)+  4.149132666831214);
+	}
+	else if((T>=-35.0) && (T<=-30.0)){
+		B=1.e+8*(-0.000086144770023*pow(T+35.,3)+ 0.003977706575736*pow(T+35.,2)  -0.145089762507325*(T+35.)+  3.333333333333331);
+	}
+	else if((T>=-30.0) && (T<=-25.0)){
+		B=1.e+8*(-0.000043984685769*pow(T+30.,3)+ 0.002685535025386*pow(T+30.,2)  -0.111773554501713*(T+30.)+  2.696559088937191);
+	}
+	else if((T>=-25.0) && (T<=-20.0)){
+		B=1.e+8*(-0.000029799523463*pow(T+25.,3)+ 0.002025764738854*pow(T+25.,2)  -0.088217055680511*(T+25.)+  2.199331606342181);
+	}
+	else if((T>=-20.0) && (T<=-15.0)){
+		B=1.e+8*(0.000136920904777*pow(T+20.,3)+  0.001578771886910*pow(T+20.,2)  -0.070194372551690*(T+20.)+  1.805165505978111);
+	}
+	else if((T>=-15.0) && (T<=-10.0)){
+		B=1.e+8*(-0.000899763781026*pow(T+15.,3)+ 0.003632585458564*pow(T+15.,2)  -0.044137585824322*(T+15.)+  1.510778053489523);
+	}
+	else if((T>=-10.0) && (T<=-5.0)){
+		B=1.e+8*(0.001676964325070*pow(T+10.,3)-  0.009863871256831*pow(T+10.,2)  -0.075294014815659*(T+10.)+  1.268434288203714);
+	}
+	else if((T>=-5.0) && (T<=-2.0)){
+		B=1.e+8*(-0.003748937622487*pow(T+5.,3)+0.015290593619213*pow(T+5.,2)  -0.048160403003748*(T+5.)+  0.854987973338348);
+	}
+	else{
+		B=1.e+8*(-0.003748937622488*pow(T+2.,3)-0.018449844983174*pow(T+2.,2)  -0.057638157095631*(T+2.)+  0.746900791092860);
+	}
+
+	/*B cannot be negative!*/
+	if(B<0) B=1.e+6;
+
+	return B;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 18231)
@@ -0,0 +1,204 @@
+/* file:  PddSurfaceMassBlance.cpp
+   Calculating the surface mass balance using the positive degree day method.
+ */
+
+#include "./elements.h"
+#include "../Numerics/numerics.h"
+
+IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures, IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p){ 
+
+  // output:
+  IssmDouble B;    // surface mass balance, melt+accumulation
+  int    iqj,imonth;
+
+  IssmDouble saccu;     // yearly surface accumulation
+  IssmDouble smelt;     // yearly melt
+  IssmDouble precrunoff;      // yearly runoff
+  IssmDouble prect; // total precipitation during 1 year taking into account des. ef.
+  IssmDouble water; //water=rain + snowmelt 
+  IssmDouble runoff; //meltwater only, does not include rain 
+  IssmDouble sconv; //rhow_rain/rhoi / 12 months
+
+  IssmDouble lapser=6.5, sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
+  // IssmDouble desfac = 0.5;                 // desert elevation factor
+  // IssmDouble s0p=0.;         // should be set to elevation from precip source
+  IssmDouble s0t=0.;         // should be set to elevation from temperature source
+  IssmDouble st;             // elevation between altitude of the temp record and current altitude
+  IssmDouble sp;             // elevation between altitude of the prec record and current altitude
+
+  // PDD and PD constants and variables
+  IssmDouble siglim;          // sigma limit for the integration which is equal to 2.5 sigmanorm
+  IssmDouble signormc = signorm - 0.5;     // sigma of the temperature distribution for cloudy day
+  IssmDouble siglimc, siglim0, siglim0c;
+  IssmDouble PDup, pddsig, PDCUT = 2.0; // PDcut: rain/snow cutoff temperature (C)
+  IssmDouble DT = 0.02;
+  IssmDouble pddt, pd; // pd: snow/precip fraction, precipitation falling as snow
+
+  IssmDouble q, qmpt; // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
+  IssmDouble qm = 0.;        // snow part of the precipitation 
+  IssmDouble qmt = 0.;       // precipitation without desertification effect adjustment
+  IssmDouble qmp = 0.;       // desertification taken into account
+  IssmDouble pdd = 0.;     
+  IssmDouble frzndd = 0.;  
+
+  IssmDouble tstar;          // monthly mean surface temp
+  IssmDouble Tsum= 0.;       // average summer (JJA) temperature
+  IssmDouble Tsurf = 0.;     // average annual temperature    
+
+  IssmDouble deltm=1./12.;
+  int    ismon[12]={11,0,1,2,3,4,5,6,7,8,9,10};
+
+  IssmDouble snwm;  // snow that could have been melted in a year.
+  IssmDouble snwmf; //  ablation factor for snow per positive degree day.
+  IssmDouble smf;   //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002).
+
+  IssmDouble dfrz=1.5, CovrLm=2009./3.35e+5, dCovrLm=dfrz*CovrLm; //m*J kg^-1 C^-1 /(J kg^-1)=m/C yr
+  IssmDouble supice,supcap,diffndd;
+  IssmDouble fsupT=0.5,  fsupndd=0.5;  // Tsurf mode factors for supice
+  IssmDouble pddtj, hmx2;
+
+  sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
+
+  /*PDD constant*/
+  siglim = 2.5*signorm; 
+  siglimc = 2.5*signormc;
+  siglim0 = siglim/DT + 0.5;
+  siglim0c = siglimc/DT + 0.5;
+  PDup = siglimc+PDCUT;
+
+  // seasonal loop
+    for (iqj = 0; iqj < 12; iqj++){
+      imonth =  ismon[iqj];
+
+      st=(s-s0t)/1000.;
+      tstar = monthlytemperatures[imonth] - lapser *max(st,sealev);
+      Tsurf = tstar*deltm+Tsurf;        
+
+      /*********compute PD ****************/
+      if (tstar < PDup){
+	pd = 1.;
+	if (tstar >= -siglimc){ pd = pds[reCast<int,IssmDouble>(tstar/DT + siglim0c)];}}
+      else { 
+	pd = 0.;}
+
+      /******exp des/elev precip reduction*******/
+      sp=(s-s0p)/1000.; // deselev effect is wrt chng in topo
+      if (sp>0.0){q = exp(-desfac*sp);}
+      else {q = 1.0;}
+
+      qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month
+      qmpt= q*monthlyprec[imonth]*sconv;           
+      qmp= qmp + qmpt;
+      qm= qm + qmpt*pd;
+
+      /*********compute PDD************/
+      // ndd(month)=-(tstar-pdd(month)) since ndd+pdd gives expectation of
+      // gaussian=T_m, so ndd=-(Tsurf-pdd)
+      if (iqj>5 &&  iqj<9){ Tsum=Tsum+tstar;} 
+
+      if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
+      else if (tstar> -siglim){
+	pddsig=pdds[reCast<int,IssmDouble>(tstar/DT + siglim0)];
+	pdd = pdd + pddsig*deltm;
+	frzndd = frzndd - (tstar-pddsig)*deltm;}
+      else{frzndd = frzndd - tstar*deltm; }
+  } // end of seasonal loop 
+  //******************************************************************
+
+    saccu = qm;
+    prect = qmp;     // total precipitation during 1 year taking into account des. ef.
+    Tsum=Tsum/3;
+
+    /***** determine PDD factors *****/
+    if(Tsum< -1.) {
+      snwmf=2.65*0.001;   //  ablation factor for snow per positive degree day.*0.001 to go from mm to m/ppd
+      smf=17.22*0.001;    //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002)
+    } 
+    else if(Tsum< 10){
+      snwmf = (0.15*Tsum + 2.8)*0.001;
+      smf = (0.0067*pow((10.-Tsum),3) + 8.3)*0.001;
+    }
+    else{
+      snwmf=4.3*0.001;
+      smf=8.3*0.001;
+    }
+    snwmf=0.95*snwmf;
+    smf=0.95*smf;
+
+    /*****  compute PDD ablation and refreezing *****/
+    pddt = pdd *365;
+    snwm = snwmf*pddt;       // snow that could have been melted in a year
+    hmx2 = min(h,dfrz);   // refreeze active layer max depth: dfrz
+
+    if(snwm < saccu) {
+      water=prect-saccu + snwm; //water=rain + snowmelt
+      //     l 2.2= capillary factor
+      //     Should refreezing be controlled by frzndd or by mean annual Tsurf?
+      //     dCovrLm concept is of warming of active layer (thickness =d@=1-
+      //     >2m)
+      //     problem with water seepage into ice: should be sealed after
+      //     refreezing
+      //     so everything needs to be predicated on 1 year scale, except for
+      //     thermal
+      //     conductivity through ice
+      //     also, need to account that melt season has low accum, so what's
+      //     going to
+      //     hold the meltwater around for refreezing? And melt-time will have
+      //     low seasonal frzndd
+
+      //      Superimposed ice :  Pfeffer et al. 1991, Tarasov 2002
+
+      supice= min(hmx2*CovrLm*frzndd+2.2*(saccu-snwm), water); // superimposed ice
+      supcap=min(2.2*(saccu-snwm),water);
+      runoff=snwm - supice;  //meltwater only, does not include rain
+    }
+    else {  //all snow melted
+      supice= min(hmx2*CovrLm*frzndd, prect );
+      runoff= saccu + smf*(pddt-saccu/snwmf) - supice;
+      supcap=0;
+    }
+    //     pdd melting doesn't cool Tsurf, so ndd refreeze shouldn't warm it
+    //     except pdd melt heat source is atmosphere, while refreeze is
+    //     ground/ice stored interim
+    //     assume pdd=ndd, then melt should equal refreeze and Tsurf should=0
+    //     assume ndd=2*pdd, then all supice is refrozen, but Tsurf should be
+    //     <0
+    //     assume ndd>pdd, little melt => little supice 
+    //     bottom line: compare for Tsurf<0 : supice and no supice case,
+    //     expect Tsurf difference
+    //     except some of cooling flux comes from atmosphere//
+    //     1 dm supice should not raise Tsurf by 1/dCovrLm = 16.675C
+    //     does supice make sense when H< 0.1m? then d=thermoactive ice layer ////
+    //     < 0.1 
+
+    //     make more sense to just use residual pdd-ndd except that pdd
+    //     residual not clear yet
+    //     frzndd should not be used up by refreezing in snow, so stick in
+    //     supcap.
+    diffndd=0;
+    if (frzndd>0) {
+      diffndd=fsupndd*min((supice-supcap)/dCovrLm ,frzndd);
+      frzndd=frzndd-diffndd;
+    }
+    if(runoff<0){
+      saccu= saccu -runoff;
+      smelt = 0;
+      precrunoff=prect-saccu;
+      //here assume pdd residual is 0, => 
+      Tsurf= max(Tsurf,-frzndd);
+    }
+    else {
+      smelt = runoff;
+      precrunoff=prect-max(0.,supice)-saccu;}
+    //here really need pdd balance, try 0.5 fudge factor?
+    //at least runoff>0 => it's fairly warm, so Tsurf is !<<0,
+    //yet from site plots, can be ice free with Tsurf=-5.5C
+    if(Tsurf<0) {
+      Tsurf= min(Tsurf+fsupT*diffndd , 0.);}
+
+    B = -smelt+saccu;
+    B = B/yts;
+    pddtj=pddt;
+
+  return B;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PrintArrays.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PrintArrays.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/PrintArrays.cpp	(revision 18231)
@@ -0,0 +1,62 @@
+
+#include "./elements.h"
+#include "../io/Print/Print.h"
+using namespace std;
+
+void printarray(IssmPDouble* array,int lines,int cols){
+	_printf_("\n");
+	for(int i=0;i<lines;i++){  
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++) _printf_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
+		_printf_(" ]\n");
+	}  
+	_printf_("\n");
+}
+void printsparsity(IssmPDouble* array,int lines,int cols){
+	int count;
+	_printf_("\n");
+	for(int i=0;i<lines;i++){  
+		_printf_("   [ ");
+		count = 0;
+		for(int j=0;j<cols;j++){
+			if(array[i*cols+j]!=0.0){
+				_printf_( " X"); count++;
+			}
+			else
+			 _printf_( " .");
+		}
+		_printf_(" ] "<<i<<" => "<<count << "\n");
+	}  
+	_printf_("\n");
+}
+void printarray(int* array,int lines,int cols){
+	_printf_("\n");
+	for(int i=0;i<lines;i++){  
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++) _printf_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
+		_printf_(" ]\n");
+	}  
+	_printf_("\n");
+}
+void printarray(bool* array,int lines,int cols){
+	_printf_("\n");
+	for(int i=0;i<lines;i++){  
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++){
+			if(array[i*cols+j]) _printf_( " 1");
+			else _printf_( " 0");
+		}
+		_printf_(" ]\n");
+	}  
+	_printf_("\n");
+}
+void printbinary(int n){
+	unsigned int i=1L<<(sizeof(n)*8-1);
+	while (i>0) {
+		if (n&i)
+		 _printf_("1");
+		else
+		 _printf_("0");
+		i>>=1;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/elements.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/elements.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Elements/elements.h	(revision 18231)
@@ -0,0 +1,31 @@
+/*!\file: elements.h
+ * \brief prototypes for elements.h
+ */ 
+
+#ifndef _SHARED_ELEMENTS_H_
+#define _SHARED_ELEMENTS_H_
+
+#include "../Numerics/types.h"
+
+IssmDouble Cuffey(IssmDouble temperature);
+IssmDouble Paterson(IssmDouble temperature);
+IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n);
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure, IssmDouble n, IssmDouble betaCC, IssmDouble referencetemperature, IssmDouble heatcapacity, IssmDouble latentheat);
+// IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n);
+IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, 
+				IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s,
+				IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p);
+void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
+				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
+				     IssmDouble* PrecipitationsPresentday,
+				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
+					  IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
+IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.);
+
+/*Print arrays*/
+void printarray(IssmPDouble* array,int lines,int cols=1);
+void printarray(int* array,int lines,int cols=1);
+void printarray(bool* 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/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Enum.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Enum.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Enum.h	(revision 18231)
@@ -0,0 +1,10 @@
+
+#ifndef _ISSM_ENUM_
+#define _ISSM_ENUM_
+
+#include "./EnumDefinitions.h"
+const char* EnumToStringx(int enum_in);
+void        EnumToStringx(char** string,int enum_in);
+int         StringToEnumx(const char* string_in,bool notfounderror=true);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumDefinitions.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumDefinitions.h	(revision 18231)
@@ -0,0 +1,763 @@
+/*
+ * \file EnumDefinitions.h:
+ * \brief: enum functions for our objects
+ */
+
+#ifndef _ENUM_DEFINITIONS_
+#define _ENUM_DEFINITIONS_
+
+enum definitions{
+	/*Model fields {{{*/
+	AutodiffIsautodiffEnum, 
+	AutodiffNumDependentsEnum,
+	AutodiffNumDependentObjectsEnum,
+	AutodiffDependentObjectNamesEnum,
+	AutodiffDependentObjectTypesEnum,
+	AutodiffDependentObjectIndicesEnum,
+	AutodiffDependentObjectsEnum,
+	AutodiffNumIndependentsEnum,
+	AutodiffNumIndependentObjectsEnum,
+	AutodiffIndependentObjectNamesEnum,
+	AutodiffIndependentObjectTypesEnum,
+	AutodiffIndependentObjectsEnum,
+	AutodiffJacobianEnum,
+	AutodiffXpEnum,
+	AutodiffDriverEnum,
+	AutodiffFosForwardIndexEnum,
+	AutodiffFovForwardIndicesEnum,
+	AutodiffFosReverseIndexEnum,
+	AutodiffMassFluxSegmentsPresentEnum,
+	AutodiffKeepEnum,
+	AutodiffObufsizeEnum,
+	AutodiffLbufsizeEnum,
+	AutodiffCbufsizeEnum,
+	AutodiffTbufsizeEnum,
+	AutodiffGcTriggerRatioEnum,
+	AutodiffGcTriggerMaxSizeEnum,
+	BalancethicknessSpcthicknessEnum,
+	BalancethicknessStabilizationEnum,
+	BalancethicknessThickeningRateEnum,
+	BasalforcingsEnum,
+	BasalforcingsGeothermalfluxEnum,
+	BasalforcingsGroundediceMeltingRateEnum,
+	BasalforcingsFloatingiceMeltingRateEnum,
+	BasalforcingsDeepwaterMeltingRateEnum,
+	BasalforcingsDeepwaterElevationEnum,
+	BasalforcingsUpperwaterElevationEnum,
+	FloatingMeltRateEnum,
+	LinearFloatingMeltRateEnum,
+	BedEnum,
+	BaseEnum,
+	ConstantsGEnum,
+	ConstantsReferencetemperatureEnum,
+	ConstantsYtsEnum,
+	DependentObjectEnum,
+	StressbalanceAbstolEnum,
+	StressbalanceIsnewtonEnum,
+	StressbalanceMaxiterEnum,
+	StressbalancePenaltyFactorEnum,
+	StressbalanceReferentialEnum,
+	StressbalanceReltolEnum,
+	StressbalanceNumRequestedOutputsEnum,
+	StressbalanceRequestedOutputsEnum,
+	StressbalanceRestolEnum,
+	StressbalanceRiftPenaltyLockEnum,
+	StressbalanceRiftPenaltyThresholdEnum,
+	StressbalanceShelfDampeningEnum,
+	StressbalanceSpcvxEnum,
+	StressbalanceSpcvyEnum,
+	StressbalanceSpcvzEnum,
+	StressbalanceFSreconditioningEnum,
+	StressbalanceVertexPairingEnum,
+	StressbalanceViscosityOvershootEnum,
+	LoadingforceXEnum,
+	LoadingforceYEnum,
+	LoadingforceZEnum,
+	FlowequationBorderSSAEnum,
+	FlowequationBorderHOEnum,
+	FlowequationBorderFSEnum,
+	FlowequationElementEquationEnum,
+	FlowequationIsSIAEnum,
+	FlowequationIsSSAEnum,
+	FlowequationIsL1L2Enum,
+	FlowequationIsHOEnum,
+	FlowequationIsFSEnum,
+	FlowequationFeSSAEnum,
+	FlowequationFeHOEnum,
+	FlowequationFeFSEnum,
+	FlowequationVertexEquationEnum,
+	FrictionCoefficientEnum,
+	FrictionPEnum,
+	FrictionQEnum,
+	FrictionMEnum,
+	FrictionCEnum,
+	FrictionLawEnum,
+	GeometryHydrostaticRatioEnum,
+	HydrologyModelEnum,
+	HydrologyshreveEnum,
+	HydrologyshreveSpcwatercolumnEnum,
+	HydrologyshreveStabilizationEnum,
+	HydrologydcEnum,
+	SedimentHeadEnum,
+	SedimentHeadOldEnum,
+	SedimentHeadResidualEnum,
+	EffectivePressureEnum,
+	EplHeadEnum,
+	EplHeadOldEnum,
+	EplHeadSlopeXEnum,
+	EplHeadSlopeYEnum,
+	HydrologydcMaxIterEnum,
+	HydrologydcRelTolEnum,
+	HydrologydcSpcsedimentHeadEnum,
+	HydrologydcSedimentCompressibilityEnum,
+	HydrologydcSedimentPorosityEnum,
+	HydrologydcSedimentThicknessEnum,
+	HydrologydcSedimentTransmitivityEnum,
+	HydrologydcWaterCompressibilityEnum,
+	HydrologydcSpceplHeadEnum,
+	HydrologydcMaskEplactiveNodeEnum,
+	HydrologydcMaskEplactiveEltEnum,
+	HydrologydcEplCompressibilityEnum,
+	HydrologydcEplPorosityEnum,
+	HydrologydcEplInitialThicknessEnum,
+	HydrologydcEplMaxThicknessEnum,
+	HydrologydcEplThicknessEnum,
+	HydrologydcEplThicknessOldEnum,
+	HydrologydcEplConductivityEnum,
+	HydrologydcIsefficientlayerEnum,
+	HydrologydcSedimentlimitFlagEnum,
+	HydrologydcSedimentlimitEnum,
+	HydrologydcTransferFlagEnum,
+	HydrologydcLeakageFactorEnum,
+	HydrologydcPenaltyFactorEnum,
+	HydrologydcPenaltyLockEnum,
+	HydrologydcBasalMoulinInputEnum,
+	HydrologyLayerEnum,
+	HydrologySedimentEnum,
+	HydrologyEfficientEnum,
+	HydrologySedimentKmaxEnum,
+	IndependentObjectEnum,
+	InversionControlParametersEnum,
+	InversionCostFunctionThresholdEnum,
+	InversionCostFunctionsCoefficientsEnum,
+	InversionCostFunctionsEnum,
+	InversionGradientScalingEnum,
+	InversionIscontrolEnum,
+	InversionTypeEnum,
+	InversionIncompleteAdjointEnum,
+	InversionMaxParametersEnum,
+	InversionMaxiterPerStepEnum,
+	InversionMaxiterEnum,
+	InversionMaxstepsEnum,
+	InversionFatolEnum,
+	InversionFrtolEnum,
+	InversionGatolEnum,
+	InversionGrtolEnum,
+	InversionGttolEnum,
+	InversionAlgorithmEnum,
+	InversionMinParametersEnum,
+	InversionNstepsEnum,
+	InversionDxminEnum,
+	InversionNumControlParametersEnum,
+	InversionNumCostFunctionsEnum,
+	InversionStepThresholdEnum,
+	InversionThicknessObsEnum,
+	InversionVxObsEnum,
+	InversionVyObsEnum,
+	InversionVzObsEnum,
+	MaskIceLevelsetEnum,
+	QmuMaskIceLevelsetEnum,
+	MaterialsBetaEnum,
+	MaterialsHeatcapacityEnum,
+	MaterialsLatentheatEnum,
+	MaterialsMeltingpointEnum,
+	MaterialsMixedLayerCapacityEnum,
+	MaterialsRheologyBEnum,
+	MaterialsRheologyBbarEnum,
+	MaterialsRheologyLawEnum,
+	MaterialsRheologyNEnum,
+	DamageIsdamageEnum,
+	DamageDEnum,
+	DamageFEnum,
+	QmuDamageDEnum,
+	DamageDbarEnum,
+	DamageLawEnum,
+	DamageC1Enum,
+	DamageC2Enum,
+	DamageC3Enum,
+	DamageC4Enum,
+	DamageElementinterpEnum,
+	DamageHealingEnum,
+	DamageStressThresholdEnum,
+	DamageStabilizationEnum,
+	DamagePenaltyThresholdEnum,
+	DamagePenaltyLockEnum,
+	DamagePenaltyFactorEnum,
+	DamageMaxiterEnum,
+	DamageSpcdamageEnum,
+	DamageMaxDamageEnum,
+	DamageEquivStressEnum,
+	DamageEvolutionNumRequestedOutputsEnum,
+	DamageEvolutionRequestedOutputsEnum,
+	NewDamageEnum,
+	MaterialsRhoIceEnum,
+	MaterialsRhoSeawaterEnum,
+	MaterialsRhoFreshwaterEnum,
+	MaterialsMuWaterEnum,
+	MaterialsThermalExchangeVelocityEnum,
+	MaterialsThermalconductivityEnum,
+	MaterialsTemperateiceconductivityEnum,
+	MaterialsLithosphereShearModulusEnum,
+	MaterialsLithosphereDensityEnum,
+	MaterialsMantleShearModulusEnum,
+	MaterialsMantleDensityEnum,
+	MeshAverageVertexConnectivityEnum,
+	MeshElements2dEnum,
+	MeshElementsEnum,
+	MeshLowerelementsEnum,
+	MeshNumberofelements2dEnum,
+	MeshNumberofelementsEnum,
+	MeshNumberoflayersEnum,
+	MeshNumberofvertices2dEnum,
+	MeshNumberofverticesEnum,
+	MeshUpperelementsEnum,
+	MeshVertexonbaseEnum,
+	MeshVertexonsurfaceEnum,
+	MeshVertexonboundaryEnum,
+	MeshXEnum,
+	MeshYEnum,
+	MeshZEnum,
+	MeshElementtypeEnum,
+	DomainTypeEnum,
+	DomainDimensionEnum,
+	Domain2DhorizontalEnum,
+	Domain2DverticalEnum,
+	Domain3DEnum,
+	MiscellaneousNameEnum, //FIXME: only used by qmu, should not be marshalled (already in queueing script)
+	MasstransportHydrostaticAdjustmentEnum,
+	MasstransportIsfreesurfaceEnum,
+	MasstransportMinThicknessEnum,
+	MasstransportPenaltyFactorEnum,
+	MasstransportSpcthicknessEnum,
+	MasstransportCalvingrateEnum,
+	MasstransportStabilizationEnum,
+	MasstransportVertexPairingEnum,
+	MasstransportNumRequestedOutputsEnum,
+	MasstransportRequestedOutputsEnum,
+	QmuIsdakotaEnum,
+	MassFluxSegmentsEnum,
+	MassFluxSegmentsPresentEnum,
+	QmuMassFluxSegmentsPresentEnum,
+	QmuNumberofpartitionsEnum,
+	QmuNumberofresponsesEnum,
+	QmuPartitionEnum,
+	QmuResponsedescriptorsEnum,
+	QmuVariabledescriptorsEnum,
+	QmuMaterialsRheologyBEnum,
+	RiftsNumriftsEnum,
+	RiftsRiftstructEnum,
+	SettingsResultsOnNodesEnum,
+	SettingsIoGatherEnum,
+	SettingsLowmemEnum,
+	SettingsOutputFrequencyEnum,
+	SettingsWaitonlockEnum,
+	DebugProfilingEnum,
+	ProfilingCurrentMemEnum,
+	ProfilingCurrentFlopsEnum,
+	ProfilingSolutionTimeEnum,
+	MaxIterationConvergenceFlagEnum,
+	SteadystateMaxiterEnum,
+	SteadystateNumRequestedOutputsEnum,
+	SteadystateReltolEnum,
+	SteadystateRequestedOutputsEnum,
+	SurfaceEnum,
+	ThermalIsenthalpyEnum,
+	ThermalIsdynamicbasalspcEnum,
+	ThermalMaxiterEnum,
+	ThermalPenaltyFactorEnum,
+	ThermalPenaltyLockEnum,
+	ThermalPenaltyThresholdEnum,
+	ThermalSpctemperatureEnum,
+	ThermalStabilizationEnum,
+	ThermalNumRequestedOutputsEnum,
+	ThermalRequestedOutputsEnum,
+	GiaMantleViscosityEnum,
+	GiaLithosphereThicknessEnum,
+	ThicknessEnum,
+	TimesteppingStartTimeEnum,
+	TimesteppingFinalTimeEnum,
+	TimesteppingCflCoefficientEnum,
+	TimesteppingTimeAdaptEnum,
+	TimesteppingTimeStepEnum,
+	TimesteppingInterpForcingsEnum,
+	TransientIsstressbalanceEnum,
+	TransientIsgroundinglineEnum,
+	TransientIsmasstransportEnum,
+	TransientIsthermalEnum,
+	TransientIsgiaEnum,
+	TransientIsdamageevolutionEnum,
+	TransientIshydrologyEnum,
+	TransientNumRequestedOutputsEnum,
+	TransientRequestedOutputsEnum,
+	PotentialEnum,
+	BalancethicknessSpcpotentialEnum,
+	BalancethicknessApparentMassbalanceEnum,
+	Balancethickness2MisfitEnum,
+	BalancethicknessNuxEnum,
+	BalancethicknessNuyEnum,
+	BalancethicknessVxObsEnum,
+	BalancethicknessVyObsEnum,
+	BalancethicknessThicknessObsEnum,
+	/*}}}*/
+	/*Surfaceforcings{{{*/
+	SurfaceforcingsEnum,
+	SMBEnum,
+	SurfaceforcingsMassBalanceEnum,
+	SMBpddEnum,
+	SurfaceforcingsDelta18oEnum,
+	SurfaceforcingsDelta18oSurfaceEnum,
+	SurfaceforcingsIsdelta18oEnum,
+	SurfaceforcingsPrecipitationsPresentdayEnum,
+	SurfaceforcingsTemperaturesPresentdayEnum,
+	SurfaceforcingsTemperaturesLgmEnum,
+	SurfaceforcingsPrecipitationEnum,
+	SurfaceforcingsDesfacEnum,
+	SurfaceforcingsS0pEnum,
+	SMBgradientsEnum,
+	SurfaceforcingsMonthlytemperaturesEnum,
+	SurfaceforcingsHrefEnum,
+	SurfaceforcingsSmbrefEnum,
+	SurfaceforcingsBPosEnum,
+	SurfaceforcingsBNegEnum,
+	SMBhenningEnum,
+	SMBcomponentsEnum,
+	SurfaceforcingsAccumulationEnum,
+	SurfaceforcingsEvaporationEnum,
+	SurfaceforcingsRunoffEnum,
+	SMBmeltcomponentsEnum,
+	SurfaceforcingsMeltEnum,
+	SurfaceforcingsRefreezeEnum,
+	/*TO BE REMOVED*/
+	SurfaceforcingsIspddEnum,
+	SurfaceforcingsIssmbgradientsEnum,
+	/*}}}*/
+	/*Solutions and Analyses{{{ */
+	SolutionTypeEnum,
+	AnalysisTypeEnum,
+	ConfigurationTypeEnum,
+	AdjointBalancethicknessAnalysisEnum,
+	AdjointBalancethickness2AnalysisEnum,
+	AdjointHorizAnalysisEnum,
+	AnalysisCounterEnum,
+	DefaultAnalysisEnum,
+	BalancethicknessAnalysisEnum,
+	BalancethicknessSolutionEnum,
+	Balancethickness2AnalysisEnum,
+	Balancethickness2SolutionEnum,
+	BalancethicknessSoftAnalysisEnum,
+	BalancethicknessSoftSolutionEnum,
+	BalancevelocityAnalysisEnum,
+	BalancevelocitySolutionEnum,
+	L2ProjectionEPLAnalysisEnum,
+	L2ProjectionBaseAnalysisEnum,
+	BedSlopeSolutionEnum,
+	DamageEvolutionSolutionEnum,
+	DamageEvolutionAnalysisEnum,
+	StressbalanceAnalysisEnum,
+	StressbalanceSIAAnalysisEnum,
+	StressbalanceSolutionEnum,
+	StressbalanceVerticalAnalysisEnum,
+	EnthalpyAnalysisEnum,
+	FlaimAnalysisEnum,
+	FlaimSolutionEnum,
+	HydrologyShreveAnalysisEnum,
+	HydrologyDCInefficientAnalysisEnum,
+	HydrologyDCEfficientAnalysisEnum,
+	HydrologySolutionEnum,
+	MeltingAnalysisEnum,
+	MasstransportAnalysisEnum,
+	MasstransportSolutionEnum,
+	FreeSurfaceBaseAnalysisEnum,
+	FreeSurfaceTopAnalysisEnum,
+	SurfaceNormalVelocityEnum,
+	ExtrudeFromBaseAnalysisEnum,
+	ExtrudeFromTopAnalysisEnum,
+	DepthAverageAnalysisEnum,
+	SteadystateSolutionEnum,
+	SurfaceSlopeSolutionEnum,
+	SmoothedSurfaceSlopeXAnalysisEnum,
+	SmoothedSurfaceSlopeYAnalysisEnum,
+	ThermalAnalysisEnum,
+	ThermalSolutionEnum,
+	TransientSolutionEnum,
+	UzawaPressureAnalysisEnum,
+	GiaSolutionEnum,
+	GiaAnalysisEnum,
+	MeshdeformationSolutionEnum,
+	MeshdeformationAnalysisEnum,
+	LevelsetAnalysisEnum,
+	ExtrapolationAnalysisEnum,
+	LsfReinitializationAnalysisEnum,
+	/*}}}*/
+	/*Approximations {{{*/
+	ApproximationEnum,
+	NoneApproximationEnum,
+	SIAApproximationEnum,
+	SSAApproximationEnum,
+	SSAHOApproximationEnum,
+	SSAFSApproximationEnum,
+	L1L2ApproximationEnum,
+	HOApproximationEnum,
+	HOFSApproximationEnum,
+	FSApproximationEnum,
+	FSvelocityEnum,
+	FSpressureEnum,
+	/*}}}*/
+	/*Datasets {{{*/
+	ConstraintsEnum,
+	LoadsEnum,
+	MaterialsEnum,
+	NodesEnum,
+	ContoursEnum,
+	ParametersEnum,
+	VerticesEnum,
+	ResultsEnum,
+	/*}}}*/
+	/*Objects {{{*/
+	GenericParamEnum,
+	AdolcParamEnum,
+	BoolInputEnum,
+	BoolParamEnum,
+	ContourEnum,
+	ControlInputEnum,
+	DatasetInputEnum,
+	DoubleInputEnum,
+	DataSetParamEnum,
+	DoubleMatArrayParamEnum,
+	DoubleMatParamEnum,
+	DoubleParamEnum,
+	DoubleVecParamEnum,
+	ElementEnum,
+	ExternalResultEnum,
+	FileParamEnum,
+	InputEnum,
+	IntInputEnum,
+	InputToExtrudeEnum,
+	InputToL2ProjectEnum,
+	InputToDepthaverageEnum,
+	IntParamEnum,
+	IntVecParamEnum,
+	TransientParamEnum,
+	MaticeEnum,
+	MatdamageiceEnum,
+	MatparEnum,
+	NodeEnum,
+	NumericalfluxEnum,
+	NumericalfluxTypeEnum,
+	ParamEnum,
+	PengridEnum,
+	PenpairEnum,
+	ProfilerEnum,
+	MatrixParamEnum,
+	NodeSIdEnum,
+	VectorParamEnum,
+	RiftfrontEnum,
+	RiftfrontTypeEnum,
+	SegmentEnum,
+	SegmentRiftfrontEnum,
+	SpcDynamicEnum,
+	SpcStaticEnum,
+	SpcTransientEnum,
+	StringArrayParamEnum,
+	StringParamEnum,
+	SegEnum,
+	SegInputEnum,
+	TriaEnum,
+	TriaInputEnum,
+	TetraEnum,
+	TetraInputEnum,
+	PentaEnum,
+	PentaInputEnum,
+	VertexEnum,
+	VertexPIdEnum,
+	VertexSIdEnum,
+	/*}}}*/
+	/*Fill {{{*/
+	AirEnum,
+	IceEnum,
+	MelangeEnum,
+	WaterEnum,
+	/*}}}*/
+	/*Rift state {{{*/
+	ClosedEnum,
+	FreeEnum,
+	OpenEnum,
+	/*}}}*/
+	/*Inputs {{{*/
+	AdjointpEnum,
+	AdjointxEnum,
+	AdjointyEnum,
+	AdjointzEnum,
+	BalancethicknessMisfitEnum,
+	BedSlopeXEnum,
+	BedSlopeYEnum,
+	BoundaryEnum,
+	ConvergedEnum,
+	FillEnum,
+	FractionIncrementEnum,
+	FrictionEnum,
+	InternalEnum,
+	MassFluxEnum,
+	MeltingOffsetEnum,
+	MisfitEnum,
+	PressureEnum,
+	PressurePicardEnum,
+	QmuPressureEnum,
+	QmuVxEnum,
+	QmuVyEnum,
+	QmuVzEnum,
+	QmuThicknessEnum,
+	QmuBaseEnum,
+	QmuSurfaceEnum,
+	QmuMeltingEnum,
+	QmuVxMeshEnum,
+	QmuVyMeshEnum,
+	QmuVzMeshEnum,
+	AndroidFrictionCoefficientEnum,
+	ResetPenaltiesEnum,
+	SegmentOnIceShelfEnum,
+	SurfaceAbsVelMisfitEnum,
+	SurfaceAreaEnum,
+	SurfaceAverageVelMisfitEnum,
+	SurfaceLogVelMisfitEnum,
+	SurfaceLogVxVyMisfitEnum,
+	SurfaceRelVelMisfitEnum,
+	SurfaceSlopeXEnum,
+	SurfaceSlopeYEnum,
+	TemperatureEnum,
+	TemperaturePicardEnum,
+	ThicknessAbsMisfitEnum,
+	VelEnum,
+	VelocityEnum,
+	VxAverageEnum,
+	VxEnum,
+	VxPicardEnum,
+	VyAverageEnum,
+	VyEnum,
+	VyPicardEnum,
+	VzEnum,
+	VzSSAEnum,
+	VzHOEnum,
+	VzPicardEnum,
+	VzFSEnum,
+	VxMeshEnum,
+	VyMeshEnum,
+	VzMeshEnum,
+	EnthalpyEnum,
+	EnthalpyPicardEnum,
+	ThicknessAbsGradientEnum,
+	ThicknessAlongGradientEnum,
+	ThicknessAcrossGradientEnum,
+	IntMatParamEnum,
+	RheologyBbarAbsGradientEnum,
+	DragCoefficientAbsGradientEnum,
+	TransientInputEnum,
+	WaterfractionEnum,
+	WatercolumnEnum,
+	BasalFrictionEnum,
+	ViscousHeatingEnum,
+	QmuTemperatureEnum,
+	HydrologyWaterVxEnum,
+	HydrologyWaterVyEnum,
+	SigmaNNEnum,
+	StressTensorEnum,
+	StressTensorxxEnum,
+	StressTensorxyEnum,
+	StressTensorxzEnum,
+	StressTensoryyEnum,
+	StressTensoryzEnum,
+	StressTensorzzEnum,
+	DeviatoricStressEnum,
+	DeviatoricStressxxEnum,
+	DeviatoricStressxyEnum,
+	DeviatoricStressxzEnum,
+	DeviatoricStressyyEnum,
+	DeviatoricStressyzEnum,
+	DeviatoricStresszzEnum,
+	StrainRateEnum,
+	StrainRatexxEnum,
+	StrainRatexyEnum,
+	StrainRatexzEnum,
+	StrainRateyyEnum,
+	StrainRateyzEnum,
+	StrainRatezzEnum,
+	DivergenceEnum,
+	GiaCrossSectionShapeEnum,
+	GiadWdtEnum,
+	GiaWEnum,
+	/*}}}*/
+	/*Element Interpolations{{{*/
+	P0Enum,
+	P1Enum,
+	P1DGEnum,
+	P1bubbleEnum,
+	P1bubblecondensedEnum,
+	P2Enum,
+	P2bubbleEnum,
+	P2bubblecondensedEnum,
+	P2xP1Enum,
+	P1xP2Enum,
+	P1xP3Enum,
+	P2xP4Enum,
+	P1P1Enum,
+	P1P1GLSEnum,
+	MINIEnum,
+	MINIcondensedEnum,
+	TaylorHoodEnum,
+	LATaylorHoodEnum,
+	XTaylorHoodEnum,
+	OneLayerP4zEnum,
+	CrouzeixRaviartEnum,
+	/*}}}*/
+	/*Results{{{*/
+	SaveResultsEnum,
+	BoolExternalResultEnum,
+	DoubleExternalResultEnum,
+	DoubleMatExternalResultEnum,
+	IntExternalResultEnum,
+	JEnum,
+	StringExternalResultEnum,
+	StepEnum,
+	TimeEnum,
+	WaterColumnOldEnum,
+	/*}}}*/
+	/*Output Definitions{{{*/
+	OutputdefinitionEnum,
+	OutputdefinitionListEnum,
+	MassfluxatgateEnum,
+	MassfluxatgateNameEnum,
+	MassfluxatgateSegmentsEnum,
+	MisfitNameEnum,
+	MisfitModelEnumEnum,
+	MisfitObservationEnum,
+	MisfitObservationEnumEnum,
+	MisfitTimeinterpolationEnum,
+	MisfitWeightsEnum,
+	MisfitWeightsEnumEnum,
+	SurfaceObservationEnum,
+	WeightsSurfaceObservationEnum,
+	/*}}}*/
+	/*Responses{{{*/
+	MinVelEnum,
+	MaxVelEnum,
+	MinVxEnum,
+	MaxVxEnum,
+	MaxAbsVxEnum,
+	MinVyEnum,
+	MaxVyEnum,
+	MaxAbsVyEnum,
+	MinVzEnum,
+	MaxVzEnum,
+	MaxAbsVzEnum,
+	IceVolumeEnum,
+	IceVolumeAboveFloatationEnum,
+	TotalSmbEnum,
+	/*}}}*/
+	/*Relaxation{{{*/
+	AbsoluteEnum,
+	IncrementalEnum,
+	AugmentedLagrangianREnum,
+	AugmentedLagrangianRhopEnum,
+	AugmentedLagrangianThetaEnum,
+	/*}}}*/
+	/*Grounding Line{{{*/
+	NoneEnum,
+	AggressiveMigrationEnum,
+	SoftMigrationEnum,
+	SubelementMigrationEnum,
+	SubelementMigration2Enum,
+	ContactEnum,
+	MaskGroundediceLevelsetEnum,
+	QmuMaskGroundediceLevelsetEnum,
+	/*}}}*/
+	/*Gauss{{{*/
+	GaussSegEnum,
+	GaussTriaEnum,
+	GaussTetraEnum,
+	GaussPentaEnum,
+	/*}}}*/
+	/*Solver{{{*/
+	FSSolverEnum,
+	/*}}}*/
+	/*Parameters{{{*/
+	AdjointEnum,
+	ColinearEnum,
+	ControlSteadyEnum,
+	FsetEnum,
+	Gradient1Enum,
+	Gradient2Enum,
+	Gradient3Enum,
+	GradientEnum,
+	GroundinglineMigrationEnum,
+	GsetEnum,
+	IndexEnum,
+	IndexedEnum,
+	IntersectEnum,
+	NodalEnum,
+	OldGradientEnum,
+	OutputFilePointerEnum,
+	OutputFileNameEnum,
+	LockFileNameEnum,
+	ToolkitsOptionsAnalysesEnum,
+	ToolkitsOptionsStringsEnum,
+	QmuErrNameEnum,
+	QmuInNameEnum,
+	QmuOutNameEnum,
+	RegularEnum,
+	ScaledEnum,
+	SeparateEnum,
+	SsetEnum,
+	VerboseEnum,
+	/*}}}*/
+	/*Interpolation {{{*/
+	TriangleInterpEnum,
+	BilinearInterpEnum,
+	NearestInterpEnum,
+	/*}}}*/
+	/*Coordinate Systems{{{*/
+	XYEnum,
+	XYZEnum,
+	/*}}}*/
+	/*Toolkits{{{*/
+	DenseEnum,
+	MpiDenseEnum,
+	MpiSparseEnum,
+	SeqEnum,
+	MpiEnum,
+	MumpsEnum,
+	GslEnum,
+	/*}}}*/
+	/*Options{{{*/
+	OptionEnum,
+	GenericOptionEnum,
+	OptionCellEnum,
+	OptionStructEnum,
+	/*}}}*/
+	/*Rheology law (move to Material) {{{*/
+	CuffeyEnum,
+	PatersonEnum,
+	ArrheniusEnum,
+	LliboutryDuvalEnum,
+	/*}}}*/
+	/*Levelset related enums (will be moved to appropriate place when finished){{{*/
+	TransientIslevelsetEnum,
+	ExtrapolationVariableEnum,
+	IceMaskNodeActivationEnum,
+	LevelsetfunctionSlopeXEnum,
+	LevelsetfunctionSlopeYEnum,
+	LevelsetfunctionPicardEnum,
+	/*}}}*/
+	MaximumNumberOfDefinitionsEnum
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumToStringx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/EnumToStringx.cpp	(revision 18231)
@@ -0,0 +1,735 @@
+/*
+* \file EnumToStringx.cpp:
+* \brief: output string associated with enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
+		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
+		case AutodiffNumDependentObjectsEnum : return "AutodiffNumDependentObjects";
+		case AutodiffDependentObjectNamesEnum : return "AutodiffDependentObjectNames";
+		case AutodiffDependentObjectTypesEnum : return "AutodiffDependentObjectTypes";
+		case AutodiffDependentObjectIndicesEnum : return "AutodiffDependentObjectIndices";
+		case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
+		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
+		case AutodiffNumIndependentObjectsEnum : return "AutodiffNumIndependentObjects";
+		case AutodiffIndependentObjectNamesEnum : return "AutodiffIndependentObjectNames";
+		case AutodiffIndependentObjectTypesEnum : return "AutodiffIndependentObjectTypes";
+		case AutodiffIndependentObjectsEnum : return "AutodiffIndependentObjects";
+		case AutodiffJacobianEnum : return "AutodiffJacobian";
+		case AutodiffXpEnum : return "AutodiffXp";
+		case AutodiffDriverEnum : return "AutodiffDriver";
+		case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
+		case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
+		case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
+		case AutodiffMassFluxSegmentsPresentEnum : return "AutodiffMassFluxSegmentsPresent";
+		case AutodiffKeepEnum : return "AutodiffKeep";
+		case AutodiffObufsizeEnum : return "AutodiffObufsize";
+		case AutodiffLbufsizeEnum : return "AutodiffLbufsize";
+		case AutodiffCbufsizeEnum : return "AutodiffCbufsize";
+		case AutodiffTbufsizeEnum : return "AutodiffTbufsize";
+		case AutodiffGcTriggerRatioEnum : return "AutodiffGcTriggerRatio";
+		case AutodiffGcTriggerMaxSizeEnum : return "AutodiffGcTriggerMaxSize";
+		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
+		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
+		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
+		case BasalforcingsEnum : return "Basalforcings";
+		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
+		case BasalforcingsGroundediceMeltingRateEnum : return "BasalforcingsGroundediceMeltingRate";
+		case BasalforcingsFloatingiceMeltingRateEnum : return "BasalforcingsFloatingiceMeltingRate";
+		case BasalforcingsDeepwaterMeltingRateEnum : return "BasalforcingsDeepwaterMeltingRate";
+		case BasalforcingsDeepwaterElevationEnum : return "BasalforcingsDeepwaterElevation";
+		case BasalforcingsUpperwaterElevationEnum : return "BasalforcingsUpperwaterElevation";
+		case FloatingMeltRateEnum : return "FloatingMeltRate";
+		case LinearFloatingMeltRateEnum : return "LinearFloatingMeltRate";
+		case BedEnum : return "Bed";
+		case BaseEnum : return "Base";
+		case ConstantsGEnum : return "ConstantsG";
+		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
+		case ConstantsYtsEnum : return "ConstantsYts";
+		case DependentObjectEnum : return "DependentObject";
+		case StressbalanceAbstolEnum : return "StressbalanceAbstol";
+		case StressbalanceIsnewtonEnum : return "StressbalanceIsnewton";
+		case StressbalanceMaxiterEnum : return "StressbalanceMaxiter";
+		case StressbalancePenaltyFactorEnum : return "StressbalancePenaltyFactor";
+		case StressbalanceReferentialEnum : return "StressbalanceReferential";
+		case StressbalanceReltolEnum : return "StressbalanceReltol";
+		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
+		case StressbalanceRequestedOutputsEnum : return "StressbalanceRequestedOutputs";
+		case StressbalanceRestolEnum : return "StressbalanceRestol";
+		case StressbalanceRiftPenaltyLockEnum : return "StressbalanceRiftPenaltyLock";
+		case StressbalanceRiftPenaltyThresholdEnum : return "StressbalanceRiftPenaltyThreshold";
+		case StressbalanceShelfDampeningEnum : return "StressbalanceShelfDampening";
+		case StressbalanceSpcvxEnum : return "StressbalanceSpcvx";
+		case StressbalanceSpcvyEnum : return "StressbalanceSpcvy";
+		case StressbalanceSpcvzEnum : return "StressbalanceSpcvz";
+		case StressbalanceFSreconditioningEnum : return "StressbalanceFSreconditioning";
+		case StressbalanceVertexPairingEnum : return "StressbalanceVertexPairing";
+		case StressbalanceViscosityOvershootEnum : return "StressbalanceViscosityOvershoot";
+		case LoadingforceXEnum : return "LoadingforceX";
+		case LoadingforceYEnum : return "LoadingforceY";
+		case LoadingforceZEnum : return "LoadingforceZ";
+		case FlowequationBorderSSAEnum : return "FlowequationBorderSSA";
+		case FlowequationBorderHOEnum : return "FlowequationBorderHO";
+		case FlowequationBorderFSEnum : return "FlowequationBorderFS";
+		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
+		case FlowequationIsSIAEnum : return "FlowequationIsSIA";
+		case FlowequationIsSSAEnum : return "FlowequationIsSSA";
+		case FlowequationIsL1L2Enum : return "FlowequationIsL1L2";
+		case FlowequationIsHOEnum : return "FlowequationIsHO";
+		case FlowequationIsFSEnum : return "FlowequationIsFS";
+		case FlowequationFeSSAEnum : return "FlowequationFeSSA";
+		case FlowequationFeHOEnum : return "FlowequationFeHO";
+		case FlowequationFeFSEnum : return "FlowequationFeFS";
+		case FlowequationVertexEquationEnum : return "FlowequationVertexEquation";
+		case FrictionCoefficientEnum : return "FrictionCoefficient";
+		case FrictionPEnum : return "FrictionP";
+		case FrictionQEnum : return "FrictionQ";
+		case FrictionMEnum : return "FrictionM";
+		case FrictionCEnum : return "FrictionC";
+		case FrictionLawEnum : return "FrictionLaw";
+		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
+		case HydrologyModelEnum : return "HydrologyModel";
+		case HydrologyshreveEnum : return "Hydrologyshreve";
+		case HydrologyshreveSpcwatercolumnEnum : return "HydrologyshreveSpcwatercolumn";
+		case HydrologyshreveStabilizationEnum : return "HydrologyshreveStabilization";
+		case HydrologydcEnum : return "Hydrologydc";
+		case SedimentHeadEnum : return "SedimentHead";
+		case SedimentHeadOldEnum : return "SedimentHeadOld";
+		case SedimentHeadResidualEnum : return "SedimentHeadResidual";
+		case EffectivePressureEnum : return "EffectivePressure";
+		case EplHeadEnum : return "EplHead";
+		case EplHeadOldEnum : return "EplHeadOld";
+		case EplHeadSlopeXEnum : return "EplHeadSlopeX";
+		case EplHeadSlopeYEnum : return "EplHeadSlopeY";
+		case HydrologydcMaxIterEnum : return "HydrologydcMaxIter";
+		case HydrologydcRelTolEnum : return "HydrologydcRelTol";
+		case HydrologydcSpcsedimentHeadEnum : return "HydrologydcSpcsedimentHead";
+		case HydrologydcSedimentCompressibilityEnum : return "HydrologydcSedimentCompressibility";
+		case HydrologydcSedimentPorosityEnum : return "HydrologydcSedimentPorosity";
+		case HydrologydcSedimentThicknessEnum : return "HydrologydcSedimentThickness";
+		case HydrologydcSedimentTransmitivityEnum : return "HydrologydcSedimentTransmitivity";
+		case HydrologydcWaterCompressibilityEnum : return "HydrologydcWaterCompressibility";
+		case HydrologydcSpceplHeadEnum : return "HydrologydcSpceplHead";
+		case HydrologydcMaskEplactiveNodeEnum : return "HydrologydcMaskEplactiveNode";
+		case HydrologydcMaskEplactiveEltEnum : return "HydrologydcMaskEplactiveElt";
+		case HydrologydcEplCompressibilityEnum : return "HydrologydcEplCompressibility";
+		case HydrologydcEplPorosityEnum : return "HydrologydcEplPorosity";
+		case HydrologydcEplInitialThicknessEnum : return "HydrologydcEplInitialThickness";
+		case HydrologydcEplMaxThicknessEnum : return "HydrologydcEplMaxThickness";
+		case HydrologydcEplThicknessEnum : return "HydrologydcEplThickness";
+		case HydrologydcEplThicknessOldEnum : return "HydrologydcEplThicknessOld";
+		case HydrologydcEplConductivityEnum : return "HydrologydcEplConductivity";
+		case HydrologydcIsefficientlayerEnum : return "HydrologydcIsefficientlayer";
+		case HydrologydcSedimentlimitFlagEnum : return "HydrologydcSedimentlimitFlag";
+		case HydrologydcSedimentlimitEnum : return "HydrologydcSedimentlimit";
+		case HydrologydcTransferFlagEnum : return "HydrologydcTransferFlag";
+		case HydrologydcLeakageFactorEnum : return "HydrologydcLeakageFactor";
+		case HydrologydcPenaltyFactorEnum : return "HydrologydcPenaltyFactor";
+		case HydrologydcPenaltyLockEnum : return "HydrologydcPenaltyLock";
+		case HydrologydcBasalMoulinInputEnum : return "HydrologydcBasalMoulinInput";
+		case HydrologyLayerEnum : return "HydrologyLayer";
+		case HydrologySedimentEnum : return "HydrologySediment";
+		case HydrologyEfficientEnum : return "HydrologyEfficient";
+		case HydrologySedimentKmaxEnum : return "HydrologySedimentKmax";
+		case IndependentObjectEnum : return "IndependentObject";
+		case InversionControlParametersEnum : return "InversionControlParameters";
+		case InversionCostFunctionThresholdEnum : return "InversionCostFunctionThreshold";
+		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
+		case InversionCostFunctionsEnum : return "InversionCostFunctions";
+		case InversionGradientScalingEnum : return "InversionGradientScaling";
+		case InversionIscontrolEnum : return "InversionIscontrol";
+		case InversionTypeEnum : return "InversionType";
+		case InversionIncompleteAdjointEnum : return "InversionIncompleteAdjoint";
+		case InversionMaxParametersEnum : return "InversionMaxParameters";
+		case InversionMaxiterPerStepEnum : return "InversionMaxiterPerStep";
+		case InversionMaxiterEnum : return "InversionMaxiter";
+		case InversionMaxstepsEnum : return "InversionMaxsteps";
+		case InversionFatolEnum : return "InversionFatol";
+		case InversionFrtolEnum : return "InversionFrtol";
+		case InversionGatolEnum : return "InversionGatol";
+		case InversionGrtolEnum : return "InversionGrtol";
+		case InversionGttolEnum : return "InversionGttol";
+		case InversionAlgorithmEnum : return "InversionAlgorithm";
+		case InversionMinParametersEnum : return "InversionMinParameters";
+		case InversionNstepsEnum : return "InversionNsteps";
+		case InversionDxminEnum : return "InversionDxmin";
+		case InversionNumControlParametersEnum : return "InversionNumControlParameters";
+		case InversionNumCostFunctionsEnum : return "InversionNumCostFunctions";
+		case InversionStepThresholdEnum : return "InversionStepThreshold";
+		case InversionThicknessObsEnum : return "InversionThicknessObs";
+		case InversionVxObsEnum : return "InversionVxObs";
+		case InversionVyObsEnum : return "InversionVyObs";
+		case InversionVzObsEnum : return "InversionVzObs";
+		case MaskIceLevelsetEnum : return "MaskIceLevelset";
+		case QmuMaskIceLevelsetEnum : return "QmuMaskIceLevelset";
+		case MaterialsBetaEnum : return "MaterialsBeta";
+		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
+		case MaterialsLatentheatEnum : return "MaterialsLatentheat";
+		case MaterialsMeltingpointEnum : return "MaterialsMeltingpoint";
+		case MaterialsMixedLayerCapacityEnum : return "MaterialsMixedLayerCapacity";
+		case MaterialsRheologyBEnum : return "MaterialsRheologyB";
+		case MaterialsRheologyBbarEnum : return "MaterialsRheologyBbar";
+		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
+		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
+		case DamageIsdamageEnum : return "DamageIsdamage";
+		case DamageDEnum : return "DamageD";
+		case DamageFEnum : return "DamageF";
+		case QmuDamageDEnum : return "QmuDamageD";
+		case DamageDbarEnum : return "DamageDbar";
+		case DamageLawEnum : return "DamageLaw";
+		case DamageC1Enum : return "DamageC1";
+		case DamageC2Enum : return "DamageC2";
+		case DamageC3Enum : return "DamageC3";
+		case DamageC4Enum : return "DamageC4";
+		case DamageElementinterpEnum : return "DamageElementinterp";
+		case DamageHealingEnum : return "DamageHealing";
+		case DamageStressThresholdEnum : return "DamageStressThreshold";
+		case DamageStabilizationEnum : return "DamageStabilization";
+		case DamagePenaltyThresholdEnum : return "DamagePenaltyThreshold";
+		case DamagePenaltyLockEnum : return "DamagePenaltyLock";
+		case DamagePenaltyFactorEnum : return "DamagePenaltyFactor";
+		case DamageMaxiterEnum : return "DamageMaxiter";
+		case DamageSpcdamageEnum : return "DamageSpcdamage";
+		case DamageMaxDamageEnum : return "DamageMaxDamage";
+		case DamageEquivStressEnum : return "DamageEquivStress";
+		case DamageEvolutionNumRequestedOutputsEnum : return "DamageEvolutionNumRequestedOutputs";
+		case DamageEvolutionRequestedOutputsEnum : return "DamageEvolutionRequestedOutputs";
+		case NewDamageEnum : return "NewDamage";
+		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
+		case MaterialsRhoSeawaterEnum : return "MaterialsRhoSeawater";
+		case MaterialsRhoFreshwaterEnum : return "MaterialsRhoFreshwater";
+		case MaterialsMuWaterEnum : return "MaterialsMuWater";
+		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
+		case MaterialsThermalconductivityEnum : return "MaterialsThermalconductivity";
+		case MaterialsTemperateiceconductivityEnum : return "MaterialsTemperateiceconductivity";
+		case MaterialsLithosphereShearModulusEnum : return "MaterialsLithosphereShearModulus";
+		case MaterialsLithosphereDensityEnum : return "MaterialsLithosphereDensity";
+		case MaterialsMantleShearModulusEnum : return "MaterialsMantleShearModulus";
+		case MaterialsMantleDensityEnum : return "MaterialsMantleDensity";
+		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
+		case MeshElements2dEnum : return "MeshElements2d";
+		case MeshElementsEnum : return "MeshElements";
+		case MeshLowerelementsEnum : return "MeshLowerelements";
+		case MeshNumberofelements2dEnum : return "MeshNumberofelements2d";
+		case MeshNumberofelementsEnum : return "MeshNumberofelements";
+		case MeshNumberoflayersEnum : return "MeshNumberoflayers";
+		case MeshNumberofvertices2dEnum : return "MeshNumberofvertices2d";
+		case MeshNumberofverticesEnum : return "MeshNumberofvertices";
+		case MeshUpperelementsEnum : return "MeshUpperelements";
+		case MeshVertexonbaseEnum : return "MeshVertexonbase";
+		case MeshVertexonsurfaceEnum : return "MeshVertexonsurface";
+		case MeshVertexonboundaryEnum : return "MeshVertexonboundary";
+		case MeshXEnum : return "MeshX";
+		case MeshYEnum : return "MeshY";
+		case MeshZEnum : return "MeshZ";
+		case MeshElementtypeEnum : return "MeshElementtype";
+		case DomainTypeEnum : return "DomainType";
+		case DomainDimensionEnum : return "DomainDimension";
+		case Domain2DhorizontalEnum : return "Domain2Dhorizontal";
+		case Domain2DverticalEnum : return "Domain2Dvertical";
+		case Domain3DEnum : return "Domain3D";
+		case MiscellaneousNameEnum : return "MiscellaneousName";
+		case MasstransportHydrostaticAdjustmentEnum : return "MasstransportHydrostaticAdjustment";
+		case MasstransportIsfreesurfaceEnum : return "MasstransportIsfreesurface";
+		case MasstransportMinThicknessEnum : return "MasstransportMinThickness";
+		case MasstransportPenaltyFactorEnum : return "MasstransportPenaltyFactor";
+		case MasstransportSpcthicknessEnum : return "MasstransportSpcthickness";
+		case MasstransportCalvingrateEnum : return "MasstransportCalvingrate";
+		case MasstransportStabilizationEnum : return "MasstransportStabilization";
+		case MasstransportVertexPairingEnum : return "MasstransportVertexPairing";
+		case MasstransportNumRequestedOutputsEnum : return "MasstransportNumRequestedOutputs";
+		case MasstransportRequestedOutputsEnum : return "MasstransportRequestedOutputs";
+		case QmuIsdakotaEnum : return "QmuIsdakota";
+		case MassFluxSegmentsEnum : return "MassFluxSegments";
+		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
+		case QmuMassFluxSegmentsPresentEnum : return "QmuMassFluxSegmentsPresent";
+		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
+		case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
+		case QmuPartitionEnum : return "QmuPartition";
+		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
+		case QmuVariabledescriptorsEnum : return "QmuVariabledescriptors";
+		case QmuMaterialsRheologyBEnum : return "QmuMaterialsRheologyB";
+		case RiftsNumriftsEnum : return "RiftsNumrifts";
+		case RiftsRiftstructEnum : return "RiftsRiftstruct";
+		case SettingsResultsOnNodesEnum : return "SettingsResultsOnNodes";
+		case SettingsIoGatherEnum : return "SettingsIoGather";
+		case SettingsLowmemEnum : return "SettingsLowmem";
+		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
+		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
+		case DebugProfilingEnum : return "DebugProfiling";
+		case ProfilingCurrentMemEnum : return "ProfilingCurrentMem";
+		case ProfilingCurrentFlopsEnum : return "ProfilingCurrentFlops";
+		case ProfilingSolutionTimeEnum : return "ProfilingSolutionTime";
+		case MaxIterationConvergenceFlagEnum : return "MaxIterationConvergenceFlag";
+		case SteadystateMaxiterEnum : return "SteadystateMaxiter";
+		case SteadystateNumRequestedOutputsEnum : return "SteadystateNumRequestedOutputs";
+		case SteadystateReltolEnum : return "SteadystateReltol";
+		case SteadystateRequestedOutputsEnum : return "SteadystateRequestedOutputs";
+		case SurfaceEnum : return "Surface";
+		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
+		case ThermalIsdynamicbasalspcEnum : return "ThermalIsdynamicbasalspc";
+		case ThermalMaxiterEnum : return "ThermalMaxiter";
+		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
+		case ThermalPenaltyLockEnum : return "ThermalPenaltyLock";
+		case ThermalPenaltyThresholdEnum : return "ThermalPenaltyThreshold";
+		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
+		case ThermalStabilizationEnum : return "ThermalStabilization";
+		case ThermalNumRequestedOutputsEnum : return "ThermalNumRequestedOutputs";
+		case ThermalRequestedOutputsEnum : return "ThermalRequestedOutputs";
+		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
+		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
+		case ThicknessEnum : return "Thickness";
+		case TimesteppingStartTimeEnum : return "TimesteppingStartTime";
+		case TimesteppingFinalTimeEnum : return "TimesteppingFinalTime";
+		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
+		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
+		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
+		case TimesteppingInterpForcingsEnum : return "TimesteppingInterpForcings";
+		case TransientIsstressbalanceEnum : return "TransientIsstressbalance";
+		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
+		case TransientIsmasstransportEnum : return "TransientIsmasstransport";
+		case TransientIsthermalEnum : return "TransientIsthermal";
+		case TransientIsgiaEnum : return "TransientIsgia";
+		case TransientIsdamageevolutionEnum : return "TransientIsdamageevolution";
+		case TransientIshydrologyEnum : return "TransientIshydrology";
+		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
+		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
+		case PotentialEnum : return "Potential";
+		case BalancethicknessSpcpotentialEnum : return "BalancethicknessSpcpotential";
+		case BalancethicknessApparentMassbalanceEnum : return "BalancethicknessApparentMassbalance";
+		case Balancethickness2MisfitEnum : return "Balancethickness2Misfit";
+		case BalancethicknessNuxEnum : return "BalancethicknessNux";
+		case BalancethicknessNuyEnum : return "BalancethicknessNuy";
+		case BalancethicknessVxObsEnum : return "BalancethicknessVxObs";
+		case BalancethicknessVyObsEnum : return "BalancethicknessVyObs";
+		case BalancethicknessThicknessObsEnum : return "BalancethicknessThicknessObs";
+		case SurfaceforcingsEnum : return "Surfaceforcings";
+		case SMBEnum : return "SMB";
+		case SurfaceforcingsMassBalanceEnum : return "SurfaceforcingsMassBalance";
+		case SMBpddEnum : return "SMBpdd";
+		case SurfaceforcingsDelta18oEnum : return "SurfaceforcingsDelta18o";
+		case SurfaceforcingsDelta18oSurfaceEnum : return "SurfaceforcingsDelta18oSurface";
+		case SurfaceforcingsIsdelta18oEnum : return "SurfaceforcingsIsdelta18o";
+		case SurfaceforcingsPrecipitationsPresentdayEnum : return "SurfaceforcingsPrecipitationsPresentday";
+		case SurfaceforcingsTemperaturesPresentdayEnum : return "SurfaceforcingsTemperaturesPresentday";
+		case SurfaceforcingsTemperaturesLgmEnum : return "SurfaceforcingsTemperaturesLgm";
+		case SurfaceforcingsPrecipitationEnum : return "SurfaceforcingsPrecipitation";
+		case SurfaceforcingsDesfacEnum : return "SurfaceforcingsDesfac";
+		case SurfaceforcingsS0pEnum : return "SurfaceforcingsS0p";
+		case SMBgradientsEnum : return "SMBgradients";
+		case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
+		case SurfaceforcingsHrefEnum : return "SurfaceforcingsHref";
+		case SurfaceforcingsSmbrefEnum : return "SurfaceforcingsSmbref";
+		case SurfaceforcingsBPosEnum : return "SurfaceforcingsBPos";
+		case SurfaceforcingsBNegEnum : return "SurfaceforcingsBNeg";
+		case SMBhenningEnum : return "SMBhenning";
+		case SMBcomponentsEnum : return "SMBcomponents";
+		case SurfaceforcingsAccumulationEnum : return "SurfaceforcingsAccumulation";
+		case SurfaceforcingsEvaporationEnum : return "SurfaceforcingsEvaporation";
+		case SurfaceforcingsRunoffEnum : return "SurfaceforcingsRunoff";
+		case SMBmeltcomponentsEnum : return "SMBmeltcomponents";
+		case SurfaceforcingsMeltEnum : return "SurfaceforcingsMelt";
+		case SurfaceforcingsRefreezeEnum : return "SurfaceforcingsRefreeze";
+		case SurfaceforcingsIspddEnum : return "SurfaceforcingsIspdd";
+		case SurfaceforcingsIssmbgradientsEnum : return "SurfaceforcingsIssmbgradients";
+		case SolutionTypeEnum : return "SolutionType";
+		case AnalysisTypeEnum : return "AnalysisType";
+		case ConfigurationTypeEnum : return "ConfigurationType";
+		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
+		case AdjointBalancethickness2AnalysisEnum : return "AdjointBalancethickness2Analysis";
+		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
+		case AnalysisCounterEnum : return "AnalysisCounter";
+		case DefaultAnalysisEnum : return "DefaultAnalysis";
+		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
+		case BalancethicknessSolutionEnum : return "BalancethicknessSolution";
+		case Balancethickness2AnalysisEnum : return "Balancethickness2Analysis";
+		case Balancethickness2SolutionEnum : return "Balancethickness2Solution";
+		case BalancethicknessSoftAnalysisEnum : return "BalancethicknessSoftAnalysis";
+		case BalancethicknessSoftSolutionEnum : return "BalancethicknessSoftSolution";
+		case BalancevelocityAnalysisEnum : return "BalancevelocityAnalysis";
+		case BalancevelocitySolutionEnum : return "BalancevelocitySolution";
+		case L2ProjectionEPLAnalysisEnum : return "L2ProjectionEPLAnalysis";
+		case L2ProjectionBaseAnalysisEnum : return "L2ProjectionBaseAnalysis";
+		case BedSlopeSolutionEnum : return "BedSlopeSolution";
+		case DamageEvolutionSolutionEnum : return "DamageEvolutionSolution";
+		case DamageEvolutionAnalysisEnum : return "DamageEvolutionAnalysis";
+		case StressbalanceAnalysisEnum : return "StressbalanceAnalysis";
+		case StressbalanceSIAAnalysisEnum : return "StressbalanceSIAAnalysis";
+		case StressbalanceSolutionEnum : return "StressbalanceSolution";
+		case StressbalanceVerticalAnalysisEnum : return "StressbalanceVerticalAnalysis";
+		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
+		case FlaimAnalysisEnum : return "FlaimAnalysis";
+		case FlaimSolutionEnum : return "FlaimSolution";
+		case HydrologyShreveAnalysisEnum : return "HydrologyShreveAnalysis";
+		case HydrologyDCInefficientAnalysisEnum : return "HydrologyDCInefficientAnalysis";
+		case HydrologyDCEfficientAnalysisEnum : return "HydrologyDCEfficientAnalysis";
+		case HydrologySolutionEnum : return "HydrologySolution";
+		case MeltingAnalysisEnum : return "MeltingAnalysis";
+		case MasstransportAnalysisEnum : return "MasstransportAnalysis";
+		case MasstransportSolutionEnum : return "MasstransportSolution";
+		case FreeSurfaceBaseAnalysisEnum : return "FreeSurfaceBaseAnalysis";
+		case FreeSurfaceTopAnalysisEnum : return "FreeSurfaceTopAnalysis";
+		case SurfaceNormalVelocityEnum : return "SurfaceNormalVelocity";
+		case ExtrudeFromBaseAnalysisEnum : return "ExtrudeFromBaseAnalysis";
+		case ExtrudeFromTopAnalysisEnum : return "ExtrudeFromTopAnalysis";
+		case DepthAverageAnalysisEnum : return "DepthAverageAnalysis";
+		case SteadystateSolutionEnum : return "SteadystateSolution";
+		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
+		case SmoothedSurfaceSlopeXAnalysisEnum : return "SmoothedSurfaceSlopeXAnalysis";
+		case SmoothedSurfaceSlopeYAnalysisEnum : return "SmoothedSurfaceSlopeYAnalysis";
+		case ThermalAnalysisEnum : return "ThermalAnalysis";
+		case ThermalSolutionEnum : return "ThermalSolution";
+		case TransientSolutionEnum : return "TransientSolution";
+		case UzawaPressureAnalysisEnum : return "UzawaPressureAnalysis";
+		case GiaSolutionEnum : return "GiaSolution";
+		case GiaAnalysisEnum : return "GiaAnalysis";
+		case MeshdeformationSolutionEnum : return "MeshdeformationSolution";
+		case MeshdeformationAnalysisEnum : return "MeshdeformationAnalysis";
+		case LevelsetAnalysisEnum : return "LevelsetAnalysis";
+		case ExtrapolationAnalysisEnum : return "ExtrapolationAnalysis";
+		case LsfReinitializationAnalysisEnum : return "LsfReinitializationAnalysis";
+		case ApproximationEnum : return "Approximation";
+		case NoneApproximationEnum : return "NoneApproximation";
+		case SIAApproximationEnum : return "SIAApproximation";
+		case SSAApproximationEnum : return "SSAApproximation";
+		case SSAHOApproximationEnum : return "SSAHOApproximation";
+		case SSAFSApproximationEnum : return "SSAFSApproximation";
+		case L1L2ApproximationEnum : return "L1L2Approximation";
+		case HOApproximationEnum : return "HOApproximation";
+		case HOFSApproximationEnum : return "HOFSApproximation";
+		case FSApproximationEnum : return "FSApproximation";
+		case FSvelocityEnum : return "FSvelocity";
+		case FSpressureEnum : return "FSpressure";
+		case ConstraintsEnum : return "Constraints";
+		case LoadsEnum : return "Loads";
+		case MaterialsEnum : return "Materials";
+		case NodesEnum : return "Nodes";
+		case ContoursEnum : return "Contours";
+		case ParametersEnum : return "Parameters";
+		case VerticesEnum : return "Vertices";
+		case ResultsEnum : return "Results";
+		case GenericParamEnum : return "GenericParam";
+		case AdolcParamEnum : return "AdolcParam";
+		case BoolInputEnum : return "BoolInput";
+		case BoolParamEnum : return "BoolParam";
+		case ContourEnum : return "Contour";
+		case ControlInputEnum : return "ControlInput";
+		case DatasetInputEnum : return "DatasetInput";
+		case DoubleInputEnum : return "DoubleInput";
+		case DataSetParamEnum : return "DataSetParam";
+		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
+		case DoubleMatParamEnum : return "DoubleMatParam";
+		case DoubleParamEnum : return "DoubleParam";
+		case DoubleVecParamEnum : return "DoubleVecParam";
+		case ElementEnum : return "Element";
+		case ExternalResultEnum : return "ExternalResult";
+		case FileParamEnum : return "FileParam";
+		case InputEnum : return "Input";
+		case IntInputEnum : return "IntInput";
+		case InputToExtrudeEnum : return "InputToExtrude";
+		case InputToL2ProjectEnum : return "InputToL2Project";
+		case InputToDepthaverageEnum : return "InputToDepthaverage";
+		case IntParamEnum : return "IntParam";
+		case IntVecParamEnum : return "IntVecParam";
+		case TransientParamEnum : return "TransientParam";
+		case MaticeEnum : return "Matice";
+		case MatdamageiceEnum : return "Matdamageice";
+		case MatparEnum : return "Matpar";
+		case NodeEnum : return "Node";
+		case NumericalfluxEnum : return "Numericalflux";
+		case NumericalfluxTypeEnum : return "NumericalfluxType";
+		case ParamEnum : return "Param";
+		case PengridEnum : return "Pengrid";
+		case PenpairEnum : return "Penpair";
+		case ProfilerEnum : return "Profiler";
+		case MatrixParamEnum : return "MatrixParam";
+		case NodeSIdEnum : return "NodeSId";
+		case VectorParamEnum : return "VectorParam";
+		case RiftfrontEnum : return "Riftfront";
+		case RiftfrontTypeEnum : return "RiftfrontType";
+		case SegmentEnum : return "Segment";
+		case SegmentRiftfrontEnum : return "SegmentRiftfront";
+		case SpcDynamicEnum : return "SpcDynamic";
+		case SpcStaticEnum : return "SpcStatic";
+		case SpcTransientEnum : return "SpcTransient";
+		case StringArrayParamEnum : return "StringArrayParam";
+		case StringParamEnum : return "StringParam";
+		case SegEnum : return "Seg";
+		case SegInputEnum : return "SegInput";
+		case TriaEnum : return "Tria";
+		case TriaInputEnum : return "TriaInput";
+		case TetraEnum : return "Tetra";
+		case TetraInputEnum : return "TetraInput";
+		case PentaEnum : return "Penta";
+		case PentaInputEnum : return "PentaInput";
+		case VertexEnum : return "Vertex";
+		case VertexPIdEnum : return "VertexPId";
+		case VertexSIdEnum : return "VertexSId";
+		case AirEnum : return "Air";
+		case IceEnum : return "Ice";
+		case MelangeEnum : return "Melange";
+		case WaterEnum : return "Water";
+		case ClosedEnum : return "Closed";
+		case FreeEnum : return "Free";
+		case OpenEnum : return "Open";
+		case AdjointpEnum : return "Adjointp";
+		case AdjointxEnum : return "Adjointx";
+		case AdjointyEnum : return "Adjointy";
+		case AdjointzEnum : return "Adjointz";
+		case BalancethicknessMisfitEnum : return "BalancethicknessMisfit";
+		case BedSlopeXEnum : return "BedSlopeX";
+		case BedSlopeYEnum : return "BedSlopeY";
+		case BoundaryEnum : return "Boundary";
+		case ConvergedEnum : return "Converged";
+		case FillEnum : return "Fill";
+		case FractionIncrementEnum : return "FractionIncrement";
+		case FrictionEnum : return "Friction";
+		case InternalEnum : return "Internal";
+		case MassFluxEnum : return "MassFlux";
+		case MeltingOffsetEnum : return "MeltingOffset";
+		case MisfitEnum : return "Misfit";
+		case PressureEnum : return "Pressure";
+		case PressurePicardEnum : return "PressurePicard";
+		case QmuPressureEnum : return "QmuPressure";
+		case QmuVxEnum : return "QmuVx";
+		case QmuVyEnum : return "QmuVy";
+		case QmuVzEnum : return "QmuVz";
+		case QmuThicknessEnum : return "QmuThickness";
+		case QmuBaseEnum : return "QmuBase";
+		case QmuSurfaceEnum : return "QmuSurface";
+		case QmuMeltingEnum : return "QmuMelting";
+		case QmuVxMeshEnum : return "QmuVxMesh";
+		case QmuVyMeshEnum : return "QmuVyMesh";
+		case QmuVzMeshEnum : return "QmuVzMesh";
+		case AndroidFrictionCoefficientEnum : return "AndroidFrictionCoefficient";
+		case ResetPenaltiesEnum : return "ResetPenalties";
+		case SegmentOnIceShelfEnum : return "SegmentOnIceShelf";
+		case SurfaceAbsVelMisfitEnum : return "SurfaceAbsVelMisfit";
+		case SurfaceAreaEnum : return "SurfaceArea";
+		case SurfaceAverageVelMisfitEnum : return "SurfaceAverageVelMisfit";
+		case SurfaceLogVelMisfitEnum : return "SurfaceLogVelMisfit";
+		case SurfaceLogVxVyMisfitEnum : return "SurfaceLogVxVyMisfit";
+		case SurfaceRelVelMisfitEnum : return "SurfaceRelVelMisfit";
+		case SurfaceSlopeXEnum : return "SurfaceSlopeX";
+		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
+		case TemperatureEnum : return "Temperature";
+		case TemperaturePicardEnum : return "TemperaturePicard";
+		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
+		case VelEnum : return "Vel";
+		case VelocityEnum : return "Velocity";
+		case VxAverageEnum : return "VxAverage";
+		case VxEnum : return "Vx";
+		case VxPicardEnum : return "VxPicard";
+		case VyAverageEnum : return "VyAverage";
+		case VyEnum : return "Vy";
+		case VyPicardEnum : return "VyPicard";
+		case VzEnum : return "Vz";
+		case VzSSAEnum : return "VzSSA";
+		case VzHOEnum : return "VzHO";
+		case VzPicardEnum : return "VzPicard";
+		case VzFSEnum : return "VzFS";
+		case VxMeshEnum : return "VxMesh";
+		case VyMeshEnum : return "VyMesh";
+		case VzMeshEnum : return "VzMesh";
+		case EnthalpyEnum : return "Enthalpy";
+		case EnthalpyPicardEnum : return "EnthalpyPicard";
+		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
+		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
+		case IntMatParamEnum : return "IntMatParam";
+		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
+		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
+		case TransientInputEnum : return "TransientInput";
+		case WaterfractionEnum : return "Waterfraction";
+		case WatercolumnEnum : return "Watercolumn";
+		case BasalFrictionEnum : return "BasalFriction";
+		case ViscousHeatingEnum : return "ViscousHeating";
+		case QmuTemperatureEnum : return "QmuTemperature";
+		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
+		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
+		case SigmaNNEnum : return "SigmaNN";
+		case StressTensorEnum : return "StressTensor";
+		case StressTensorxxEnum : return "StressTensorxx";
+		case StressTensorxyEnum : return "StressTensorxy";
+		case StressTensorxzEnum : return "StressTensorxz";
+		case StressTensoryyEnum : return "StressTensoryy";
+		case StressTensoryzEnum : return "StressTensoryz";
+		case StressTensorzzEnum : return "StressTensorzz";
+		case DeviatoricStressEnum : return "DeviatoricStress";
+		case DeviatoricStressxxEnum : return "DeviatoricStressxx";
+		case DeviatoricStressxyEnum : return "DeviatoricStressxy";
+		case DeviatoricStressxzEnum : return "DeviatoricStressxz";
+		case DeviatoricStressyyEnum : return "DeviatoricStressyy";
+		case DeviatoricStressyzEnum : return "DeviatoricStressyz";
+		case DeviatoricStresszzEnum : return "DeviatoricStresszz";
+		case StrainRateEnum : return "StrainRate";
+		case StrainRatexxEnum : return "StrainRatexx";
+		case StrainRatexyEnum : return "StrainRatexy";
+		case StrainRatexzEnum : return "StrainRatexz";
+		case StrainRateyyEnum : return "StrainRateyy";
+		case StrainRateyzEnum : return "StrainRateyz";
+		case StrainRatezzEnum : return "StrainRatezz";
+		case DivergenceEnum : return "Divergence";
+		case GiaCrossSectionShapeEnum : return "GiaCrossSectionShape";
+		case GiadWdtEnum : return "GiadWdt";
+		case GiaWEnum : return "GiaW";
+		case P0Enum : return "P0";
+		case P1Enum : return "P1";
+		case P1DGEnum : return "P1DG";
+		case P1bubbleEnum : return "P1bubble";
+		case P1bubblecondensedEnum : return "P1bubblecondensed";
+		case P2Enum : return "P2";
+		case P2bubbleEnum : return "P2bubble";
+		case P2bubblecondensedEnum : return "P2bubblecondensed";
+		case P2xP1Enum : return "P2xP1";
+		case P1xP2Enum : return "P1xP2";
+		case P1xP3Enum : return "P1xP3";
+		case P2xP4Enum : return "P2xP4";
+		case P1P1Enum : return "P1P1";
+		case P1P1GLSEnum : return "P1P1GLS";
+		case MINIEnum : return "MINI";
+		case MINIcondensedEnum : return "MINIcondensed";
+		case TaylorHoodEnum : return "TaylorHood";
+		case LATaylorHoodEnum : return "LATaylorHood";
+		case XTaylorHoodEnum : return "XTaylorHood";
+		case OneLayerP4zEnum : return "OneLayerP4z";
+		case CrouzeixRaviartEnum : return "CrouzeixRaviart";
+		case SaveResultsEnum : return "SaveResults";
+		case BoolExternalResultEnum : return "BoolExternalResult";
+		case DoubleExternalResultEnum : return "DoubleExternalResult";
+		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
+		case IntExternalResultEnum : return "IntExternalResult";
+		case JEnum : return "J";
+		case StringExternalResultEnum : return "StringExternalResult";
+		case StepEnum : return "Step";
+		case TimeEnum : return "Time";
+		case WaterColumnOldEnum : return "WaterColumnOld";
+		case OutputdefinitionEnum : return "Outputdefinition";
+		case OutputdefinitionListEnum : return "OutputdefinitionList";
+		case MassfluxatgateEnum : return "Massfluxatgate";
+		case MassfluxatgateNameEnum : return "MassfluxatgateName";
+		case MassfluxatgateSegmentsEnum : return "MassfluxatgateSegments";
+		case MisfitNameEnum : return "MisfitName";
+		case MisfitModelEnumEnum : return "MisfitModelEnum";
+		case MisfitObservationEnum : return "MisfitObservation";
+		case MisfitObservationEnumEnum : return "MisfitObservationEnum";
+		case MisfitTimeinterpolationEnum : return "MisfitTimeinterpolation";
+		case MisfitWeightsEnum : return "MisfitWeights";
+		case MisfitWeightsEnumEnum : return "MisfitWeightsEnum";
+		case SurfaceObservationEnum : return "SurfaceObservation";
+		case WeightsSurfaceObservationEnum : return "WeightsSurfaceObservation";
+		case MinVelEnum : return "MinVel";
+		case MaxVelEnum : return "MaxVel";
+		case MinVxEnum : return "MinVx";
+		case MaxVxEnum : return "MaxVx";
+		case MaxAbsVxEnum : return "MaxAbsVx";
+		case MinVyEnum : return "MinVy";
+		case MaxVyEnum : return "MaxVy";
+		case MaxAbsVyEnum : return "MaxAbsVy";
+		case MinVzEnum : return "MinVz";
+		case MaxVzEnum : return "MaxVz";
+		case MaxAbsVzEnum : return "MaxAbsVz";
+		case IceVolumeEnum : return "IceVolume";
+		case IceVolumeAboveFloatationEnum : return "IceVolumeAboveFloatation";
+		case TotalSmbEnum : return "TotalSmb";
+		case AbsoluteEnum : return "Absolute";
+		case IncrementalEnum : return "Incremental";
+		case AugmentedLagrangianREnum : return "AugmentedLagrangianR";
+		case AugmentedLagrangianRhopEnum : return "AugmentedLagrangianRhop";
+		case AugmentedLagrangianThetaEnum : return "AugmentedLagrangianTheta";
+		case NoneEnum : return "None";
+		case AggressiveMigrationEnum : return "AggressiveMigration";
+		case SoftMigrationEnum : return "SoftMigration";
+		case SubelementMigrationEnum : return "SubelementMigration";
+		case SubelementMigration2Enum : return "SubelementMigration2";
+		case ContactEnum : return "Contact";
+		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
+		case QmuMaskGroundediceLevelsetEnum : return "QmuMaskGroundediceLevelset";
+		case GaussSegEnum : return "GaussSeg";
+		case GaussTriaEnum : return "GaussTria";
+		case GaussTetraEnum : return "GaussTetra";
+		case GaussPentaEnum : return "GaussPenta";
+		case FSSolverEnum : return "FSSolver";
+		case AdjointEnum : return "Adjoint";
+		case ColinearEnum : return "Colinear";
+		case ControlSteadyEnum : return "ControlSteady";
+		case FsetEnum : return "Fset";
+		case Gradient1Enum : return "Gradient1";
+		case Gradient2Enum : return "Gradient2";
+		case Gradient3Enum : return "Gradient3";
+		case GradientEnum : return "Gradient";
+		case GroundinglineMigrationEnum : return "GroundinglineMigration";
+		case GsetEnum : return "Gset";
+		case IndexEnum : return "Index";
+		case IndexedEnum : return "Indexed";
+		case IntersectEnum : return "Intersect";
+		case NodalEnum : return "Nodal";
+		case OldGradientEnum : return "OldGradient";
+		case OutputFilePointerEnum : return "OutputFilePointer";
+		case OutputFileNameEnum : return "OutputFileName";
+		case LockFileNameEnum : return "LockFileName";
+		case ToolkitsOptionsAnalysesEnum : return "ToolkitsOptionsAnalyses";
+		case ToolkitsOptionsStringsEnum : return "ToolkitsOptionsStrings";
+		case QmuErrNameEnum : return "QmuErrName";
+		case QmuInNameEnum : return "QmuInName";
+		case QmuOutNameEnum : return "QmuOutName";
+		case RegularEnum : return "Regular";
+		case ScaledEnum : return "Scaled";
+		case SeparateEnum : return "Separate";
+		case SsetEnum : return "Sset";
+		case VerboseEnum : return "Verbose";
+		case TriangleInterpEnum : return "TriangleInterp";
+		case BilinearInterpEnum : return "BilinearInterp";
+		case NearestInterpEnum : return "NearestInterp";
+		case XYEnum : return "XY";
+		case XYZEnum : return "XYZ";
+		case DenseEnum : return "Dense";
+		case MpiDenseEnum : return "MpiDense";
+		case MpiSparseEnum : return "MpiSparse";
+		case SeqEnum : return "Seq";
+		case MpiEnum : return "Mpi";
+		case MumpsEnum : return "Mumps";
+		case GslEnum : return "Gsl";
+		case OptionEnum : return "Option";
+		case GenericOptionEnum : return "GenericOption";
+		case OptionCellEnum : return "OptionCell";
+		case OptionStructEnum : return "OptionStruct";
+		case CuffeyEnum : return "Cuffey";
+		case PatersonEnum : return "Paterson";
+		case ArrheniusEnum : return "Arrhenius";
+		case LliboutryDuvalEnum : return "LliboutryDuval";
+		case TransientIslevelsetEnum : return "TransientIslevelset";
+		case ExtrapolationVariableEnum : return "ExtrapolationVariable";
+		case IceMaskNodeActivationEnum : return "IceMaskNodeActivation";
+		case LevelsetfunctionSlopeXEnum : return "LevelsetfunctionSlopeX";
+		case LevelsetfunctionSlopeYEnum : return "LevelsetfunctionSlopeY";
+		case LevelsetfunctionPicardEnum : return "LevelsetfunctionPicard";
+		case MaximumNumberOfDefinitionsEnum : return "MaximumNumberOfDefinitions";
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=xNew<char>(len+1);
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/README	(revision 18231)
@@ -0,0 +1,10 @@
+
+DO NOT MODIFY the following files:
+- StringToEnumx.cpp
+- EnumToStringx.cpp
+- src/m/enum/*
+all these files are automatically synchronized with EnumDefinitions.h
+
+TO ADD AN ENUM:
+add the corresponding lines to EnumDefinitions.h
+and execute synchronizing script.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/StringToEnumx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/StringToEnumx.cpp	(revision 18231)
@@ -0,0 +1,743 @@
+/*
+* \file StringToEnumx.cpp:
+* \brief: output enum associated with string
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+
+int  StringToEnumx(const char* name,bool notfounderror){
+
+   int  stage=1;
+
+   if(stage==1){
+	      if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
+	      else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
+	      else if (strcmp(name,"AutodiffNumDependentObjects")==0) return AutodiffNumDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectNames")==0) return AutodiffDependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectTypes")==0) return AutodiffDependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectIndices")==0) return AutodiffDependentObjectIndicesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependentObjects")==0) return AutodiffNumIndependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectNames")==0) return AutodiffIndependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectTypes")==0) return AutodiffIndependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjects")==0) return AutodiffIndependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
+	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
+	      else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
+	      else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
+	      else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
+	      else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
+	      else if (strcmp(name,"AutodiffMassFluxSegmentsPresent")==0) return AutodiffMassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
+	      else if (strcmp(name,"AutodiffObufsize")==0) return AutodiffObufsizeEnum;
+	      else if (strcmp(name,"AutodiffLbufsize")==0) return AutodiffLbufsizeEnum;
+	      else if (strcmp(name,"AutodiffCbufsize")==0) return AutodiffCbufsizeEnum;
+	      else if (strcmp(name,"AutodiffTbufsize")==0) return AutodiffTbufsizeEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerRatio")==0) return AutodiffGcTriggerRatioEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerMaxSize")==0) return AutodiffGcTriggerMaxSizeEnum;
+	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
+	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
+	      else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
+	      else if (strcmp(name,"Basalforcings")==0) return BasalforcingsEnum;
+	      else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
+	      else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterMeltingRate")==0) return BasalforcingsDeepwaterMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterElevation")==0) return BasalforcingsDeepwaterElevationEnum;
+	      else if (strcmp(name,"BasalforcingsUpperwaterElevation")==0) return BasalforcingsUpperwaterElevationEnum;
+	      else if (strcmp(name,"FloatingMeltRate")==0) return FloatingMeltRateEnum;
+	      else if (strcmp(name,"LinearFloatingMeltRate")==0) return LinearFloatingMeltRateEnum;
+	      else if (strcmp(name,"Bed")==0) return BedEnum;
+	      else if (strcmp(name,"Base")==0) return BaseEnum;
+	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
+	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
+	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
+	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
+	      else if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
+	      else if (strcmp(name,"StressbalanceIsnewton")==0) return StressbalanceIsnewtonEnum;
+	      else if (strcmp(name,"StressbalanceMaxiter")==0) return StressbalanceMaxiterEnum;
+	      else if (strcmp(name,"StressbalancePenaltyFactor")==0) return StressbalancePenaltyFactorEnum;
+	      else if (strcmp(name,"StressbalanceReferential")==0) return StressbalanceReferentialEnum;
+	      else if (strcmp(name,"StressbalanceReltol")==0) return StressbalanceReltolEnum;
+	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
+	      else if (strcmp(name,"StressbalanceRequestedOutputs")==0) return StressbalanceRequestedOutputsEnum;
+	      else if (strcmp(name,"StressbalanceRestol")==0) return StressbalanceRestolEnum;
+	      else if (strcmp(name,"StressbalanceRiftPenaltyLock")==0) return StressbalanceRiftPenaltyLockEnum;
+	      else if (strcmp(name,"StressbalanceRiftPenaltyThreshold")==0) return StressbalanceRiftPenaltyThresholdEnum;
+	      else if (strcmp(name,"StressbalanceShelfDampening")==0) return StressbalanceShelfDampeningEnum;
+	      else if (strcmp(name,"StressbalanceSpcvx")==0) return StressbalanceSpcvxEnum;
+	      else if (strcmp(name,"StressbalanceSpcvy")==0) return StressbalanceSpcvyEnum;
+	      else if (strcmp(name,"StressbalanceSpcvz")==0) return StressbalanceSpcvzEnum;
+	      else if (strcmp(name,"StressbalanceFSreconditioning")==0) return StressbalanceFSreconditioningEnum;
+	      else if (strcmp(name,"StressbalanceVertexPairing")==0) return StressbalanceVertexPairingEnum;
+	      else if (strcmp(name,"StressbalanceViscosityOvershoot")==0) return StressbalanceViscosityOvershootEnum;
+	      else if (strcmp(name,"LoadingforceX")==0) return LoadingforceXEnum;
+	      else if (strcmp(name,"LoadingforceY")==0) return LoadingforceYEnum;
+	      else if (strcmp(name,"LoadingforceZ")==0) return LoadingforceZEnum;
+	      else if (strcmp(name,"FlowequationBorderSSA")==0) return FlowequationBorderSSAEnum;
+	      else if (strcmp(name,"FlowequationBorderHO")==0) return FlowequationBorderHOEnum;
+	      else if (strcmp(name,"FlowequationBorderFS")==0) return FlowequationBorderFSEnum;
+	      else if (strcmp(name,"FlowequationElementEquation")==0) return FlowequationElementEquationEnum;
+	      else if (strcmp(name,"FlowequationIsSIA")==0) return FlowequationIsSIAEnum;
+	      else if (strcmp(name,"FlowequationIsSSA")==0) return FlowequationIsSSAEnum;
+	      else if (strcmp(name,"FlowequationIsL1L2")==0) return FlowequationIsL1L2Enum;
+	      else if (strcmp(name,"FlowequationIsHO")==0) return FlowequationIsHOEnum;
+	      else if (strcmp(name,"FlowequationIsFS")==0) return FlowequationIsFSEnum;
+	      else if (strcmp(name,"FlowequationFeSSA")==0) return FlowequationFeSSAEnum;
+	      else if (strcmp(name,"FlowequationFeHO")==0) return FlowequationFeHOEnum;
+	      else if (strcmp(name,"FlowequationFeFS")==0) return FlowequationFeFSEnum;
+	      else if (strcmp(name,"FlowequationVertexEquation")==0) return FlowequationVertexEquationEnum;
+	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
+	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
+	      else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
+	      else if (strcmp(name,"FrictionM")==0) return FrictionMEnum;
+	      else if (strcmp(name,"FrictionC")==0) return FrictionCEnum;
+	      else if (strcmp(name,"FrictionLaw")==0) return FrictionLawEnum;
+	      else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
+	      else if (strcmp(name,"HydrologyModel")==0) return HydrologyModelEnum;
+	      else if (strcmp(name,"Hydrologyshreve")==0) return HydrologyshreveEnum;
+	      else if (strcmp(name,"HydrologyshreveSpcwatercolumn")==0) return HydrologyshreveSpcwatercolumnEnum;
+	      else if (strcmp(name,"HydrologyshreveStabilization")==0) return HydrologyshreveStabilizationEnum;
+	      else if (strcmp(name,"Hydrologydc")==0) return HydrologydcEnum;
+	      else if (strcmp(name,"SedimentHead")==0) return SedimentHeadEnum;
+	      else if (strcmp(name,"SedimentHeadOld")==0) return SedimentHeadOldEnum;
+	      else if (strcmp(name,"SedimentHeadResidual")==0) return SedimentHeadResidualEnum;
+	      else if (strcmp(name,"EffectivePressure")==0) return EffectivePressureEnum;
+	      else if (strcmp(name,"EplHead")==0) return EplHeadEnum;
+	      else if (strcmp(name,"EplHeadOld")==0) return EplHeadOldEnum;
+	      else if (strcmp(name,"EplHeadSlopeX")==0) return EplHeadSlopeXEnum;
+	      else if (strcmp(name,"EplHeadSlopeY")==0) return EplHeadSlopeYEnum;
+	      else if (strcmp(name,"HydrologydcMaxIter")==0) return HydrologydcMaxIterEnum;
+	      else if (strcmp(name,"HydrologydcRelTol")==0) return HydrologydcRelTolEnum;
+	      else if (strcmp(name,"HydrologydcSpcsedimentHead")==0) return HydrologydcSpcsedimentHeadEnum;
+	      else if (strcmp(name,"HydrologydcSedimentCompressibility")==0) return HydrologydcSedimentCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentPorosity")==0) return HydrologydcSedimentPorosityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentThickness")==0) return HydrologydcSedimentThicknessEnum;
+	      else if (strcmp(name,"HydrologydcSedimentTransmitivity")==0) return HydrologydcSedimentTransmitivityEnum;
+	      else if (strcmp(name,"HydrologydcWaterCompressibility")==0) return HydrologydcWaterCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcSpceplHead")==0) return HydrologydcSpceplHeadEnum;
+	      else if (strcmp(name,"HydrologydcMaskEplactiveNode")==0) return HydrologydcMaskEplactiveNodeEnum;
+	      else if (strcmp(name,"HydrologydcMaskEplactiveElt")==0) return HydrologydcMaskEplactiveEltEnum;
+	      else if (strcmp(name,"HydrologydcEplCompressibility")==0) return HydrologydcEplCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcEplPorosity")==0) return HydrologydcEplPorosityEnum;
+	      else if (strcmp(name,"HydrologydcEplInitialThickness")==0) return HydrologydcEplInitialThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplMaxThickness")==0) return HydrologydcEplMaxThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplThicknessOld")==0) return HydrologydcEplThicknessOldEnum;
+	      else if (strcmp(name,"HydrologydcEplConductivity")==0) return HydrologydcEplConductivityEnum;
+	      else if (strcmp(name,"HydrologydcIsefficientlayer")==0) return HydrologydcIsefficientlayerEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimitFlag")==0) return HydrologydcSedimentlimitFlagEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimit")==0) return HydrologydcSedimentlimitEnum;
+	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
+	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
+	      else if (strcmp(name,"HydrologydcPenaltyLock")==0) return HydrologydcPenaltyLockEnum;
+	      else if (strcmp(name,"HydrologydcBasalMoulinInput")==0) return HydrologydcBasalMoulinInputEnum;
+	      else if (strcmp(name,"HydrologyLayer")==0) return HydrologyLayerEnum;
+	      else if (strcmp(name,"HydrologySediment")==0) return HydrologySedimentEnum;
+	      else if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
+	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
+	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
+	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
+	      else if (strcmp(name,"InversionCostFunctionThreshold")==0) return InversionCostFunctionThresholdEnum;
+	      else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
+	      else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
+	      else if (strcmp(name,"InversionGradientScaling")==0) return InversionGradientScalingEnum;
+	      else if (strcmp(name,"InversionIscontrol")==0) return InversionIscontrolEnum;
+	      else if (strcmp(name,"InversionType")==0) return InversionTypeEnum;
+	      else if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
+	      else if (strcmp(name,"InversionMaxParameters")==0) return InversionMaxParametersEnum;
+	      else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
+	      else if (strcmp(name,"InversionMaxiter")==0) return InversionMaxiterEnum;
+	      else if (strcmp(name,"InversionMaxsteps")==0) return InversionMaxstepsEnum;
+	      else if (strcmp(name,"InversionFatol")==0) return InversionFatolEnum;
+	      else if (strcmp(name,"InversionFrtol")==0) return InversionFrtolEnum;
+	      else if (strcmp(name,"InversionGatol")==0) return InversionGatolEnum;
+	      else if (strcmp(name,"InversionGrtol")==0) return InversionGrtolEnum;
+	      else if (strcmp(name,"InversionGttol")==0) return InversionGttolEnum;
+	      else if (strcmp(name,"InversionAlgorithm")==0) return InversionAlgorithmEnum;
+	      else if (strcmp(name,"InversionMinParameters")==0) return InversionMinParametersEnum;
+	      else if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
+	      else if (strcmp(name,"InversionDxmin")==0) return InversionDxminEnum;
+	      else if (strcmp(name,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
+	      else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
+	      else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
+	      else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
+	      else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
+	      else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
+	      else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
+	      else if (strcmp(name,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
+	      else if (strcmp(name,"QmuMaskIceLevelset")==0) return QmuMaskIceLevelsetEnum;
+	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
+	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
+	      else if (strcmp(name,"MaterialsLatentheat")==0) return MaterialsLatentheatEnum;
+	      else if (strcmp(name,"MaterialsMeltingpoint")==0) return MaterialsMeltingpointEnum;
+	      else if (strcmp(name,"MaterialsMixedLayerCapacity")==0) return MaterialsMixedLayerCapacityEnum;
+	      else if (strcmp(name,"MaterialsRheologyB")==0) return MaterialsRheologyBEnum;
+	      else if (strcmp(name,"MaterialsRheologyBbar")==0) return MaterialsRheologyBbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
+	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
+	      else if (strcmp(name,"DamageIsdamage")==0) return DamageIsdamageEnum;
+	      else if (strcmp(name,"DamageD")==0) return DamageDEnum;
+	      else if (strcmp(name,"DamageF")==0) return DamageFEnum;
+	      else if (strcmp(name,"QmuDamageD")==0) return QmuDamageDEnum;
+	      else if (strcmp(name,"DamageDbar")==0) return DamageDbarEnum;
+	      else if (strcmp(name,"DamageLaw")==0) return DamageLawEnum;
+	      else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
+	      else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
+	      else if (strcmp(name,"DamageC3")==0) return DamageC3Enum;
+	      else if (strcmp(name,"DamageC4")==0) return DamageC4Enum;
+	      else if (strcmp(name,"DamageElementinterp")==0) return DamageElementinterpEnum;
+	      else if (strcmp(name,"DamageHealing")==0) return DamageHealingEnum;
+	      else if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
+	      else if (strcmp(name,"DamageStabilization")==0) return DamageStabilizationEnum;
+	      else if (strcmp(name,"DamagePenaltyThreshold")==0) return DamagePenaltyThresholdEnum;
+	      else if (strcmp(name,"DamagePenaltyLock")==0) return DamagePenaltyLockEnum;
+	      else if (strcmp(name,"DamagePenaltyFactor")==0) return DamagePenaltyFactorEnum;
+	      else if (strcmp(name,"DamageMaxiter")==0) return DamageMaxiterEnum;
+	      else if (strcmp(name,"DamageSpcdamage")==0) return DamageSpcdamageEnum;
+	      else if (strcmp(name,"DamageMaxDamage")==0) return DamageMaxDamageEnum;
+	      else if (strcmp(name,"DamageEquivStress")==0) return DamageEquivStressEnum;
+	      else if (strcmp(name,"DamageEvolutionNumRequestedOutputs")==0) return DamageEvolutionNumRequestedOutputsEnum;
+	      else if (strcmp(name,"DamageEvolutionRequestedOutputs")==0) return DamageEvolutionRequestedOutputsEnum;
+	      else if (strcmp(name,"NewDamage")==0) return NewDamageEnum;
+	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
+	      else if (strcmp(name,"MaterialsRhoSeawater")==0) return MaterialsRhoSeawaterEnum;
+	      else if (strcmp(name,"MaterialsRhoFreshwater")==0) return MaterialsRhoFreshwaterEnum;
+	      else if (strcmp(name,"MaterialsMuWater")==0) return MaterialsMuWaterEnum;
+	      else if (strcmp(name,"MaterialsThermalExchangeVelocity")==0) return MaterialsThermalExchangeVelocityEnum;
+	      else if (strcmp(name,"MaterialsThermalconductivity")==0) return MaterialsThermalconductivityEnum;
+	      else if (strcmp(name,"MaterialsTemperateiceconductivity")==0) return MaterialsTemperateiceconductivityEnum;
+	      else if (strcmp(name,"MaterialsLithosphereShearModulus")==0) return MaterialsLithosphereShearModulusEnum;
+	      else if (strcmp(name,"MaterialsLithosphereDensity")==0) return MaterialsLithosphereDensityEnum;
+	      else if (strcmp(name,"MaterialsMantleShearModulus")==0) return MaterialsMantleShearModulusEnum;
+	      else if (strcmp(name,"MaterialsMantleDensity")==0) return MaterialsMantleDensityEnum;
+	      else if (strcmp(name,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
+	      else if (strcmp(name,"MeshElements2d")==0) return MeshElements2dEnum;
+	      else if (strcmp(name,"MeshElements")==0) return MeshElementsEnum;
+	      else if (strcmp(name,"MeshLowerelements")==0) return MeshLowerelementsEnum;
+	      else if (strcmp(name,"MeshNumberofelements2d")==0) return MeshNumberofelements2dEnum;
+	      else if (strcmp(name,"MeshNumberofelements")==0) return MeshNumberofelementsEnum;
+	      else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
+	      else if (strcmp(name,"MeshNumberofvertices2d")==0) return MeshNumberofvertices2dEnum;
+	      else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
+	      else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
+	      else if (strcmp(name,"MeshVertexonbase")==0) return MeshVertexonbaseEnum;
+	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+	      else if (strcmp(name,"MeshVertexonboundary")==0) return MeshVertexonboundaryEnum;
+	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
+	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
+	      else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
+	      else if (strcmp(name,"MeshElementtype")==0) return MeshElementtypeEnum;
+	      else if (strcmp(name,"DomainType")==0) return DomainTypeEnum;
+	      else if (strcmp(name,"DomainDimension")==0) return DomainDimensionEnum;
+	      else if (strcmp(name,"Domain2Dhorizontal")==0) return Domain2DhorizontalEnum;
+	      else if (strcmp(name,"Domain2Dvertical")==0) return Domain2DverticalEnum;
+	      else if (strcmp(name,"Domain3D")==0) return Domain3DEnum;
+	      else if (strcmp(name,"MiscellaneousName")==0) return MiscellaneousNameEnum;
+	      else if (strcmp(name,"MasstransportHydrostaticAdjustment")==0) return MasstransportHydrostaticAdjustmentEnum;
+	      else if (strcmp(name,"MasstransportIsfreesurface")==0) return MasstransportIsfreesurfaceEnum;
+	      else if (strcmp(name,"MasstransportMinThickness")==0) return MasstransportMinThicknessEnum;
+	      else if (strcmp(name,"MasstransportPenaltyFactor")==0) return MasstransportPenaltyFactorEnum;
+	      else if (strcmp(name,"MasstransportSpcthickness")==0) return MasstransportSpcthicknessEnum;
+	      else if (strcmp(name,"MasstransportCalvingrate")==0) return MasstransportCalvingrateEnum;
+	      else if (strcmp(name,"MasstransportStabilization")==0) return MasstransportStabilizationEnum;
+	      else if (strcmp(name,"MasstransportVertexPairing")==0) return MasstransportVertexPairingEnum;
+	      else if (strcmp(name,"MasstransportNumRequestedOutputs")==0) return MasstransportNumRequestedOutputsEnum;
+	      else if (strcmp(name,"MasstransportRequestedOutputs")==0) return MasstransportRequestedOutputsEnum;
+	      else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
+	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
+	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"QmuMassFluxSegmentsPresent")==0) return QmuMassFluxSegmentsPresentEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
+	      else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
+	      else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
+	      else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
+	      else if (strcmp(name,"QmuMaterialsRheologyB")==0) return QmuMaterialsRheologyBEnum;
+	      else if (strcmp(name,"RiftsNumrifts")==0) return RiftsNumriftsEnum;
+	      else if (strcmp(name,"RiftsRiftstruct")==0) return RiftsRiftstructEnum;
+	      else if (strcmp(name,"SettingsResultsOnNodes")==0) return SettingsResultsOnNodesEnum;
+	      else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
+	      else if (strcmp(name,"SettingsLowmem")==0) return SettingsLowmemEnum;
+	      else if (strcmp(name,"SettingsOutputFrequency")==0) return SettingsOutputFrequencyEnum;
+	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
+	      else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
+	      else if (strcmp(name,"ProfilingCurrentMem")==0) return ProfilingCurrentMemEnum;
+	      else if (strcmp(name,"ProfilingCurrentFlops")==0) return ProfilingCurrentFlopsEnum;
+	      else if (strcmp(name,"ProfilingSolutionTime")==0) return ProfilingSolutionTimeEnum;
+	      else if (strcmp(name,"MaxIterationConvergenceFlag")==0) return MaxIterationConvergenceFlagEnum;
+	      else if (strcmp(name,"SteadystateMaxiter")==0) return SteadystateMaxiterEnum;
+	      else if (strcmp(name,"SteadystateNumRequestedOutputs")==0) return SteadystateNumRequestedOutputsEnum;
+	      else if (strcmp(name,"SteadystateReltol")==0) return SteadystateReltolEnum;
+	      else if (strcmp(name,"SteadystateRequestedOutputs")==0) return SteadystateRequestedOutputsEnum;
+	      else if (strcmp(name,"Surface")==0) return SurfaceEnum;
+	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
+	      else if (strcmp(name,"ThermalIsdynamicbasalspc")==0) return ThermalIsdynamicbasalspcEnum;
+	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
+	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
+	      else if (strcmp(name,"ThermalPenaltyLock")==0) return ThermalPenaltyLockEnum;
+	      else if (strcmp(name,"ThermalPenaltyThreshold")==0) return ThermalPenaltyThresholdEnum;
+	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
+	      else if (strcmp(name,"ThermalStabilization")==0) return ThermalStabilizationEnum;
+	      else if (strcmp(name,"ThermalNumRequestedOutputs")==0) return ThermalNumRequestedOutputsEnum;
+	      else if (strcmp(name,"ThermalRequestedOutputs")==0) return ThermalRequestedOutputsEnum;
+	      else if (strcmp(name,"GiaMantleViscosity")==0) return GiaMantleViscosityEnum;
+	      else if (strcmp(name,"GiaLithosphereThickness")==0) return GiaLithosphereThicknessEnum;
+	      else if (strcmp(name,"Thickness")==0) return ThicknessEnum;
+	      else if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
+	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
+	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
+	      else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
+	      else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
+	      else if (strcmp(name,"TimesteppingInterpForcings")==0) return TimesteppingInterpForcingsEnum;
+	      else if (strcmp(name,"TransientIsstressbalance")==0) return TransientIsstressbalanceEnum;
+	      else if (strcmp(name,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
+	      else if (strcmp(name,"TransientIsmasstransport")==0) return TransientIsmasstransportEnum;
+	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
+	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
+	      else if (strcmp(name,"TransientIsdamageevolution")==0) return TransientIsdamageevolutionEnum;
+	      else if (strcmp(name,"TransientIshydrology")==0) return TransientIshydrologyEnum;
+	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
+	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
+	      else if (strcmp(name,"Potential")==0) return PotentialEnum;
+	      else if (strcmp(name,"BalancethicknessSpcpotential")==0) return BalancethicknessSpcpotentialEnum;
+	      else if (strcmp(name,"BalancethicknessApparentMassbalance")==0) return BalancethicknessApparentMassbalanceEnum;
+	      else if (strcmp(name,"Balancethickness2Misfit")==0) return Balancethickness2MisfitEnum;
+	      else if (strcmp(name,"BalancethicknessNux")==0) return BalancethicknessNuxEnum;
+	      else if (strcmp(name,"BalancethicknessNuy")==0) return BalancethicknessNuyEnum;
+	      else if (strcmp(name,"BalancethicknessVxObs")==0) return BalancethicknessVxObsEnum;
+	      else if (strcmp(name,"BalancethicknessVyObs")==0) return BalancethicknessVyObsEnum;
+	      else if (strcmp(name,"BalancethicknessThicknessObs")==0) return BalancethicknessThicknessObsEnum;
+	      else if (strcmp(name,"Surfaceforcings")==0) return SurfaceforcingsEnum;
+	      else if (strcmp(name,"SMB")==0) return SMBEnum;
+	      else if (strcmp(name,"SurfaceforcingsMassBalance")==0) return SurfaceforcingsMassBalanceEnum;
+	      else if (strcmp(name,"SMBpdd")==0) return SMBpddEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18o")==0) return SurfaceforcingsDelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18oSurface")==0) return SurfaceforcingsDelta18oSurfaceEnum;
+	      else if (strcmp(name,"SurfaceforcingsIsdelta18o")==0) return SurfaceforcingsIsdelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitationsPresentday")==0) return SurfaceforcingsPrecipitationsPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesPresentday")==0) return SurfaceforcingsTemperaturesPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesLgm")==0) return SurfaceforcingsTemperaturesLgmEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitation")==0) return SurfaceforcingsPrecipitationEnum;
+	      else if (strcmp(name,"SurfaceforcingsDesfac")==0) return SurfaceforcingsDesfacEnum;
+	      else if (strcmp(name,"SurfaceforcingsS0p")==0) return SurfaceforcingsS0pEnum;
+	      else if (strcmp(name,"SMBgradients")==0) return SMBgradientsEnum;
+	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
+	      else if (strcmp(name,"SurfaceforcingsHref")==0) return SurfaceforcingsHrefEnum;
+	      else if (strcmp(name,"SurfaceforcingsSmbref")==0) return SurfaceforcingsSmbrefEnum;
+	      else if (strcmp(name,"SurfaceforcingsBPos")==0) return SurfaceforcingsBPosEnum;
+	      else if (strcmp(name,"SurfaceforcingsBNeg")==0) return SurfaceforcingsBNegEnum;
+	      else if (strcmp(name,"SMBhenning")==0) return SMBhenningEnum;
+	      else if (strcmp(name,"SMBcomponents")==0) return SMBcomponentsEnum;
+	      else if (strcmp(name,"SurfaceforcingsAccumulation")==0) return SurfaceforcingsAccumulationEnum;
+	      else if (strcmp(name,"SurfaceforcingsEvaporation")==0) return SurfaceforcingsEvaporationEnum;
+	      else if (strcmp(name,"SurfaceforcingsRunoff")==0) return SurfaceforcingsRunoffEnum;
+	      else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
+	      else if (strcmp(name,"SurfaceforcingsMelt")==0) return SurfaceforcingsMeltEnum;
+	      else if (strcmp(name,"SurfaceforcingsRefreeze")==0) return SurfaceforcingsRefreezeEnum;
+	      else if (strcmp(name,"SurfaceforcingsIspdd")==0) return SurfaceforcingsIspddEnum;
+	      else if (strcmp(name,"SurfaceforcingsIssmbgradients")==0) return SurfaceforcingsIssmbgradientsEnum;
+	      else if (strcmp(name,"SolutionType")==0) return SolutionTypeEnum;
+	      else if (strcmp(name,"AnalysisType")==0) return AnalysisTypeEnum;
+	      else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
+	      else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"AdjointBalancethickness2Analysis")==0) return AdjointBalancethickness2AnalysisEnum;
+	      else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
+	      else if (strcmp(name,"AnalysisCounter")==0) return AnalysisCounterEnum;
+	      else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessSolution")==0) return BalancethicknessSolutionEnum;
+	      else if (strcmp(name,"Balancethickness2Analysis")==0) return Balancethickness2AnalysisEnum;
+	      else if (strcmp(name,"Balancethickness2Solution")==0) return Balancethickness2SolutionEnum;
+	      else if (strcmp(name,"BalancethicknessSoftAnalysis")==0) return BalancethicknessSoftAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessSoftSolution")==0) return BalancethicknessSoftSolutionEnum;
+	      else if (strcmp(name,"BalancevelocityAnalysis")==0) return BalancevelocityAnalysisEnum;
+	      else if (strcmp(name,"BalancevelocitySolution")==0) return BalancevelocitySolutionEnum;
+	      else if (strcmp(name,"L2ProjectionEPLAnalysis")==0) return L2ProjectionEPLAnalysisEnum;
+	      else if (strcmp(name,"L2ProjectionBaseAnalysis")==0) return L2ProjectionBaseAnalysisEnum;
+	      else if (strcmp(name,"BedSlopeSolution")==0) return BedSlopeSolutionEnum;
+	      else if (strcmp(name,"DamageEvolutionSolution")==0) return DamageEvolutionSolutionEnum;
+	      else if (strcmp(name,"DamageEvolutionAnalysis")==0) return DamageEvolutionAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceAnalysis")==0) return StressbalanceAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceSIAAnalysis")==0) return StressbalanceSIAAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceSolution")==0) return StressbalanceSolutionEnum;
+	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
+	      else if (strcmp(name,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
+	      else if (strcmp(name,"FlaimAnalysis")==0) return FlaimAnalysisEnum;
+	      else if (strcmp(name,"FlaimSolution")==0) return FlaimSolutionEnum;
+	      else if (strcmp(name,"HydrologyShreveAnalysis")==0) return HydrologyShreveAnalysisEnum;
+	      else if (strcmp(name,"HydrologyDCInefficientAnalysis")==0) return HydrologyDCInefficientAnalysisEnum;
+	      else if (strcmp(name,"HydrologyDCEfficientAnalysis")==0) return HydrologyDCEfficientAnalysisEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
+	      else if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
+	      else if (strcmp(name,"MasstransportAnalysis")==0) return MasstransportAnalysisEnum;
+	      else if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
+	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
+	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
+	      else if (strcmp(name,"SurfaceNormalVelocity")==0) return SurfaceNormalVelocityEnum;
+	      else if (strcmp(name,"ExtrudeFromBaseAnalysis")==0) return ExtrudeFromBaseAnalysisEnum;
+	      else if (strcmp(name,"ExtrudeFromTopAnalysis")==0) return ExtrudeFromTopAnalysisEnum;
+	      else if (strcmp(name,"DepthAverageAnalysis")==0) return DepthAverageAnalysisEnum;
+	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
+	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
+	      else if (strcmp(name,"SmoothedSurfaceSlopeXAnalysis")==0) return SmoothedSurfaceSlopeXAnalysisEnum;
+	      else if (strcmp(name,"SmoothedSurfaceSlopeYAnalysis")==0) return SmoothedSurfaceSlopeYAnalysisEnum;
+	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
+	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
+	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
+	      else if (strcmp(name,"UzawaPressureAnalysis")==0) return UzawaPressureAnalysisEnum;
+	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
+	      else if (strcmp(name,"GiaAnalysis")==0) return GiaAnalysisEnum;
+	      else if (strcmp(name,"MeshdeformationSolution")==0) return MeshdeformationSolutionEnum;
+	      else if (strcmp(name,"MeshdeformationAnalysis")==0) return MeshdeformationAnalysisEnum;
+	      else if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
+	      else if (strcmp(name,"ExtrapolationAnalysis")==0) return ExtrapolationAnalysisEnum;
+	      else if (strcmp(name,"LsfReinitializationAnalysis")==0) return LsfReinitializationAnalysisEnum;
+	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
+	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
+	      else if (strcmp(name,"SIAApproximation")==0) return SIAApproximationEnum;
+	      else if (strcmp(name,"SSAApproximation")==0) return SSAApproximationEnum;
+	      else if (strcmp(name,"SSAHOApproximation")==0) return SSAHOApproximationEnum;
+	      else if (strcmp(name,"SSAFSApproximation")==0) return SSAFSApproximationEnum;
+	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
+	      else if (strcmp(name,"HOApproximation")==0) return HOApproximationEnum;
+	      else if (strcmp(name,"HOFSApproximation")==0) return HOFSApproximationEnum;
+	      else if (strcmp(name,"FSApproximation")==0) return FSApproximationEnum;
+	      else if (strcmp(name,"FSvelocity")==0) return FSvelocityEnum;
+	      else if (strcmp(name,"FSpressure")==0) return FSpressureEnum;
+	      else if (strcmp(name,"Constraints")==0) return ConstraintsEnum;
+	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
+	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
+	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
+	      else if (strcmp(name,"Contours")==0) return ContoursEnum;
+	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
+	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
+	      else if (strcmp(name,"Results")==0) return ResultsEnum;
+	      else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
+	      else if (strcmp(name,"AdolcParam")==0) return AdolcParamEnum;
+	      else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
+	      else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
+	      else if (strcmp(name,"Contour")==0) return ContourEnum;
+	      else if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
+	      else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
+	      else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
+	      else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
+	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
+	      else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
+	      else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
+	      else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
+	      else if (strcmp(name,"Element")==0) return ElementEnum;
+	      else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
+	      else if (strcmp(name,"FileParam")==0) return FileParamEnum;
+	      else if (strcmp(name,"Input")==0) return InputEnum;
+	      else if (strcmp(name,"IntInput")==0) return IntInputEnum;
+	      else if (strcmp(name,"InputToExtrude")==0) return InputToExtrudeEnum;
+	      else if (strcmp(name,"InputToL2Project")==0) return InputToL2ProjectEnum;
+	      else if (strcmp(name,"InputToDepthaverage")==0) return InputToDepthaverageEnum;
+	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
+	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
+	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
+	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
+	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
+	      else if (strcmp(name,"Node")==0) return NodeEnum;
+	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
+	      else if (strcmp(name,"NumericalfluxType")==0) return NumericalfluxTypeEnum;
+	      else if (strcmp(name,"Param")==0) return ParamEnum;
+	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
+	      else if (strcmp(name,"Penpair")==0) return PenpairEnum;
+	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
+	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
+	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
+	      else if (strcmp(name,"Riftfront")==0) return RiftfrontEnum;
+	      else if (strcmp(name,"RiftfrontType")==0) return RiftfrontTypeEnum;
+	      else if (strcmp(name,"Segment")==0) return SegmentEnum;
+	      else if (strcmp(name,"SegmentRiftfront")==0) return SegmentRiftfrontEnum;
+	      else if (strcmp(name,"SpcDynamic")==0) return SpcDynamicEnum;
+	      else if (strcmp(name,"SpcStatic")==0) return SpcStaticEnum;
+	      else if (strcmp(name,"SpcTransient")==0) return SpcTransientEnum;
+	      else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
+	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
+	      else if (strcmp(name,"Seg")==0) return SegEnum;
+	      else if (strcmp(name,"SegInput")==0) return SegInputEnum;
+	      else if (strcmp(name,"Tria")==0) return TriaEnum;
+	      else if (strcmp(name,"TriaInput")==0) return TriaInputEnum;
+	      else if (strcmp(name,"Tetra")==0) return TetraEnum;
+	      else if (strcmp(name,"TetraInput")==0) return TetraInputEnum;
+	      else if (strcmp(name,"Penta")==0) return PentaEnum;
+	      else if (strcmp(name,"PentaInput")==0) return PentaInputEnum;
+	      else if (strcmp(name,"Vertex")==0) return VertexEnum;
+	      else if (strcmp(name,"VertexPId")==0) return VertexPIdEnum;
+	      else if (strcmp(name,"VertexSId")==0) return VertexSIdEnum;
+	      else if (strcmp(name,"Air")==0) return AirEnum;
+	      else if (strcmp(name,"Ice")==0) return IceEnum;
+	      else if (strcmp(name,"Melange")==0) return MelangeEnum;
+	      else if (strcmp(name,"Water")==0) return WaterEnum;
+	      else if (strcmp(name,"Closed")==0) return ClosedEnum;
+	      else if (strcmp(name,"Free")==0) return FreeEnum;
+	      else if (strcmp(name,"Open")==0) return OpenEnum;
+	      else if (strcmp(name,"Adjointp")==0) return AdjointpEnum;
+	      else if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
+	      else if (strcmp(name,"Adjointy")==0) return AdjointyEnum;
+	      else if (strcmp(name,"Adjointz")==0) return AdjointzEnum;
+	      else if (strcmp(name,"BalancethicknessMisfit")==0) return BalancethicknessMisfitEnum;
+	      else if (strcmp(name,"BedSlopeX")==0) return BedSlopeXEnum;
+	      else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
+	      else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
+	      else if (strcmp(name,"Converged")==0) return ConvergedEnum;
+	      else if (strcmp(name,"Fill")==0) return FillEnum;
+	      else if (strcmp(name,"FractionIncrement")==0) return FractionIncrementEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"Friction")==0) return FrictionEnum;
+	      else if (strcmp(name,"Internal")==0) return InternalEnum;
+	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
+	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
+	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
+	      else if (strcmp(name,"PressurePicard")==0) return PressurePicardEnum;
+	      else if (strcmp(name,"QmuPressure")==0) return QmuPressureEnum;
+	      else if (strcmp(name,"QmuVx")==0) return QmuVxEnum;
+	      else if (strcmp(name,"QmuVy")==0) return QmuVyEnum;
+	      else if (strcmp(name,"QmuVz")==0) return QmuVzEnum;
+	      else if (strcmp(name,"QmuThickness")==0) return QmuThicknessEnum;
+	      else if (strcmp(name,"QmuBase")==0) return QmuBaseEnum;
+	      else if (strcmp(name,"QmuSurface")==0) return QmuSurfaceEnum;
+	      else if (strcmp(name,"QmuMelting")==0) return QmuMeltingEnum;
+	      else if (strcmp(name,"QmuVxMesh")==0) return QmuVxMeshEnum;
+	      else if (strcmp(name,"QmuVyMesh")==0) return QmuVyMeshEnum;
+	      else if (strcmp(name,"QmuVzMesh")==0) return QmuVzMeshEnum;
+	      else if (strcmp(name,"AndroidFrictionCoefficient")==0) return AndroidFrictionCoefficientEnum;
+	      else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
+	      else if (strcmp(name,"SegmentOnIceShelf")==0) return SegmentOnIceShelfEnum;
+	      else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
+	      else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
+	      else if (strcmp(name,"SurfaceRelVelMisfit")==0) return SurfaceRelVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceSlopeX")==0) return SurfaceSlopeXEnum;
+	      else if (strcmp(name,"SurfaceSlopeY")==0) return SurfaceSlopeYEnum;
+	      else if (strcmp(name,"Temperature")==0) return TemperatureEnum;
+	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
+	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
+	      else if (strcmp(name,"Vel")==0) return VelEnum;
+	      else if (strcmp(name,"Velocity")==0) return VelocityEnum;
+	      else if (strcmp(name,"VxAverage")==0) return VxAverageEnum;
+	      else if (strcmp(name,"Vx")==0) return VxEnum;
+	      else if (strcmp(name,"VxPicard")==0) return VxPicardEnum;
+	      else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
+	      else if (strcmp(name,"Vy")==0) return VyEnum;
+	      else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
+	      else if (strcmp(name,"Vz")==0) return VzEnum;
+	      else if (strcmp(name,"VzSSA")==0) return VzSSAEnum;
+	      else if (strcmp(name,"VzHO")==0) return VzHOEnum;
+	      else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
+	      else if (strcmp(name,"VzFS")==0) return VzFSEnum;
+	      else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
+	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
+	      else if (strcmp(name,"VzMesh")==0) return VzMeshEnum;
+	      else if (strcmp(name,"Enthalpy")==0) return EnthalpyEnum;
+	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
+	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
+	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
+	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
+	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
+	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
+	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
+	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
+	      else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
+	      else if (strcmp(name,"Watercolumn")==0) return WatercolumnEnum;
+	      else if (strcmp(name,"BasalFriction")==0) return BasalFrictionEnum;
+	      else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
+	      else if (strcmp(name,"QmuTemperature")==0) return QmuTemperatureEnum;
+	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
+	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	      else if (strcmp(name,"SigmaNN")==0) return SigmaNNEnum;
+	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
+	      else if (strcmp(name,"StressTensorxx")==0) return StressTensorxxEnum;
+	      else if (strcmp(name,"StressTensorxy")==0) return StressTensorxyEnum;
+	      else if (strcmp(name,"StressTensorxz")==0) return StressTensorxzEnum;
+	      else if (strcmp(name,"StressTensoryy")==0) return StressTensoryyEnum;
+	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
+	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
+	      else if (strcmp(name,"DeviatoricStress")==0) return DeviatoricStressEnum;
+	      else if (strcmp(name,"DeviatoricStressxx")==0) return DeviatoricStressxxEnum;
+	      else if (strcmp(name,"DeviatoricStressxy")==0) return DeviatoricStressxyEnum;
+	      else if (strcmp(name,"DeviatoricStressxz")==0) return DeviatoricStressxzEnum;
+	      else if (strcmp(name,"DeviatoricStressyy")==0) return DeviatoricStressyyEnum;
+	      else if (strcmp(name,"DeviatoricStressyz")==0) return DeviatoricStressyzEnum;
+	      else if (strcmp(name,"DeviatoricStresszz")==0) return DeviatoricStresszzEnum;
+	      else if (strcmp(name,"StrainRate")==0) return StrainRateEnum;
+	      else if (strcmp(name,"StrainRatexx")==0) return StrainRatexxEnum;
+	      else if (strcmp(name,"StrainRatexy")==0) return StrainRatexyEnum;
+	      else if (strcmp(name,"StrainRatexz")==0) return StrainRatexzEnum;
+	      else if (strcmp(name,"StrainRateyy")==0) return StrainRateyyEnum;
+	      else if (strcmp(name,"StrainRateyz")==0) return StrainRateyzEnum;
+	      else if (strcmp(name,"StrainRatezz")==0) return StrainRatezzEnum;
+	      else if (strcmp(name,"Divergence")==0) return DivergenceEnum;
+	      else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
+	      else if (strcmp(name,"GiadWdt")==0) return GiadWdtEnum;
+	      else if (strcmp(name,"GiaW")==0) return GiaWEnum;
+	      else if (strcmp(name,"P0")==0) return P0Enum;
+	      else if (strcmp(name,"P1")==0) return P1Enum;
+	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
+	      else if (strcmp(name,"P1bubble")==0) return P1bubbleEnum;
+	      else if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
+	      else if (strcmp(name,"P2")==0) return P2Enum;
+	      else if (strcmp(name,"P2bubble")==0) return P2bubbleEnum;
+	      else if (strcmp(name,"P2bubblecondensed")==0) return P2bubblecondensedEnum;
+	      else if (strcmp(name,"P2xP1")==0) return P2xP1Enum;
+	      else if (strcmp(name,"P1xP2")==0) return P1xP2Enum;
+	      else if (strcmp(name,"P1xP3")==0) return P1xP3Enum;
+	      else if (strcmp(name,"P2xP4")==0) return P2xP4Enum;
+	      else if (strcmp(name,"P1P1")==0) return P1P1Enum;
+	      else if (strcmp(name,"P1P1GLS")==0) return P1P1GLSEnum;
+	      else if (strcmp(name,"MINI")==0) return MINIEnum;
+	      else if (strcmp(name,"MINIcondensed")==0) return MINIcondensedEnum;
+	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
+	      else if (strcmp(name,"LATaylorHood")==0) return LATaylorHoodEnum;
+	      else if (strcmp(name,"XTaylorHood")==0) return XTaylorHoodEnum;
+	      else if (strcmp(name,"OneLayerP4z")==0) return OneLayerP4zEnum;
+	      else if (strcmp(name,"CrouzeixRaviart")==0) return CrouzeixRaviartEnum;
+	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
+	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
+	      else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
+	      else if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
+	      else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
+	      else if (strcmp(name,"J")==0) return JEnum;
+	      else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
+	      else if (strcmp(name,"Step")==0) return StepEnum;
+	      else if (strcmp(name,"Time")==0) return TimeEnum;
+         else stage=6;
+   }
+   if(stage==6){
+	      if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
+	      else if (strcmp(name,"Outputdefinition")==0) return OutputdefinitionEnum;
+	      else if (strcmp(name,"OutputdefinitionList")==0) return OutputdefinitionListEnum;
+	      else if (strcmp(name,"Massfluxatgate")==0) return MassfluxatgateEnum;
+	      else if (strcmp(name,"MassfluxatgateName")==0) return MassfluxatgateNameEnum;
+	      else if (strcmp(name,"MassfluxatgateSegments")==0) return MassfluxatgateSegmentsEnum;
+	      else if (strcmp(name,"MisfitName")==0) return MisfitNameEnum;
+	      else if (strcmp(name,"MisfitModelEnum")==0) return MisfitModelEnumEnum;
+	      else if (strcmp(name,"MisfitObservation")==0) return MisfitObservationEnum;
+	      else if (strcmp(name,"MisfitObservationEnum")==0) return MisfitObservationEnumEnum;
+	      else if (strcmp(name,"MisfitTimeinterpolation")==0) return MisfitTimeinterpolationEnum;
+	      else if (strcmp(name,"MisfitWeights")==0) return MisfitWeightsEnum;
+	      else if (strcmp(name,"MisfitWeightsEnum")==0) return MisfitWeightsEnumEnum;
+	      else if (strcmp(name,"SurfaceObservation")==0) return SurfaceObservationEnum;
+	      else if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
+	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
+	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
+	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
+	      else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
+	      else if (strcmp(name,"MaxAbsVx")==0) return MaxAbsVxEnum;
+	      else if (strcmp(name,"MinVy")==0) return MinVyEnum;
+	      else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
+	      else if (strcmp(name,"MaxAbsVy")==0) return MaxAbsVyEnum;
+	      else if (strcmp(name,"MinVz")==0) return MinVzEnum;
+	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
+	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"IceVolumeAboveFloatation")==0) return IceVolumeAboveFloatationEnum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
+	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
+	      else if (strcmp(name,"Incremental")==0) return IncrementalEnum;
+	      else if (strcmp(name,"AugmentedLagrangianR")==0) return AugmentedLagrangianREnum;
+	      else if (strcmp(name,"AugmentedLagrangianRhop")==0) return AugmentedLagrangianRhopEnum;
+	      else if (strcmp(name,"AugmentedLagrangianTheta")==0) return AugmentedLagrangianThetaEnum;
+	      else if (strcmp(name,"None")==0) return NoneEnum;
+	      else if (strcmp(name,"AggressiveMigration")==0) return AggressiveMigrationEnum;
+	      else if (strcmp(name,"SoftMigration")==0) return SoftMigrationEnum;
+	      else if (strcmp(name,"SubelementMigration")==0) return SubelementMigrationEnum;
+	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
+	      else if (strcmp(name,"Contact")==0) return ContactEnum;
+	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
+	      else if (strcmp(name,"QmuMaskGroundediceLevelset")==0) return QmuMaskGroundediceLevelsetEnum;
+	      else if (strcmp(name,"GaussSeg")==0) return GaussSegEnum;
+	      else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
+	      else if (strcmp(name,"GaussTetra")==0) return GaussTetraEnum;
+	      else if (strcmp(name,"GaussPenta")==0) return GaussPentaEnum;
+	      else if (strcmp(name,"FSSolver")==0) return FSSolverEnum;
+	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
+	      else if (strcmp(name,"Colinear")==0) return ColinearEnum;
+	      else if (strcmp(name,"ControlSteady")==0) return ControlSteadyEnum;
+	      else if (strcmp(name,"Fset")==0) return FsetEnum;
+	      else if (strcmp(name,"Gradient1")==0) return Gradient1Enum;
+	      else if (strcmp(name,"Gradient2")==0) return Gradient2Enum;
+	      else if (strcmp(name,"Gradient3")==0) return Gradient3Enum;
+	      else if (strcmp(name,"Gradient")==0) return GradientEnum;
+	      else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
+	      else if (strcmp(name,"Gset")==0) return GsetEnum;
+	      else if (strcmp(name,"Index")==0) return IndexEnum;
+	      else if (strcmp(name,"Indexed")==0) return IndexedEnum;
+	      else if (strcmp(name,"Intersect")==0) return IntersectEnum;
+	      else if (strcmp(name,"Nodal")==0) return NodalEnum;
+	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
+	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
+	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
+	      else if (strcmp(name,"ToolkitsOptionsAnalyses")==0) return ToolkitsOptionsAnalysesEnum;
+	      else if (strcmp(name,"ToolkitsOptionsStrings")==0) return ToolkitsOptionsStringsEnum;
+	      else if (strcmp(name,"QmuErrName")==0) return QmuErrNameEnum;
+	      else if (strcmp(name,"QmuInName")==0) return QmuInNameEnum;
+	      else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
+	      else if (strcmp(name,"Regular")==0) return RegularEnum;
+	      else if (strcmp(name,"Scaled")==0) return ScaledEnum;
+	      else if (strcmp(name,"Separate")==0) return SeparateEnum;
+	      else if (strcmp(name,"Sset")==0) return SsetEnum;
+	      else if (strcmp(name,"Verbose")==0) return VerboseEnum;
+	      else if (strcmp(name,"TriangleInterp")==0) return TriangleInterpEnum;
+	      else if (strcmp(name,"BilinearInterp")==0) return BilinearInterpEnum;
+	      else if (strcmp(name,"NearestInterp")==0) return NearestInterpEnum;
+	      else if (strcmp(name,"XY")==0) return XYEnum;
+	      else if (strcmp(name,"XYZ")==0) return XYZEnum;
+	      else if (strcmp(name,"Dense")==0) return DenseEnum;
+	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
+	      else if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
+	      else if (strcmp(name,"Seq")==0) return SeqEnum;
+	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
+	      else if (strcmp(name,"Mumps")==0) return MumpsEnum;
+	      else if (strcmp(name,"Gsl")==0) return GslEnum;
+	      else if (strcmp(name,"Option")==0) return OptionEnum;
+	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
+	      else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
+	      else if (strcmp(name,"OptionStruct")==0) return OptionStructEnum;
+	      else if (strcmp(name,"Cuffey")==0) return CuffeyEnum;
+	      else if (strcmp(name,"Paterson")==0) return PatersonEnum;
+	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
+	      else if (strcmp(name,"LliboutryDuval")==0) return LliboutryDuvalEnum;
+	      else if (strcmp(name,"TransientIslevelset")==0) return TransientIslevelsetEnum;
+	      else if (strcmp(name,"ExtrapolationVariable")==0) return ExtrapolationVariableEnum;
+	      else if (strcmp(name,"IceMaskNodeActivation")==0) return IceMaskNodeActivationEnum;
+	      else if (strcmp(name,"LevelsetfunctionSlopeX")==0) return LevelsetfunctionSlopeXEnum;
+	      else if (strcmp(name,"LevelsetfunctionSlopeY")==0) return LevelsetfunctionSlopeYEnum;
+	      else if (strcmp(name,"LevelsetfunctionPicard")==0) return LevelsetfunctionPicardEnum;
+	      else if (strcmp(name,"MaximumNumberOfDefinitions")==0) return MaximumNumberOfDefinitionsEnum;
+         else stage=7;
+   }
+	/*If we reach this point, the string provided has not been found*/
+	if(notfounderror)
+		_error_("Enum " << name << " not found");
+	else
+		return -1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Synchronize.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Enum/Synchronize.sh	(revision 18231)
@@ -0,0 +1,249 @@
+#!/bin/bash
+#Synchronize EnumToStringx.cpp and StringToEnumx.cpp and matlab Enums
+
+#Get all lines of EnumDefinitions2.h which hold Enum | remove all commas > put everything in file temp
+cat EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-zA-Z]Enum," -e "MaximumNumberOfDefinitionsEnum" | grep -v include | sed -e "s/,/ /g" | awk '{print $1}' > temp
+
+#Removed existing files
+rm $ISSM_DIR/src/m/enum/*.m
+rm $ISSM_DIR/src/m/enum/*.py
+rm $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+rm $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+
+#Get number of enums
+NUMENUMS=$(wc -l temp | awk '{printf("%s",$1);}');
+
+#Deal with Analyses
+#Build EnumToAnalysis.cpp {{{
+#Header
+cat <<END > $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+/*
+* \file EnumToAnalysis.cpp
+* \brief: output class depending on enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include "./analyses.h"
+#include "../shared/shared.h"
+
+Analysis* EnumToAnalysis(int analysis_enum){
+
+	switch(analysis_enum){
+END
+#core
+cat temp | grep [a-zA-Z0-9]Analysis | \
+	grep -v DefaultAnalysis | grep -v FlaimAnalysis | grep -v SurfaceSlopeAnalysis | grep -v BedSlopeAnalysis | \
+	awk '{print "\t\t#ifdef _HAVE_"toupper(substr($1,1,length($1)-12))"_\n\t\t" "case " $1" : return new " substr($1,1,length($1)-4) "();\n\t\t#endif"}' \
+		>> $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+
+#Footer
+cat <<END >> $ISSM_DIR/src/c/analyses/EnumToAnalysis.cpp
+		default : _error_("enum provided not supported ("<<EnumToStringx(analysis_enum)<<")");
+	}
+}
+END
+#}}}
+#Build analyses.m4{{{
+#Header
+cat <<END > $ISSM_DIR/m4/analyses.m4
+
+dnl   WARNING: DO NOT MODIFY THIS FILE
+dnl            this file has been automatically generated by Synchronize.sh
+dnl            Please read README for more information
+
+# AX_ANALYSES_SELECTION
+# -----------------
+# Check for analyses compilation
+AC_DEFUN([AX_ANALYSES_SELECTION],
+[
+
+END
+#core
+cat temp | grep [a-zA-Z0-9]Analysis | \
+	grep -v DefaultAnalysis | grep -v FlaimAnalysis | grep -v SurfaceSlopeAnalysis | grep -v BedSlopeAnalysis | \
+	sed -e "s/AnalysisEnum//g" | \
+	awk '{print "dnl with-" $1"{{{\n\
+AC_ARG_WITH([" $1"],\n\
+\tAS_HELP_STRING([--with-" $1" = YES], [compile with " $1" capabilities (default is yes)]),\n\
+\t[" toupper($1)"=$withval],[" toupper($1)"=yes])\n\
+AC_MSG_CHECKING(for " $1" capability compilation)\n\n\
+HAVE_"  toupper($1)"=no \n\
+if test \"x$"  toupper($1)"\" = \"xyes\"; then\n\
+	HAVE_"  toupper($1)"=yes\n\
+	AC_DEFINE([_HAVE_"  toupper($1)"_],[1],[with " $1"capability])\n\
+fi\n\
+AM_CONDITIONAL([" toupper($1)"], [test x$HAVE_" toupper($1)" = xyes])\n\
+AC_MSG_RESULT($HAVE_" toupper($1)")\n\
+dnl }}}"}' \
+	>> $ISSM_DIR/m4/analyses.m4
+
+#Footer
+cat <<END >> $ISSM_DIR/m4/analyses.m4
+
+])
+END
+#}}}
+
+#Enum to String conversions
+#Build EnumToStringx.cpp {{{
+#Header
+cat <<END >  $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+/*
+* \file EnumToStringx.cpp:
+* \brief: output string associated with enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+END
+#core
+cat temp |  awk '{print "\t\t" "case " $1" : return \"" substr($1,1,length($1)-4) "\";"}' >> $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+#Footer
+cat <<END >> $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=xNew<char>(len+1);
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
+END
+#}}}
+#Build StringToEnumx.cpp {{{
+#Header
+cat <<END > $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+/*
+* \file StringToEnumx.cpp:
+* \brief: output enum associated with string
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+
+int  StringToEnumx(const char* name,bool notfounderror){
+
+   int  stage=1;
+
+END
+
+#core
+i1=1;
+i2=120;
+for (( i=1 ; i<=100 ; i++ )); do
+	echo "   if(stage==$i){" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	awk -v i1=$i1 -v i2=$i2 '{if(NR>=i1 && NR<=i2) print $0 }' temp |
+	awk '{print "\t" ((NR==1)?"      if":"      else if") " (strcmp(name,\"" substr($1,1,length($1)-4) "\")==0) return " $1 ";"}' >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	echo "         else stage=$(($i+1));" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	echo "   }" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	
+	if [ $i2 -ge $NUMENUMS ]; then break; fi
+	let i1=$i1+120
+	let i2=$i2+120
+done
+
+#footer
+cat <<END >> $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+	/*If we reach this point, the string provided has not been found*/
+	if(notfounderror)
+		_error_("Enum " << name << " not found");
+	else
+		return -1;
+}
+END
+#}}}
+
+#Deal with Python Enums
+#Build EnumDefinitions.py{{{
+cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
+from StringToEnum import StringToEnum
+
+"""
+
+WARNING: DO NOT MODIFY THIS FILE
+this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+Please read src/c/shared/Enum/README for more information
+
+"""
+
+END
+#core
+cat temp |  awk '{print "def " $1"(): return StringToEnum(\"" substr($1,1,length($1)-4) "\")[0]"}' >> $ISSM_DIR/src/m/enum/EnumDefinitions.py
+#}}}
+
+#Deal with Matlab Enums`
+ENUM=0;
+
+for NAMEENUM in $(cat temp); do
+
+	#Get name and enum of the line i
+	NAME=$(echo $NAMEENUM | sed -e "s/Enum//g")
+	#offset Enum by one (Enum begins with 0 and not 1!)
+	let ENUM=$ENUM+1
+
+	#print info {{{
+	if [ $ENUM -lt 10 ]
+	then
+		printf "\r                                                                      "
+		printf "\r  $ENUM/$NUMENUMS Adding "$NAME"..."
+	else
+		if [ $ENUM -lt 100 ]
+		then
+			printf "\r                                                                      "
+			printf "\r $ENUM/$NUMENUMS Adding "$NAME"..."
+		else
+			printf "\r                                                                      "
+			printf "\r$ENUM/$NUMENUMS Adding "$NAME"..."
+		fi
+	fi
+	#}}}
+	#Add case to matlabenum file{{{
+	cat <<END > $ISSM_DIR"/src/m/enum/"$(echo $NAMEENUM".m")
+function macro=$(echo $NAMEENUM)()
+%$(echo $NAMEENUM | awk {'print toupper($1)'}) - Enum of $(echo $NAME)
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=$NAMEENUM()
+
+macro=StringToEnum('$NAME');
+END
+#}}}
+
+done
+#clean up{{{
+rm temp
+#}}}
+#print info {{{
+printf "\r                                                                      "
+printf "\rdone!\n"
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/Exceptions.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/Exceptions.cpp	(revision 18231)
@@ -0,0 +1,121 @@
+/* \file Exceptions.cpp
+ * \brief: implementation of the exceptions.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include <cstdio>
+#include "./exceptions.h"
+#include "../io/Print/Print.h"
+#include "../io/Comm/IssmComm.h"
+#include "../MemOps/MemOps.h"
+
+ErrorException::ErrorException(const string & what_arg){/*{{{*/
+
+	int len;
+	len           = strlen(what_arg.c_str())+1;
+	what_str      = new char[len];
+	memcpy(what_str,what_arg.c_str(),len);
+
+	file_name     = NULL;
+	function_name = NULL;
+	file_line     = 0;
+
+}/*}}}*/
+ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
+
+	int len;
+
+	len      = strlen(what_arg.c_str())+1;
+	what_str = new char[len];
+	memcpy(what_str,what_arg.c_str(),len);
+
+	len       = strlen(what_file.c_str())+1;
+	file_name = new char[len];
+	memcpy(file_name,what_file.c_str(),len);
+
+	len           = strlen(what_function.c_str())+1;
+	function_name = new char[len];
+	memcpy(function_name,what_function.c_str(),len);
+
+	file_line= what_line;
+	/*When error messages are not shown properly, uncomment the following line*/
+	//this->Report();
+
+}/*}}}*/
+ErrorException::~ErrorException() throw(){/*{{{*/
+	delete [] what_str;
+	delete [] file_name;
+	delete [] function_name;
+}/*}}}*/
+const char* ErrorException::what() const throw(){/*{{{*/
+	return what_str;
+}/*}}}*/
+void ErrorException::Report() const{/*{{{*/
+
+	/*WINDOWS*/
+	if(!function_name || file_line==0){
+		_printf_("Error message: " << what());
+		return;
+	}
+
+	/*recover my_rank and num_procs:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
+	if(num_procs==1){
+		_printf_("\n??? Error in ==> " << file_name << ":" << file_line << "\n");
+		_printf_(function_name << " error message: " << what() << "\n\n");
+	}
+	else{
+		_printf_("\n[" << my_rank<< "] ??? Error using ==> " << file_name << ":" << file_line << "\n");
+		_printf_(  "[" << my_rank << "] " << function_name << " error message: " << what() << "\n\n");
+	}
+
+	return;
+}/*}}}*/
+const char* ErrorException::MatlabReport() const{/*{{{*/
+
+	/*Output*/
+	std::ostringstream buffer;
+	char *message = NULL;
+
+	/*WINDOWS*/
+	if(!function_name || file_line==0){ 
+		buffer << " error message: " << this->what_str;
+	}
+	else{
+		buffer << "\nError in ==> " << this->file_name << ":" << file_line << "\n";
+		buffer << this->function_name << " error message: " << this->what_str;
+	}
+
+	/*Convert std::ostringstream to std::string and then create char* */
+	std::string buffer2 = buffer.str();
+	message = xNew<char>(strlen(buffer2.c_str())+1); sprintf(message,"%s",buffer2.c_str());
+	return message;
+}/*}}}*/
+const char* ErrorException::PythonReport() const{/*{{{*/
+
+	/*Output*/
+	std::ostringstream buffer;
+	char *message = NULL;
+
+	/*WINDOWS*/
+	if(!function_name || file_line==0){ 
+		buffer << " error message: " << this->what_str;
+	}
+	else{
+		buffer << "\nError in ==> " << this->file_name << ":" << file_line << "\n";
+		buffer << this->function_name << " error message: " << this->what_str;
+	}
+
+	/*Convert std::ostringstream to std::string and then create char* */
+	std::string buffer2 = buffer.str();
+	message = xNew<char>(strlen(buffer2.c_str())+1); sprintf(message,"%s",buffer2.c_str());
+	return message;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/exceptions.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exceptions/exceptions.h	(revision 18231)
@@ -0,0 +1,94 @@
+/*!\file exceptions.h
+ * \brief: two types of exceptions are handled for now. Errors, and 
+ * warnings. Those exceptions are trapped provided the matlab modules 
+ * are started using MODULEBOOT, and ended using MODULEEND. These are 
+ * macros hiding try, catch statements. This header file defines our 
+ * own exceptions
+ */
+
+#ifndef _MY_EXCEPTIONS_H_
+#define _MY_EXCEPTIONS_H_
+
+#include <exception>
+#include <string>
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+
+using namespace std;
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*macros: */
+/* _assert_ {{{*/
+/*Assertion macro: do nothing if macro _ISSM_DEBUG_ undefined*/
+#ifdef _ISSM_DEBUG_ 
+#define _assert_(statement)\
+  if (!(statement)) _error_("Assertion \""<<#statement<<"\" failed, please report bug to "<<PACKAGE_BUGREPORT)
+#else
+#define _assert_(ignore)\
+  ((void) 0)
+#endif
+/*}}}*/
+/* _error_ {{{*/
+/*new Error exception macro*/
+#ifdef _INTEL_WIN_
+#define _error_(StreamArgs)\
+   do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#else
+#define _error_(StreamArgs)\
+	do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(__FILE__,__func__,__LINE__,aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#endif
+/*}}}*/
+/* ExceptionTrapBegin/ExceptionTrapEnd {{{*/
+
+/*The following macros hide the error exception handling in a matlab module. Just put 
+ * ExceptionTrapBegin(); and ExceptionTrapEnd(); at the beginning and end of a module, and c++ exceptions 
+ * will be trapped. Really nifty!*/
+
+#define ExceptionTrapBegin(); \
+	try{
+
+#define ExceptionTrapEnd(); }\
+	catch(ErrorException &exception){\
+		exception.Report();\
+		return 0;\
+	}\
+	catch(exception& e) {\
+		_printf_("Standard exception: " << e.what() << "\n\n");\
+		return 0;\
+	}\
+	catch(...){\
+		_printf_("An unexpected error occurred \n\n");\
+		return 0;\
+	}
+/*}}}*/
+
+/*ISSM exception class: */
+class ErrorException: public exception { /*{{{*/
+
+	char* what_str;
+	char* function_name;
+	char* file_name;
+	int   file_line;
+
+	public:
+	ErrorException(const string &what_arg); //for windows
+	ErrorException(const string &what_file,const string& what_function,int what_line,const string& what_arg);//UNIX
+	~ErrorException() throw();
+	virtual const char *what() const throw();
+	void Report() const;
+	const char* MatlabReport() const;
+	const char* PythonReport() const;
+
+};
+/*}}}*/
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.cpp	(revision 18231)
@@ -0,0 +1,99 @@
+/*!\file:  Exp.cpp
+ * \brief Exp.cpp: write the vertex coordinates defined in a domain 
+ * outline from Argus (.exp file). The first contour in the file is for 
+ * the outside domain outline. 
+ */
+#include <stdio.h>
+#include <math.h>
+
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+#include "./exp.h"
+
+int ExpWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,char* domainname){/*{{{*/
+
+	/*I/O: */
+	FILE* fid=NULL;
+
+	/*open domain outline file for writing: */
+	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
+
+	/*Start writing profiles: */
+	for(int counter=0;counter<nprof;counter++){
+
+		/*Write header: */
+		fprintf(fid,"## Name:%s\n",domainname);
+		fprintf(fid,"## Icon:0\n");
+		fprintf(fid,"# Points Count	Value\n");
+		fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
+		fprintf(fid,"# X pos	Y pos\n");
+
+		/*Write vertices: */
+		for(int i=0;i<profnvertices[counter];i++){
+			fprintf(fid,"%lf\t%lf\n",pprofx[counter][i],pprofy[counter][i]);
+		}
+
+		/*Write blank line: */
+		if(counter<nprof-1) fprintf(fid,"\n");
+	}
+
+	/*close Exp file: */
+	fclose(fid);
+
+	return 1;
+}/*}}}*/
+int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){ /*{{{*/
+
+	double x0,y0;
+
+	/*Go through all vertices of the mesh:*/
+	for(int i=0;i<nods;i++){
+		if (in[i]){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+		/*pick up vertex: */
+		x0=x[i];
+		y0=y[i];
+		if (pnpoly(numvertices,xc,yc,x0,y0,edgevalue)){
+			in[i]=1.;
+		}
+		else{
+			in[i]=0.;
+		}
+	}
+
+	return 1;
+}
+/*}}}*/
+/*pnpoly{{{*/
+int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
+	int i, j, c = 0;
+	double n1, n2, normp, scalar;
+
+	/*first test, are they colinear? if yes, is the point in the middle of the segment*/
+	if (edgevalue != 2 ){
+		for (i = 0, j = npol-1; i < npol; j = i++) {
+			n1=pow(yp[i]-yp[j],2.0)+pow(xp[i]-xp[j],2.0);
+			n2=pow(y-yp[j],2.0)+pow(x-xp[j],2.0);
+			normp=pow(n1*n2,0.5);
+			scalar=(yp[i]-yp[j])*(y-yp[j])+(xp[i]-xp[j])*(x-xp[j]);
+
+			if (scalar == normp){
+				if (n2<=n1){
+					c = edgevalue;
+					return c;
+				}
+			}
+		}
+	}
+	/*second test : point is neither on a vertex, nor on a side, where is it ?*/
+	for (i = 0, j = npol-1; i < npol; j = i++) {
+		if ((((yp[i]<=y) && (y<yp[j])) ||
+					((yp[j]<=y) && (y<yp[i]))) &&
+				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])){
+			c = !c;
+		}
+	}
+	return c;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Exp/exp.h	(revision 18231)
@@ -0,0 +1,176 @@
+/* \file exp.h
+ * \brief: header file for contour (argus type, files in .exp extension) operations
+ */
+
+#ifndef _EXP_H_
+#define _EXP_H_
+
+#include <cstring>
+#include "../Numerics/recast.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue);
+int ExpWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,char* domainname);
+int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue);
+
+template <class doubletype> int IsInPoly(doubletype* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){ /*{{{*/
+
+	int i;
+	double x0,y0;
+	doubletype value;
+	double xmin=xc[0];
+	double xmax=xc[0];
+	double ymin=yc[0];
+	double ymax=yc[0];
+
+	/*Get extrema*/
+	for (i=1;i<numvertices;i++){
+		if(xc[i]<xmin) xmin=xc[i];
+		if(xc[i]>xmax) xmax=xc[i];
+		if(yc[i]<ymin) ymin=yc[i];
+		if(yc[i]>ymax) ymax=yc[i];
+	}
+
+	/*Go through all vertices of the mesh:*/
+	for (i=i0;i<i1;i++){
+
+		//Get current value of value[i] -> do not change it if != 0
+		value=in[i];
+		if (reCast<bool,doubletype>(value)){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+
+		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
+		x0=x[i]; y0=y[i];
+		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
+			value=0;
+		}
+		else{
+			value=pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
+		}
+		in[i]=value;
+	}
+	 return 1;
+}/*}}}*/
+template <class doubletype> int ExpRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){ /*{{{*/
+
+	/*indexing: */
+	int i,counter;
+
+	/*I/O: */
+	FILE   *fid = NULL;
+	char    chardummy[256];
+	double  ddummy;
+
+	/*output: */
+	int          nprof;                //number of profiles in the domainname file
+	int         *profnvertices = NULL; //array holding the number of vertices for the nprof profiles
+	doubletype **pprofx        = NULL; //array of profiles x coordinates
+	doubletype **pprofy        = NULL; //array of profiles y coordinates
+	bool        *closed        = NULL; //array holding closed flags for the nprof profiles
+
+	/*For each profile: */
+	int         n;
+	doubletype *x  = NULL;
+	doubletype *y  = NULL;
+	bool        cl;
+
+	/*open domain outline file for reading: */
+	if ((fid=fopen(domainname,"r"))==NULL){
+		_error_("could not find domain file " << domainname); 
+	}
+
+	/*Do a first pass through the domainname file, to figure out how many profiles we need to read: */
+	nprof=1;
+	for(;;){
+		//## Name:filename
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//## Icon:0
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//# Points Count Value
+		if(fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy)!=4) _error_("Could not read " << domainname);
+		if(fscanf(fid,"%20i %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
+		//# X pos Y pos
+		if(fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy)!=5) _error_("Could not read " << domainname);
+		for (i=0;i<n;i++){
+			if(fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy)!=2){
+				_error_("Could not read coordinate of vertex "<< i <<" of "<<domainname);
+			}
+		}
+		/*check whether we are at the end of the file, otherwise, keep reading next profile:*/
+		if(feof(fid)) break;
+		nprof++;
+	}
+
+	/*Allocate and initialize all the profiles: */
+	profnvertices = xNew<int>(nprof);
+	pprofx        = xNew<doubletype*>(nprof);
+	pprofy        = xNew<doubletype*>(nprof);
+	for (i=0;i<nprof;i++){
+		pprofx[i] = NULL;
+		pprofy[i] = NULL;
+	}
+	closed=xNew<bool>(nprof);
+
+	/*Reaset file pointer to beginning of file: */
+	fseek(fid,0,SEEK_SET);
+
+	/*Start reading profiles: */
+	for(counter=0;counter<nprof;counter++){
+
+		/*Skip header: */
+		//## Name:filename
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//## Icon:0
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//# Points Count Value
+		if(fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy)!=4) _error_("Could not read " << domainname);
+
+		/*Get number of profile vertices: */
+		if(fscanf(fid,"%20i %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
+
+		/*Skip next line: */
+		//# X pos Y pos
+		if(fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy)!=5) _error_("Could not read " << domainname);
+
+		/*Allocate vertices: */
+		x=xNew<doubletype>(n);
+		y=xNew<doubletype>(n);
+
+		/*Read vertices: */
+		for (i=0;i<n;i++){
+			if(fscanf(fid,"%20lf %20lf\n",&x[i],&y[i])!=2){
+				_error_("Could not read coordinate of vertex "<<i<<" of "<<domainname);
+			}
+		}
+
+		/*Now check that we are dealing with open contours: */
+		cl=false;
+		if((x[0]==x[n-1]) && (y[0]==y[n-1])){
+			cl=true;
+		}
+
+		/*Assign pointers: */
+		profnvertices[counter]=n;
+		pprofx[counter]=x;
+		pprofy[counter]=y;
+		closed[counter]=cl;
+	}
+
+	/*close domain outline file: */
+	fclose(fid);
+
+	/*Assign output pointers: */
+	*pnprof=nprof;
+	*pprofnvertices=profnvertices;
+	*ppprofx=pprofx;
+	*ppprofy=pprofy;
+	if(pclosed) *pclosed=closed;
+	else         xDelete<bool>(closed);
+	return 1;
+
+} /*}}}*/
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 18231)
@@ -0,0 +1,146 @@
+/*!\file fx.cpp
+ * \brief: analytical fonction for FS 
+ * test case for a cube with Dirichlet conditions on all faces and no variation in z
+ * case 1: 2d test with quadratic functions
+ * case 2: 2d test with sinusoidal functions
+ * case 3: 3d test with quadratic functions
+ * case 4: 3d test with sinusoidal functions
+ * case 5: 3d test with sinusoidal functions, no variations with z, non homogeneous Dirichlet conditions
+ * case 6: 3d test with sinusoidal functions, non homogeneous Dirichlet conditions
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Numerics/constants.h"
+#include "./fsanalyticals.h"
+#include "../shared.h"
+
+IssmDouble fx(IssmDouble x,IssmDouble y,IssmDouble z,int testid){ /*{{{*/ 
+	IssmDouble p=2;
+	IssmDouble q=2;
+	IssmDouble a=1;
+
+	switch(testid){
+		case 1:
+			z=y;
+			return  4*pow(x, 2)*z*pow(x - 1, 2) + 4*pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*pow(x, 2)*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*pow(x - 1, 2)*(2*z - 1) + 16*x*z*(x - 1)*(z - 1)*(2*z - 1) - 4*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 6*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + 4*z*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 2*z*(6*pow(x, 2) - 6*x + 1) + z - 1.0L/2.0L;
+		case 2: case 11:
+			z=y;
+			return 10*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 3)*pow(sin(PI*p*z), 2)*cos(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 3)*pow(cos(PI*p*z), 3) - 6*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2)*cos(PI*p*z) + PI*q*sin(PI*q*z)*cos(PI*q*x);
+		case 3: 
+			return 4*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 4*pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1) + 4*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 4*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 4*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) + 16*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 2*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 4*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1) + y - 1.0L/2.0L;
+		case 4: 
+			return 4*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) + 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x) + PI*q*sin(PI*q*y)*sin(PI*q*z)*cos(PI*q*x);
+		case 5: 
+			return 2.*(cos(PI*p*x) - 1)*PI*PI*p*p*sin(PI*p*y) + 3*PI*PI*p*p*sin(PI*p*y)*cos(PI*p*x) + PI*q*sin(PI*q*y)*cos(PI*q*x);
+		case 6: 
+			return 4. * PI*PI * p*p * (cos(p*PI*x)-1) * sin(p*PI*y) * sin(p*PI*z)+ 2. * PI*PI*p*p*  sin(p*PI*y)    * sin(p*PI*z) * cos(p*PI*x) + q * PI * cos(q*PI*x) * sin(q*PI*y) * sin(q*PI*z);
+		case 7: 
+			z=y;
+			return 4*pow(x, 2)*z*pow(x - 1, 2) + 4*pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*pow(x, 2)*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*pow(x - 1, 2)*(2*z - 1) + 16*x*z*(x - 1)*(z - 1)*(2*z - 1) - 4*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 6*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + 4*z*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 2*z*(6*pow(x, 2) - 6*x + 1) + 1;
+		case 8: case 18:
+			return 1.0;
+		case 9:
+			return 4*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) + 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x) + 2*x*z;
+		case 10:
+			return 4*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) + 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x) + PI*q*pow(z, a)*sin(PI*q*y)*cos(PI*q*x);
+		case 21:
+			z=y;
+			return z - 4.0L/3.0L*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) + 2*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) - 1.0L/2.0L + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+		case 24:
+			return 2*pow(2, 1.0L/3.0L)*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) - 2.0L/3.0L*pow(2, 1.0L/3.0L)*PI*p*(12*pow(PI, 3)*pow(p, 3)*sin(PI*p*x)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2)*cos(PI*p*x) - (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)))*sin(PI*p*x)*sin(PI*p*y)*sin(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + PI*q*sin(PI*q*y)*sin(PI*q*z)*cos(PI*q*x) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*sin(PI*p*y)*pow(sin(PI*p*z), 2)*cos(PI*p*y) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*sin(PI*p*z)*cos(PI*p*z) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(-2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + pow(2, 1.0L/3.0L)*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L);
+
+		case 101: 
+			return 4*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 8*pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1) + 4*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 12*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - 6*x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 12*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) + 32*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 6*x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 6*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 8*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 6*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1);
+		default:
+			_error_("FS analytical solution"<<testid<<" not implemented yet");
+	}
+}
+/*}}}*/
+IssmDouble fy(IssmDouble x,IssmDouble y,IssmDouble z,int testid){ /*{{{*/ 
+	IssmDouble p=2;
+	IssmDouble q=2;
+	IssmDouble a=1;
+
+	switch(testid){
+		case 1:
+			z=y;
+			return -8*pow(x, 3) + 4*pow(x, 2)*z*(x - 1)*(z - 1) + 2*pow(x, 2)*z*(x - 1)*(2*z - 1) + 2*pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 12*pow(x, 2) + 4*x*z*pow(x - 1, 2)*(z - 1) + 2*x*z*pow(x - 1, 2)*(2*z - 1) + 2*x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*x - 6*pow(z, 4)*(2*x - 1) + 12*pow(z, 3)*(2*x - 1) - 6*pow(z, 2)*(2*x - 1) - 24*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + 24*z*(2*pow(x, 3) - 3*pow(x, 2) + x) - 1.0L/2.0L;
+		case 2: case 11:
+			z=y;
+			return -10*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*z), 3)*cos(PI*p*x) + 6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*sin(PI*p*z)*cos(PI*p*x)*pow(cos(PI*p*z), 2) + 2*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*z), 3)*pow(cos(PI*p*x), 3) + PI*q*sin(PI*q*x)*cos(PI*q*z);
+		case 3: 
+			return 4*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + 2*pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + 2*pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 4*x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) - 4*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) - 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2) + 4*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 16*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 2*x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 4*x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1) + x - 4*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - 2*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 1.0L/2.0L;
+		case 4: 
+			return -2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y) + PI*q*sin(PI*q*x)*sin(PI*q*z)*cos(PI*q*y);
+		case 5: 
+			return -(cos(PI*p*y) - 1)*PI*PI*p*p*sin(PI*p*x) + PI*q*sin(PI*q*x)*cos(PI*q*y);
+		case 6: 
+			return - 4. * PI*PI * p*p * (cos(p*PI*y)-1) * sin(p*PI*x) * sin(p*PI*z)-  2. * PI*PI * p*p *  sin(p*PI*x)    * cos(p*PI*y) * sin(p*PI*z)+ q * PI * sin(q*PI*x) * cos(q*PI*y) * sin(q*PI*z);
+		case 7: 
+			z=y;
+			return -8*pow(x, 3) + 4*pow(x, 2)*z*(x - 1)*(z - 1) + 2*pow(x, 2)*z*(x - 1)*(2*z - 1) + 2*pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 12*pow(x, 2) + 4*x*z*pow(x - 1, 2)*(z - 1) + 2*x*z*pow(x - 1, 2)*(2*z - 1) + 2*x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 4*x - 6*pow(z, 4)*(2*x - 1) + 12*pow(z, 3)*(2*x - 1) - 6*pow(z, 2)*(2*x - 1) - 24*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + 24*z*(2*pow(x, 3) - 3*pow(x, 2) + x);
+		case 8: case 18:
+			return 1.0;
+		case 9: 
+			return -2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y) + 2*y*z;
+		case 10:
+			return -2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y) + PI*q*pow(z, a)*sin(PI*q*x)*cos(PI*q*y);
+		case 21:
+			z=y;
+			return x + (4.0L/3.0L)*pow(2, 1.0L/3.0L)*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/2.0L - 2*pow(2, 1.0L/3.0L)*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+		case 24:
+			return -pow(2, 1.0L/3.0L)*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) + (1.0L/3.0L)*pow(2, 1.0L/3.0L)*PI*p*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*sin(PI*p*y)*pow(sin(PI*p*z), 2)*cos(PI*p*y) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z)))*sin(PI*p*x)*sin(PI*p*y)*sin(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + PI*q*sin(PI*q*x)*sin(PI*q*z)*cos(PI*q*y) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(12*pow(PI, 3)*pow(p, 3)*sin(PI*p*x)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2)*cos(PI*p*x) - (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*sin(PI*p*z)*cos(PI*p*z) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(-2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L); 
+
+		case 101: 
+			return 12*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + 6*pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + 6*pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 8*x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) - 4*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) - 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2) + 12*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 6*x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 32*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 6*x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 8*x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 4*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - 2*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1);
+		default:
+			_error_("FS analytical solution"<<testid<<" not implemented yet");
+	}
+}
+/*}}}*/
+IssmDouble fz(IssmDouble x,IssmDouble y,IssmDouble z,int testid){ /*{{{*/ 
+	IssmDouble p = 2.0;  
+	IssmDouble q = 2.0;   
+	IssmDouble a = 1.0;
+
+	switch(testid){
+		case 1: case 2: case 7: case 8: case 11: case 18: case 21:
+			return 0.;
+		case 3: 
+			return 2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1) + 2*pow(x, 2)*y*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1) - 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) - 2*x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + 2*x*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*y*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1);
+		case 4: 
+			return -2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*z) - 1)*sin(PI*p*x)*sin(PI*p*y) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z) + PI*q*sin(PI*q*x)*sin(PI*q*y)*cos(PI*q*z);
+		case 5: 
+			return 2*PI*PI*p*p*sin(PI*p*x)*sin(PI*p*y);
+		case 6: 
+			return - 2. * PI*PI * p*p * (cos(p*PI*z)-1) * sin(p*PI*x) * sin(p*PI*y)-PI*PI * p*p *  sin(p*PI*x)    * sin(p*PI*y) * cos(p*PI*z)+ q * PI * sin(q*PI*x) * sin(q*PI*y) * cos(q*PI*z);
+		case 9:
+			return -2*pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z) + pow(x, 2) + pow(y, 2);
+		case 10:
+			return a*pow(z, a - 1)*(sin(PI*q*x)*sin(PI*q*y) + 1) - 2*pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z);
+		case 24:
+			return -pow(2, 1.0L/3.0L)*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) + (1.0L/3.0L)*pow(2, 1.0L/3.0L)*PI*p*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*sin(PI*p*z)*cos(PI*p*z) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(-2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)))*sin(PI*p*x)*sin(PI*p*y)*sin(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + PI*q*sin(PI*q*x)*sin(PI*q*y)*cos(PI*q*z) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*sin(PI*p*y)*pow(sin(PI*p*z), 2)*cos(PI*p*y) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*sin(PI*p*x)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2)*cos(PI*p*x) - (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L);
+		default:
+			_error_("FS analytical solution"<<testid<<" not implemented yet");
+	}
+}
+/*}}}*/
+IssmDouble alpha(IssmDouble x,IssmDouble y,IssmDouble z,int testid){ /*{{{*/ 
+	IssmDouble p = 2.0;  
+	IssmDouble q = 2.0;   
+
+	switch(testid){
+		case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 21:
+			return 0.;
+		case 11:
+			z=y;
+			return -10*PI*p*sqrt((9.0L/25.0L)*pow(PI, 2)*pow(p, 2)*pow(cos(2*PI*p*x), 2) + 1)*(9*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(cos(2*PI*p*x), 2)*pow(cos(PI*p*z), 2) - 9*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2)*pow(cos(2*PI*p*x), 2) + 90*PI*p*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*x)*cos(2*PI*p*x)*cos(PI*p*z) - 25*pow(sin(PI*p*x), 2)*pow(cos(PI*p*z), 2) + 25*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2))/((9*pow(PI, 2)*pow(p, 2)*pow(cos(2*PI*p*x), 2) + 25)*(3*PI*p*sin(PI*p*z)*cos(PI*p*x)*cos(2*PI*p*x) - 5*sin(PI*p*x)*cos(PI*p*z))*sin(PI*p*x)*sin(PI*p*z));
+		case 18:
+			return (120.0L/109.0L)*sqrt(109.)/(10*x - 3*z);
+		default:
+			_error_("FS analytical solution"<<testid<<" not implemented yet");
+	}
+}
+/*}}}*/
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/FSanalyticals/fsanalyticals.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file: elements.h
+ * \brief prototypes for elements.h
+ */ 
+
+#ifndef _SHARED_ANALYTICALS_H_
+#define _SHARED_ANALYTICALS_H_
+
+#include "../Numerics/types.h"
+
+IssmDouble fx(IssmDouble x_coord, IssmDouble y_coord, IssmDouble z_coord, int testid);
+IssmDouble fy(IssmDouble x_coord, IssmDouble y_coord, IssmDouble z_coord, int testid);
+IssmDouble fz(IssmDouble x_coord, IssmDouble y_coord, IssmDouble z_coord, int testid);
+IssmDouble alpha(IssmDouble x_coord, IssmDouble y_coord, IssmDouble z_coord, int testid);
+
+#endif //ifndef _SHARED_ANALYTICALS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Ll2xyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Ll2xyx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Ll2xyx.cpp	(revision 18231)
@@ -0,0 +1,124 @@
+/*!\file Ll2xyx.cpp
+ */
+
+#include "../../shared/shared.h"
+#include "./latlong.h"
+#include <math.h>
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	double  central_meridian,standard_parallel;
+
+	Ll2xydef(&central_meridian,&standard_parallel,sgn);
+
+	return(Ll2xyx(x,y,lat,lon,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  re,ex2,ex;
+	double  latitude,longitude;
+	double  T,rho,sl,tc,mc;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Radius of the earth in meters  */
+	re  = 6378.273*1.e3;
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2 = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex  =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	for(i=0; i<ncoord; i++){
+		latitude  = fabs(lat[i]) * PI/180.;
+		longitude = (lon[i] + delta) * PI/180.;
+
+		/*  compute X and Y in grid coordinates.  */
+		T = tan(PI/4.-latitude/2.) / pow(((1.-ex*sin(latitude))/(1.+ex*sin(latitude))),(ex/2.));
+
+		if ((90. - slat) < 1.e-5)
+			rho = 2.*re*T/sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)));
+		else {
+			sl  = slat*PI/180.;
+			tc  = tan(PI/4.-sl/2.)/pow(((1.-ex*sin(sl))/(1.+ex*sin(sl))),(ex/2.));
+			mc  = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2)));
+			rho = re*mc*T/tc;
+		}
+
+		y[i]= -rho*(double)sgn*cos(sgn*longitude);
+		x[i]=  rho*(double)sgn*sin(sgn*longitude);
+
+		if (latitude>= PI/2.){
+			x[i] = 0.0;
+			y[i] = 0.0;
+			iret=1;
+		}
+	}
+	return(iret);
+}
+
+void Ll2xydef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn ==  1) {
+		*pdelta= 45;
+		*pslat = 70;
+		if(flag) _printf0_("Info: creating coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		if(flag) _printf0_("Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Xy2llx.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Xy2llx.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/Xy2llx.cpp	(revision 18231)
@@ -0,0 +1,132 @@
+/*!\file Xy2llx.cpp
+ */
+
+#include "../../shared/shared.h"
+#include "./latlong.h"
+#include <math.h>
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	double  central_meridian,standard_parallel;
+
+	Xy2lldef(&central_meridian,&standard_parallel,sgn);
+
+	return(Xy2llx(lat,lon,x,y,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  re,ex2,ex;
+	double  sl,rho,cm,T,chi;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Radius of the earth in meters  */
+	re   = 6378.273e+3;
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2  = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex   =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	for(i=0; i<ncoord; i++){
+		sl = slat*PI/180.;
+		cm = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2)));
+		rho= sqrt(pow(x[i],2) + pow(y[i],2));
+		T  = tan((PI/4.0) - (sl/2.0))/pow(((1.0-ex*sin(sl))/(1.0+ex*sin(sl))),(ex/2.0));
+
+		if(fabs(slat-90.) < 1.e-5)
+			T =rho*sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)))/2./re;
+		else
+			T =rho*T/(re*cm);
+
+		chi = (PI / 2.0) - 2.0 * atan(T);
+		lat[i] = chi + ((ex2 / 2.0) + (5.0 * pow(ex2,2.0) / 24.0) + (pow(ex2,3.0) / 12.0)) *
+			   sin(2.0 * chi) + ((7.0 * pow(ex2,2.0) / 48.0) + (29.0 * pow(ex2,3.0) / 240.0)) *
+			   sin(4.0 * chi) + (7.0 * pow(ex2,3.0) / 120.0) * sin(6.0 * chi) ;
+
+		lat[i] = (double)sgn * lat[i];
+		lon[i] = atan2((double)sgn * x[i],-(double)sgn * y[i]);
+		lon[i] = (double)sgn * lon[i];
+
+		if(rho <= 0.1){
+			lat[i] = 90. * (double)sgn;
+			lon[i] = 0.0;
+			iret=1;
+		}
+
+		lon[i] = lon[i] * 180. / PI;
+		lat[i] = lat[i] * 180. / PI;
+		lon[i] = lon[i] - delta; 
+	}
+
+	return(iret);
+}
+
+void Xy2lldef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn == 1) {
+		*pdelta= 45;
+		*pslat = 70;
+		if(flag) _printf0_("Warning: expecting coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		if(flag) _printf0_("Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/latlong.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/latlong.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/LatLong/latlong.h	(revision 18231)
@@ -0,0 +1,16 @@
+/*!\file: latlong.h
+ * \brief prototypes for latlong.h
+ */ 
+
+#ifndef _SHARED_LATLONG_H_
+#define _SHARED_LATLONG_H_
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn);
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn, double central_meridian, double standard_parallel);
+void Ll2xydef(double* pdelta, double* pslat, int sgn);
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn);
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn, double central_meridian, double standard_parallel);
+void Xy2lldef(double* pdelta, double* pslat, int sgn);
+
+#endif //ifndef _SHARED_LATLONG_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/MatrixUtils.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/MatrixUtils.cpp	(revision 18231)
@@ -0,0 +1,475 @@
+/*!\file: MatrixUtils
+ * \brief triple multiply
+ */ 
+
+/*Headers*/
+/*{{{*/
+#include <stdio.h>
+#include <sys/types.h>
+#include <math.h>
+#include <float.h>    /*  DBL_EPSILON  */
+
+#include "./matrix.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+/*}}}*/
+
+int TripleMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int nrowc, int ncolc, int itrnc, IssmDouble* d, int iaddd){/*{{{*/
+	/*TripleMultiply    Perform triple matrix product a*b*c+d.*/
+
+	int         idima,idimb,idimc,idimd;
+	IssmDouble *dtemp;
+	_assert_(a && b && c && d);
+
+	/*  set up dimensions for triple product  */
+	if (!itrna){
+		idima=nrowa;
+		idimb=ncola;
+	}
+	else{
+		idima=ncola;
+		idimb=nrowa;
+	}
+
+	if (!itrnb){
+		if (nrowb != idimb) _error_("Matrix A and B inner vectors not equal size.");
+		idimc=ncolb;
+	}
+	else{
+		if (ncolb != idimb) _error_("Matrix A and B inner vectors not equal size.");
+		idimc=nrowb;
+	}
+
+	if (!itrnc) {
+		if (nrowc != idimc) _error_("Matrix B and C inner vectors not equal size.");
+		idimd=ncolc;
+	}
+	else{
+		if (ncolc != idimc) _error_("Matrix B and C inner vectors not equal size.");
+		idimd=nrowc;
+	}
+
+	/*  perform the matrix triple product in the order that minimizes the
+		 number of multiplies and the temporary space used, noting that
+		 (a*b)*c requires ac(b+d) multiplies and ac IssmDoubles, and a*(b*c)
+		 requires bd(a+c) multiplies and bd IssmDoubles (both are the same for
+		 a symmetric triple product)  */
+
+	/*  multiply (a*b)*c+d  */
+	if (idima*idimc*(idimb+idimd) <= idimb*idimd*(idima+idimc)) {
+		dtemp=xNew<IssmDouble>(idima*idimc);
+
+		MatrixMultiply(a,nrowa,ncola,itrna,b,nrowb,ncolb,itrnb,dtemp,0);
+		MatrixMultiply(dtemp,idima,idimc,0,c,nrowc,ncolc,itrnc,d,iaddd);
+		xDelete<IssmDouble>(dtemp);
+	}
+
+	/*  multiply a*(b*c)+d  */
+	else{
+		dtemp=xNew<IssmDouble>(idimb*idimd);
+
+		MatrixMultiply(b,nrowb,ncolb,itrnb,c,nrowc,ncolc,itrnc,dtemp,0);
+		MatrixMultiply(a,nrowa,ncola,itrna,dtemp,idimb,idimd,0,d,iaddd);
+		xDelete<IssmDouble>(dtemp);
+	}
+
+	return 1;
+}/*}}}*/
+int MatrixMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc ){/*{{{*/
+	/*MatrixMultiply    Perform matrix multiplication a*b+c.*/
+	int noerr=1;
+	int i,j,k,ipta,iptb,iptc;
+	int nrowc,ncolc,iinca,jinca,iincb,jincb,ntrma,ntrmb,nterm;
+
+	_assert_(a && b && c);
+
+	/*  set up dimensions and increments for matrix a  */
+	if (!itrna) {
+		nrowc=nrowa;
+		ntrma=ncola;
+		iinca=ncola;
+		jinca=1;
+	}
+	else {
+		nrowc=ncola;
+		ntrma=nrowa;
+		iinca=1;
+		jinca=ncola;
+	}
+
+	/*  set up dimensions and increments for matrix b  */
+	if (!itrnb) {
+		ncolc=ncolb;
+		ntrmb=nrowb;
+		iincb=ncolb;
+		jincb=1;
+	}
+	else {
+		ncolc=nrowb;
+		ntrmb=ncolb;
+		iincb=1;
+		jincb=ncolb;
+	}
+
+	if (ntrma != ntrmb) _error_("Matrix A and B inner vectors not equal size");
+
+	nterm=ntrma;
+
+	/*  zero matrix c, if not being added to product  */
+	if (!iaddc) for (i=0;i<nrowc*ncolc;i++) c[i]=0.;
+
+	/*  perform the matrix multiplication  */
+	iptc=0;
+	for (i=0; i<nrowc; i++){
+		for (j=0; j<ncolc; j++){
+			ipta=i*iinca;
+			iptb=j*jincb;
+
+			for (k=0; k<nterm; k++){
+				c[iptc]+=a[ipta]*b[iptb];
+				ipta+=jinca;
+				iptb+=iincb;
+			}
+			iptc++;
+		}
+	}
+
+	return noerr;
+}/*}}}*/
+int MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet ){/*{{{*/
+	/* MatrixInverse    Perform matrix inversion and linear equation solution.
+
+		This function uses Gaussian elimination on the original matrix
+		augmented by an identity matrix of the same size to calculate
+		the inverse (see for example, "Modern Methods of Engineering
+		Computation", Sec. 6.4).  By noting how the matrices are
+		unpopulated and repopulated, the calculation may be done in place.
+
+		Gaussian elimination is inherently inefficient, and so this is
+		intended for small matrices.  */
+	int noerr=1;
+	int i,j,k,ipt,jpt,irow,icol,ipiv,ncol;
+	int *pivrc1,*pivrc2,*pindx;
+	IssmDouble pivot,det,dtemp;
+
+	if (!b && nvec) {
+		_error_("No right-hand side for nvec=" << nvec << ".");
+		noerr=0;
+		return noerr;
+	}
+
+	/*In debugging mode, check that we are not dealing with simple matrices*/
+	_assert_(!(ndim==2 && nrow==2));
+	_assert_(!(ndim==3 && nrow==3));
+
+	/*  initialize local variables and arrays  */
+
+	ncol=nrow;
+	det=1.;
+	pivrc1 =xNew<int>(nrow);
+	pivrc2 =xNew<int>(nrow);
+	pindx =xNew<int>(nrow);
+
+	/*  loop over the rows/columns of the matrix  */
+
+	for (i=0; i<nrow; i++) {
+
+		/*  search for pivot, finding the term with the greatest magnitude
+			 in the rows/columns not yet used  */
+
+		pivot=0.;
+		for (j=0; j<nrow; j++)
+		 if (!pindx[j])
+		  for (k=0; k<ncol; k++)
+			if (!pindx[k])
+			 if (fabs(a[j*ndim+k]) > fabs(pivot)) {
+				 irow=j;
+				 icol=k;
+				 pivot=a[j*ndim+k];
+			 }
+
+		if (fabs(pivot) < DBL_EPSILON) {
+			xDelete<int>(pivrc1);
+			xDelete<int>(pivrc2);
+			xDelete<int>(pindx);
+			_error_("Pivot " << pivot << " less than machine epsilon");
+			noerr=0;
+			return noerr;
+		}
+
+		pivrc1[i]=irow;
+		pivrc2[i]=icol;
+
+		ipiv=icol;
+		pindx[ipiv]++;
+
+		//		_printf_("pivot for i=" << i << ": irow=" << irow << ", icol=" << icol  << ", pindx[" << ipiv << "]=" << pindx[ipiv] << "\n\n");
+
+		/*  switch rows to put pivot element on diagonal, noting that the
+			 column stays the same and the determinant changes sign  */
+
+		if (irow != icol) {
+			//			_printf_("row switch for i=" << i << ": irow=" << irow << ", icol=" << icol << "\n\n");
+
+			ipt=irow*ndim;
+			jpt=icol*ndim;
+			for (k=0; k<ncol; k++) {
+				dtemp   =a[ipt+k];
+				a[ipt+k]=a[jpt+k];
+				a[jpt+k]=dtemp;
+			}
+
+			ipt=irow*nvec;
+			jpt=icol*nvec;
+			for (k=0; k<nvec; k++) {
+				dtemp   =b[ipt+k];
+				b[ipt+k]=b[jpt+k];
+				b[jpt+k]=dtemp;
+			}
+
+			det=-det;
+		}
+
+		/*  divide pivot row by pivot element, noting that the original
+			 matrix will have 1 on the diagonal, which will be discarded,
+			 and the augmented matrix will start with 1 from the identity
+			 matrix and then have 1/pivot, which is part of the inverse.  */
+
+		a[ipiv*ndim+ipiv]=1.;
+
+		ipt=ipiv*ndim;
+		for (k=0; k<ncol; k++)
+		 a[ipt+k]/=pivot;
+
+		ipt=ipiv*nvec;
+		for (k=0; k<nvec; k++)
+		 b[ipt+k]/=pivot;
+
+		/*  reduce non-pivot rows such that they will have 0 in the pivot
+			 column, which will be discarded, and the augmented matrix will
+			 start with 0 from the identity matrix and then have non-zero
+			 in the corresponding column, which is part of the inverse.
+			 only one column of the augmented matrix is populated at a time,
+			 which corresponds to the only column of the original matrix
+			 being zeroed, so that the inverse may be done in place.  */
+
+		for (j=0; j<nrow; j++) {
+			if (j == ipiv) continue;
+
+			dtemp=a[j*ndim+ipiv];
+			a[j*ndim+ipiv]=0.;
+
+			if (fabs(dtemp) > DBL_EPSILON) {
+				ipt=j   *ndim;
+				jpt=ipiv*ndim;
+				for (k=0; k<ncol; k++)
+				 a[ipt+k]-=dtemp*a[jpt+k];
+
+				ipt=j   *nvec;
+				jpt=ipiv*nvec;
+				for (k=0; k<nvec; k++)
+				 b[ipt+k]-=dtemp*b[jpt+k];
+			}
+		}
+
+		/*  for a diagonal matrix, the determinant is the product of the
+			 diagonal terms, and so it may be accumulated from the pivots,
+			 noting that switching rows changes the sign as above  */
+
+		det*=pivot;
+	}
+
+	/*  switch columns back in reverse order, noting that a row switch
+		 in the original matrix corresponds to a column switch in the
+		 inverse matrix  */
+
+	for (i=0; i<nrow; i++) {
+		j=(nrow-1)-i;
+
+		if (pivrc1[j] != pivrc2[j]) {
+			irow=pivrc1[j];
+			icol=pivrc2[j];
+
+			//			_printf_("column switch back for j=" << j << ": irow=" << irow << ", icol=" << icol << "\n\n");
+
+			ipt=0;
+			for (k=0; k<nrow; k++) {
+				dtemp      =a[ipt+irow];
+				a[ipt+irow]=a[ipt+icol];
+				a[ipt+icol]=dtemp;
+				ipt+=ndim;
+			}
+		}
+	}
+
+	if (pdet) *pdet=det;
+	xDelete<int>(pivrc1);
+	xDelete<int>(pivrc2);
+	xDelete<int>(pindx);
+	return noerr;
+}/*}}}*/
+
+void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
+	/*Compute determinant of a 2x2 matrix*/
+
+	/*det = a*d - c*b*/
+	*Adet= A[0]*A[3]-A[2]*A[1];
+}
+/*}}}*/
+void Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble det;
+
+	/*Compute determinant*/
+	Matrix2x2Determinant(&det,A);
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
+
+	/*Compute invert*/
+	Ainv[0]=   A[3]/det; /* =  d/det */
+	Ainv[1]= - A[1]/det; /* = -b/det */
+	Ainv[2]= - A[2]/det; /* = -c/det */
+	Ainv[3]=   A[0]/det; /* =  a/det */
+
+}/*}}}*/
+
+void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
+	/*Compute determinant of a 3x3 matrix*/
+
+	/*det = a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g)*/
+	*Adet= A[0]*A[4]*A[8]-A[0]*A[5]*A[7]-A[3]*A[1]*A[8]+A[3]*A[2]*A[7]+A[6]*A[1]*A[5]-A[6]*A[2]*A[4];
+}
+/*}}}*/
+IssmDouble Matrix3x3Determinant(IssmDouble a1,IssmDouble a2,IssmDouble a3, IssmDouble b1,IssmDouble b2,IssmDouble b3, IssmDouble c1,IssmDouble c2,IssmDouble c3){/*{{{*/
+	/*Compute determinant of a 3x3 matrix*/
+
+	/*det = a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g)
+	 * a b c   a1 a2 a3
+	 * d e f   b1 b2 b3
+	 * g h i   c1 c2 c3 */
+	return a1*b2*c3-a1*b3*c2-b1*a2*c3+b1*a3*c2+c1*a2*b3-c1*a3*b2;
+}
+/*}}}*/
+void Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble det;
+
+	/*Compute determinant*/
+	Matrix3x3Determinant(&det,A);
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
+
+	/*Compute invert*/
+	Ainv[0]=(A[4]*A[8]-A[5]*A[7])/det; /* = (e*i-f*h)/det */
+	Ainv[1]=(A[2]*A[7]-A[1]*A[8])/det; /* = (c*h-b*i)/det */
+	Ainv[2]=(A[1]*A[5]-A[2]*A[4])/det; /* = (b*f-c*e)/det */
+	Ainv[3]=(A[5]*A[6]-A[3]*A[8])/det; /* = (f*g-d*i)/det */
+	Ainv[4]=(A[0]*A[8]-A[2]*A[6])/det; /* = (a*i-c*g)/det */
+	Ainv[5]=(A[2]*A[3]-A[0]*A[5])/det; /* = (c*d-a*f)/det */
+	Ainv[6]=(A[3]*A[7]-A[4]*A[6])/det; /* = (d*h-e*g)/det */
+	Ainv[7]=(A[1]*A[6]-A[0]*A[7])/det; /* = (b*g-a*h)/det */
+	Ainv[8]=(A[0]*A[4]-A[1]*A[3])/det; /* = (a*e-b*d)/det */
+
+}/*}}}*/
+void Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B){/*{{{*/
+
+	IssmDouble Ainv[3][3];
+
+	Matrix3x3Invert(&Ainv[0][0],A);
+	for(int i=0;i<3;i++) X[i]=Ainv[i][0]*B[0] + Ainv[i][1]*B[1] + Ainv[i][2]*B[2];
+
+}/*}}}*/
+
+void Matrix4x4Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
+	/*Compute determinant of a 4x4 matrix*/
+
+	IssmDouble a1 = A[0*4+0];
+	IssmDouble b1 = A[0*4+1]; 
+	IssmDouble c1 = A[0*4+2];
+	IssmDouble d1 = A[0*4+3];
+
+	IssmDouble a2 = A[1*4+0];
+	IssmDouble b2 = A[1*4+1]; 
+	IssmDouble c2 = A[1*4+2];
+	IssmDouble d2 = A[1*4+3];
+
+	IssmDouble a3 = A[2*4+0]; 
+	IssmDouble b3 = A[2*4+1];
+	IssmDouble c3 = A[2*4+2];
+	IssmDouble d3 = A[2*4+3];
+
+	IssmDouble a4 = A[3*4+0];
+	IssmDouble b4 = A[3*4+1]; 
+	IssmDouble c4 = A[3*4+2];
+	IssmDouble d4 = A[3*4+3];
+
+	*Adet= a1 * Matrix3x3Determinant(b2, b3, b4, c2, c3, c4, d2, d3, d4)
+		  - b1 * Matrix3x3Determinant(a2, a3, a4, c2, c3, c4, d2, d3, d4)
+		  + c1 * Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, d2, d3, d4)
+		  - d1 * Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, c2, c3, c4);
+}
+/*}}}*/
+void Matrix4x4Adjoint(IssmDouble* Aadj,IssmDouble* A){/*{{{*/
+
+    IssmDouble a1 = A[0*4+0];
+    IssmDouble b1 = A[0*4+1]; 
+    IssmDouble c1 = A[0*4+2];
+    IssmDouble d1 = A[0*4+3];
+
+    IssmDouble a2 = A[1*4+0];
+    IssmDouble b2 = A[1*4+1]; 
+    IssmDouble c2 = A[1*4+2];
+    IssmDouble d2 = A[1*4+3];
+
+    IssmDouble a3 = A[2*4+0];
+    IssmDouble b3 = A[2*4+1];
+    IssmDouble c3 = A[2*4+2];
+    IssmDouble d3 = A[2*4+3];
+
+    IssmDouble a4 = A[3*4+0];
+    IssmDouble b4 = A[3*4+1]; 
+    IssmDouble c4 = A[3*4+2];
+    IssmDouble d4 = A[3*4+3];
+
+    /* Row column labeling reversed since we transpose rows & columns*/
+    Aadj[0*4+0]  =   Matrix3x3Determinant(b2, b3, b4, c2, c3, c4, d2, d3, d4);
+    Aadj[1*4+0]  = - Matrix3x3Determinant(a2, a3, a4, c2, c3, c4, d2, d3, d4);
+    Aadj[2*4+0]  =   Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, d2, d3, d4);
+    Aadj[3*4+0]  = - Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, c2, c3, c4);
+
+    Aadj[0*4+1]  = - Matrix3x3Determinant(b1, b3, b4, c1, c3, c4, d1, d3, d4);
+    Aadj[1*4+1]  =   Matrix3x3Determinant(a1, a3, a4, c1, c3, c4, d1, d3, d4);
+    Aadj[2*4+1]  = - Matrix3x3Determinant(a1, a3, a4, b1, b3, b4, d1, d3, d4);
+    Aadj[3*4+1]  =   Matrix3x3Determinant(a1, a3, a4, b1, b3, b4, c1, c3, c4);
+
+    Aadj[0*4+2]  =   Matrix3x3Determinant(b1, b2, b4, c1, c2, c4, d1, d2, d4);
+    Aadj[1*4+2]  = - Matrix3x3Determinant(a1, a2, a4, c1, c2, c4, d1, d2, d4);
+    Aadj[2*4+2]  =   Matrix3x3Determinant(a1, a2, a4, b1, b2, b4, d1, d2, d4);
+    Aadj[3*4+2]  = - Matrix3x3Determinant(a1, a2, a4, b1, b2, b4, c1, c2, c4);
+
+    Aadj[0*4+3]  = - Matrix3x3Determinant(b1, b2, b3, c1, c2, c3, d1, d2, d3);
+    Aadj[1*4+3]  =   Matrix3x3Determinant(a1, a2, a3, c1, c2, c3, d1, d2, d3);
+    Aadj[2*4+3]  = - Matrix3x3Determinant(a1, a2, a3, b1, b2, b3, d1, d2, d3);
+    Aadj[3*4+3]  =   Matrix3x3Determinant(a1, a2, a3, b1, b2, b3, c1, c2, c3);
+}/*}}}*/
+void Matrix4x4Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble det;
+
+	/*Compute determinant*/
+	Matrix4x4Determinant(&det,A);
+	//if(fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
+
+	/*Compute adjoint matrix*/
+	Matrix4x4Adjoint(Ainv,A);
+
+	/*Scalte adjoint matrix to get inverse*/
+	for(int i=0;i<4*4;i++) Ainv[i] = Ainv[i]/det;
+}/*}}}*/
+void Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble *B){/*{{{*/
+	IssmDouble Ainv[4][4];
+
+	Matrix4x4Invert(&Ainv[0][0],A);
+	for(int i=0;i<4;i++) X[i]=Ainv[i][0]*B[0] + Ainv[i][1]*B[1] + Ainv[i][2]*B[2] + Ainv[i][3]*B[3];
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/matrix.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Matrix/matrix.h	(revision 18231)
@@ -0,0 +1,27 @@
+/*!\file: matrix.h
+ * \brief prototypes for matrix.h
+ */ 
+
+#ifndef _MATRIXUTILS_H_
+#define _MATRIXUTILS_H_
+
+#include "../Numerics/types.h"
+
+int  TripleMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int nrowc, int ncolc, int itrnc, IssmDouble* d, int iaddd);
+int  MatrixMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc );
+int  MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet );
+
+void Matrix2x2Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A);
+
+void Matrix3x3Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A);
+IssmDouble Matrix3x3Determinant( IssmDouble a1,IssmDouble a2,IssmDouble a3, IssmDouble b1,IssmDouble b2,IssmDouble b3, IssmDouble c1,IssmDouble c2,IssmDouble c3);
+void Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B);
+
+void Matrix4x4Adjoint(IssmDouble* Aadj, IssmDouble* A);
+void Matrix4x4Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix4x4Determinant(IssmDouble* Adet,IssmDouble* A);
+void Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B);
+
+#endif //ifndef _MATRIXUTILS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.cpp	(revision 18231)
@@ -0,0 +1,23 @@
+/*
+ * MemOps.cpp
+ *
+ *  Created on: Sep 10, 2013
+ *      Author: utke
+ */
+
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "MemOps.h"
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+template <> adouble*  xNew(unsigned int size) {
+	ensureContiguousLocations(size);
+	adouble* aT_p=new adouble[size];
+	assert(aT_p);
+	return aT_p;
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/MemOps/MemOps.h	(revision 18231)
@@ -0,0 +1,149 @@
+/* \file MemOps.h
+ * \brief: header file for memory allocations as well as templated new/delete checking for non-null pointers
+ */
+
+#ifndef _MEM_OPS_H_
+#define _MEM_OPS_H_
+
+#include <cassert>
+
+/* memory management of types T with non-trivial constructors require C++ style memory management*/
+#define USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+/* but for speed one may alternatively use C memory management but can do so safely only for T that are at most 
+ * plain old data structures (POD)*/
+#ifndef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+#include <cstdlib>
+#endif 
+
+template <class T> T* xNew(unsigned int size) { /*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* aT_p=new T[size];
+  assert(aT_p);
+  return aT_p;
+#else
+  T* aT_p=(T*)malloc(size*sizeof(T));
+  assert(aT_p);
+  return aT_p;
+#endif  
+}/*}}}*/
+template <class T> T** xNew(unsigned int dim1, unsigned int dim2) { /*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* buf=xNew<T>(dim1*dim2);
+  T** aT_pp =new T*[dim1];
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#else
+  T* buf=(T*)malloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#endif
+}/*}}}*/
+template <class T> T* xNewZeroInit(unsigned int size) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* aT_p=xNew<T>(size);
+  for (unsigned int i=0; i<size;++i) 
+    aT_p[i]=(T)0;
+  return aT_p;
+#else
+  T* aT_p=(T*)calloc(size,sizeof(T));
+  assert(aT_p);
+  return aT_p;
+#endif
+}/*}}}*/
+template <class T> T** xNewZeroInit(unsigned int dim1, unsigned int dim2) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T** aT_pp=xNew<T>(dim1,dim2);
+  for (unsigned int i=0; i<dim1*dim2;++i)
+    (*aT_pp)[i]=(T)0;
+  return aT_pp;
+#else
+  T* buf=(T*)calloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#endif
+}/*}}}*/
+template <class T> void xDelete(T**& aT_pp) {/*{{{*/
+  if (aT_pp) {
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+    delete [](*aT_pp);
+    delete [](aT_pp);
+#else
+    free((void*)*aT_pp)
+    free((void**)aT_pp);
+#endif
+  }
+  aT_pp=0;
+}/*}}}*/
+template <class T> void xDelete(T*& aT_p) {/*{{{*/
+  if (aT_p) 
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+    delete []aT_p;
+#else
+    free((void*)aT_p);
+#endif
+  aT_p=0;
+}/*}}}*/
+template <class T> T* xReNew(T* old, unsigned int old_size, unsigned int size) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+	T* aT_p=0;
+	if (!old) { // no old memory
+		if (size)  
+		 aT_p=xNew<T>(size); // according to realloc behavior in manual page 
+	}
+	else { // have old memory
+		if (!size)  // but 0 size
+		 xDelete<T>(old); // according to realloc behavior in manual page
+		else { // non-zero size
+			assert(old_size); // have old memory - need to have old_size set or this call is bad
+			// allocate new, delete old; ; even for the case when size is 
+			// less than old_size we can't just keep the memory unchanged 
+			// because otherwise classes that have ctors/dtors with side-effects 
+			// may misbehave, for example classes with static instance/operations counters. 
+			aT_p=xNew<T>(size);
+			unsigned int iMax=(old_size<size)?old_size:size;
+			for (unsigned int i=0; i<iMax;++i) { 
+				// we need to copy the items by explicit assignments
+				aT_p[i]=old[i];
+			}
+			xDelete<T>(old);
+		}
+	}
+	return aT_p;
+#else
+	T* aT_p=0;
+	aT_p=(T*)realloc((void*)old,size*sizeof(T));
+	if (size) 
+	 assert(aT_p); // according to realloc behavior in manual page
+	return aT_p;
+#endif 
+}/*}}}*/
+template <class T>  T* xMemCpy(T* dest, const T* src, unsigned int size) {/*{{{*/
+  assert(dest); assert(src);
+  for (int i=0; i<size;++i) 
+    dest[i]=src[i];
+  return dest;
+};
+/*}}}*/
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+#include "../Numerics/types.h"
+template <> adouble*  xNew(unsigned int size);
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/BrentSearch.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/BrentSearch.cpp	(revision 18231)
@@ -0,0 +1,250 @@
+/*!\file:  BrentSearch.cpp
+ * \brief optimization algorithm
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <float.h>
+#include <iomanip>
+
+#include "../Exceptions/exceptions.h"
+#include "../io/io.h"
+#include "../MemOps/MemOps.h"
+#include "./Verbosity.h"
+#include "./OptPars.h"
+#include "./types.h"
+#include "./isnan.h"
+
+void BrentSearch(IssmDouble** pJ,OptPars optpars,IssmDouble* X0,IssmDouble (*f)(IssmDouble*,void*),IssmDouble (*g)(IssmDouble**,IssmDouble*,void*),void* usr){
+
+	/* This routine is optimizing a given function using Brent's method
+	 * (Golden or parabolic procedure)*/
+
+	/*Intermediary*/
+	int        iter;
+	IssmDouble si,gold,intervalgold,oldintervalgold;
+	IssmDouble parab_num,parab_den,distance;
+	IssmDouble fxmax,fxmin,fxbest;
+	IssmDouble fx,fx1,fx2;
+	IssmDouble x,x1,x2,xm,xbest;
+	IssmDouble tol1,tol2,seps;
+	IssmDouble tolerance = 1.e-4;
+
+	/*Recover parameters:*/
+	int         nsteps  = optpars.nsteps;
+	int         nsize   = optpars.nsize;
+	IssmDouble  xmin    = optpars.xmin;
+	IssmDouble  xmax    = optpars.xmax;
+	int        *maxiter = optpars.maxiter;
+	IssmDouble *cm_jump = optpars.cm_jump;
+
+	/*Initialize gradient and controls*/
+	IssmDouble* G = NULL;
+	IssmDouble* J = xNew<IssmDouble>(nsteps);
+	IssmDouble* X = xNew<IssmDouble>(nsize);
+
+	/*Header of printf*/
+	_printf0_("\n");
+	_printf0_("       x       |  Cost function f(x)  |  List of contributions\n");
+
+	/*start iterations*/
+	for(int n=0;n<nsteps;n++){
+
+		/*Print iteration number*/
+		_printf0_("====================== step "<< n+1 << "/" << nsteps <<" ===============================\n");
+
+		/*Reset some variables*/
+		iter = 0;
+		xmin = 0.;
+		xmax = 1.;
+		bool loop = true;
+		cout<<setprecision(5);
+
+		/*Get current Gradient at xmin=0*/
+		_printf0_(" x = "<<setw(9)<<xmin<<" | ");
+		fxmin = (*g)(&G,X0,usr); if(xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
+		
+		/*Get f(xmax)*/
+		_printf0_(" x = "<<setw(9)<<xmax<<" | ");
+		for(int i=0;i<nsize;i++) X[i]=X0[i]+xmax*G[i];
+		fxmax = (*f)(X,usr); if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
+		//if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary\n");
+
+		/*test if jump option activated and xmin==0*/
+		if(!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && (fxmax/fxmin)<cm_jump[n]){
+			for(int i=0;i<nsize;i++) X0[i]=X0[i]+xmax*G[i];
+			xDelete<IssmDouble>(G);
+			J[n]=fxmax;
+			continue;
+		}
+
+		/*initialize optimization variables*/
+		seps=sqrt(DBL_EPSILON);    //precision of a IssmDouble
+		distance=0.0;              //new_x=old_x + distance
+		gold=0.5*(3.0-sqrt(5.0));  //gold = 1 - golden ratio
+		intervalgold=0.0;          //distance used by Golden procedure
+
+		/*1: initialize the values of the 4 x needed (x1,x2,x,xbest)*/
+		x1=xmin+gold*(xmax-xmin);
+		x2=x1;
+		xbest=x1;
+		x=xbest;
+
+		/*2: call the function to be evaluated*/
+		_printf0_(" x = "<<setw(9)<<x<<" | ");
+		for(int i=0;i<nsize;i++) X[i]=X0[i]+x*G[i];
+		fxbest = (*f)(X,usr); if(xIsNan<IssmDouble>(fxbest)) _error_("Function evaluation returned NaN");
+		iter++;
+
+		/*3: update the other variables*/
+		fx1=fxbest;
+		fx2=fxbest;
+		/*xm is always in the middle of a and b*/
+		xm=0.5*(xmin+xmax);                           
+		/*update tolerances*/
+		tol1=seps*sqrt(pow(xbest,2))+tolerance/3.0;
+		tol2=2.0*tol1;
+
+		/*4: print result*/
+		//if(VerboseControl())
+		 //_printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial\n");
+		if (!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && ((fxbest/fxmin)<cm_jump[n])){
+			//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump[n] << "\n");
+			loop=false;
+		}
+
+		while(loop){
+
+			bool goldenflag=true;
+
+			// Is a parabolic fit possible ?
+			if (sqrt(pow(intervalgold,2))>tol1){
+
+				// Yes, so fit parabola
+				goldenflag=false;
+				parab_num=(xbest-x1)*(xbest-x1)*(fxbest-fx2)-(xbest-x2)*(xbest-x2)*(fxbest-fx1);;
+				parab_den=2.0*(xbest-x1)*(fxbest-fx2)-2.0*(xbest-x2)*(fxbest-fx1);
+
+				//reverse p if necessary
+				if(parab_den>0.0){ 
+					parab_num=-parab_num;
+				}
+				parab_den=sqrt(pow(parab_den,2));
+				oldintervalgold=intervalgold;
+				intervalgold=distance;
+
+				// Is the parabola acceptable (we use seps here because in some configuration parab_num==parab_den*(xmax-xbest)
+				// and the result is not repeatable anymore
+				if (( sqrt(pow(parab_num,2)) < sqrt(pow(0.5*parab_den*oldintervalgold,2))) &&
+							(parab_num>parab_den*(xmin-xbest)+seps) && 
+							(parab_num<parab_den*(xmax-xbest)-seps)){
+
+					// Yes, parabolic interpolation step
+					distance=parab_num/parab_den;
+					x=xbest+distance;
+
+					// f must not be evaluated too close to min_x or max_x
+					if (((x-xmin)<tol2) || ((xmax-x)<tol2)){
+						if ((xm-xbest)<0.0) si=-1;
+						else                si=1;
+						//compute new distance
+						distance=tol1*si;
+					}
+				}
+				else{
+					// Not acceptable, must do a golden section step
+					goldenflag=true;
+				}
+			}
+
+			//Golden procedure
+			if(goldenflag){
+				// compute the new distance d
+				if(xbest>=xm){
+					intervalgold=xmin-xbest;    
+				}
+				else{ 
+					intervalgold=xmax-xbest;  
+				}
+				distance=gold*intervalgold;
+			}
+
+			// The function must not be evaluated too close to xbest
+			if(distance<0) si=-1;
+			else           si=1;
+			if(sqrt(pow(distance,2))>tol1) x=xbest+si*sqrt(pow(distance,2));
+			else                           x=xbest+si*tol1;
+
+			//evaluate function on x
+			_printf0_(" x = "<<setw(9)<<x<<" | ");
+			for(int i=0;i<nsize;i++) X[i]=X0[i]+x*G[i];
+			fx = (*f)(X,usr); if(xIsNan<IssmDouble>(fx)) _error_("Function evaluation returned NaN");
+			iter++;
+
+			// Update a, b, xm, x1, x2, tol1, tol2
+			if (fx<=fxbest){
+				if (x>=xbest) xmin=xbest;
+				else          xmax=xbest;
+				x1=x2;    fx1=fx2;
+				x2=xbest; fx2=fxbest;
+				xbest=x;  fxbest=fx;
+			}
+			else{ // fx > fxbest
+				if (x<xbest) xmin=x;
+				else         xmax=x;
+				if ((fx<=fx2) || (x2==xbest)){
+					x1=x2; fx1=fx2;
+					x2=x;  fx2=fx;
+				}
+				else if ( (fx <= fx1) || (x1 == xbest) || (x1 == x2) ){
+					x1=x;  fx1=fx;
+				}
+			}
+			xm = 0.5*(xmin+xmax);
+			tol1=seps*pow(pow(xbest,2),0.5)+tolerance/3.0;
+			tol2=2.0*tol1;
+			//if(VerboseControl())
+			// _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
+			//			 "         "<<(goldenflag?"golden":"parabolic")<<"\n");
+
+			/*Stop the optimization?*/
+			if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
+				//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance << "\n");
+				loop=false;
+			}
+			else if (iter>=maxiter[n]){
+				//if(VerboseControl()) _printf0_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter[n] << ")\n");
+				loop=false;
+			}
+			else if (!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && ((fxbest/fxmin)<cm_jump[n])){
+				//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump[n] << "\n");
+				loop=false;
+			}
+			else{
+				//continue
+				loop=true;
+			}
+		}//end while
+
+		//Now, check that the value on the boundaries are not better than current fxbest
+		if (fxbest>fxmin){
+			xbest=optpars.xmin; fxbest=fxmin;
+		}
+		if (fxbest>fxmax){
+			xbest=optpars.xmax; fxbest=fxmax;
+		}
+
+		/*Assign output pointers: */
+		for(int i=0;i<nsize;i++) X0[i]=X0[i]+xbest*G[i];
+		xDelete<IssmDouble>(G);
+		J[n]=fxbest;
+	}
+	
+	/*return*/
+	xDelete<IssmDouble>(X);
+	*pJ=J;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.cpp	(revision 18231)
@@ -0,0 +1,1709 @@
+/*  Gauss point structures and prototypes  */
+#include <math.h>
+#include <float.h>
+
+#include "./GaussPoints.h"
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+#include "../Numerics/constants.h"
+
+/*General Gauss points*/
+void GaussLegendreLinear( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus){/*{{{*/
+	/* Gauss-Legendre quadrature points.
+
+		The recurrence coefficients for Legendre polynomials on (-1,1)
+		are defined (from the ORTHPOL subroutine RECUR with ipoly=1) as:
+
+		alpha(i)=0.
+		beta (i)=1./(4.-1./(i-1)^2))
+
+		For degree p, the required number of Gauss-Legendre points is
+		n>=(p+1)/2.*/
+
+	/*Intermediaries*/
+	int i;
+	IssmPDouble *alpha,*beta;
+
+	/*p= 1, npoint= 1*/
+	static IssmPDouble wgt1[]={2.000000000000000};
+	static IssmPDouble xi1[]={0.000000000000000};
+
+	/*p= 3, npoint= 2*/
+	static IssmPDouble wgt2[]={1.000000000000000, 1.000000000000000};
+	static IssmPDouble xi2[]={-0.577350269189626, 0.577350269189626};
+
+	/*p= 5, npoint= 3*/
+	static IssmPDouble wgt3[]={0.555555555555556, 0.888888888888889, 0.555555555555556};
+	static IssmPDouble xi3[]={-0.774596669241483, 0.000000000000000, 0.774596669241483};
+
+	/*p= 7, npoint= 4*/
+	static IssmPDouble wgt4[]={0.347854845137454, 0.652145154862546, 0.652145154862546, 0.347854845137454};
+	static IssmPDouble xi4[]={-0.861136311594053,-0.339981043584856, 0.339981043584856, 0.861136311594053};
+
+	/*npoint= 5*/
+	static IssmPDouble wgt5[]={0.5688888888888889,0.4786286704993665,0.4786286704993665,0.2369268850561891,0.2369268850561891};
+	static IssmPDouble xi5[]={0.0000000000000000,-0.5384693101056831,0.5384693101056831,-0.9061798459386640,0.9061798459386640};
+
+	/*npoint= 6*/
+	static IssmPDouble wgt6[]={0.3607615730481386,0.3607615730481386,0.4679139345726910,0.4679139345726910,0.1713244923791704,0.1713244923791704};
+	static IssmPDouble xi6[]={-0.6612093864662645,0.6612093864662645,-0.2386191860831969,0.2386191860831969,-0.9324695142031521,0.9324695142031521};
+
+	/*npoint= 7*/
+	static IssmPDouble wgt7[]={0.4179591836734694,0.3818300505051189,0.3818300505051189,0.2797053914892766,0.2797053914892766,0.1294849661688697,0.1294849661688697};
+	static IssmPDouble xi7[]={0.0000000000000000,-0.4058451513773972,0.4058451513773972,-0.7415311855993945,0.7415311855993945,-0.9491079123427585,0.9491079123427585};
+
+	static IssmPDouble* wgtp[MAX_LINE_GAUS_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4, wgt5, wgt6, wgt7};
+	static IssmPDouble* xip [MAX_LINE_GAUS_PTS]={xi1  ,xi2  ,xi3  ,xi4, xi5, xi6, xi7};
+
+	*pxgaus =xNew<IssmPDouble>(ngaus);
+	*pxwgt  =xNew<IssmPDouble>(ngaus);
+
+	/*  check to see if Gauss points need to be calculated  */
+	if(ngaus <= MAX_LINE_GAUS_PTS) {
+
+		/*  copy the points from the static arrays (noting that the pointers
+			 could be returned directly, but then the calling function would
+			 have to know to not free them)  */
+
+		for(i=0; i<ngaus; i++) {
+			(*pxgaus)[i]=xip [ngaus-1][i];
+			(*pxwgt )[i]=wgtp[ngaus-1][i];
+		}
+	}
+	else{
+
+		/*  calculate the Gauss points using recurrence relations  */
+		alpha=xNew<IssmPDouble>(ngaus);
+		beta =xNew<IssmPDouble>(ngaus);
+
+		/*  calculate the Legendre recurrence coefficients  */
+		alpha[0]=0.;
+		beta [0]=2.;
+
+		for (i=1; i<ngaus; i++) {
+			alpha[i]=0.;
+			beta [i]=1./(4.-1./(i*i));
+		}
+
+		/*  calculate the Gauss points  */
+		GaussRecur(*pxgaus, *pxwgt, ngaus, alpha, beta );
+		xDelete<IssmPDouble>(beta);
+		xDelete<IssmPDouble>(alpha);
+	}
+}/*}}}*/
+void GaussLegendreTria( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord ) {/*{{{*/
+	/*Gauss quadrature points for the triangle.
+
+	  Higher-order points from D.A. Dunavant, "High Degree Efficient
+	  Symmetrical Gaussian Quadrature Rules for the Triangle", IJNME,
+	  Vol. 21, pp. 1129-1148 (1985), as transcribed for Probe rules3.*/
+
+	/*Intermediaries*/
+	int i,j,ipt,nigaus;
+	IssmPDouble xi,eta;
+	IssmPDouble *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt;
+
+	/*Hardcoded Gauss points declaration*/
+	/*p= 1, npoint= 1{{{*/
+	static IssmPDouble wgt1[]={
+		1.732050807568877};
+	static IssmPDouble l11[]={
+		0.333333333333333};
+	static IssmPDouble l21[]={
+		0.333333333333333};
+	static IssmPDouble l31[]={
+		0.333333333333333};
+	/*}}}*/
+	/*p= 2, npoint= 3  {{{*/
+	static IssmPDouble wgt2[]={
+		0.577350269189625, 0.577350269189625, 0.577350269189625};
+	static IssmPDouble l12[]={
+		0.666666666666667, 0.166666666666667, 0.166666666666667};
+	static IssmPDouble l22[]={
+		0.166666666666667, 0.666666666666667, 0.166666666666667};
+	static IssmPDouble l32[]={
+		0.166666666666667, 0.166666666666667, 0.666666666666667};
+	/*}}}*/
+	/*p= 3, npoint= 4  {{{*/
+	static IssmPDouble wgt3[]={
+		-0.974278579257493, 0.902109795608790, 0.902109795608790, 
+		0.902109795608790};
+	static IssmPDouble l13[]={
+		0.333333333333333, 0.600000000000000, 0.200000000000000, 
+		0.200000000000000};
+	static IssmPDouble l23[]={
+		0.333333333333333, 0.200000000000000, 0.600000000000000, 
+		0.200000000000000};
+	static IssmPDouble l33[]={
+		0.333333333333333, 0.200000000000000, 0.200000000000000, 
+		0.600000000000000};
+	/*}}}*/
+	/*p= 4, npoint= 6  {{{*/
+	static IssmPDouble wgt4[]={
+		0.386908262797819, 0.386908262797819, 0.386908262797819, 
+		0.190442006391807, 0.190442006391807, 0.190442006391807};
+	static IssmPDouble l14[]={
+		0.108103018168070, 0.445948490915965, 0.445948490915965, 
+		0.816847572980459, 0.091576213509771, 0.091576213509771};
+	static IssmPDouble l24[]={
+		0.445948490915965, 0.108103018168070, 0.445948490915965, 
+		0.091576213509771, 0.816847572980459, 0.091576213509771};
+	static IssmPDouble l34[]={
+		0.445948490915965, 0.445948490915965, 0.108103018168070, 
+		0.091576213509771, 0.091576213509771, 0.816847572980459};
+	/*}}}*/
+	/*p= 5, npoint= 7  {{{*/
+	static IssmPDouble wgt5[]={
+		0.389711431702997, 0.229313399254729, 0.229313399254729, 
+		0.229313399254729, 0.218133059367230, 0.218133059367230, 
+		0.218133059367230};
+	static IssmPDouble l15[]={
+		0.333333333333333, 0.059715871789770, 0.470142064105115, 
+		0.470142064105115, 0.797426985353087, 0.101286507323456, 
+		0.101286507323456};
+	static IssmPDouble l25[]={
+		0.333333333333333, 0.470142064105115, 0.059715871789770, 
+		0.470142064105115, 0.101286507323456, 0.797426985353087, 
+		0.101286507323456};
+	static IssmPDouble l35[]={
+		0.333333333333333, 0.470142064105115, 0.470142064105115, 
+		0.059715871789770, 0.101286507323456, 0.101286507323456, 
+		0.797426985353087};
+	/*}}}*/
+	/*p= 6, npoint=12  {{{*/
+	static IssmPDouble wgt6[]={
+		0.202279763184836, 0.202279763184836, 0.202279763184836, 
+		0.088065961139281, 0.088065961139281, 0.088065961139281, 
+		0.143502272432755, 0.143502272432755, 0.143502272432755, 
+		0.143502272432755, 0.143502272432755, 0.143502272432755};
+	static IssmPDouble l16[]={
+		0.501426509658179, 0.249286745170910, 0.249286745170910, 
+		0.873821971016996, 0.063089014491502, 0.063089014491502, 
+		0.053145049844817, 0.053145049844817, 0.310352451033784, 
+		0.636502499121399, 0.310352451033784, 0.636502499121399};
+	static IssmPDouble l26[]={
+		0.249286745170910, 0.501426509658179, 0.249286745170910, 
+		0.063089014491502, 0.873821971016996, 0.063089014491502, 
+		0.310352451033784, 0.636502499121399, 0.053145049844817, 
+		0.053145049844817, 0.636502499121399, 0.310352451033784};
+	static IssmPDouble l36[]={
+		0.249286745170910, 0.249286745170910, 0.501426509658179, 
+		0.063089014491502, 0.063089014491502, 0.873821971016996, 
+		0.636502499121399, 0.310352451033784, 0.636502499121399, 
+		0.310352451033784, 0.053145049844817, 0.053145049844817};
+	/*}}}*/
+	/*p= 7, npoint=13  {{{*/
+	static IssmPDouble wgt7[]={
+		-0.259062916308362, 0.304174548458604, 0.304174548458604, 
+		0.304174548458604, 0.092400122517855, 0.092400122517855, 
+		0.092400122517855, 0.133564951824643, 0.133564951824643, 
+		0.133564951824643, 0.133564951824643, 0.133564951824643, 
+		0.133564951824643};
+	static IssmPDouble l17[]={
+		0.333333333333333, 0.479308067841920, 0.260345966079040, 
+		0.260345966079040, 0.869739794195568, 0.065130102902216, 
+		0.065130102902216, 0.048690315425316, 0.048690315425316, 
+		0.312865496004874, 0.638444188569810, 0.312865496004874, 
+		0.638444188569810};
+	static IssmPDouble l27[]={
+		0.333333333333333, 0.260345966079040, 0.479308067841920, 
+		0.260345966079040, 0.065130102902216, 0.869739794195568, 
+		0.065130102902216, 0.312865496004874, 0.638444188569810, 
+		0.048690315425316, 0.048690315425316, 0.638444188569810, 
+		0.312865496004874};
+	static IssmPDouble l37[]={
+		0.333333333333333, 0.260345966079040, 0.260345966079040, 
+		0.479308067841920, 0.065130102902216, 0.065130102902216, 
+		0.869739794195568, 0.638444188569810, 0.312865496004874, 
+		0.638444188569810, 0.312865496004874, 0.048690315425316, 
+		0.048690315425316};
+	/*}}}*/
+	/*p= 8, npoint=16  {{{*/
+	static IssmPDouble wgt8[]={
+		0.249961964823104, 0.164703541925695, 0.164703541925695, 
+		0.164703541925695, 0.178777729989794, 0.178777729989794, 
+		0.178777729989794, 0.056219767020733, 0.056219767020733, 
+		0.056219767020733, 0.047164287656184, 0.047164287656184, 
+		0.047164287656184, 0.047164287656184, 0.047164287656184, 
+		0.047164287656184};
+	static IssmPDouble l18[]={
+		0.333333333333333, 0.081414823414554, 0.459292588292723, 
+		0.459292588292723, 0.658861384496480, 0.170569307751760, 
+		0.170569307751760, 0.898905543365938, 0.050547228317031, 
+		0.050547228317031, 0.008394777409958, 0.008394777409958, 
+		0.263112829634638, 0.728492392955404, 0.263112829634638, 
+		0.728492392955404};
+	static IssmPDouble l28[]={
+		0.333333333333333, 0.459292588292723, 0.081414823414554, 
+		0.459292588292723, 0.170569307751760, 0.658861384496480, 
+		0.170569307751760, 0.050547228317031, 0.898905543365938, 
+		0.050547228317031, 0.263112829634638, 0.728492392955404, 
+		0.008394777409958, 0.008394777409958, 0.728492392955404, 
+		0.263112829634638};
+	static IssmPDouble l38[]={
+		0.333333333333333, 0.459292588292723, 0.459292588292723, 
+		0.081414823414554, 0.170569307751760, 0.170569307751760, 
+		0.658861384496480, 0.050547228317031, 0.050547228317031, 
+		0.898905543365938, 0.728492392955404, 0.263112829634638, 
+		0.728492392955404, 0.263112829634638, 0.008394777409958, 
+		0.008394777409958};
+	/*}}}*/
+	/*p= 9, npoint=19  {{{*/
+	static IssmPDouble wgt9[]={
+		0.168244134395468, 0.054273292833345, 0.054273292833345, 
+		0.054273292833345, 0.134801255248419, 0.134801255248419, 
+		0.134801255248419, 0.137953930529909, 0.137953930529909, 
+		0.137953930529909, 0.044301833780383, 0.044301833780383, 
+		0.044301833780383, 0.074969289332873, 0.074969289332873, 
+		0.074969289332873, 0.074969289332873, 0.074969289332873, 
+		0.074969289332873};
+	static IssmPDouble l19[]={
+		0.333333333333333, 0.020634961602525, 0.489682519198738, 
+		0.489682519198738, 0.125820817014127, 0.437089591492937, 
+		0.437089591492937, 0.623592928761935, 0.188203535619033, 
+		0.188203535619033, 0.910540973211095, 0.044729513394453, 
+		0.044729513394453, 0.036838412054736, 0.036838412054736, 
+		0.221962989160766, 0.741198598784498, 0.221962989160766, 
+		0.741198598784498};
+	static IssmPDouble l29[]={
+		0.333333333333333, 0.489682519198738, 0.020634961602525, 
+		0.489682519198738, 0.437089591492937, 0.125820817014127, 
+		0.437089591492937, 0.188203535619033, 0.623592928761935, 
+		0.188203535619033, 0.044729513394453, 0.910540973211095, 
+		0.044729513394453, 0.221962989160766, 0.741198598784498, 
+		0.036838412054736, 0.036838412054736, 0.741198598784498, 
+		0.221962989160766};
+	static IssmPDouble l39[]={
+		0.333333333333333, 0.489682519198738, 0.489682519198738, 
+		0.020634961602525, 0.437089591492937, 0.437089591492937, 
+		0.125820817014127, 0.188203535619033, 0.188203535619033, 
+		0.623592928761935, 0.044729513394453, 0.044729513394453, 
+		0.910540973211095, 0.741198598784498, 0.221962989160766, 
+		0.741198598784498, 0.221962989160766, 0.036838412054736, 
+		0.036838412054736};
+	/*}}}*/
+	/*p=10, npoint=25  {{{*/
+	static IssmPDouble wgt10[]={
+		0.157301373584232, 0.063611224790829, 0.063611224790829, 
+		0.063611224790829, 0.078498377595183, 0.078498377595183, 
+		0.078498377595183, 0.126020408629139, 0.126020408629139, 
+		0.126020408629139, 0.126020408629139, 0.126020408629139, 
+		0.126020408629139, 0.049064223302117, 0.049064223302117, 
+		0.049064223302117, 0.049064223302117, 0.049064223302117, 
+		0.049064223302117, 0.016318805873179, 0.016318805873179, 
+		0.016318805873179, 0.016318805873179, 0.016318805873179, 
+		0.016318805873179};
+	static IssmPDouble l110[]={
+		0.333333333333333, 0.028844733232685, 0.485577633383657, 
+		0.485577633383657, 0.781036849029926, 0.109481575485037, 
+		0.109481575485037, 0.141707219414880, 0.141707219414880, 
+		0.307939838764121, 0.550352941820999, 0.307939838764121, 
+		0.550352941820999, 0.025003534762686, 0.025003534762686, 
+		0.246672560639903, 0.728323904597411, 0.246672560639903, 
+		0.728323904597411, 0.009540815400299, 0.009540815400299, 
+		0.066803251012200, 0.923655933587500, 0.066803251012200, 
+		0.923655933587500};
+	static IssmPDouble l210[]={
+		0.333333333333333, 0.485577633383657, 0.028844733232685, 
+		0.485577633383657, 0.109481575485037, 0.781036849029926, 
+		0.109481575485037, 0.307939838764121, 0.550352941820999, 
+		0.141707219414880, 0.141707219414880, 0.550352941820999, 
+		0.307939838764121, 0.246672560639903, 0.728323904597411, 
+		0.025003534762686, 0.025003534762686, 0.728323904597411, 
+		0.246672560639903, 0.066803251012200, 0.923655933587500, 
+		0.009540815400299, 0.009540815400299, 0.923655933587500, 
+		0.066803251012200};
+	static IssmPDouble l310[]={
+		0.333333333333333, 0.485577633383657, 0.485577633383657, 
+		0.028844733232685, 0.109481575485037, 0.109481575485037, 
+		0.781036849029926, 0.550352941820999, 0.307939838764121, 
+		0.550352941820999, 0.307939838764121, 0.141707219414880, 
+		0.141707219414880, 0.728323904597411, 0.246672560639903, 
+		0.728323904597411, 0.246672560639903, 0.025003534762686, 
+		0.025003534762686, 0.923655933587500, 0.066803251012200, 
+		0.923655933587500, 0.066803251012200, 0.009540815400299, 
+		0.009540815400299};
+	/*}}}*/
+	/*p=11, npoint=27  {{{*/
+	static IssmPDouble wgt11[]={
+		0.001605622060698, 0.001605622060698, 0.001605622060698, 
+		0.133626914252765, 0.133626914252765, 0.133626914252765, 
+		0.102750410879760, 0.102750410879760, 0.102750410879760, 
+		0.062673462600454, 0.062673462600454, 0.062673462600454, 
+		0.023659348114362, 0.023659348114362, 0.023659348114362, 
+		0.090650537039958, 0.090650537039958, 0.090650537039958, 
+		0.090650537039958, 0.090650537039958, 0.090650537039958, 
+		0.035866718600836, 0.035866718600836, 0.035866718600836, 
+		0.035866718600836, 0.035866718600836, 0.035866718600836};
+	static IssmPDouble l111[]={
+		-0.069222096541517, 0.534611048270758, 0.534611048270758, 
+		0.202061394068290, 0.398969302965855, 0.398969302965855, 
+		0.593380199137435, 0.203309900431282, 0.203309900431282, 
+		0.761298175434837, 0.119350912282581, 0.119350912282581, 
+		0.935270103777448, 0.032364948111276, 0.032364948111276, 
+		0.050178138310495, 0.050178138310495, 0.356620648261293, 
+		0.593201213428213, 0.356620648261293, 0.593201213428213, 
+		0.021022016536166, 0.021022016536166, 0.171488980304042, 
+		0.807489003159792, 0.171488980304042, 0.807489003159792};
+	static IssmPDouble l211[]={
+		0.534611048270758,-0.069222096541517, 0.534611048270758, 
+		0.398969302965855, 0.202061394068290, 0.398969302965855, 
+		0.203309900431282, 0.593380199137435, 0.203309900431282, 
+		0.119350912282581, 0.761298175434837, 0.119350912282581, 
+		0.032364948111276, 0.935270103777448, 0.032364948111276, 
+		0.356620648261293, 0.593201213428213, 0.050178138310495, 
+		0.050178138310495, 0.593201213428213, 0.356620648261293, 
+		0.171488980304042, 0.807489003159792, 0.021022016536166, 
+		0.021022016536166, 0.807489003159792, 0.171488980304042};
+	static IssmPDouble l311[]={
+		0.534611048270758, 0.534611048270758,-0.069222096541517, 
+		0.398969302965855, 0.398969302965855, 0.202061394068290, 
+		0.203309900431282, 0.203309900431282, 0.593380199137435, 
+		0.119350912282581, 0.119350912282581, 0.761298175434837, 
+		0.032364948111276, 0.032364948111276, 0.935270103777448, 
+		0.593201213428213, 0.356620648261293, 0.593201213428213, 
+		0.356620648261293, 0.050178138310495, 0.050178138310495, 
+		0.807489003159792, 0.171488980304042, 0.807489003159792, 
+		0.171488980304042, 0.021022016536166, 0.021022016536166};
+	/*}}}*/
+	/*p=12, npoint=33  {{{*/
+	static IssmPDouble wgt12[]={
+		0.044567514407799, 0.044567514407799, 0.044567514407799, 
+		0.075677707051848, 0.075677707051848, 0.075677707051848, 
+		0.108873638018933, 0.108873638018933, 0.108873638018933, 
+		0.060268635501892, 0.060268635501892, 0.060268635501892, 
+		0.010680277434033, 0.010680277434033, 0.010680277434033, 
+		0.069925589232074, 0.069925589232074, 0.069925589232074, 
+		0.069925589232074, 0.069925589232074, 0.069925589232074, 
+		0.038723067079683, 0.038723067079683, 0.038723067079683, 
+		0.038723067079683, 0.038723067079683, 0.038723067079683, 
+		0.029992592075802, 0.029992592075802, 0.029992592075802, 
+		0.029992592075802, 0.029992592075802, 0.029992592075802};
+	static IssmPDouble l112[]={
+		0.023565220452390, 0.488217389773805, 0.488217389773805, 
+		0.120551215411079, 0.439724392294460, 0.439724392294460, 
+		0.457579229975768, 0.271210385012116, 0.271210385012116, 
+		0.744847708916828, 0.127576145541586, 0.127576145541586, 
+		0.957365299093579, 0.021317350453210, 0.021317350453210, 
+		0.115343494534698, 0.115343494534698, 0.275713269685514, 
+		0.608943235779788, 0.275713269685514, 0.608943235779788, 
+		0.022838332222257, 0.022838332222257, 0.281325580989940, 
+		0.695836086787803, 0.281325580989940, 0.695836086787803, 
+		0.025734050548330, 0.025734050548330, 0.116251915907597, 
+		0.858014033544073, 0.116251915907597, 0.858014033544073};
+	static IssmPDouble l212[]={
+		0.488217389773805, 0.023565220452390, 0.488217389773805, 
+		0.439724392294460, 0.120551215411079, 0.439724392294460, 
+		0.271210385012116, 0.457579229975768, 0.271210385012116, 
+		0.127576145541586, 0.744847708916828, 0.127576145541586, 
+		0.021317350453210, 0.957365299093579, 0.021317350453210, 
+		0.275713269685514, 0.608943235779788, 0.115343494534698, 
+		0.115343494534698, 0.608943235779788, 0.275713269685514, 
+		0.281325580989940, 0.695836086787803, 0.022838332222257, 
+		0.022838332222257, 0.695836086787803, 0.281325580989940, 
+		0.116251915907597, 0.858014033544073, 0.025734050548330, 
+		0.025734050548330, 0.858014033544073, 0.116251915907597};
+	static IssmPDouble l312[]={
+		0.488217389773805, 0.488217389773805, 0.023565220452390, 
+		0.439724392294460, 0.439724392294460, 0.120551215411079, 
+		0.271210385012116, 0.271210385012116, 0.457579229975768, 
+		0.127576145541586, 0.127576145541586, 0.744847708916828, 
+		0.021317350453210, 0.021317350453210, 0.957365299093579, 
+		0.608943235779788, 0.275713269685514, 0.608943235779788, 
+		0.275713269685514, 0.115343494534698, 0.115343494534698, 
+		0.695836086787803, 0.281325580989940, 0.695836086787803, 
+		0.281325580989940, 0.022838332222257, 0.022838332222257, 
+		0.858014033544073, 0.116251915907597, 0.858014033544073, 
+		0.116251915907597, 0.025734050548330, 0.025734050548330};
+	/*}}}*/
+	/*p=13, npoint=37  {{{*/
+	static IssmPDouble wgt13[]={
+		0.090968907790622, 0.019537784619314, 0.019537784619314, 
+		0.019537784619314, 0.054427130356344, 0.054427130356344, 
+		0.054427130356344, 0.081531965976677, 0.081531965976677, 
+		0.081531965976677, 0.082036138309652, 0.082036138309652, 
+		0.082036138309652, 0.053983743853694, 0.053983743853694, 
+		0.053983743853694, 0.013814441407066, 0.013814441407066, 
+		0.013814441407066, 0.063823305703923, 0.063823305703923, 
+		0.063823305703923, 0.063823305703923, 0.063823305703923, 
+		0.063823305703923, 0.030140218568265, 0.030140218568265, 
+		0.030140218568265, 0.030140218568265, 0.030140218568265, 
+		0.030140218568265, 0.026884523429480, 0.026884523429480, 
+		0.026884523429480, 0.026884523429480, 0.026884523429480, 
+		0.026884523429480};
+	static IssmPDouble l113[]={
+		0.333333333333333, 0.009903630120591, 0.495048184939705, 
+		0.495048184939705, 0.062566729780852, 0.468716635109574, 
+		0.468716635109574, 0.170957326397447, 0.414521336801277, 
+		0.414521336801277, 0.541200855914337, 0.229399572042831, 
+		0.229399572042831, 0.771151009607340, 0.114424495196330, 
+		0.114424495196330, 0.950377217273082, 0.024811391363459, 
+		0.024811391363459, 0.094853828379579, 0.094853828379579, 
+		0.268794997058761, 0.636351174561660, 0.268794997058761, 
+		0.636351174561660, 0.018100773278807, 0.018100773278807, 
+		0.291730066734288, 0.690169159986905, 0.291730066734288, 
+		0.690169159986905, 0.022233076674090, 0.022233076674090, 
+		0.126357385491669, 0.851409537834241, 0.126357385491669, 
+		0.851409537834241};
+	static IssmPDouble l213[]={
+		0.333333333333333, 0.495048184939705, 0.009903630120591, 
+		0.495048184939705, 0.468716635109574, 0.062566729780852, 
+		0.468716635109574, 0.414521336801277, 0.170957326397447, 
+		0.414521336801277, 0.229399572042831, 0.541200855914337, 
+		0.229399572042831, 0.114424495196330, 0.771151009607340, 
+		0.114424495196330, 0.024811391363459, 0.950377217273082, 
+		0.024811391363459, 0.268794997058761, 0.636351174561660, 
+		0.094853828379579, 0.094853828379579, 0.636351174561660, 
+		0.268794997058761, 0.291730066734288, 0.690169159986905, 
+		0.018100773278807, 0.018100773278807, 0.690169159986905, 
+		0.291730066734288, 0.126357385491669, 0.851409537834241, 
+		0.022233076674090, 0.022233076674090, 0.851409537834241, 
+		0.126357385491669};
+	static IssmPDouble l313[]={
+		0.333333333333333, 0.495048184939705, 0.495048184939705, 
+		0.009903630120591, 0.468716635109574, 0.468716635109574, 
+		0.062566729780852, 0.414521336801277, 0.414521336801277, 
+		0.170957326397447, 0.229399572042831, 0.229399572042831, 
+		0.541200855914337, 0.114424495196330, 0.114424495196330, 
+		0.771151009607340, 0.024811391363459, 0.024811391363459, 
+		0.950377217273082, 0.636351174561660, 0.268794997058761, 
+		0.636351174561660, 0.268794997058761, 0.094853828379579, 
+		0.094853828379579, 0.690169159986905, 0.291730066734288, 
+		0.690169159986905, 0.291730066734288, 0.018100773278807, 
+		0.018100773278807, 0.851409537834241, 0.126357385491669, 
+		0.851409537834241, 0.126357385491669, 0.022233076674090, 
+		0.022233076674090};
+	/*}}}*/
+	/*p=14, npoint=42{{{*/
+	static IssmPDouble wgt14[]={
+		0.037903474783419, 0.037903474783419, 0.037903474783419, 
+		0.056791094234956, 0.056791094234956, 0.056791094234956, 
+		0.089675379523011, 0.089675379523011, 0.089675379523011, 
+		0.073027745871103, 0.073027745871103, 0.073027745871103, 
+		0.024999901169244, 0.024999901169244, 0.024999901169244, 
+		0.008527585185524, 0.008527585185524, 0.008527585185524, 
+		0.042722337771116, 0.042722337771116, 0.042722337771116, 
+		0.042722337771116, 0.042722337771116, 0.042722337771116, 
+		0.066807816407881, 0.066807816407881, 0.066807816407881, 
+		0.066807816407881, 0.066807816407881, 0.066807816407881, 
+		0.025004419126360, 0.025004419126360, 0.025004419126360, 
+		0.025004419126360, 0.025004419126360, 0.025004419126360, 
+		0.008677970905831, 0.008677970905831, 0.008677970905831, 
+		0.008677970905831, 0.008677970905831, 0.008677970905831};
+	static IssmPDouble l114[]={
+		0.022072179275643, 0.488963910362179, 0.488963910362179, 
+		0.164710561319092, 0.417644719340454, 0.417644719340454, 
+		0.453044943382323, 0.273477528308839, 0.273477528308839, 
+		0.645588935174913, 0.177205532412543, 0.177205532412543, 
+		0.876400233818255, 0.061799883090873, 0.061799883090873, 
+		0.961218077502598, 0.019390961248701, 0.019390961248701, 
+		0.057124757403648, 0.057124757403648, 0.172266687821356, 
+		0.770608554774996, 0.172266687821356, 0.770608554774996, 
+		0.092916249356972, 0.092916249356972, 0.336861459796345, 
+		0.570222290846683, 0.336861459796345, 0.570222290846683, 
+		0.014646950055654, 0.014646950055654, 0.298372882136258, 
+		0.686980167808088, 0.298372882136258, 0.686980167808088, 
+		0.001268330932872, 0.001268330932872, 0.118974497696957, 
+		0.879757171370171, 0.118974497696957, 0.879757171370171};
+	static IssmPDouble l214[]={
+		0.488963910362179, 0.022072179275643, 0.488963910362179, 
+		0.417644719340454, 0.164710561319092, 0.417644719340454, 
+		0.273477528308839, 0.453044943382323, 0.273477528308839, 
+		0.177205532412543, 0.645588935174913, 0.177205532412543, 
+		0.061799883090873, 0.876400233818255, 0.061799883090873, 
+		0.019390961248701, 0.961218077502598, 0.019390961248701, 
+		0.172266687821356, 0.770608554774996, 0.057124757403648, 
+		0.057124757403648, 0.770608554774996, 0.172266687821356, 
+		0.336861459796345, 0.570222290846683, 0.092916249356972, 
+		0.092916249356972, 0.570222290846683, 0.336861459796345, 
+		0.298372882136258, 0.686980167808088, 0.014646950055654, 
+		0.014646950055654, 0.686980167808088, 0.298372882136258, 
+		0.118974497696957, 0.879757171370171, 0.001268330932872, 
+		0.001268330932872, 0.879757171370171, 0.118974497696957};
+	static IssmPDouble l314[]={
+		0.488963910362179, 0.488963910362179, 0.022072179275643, 
+		0.417644719340454, 0.417644719340454, 0.164710561319092, 
+		0.273477528308839, 0.273477528308839, 0.453044943382323, 
+		0.177205532412543, 0.177205532412543, 0.645588935174913, 
+		0.061799883090873, 0.061799883090873, 0.876400233818255, 
+		0.019390961248701, 0.019390961248701, 0.961218077502598, 
+		0.770608554774996, 0.172266687821356, 0.770608554774996, 
+		0.172266687821356, 0.057124757403648, 0.057124757403648, 
+		0.570222290846683, 0.336861459796345, 0.570222290846683, 
+		0.336861459796345, 0.092916249356972, 0.092916249356972, 
+		0.686980167808088, 0.298372882136258, 0.686980167808088, 
+		0.298372882136258, 0.014646950055654, 0.014646950055654, 
+		0.879757171370171, 0.118974497696957, 0.879757171370171, 
+		0.118974497696957, 0.001268330932872, 0.001268330932872};
+	/*}}}*/
+	/*p=15, npoint=48{{{*/
+	static IssmPDouble wgt15[]={
+		0.003320126005206, 0.003320126005206, 0.003320126005206, 
+		0.076641563419124, 0.076641563419124, 0.076641563419124, 
+		0.088657703045151, 0.088657703045151, 0.088657703045151, 
+		0.041028362044303, 0.041028362044303, 0.041028362044303, 
+		0.023018566716310, 0.023018566716310, 0.023018566716310, 
+		0.008225364846296, 0.008225364846296, 0.008225364846296, 
+		0.066770684377964, 0.066770684377964, 0.066770684377964, 
+		0.066770684377964, 0.066770684377964, 0.066770684377964, 
+		0.047139173172681, 0.047139173172681, 0.047139173172681, 
+		0.047139173172681, 0.047139173172681, 0.047139173172681, 
+		0.003779468865339, 0.003779468865339, 0.003779468865339, 
+		0.003779468865339, 0.003779468865339, 0.003779468865339, 
+		0.037248306609289, 0.037248306609289, 0.037248306609289, 
+		0.037248306609289, 0.037248306609289, 0.037248306609289, 
+		0.013291658531346, 0.013291658531346, 0.013291658531346, 
+		0.013291658531346, 0.013291658531346, 0.013291658531346};
+	static IssmPDouble l115[]={
+		-0.013945833716486, 0.506972916858243, 0.506972916858243, 
+		0.137187291433955, 0.431406354283023, 0.431406354283023, 
+		0.444612710305711, 0.277693644847144, 0.277693644847144, 
+		0.747070217917492, 0.126464891041254, 0.126464891041254, 
+		0.858383228050628, 0.070808385974686, 0.070808385974686, 
+		0.962069659517853, 0.018965170241073, 0.018965170241073, 
+		0.133734161966621, 0.133734161966621, 0.261311371140087, 
+		0.604954466893291, 0.261311371140087, 0.604954466893291, 
+		0.036366677396917, 0.036366677396917, 0.388046767090269, 
+		0.575586555512814, 0.388046767090269, 0.575586555512814, 
+		-0.010174883126571,-0.010174883126571, 0.285712220049916, 
+		0.724462663076655, 0.285712220049916, 0.724462663076655, 
+		0.036843869875878, 0.036843869875878, 0.215599664072284, 
+		0.747556466051838, 0.215599664072284, 0.747556466051838, 
+		0.012459809331199, 0.012459809331199, 0.103575616576386, 
+		0.883964574092416, 0.103575616576386, 0.883964574092416};
+	static IssmPDouble l215[]={
+		0.506972916858243,-0.013945833716486, 0.506972916858243, 
+		0.431406354283023, 0.137187291433955, 0.431406354283023, 
+		0.277693644847144, 0.444612710305711, 0.277693644847144, 
+		0.126464891041254, 0.747070217917492, 0.126464891041254, 
+		0.070808385974686, 0.858383228050628, 0.070808385974686, 
+		0.018965170241073, 0.962069659517853, 0.018965170241073, 
+		0.261311371140087, 0.604954466893291, 0.133734161966621, 
+		0.133734161966621, 0.604954466893291, 0.261311371140087, 
+		0.388046767090269, 0.575586555512814, 0.036366677396917, 
+		0.036366677396917, 0.575586555512814, 0.388046767090269, 
+		0.285712220049916, 0.724462663076655,-0.010174883126571, 
+		-0.010174883126571, 0.724462663076655, 0.285712220049916, 
+		0.215599664072284, 0.747556466051838, 0.036843869875878, 
+		0.036843869875878, 0.747556466051838, 0.215599664072284, 
+		0.103575616576386, 0.883964574092416, 0.012459809331199, 
+		0.012459809331199, 0.883964574092416, 0.103575616576386};
+	static IssmPDouble l315[]={
+		0.506972916858243, 0.506972916858243,-0.013945833716486, 
+		0.431406354283023, 0.431406354283023, 0.137187291433955, 
+		0.277693644847144, 0.277693644847144, 0.444612710305711, 
+		0.126464891041254, 0.126464891041254, 0.747070217917492, 
+		0.070808385974686, 0.070808385974686, 0.858383228050628, 
+		0.018965170241073, 0.018965170241073, 0.962069659517853, 
+		0.604954466893291, 0.261311371140087, 0.604954466893291, 
+		0.261311371140087, 0.133734161966621, 0.133734161966621, 
+		0.575586555512814, 0.388046767090269, 0.575586555512814, 
+		0.388046767090269, 0.036366677396917, 0.036366677396917, 
+		0.724462663076655, 0.285712220049916, 0.724462663076655, 
+		0.285712220049916,-0.010174883126571,-0.010174883126571, 
+		0.747556466051838, 0.215599664072284, 0.747556466051838, 
+		0.215599664072284, 0.036843869875878, 0.036843869875878, 
+		0.883964574092416, 0.103575616576386, 0.883964574092416, 
+		0.103575616576386, 0.012459809331199, 0.012459809331199};
+	/*}}}*/
+	/*p=16, npoint=52  {{{*/
+	static IssmPDouble wgt16[]={
+		0.081191089584902, 0.011095307165226, 0.011095307165226, 
+		0.011095307165226, 0.072244353151393, 0.072244353151393, 
+		0.072244353151393, 0.046577417012049, 0.046577417012049, 
+		0.046577417012049, 0.072975670074230, 0.072975670074230, 
+		0.072975670074230, 0.051961986412307, 0.051961986412307, 
+		0.051961986412307, 0.024595292810646, 0.024595292810646, 
+		0.024595292810646, 0.006205006808607, 0.006205006808607, 
+		0.006205006808607, 0.056764756525753, 0.056764756525753, 
+		0.056764756525753, 0.056764756525753, 0.056764756525753, 
+		0.056764756525753, 0.026497443692048, 0.026497443692048, 
+		0.026497443692048, 0.026497443692048, 0.026497443692048, 
+		0.026497443692048, 0.004133096181263, 0.004133096181263, 
+		0.004133096181263, 0.004133096181263, 0.004133096181263, 
+		0.004133096181263, 0.033055830705140, 0.033055830705140, 
+		0.033055830705140, 0.033055830705140, 0.033055830705140, 
+		0.033055830705140, 0.011864642509229, 0.011864642509229, 
+		0.011864642509229, 0.011864642509229, 0.011864642509229, 
+		0.011864642509229};
+	static IssmPDouble l116[]={
+		0.333333333333333, 0.005238916103123, 0.497380541948438, 
+		0.497380541948438, 0.173061122901295, 0.413469438549352, 
+		0.413469438549352, 0.059082801866017, 0.470458599066991, 
+		0.470458599066991, 0.518892500060958, 0.240553749969521, 
+		0.240553749969521, 0.704068411554854, 0.147965794222573, 
+		0.147965794222573, 0.849069624685052, 0.075465187657474, 
+		0.075465187657474, 0.966807194753950, 0.016596402623025, 
+		0.016596402623025, 0.103575692245252, 0.103575692245252, 
+		0.296555596579887, 0.599868711174861, 0.296555596579887, 
+		0.599868711174861, 0.020083411655416, 0.020083411655416, 
+		0.337723063403079, 0.642193524941505, 0.337723063403079, 
+		0.642193524941505,-0.004341002614139,-0.004341002614139, 
+		0.204748281642812, 0.799592720971327, 0.204748281642812, 
+		0.799592720971327, 0.041941786468010, 0.041941786468010, 
+		0.189358492130623, 0.768699721401368, 0.189358492130623, 
+		0.768699721401368, 0.014317320230681, 0.014317320230681, 
+		0.085283615682657, 0.900399064086661, 0.085283615682657, 
+		0.900399064086661};
+	static IssmPDouble l216[]={
+		0.333333333333333, 0.497380541948438, 0.005238916103123, 
+		0.497380541948438, 0.413469438549352, 0.173061122901295, 
+		0.413469438549352, 0.470458599066991, 0.059082801866017, 
+		0.470458599066991, 0.240553749969521, 0.518892500060958, 
+		0.240553749969521, 0.147965794222573, 0.704068411554854, 
+		0.147965794222573, 0.075465187657474, 0.849069624685052, 
+		0.075465187657474, 0.016596402623025, 0.966807194753950, 
+		0.016596402623025, 0.296555596579887, 0.599868711174861, 
+		0.103575692245252, 0.103575692245252, 0.599868711174861, 
+		0.296555596579887, 0.337723063403079, 0.642193524941505, 
+		0.020083411655416, 0.020083411655416, 0.642193524941505, 
+		0.337723063403079, 0.204748281642812, 0.799592720971327, 
+		-0.004341002614139,-0.004341002614139, 0.799592720971327, 
+		0.204748281642812, 0.189358492130623, 0.768699721401368, 
+		0.041941786468010, 0.041941786468010, 0.768699721401368, 
+		0.189358492130623, 0.085283615682657, 0.900399064086661, 
+		0.014317320230681, 0.014317320230681, 0.900399064086661, 
+		0.085283615682657};
+	static IssmPDouble l316[]={
+		0.333333333333333, 0.497380541948438, 0.497380541948438, 
+		0.005238916103123, 0.413469438549352, 0.413469438549352, 
+		0.173061122901295, 0.470458599066991, 0.470458599066991, 
+		0.059082801866017, 0.240553749969521, 0.240553749969521, 
+		0.518892500060958, 0.147965794222573, 0.147965794222573, 
+		0.704068411554854, 0.075465187657474, 0.075465187657474, 
+		0.849069624685052, 0.016596402623025, 0.016596402623025, 
+		0.966807194753950, 0.599868711174861, 0.296555596579887, 
+		0.599868711174861, 0.296555596579887, 0.103575692245252, 
+		0.103575692245252, 0.642193524941505, 0.337723063403079, 
+		0.642193524941505, 0.337723063403079, 0.020083411655416, 
+		0.020083411655416, 0.799592720971327, 0.204748281642812, 
+		0.799592720971327, 0.204748281642812,-0.004341002614139, 
+		-0.004341002614139, 0.768699721401368, 0.189358492130623, 
+		0.768699721401368, 0.189358492130623, 0.041941786468010, 
+		0.041941786468010, 0.900399064086661, 0.085283615682657, 
+		0.900399064086661, 0.085283615682657, 0.014317320230681, 
+		0.014317320230681};
+	/*}}}*/
+	/*p=17, npoint=61{{{*/
+	static IssmPDouble wgt17[]={
+		0.057914928034477, 0.008822054327014, 0.008822054327014, 
+		0.008822054327014, 0.025410682752829, 0.025410682752829, 
+		0.025410682752829, 0.042176958517489, 0.042176958517489, 
+		0.042176958517489, 0.053879858604088, 0.053879858604088, 
+		0.053879858604088, 0.054138904728481, 0.054138904728481, 
+		0.054138904728481, 0.042981974139367, 0.042981974139367, 
+		0.042981974139367, 0.024345832713105, 0.024345832713105, 
+		0.024345832713105, 0.005533341446715, 0.005533341446715, 
+		0.005533341446715, 0.014063655552443, 0.014063655552443, 
+		0.014063655552443, 0.014063655552443, 0.014063655552443, 
+		0.014063655552443, 0.046428907569036, 0.046428907569036, 
+		0.046428907569036, 0.046428907569036, 0.046428907569036, 
+		0.046428907569036, 0.031973646148520, 0.031973646148520, 
+		0.031973646148520, 0.031973646148520, 0.031973646148520, 
+		0.031973646148520, 0.014682366990538, 0.014682366990538, 
+		0.014682366990538, 0.014682366990538, 0.014682366990538, 
+		0.014682366990538, 0.031684053418215, 0.031684053418215, 
+		0.031684053418215, 0.031684053418215, 0.031684053418215, 
+		0.031684053418215, 0.011545213295771, 0.011545213295771, 
+		0.011545213295771, 0.011545213295771, 0.011545213295771, 
+		0.011545213295771};
+	static IssmPDouble l117[]={
+		0.333333333333333, 0.005658918886452, 0.497170540556774, 
+		0.497170540556774, 0.035647354750751, 0.482176322624625, 
+		0.482176322624625, 0.099520061958437, 0.450239969020782, 
+		0.450239969020782, 0.199467521245206, 0.400266239377397, 
+		0.400266239377397, 0.495717464058095, 0.252141267970953, 
+		0.252141267970953, 0.675905990683077, 0.162047004658461, 
+		0.162047004658461, 0.848248235478508, 0.075875882260746, 
+		0.075875882260746, 0.968690546064356, 0.015654726967822, 
+		0.015654726967822, 0.010186928826919, 0.010186928826919, 
+		0.334319867363658, 0.655493203809423, 0.334319867363658, 
+		0.655493203809423, 0.135440871671036, 0.135440871671036, 
+		0.292221537796944, 0.572337590532020, 0.292221537796944, 
+		0.572337590532020, 0.054423924290583, 0.054423924290583, 
+		0.319574885423190, 0.626001190286228, 0.319574885423190, 
+		0.626001190286228, 0.012868560833637, 0.012868560833637, 
+		0.190704224192292, 0.796427214974071, 0.190704224192292, 
+		0.796427214974071, 0.067165782413524, 0.067165782413524, 
+		0.180483211648746, 0.752351005937729, 0.180483211648746, 
+		0.752351005937729, 0.014663182224828, 0.014663182224828, 
+		0.080711313679564, 0.904625504095608, 0.080711313679564, 
+		0.904625504095608};
+	static IssmPDouble l217[]={
+		0.333333333333333, 0.497170540556774, 0.005658918886452, 
+		0.497170540556774, 0.482176322624625, 0.035647354750751, 
+		0.482176322624625, 0.450239969020782, 0.099520061958437, 
+		0.450239969020782, 0.400266239377397, 0.199467521245206, 
+		0.400266239377397, 0.252141267970953, 0.495717464058095, 
+		0.252141267970953, 0.162047004658461, 0.675905990683077, 
+		0.162047004658461, 0.075875882260746, 0.848248235478508, 
+		0.075875882260746, 0.015654726967822, 0.968690546064356, 
+		0.015654726967822, 0.334319867363658, 0.655493203809423, 
+		0.010186928826919, 0.010186928826919, 0.655493203809423, 
+		0.334319867363658, 0.292221537796944, 0.572337590532020, 
+		0.135440871671036, 0.135440871671036, 0.572337590532020, 
+		0.292221537796944, 0.319574885423190, 0.626001190286228, 
+		0.054423924290583, 0.054423924290583, 0.626001190286228, 
+		0.319574885423190, 0.190704224192292, 0.796427214974071, 
+		0.012868560833637, 0.012868560833637, 0.796427214974071, 
+		0.190704224192292, 0.180483211648746, 0.752351005937729, 
+		0.067165782413524, 0.067165782413524, 0.752351005937729, 
+		0.180483211648746, 0.080711313679564, 0.904625504095608, 
+		0.014663182224828, 0.014663182224828, 0.904625504095608, 
+		0.080711313679564};
+	static IssmPDouble l317[]={
+		0.333333333333333, 0.497170540556774, 0.497170540556774, 
+		0.005658918886452, 0.482176322624625, 0.482176322624625, 
+		0.035647354750751, 0.450239969020782, 0.450239969020782, 
+		0.099520061958437, 0.400266239377397, 0.400266239377397, 
+		0.199467521245206, 0.252141267970953, 0.252141267970953, 
+		0.495717464058095, 0.162047004658461, 0.162047004658461, 
+		0.675905990683077, 0.075875882260746, 0.075875882260746, 
+		0.848248235478508, 0.015654726967822, 0.015654726967822, 
+		0.968690546064356, 0.655493203809423, 0.334319867363658, 
+		0.655493203809423, 0.334319867363658, 0.010186928826919, 
+		0.010186928826919, 0.572337590532020, 0.292221537796944, 
+		0.572337590532020, 0.292221537796944, 0.135440871671036, 
+		0.135440871671036, 0.626001190286228, 0.319574885423190, 
+		0.626001190286228, 0.319574885423190, 0.054423924290583, 
+		0.054423924290583, 0.796427214974071, 0.190704224192292, 
+		0.796427214974071, 0.190704224192292, 0.012868560833637, 
+		0.012868560833637, 0.752351005937729, 0.180483211648746, 
+		0.752351005937729, 0.180483211648746, 0.067165782413524, 
+		0.067165782413524, 0.904625504095608, 0.080711313679564, 
+		0.904625504095608, 0.080711313679564, 0.014663182224828, 
+		0.014663182224828};
+	/*}}}*/
+	/*p=18, npoint=70  {{{*/
+
+	static IssmPDouble wgt18[]={
+		0.053364381350150, 0.015713921277179, 0.015713921277179, 
+		0.015713921277179, 0.032495554156279, 0.032495554156279, 
+		0.032495554156279, 0.033672969465771, 0.033672969465771, 
+		0.033672969465771, 0.048071249104579, 0.048071249104579, 
+		0.048071249104579, 0.055869421169115, 0.055869421169115, 
+		0.055869421169115, 0.043429498443148, 0.043429498443148, 
+		0.043429498443148, 0.026451755176745, 0.026451755176745, 
+		0.026451755176745, 0.011767418126433, 0.011767418126433, 
+		0.011767418126433,-0.003850519950463,-0.003850519950463, 
+		-0.003850519950463, 0.010967196889496, 0.010967196889496, 
+		0.010967196889496, 0.010967196889496, 0.010967196889496, 
+		0.010967196889496, 0.047211440790349, 0.047211440790349, 
+		0.047211440790349, 0.047211440790349, 0.047211440790349, 
+		0.047211440790349, 0.030617090859378, 0.030617090859378, 
+		0.030617090859378, 0.030617090859378, 0.030617090859378, 
+		0.030617090859378, 0.031834201210069, 0.031834201210069, 
+		0.031834201210069, 0.031834201210069, 0.031834201210069, 
+		0.031834201210069, 0.014037809005559, 0.014037809005559, 
+		0.014037809005559, 0.014037809005559, 0.014037809005559, 
+		0.014037809005559, 0.013222699422034, 0.013222699422034, 
+		0.013222699422034, 0.013222699422034, 0.013222699422034, 
+		0.013222699422034, 0.000079999375178, 0.000079999375178, 
+		0.000079999375178, 0.000079999375178, 0.000079999375178, 
+		0.000079999375178};
+	static IssmPDouble l118[]={
+		0.333333333333333, 0.013310382738157, 0.493344808630921, 
+		0.493344808630921, 0.061578811516086, 0.469210594241957, 
+		0.469210594241957, 0.127437208225989, 0.436281395887006, 
+		0.436281395887006, 0.210307658653168, 0.394846170673416, 
+		0.394846170673416, 0.500410862393686, 0.249794568803157, 
+		0.249794568803157, 0.677135612512315, 0.161432193743843, 
+		0.161432193743843, 0.846803545029257, 0.076598227485371, 
+		0.076598227485371, 0.951495121293100, 0.024252439353450, 
+		0.024252439353450, 0.913707265566071, 0.043146367216965, 
+		0.043146367216965, 0.008430536202420, 0.008430536202420, 
+		0.358911494940944, 0.632657968856636, 0.358911494940944, 
+		0.632657968856636, 0.131186551737188, 0.131186551737188, 
+		0.294402476751957, 0.574410971510855, 0.294402476751957, 
+		0.574410971510855, 0.050203151565675, 0.050203151565675, 
+		0.325017801641814, 0.624779046792512, 0.325017801641814, 
+		0.624779046792512, 0.066329263810916, 0.066329263810916, 
+		0.184737559666046, 0.748933176523037, 0.184737559666046, 
+		0.748933176523037, 0.011996194566236, 0.011996194566236, 
+		0.218796800013321, 0.769207005420443, 0.218796800013321, 
+		0.769207005420443, 0.014858100590125, 0.014858100590125, 
+		0.101179597136408, 0.883962302273467, 0.101179597136408, 
+		0.883962302273467,-0.035222015287949,-0.035222015287949, 
+		0.020874755282586, 1.014347260005363, 0.020874755282586, 
+		1.014347260005363};
+	static IssmPDouble l218[]={
+		0.333333333333333, 0.493344808630921, 0.013310382738157, 
+		0.493344808630921, 0.469210594241957, 0.061578811516086, 
+		0.469210594241957, 0.436281395887006, 0.127437208225989, 
+		0.436281395887006, 0.394846170673416, 0.210307658653168, 
+		0.394846170673416, 0.249794568803157, 0.500410862393686, 
+		0.249794568803157, 0.161432193743843, 0.677135612512315, 
+		0.161432193743843, 0.076598227485371, 0.846803545029257, 
+		0.076598227485371, 0.024252439353450, 0.951495121293100, 
+		0.024252439353450, 0.043146367216965, 0.913707265566071, 
+		0.043146367216965, 0.358911494940944, 0.632657968856636, 
+		0.008430536202420, 0.008430536202420, 0.632657968856636, 
+		0.358911494940944, 0.294402476751957, 0.574410971510855, 
+		0.131186551737188, 0.131186551737188, 0.574410971510855, 
+		0.294402476751957, 0.325017801641814, 0.624779046792512, 
+		0.050203151565675, 0.050203151565675, 0.624779046792512, 
+		0.325017801641814, 0.184737559666046, 0.748933176523037, 
+		0.066329263810916, 0.066329263810916, 0.748933176523037, 
+		0.184737559666046, 0.218796800013321, 0.769207005420443, 
+		0.011996194566236, 0.011996194566236, 0.769207005420443, 
+		0.218796800013321, 0.101179597136408, 0.883962302273467, 
+		0.014858100590125, 0.014858100590125, 0.883962302273467, 
+		0.101179597136408, 0.020874755282586, 1.014347260005363, 
+		-0.035222015287949,-0.035222015287949, 1.014347260005363, 
+		0.020874755282586};
+	static IssmPDouble l318[]={
+		0.333333333333333, 0.493344808630921, 0.493344808630921, 
+		0.013310382738157, 0.469210594241957, 0.469210594241957, 
+		0.061578811516086, 0.436281395887006, 0.436281395887006, 
+		0.127437208225989, 0.394846170673416, 0.394846170673416, 
+		0.210307658653168, 0.249794568803157, 0.249794568803157, 
+		0.500410862393686, 0.161432193743843, 0.161432193743843, 
+		0.677135612512315, 0.076598227485371, 0.076598227485371, 
+		0.846803545029257, 0.024252439353450, 0.024252439353450, 
+		0.951495121293100, 0.043146367216965, 0.043146367216965, 
+		0.913707265566071, 0.632657968856636, 0.358911494940944, 
+		0.632657968856636, 0.358911494940944, 0.008430536202420, 
+		0.008430536202420, 0.574410971510855, 0.294402476751957, 
+		0.574410971510855, 0.294402476751957, 0.131186551737188, 
+		0.131186551737188, 0.624779046792512, 0.325017801641814, 
+		0.624779046792512, 0.325017801641814, 0.050203151565675, 
+		0.050203151565675, 0.748933176523037, 0.184737559666046, 
+		0.748933176523037, 0.184737559666046, 0.066329263810916, 
+		0.066329263810916, 0.769207005420443, 0.218796800013321, 
+		0.769207005420443, 0.218796800013321, 0.011996194566236, 
+		0.011996194566236, 0.883962302273467, 0.101179597136408, 
+		0.883962302273467, 0.101179597136408, 0.014858100590125, 
+		0.014858100590125, 1.014347260005363, 0.020874755282586, 
+		1.014347260005363, 0.020874755282586,-0.035222015287949, 
+		-0.035222015287949};
+	/*}}}*/
+	/*p=19, npoint=73  {{{*/
+
+	static IssmPDouble wgt19[]={
+		0.056995437856306, 0.017893352515055, 0.017893352515055, 
+		0.017893352515055, 0.038775849701151, 0.038775849701151, 
+		0.038775849701151, 0.052422467754193, 0.052422467754193, 
+		0.052422467754193, 0.052811905405354, 0.052811905405354, 
+		0.052811905405354, 0.041844983939388, 0.041844983939388, 
+		0.041844983939388, 0.027800807314648, 0.027800807314648, 
+		0.027800807314648, 0.014002903771278, 0.014002903771278, 
+		0.014002903771278, 0.003601560678933, 0.003601560678933, 
+		0.003601560678933, 0.006728804180578, 0.006728804180578, 
+		0.006728804180578, 0.006728804180578, 0.006728804180578, 
+		0.006728804180578, 0.044295745540949, 0.044295745540949, 
+		0.044295745540949, 0.044295745540949, 0.044295745540949, 
+		0.044295745540949, 0.015382176206141, 0.015382176206141, 
+		0.015382176206141, 0.015382176206141, 0.015382176206141, 
+		0.015382176206141, 0.027928534240338, 0.027928534240338, 
+		0.027928534240338, 0.027928534240338, 0.027928534240338, 
+		0.027928534240338, 0.004316169837400, 0.004316169837400, 
+		0.004316169837400, 0.004316169837400, 0.004316169837400, 
+		0.004316169837400, 0.031597525960379, 0.031597525960379, 
+		0.031597525960379, 0.031597525960379, 0.031597525960379, 
+		0.031597525960379, 0.017768353603780, 0.017768353603780, 
+		0.017768353603780, 0.017768353603780, 0.017768353603780, 
+		0.017768353603780, 0.006581669842530, 0.006581669842530, 
+		0.006581669842530, 0.006581669842530, 0.006581669842530, 
+		0.006581669842530};
+	static IssmPDouble l119[]={
+		0.333333333333333, 0.020780025853987, 0.489609987073006, 
+		0.489609987073006, 0.090926214604215, 0.454536892697893, 
+		0.454536892697893, 0.197166638701138, 0.401416680649431, 
+		0.401416680649431, 0.488896691193805, 0.255551654403098, 
+		0.255551654403098, 0.645844115695741, 0.177077942152130, 
+		0.177077942152130, 0.779877893544096, 0.110061053227952, 
+		0.110061053227952, 0.888942751496321, 0.055528624251840, 
+		0.055528624251840, 0.974756272445543, 0.012621863777229, 
+		0.012621863777229, 0.003611417848412, 0.003611417848412, 
+		0.395754787356943, 0.600633794794645, 0.395754787356943, 
+		0.600633794794645, 0.134466754530780, 0.134466754530780, 
+		0.307929983880436, 0.557603261588784, 0.307929983880436, 
+		0.557603261588784, 0.014446025776115, 0.014446025776115, 
+		0.264566948406520, 0.720987025817365, 0.264566948406520, 
+		0.720987025817365, 0.046933578838178, 0.046933578838178, 
+		0.358539352205951, 0.594527068955871, 0.358539352205951, 
+		0.594527068955871, 0.002861120350567, 0.002861120350567, 
+		0.157807405968595, 0.839331473680839, 0.157807405968595, 
+		0.839331473680839, 0.223861424097916, 0.223861424097916, 
+		0.075050596975911, 0.701087978926173, 0.075050596975911, 
+		0.701087978926173, 0.034647074816760, 0.034647074816760, 
+		0.142421601113383, 0.822931324069857, 0.142421601113383, 
+		0.822931324069857, 0.010161119296278, 0.010161119296278, 
+		0.065494628082938, 0.924344252620784, 0.065494628082938, 
+		0.924344252620784};
+	static IssmPDouble l219[]={
+		0.333333333333333, 0.489609987073006, 0.020780025853987, 
+		0.489609987073006, 0.454536892697893, 0.090926214604215, 
+		0.454536892697893, 0.401416680649431, 0.197166638701138, 
+		0.401416680649431, 0.255551654403098, 0.488896691193805, 
+		0.255551654403098, 0.177077942152130, 0.645844115695741, 
+		0.177077942152130, 0.110061053227952, 0.779877893544096, 
+		0.110061053227952, 0.055528624251840, 0.888942751496321, 
+		0.055528624251840, 0.012621863777229, 0.974756272445543, 
+		0.012621863777229, 0.395754787356943, 0.600633794794645, 
+		0.003611417848412, 0.003611417848412, 0.600633794794645, 
+		0.395754787356943, 0.307929983880436, 0.557603261588784, 
+		0.134466754530780, 0.134466754530780, 0.557603261588784, 
+		0.307929983880436, 0.264566948406520, 0.720987025817365, 
+		0.014446025776115, 0.014446025776115, 0.720987025817365, 
+		0.264566948406520, 0.358539352205951, 0.594527068955871, 
+		0.046933578838178, 0.046933578838178, 0.594527068955871, 
+		0.358539352205951, 0.157807405968595, 0.839331473680839, 
+		0.002861120350567, 0.002861120350567, 0.839331473680839, 
+		0.157807405968595, 0.075050596975911, 0.701087978926173, 
+		0.223861424097916, 0.223861424097916, 0.701087978926173, 
+		0.075050596975911, 0.142421601113383, 0.822931324069857, 
+		0.034647074816760, 0.034647074816760, 0.822931324069857, 
+		0.142421601113383, 0.065494628082938, 0.924344252620784, 
+		0.010161119296278, 0.010161119296278, 0.924344252620784, 
+		0.065494628082938};
+	static IssmPDouble l319[]={
+		0.333333333333333, 0.489609987073006, 0.489609987073006, 
+		0.020780025853987, 0.454536892697893, 0.454536892697893, 
+		0.090926214604215, 0.401416680649431, 0.401416680649431, 
+		0.197166638701138, 0.255551654403098, 0.255551654403098, 
+		0.488896691193805, 0.177077942152130, 0.177077942152130, 
+		0.645844115695741, 0.110061053227952, 0.110061053227952, 
+		0.779877893544096, 0.055528624251840, 0.055528624251840, 
+		0.888942751496321, 0.012621863777229, 0.012621863777229, 
+		0.974756272445543, 0.600633794794645, 0.395754787356943, 
+		0.600633794794645, 0.395754787356943, 0.003611417848412, 
+		0.003611417848412, 0.557603261588784, 0.307929983880436, 
+		0.557603261588784, 0.307929983880436, 0.134466754530780, 
+		0.134466754530780, 0.720987025817365, 0.264566948406520, 
+		0.720987025817365, 0.264566948406520, 0.014446025776115, 
+		0.014446025776115, 0.594527068955871, 0.358539352205951, 
+		0.594527068955871, 0.358539352205951, 0.046933578838178, 
+		0.046933578838178, 0.839331473680839, 0.157807405968595, 
+		0.839331473680839, 0.157807405968595, 0.002861120350567, 
+		0.002861120350567, 0.701087978926173, 0.075050596975911, 
+		0.701087978926173, 0.075050596975911, 0.223861424097916, 
+		0.223861424097916, 0.822931324069857, 0.142421601113383, 
+		0.822931324069857, 0.142421601113383, 0.034647074816760, 
+		0.034647074816760, 0.924344252620784, 0.065494628082938, 
+		0.924344252620784, 0.065494628082938, 0.010161119296278, 
+		0.010161119296278};
+	/*}}}*/
+	/*p=20, npoint=79 {{{*/
+	static IssmPDouble wgt20[]={
+		0.057256499746719, 0.001501721280705, 0.001501721280705, 
+		0.001501721280705, 0.020195803723819, 0.020195803723819, 
+		0.020195803723819, 0.039624016090841, 0.039624016090841, 
+		0.039624016090841, 0.052739185030045, 0.052739185030045, 
+		0.052739185030045, 0.053043868444611, 0.053043868444611, 
+		0.053043868444611, 0.042206713977986, 0.042206713977986, 
+		0.042206713977986, 0.027708365070095, 0.027708365070095, 
+		0.027708365070095, 0.013333849876622, 0.013333849876622, 
+		0.013333849876622,-0.001094760895106,-0.001094760895106, 
+		-0.001094760895106, 0.003033053580543, 0.003033053580543, 
+		0.003033053580543, 0.028519670065604, 0.028519670065604, 
+		0.028519670065604, 0.028519670065604, 0.028519670065604, 
+		0.028519670065604, 0.008381451951650, 0.008381451951650, 
+		0.008381451951650, 0.008381451951650, 0.008381451951650, 
+		0.008381451951650, 0.044695409202580, 0.044695409202580, 
+		0.044695409202580, 0.044695409202580, 0.044695409202580, 
+		0.044695409202580, 0.014672360101834, 0.014672360101834, 
+		0.014672360101834, 0.014672360101834, 0.014672360101834, 
+		0.014672360101834, 0.031791643800640, 0.031791643800640, 
+		0.031791643800640, 0.031791643800640, 0.031791643800640, 
+		0.031791643800640, 0.001220064691226, 0.001220064691226, 
+		0.001220064691226, 0.001220064691226, 0.001220064691226, 
+		0.001220064691226, 0.017515684095300, 0.017515684095300, 
+		0.017515684095300, 0.017515684095300, 0.017515684095300, 
+		0.017515684095300, 0.006190192638113, 0.006190192638113, 
+		0.006190192638113, 0.006190192638113, 0.006190192638113, 
+		0.006190192638113};
+	static IssmPDouble l120[]={
+		0.333333333333333,-0.001900928704400, 0.500950464352200, 
+		0.500950464352200, 0.023574084130543, 0.488212957934729, 
+		0.488212957934729, 0.089726636099435, 0.455136681950283, 
+		0.455136681950283, 0.196007481363421, 0.401996259318289, 
+		0.401996259318289, 0.488214180481157, 0.255892909759421, 
+		0.255892909759421, 0.647023488009788, 0.176488255995106, 
+		0.176488255995106, 0.791658289326483, 0.104170855336758, 
+		0.104170855336758, 0.893862072318140, 0.053068963840930, 
+		0.053068963840930, 0.916762569607942, 0.041618715196029, 
+		0.041618715196029, 0.976836157186356, 0.011581921406822, 
+		0.011581921406822, 0.048741583664839, 0.048741583664839, 
+		0.344855770229001, 0.606402646106160, 0.344855770229001, 
+		0.606402646106160, 0.006314115948605, 0.006314115948605, 
+		0.377843269594854, 0.615842614456541, 0.377843269594854, 
+		0.615842614456541, 0.134316520547348, 0.134316520547348, 
+		0.306635479062357, 0.559048000390295, 0.306635479062357, 
+		0.559048000390295, 0.013973893962392, 0.013973893962392, 
+		0.249419362774742, 0.736606743262866, 0.249419362774742, 
+		0.736606743262866, 0.075549132909764, 0.075549132909764, 
+		0.212775724802802, 0.711675142287434, 0.212775724802802, 
+		0.711675142287434,-0.008368153208227,-0.008368153208227, 
+		0.146965436053239, 0.861402717154987, 0.146965436053239, 
+		0.861402717154987, 0.026686063258714, 0.026686063258714, 
+		0.137726978828923, 0.835586957912363, 0.137726978828923, 
+		0.835586957912363, 0.010547719294141, 0.010547719294141, 
+		0.059696109149007, 0.929756171556853, 0.059696109149007, 
+		0.929756171556853};
+	static IssmPDouble l220[]={
+		0.333333333333333, 0.500950464352200,-0.001900928704400, 
+		0.500950464352200, 0.488212957934729, 0.023574084130543, 
+		0.488212957934729, 0.455136681950283, 0.089726636099435, 
+		0.455136681950283, 0.401996259318289, 0.196007481363421, 
+		0.401996259318289, 0.255892909759421, 0.488214180481157, 
+		0.255892909759421, 0.176488255995106, 0.647023488009788, 
+		0.176488255995106, 0.104170855336758, 0.791658289326483, 
+		0.104170855336758, 0.053068963840930, 0.893862072318140, 
+		0.053068963840930, 0.041618715196029, 0.916762569607942, 
+		0.041618715196029, 0.011581921406822, 0.976836157186356, 
+		0.011581921406822, 0.344855770229001, 0.606402646106160, 
+		0.048741583664839, 0.048741583664839, 0.606402646106160, 
+		0.344855770229001, 0.377843269594854, 0.615842614456541, 
+		0.006314115948605, 0.006314115948605, 0.615842614456541, 
+		0.377843269594854, 0.306635479062357, 0.559048000390295, 
+		0.134316520547348, 0.134316520547348, 0.559048000390295, 
+		0.306635479062357, 0.249419362774742, 0.736606743262866, 
+		0.013973893962392, 0.013973893962392, 0.736606743262866, 
+		0.249419362774742, 0.212775724802802, 0.711675142287434, 
+		0.075549132909764, 0.075549132909764, 0.711675142287434, 
+		0.212775724802802, 0.146965436053239, 0.861402717154987, 
+		-0.008368153208227,-0.008368153208227, 0.861402717154987, 
+		0.146965436053239, 0.137726978828923, 0.835586957912363, 
+		0.026686063258714, 0.026686063258714, 0.835586957912363, 
+		0.137726978828923, 0.059696109149007, 0.929756171556853, 
+		0.010547719294141, 0.010547719294141, 0.929756171556853, 
+		0.059696109149007};
+	static IssmPDouble l320[]={
+		0.333333333333333, 0.500950464352200, 0.500950464352200, 
+		-0.001900928704400, 0.488212957934729, 0.488212957934729, 
+		0.023574084130543, 0.455136681950283, 0.455136681950283, 
+		0.089726636099435, 0.401996259318289, 0.401996259318289, 
+		0.196007481363421, 0.255892909759421, 0.255892909759421, 
+		0.488214180481157, 0.176488255995106, 0.176488255995106, 
+		0.647023488009788, 0.104170855336758, 0.104170855336758, 
+		0.791658289326483, 0.053068963840930, 0.053068963840930, 
+		0.893862072318140, 0.041618715196029, 0.041618715196029, 
+		0.916762569607942, 0.011581921406822, 0.011581921406822, 
+		0.976836157186356, 0.606402646106160, 0.344855770229001, 
+		0.606402646106160, 0.344855770229001, 0.048741583664839, 
+		0.048741583664839, 0.615842614456541, 0.377843269594854, 
+		0.615842614456541, 0.377843269594854, 0.006314115948605, 
+		0.006314115948605, 0.559048000390295, 0.306635479062357, 
+		0.559048000390295, 0.306635479062357, 0.134316520547348, 
+		0.134316520547348, 0.736606743262866, 0.249419362774742, 
+		0.736606743262866, 0.249419362774742, 0.013973893962392, 
+		0.013973893962392, 0.711675142287434, 0.212775724802802, 
+		0.711675142287434, 0.212775724802802, 0.075549132909764, 
+		0.075549132909764, 0.861402717154987, 0.146965436053239, 
+		0.861402717154987, 0.146965436053239,-0.008368153208227, 
+		-0.008368153208227, 0.835586957912363, 0.137726978828923, 
+		0.835586957912363, 0.137726978828923, 0.026686063258714, 
+		0.026686063258714, 0.929756171556853, 0.059696109149007, 
+		0.929756171556853, 0.059696109149007, 0.010547719294141, 
+		0.010547719294141};
+	/*}}}*/
+
+	static IssmPDouble* wgtp[MAX_TRIA_SYM_ORD]={
+		wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 ,
+		wgt6 ,wgt7 ,wgt8 ,wgt9 ,wgt10,
+		wgt11,wgt12,wgt13,wgt14,wgt15,
+		wgt16,wgt17,wgt18,wgt19,wgt20};
+	static IssmPDouble* l1p [MAX_TRIA_SYM_ORD]={
+		l11  ,l12  ,l13  ,l14  ,l15  ,
+		l16  ,l17  ,l18  ,l19  ,l110 ,
+		l111 ,l112 ,l113 ,l114 ,l115 ,
+		l116 ,l117 ,l118 ,l119 ,l120 };
+	static IssmPDouble* l2p [MAX_TRIA_SYM_ORD]={
+		l21  ,l22  ,l23  ,l24  ,l25  ,
+		l26  ,l27  ,l28  ,l29  ,l210 ,
+		l211 ,l212 ,l213 ,l214 ,l215 ,
+		l216 ,l217 ,l218 ,l219 ,l220 };
+	static IssmPDouble* l3p [MAX_TRIA_SYM_ORD]={
+		l31  ,l32  ,l33  ,l34  ,l35  ,
+		l36  ,l37  ,l38  ,l39  ,l310 ,
+		l311 ,l312 ,l313 ,l314 ,l315 ,
+		l316 ,l317 ,l318 ,l319 ,l320 };
+
+	static int np[MAX_TRIA_SYM_ORD]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble),
+		sizeof(wgt5 )/sizeof(IssmPDouble),
+		sizeof(wgt6 )/sizeof(IssmPDouble),
+		sizeof(wgt7 )/sizeof(IssmPDouble),
+		sizeof(wgt8 )/sizeof(IssmPDouble),
+		sizeof(wgt9 )/sizeof(IssmPDouble),
+		sizeof(wgt10)/sizeof(IssmPDouble),
+		sizeof(wgt11)/sizeof(IssmPDouble),
+		sizeof(wgt12)/sizeof(IssmPDouble),
+		sizeof(wgt13)/sizeof(IssmPDouble),
+		sizeof(wgt14)/sizeof(IssmPDouble),
+		sizeof(wgt15)/sizeof(IssmPDouble),
+		sizeof(wgt16)/sizeof(IssmPDouble),
+		sizeof(wgt17)/sizeof(IssmPDouble),
+		sizeof(wgt18)/sizeof(IssmPDouble),
+		sizeof(wgt19)/sizeof(IssmPDouble),
+		sizeof(wgt20)/sizeof(IssmPDouble)};
+
+	//	_printf0_("GaussLegendreTria: iord=" << iord << "\n");
+
+	/*  check to see if Gauss points need to be calculated  */
+	if (iord <= MAX_TRIA_SYM_ORD) {
+
+		/*  copy the points from the static arrays (noting that the pointers
+			 could be returned directly, but then the calling function would
+			 have to know to not free them)  */
+
+		*pngaus=np[iord-1];
+
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
+
+		for (i=0; i<*pngaus; i++) {
+			(*pl1 )[i]=l1p [iord-1][i];
+			(*pl2 )[i]=l2p [iord-1][i];
+			(*pl3 )[i]=l3p [iord-1][i];
+			(*pwgt)[i]=wgtp[iord-1][i];
+		}
+	}
+	else {
+
+		/*  calculate the Gauss points from the collapsed quadrilateral  */
+		nigaus =iord/2+1;
+		*pngaus=nigaus*nigaus;
+
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
+
+		/*  get the gauss points in each direction  */
+		GaussLegendreLinear(&xgaus, &xwgt, nigaus);
+
+		egaus=xgaus;
+		ewgt =xwgt;
+
+		/*  collapse the gauss points into the triangle and transform into
+			 area coordinates  */
+		ipt=0;
+		for (j=0; j<nigaus; j++) {
+			for (i=0; i<nigaus; i++) {
+				xi        =      1./2.*(1.-egaus[j])*xgaus[i];
+				eta       =SQRT3/2.*(1.+egaus[j]);
+				(*pwgt)[ipt]=xwgt[i]*ewgt[j]*(SQRT3/4.*(1.-egaus[j]));
+
+				(*pl1 )[ipt]=(1.-xi-eta/SQRT3)/2.;
+				(*pl2 )[ipt]=(1.+xi-eta/SQRT3)/2.;
+				(*pl3 )[ipt]=       eta/SQRT3;
+
+				ipt++;
+			}
+		}
+		xDelete<IssmPDouble>(xwgt );
+		xDelete<IssmPDouble>(xgaus);
+	}
+
+	//	_printf0_("GaussLegendreTria - ngaus=" << *pngaus << "\n");
+	//	for (i=0; i<*pngaus; i++)
+	//		_printf0_("i=" << i << ": l1gaus=" << (*pl1 )[i] << ",l2gaus=" << (*pl2 )[i] << ",l3gaus=" << (*pl3 )[i]<< ",wgt=" << (*pwgt)[i]<< "\n\n");
+
+	return;
+}/*}}}*/
+void GaussLegendreTetra( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pl4, IssmDouble** pwgt, int iord ) {/*{{{*/
+	/* Gauss quadrature points for the tetrahedron.
+
+		p=2-3 points from Y. Jinyun, "Symmetric Gaussian Quadrature
+		Formulae for Tetrahedronal Regions", Computer Methods in Applied
+		Mechanics and Engineering, Vol. 43, pp. 349-353 (1984).
+
+		p=4-6 points from P. Keast, "Moderate-Degree Tetrahedral
+		Quadrature Formulas", Computer Methods in Applied Mechanics and
+		Engineering, Vol. 55, pp. 339-348 (1986).*/
+
+	/*Intermediaries*/
+	int i,j,k,ipt,nigaus;
+	IssmPDouble xi,eta,zeta;
+	IssmPDouble *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt,*zgaus,*zwgt;
+
+	/*Hardcoded Gauss points definition*/
+	/*p= 1, npoint= 1  {{{*/
+	static IssmPDouble wgt1[]={
+		1.000000000000000};
+	static IssmPDouble l11[]={
+		0.250000000000000};
+	static IssmPDouble l21[]={
+		0.250000000000000};
+	static IssmPDouble l31[]={
+		0.250000000000000};
+	static IssmPDouble l41[]={
+		0.250000000000000};
+	/*}}}*/
+	/*p= 2, npoint= 4  {{{*/
+
+	static IssmPDouble wgt2[]={
+		0.250000000000000, 0.250000000000000, 0.250000000000000,
+		0.250000000000000};
+	static IssmPDouble l12[]={
+		0.585410196624969, 0.138196601125011, 0.138196601125011,
+		0.138196601125011};
+	static IssmPDouble l22[]={
+		0.138196601125011, 0.585410196624969, 0.138196601125011,
+		0.138196601125011};
+	static IssmPDouble l32[]={
+		0.138196601125011, 0.138196601125011, 0.585410196624969,
+		0.138196601125011};
+	static IssmPDouble l42[]={
+		0.138196601125011, 0.138196601125011, 0.138196601125011,
+		0.585410196624969};
+	/*}}}*/
+	/*p= 3, npoint= 5  {{{*/
+	static IssmPDouble wgt3[]={
+		-0.800000000000000, 0.450000000000000, 0.450000000000000, 
+		0.450000000000000, 0.450000000000000};
+	static IssmPDouble l13[]={
+		0.250000000000000, 0.500000000000000, 0.166666666666667, 
+		0.166666666666667, 0.166666666666667};
+	static IssmPDouble l23[]={
+		0.250000000000000, 0.166666666666667, 0.500000000000000, 
+		0.166666666666667, 0.166666666666667};
+	static IssmPDouble l33[]={
+		0.250000000000000, 0.166666666666667, 0.166666666666667, 
+		0.500000000000000, 0.166666666666667};
+	static IssmPDouble l43[]={
+		0.250000000000000, 0.166666666666667, 0.166666666666667, 
+		0.166666666666667, 0.500000000000000};
+	/*}}}*/
+	/*p= 4, npoint=11  {{{*/
+
+	static IssmPDouble wgt4[]={
+		-0.013155555555556, 0.007622222222222, 0.007622222222222, 
+		0.007622222222222, 0.007622222222222, 0.024888888888889,
+		0.024888888888889, 0.024888888888889, 0.024888888888889, 
+		0.024888888888889, 0.024888888888889};
+	static IssmPDouble l14[]={
+		0.250000000000000, 0.785714285714286, 0.071428571428571, 
+		0.071428571428571, 0.071428571428571, 0.399403576166799,
+		0.399403576166799, 0.399403576166799, 0.100596423833201, 
+		0.100596423833201, 0.100596423833201};
+	static IssmPDouble l24[]={
+		0.250000000000000, 0.071428571428571, 0.785714285714286, 
+		0.071428571428571, 0.071428571428571, 0.399403576166799,
+		0.100596423833201, 0.100596423833201, 0.399403576166799, 
+		0.399403576166799, 0.100596423833201};
+	static IssmPDouble l34[]={
+		0.250000000000000, 0.071428571428571, 0.071428571428571, 
+		0.785714285714286, 0.071428571428571, 0.100596423833201, 
+		0.399403576166799, 0.100596423833201, 0.399403576166799,
+		0.100596423833201, 0.399403576166799};
+	static IssmPDouble l44[]={
+		0.250000000000000, 0.071428571428571, 0.071428571428571, 
+		0.071428571428571, 0.785714285714286, 0.100596423833201, 
+		0.100596423833201, 0.399403576166799, 0.100596423833201,
+		0.399403576166799, 0.399403576166799};
+	/*}}}*/
+	/*p= 5, npoint=15  {{{*/
+
+	static IssmPDouble wgt5[]={
+		0.030283678097089, 0.006026785714286, 0.006026785714286, 
+		0.006026785714286, 0.006026785714286, 0.011645249086029, 
+		0.011645249086029, 0.011645249086029, 0.011645249086029,
+		0.010949141561386, 0.010949141561386, 0.010949141561386,
+		0.010949141561386, 0.010949141561386, 0.010949141561386};
+	static IssmPDouble l15[]={
+		0.250000000000000, 0.000000000000000, 0.333333333333333, 
+		0.333333333333333, 0.333333333333333, 0.727272727272727, 
+		0.090909090909091, 0.090909090909091, 0.090909090909091, 
+		0.066550153573664, 0.066550153573664, 0.066550153573664, 
+		0.433449846426336, 0.433449846426336, 0.433449846426336};
+	static IssmPDouble l25[]={
+		0.250000000000000, 0.333333333333333, 0.000000000000000, 
+		0.333333333333333, 0.333333333333333, 0.090909090909091, 
+		0.727272727272727, 0.090909090909091, 0.090909090909091, 
+		0.066550153573664, 0.433449846426336, 0.433449846426336, 
+		0.066550153573664, 0.066550153573664, 0.433449846426336};
+	static IssmPDouble l35[]={
+		0.250000000000000, 0.333333333333333, 0.333333333333333, 
+		0.000000000000000, 0.333333333333333, 0.090909090909091, 
+		0.090909090909091, 0.727272727272727, 0.090909090909091, 
+		0.433449846426336, 0.066550153573664, 0.433449846426336, 
+		0.066550153573664, 0.433449846426336, 0.066550153573664};
+	static IssmPDouble l45[]={
+		0.250000000000000, 0.333333333333333, 0.333333333333333, 
+		0.333333333333333, 0.000000000000000, 0.090909090909091, 
+		0.090909090909091, 0.090909090909091, 0.727272727272727, 
+		0.433449846426336, 0.433449846426336, 0.066550153573664, 
+		0.433449846426336, 0.066550153573664, 0.066550153573664};
+	/*}}}*/
+	/*p= 6, npoint=24  {{{*/
+
+	static IssmPDouble wgt6[]={
+		0.006653791709695, 0.006653791709695, 0.006653791709695, 
+		0.006653791709695, 0.001679535175887, 0.001679535175887, 
+		0.001679535175887, 0.001679535175887, 0.009226196923942, 
+		0.009226196923942, 0.009226196923942, 0.009226196923942,
+		0.008035714285714, 0.008035714285714, 0.008035714285714, 
+		0.008035714285714, 0.008035714285714, 0.008035714285714, 
+		0.008035714285714, 0.008035714285714, 0.008035714285714, 
+		0.008035714285714, 0.008035714285714, 0.008035714285714};
+	static IssmPDouble l16[]={
+		0.356191386222545, 0.214602871259152, 0.214602871259152, 
+		0.214602871259152, 0.877978124396166, 0.040673958534611, 
+		0.040673958534611, 0.040673958534611, 0.032986329573173, 
+		0.322337890142276, 0.322337890142276, 0.322337890142276,
+
+		0.063661001875018, 0.063661001875018, 0.063661001875018, 
+		0.063661001875018, 0.063661001875018, 0.063661001875018, 
+		0.269672331458316, 0.603005664791649, 0.269672331458316, 
+		0.603005664791649, 0.269672331458316, 0.603005664791649};
+	static IssmPDouble l26[]={
+		0.214602871259152, 0.356191386222545, 0.214602871259152, 
+		0.214602871259152, 0.040673958534611, 0.877978124396166, 
+		0.040673958534611, 0.040673958534611, 0.322337890142276, 
+		0.032986329573173, 0.322337890142276, 0.322337890142276,
+
+		0.063661001875018, 0.063661001875018, 0.269672331458316, 
+		0.603005664791649, 0.269672331458316, 0.603005664791649, 
+		0.063661001875018, 0.063661001875018, 0.063661001875018, 
+		0.063661001875018, 0.603005664791649, 0.269672331458316};
+	static IssmPDouble l36[]={
+		0.214602871259152, 0.214602871259152, 0.356191386222545, 
+		0.214602871259152, 0.040673958534611, 0.040673958534611, 
+		0.877978124396166, 0.040673958534611, 0.322337890142276, 
+		0.322337890142276, 0.032986329573173, 0.322337890142276,
+
+		0.269672331458316, 0.603005664791649, 0.063661001875018, 
+		0.063661001875018, 0.603005664791649, 0.269672331458316, 
+		0.063661001875018, 0.063661001875018, 0.603005664791649, 
+		0.269672331458316, 0.063661001875018, 0.063661001875018};
+	static IssmPDouble l46[]={
+		0.214602871259152, 0.214602871259152, 0.214602871259152, 
+		0.356191386222545, 0.040673958534611, 0.040673958534611, 
+		0.040673958534611, 0.877978124396166, 0.322337890142276, 
+		0.322337890142276, 0.322337890142276, 0.032986329573173,
+
+		0.603005664791649, 0.269672331458316, 0.603005664791649, 
+		0.269672331458316, 0.063661001875018, 0.063661001875018, 
+		0.603005664791649, 0.269672331458316, 0.063661001875018, 
+		0.063661001875018, 0.063661001875018, 0.063661001875018};
+	/*}}}*/
+
+	static IssmPDouble* wgtp[MAX_TETRA_SYM_ORD]={wgt1,wgt2,wgt3,wgt4,wgt5,wgt6};
+	static IssmPDouble* l1p [MAX_TETRA_SYM_ORD]={l11 ,l12 ,l13 ,l14 ,l15 ,l16 };
+	static IssmPDouble* l2p [MAX_TETRA_SYM_ORD]={l21 ,l22 ,l23 ,l24 ,l25 ,l26 };
+	static IssmPDouble* l3p [MAX_TETRA_SYM_ORD]={l31 ,l32 ,l33 ,l34 ,l35 ,l36 };
+	static IssmPDouble* l4p [MAX_TETRA_SYM_ORD]={l41 ,l42 ,l43 ,l44 ,l45 ,l46 };
+
+	static int np[MAX_TETRA_SYM_ORD]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble),
+		sizeof(wgt5 )/sizeof(IssmPDouble),
+		sizeof(wgt6 )/sizeof(IssmPDouble)};
+
+	//	_printf0_("GaussLegendreTetra: iord=" << iord << "\n");
+
+	/*  check to see if Gauss points need to be calculated  */
+	if (iord <= MAX_TETRA_SYM_ORD) {
+
+		/*  copy the points from the static arrays (noting that the pointers
+			 could be returned directly, but then the calling function would
+			 have to know to not free them), and multiply the weights by the
+			 volume of the parametric tetrahedron  */
+
+		*pngaus=np[iord-1];
+
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pl4  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
+
+		for (i=0; i<*pngaus; i++) {
+			(*pl1 )[i]=l1p [iord-1][i];
+			(*pl2 )[i]=l2p [iord-1][i];
+			(*pl3 )[i]=l3p [iord-1][i];
+			(*pl4 )[i]=l4p [iord-1][i];
+			(*pwgt)[i]=wgtp[iord-1][i];
+		}
+	}
+	else {
+
+		/*  calculate the Gauss points from the collapsed hexahedron  */
+		nigaus =iord/2+1;
+		*pngaus=nigaus*nigaus*nigaus;
+
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pl4  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
+
+		/*  get the gauss points in each direction  */
+		GaussLegendreLinear(&xgaus, &xwgt, nigaus);
+
+		egaus=xgaus;
+		ewgt =xwgt;
+		zgaus=xgaus;
+		zwgt =xwgt;
+
+		/*  collapse the gauss points into the tetrahedron and transform into
+			 volume coordinates  */
+		ipt=0;
+		for (k=0; k<nigaus; k++) {
+			for (j=0; j<nigaus; j++) {
+				for (i=0; i<nigaus; i++) {
+					xi        =1./4.*(1.-egaus[j])*(1.-zgaus[k])*xgaus[i];
+					eta       =1./4./SQRT3
+					  *(5.+3.*egaus[j]-zgaus[k]-3.*egaus[j]*zgaus[k]);
+					zeta      =sqrt(2./3.)*(1.+zgaus[k]);
+					(*pwgt)[ipt]=xwgt[i]*ewgt[j]*zwgt[k]*(SQRT2/16.*(1.-egaus[j])*pow(1.-zgaus[k],2));
+
+					(*pl1 )[ipt]=(1.-xi-eta/SQRT3-zeta/sqrt(6.))/2.;
+					(*pl2 )[ipt]=(1.+xi-eta/SQRT3-zeta/sqrt(6.))/2.;
+					(*pl3 )[ipt]=(      eta         -zeta/sqrt(8.))/SQRT3;
+					(*pl4 )[ipt]=(                   zeta/sqrt(8.))*SQRT3;
+
+					ipt++;
+				}
+			}
+		}
+		xDelete<IssmPDouble>(xwgt );
+		xDelete<IssmPDouble>(xgaus);
+	}
+}/*}}}*/
+void GaussLobatto( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus ) {/*{{{*/
+	/*Gauss-Lobatto quadrature points.
+
+	  The recurrence coefficients for Legendre polynomials on (-1,1)
+	  are defined (from the ORTHPOL subroutine RECUR with ipoly=1) as:
+
+	  alpha(i)=0.
+	  beta (i)=1./(4.-1./(i-1)^2))
+
+	  and then modified for the Gauss-Lobatto quadrature rule on (-1,1)
+	  (from the ORTHPOL subroutine LOB).
+
+	  For degree p, the required number of Gauss-Lobatto points is
+	  n>=(p+1)/2+1 (one more than Gauss-Legendre).*/
+
+	int i;
+	IssmPDouble *alpha,*beta;
+	IssmPDouble left=-1.,right= 1.;
+	IssmPDouble p0l=0.,p0r=0.,p1l=1.,p1r=1.,pm1l,pm1r,det;
+
+	/*p= 1, npoint= 1 (Gauss-Legendre)*/
+	static IssmPDouble wgt1[]={2.000000000000000};
+	static IssmPDouble xi1[]={0.000000000000000};
+
+	/*p= 1, npoint= 2*/
+	static IssmPDouble wgt2[]={1.000000000000000, 1.000000000000000};
+	static IssmPDouble xi2[]={-1.000000000000000, 1.000000000000000};
+
+	/*p= 3, npoint= 3*/
+	static IssmPDouble wgt3[]={0.333333333333333, 1.333333333333333, 0.333333333333333};
+	static IssmPDouble xi3[]={-1.000000000000000, 0.000000000000000, 1.000000000000000};
+
+	/*p= 5, npoint= 4*/
+	static IssmPDouble wgt4[]={0.166666666666667, 0.833333333333333, 0.833333333333333, 0.166666666666667};
+	static IssmPDouble xi4[]={-1.000000000000000,-0.447213595499958, 0.447213595499958, 1.000000000000000};
+
+	/*p= 7, npoint= 5*/
+	static IssmPDouble wgt5[]={0.100000000000000, 0.544444444444444, 0.711111111111111, 0.544444444444444, 0.100000000000000};
+	static IssmPDouble xi5[]={-1.000000000000000,-0.654653670707977, 0.000000000000000, 0.654653670707977, 1.000000000000000};
+
+	static IssmPDouble* wgtp[MAX_LINE_GLOB_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 };
+	static IssmPDouble* xip [MAX_LINE_GLOB_PTS]={xi1  ,xi2  ,xi3  ,xi4  ,xi5  };
+
+	*pxgaus =xNew<IssmPDouble>(ngaus);
+	*pxwgt  =xNew<IssmPDouble>(ngaus);
+
+	/*  check to see if Gauss points need to be calculated  */
+	if (ngaus <= MAX_LINE_GLOB_PTS) {
+
+		/*  copy the points from the static arrays (noting that the pointers
+			 could be returned directly, but then the calling function would
+			 have to know to not free them)  */
+		for (i=0; i<ngaus; i++) {
+			(*pxgaus)[i]=xip [ngaus-1][i];
+			(*pxwgt )[i]=wgtp[ngaus-1][i];
+		}
+	}
+	else {
+
+		/*  calculate the Gauss points using recurrence relations  */
+		alpha=xNew<IssmPDouble>(ngaus);
+		beta =xNew<IssmPDouble>(ngaus);
+
+		/*  calculate the Legendre recurrence coefficients  */
+		alpha[0]=0.;
+		beta [0]=2.;
+
+		for (i=1; i<ngaus; i++) {
+			alpha[i]=0.;
+			beta [i]=1./(4.-1./(i*i));
+		}
+
+		/*  calculate the Gauss-Lobatto quadrature formula  */
+		for (i=0; i<ngaus-1; i++) {
+			pm1l=p0l;
+			p0l=p1l;
+			pm1r=p0r;
+			p0r=p1r;
+			p1l=(left -alpha[i])*p0l-beta[i]*pm1l;
+			p1r=(right-alpha[i])*p0r-beta[i]*pm1r;
+		}
+
+		/*  Normalize system to prevent underflow:
+			 [ p1l p0l ]{ a } = {left *p1l}
+			 [ p1r p0r ]{ b }   {right*p1r}
+			 dividing by p1l in the first equation and p1r in the second.  */
+
+		//		det=p1l*p0r-p1r*p0l;
+		det=p0r/p1r-p0l/p1l;
+		//		alpha[ngaus-1]=(left*p1l*p0r-right*p1r*p0l)/det;
+		//		beta [ngaus-1]=(right-left)*p1l*p1r/det;
+		alpha[ngaus-1]=(left *(p0r/p1r)-right*(p0l/p1l))/det;
+		beta [ngaus-1]=(right          -left           )/det;
+
+		/*  calculate the Gauss points  */
+		GaussRecur(*pxgaus, *pxwgt, ngaus, alpha, beta );
+		xDelete<IssmPDouble>(beta );
+		xDelete<IssmPDouble>(alpha);
+	}
+
+}/*}}}*/
+void GaussRecur( IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta ) {/*{{{*/
+	/*Gauss quadrature points from recursion coefficients.
+	 *
+	 *The routine uses the algorithm from the ORTHPOL routine GAUSS, which
+	 *finds the eigenvalues of a tridiagonal matrix.*/
+
+	/*Intermediaries*/
+	int i,j,k,l,m,ii,mml,iter;
+	IssmPDouble p,g,r,s,c,f,b;
+	IssmPDouble* work;
+
+	if (n==1){
+		zero[0]  =alpha[0];
+		weight[0]=beta[0];
+		return;
+	}
+
+	work=xNew<IssmPDouble>(n);
+
+	zero[0]  =alpha[0];
+	weight[0]=1.;
+	work[n-1]=0.;
+	for (i=1; i<=n-1; i++){
+		zero[i]=alpha[i];
+		work[i-1]=sqrt(beta[i]);
+		weight[i]=0;
+	}
+
+	for (l=0; l<=n-1; l++){
+		iter=0;
+		do {
+
+			/*  Look for a small subdiagonal element.  */
+			for (m=l; m<=n-1; m++) {
+				if (m == n-1) break;
+				if (fabs(work[m])
+							<= DBL_EPSILON*(fabs(zero[m])+fabs(zero[m+1])))
+				 break;
+			}
+			p=zero[l];
+			if (m==l) break;
+			++iter;
+
+			/*  Form shift.  */
+			g=(zero[l+1]-p)/(2.*work[l]);
+			r=sqrt(g*g+1.);
+			//			g=zero[m]-p+work[l]/(g+FortranSign(r,g));
+			g=zero[m]-p+work[l]/(g+(g>=0 ? fabs(r) : -fabs(r)));
+			s=1.;
+			c=1.;
+			p=0.;
+			mml=m-l;
+
+			/*  For i=m-1 step -1 until l do ...  */
+			for (ii=1; ii<=mml; ii++) {
+				i=m-ii;
+				f=s*work[i];
+				b=c*work[i];
+				if (fabs(f) >= fabs(g)) {
+					c=g/f;
+					r=sqrt(c*c+1.);
+					work[i+1]=f*r;
+					s=1./r;
+					c*=s;
+				}
+				else {
+					s=f/g;
+					r=sqrt(s*s+1.);
+					work[i+1]=g*r;
+					c=1./r;
+					s*=c;
+				}
+				g=zero[i+1]-p;
+				r=(zero[i]-g)*s+2.*c*b;
+				p=s*r;
+				zero[i+1]=g+p;
+				g=c*r-b;
+
+				/*  Form first component of vector.  */
+				f=weight[i+1];
+				weight[i+1]=s*weight[i]+c*f;
+				weight[i  ]=c*weight[i]-s*f;
+			}
+			zero[l]-=p;
+			work[l]=g;
+			work[m]=0.;
+		} while (iter < MAX_GAUS_ITER);
+		if (iter >= MAX_GAUS_ITER) {
+			xDelete<IssmPDouble>(work);
+			_error_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
+		}
+	}
+
+	/*  Order eigenvalues and eigenvectors.  */
+	for (i=0;i<n-1;i++) {
+		k=i;
+		p=zero[i];
+		for (j=i+1;j<n;j++){
+			if (zero[j] < p){
+				k=j;
+				p=zero[j];
+			}
+		}
+		if (k > i){
+			p=zero[i];
+			zero[i]=zero[k];
+			zero[k]=p;
+			p=weight[i];
+			weight[i]=weight[k];
+			weight[k]=p;
+		}
+	}
+	for (i=0;i<n;i++){
+		weight[i]=beta[0]*weight[i]*weight[i];
+	}
+
+	/*Cleanup*/
+	xDelete<IssmPDouble>(work);
+
+}/*}}}*/
+
+/*Element Gauss points TO BE REMOVED*/
+void gaussQuad( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus ) {/*{{{*/
+	/*Gauss quadrature points for the quadrilaterial.*/
+
+	/*get the gauss points using the product of two line rules  */
+	GaussLegendreLinear(pxgaus, pxwgt, nigaus);
+	GaussLegendreLinear(pegaus, pewgt, njgaus);
+}/*}}}*/
+void gaussHexa( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus ) {/*{{{*/
+	/*Gauss quadrature points for the hexahedron.*/
+
+	/*  get the gauss points using the product of three line rules  */
+	GaussLegendreLinear(pxgaus, pxwgt, nigaus);
+	GaussLegendreLinear(pegaus, pewgt, njgaus);
+	GaussLegendreLinear(pzgaus, pzwgt, nkgaus);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/GaussPoints.h	(revision 18231)
@@ -0,0 +1,23 @@
+/*!\file:  GaussPoints.h
+ * \brief
+ */ 
+
+#include "../../shared/Numerics/types.h"
+#ifndef _GAUSSPOINTS_H
+#define _GAUSSPOINTS_H
+
+#define MAX_LINE_GAUS_PTS    7
+void GaussLegendreLinear(IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus);
+#define MAX_TRIA_SYM_ORD    20
+void GaussLegendreTria(int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord);
+#define MAX_TETRA_SYM_ORD    6
+void GaussLegendreTetra(int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pl4, IssmDouble** pwgt, int iord);
+#define MAX_LINE_GLOB_PTS    5
+void GaussLobatto(IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus);
+#define MAX_GAUS_ITER   30
+void GaussRecur(IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta);
+
+void gaussQuad(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus);
+void gaussHexa(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/NewtonSolveDnorm.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/NewtonSolveDnorm.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/NewtonSolveDnorm.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+#include <math.h>
+#include "./types.h"
+#include "../Exceptions/exceptions.h"
+
+int NewtonSolveDnorm(IssmDouble* pdnorm,IssmDouble c1,IssmDouble c2,IssmDouble c3,IssmDouble n,IssmDouble dnorm){
+	/* solve the following equation using Newton-Raphson
+	 *
+	 *   c1*x^(s-1) + c2*x = c3
+	 *
+	 *   s = (1+n)/n
+	 *
+	 *   we solve y = 10^x:
+	 */
+
+	/*trivial solution*/
+	if(c3==0.){
+		*pdnorm = 0.;
+		return 0;
+	}
+
+	/*Intermediaries*/
+	int        counter = 0;
+	IssmDouble s = (1.+n)/n;
+	IssmDouble y2;
+	IssmDouble threshold = 1.e-12;
+
+	/*Initial guess*/
+	_assert_(dnorm>0.); 
+	IssmDouble y1 = log10(dnorm);
+
+	while(true){
+
+		/*Newton step*/
+		y2 = y1 - (c1*pow(pow(10.,y1),s-1.) + c2*pow(10.,y1) - c3)/((s-1)*c1*log(10.)*pow(pow(10.,y1),s-1.) + c2*log(10.)*pow(10.,y1));
+
+		if( fabs(y2-y1)/(fabs(y2))<threshold ){
+			break;
+		}
+		else{
+			y1=y2;
+			counter++;
+		}
+
+		if(counter>50) break;
+	}
+
+	/*Avoid extremely large values that indicate non convergence*/
+	if(y2>50.) y2 = 50;
+
+	/*Assign output pointer*/
+	*pdnorm = pow(10.,y2);
+	return 0;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/OptPars.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/OptPars.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/OptPars.h	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file:  OptPars.h
+ * \brief place holder for optimization parameters
+ */ 
+
+#ifndef _OPTPARS_H_
+#define _OPTPARS_H_
+
+#include "./types.h"
+
+struct OptPars{
+
+	IssmDouble  xmin;
+	IssmDouble  xmax;
+	IssmDouble *cm_jump;
+	int* maxiter;
+	int  nsteps;
+	int  nsize;
+
+};
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/README	(revision 18231)
@@ -0,0 +1,9 @@
+
+DO NOT MODIFY the following files:
+- Verbosity.cpp
+- src/m/shared/Verb*.m
+all these files are automatically synchronized with Verbosity.h
+
+TO ADD A VERBOSITY LEVEL:
+add the corresponding line to Verbosity.h
+and execute synchronizing script.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Synchronize.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Synchronize.sh	(revision 18231)
@@ -0,0 +1,156 @@
+#!/bin/bash
+#Synchronize Verbosity
+#first remove existing files
+rm $ISSM_DIR/src/m/classes/Verb*.m
+
+echo "Synchronizing Verbosity levels..."
+
+#Get all lines of Verbosity.cpp
+cat Verbosity.h |  grep "bool Verbose" | awk '{print $2}' | sed -e "s/(/ /" | awk '{print $1}' | awk '{ printf "%s %s\n", NR, $0 }' >temp
+#Build header of Verbosity.cpp {{{
+cat <<END > Verbosity.cpp
+/*
+* \file Verbosity.cpp:
+* \brief: Manage verbosity levels
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+/*include*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Verbosity.h"
+#include "../Exceptions/exceptions.h"
+/*}}}*/
+
+/*Verbosityt levels*/
+END
+#}}}
+
+#get number of lines in temp
+NUMBEROFLINES=$(wc -l temp | awk '{printf("%s",$1);}');
+
+# go through the lines of temp
+for (( i=1 ; i<=$NUMBEROFLINES ; i++ )); do
+
+	#Get name of the line i
+	FILENAME=$(cat temp | grep "^[ ]*$i " | awk '{printf("%s",$2);}');
+	LEVELNAME=$(echo $FILENAME | sed -e "s/Verbose//g");
+
+	let POWER=$i-1
+	let BINARY=2**$POWER
+
+	echo "$FILENAME -> 2^$POWER = $BINARY"
+
+	#Add case to verbose.m FIELDS{{{
+	if [ $i -eq 1 ]; then cat <<END >> FIELDS
+		%BEGINFIELDS
+END
+fi
+	cat <<END >> FIELDS
+		$(echo $LEVELNAME | awk {'print tolower($1)'})=false;
+END
+	if [ $i -eq $NUMBEROFLINES ]; then cat <<END >> FIELDS
+		%ENDFIELDS
+END
+fi
+#}}}
+	#Add case to verbose.m VERB2BIN{{{
+	if [ $i -eq 1 ]; then cat <<END >> VERB2BIN
+		%BEGINVERB2BIN
+		binary=0;
+END
+fi
+	cat <<END >> VERB2BIN
+		if (verbose.$(echo $LEVELNAME | awk {'print tolower($1)'})), binary=bitor(binary,$BINARY); end
+END
+	if [ $i -eq $NUMBEROFLINES ]; then cat <<END >> VERB2BIN
+		%ENDVERB2BIN
+END
+fi
+#}}}
+	#Add case to verbose.m BIN2VERB{{{
+	if [ $i -eq 1 ]; then cat <<END >> BIN2VERB
+		%BEGINBIN2VERB
+END
+fi
+	cat <<END >> BIN2VERB
+		if bitand(binary,$BINARY), verbose.$(echo $LEVELNAME | awk {'print tolower($1)'})=true; else verbose.$(echo $LEVELNAME | awk {'print tolower($1)'})=false; end
+END
+	if [ $i -eq $NUMBEROFLINES ]; then cat <<END >> BIN2VERB
+		%ENDBIN2VERB
+END
+fi
+#}}}
+	#Add case to verbose.m DISP{{{
+	if [ $i -eq 1 ]; then cat <<END >> DISP
+		%BEGINDISP
+		disp(sprintf('class ''%s''  = ',class(verbose)));
+END
+fi
+	cat <<END >> DISP
+		disp(sprintf('   %15s : %s','$(echo $LEVELNAME | awk {'print tolower($1)'})',mat2str(verbose.$(echo $LEVELNAME | awk {'print tolower($1)'}))));
+END
+	if [ $i -eq $NUMBEROFLINES ]; then cat <<END >> DISP
+		%ENDDISP
+END
+fi
+#}}}
+	#Add case to Verbosity.cpp {{{
+	cat <<END >> Verbosity.cpp
+bool $FILENAME(void){return (GetVerbosityLevel() & $BINARY);} /* 2^$POWER*/
+END
+	#}}}
+
+done
+
+#Add footer of Verbosity.cpp{{{
+cat <<END >> Verbosity.cpp
+
+/*Verbosity Setup*/
+static int verbositylevel=-1;
+void SetVerbosityLevel(int level){/*{{{*/
+
+	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
+
+	verbositylevel = level;
+
+}/*}}}*/
+int  GetVerbosityLevel(void){/*{{{*/
+	_assert_(verbositylevel>=0);
+	return verbositylevel;
+}/*}}}*/
+END
+#}}}
+#Complete verbose.m {{{
+VERBOSEPATH="$ISSM_DIR/src/m/classes/verbose.m"
+cat $VERBOSEPATH  | sed "/%BEGINFIELDS/,$ d"  > temp_begin
+cat $VERBOSEPATH  | sed "1,/%ENDFIELDS/d" > temp_end
+cat temp_begin FIELDS temp_end > $VERBOSEPATH
+rm temp_begin temp_end FIELDS
+
+cat $VERBOSEPATH  | sed "/%BEGINVERB2BIN/,$ d"  > temp_begin
+cat $VERBOSEPATH  | sed "1,/%ENDVERB2BIN/d" > temp_end
+cat temp_begin VERB2BIN temp_end > $VERBOSEPATH
+rm temp_begin temp_end VERB2BIN
+
+cat $VERBOSEPATH  | sed "/%BEGINBIN2VERB/,$ d"  > temp_begin
+cat $VERBOSEPATH  | sed "1,/%ENDBIN2VERB/d" > temp_end
+cat temp_begin BIN2VERB temp_end > $VERBOSEPATH
+rm temp_begin temp_end BIN2VERB
+
+cat $VERBOSEPATH  | sed "/%BEGINDISP/,$ d"  > temp_begin
+cat $VERBOSEPATH  | sed "1,/%ENDDISP/d" > temp_end
+cat temp_begin DISP temp_end > $VERBOSEPATH
+rm temp_begin temp_end DISP
+#}}}
+
+#clean up{{{
+rm temp
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.cpp	(revision 18231)
@@ -0,0 +1,43 @@
+/*
+* \file Verbosity.cpp:
+* \brief: Manage verbosity levels
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+/*include*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Verbosity.h"
+#include "../Exceptions/exceptions.h"
+/*}}}*/
+
+/*Verbosityt levels*/
+bool VerboseMProcessor(void){return (GetVerbosityLevel() & 1);} /* 2^0*/
+bool VerboseModule(void){return (GetVerbosityLevel() & 2);} /* 2^1*/
+bool VerboseSolution(void){return (GetVerbosityLevel() & 4);} /* 2^2*/
+bool VerboseSolver(void){return (GetVerbosityLevel() & 8);} /* 2^3*/
+bool VerboseConvergence(void){return (GetVerbosityLevel() & 16);} /* 2^4*/
+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*/
+static int verbositylevel=-1;
+void SetVerbosityLevel(int level){/*{{{*/
+
+	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
+
+	verbositylevel = level;
+
+}/*}}}*/
+int  GetVerbosityLevel(void){/*{{{*/
+	_assert_(verbositylevel>=0);
+	return verbositylevel;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/Verbosity.h	(revision 18231)
@@ -0,0 +1,22 @@
+/*!\file:Verbosity.h
+ * \brief: Deal with verbosity levels
+ */ 
+
+#ifndef _VERBOSITY_H_
+#define _VERBOSITY_H_
+
+/*List of Verbosity levels (Add your own and Synchronize: must begin with "Verbose")*/
+bool VerboseMProcessor(void);
+bool VerboseModule(void);
+bool VerboseSolution(void);
+bool VerboseSolver(void);
+bool VerboseConvergence(void);
+bool VerboseControl(void);
+bool VerboseQmu(void);
+bool VerboseAutodiff(void);
+
+/*Setup Verbosity level*/
+void SetVerbosityLevel(int level);
+int  GetVerbosityLevel(void);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+#include <math.h>
+
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+#include "../Numerics/types.h"
+#include "./isnan.h"
+
+void XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors){
+
+	IssmDouble	x[3],y[3],z[3];
+	IssmDouble	x_norm, y_norm, z_norm;
+
+	for(int i=0;i<6;i++){
+		if(xIsNan<IssmDouble>(xzvectors[i])){
+			/*At least one NaN found: default to Id*/
+			T[0*3+0] = 1.0;	T[0*3+1] = 0.0;	T[0*3+2] = 0.0;
+			T[1*3+0] = 0.0;	T[1*3+1] = 1.0;	T[1*3+2] = 0.0;
+			T[2*3+0] = 0.0;	T[2*3+1] = 0.0;	T[2*3+2] = 1.0;
+
+			return;
+		}
+	}
+
+	/* get input {x} (vector in local x-z plane): */
+	x[0] = xzvectors[0];
+	x[1] = xzvectors[1];
+	x[2] = xzvectors[2];
+
+	/* get input {z} (local tangent plane normal vector): */
+	z[0] = xzvectors[3];
+	z[1] = xzvectors[4];
+	z[2] = xzvectors[5];
+
+	/* compute {y} = {z} x {x}: */
+	y[0] =  x[2]*z[1] - x[1]*z[2];
+	y[1] = -x[2]*z[0] + x[0]*z[2];
+	y[2] =  x[1]*z[0] - x[0]*z[1];
+
+	/* normalise {x}, {y} and {z} to form unit vectors {i_hat}, {j_hat} and {k_hat};
+		store in {x}, {y}, and {z}: */
+	x_norm = sqrt( x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);
+	y_norm = sqrt( y[0]*y[0] + y[1]*y[1] + y[2]*y[2]);
+	z_norm = sqrt( z[0]*z[0] + z[1]*z[1] + z[2]*z[2]);
+
+	x[0] = x[0]/x_norm;		x[1] = x[1]/x_norm;		x[2] = x[2]/x_norm;
+	y[0] = y[0]/y_norm;		y[1] = y[1]/y_norm;		y[2] = y[2]/y_norm;
+	z[0] = z[0]/z_norm;		z[1] = z[1]/z_norm;		z[2] = z[2]/z_norm;
+
+	/* Tlg columns are just {i_hat}, {j_hat} and {k_hat}, respectively: */
+	T[0*3+0] = x[0];	T[0*3+1] = y[0];	T[0*3+2] = z[0];
+	T[1*3+0] = x[1];	T[1*3+1] = y[1];	T[1*3+2] = z[1];
+	T[2*3+0] = x[2];	T[2*3+1] = y[2];	T[2*3+2] = z[2];
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/constants.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/constants.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/constants.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*!\file: constants.h
+ * \brief prototypes for constants.h
+ */ 
+
+#ifndef _ISSM_CONSTANTS_H_
+#define _ISSM_CONSTANTS_H_
+
+#define UNDEF -9999
+#define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
+#define SQRT2 1.414213562373095048801688724209698078569671875376948073176679738
+#define SQRT3 1.732050807568877293527446341505872366942805253810380628055806979
+#define PI 3.141592653589793238462643383279502884197169399375105820974944592308
+
+#define NDOF1 1
+#define NDOF2 2
+#define NDOF3 3
+#define NDOF4 4
+
+#define DIM2 2
+#define DIM3 3
+
+/*Windows specific typefefs: */
+#ifdef _INTEL_WIN_
+
+/*Complicated way, which does not handle INFINITY though: */
+/*#ifndef NAN
+	static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
+	#define NAN (*(const float *) __nan)
+#endif*/
+
+//For reference, for Intel compile on win64
+//#define NAN 0.0/0.0 
+//#define INFINITY 1.0/0.0
+
+//Most generic way it would seem:
+#define INFINITY (DBL_MAX+DBL_MAX)
+#define NAN (INFINITY-INFINITY)
+
+#endif
+
+#endif //ifndef _ISSMTYPEDEFS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cross.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cross.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cross.cpp	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file:  cross.cpp
+ * \brief cross product for 2 vectors
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./types.h"
+
+void cross(IssmDouble* result,IssmDouble* vector1,IssmDouble* vector2){
+
+	/*result,vector1 and vector2 are all assumed to be of size 3: */
+
+	result[0]=vector1[1]*vector2[2]-vector1[2]*vector2[1];
+	result[1]=vector1[2]*vector2[0]-vector1[0]*vector2[2];
+	result[2]=vector1[0]*vector2[1]-vector1[1]*vector2[0];
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cubic.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cubic.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/cubic.cpp	(revision 18231)
@@ -0,0 +1,92 @@
+#include <math.h>
+
+#include "./numerics.h"
+
+IssmDouble CBRT(IssmDouble Z){
+
+	IssmDouble ret;
+
+	if (Z> 0.0){
+		ret = fabs(pow(fabs(Z),1./3.));
+	}
+	else if(Z< 0.0){
+		ret = - fabs(pow(fabs(Z),1./3.));
+	}
+	else{
+		ret = 0.;
+	}
+	return ret;
+}
+
+int cubic(IssmDouble a,IssmDouble b,IssmDouble c,IssmDouble d, IssmDouble x[3], int* num){
+	/* Find the real roots of linear/quadratic and cubic equations:
+	 *
+	 *   a x^3 + bx^2 + cx + d = 0
+	 *
+	 *   returns the roots in x
+	 *   num is the number of roots */
+
+	/*Some useful constants*/
+	const IssmDouble pi    = 3.1415926535897932;
+	const IssmDouble third = 1./3.;
+
+	/*Intermediaries*/
+	IssmDouble U[3],W,P,Q,delta,phi;
+
+	/* determine the degree of the polynomial */
+	if (a != 0.0){
+		//cubic problem
+		W     = b/a *third;
+		P     = pow((c/a *third - pow(W,2)),3);
+		Q     = -.5 *(2.0*pow(W,3)-(c*W-d)/a );
+		delta = pow(Q,2)+P;
+		if ( delta < 0.0 ){
+			//three real solutions!
+			//Confine the argument of coeffCOS to the interval [-1;1]!
+			phi = acos(min(1.0,max(-1.0,Q/sqrt(-P))));
+			P   = 2.0*pow((-P),(5.e-1*third));
+			for(int i=0;i<3;i++)	U[i] = P*cos((phi+2*((IssmDouble)i)*pi)*third)-W;
+			x[0] = min(U[0], min(U[1], U[2]));
+			x[1] = max(min(U[0], U[1]),max( min(U[0], U[2]), min(U[1], U[2])));
+			x[2] = max(U[0], max(U[1], U[2]));
+			*num = 3;
+		}
+		else{
+			// only one real solution!
+			delta = sqrt(delta);
+			x[0] = CBRT(Q+delta)+CBRT(Q-delta)-W;
+			*num=1;
+		}
+	}
+	else if (b != 0.0){
+		// quadratic problem
+		P     = 0.5*c/b;
+		delta = pow(P,2)-d/b;
+		if (delta > 0.0){
+			// 2 real solutions
+			x[0] = -P - sqrt(delta);
+			x[1] = -P + sqrt(delta);
+			*num = 2;
+		}
+		else{
+			// no real solution
+			*num = 0;
+		}
+	}
+	else if (c != 0.0){
+		//linear equation
+		x[0] = d/c;
+		*num = 1;
+	}
+	else{
+		//no equation
+		*num = 0;
+	}
+
+	/* perform one step of a newton iteration in order to minimize round-off errors */
+	for(int i=0;i<*num;i++){
+		x[i] = x[i] - (d+x[i]*(c+x[i]*(b+x[i]*a)))/(c+x[i]*(2.0*b+x[i]*3.0*a));
+	}
+
+	return 0;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/extrema.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/extrema.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/extrema.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file:  extrema.cpp
+ * \brief min and max functions
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./types.h"
+
+IssmDouble min(IssmDouble a,IssmDouble b){
+	if (a<b)return a;
+	else return b;
+}
+int min(int a,int b){
+	if (a<b)return a;
+	else return b;
+}
+IssmDouble max(IssmDouble a,IssmDouble b){
+	if (a>b)return a;
+	else return b;
+}
+int max(int a,int b){
+	if (a>b)return a;
+	else return b;
+}
+
+#ifdef _HAVE_ADOLC_
+IssmPDouble  min(IssmPDouble a,IssmPDouble b){
+	if (a<b)return a;
+	else return b;
+}
+IssmPDouble  max(IssmPDouble a,IssmPDouble b){
+	if (a>b)return a;
+	else return b;
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.cpp	(revision 18231)
@@ -0,0 +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 "isnan.h"
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+template <> int xIsNan<adouble> (const adouble& X){
+  return isnan(X.getValue());
+}
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/isnan.h	(revision 18231)
@@ -0,0 +1,30 @@
+/*!\file:  isnan.h
+ * \brief: only used for intel compiler.
+ */ 
+
+#ifndef _XISNAN_H_
+#define _XISNAN_H_
+
+#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) {
+#ifdef _INTEL_WIN_
+		return (X!=X)?1:0;
+#else
+		return isnan(X);
+#endif
+}
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+#include "./types.h"
+template <> int xIsNan<adouble> (const adouble& X);
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/numerics.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/numerics.h	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file: numerics.h
+ * \brief prototypes for numerics.h
+ */ 
+
+#ifndef _NUMERICS_H_
+#define  _NUMERICS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Verbosity.h"
+#include "./GaussPoints.h"
+#include "./isnan.h"
+#include "./recast.h"
+#include "./types.h"
+#include "./constants.h"
+#include "./OptPars.h"
+
+IssmDouble  min(IssmDouble a,IssmDouble b);
+IssmDouble  max(IssmDouble a,IssmDouble b);
+
+#ifdef _HAVE_ADOLC_
+IssmPDouble  min(IssmPDouble a,IssmPDouble b);
+IssmPDouble  max(IssmPDouble a,IssmPDouble b);
+#endif
+
+int         min(int a,int b);
+int         max(int a,int b);
+void        BrentSearch(IssmDouble** pJ,OptPars optpars,IssmDouble* X0,IssmDouble (*f)(IssmDouble*,void*),IssmDouble (*g)(IssmDouble**,IssmDouble*,void*),void* usr);
+void        cross(IssmDouble *result,IssmDouble*vector1,IssmDouble*vector2);
+void        XZvectorsToCoordinateSystem(IssmDouble *T,IssmDouble*xzvectors);
+int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d, double X[3], int *num);
+
+int         NewtonSolveDnorm(IssmDouble* pdnorm,IssmDouble c1,IssmDouble c2,IssmDouble c3,IssmDouble n,IssmDouble dnorm);
+
+#endif //ifndef _NUMERICS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/recast.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/recast.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/recast.h	(revision 18231)
@@ -0,0 +1,42 @@
+/*
+ * recast.h
+ *
+ *  Created on: Jun 26, 2012
+ *      Author: utke
+ */
+
+#ifndef _RECAST_H_
+#define _RECAST_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_)
+
+template<class To, class From> To reCast(const From& from) {
+    return (To)from;
+}
+
+#else
+#include "./types.h"
+
+template<class To, class From> struct ForPartialSpecialization {
+    static  To reCast(const From& from ) { return (To) from;}
+};
+
+template<class To, class From> To reCast(const From& from) {
+    return ForPartialSpecialization<To,From>::reCast(from);
+}
+/**
+ * partial specialization
+ */
+template<class To> struct ForPartialSpecialization<To,adouble> {
+    static  To reCast(const adouble& from ) { return (To) (from.getValue());}
+};
+
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/types.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/types.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Numerics/types.h	(revision 18231)
@@ -0,0 +1,36 @@
+/*!\file: types.h
+ * \brief prototypes for types.h
+ */ 
+
+#ifndef _TYPES_H_
+#define  _TYPES_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+
+/*here are our abstracted types: inspired on petsc */
+#if ISSM_USE_64BIT_INDICES == 1
+typedef long long IssmInt;
+#else
+typedef int IssmInt;
+#endif  
+
+#if defined(_HAVE_ADOLC_) &&  !defined(_WRAPPERS_)
+#include "adolc/adolc.h"
+// for active variables
+typedef adouble IssmDouble;
+// for passive variables
+typedef double IssmPDouble;
+#else 
+// see above
+typedef double IssmDouble; 
+// see above
+typedef IssmDouble IssmPDouble;
+#endif
+
+#endif //ifndef _TYPES_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/binary_search.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/binary_search.cpp	(revision 18231)
@@ -0,0 +1,68 @@
+/*!\file:  binary_search.cpp
+ * \brief  binary search on an integer array, that is already sorted
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../Exceptions/exceptions.h"
+#include <stdio.h>
+
+int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){ /*{{{*/
+
+	/*output: */
+	int offset;  //offset, if found
+	int found=0; //found=0 if target is not found, 1 otherwise.
+
+	/*intermediary: */
+	int *beg = NULL;
+	int *end = NULL;
+	int *mid = NULL;
+
+	_assert_(sorted_integers);
+
+	// point to beginning and end of the array
+	beg=sorted_integers;
+	end=sorted_integers+num_integers;
+	mid=beg+(int)(num_integers/2);
+
+	if (*beg==target){
+		found=1;
+		offset=0;
+	}
+	else if(*(end-1)==target){
+		found=1;
+		offset=num_integers-1;
+	}
+	else{
+		while((beg <= end) && (*mid != target)){
+			// is the target in lower or upper half?
+			if (target < *mid) {
+				end = mid - 1;  //new end
+				mid = beg + (end-beg)/2;  //new middle
+			}
+			else {
+				beg = mid + 1;  //new beginning
+				mid = beg + (end-beg)/2;  //new middle
+			}
+		}
+
+		//did we find the target?
+		if (*mid == target) {
+			found=1;
+			offset=mid-sorted_integers;
+		}
+		else {
+			found=0;
+		}
+	}
+
+	/*Assign output pointers:*/
+	*poffset=offset;
+
+	/*Return result: */
+	return found;
+} /*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/sorting.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/sorting.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Sorting/sorting.h	(revision 18231)
@@ -0,0 +1,61 @@
+/*!\file: sorting.h
+ * \brief prototypes for sorting.h
+ */ 
+
+#ifndef _SORTING_H_
+#define  _SORTING_H_
+
+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/branches/trunk-jpl-ad2-integrated/src/c/shared/String/ApiPrintf.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/ApiPrintf.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/ApiPrintf.cpp	(revision 18231)
@@ -0,0 +1,15 @@
+/*!\file:  ApiPrintf: this file only gets compiled and linked for issm.exe. API specific 
+ * versions of this file (for Python and Matlab) will be used for the wrappers (modules). 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+
+void ApiPrintf(const char* string){
+	printf("%s",string);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/DescriptorIndex.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/DescriptorIndex.cpp	(revision 18231)
@@ -0,0 +1,72 @@
+/*!\file:  DescriptorIndex: return type of qmu variable: indexed, scaled, nodal or regular
+ * + figure out the descriptor root. 
+ * Ex: scaled_Thickness_1 should return SCALEDENUM, fill root with Thickness, and initialize index 
+ * to 1.
+ */ 
+
+#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 <ctype.h>
+#include "../Enum/Enum.h"
+#include "../io/io.h"
+#include "../Exceptions/exceptions.h"
+
+int  DescriptorIndex(char* root, int* pindex,char* descriptor){ //We assume root has already been allocated, and we just have to copy into it.
+
+	char * pch=NULL;
+
+	/*retrieve first token, separated by underscore: */
+	pch = strtok (descriptor,"_");
+	if(!pch)_error_("descriptor " << descriptor << " is not correctly formatted!");
+
+	if (strncmp(pch,"scaled",6)==0){
+		/*we have a scaled variable. recover the root: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("scaled descriptor " << descriptor << " is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+
+		/*now recover  the index if it exists: */
+		pch = strtok (NULL, "_");
+		if(!pch){
+			*pindex=-1;
+		}
+		else{
+			sscanf(pch,"%i",pindex);
+		}
+		return ScaledEnum;
+	}
+	else if (strncmp(pch,"indexed",7)==0){
+		/*we have an indexed variable. recover the root: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		sscanf(pch,"%i",pindex);
+		return IndexedEnum;
+	}
+	else if (strncmp(pch,"nodal",5)==0){
+		/*we have an indexed variable. recover the root: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		sscanf(pch,"%i",pindex);
+		return NodalEnum;
+	}
+	else{
+		/*We don't have _ in the name, this is a regular variable: */
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		*pindex=-1;
+		return RegularEnum;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/sharedstring.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/sharedstring.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/String/sharedstring.h	(revision 18231)
@@ -0,0 +1,11 @@
+/*!\file: sharedstring.h
+ * \brief prototypes for sharedstring.h
+ */ 
+
+#ifndef _SHAREDSTRING_H_
+#define  _SHAREDSTRING_H_
+
+int  DescriptorIndex(char* root, int* pindex,char* descriptor);
+void ApiPrintf(const char* string);
+
+#endif //ifndef _SHAREDSTRING_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/LaunchThread.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/LaunchThread.cpp	(revision 18231)
@@ -0,0 +1,70 @@
+/*!\file:  LaunchThread.cpp
+ * \brief  launch thread in a generic way, covering single and multi-threaded cases
+ * This routine attempts to simplify management of multi-threading. When multi-threadeing 
+ * is not requested (serial run), LaunchThread will just call the function (provided in argument 
+ * list), nothing fancy there.  If multi-threading is requested, LaunchThread will launch the 
+ * function on multiple threads (num_threads of them), and provide these functions with the 
+ * local data they need (folded in the "gate" structure) + the thread id + the number of threads 
+ * All this info is collected in the pthread_handle structure. 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _MULTITHREADING_
+#include <pthread.h>
+#endif
+
+#include "./issm_threads.h"
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+
+void LaunchThread(void* function(void*), void* gate,int num_threads){
+
+	#ifdef _MULTITHREADING_
+	int i;
+	int            *status  = NULL;
+	pthread_t      *threads = NULL;
+	pthread_handle *handles = NULL;
+
+	/*check number of threads*/
+	if(num_threads<1)    _error_("number of threads must be at least 1");
+	if(num_threads>2000) _error_("number of threads seems to be too high ("<<num_threads<<">2000)");
+
+	/*dynamically allocate: */
+	threads=xNew<pthread_t>(num_threads);
+	handles=xNew<pthread_handle>(num_threads);
+
+	for(i=0;i<num_threads;i++){
+		handles[i].gate=gate;
+		handles[i].id=i;
+		handles[i].num=num_threads;
+	}
+	for(i=0;i<num_threads;i++){
+
+		if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
+			_error_("pthread_create error");
+		}
+	}
+	for(i=0;i<num_threads;i++){
+		if(pthread_join(threads[i],(void**)&status)){
+			_error_("pthread_join error");
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<pthread_t>(threads);
+	xDelete<pthread_handle>(handles);
+
+	#else
+	pthread_handle handle;
+	handle.gate=gate;
+	handle.id=0;
+	handle.num=1;
+
+	function((void*)&handle);
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/PartitionRange.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/PartitionRange.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/PartitionRange.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file:  PartitionRange.cpp
+ * \brief: return i0,i1, range of local thread.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <math.h>
+
+void PartitionRange(int* pi0,int* pi1, int num_el,int num_threads,int my_thread){
+
+	/*output: */
+	int i0=-1;
+	int i1=-1;
+
+	int step;
+	int i;
+
+	/*distribute elements across threads :*/
+	step=(int)floor((double)num_el/(double)num_threads);
+	for(i=0;i<(my_thread+1);i++){
+		i0=i*step;
+		if(i==(num_threads-1))i1=num_el;
+		else i1=i0+step;
+	}
+
+	/*Assign output pointers:*/
+	*pi0=i0;
+	*pi1=i1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/issm_threads.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/issm_threads.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/Threads/issm_threads.h	(revision 18231)
@@ -0,0 +1,21 @@
+/*!\file: issm_threads.h
+ * \brief prototypes for issm_threads.h
+ */ 
+
+#ifndef _ISSM_THREADS_H_
+#define  _ISSM_THREADS_H_
+
+/*structure that holds the local data for each thread (in the gate), 
+ * + the thread specific information (my id + number of threads) : */
+typedef struct{
+	void* gate;
+	int   id;
+	int   num;
+} pthread_handle;
+
+/*routine that launches "function" in a multi-threaded way if requested, 
+ * or just serially if not requested: */
+void LaunchThread(void* function(void*), void* gate,int num_threads);
+void PartitionRange(int* pi0,int* pi1, int num_el,int num_threads,int my_thread);
+
+#endif //ifndef _ISSM_THREADS_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/AssociateSegmentToElement.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 18231)
@@ -0,0 +1,24 @@
+/*!\file:  AssociateSegmentToElement.cpp
+ * \brief for each segment, look for the corresponding element.
+ */ 
+
+#include "./trimesh.h"
+
+int AssociateSegmentToElement(int** psegments,int nseg,int* index,int nel){
+
+	/*node indices: */
+	int A,B;
+
+	/*Recover segments: */
+	int* segments=*psegments;
+
+	for(int i=0;i<nseg;i++){
+		A=segments[3*i+0];
+		B=segments[3*i+1];
+		segments[3*i+2]=FindElement(A,B,index,nel)+1; //matlab indexing.
+	}
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/GridInsideHole.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+/*
+ * GridInsideHole.c:
+ * from a convex set of points, figure out a point that for sure lies inside the profile.
+ */
+
+#include <math.h>
+
+#include "./trimesh.h"
+#include "../Exp/exp.h"
+
+#undef M_PI
+#define M_PI 3.141592653589793238462643
+
+int GridInsideHole(double* px0,double* py0,int n,double* x,double* y){
+
+	double flag=0.0;
+	double xA,xB,xC,xD,xE;
+	double yA,yB,yC,yD,yE;
+
+	/*Take first and last vertices: */
+	xA=x[0];
+	yA=y[0];
+	xB=x[n-1];
+	yB=y[n-1];
+
+	/*Figure out middle of segment [A B]: */
+	xC=(xA+xB)/2;
+	yC=(yA+yB)/2;
+
+	/*D and E are on each side of segment [A B], on the median line between segment [A  B], 
+	 *at an angle of 10 degree (less than the minimum 30 enforced by the quality of the mesh: */
+	xD=xC+tan(10./180.*M_PI)*(yC-yA);
+	yD=yC+tan(10./180.*M_PI)*(xA-xC);
+	xE=xC-tan(10./180.*M_PI)*(yC-yA);
+	yE=yC-tan(10./180.*M_PI)*(xA-xC);
+
+	/*Either E or D is inside profile (x,y): */
+	IsInPolySerial(&flag,&xD,&yD,1,x,y,n,2);
+	/*FIXME: used to be 'flag' and not '!flag', check*/
+	if(!flag){
+		/*D is inside the poly: */
+		*px0=xD;
+		*py0=yD;
+	}
+	else{
+		/*E is inside the poly: */
+		*px0=xE;
+		*py0=yE;
+	}
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/OrderSegments.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/OrderSegments.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/OrderSegments.cpp	(revision 18231)
@@ -0,0 +1,46 @@
+/*
+ * OrderSegments.c: 
+ * reorder segments so that their normals point outside the domain outline.
+ */
+#include "./trimesh.h"
+
+int OrderSegments(int** psegments,int nseg,int* index,int nel){
+
+	/*vertex indices: */
+	int A,B;
+
+	/*element index*/
+	int el;
+
+	/*Recover segments: */
+	int* segments=*psegments;
+
+	for(int i=0;i<nseg;i++){
+		A=segments[3*i+0];
+		B=segments[3*i+1];
+		el=segments[3*i+2]-1; //after AssociateSegmentToElement, el was a matlab index, we need the c index now.
+
+		if (index[3*el+0]==A){
+			if (index[3*el+2]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+		else if (index[3*el+1]==A){
+			if (index[3*el+0]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+		else{
+			if (index[3*el+1]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 18231)
@@ -0,0 +1,96 @@
+/*
+ * SplitMeshForRifts.c:
+ */
+#include "./trimesh.h"
+#include "../MemOps/MemOps.h"
+
+int SplitMeshForRifts(int* pnel,int** pindex,int* pnods,double** px,double** py,int* pnsegs,int** psegments,int** psegmentmarkerlist){
+
+	/*Some notes on dimensions: 
+	index  of size nelx3
+	x and y of size nodsx1
+	segments of size nsegsx3*/
+
+	int i,j,k,l;
+	int node;
+	int el;
+	int  nriftsegs;
+	int* riftsegments=NULL; 
+	int* flags=NULL;
+	int  NumGridElementListOnOneSideOfRift;
+	int* GridElementListOnOneSideOfRift=NULL;
+
+	/*Recover input: */
+	int     nel               = *pnel;
+	int    *index             = *pindex;
+	int     nods              = *pnods;
+	double *x                 = *px;
+	double *y                 = *py;
+	int     nsegs             = *pnsegs;
+	int    *segments          = *psegments;
+	int    *segmentmarkerlist = *psegmentmarkerlist;
+
+	/*Establish list of segments that belong to a rift: */
+	/*riftsegments of size nriftsegsx4 (4 for first element on segment,second element,first node and second snode)*/
+	RiftSegmentsFromSegments(&nriftsegs,&riftsegments,nel,index,nsegs,segments);
+
+	/*Go through all nodes of the rift segments, and start splitting the mesh: */
+	flags=xNewZeroInit<int>(nods); //to make sure we don't split the same nodes twice!
+	for (i=0;i<nriftsegs;i++){
+		for (j=0;j<2;j++){
+
+			node=riftsegments[4*i+j+2];
+			if(flags[node-1]){
+				/*This node was already split, skip:*/
+				continue;
+			}
+			else{
+				flags[node-1]=1;
+			}
+
+			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
+				 * NumGridElementListOnOneSideOfRift) that all contain node 
+				 *and that are on the same side of the rift. For all these
+				 elements, we clone node into another node, and we swap all
+				 instances of node in the triangulation *for those elements, to the
+				 new node.*/
+
+				//create new node
+				x=xReNew<double>(x,nods,nods+1);
+				y=xReNew<double>(y,nods,nods+1);
+				x[nods]=x[node-1]; //matlab indexing
+				y[nods]=y[node-1]; //matlab indexing
+
+				//augment number of nodes 
+				nods++;
+
+				//change elements owning this node
+				for (k=0;k<NumGridElementListOnOneSideOfRift;k++){
+					el=GridElementListOnOneSideOfRift[k];
+					for (l=0;l<3;l++){
+						if (index[3*el+l]==node) index[3*el+l]=nods; //again, matlab indexing.
+					}
+				}
+			}// if(IsGridOnRift(riftsegments,nriftsegs,node))
+		} //for(j=0;j<2;j++)
+	} //for (i=0;i<nriftsegs;i++)
+
+	/*update segments: they got modified completely by adding new nodes.*/
+	UpdateSegments(&segments,&segmentmarkerlist, &nsegs,index,x,y,riftsegments,nriftsegs,nods,nel);
+
+	/*Assign output pointers: */
+	*pnel=nel;
+	*pindex=index;
+	*pnods=nods;
+	*px=x;
+	*py=y;
+	*pnsegs=nsegs;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 18231)
@@ -0,0 +1,912 @@
+/*
+ * TriMeshUtils: mesh manipulation routines: 
+ */
+
+#include <stdio.h>
+
+#include "./trimesh.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+#define RIFTPENALTYPAIRSWIDTH 8
+int IsGridOnRift(int* riftsegments, int nriftsegs, int node){/*{{{*/
+
+	/*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;
+	int count;
+
+	count=0;
+	for (i=0;i<nriftsegs;i++){
+		for (j=0;j<2;j++){
+			if ((*(riftsegments+4*i+2+j))==node) count++;
+		}
+	}
+	if (count==2){
+		return 1;
+	}
+	else{
+		return 0;
+	}
+}/*}}}*/
+int GridElementsList(int** pGridElements, int* pNumGridElements,int node,int* index,int nel){/*{{{*/
+
+	/*From a node, recover all the elements that are connected to it: */
+	int i,j;
+	int noerr=1;
+
+	int max_number_elements=12;
+	int current_size;
+	int NumGridElements;
+	int* GridElements=NULL;
+	int* GridElementsRealloc=NULL;
+
+	/*From a mesh with 30 degrees minimum angle, we get 12 possible elements that own 
+	 * the node. We start by allocating GridElements with that size, and realloc 
+	 * more if needed.*/
+
+	current_size=max_number_elements;
+	NumGridElements=0;
+	GridElements=xNew<int>(max_number_elements);
+
+	for (i=0;i<nel;i++){
+		for (j=0;j<3;j++){
+			if (index[3*i+j]==node){
+				if (NumGridElements<=(current_size-1)){
+					GridElements[NumGridElements]=i;
+					NumGridElements++;
+					break;
+				}
+				else{
+					/*Reallocate another max_number_elements slots in the GridElements: */
+					GridElementsRealloc=xReNew<int>(GridElements,current_size,(current_size+max_number_elements));
+					if (!GridElementsRealloc){
+						noerr=0;
+						goto cleanup_and_return;
+					}
+					current_size+=max_number_elements;
+					GridElements=GridElementsRealloc;
+					GridElements[NumGridElements]=i;
+					NumGridElements++;
+					break;
+				}
+			}
+		}
+	}
+	cleanup_and_return:
+	if(!noerr){
+		xDelete<int>(GridElements);
+	}
+	/*Allocate return pointers: */
+	*pGridElements=GridElements;
+	*pNumGridElements=NumGridElements;
+	return noerr;
+}/*}}}*/
+int IsNeighbor(int el1,int el2,int* index){/*{{{*/
+	/*From a triangulation held in index, figure out if elements 1 and 2 have two nodes in common: */
+	int i,j;
+	int count=0;
+	for (i=0;i<3;i++){
+		for (j=0;j<3;j++){
+			if (index[3*el1+i]==index[3*el2+j])count++;
+		}
+	}
+	if (count==2){
+		return 1;
+	}
+	else{
+		return 0;
+	}
+}/*}}}*/
+int IsOnRift(int el,int nriftsegs,int* riftsegments){/*{{{*/
+	/*From a list of elements segments, figure out if el belongs to it: */
+	int i;
+	for (i=0;i<nriftsegs;i++){
+		if ((*(riftsegments+4*i+0)==el) || (*(riftsegments+4*i+1)==el)){
+			return 1;
+		}
+	}
+	return 0;
+}/*}}}*/
+void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index,int nsegs,int* segments){/*{{{*/
+
+	int i,counter;
+	int el,el2;
+
+	int  nriftsegs;
+	int* riftsegments=NULL;
+	int* riftsegments_uncompressed=NULL; 
+	int  element_nodes[3];
+
+	/*Allocate segmentflags: */
+	riftsegments_uncompressed=xNewZeroInit<int>(nsegs*5);
+
+	/*Find the segments that belong to a rift: they are the ones that see two elements. The other ones belong to a boundary 
+	 *or a hole: */
+	nriftsegs=0;
+	for (i=0;i<nsegs;i++){
+		el=(int)*(segments+3*i+2)-1; //element found in AssociateSegmentToElements
+		/*Temporarily set nodes belonging to the segments to -1 in the triangulation index, and 
+		 *then  proceed to find another element that owns the segment. If we don't find it, we know 
+		 *we are dealing with a boundary or hole, otherwise, we are dealing with a rift: */
+		element_nodes[0]=*(index+3*el+0);
+		element_nodes[1]=*(index+3*el+1);
+		element_nodes[2]=*(index+3*el+2);
+
+		index[3*el+0]=-1;
+		index[3*el+1]=-1;
+		index[3*el+2]=-1;
+
+		el2=FindElement(*(segments+3*i+0),*(segments+3*i+1),index,nel); 
+
+		/*Restore index: */
+		index[3*el+0]=element_nodes[0];
+		index[3*el+1]=element_nodes[1];
+		index[3*el+2]=element_nodes[2];
+
+		if (el2!=-1){
+			/*el and el2 are on a segment rift, facing one another, plug them into riftsegments_uncompressed: */
+		    riftsegments_uncompressed[5*i+0]=1;
+		    riftsegments_uncompressed[5*i+1]=el;
+		    riftsegments_uncompressed[5*i+2]=el2;
+		    riftsegments_uncompressed[5*i+3]=segments[3*i+0];
+			 riftsegments_uncompressed[5*i+4]=segments[3*i+1];
+			 nriftsegs++;
+		}
+	}
+
+	/*Compress riftsegments_uncompressed:*/
+	riftsegments=xNew<int>(nriftsegs*4);
+	counter=0;
+	for (i=0;i<nsegs;i++){
+		if (riftsegments_uncompressed[5*i+0]){
+			riftsegments[counter*4+0]=riftsegments_uncompressed[5*i+1];
+			riftsegments[counter*4+1]=riftsegments_uncompressed[5*i+2];
+			riftsegments[counter*4+2]=riftsegments_uncompressed[5*i+3];
+			riftsegments[counter*4+3]=riftsegments_uncompressed[5*i+4];
+			counter++;
+		}
+	}
+	xDelete<int>(riftsegments_uncompressed);
+
+	/*Assign output pointers: */
+	*priftsegments=riftsegments;
+	*pnriftsegs=nriftsegs;
+}/*}}}*/
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,int* index,int nel){/*{{{*/
+
+	int noerr=1;
+	int k,l,counter;
+	int newel;
+
+	int* GridElements=NULL;
+	int  NumGridElements;
+
+	/*Output: */
+	int NumGridElementListOnOneSideOfRift;
+	int* GridElementListOnOneSideOfRift=NULL;
+
+	/*Build a list of all the elements connected to this node: */
+	GridElementsList(&GridElements,&NumGridElements,node,index,nel);
+
+	/*Figure out the list of elements  that are on the same side of the rift. To do so, we start from one 
+	 * side of the rift and keep rotating in the same direction:*/
+	GridElementListOnOneSideOfRift=xNew<int>(NumGridElements);
+	//bootstrap the GridElementListOnOneSideOfRift by filling elements from riftsegments: */
+	GridElementListOnOneSideOfRift[0]=*(riftsegments+4*segmentnumber+0); /*this one does not belong to the same side, but is just there 
+															   for a rotation direction, we 'll take it out when we are 
+															   done rotating*/
+	GridElementListOnOneSideOfRift[1]=*(riftsegments+4*segmentnumber+1);
+	counter=1;
+	for (;;){
+		/*Find neighbour of element GridElementListOnOneSideOfRift[counter], not 
+		 * equal to GridElementListOnOneSideOfRift[counter-1]*/
+		for (k=0;k<NumGridElements;k++){
+			if(IsNeighbor(GridElements[k],GridElementListOnOneSideOfRift[counter],index)){
+				/*Verify this element is not already in our list of element on the same side of the rift: */
+				newel=1;
+				for (l=0;l<=counter;l++){
+					if (GridElements[k]==GridElementListOnOneSideOfRift[l]){
+						newel=0;
+						break;
+					}
+				}
+				if (newel){
+					counter++;
+					GridElementListOnOneSideOfRift[counter]=GridElements[k];
+					if (IsOnRift(GridElements[k],nriftsegs,riftsegments)){
+						break;
+					}
+					k=-1;
+				}
+			}
+		}
+		/*Reduce counter by 1 and get rift of first element in GridElementListOnOneSideOfRift:*/
+		NumGridElementListOnOneSideOfRift=counter;
+		for (l=0;l<NumGridElementListOnOneSideOfRift;l++){
+			GridElementListOnOneSideOfRift[l]=GridElementListOnOneSideOfRift[l+1];
+		}
+		break;
+	}// for (;;)
+
+	/*Free ressources: */
+	xDelete<int>(GridElements);
+	/*Assign output pointers: */
+	*pNumGridElementListOnOneSideOfRift=NumGridElementListOnOneSideOfRift;
+	*pGridElementListOnOneSideOfRift=GridElementListOnOneSideOfRift;
+	return noerr;
+}/*}}}*/
+int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+	int el1,el2;
+
+	int *segments          = NULL;
+	int *segmentmarkerlist = NULL;
+	int  nsegs;
+
+	/*Recover input: */
+	segments          = *psegments;
+	segmentmarkerlist = *psegmentmarkerlist;
+	nsegs             = *pnsegs;
+
+	/*Reallocate segments: */
+	segments         =xReNew<int>(segments,         nsegs*3,(nsegs+nriftsegs)*3);
+	segmentmarkerlist=xReNew<int>(segmentmarkerlist,nsegs,(nsegs+nriftsegs));
+
+	/*First, update the existing segments to the new nodes :*/
+	for (i=0;i<nriftsegs;i++){
+		el1=riftsegments[4*i+0];
+		el2=riftsegments[4*i+1];
+		for (j=0;j<nsegs;j++){
+			if (segments[3*j+2]==(el1+1)){
+				/*segment j is the same as rift segment i.Let's update segments[j][:] using  element el1 and the corresponding rift segment.
+				 *Because riftsegments does not represent a list of rift segments anymore (it got heavily modified in SplitElementsForRifts, 
+				 *we can only rely on the position (x,y) of the rift nodes to create a segment:*/
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el1*3+k); _assert_(segments[3*j+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+1)-1])  && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el1*3+k); _assert_(segments[3*j+1]<nods+1);
+						break;
+					}
+				}
+				/*Deal with el2: */
+				*(segments+3*(nsegs+i)+2)=el2+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el2*3+k); _assert_(segments[3*(nsegs+i)+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el2*3+k); _assert_(segments[3*(nsegs+i)+1]<nods+1);
+						break;
+					}
+				}
+			}
+			if (*(segments+3*j+2)==(el2+1)){
+				/*segment j is the same as rift segment i.*/
+				/*Let's update segments[j][:] using  element el2 and the corresponding rift segment: */
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el2*3+k); _assert_(segments[3*j+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el2*3+k);_assert_(segments[3*j+1]<nods+1);
+						break;
+					}
+				}
+				/*Deal with el1: */
+				*(segments+3*(nsegs+i)+2)=el1+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el1*3+k);_assert_(segments[3*(nsegs+i)+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el1*3+k);_assert_(segments[3*(nsegs+i)+1]<nods+1);
+						break;
+					}
+				}
+			}
+		}
+	}
+	nsegs+=nriftsegs;
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnsegs=nsegs;
+
+	return noerr;
+}/*}}}*/
+int FindElement(int A,int B,int* index,int nel){/*{{{*/
+
+	int el=-1;
+	for (int n=0;n<nel;n++){
+		if(((index[3*n+0]==A) || (index[3*n+1]==A) || (index[3*n+2]==A)) && ((index[3*n+0]==B) || (index[3*n+1]==B) || (index[3*n+2]==B))){
+			el=n;
+			break;
+		}
+	}
+	return el;
+}/*}}}*/
+int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nel){/*{{{*/
+
+	/*Using segment markers, wring out the rift segments from the segments. Rift markers are 
+	 *of the form 2+i where i=0 to number of rifts */
+
+	int noerr=1;
+	int i,j,counter;
+
+	/*input: */
+	int *segments          = NULL;
+	int *segmentmarkerlist = NULL;
+	int numsegs;
+
+	/*output: */
+	int   new_numsegs;
+	int  *riftsnumsegs       = NULL;
+	int **riftssegments      = NULL;
+	int  *new_segments       = NULL;
+	int  *new_segmentmarkers = NULL;
+
+	/*intermediary: */
+	int* riftsegment=NULL;
+
+	/*Recover input arguments: */
+	segments          = *psegments;
+	numsegs           = *pnumsegs;
+	segmentmarkerlist = *psegmentmarkerlist;
+
+	/*First, figure out  how many segments will be left in 'segments': */
+	counter=0;
+	for (i=0;i<numsegs;i++){
+		if (segmentmarkerlist[i]==1)counter++; //1 is default marker for non-rifts;
+	}
+	/*Allocate new segments: */
+	new_numsegs=counter;
+	new_segments=xNew<int>(new_numsegs*3);
+	new_segmentmarkers=xNew<int>(new_numsegs);
+
+	/*Copy new segments info : */
+	counter=0;
+	for (i=0;i<numsegs;i++){
+		if (segmentmarkerlist[i]==1){
+			new_segments[3*counter+0]=segments[3*i+0];
+			new_segments[3*counter+1]=segments[3*i+1];
+			new_segments[3*counter+2]=segments[3*i+2];
+			new_segmentmarkers[counter]=segmentmarkerlist[i];
+			counter++;
+		}
+	}
+
+	/*Now deal with rift segments: */
+	riftsnumsegs=xNew<int>(numrifts);
+	riftssegments=xNew<int*>(numrifts);
+	for (i=0;i<numrifts;i++){
+		/*Figure out how many segments for rift i: */
+		counter=0;
+		for (j=0;j<numsegs;j++){
+			if (segmentmarkerlist[j]==2+i)counter++;
+		}
+		riftsnumsegs[i]=counter;
+		riftsegment=xNew<int>(counter*3);
+		/*Copy new segments info :*/
+		counter=0;
+		for (j=0;j<numsegs;j++){
+			if (segmentmarkerlist[j]==(2+i)){
+				riftsegment[3*counter+0]=segments[3*j+0];_assert_(riftsegment[3*counter+0]<nods+1);
+				riftsegment[3*counter+1]=segments[3*j+1];_assert_(riftsegment[3*counter+1]<nods+1);
+				riftsegment[3*counter+2]=segments[3*j+2];_assert_(riftsegment[3*counter+2]<nel+1);
+				counter++;
+			}
+		}
+		*(riftssegments+i)=riftsegment;
+	}
+
+	/*Free ressources: */
+	xDelete<int>(segments);
+
+	/*Assign output pointers: */
+	*psegments=new_segments;
+	*psegmentmarkerlist=new_segmentmarkers;
+	*pnumsegs=new_numsegs;
+	*pnumrifts=numrifts;
+	*priftssegments=riftssegments;
+	*priftsnumsegs=riftsnumsegs;
+	return noerr;
+}/*}}}*/
+int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+
+	/*output: */
+	int  *riftsnumpairs = NULL;
+	int **riftspairs    = NULL;
+
+	/*intermediary :*/
+	int  numsegs;
+	int* segments=NULL;
+	int* pairs=NULL;
+	int  node1,node2,node3,node4;
+
+	riftsnumpairs=xNew<int>(numrifts);
+	riftspairs=xNew<int*>(numrifts);
+	for (i=0;i<numrifts;i++){
+		segments=riftssegments[i];
+		numsegs =riftsnumsegments[i];
+		riftsnumpairs[i]=numsegs;
+		pairs=xNew<int>(2*numsegs);
+		for (j=0;j<numsegs;j++){
+			pairs[2*j+0]=segments[3*j+2]; //retrieve element to which this segment belongs.
+			node1=segments[3*j+0]-1; node2=segments[3*j+1]-1;
+			/*Find element facing on other side of rift: */
+			for (k=0;k<numsegs;k++){
+				if (k==j)continue;
+				node3=segments[3*k+0]-1; node4=segments[3*k+1]-1;
+				/*We are trying to find 2 elements, where position of node3 == position of node1, and position of node4 == position of node2*/
+				if (   ((x[node3]==x[node1]) && (y[node3]==y[node1]) && (x[node4]==x[node2]) && (y[node4]==y[node2]))
+				    || ((x[node3]==x[node2]) && (y[node3]==y[node2]) && (x[node4]==x[node1]) && (y[node4]==y[node1]))  ){
+					/*We found the corresponding element: */
+					pairs[2*j+1]=segments[3*k+2];
+					break;
+				}
+			}
+		}
+		riftspairs[i]=pairs;
+	}
+
+	/*Assign output pointers: */
+	*priftsnumpairs=riftsnumpairs;
+	*priftspairs=riftspairs;
+	return noerr;
+}/*}}}*/
+int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs){/*{{{*/
+
+	int i;
+	int noerr=1;
+
+	/*output: */
+	int riftflag=0;
+	int numrifts=0;
+
+	int maxmark=1; //default marker for regular segments
+
+	/*Any marker >=2 indicates a certain rift: */
+	numrifts=0;
+	for (i=0;i<nsegs;i++){
+		if (segmentmarkerlist[i]>maxmark){
+			numrifts++;
+			maxmark=segmentmarkerlist[i];
+		}
+	}
+	if(numrifts)riftflag=1;
+
+	/*Assign output pointers:*/
+	*priftflag=riftflag;
+	*pnumrifts=numrifts;
+	return noerr;
+}/*}}}*/
+int OrderRifts(int** priftstips,int** riftssegments,int** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels){/*{{{*/
+
+	int noerr=1;
+	int i,j,k,counter;
+
+	/*intermediary: */
+	int *riftsegments = NULL;
+	int *riftpairs    = NULL;
+	int numsegs;
+
+	/*ordering and copy: */
+	int *order             = NULL;
+	int *riftsegments_copy = NULL;
+	int *riftpairs_copy    = NULL;
+
+	/*node and element manipulation: */
+	int node1,node2,node3,node4,temp_node,tip1,tip2,node;
+	int el2;
+	int already_ordered=0;
+
+	/*output: */
+	int* riftstips=NULL;
+
+	/*Allocate byproduct of this routine, riftstips: */
+	riftstips=xNew<int>(numrifts*2);
+
+	/*Go through all rifts: */
+	for (i=0;i<numrifts;i++){
+		riftsegments = riftssegments[i];
+		riftpairs    = riftspairs[i];
+		numsegs      = riftsnumsegments[i];
+
+		/*Allocate copy of riftsegments and riftpairs, 
+		 *as well as ordering vector: */
+		riftsegments_copy=xNew<int>(numsegs*3);
+		riftpairs_copy=xNew<int>(numsegs*2);
+		order=xNew<int>(numsegs);
+
+		/*First find the tips, using the pairs. If a pair of elements has one node in common, this node is a rift tip: */
+		tip1=-1;
+		tip2=-1;
+
+		for (j=0;j<numsegs;j++){
+			el2=*(riftpairs+2*j+1);
+			node1=*(riftsegments+3*j+0);
+			node2=*(riftsegments+3*j+1);
+			/*Summary, el1 and el2 are facing one another across the rift. node1 and node2 belong to el1 and 
+			 *are located on the rift. Find node3 and node4, nodes belonging to el2 and located on the rift: */
+			for (k=0;k<numsegs;k++){
+				if (*(riftsegments+3*k+2)==el2){
+					node3=*(riftsegments+3*k+0);
+					node4=*(riftsegments+3*k+1);
+					break;
+				}
+			}
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			_assert_(node1<nods+1 && node4<nods+1);
+			_assert_(node1>0 && node4>0);
+			if ((x[node1-1]==x[node4-1]) && (y[node1-1]==y[node4-1])){
+				/*Swap node3 and node4:*/
+				temp_node=node3;
+				node3=node4;
+				node4=temp_node;
+			}
+
+			/*Figure out if a tip is on this element: */
+			if (node3==node1){
+				/*node1 is a tip*/
+				if (tip1==-1) {
+					tip1=node1;
+					continue;
+				}
+				if ((tip2==-1) && (node1!=tip1)){
+					tip2=node1;
+					break;
+				}
+			}
+
+			if (node4==node2){
+				/*node2 is a tip*/
+				if (tip1==-1){
+					tip1=node2;
+					continue;
+				}
+				if ((tip2==-1) && (node2!=tip1)){
+					tip2=node2;
+					break;
+				}
+			}
+		}
+
+		/*Record tips in riftstips: */
+		*(riftstips+2*i+0)=tip1;
+		*(riftstips+2*i+1)=tip2;
+
+		/*We have the two tips for this rift.  Go from tip1 to tip2, and figure out the order in which segments are sequential. 
+		 *Because two elements are connected to tip1, we chose one first, which defines the direction we are rotating along the rift. */
+		node=tip1;
+		for (counter=0;counter<numsegs;counter++){
+			for (j=0;j<numsegs;j++){
+				node1=*(riftsegments+3*j+0);
+				node2=*(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: */
+					already_ordered=0;
+					for (k=0;k<counter;k++){
+						if(order[k]==j){
+							already_ordered=1;
+							break;
+						}
+					}
+					if (!already_ordered){
+						order[counter]=j;
+						if(node1==node){
+							node=node2;
+						}
+						else if(node2==node){
+							node=node1;
+						}
+						break;
+					}
+				}
+			}
+		}
+
+		/*Using the order vector, and the riftsegments_copy and riftspairs_copy, reorder the segments and the pairs: */
+		for (j=0;j<numsegs;j++){
+			_assert_(order[j]<numsegs);
+			*(riftsegments_copy+3*j+0)=*(riftsegments+3*order[j]+0);
+			*(riftsegments_copy+3*j+1)=*(riftsegments+3*order[j]+1);
+			*(riftsegments_copy+3*j+2)=*(riftsegments+3*order[j]+2);
+			*(riftpairs_copy+2*j+0)=*(riftpairs+2*order[j]+0);
+			*(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);
+			*(riftsegments+3*j+1)=*(riftsegments_copy+3*j+1);
+			*(riftsegments+3*j+2)=*(riftsegments_copy+3*j+2);
+			*(riftpairs+2*j+0)=*(riftpairs_copy+2*j+0);
+			*(riftpairs+2*j+1)=*(riftpairs_copy+2*j+1);
+		}
+
+		xDelete<int>(order);
+		xDelete<int>(riftsegments_copy);
+		xDelete<int>(riftpairs_copy);
+
+	}
+
+	/*Assign output pointer:*/
+	*priftstips=riftstips;
+	return noerr;
+}/*}}}*/
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int** riftssegments,/*{{{*/
+		int* riftsnumsegs,int** riftspairs,int* riftstips,double* x,double* y){
+
+	int noerr=1;
+	int i,j,k,k0;
+
+	double el1,el2,node1,node2,node3,node4;
+	double temp_node;
+
+	/*output: */
+	double **riftspenaltypairs    = NULL;
+	double  *riftpenaltypairs     = NULL;
+	int     *riftsnumpenaltypairs = NULL;
+
+	/*intermediary: */
+	int numsegs;
+	int* riftsegments=NULL;
+	int* riftpairs=NULL;
+	int counter;
+	double normal[2];
+	double length;
+	int    k1,k2;
+
+	/*Allocate: */
+	riftspenaltypairs=xNew<double*>(numrifts);
+	riftsnumpenaltypairs=xNew<int>(numrifts);
+
+	for(i=0;i<numrifts;i++){
+		numsegs=riftsnumsegs[i];
+		riftsegments=riftssegments[i];
+		riftpairs=riftspairs[i];
+
+		/*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;
+		for(j=0;j<(numsegs/2);j++){
+			el1=*(riftpairs+2*j+0);
+			el2=*(riftpairs+2*j+1);
+			node1=*(riftsegments+3*j+0);
+			node2=*(riftsegments+3*j+1);
+			/*Find segment index to recover node3 and node4, facing node1 and node2: */
+			k0=-1;
+			for(k=0;k<numsegs;k++){
+				if(*(riftsegments+3*k+2)==el2){
+					k0=k;
+					break;
+				}
+			}
+			node3=*(riftsegments+3*k0+0);
+			node4=*(riftsegments+3*k0+1);
+
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			if ((x[(int)node1-1]==x[(int)node4-1]) && (y[(int)node1-1]==y[(int)node4-1])){
+				/*Swap node3 and node4:*/
+				temp_node=node3;
+				node3=node4;
+				node4=temp_node;
+			}	
+			/*Ok, we have node1 facing node3, and node2 facing node4. Compute the normal to 
+			 *this segment, and its length: */
+			normal[0]=cos(atan2(x[(int)node1-1]-x[(int)node2-1],y[(int)node2-1]-y[(int)node1-1]));
+			normal[1]=sin(atan2(x[(int)node1-1]-x[(int)node2-1],y[(int)node2-1]-y[(int)node1-1]));
+			length=sqrt(pow(x[(int)node2-1]-x[(int)node1-1],(double)2)+pow(y[(int)node2-1]-y[(int)node1-1],(double)2));
+
+			/*Be careful here, we want penalty loads on each node, not on each segment. This means we cannot plug node1,
+			 * node2, node3 and node4 directly into riftpenaltypairs. We need to include node1, node2, node3 and node4, 
+			 * only once. We'll add the normals and the lengths : */
+
+			if(node1!=node3){ //exclude tips from loads
+				k1=-1;
+				for(k=0;k<counter;k++){
+					if( (*(riftpenaltypairs+k*7+0))==node1){
+						k1=k; 
+						break;
+					}
+				}
+				if(k1==-1){
+					*(riftpenaltypairs+counter*7+0)=node1;
+					*(riftpenaltypairs+counter*7+1)=node3;
+					*(riftpenaltypairs+counter*7+2)=el1;
+					*(riftpenaltypairs+counter*7+3)=el2;
+					*(riftpenaltypairs+counter*7+4)=normal[0];
+					*(riftpenaltypairs+counter*7+5)=normal[1];
+					*(riftpenaltypairs+counter*7+6)=length/2;
+					counter++;
+				}
+				else{
+					*(riftpenaltypairs+k1*7+4)+=normal[0];
+					*(riftpenaltypairs+k1*7+5)+=normal[1];
+					*(riftpenaltypairs+k1*7+6)+=length/2;
+				}
+			}
+			if(node2!=node4){
+				k2=-1;
+				for(k=0;k<counter;k++){
+					if( (*(riftpenaltypairs+k*7+0))==node2){
+						k2=k;
+						break;
+					}
+				}
+				if(k2==-1){
+					*(riftpenaltypairs+counter*7+0)=node2;
+					*(riftpenaltypairs+counter*7+1)=node4;
+					*(riftpenaltypairs+counter*7+2)=el1;
+					*(riftpenaltypairs+counter*7+3)=el2;
+					*(riftpenaltypairs+counter*7+4)=normal[0];
+					*(riftpenaltypairs+counter*7+5)=normal[1];
+					*(riftpenaltypairs+counter*7+6)=length/2;
+					counter++;
+				}
+				else{
+					*(riftpenaltypairs+k2*7+4)+=normal[0];
+					*(riftpenaltypairs+k2*7+5)+=normal[1];
+					*(riftpenaltypairs+k2*7+6)+=length/2;
+				}
+			}
+		}
+		/*Renormalize normals: */
+		for(j=0;j<counter;j++){
+			double magnitude=sqrt(pow( double(riftpenaltypairs[j*7+4]),2) + pow( double(riftpenaltypairs[j*7+5]),2) );
+			*(riftpenaltypairs+j*7+4)=*(riftpenaltypairs+j*7+4)/magnitude;
+			*(riftpenaltypairs+j*7+5)=*(riftpenaltypairs+j*7+5)/magnitude;
+		}
+
+		riftspenaltypairs[i]=riftpenaltypairs;
+		riftsnumpenaltypairs[i]=(numsegs/2-1);
+	}
+
+	/*Assign output pointers: */
+	*priftspenaltypairs=riftspenaltypairs;
+	*priftsnumpenaltypairs=riftsnumpenaltypairs;
+	return noerr;
+}/*}}}*/
+int RemoveCornersFromRifts(int** pindex,int* pnel,double** px,double** py,int* pnods,int* segments,int* segmentmarkers,int num_seg){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+	int node1,node2,node3;
+	int el;
+	double  pair[2];
+	int     pair_count=0;
+	int     triple=0;
+
+	/*Recover input: */
+	int    *index = *pindex;
+	int     nel   = *pnel;
+	double *x     = *px;
+	double *y     = *py;
+	int     nods  = *pnods;
+
+	for (i=0;i<num_seg;i++){
+		node1=*(segments+3*i+0);
+		node2=*(segments+3*i+1);
+		/*Find all elements connected to [node1 node2]: */
+		pair_count=0;
+		for (j=0;j<nel;j++){
+			if (*(index+3*j+0)==node1){
+				if ((*(index+3*j+1)==node2) || (*(index+3*j+2)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+			if (*(index+3*j+1)==node1){
+				if ((*(index+3*j+0)==node2) || (*(index+3*j+2)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+			if (*(index+3*j+2)==node1){
+				if ((*(index+3*j+0)==node2) || (*(index+3*j+1)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+		}
+		/*Ok, we have pair_count elements connected to this segment. For each of these elements, 
+		 *figure out if the third node also belongs to a segment: */
+		if ((pair_count==0) || (pair_count==1)){ //we only select the rift segments, which belong to  2 elements
+			continue;
+		}
+		else{
+			for (j=0;j<pair_count;j++){
+				el=(int)pair[j];
+				triple=0;
+				/*First find node3: */
+				if (*(index+3*el+0)==node1){
+					if (*(index+3*el+1)==node2)node3=*(index+3*el+2);
+					else node3=*(index+3*el+1);
+				}
+				if (*(index+3*el+1)==node1){
+					if (*(index+3*el+0)==node2)node3=*(index+3*el+2);
+					else node3=*(index+3*el+0);
+				}
+				if (*(index+3*el+2)==node1){
+					if (*(index+3*el+0)==node2)node3=*(index+3*el+1);
+					else node3=*(index+3*el+0);
+				}
+				/*Ok, we have node3. Does node3 belong to a segment? : */
+				for (k=0;k<num_seg;k++){
+					if ((node3==*(segments+3*k+0)) || (node3==*(segments+3*k+1))){
+						triple=1;
+						break;
+					}
+				}
+				if(triple==1){
+					/*el is a corner element: we need to split it in 3 triangles: */
+					x=xReNew<double>(x,nods,nods+1);
+					y=xReNew<double>(y,nods,nods+1);
+					x[nods]=(x[(int)node1-1]+x[(int)node2-1]+x[(int)node3-1])/3;
+					y[nods]=(y[(int)node1-1]+y[(int)node2-1]+y[(int)node3-1])/3;
+					index=xReNew<int>(index,nel*3,(nel+2*3));
+					/*First, reassign element el: */
+					*(index+3*el+0)=node1;
+					*(index+3*el+1)=node2;
+					*(index+3*el+2)=nods+1;
+					/*Other two elements: */
+					*(index+3*nel+0)=node2;
+					*(index+3*nel+1)=node3;
+					*(index+3*nel+2)=nods+1;
+
+					*(index+3*(nel+1)+0)=node3;
+					*(index+3*(nel+1)+1)=node1;
+					*(index+3*(nel+1)+2)=nods+1;
+					/*we need  to change the segment elements corresponding to el: */
+					for (k=0;k<num_seg;k++){
+						if (*(segments+3*k+2)==(el+1)){
+							if ( ((*(segments+3*k+0)==node1) && (*(segments+3*k+1)==node2)) || ((*(segments+3*k+0)==node2) && (*(segments+3*k+1)==node1))) *(segments+3*k+2)=el+1;
+							if ( ((*(segments+3*k+0)==node2) && (*(segments+3*k+1)==node3)) || ((*(segments+3*k+0)==node3) && (*(segments+3*k+1)==node2))) *(segments+3*k+2)=nel+1;
+							if ( ((*(segments+3*k+0)==node3) && (*(segments+3*k+1)==node1)) || ((*(segments+3*k+0)==node1) && (*(segments+3*k+1)==node3))) *(segments+3*k+2)=nel+2;
+						}
+					}
+
+					nods=nods+1;
+					nel=nel+2;
+					i=0;
+					break;
+				}
+			} //for (j=0;j<pair_count;j++)
+		}
+	}// for (i=0;i<num_seg;i++)
+
+	/*Assign output pointers: */
+	*pindex=index;
+	*pnel=nel;
+	*px=x;
+	*py=y;
+	*pnods=nods;
+	return noerr;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/trimesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/trimesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/TriMesh/trimesh.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*!\file:  trimesh.h
+ * \brief
+ */ 
+
+#ifndef _SHARED_TRIMESH_H
+#define _SHARED_TRIMESH_H
+
+#include <stdio.h>
+#include <math.h>
+
+//#define REAL double //took  it out because it may conflict with stdlib.h defines. put back if necessary
+int AssociateSegmentToElement(int** psegments,int nseg,int* index,int nel);
+int OrderSegments(int** psegments,int nseg, int* index,int nel);
+int GridInsideHole(double* px0,double* py0,int n,double* x,double* y);
+int FindElement(int A,int B,int* index,int nel);
+int SplitMeshForRifts(int* pnel,int** pindex,int* pnods,double** px,double** py,int* pnsegs,int** psegments,int** psegmentmarkerlist);
+int IsGridOnRift(int* riftsegments, int nriftsegs, int node);
+int GridElementsList(int** pGridElements, int* pNumGridElements,int node,double * index,int nel);
+int IsNeighbor(int el1,int el2,int* index);
+int IsOnRift(int el,int nriftsegs,int* riftsegments);
+void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index, int nsegs,int* segments);
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift,int segmentnumber, int nriftsegs,int* riftsegments, int node,int* index,int nel);
+int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel);
+int FindElement(double A,double B,int* index,int nel);
+int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs);
+int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nels);
+int OrderRifts(int** priftstips,int** riftssegments,int** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels);
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int**  riftssegments,
+		int* riftsnumsegments,int** riftspairs,int* riftstips,double* x,double* y);
+int RemoveCornersFromRifts(int** pindex,int* pnel,double** px,double** py,int* pnods,int* segments,int* segmentmarkers,int num_seg);
+int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y);
+
+#endif  /* _SHARED_TRIMESH_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.cpp	(revision 18231)
@@ -0,0 +1,57 @@
+/*! \file IssmComm.cpp
+ * \brief  file containing the methods for IssmComm.h
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmComm.h"
+#include "../../Numerics/types.h"
+#include "../../Exceptions/exceptions.h"
+
+void IssmComm::SetComm(ISSM_MPI_Comm incomm){ /*{{{*/
+
+	/*A comm is provided, we are running in parallel (this is not a module)*/
+	parallel = true;
+	comm     = incomm;
+
+}/*}}}*/
+void IssmComm::SetComm(void){ /*{{{*/
+
+	/*no comm provided, This is a matlab/python module*/
+	parallel = false;
+
+	/*No need to initialise comm*/
+
+}/*}}}*/
+ISSM_MPI_Comm IssmComm::GetComm(){  /*{{{*/
+	if(!parallel) _error_("Cannot return comm in serial mode");
+	return comm;
+}/*}}}*/
+int IssmComm::GetRank(){  /*{{{*/
+
+	int my_rank = 0;
+
+	/*for matlab and python modules*/
+	if(!parallel) return my_rank;
+
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+
+	return my_rank;
+
+}/*}}}*/
+int IssmComm::GetSize(){  /*{{{*/
+
+	int size = 1;
+
+	/*for matlab and python modules*/
+	if(!parallel) return size;
+
+	ISSM_MPI_Comm_size(comm,&size);
+
+	return size;
+
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Comm/IssmComm.h	(revision 18231)
@@ -0,0 +1,34 @@
+/* \file IssmComm.h
+ * \brief  create a class with a static comm, and static methods to access it
+ * This is a way of protecting access to the communicator.
+ */
+
+#ifndef _ISSM_COMM_H
+#define _ISSM_COMM_H
+
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../../toolkits/mpi/issmmpi.h"
+
+/*}}}*/
+
+class IssmComm {
+
+	private:
+		static ISSM_MPI_Comm comm;
+		static bool parallel;
+
+	public:
+		static void SetComm(ISSM_MPI_Comm incomm);
+		static void SetComm(void);
+		static ISSM_MPI_Comm GetComm(void);
+		static int GetRank(void);
+		static int GetSize(void);
+};
+
+#endif  /* _ISSM_COMM_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/WriteLockFile.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/WriteLockFile.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/WriteLockFile.cpp	(revision 18231)
@@ -0,0 +1,27 @@
+/*!\file:  WriteLockFile.cpp
+ * \brief
+ */ 
+#include <cstdio>
+#include "../../Exceptions/exceptions.h"
+#include "../Comm/IssmComm.h"
+#include "../Print/Print.h"
+#include <cstdio>
+
+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/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/diskio.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/diskio.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/diskio.h	(revision 18231)
@@ -0,0 +1,15 @@
+/*\file diskio.h
+ *\brief: I/O for ISSM from disk
+ */
+
+#ifndef _DISK_IO_H_
+#define _DISK_IO_H_
+
+#include <stdio.h>
+
+FILE* pfopen(char* filename,const char* format);
+FILE* pfopen0(char* filename,const char* format);
+void  pfclose(FILE* fid,char* filename);
+void WriteLockFile(char* filename);
+
+#endif	/* _IO_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfclose.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfclose.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfclose.cpp	(revision 18231)
@@ -0,0 +1,19 @@
+/*!\file:  pfclose.cpp
+ * \brief fclose wrapper for parallel solution
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../../shared.h"
+
+void pfclose(FILE* fid,char* filename){
+
+	/*Close file handle: */
+	_assert_(fid);
+	if(fclose(fid)!=0)_error_("could not close file " << filename);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfopen.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfopen.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Disk/pfopen.cpp	(revision 18231)
@@ -0,0 +1,46 @@
+/*!\file:  pfopen.cpp
+ * \brief fopen wrapper for parallel solution
+ */ 
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../Print/Print.h"
+#include "../Comm/IssmComm.h"
+#include "../../Exceptions/exceptions.h"
+
+FILE* pfopen0(char* filename,const char* format){
+
+	FILE* fid=NULL;
+
+	/*recover my_rank:*/
+	int my_rank  = IssmComm::GetRank();
+	if(my_rank) _error_("This function should only be called by cpu 0");
+
+	/*Open handle to data on disk*/
+	fid = fopen(filename,format);
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing");
+
+	return fid;
+}
+FILE* pfopen(char* filename,const char* format){
+
+	FILE* fid=NULL;
+
+	/*recover my_rank:*/
+	int my_rank  = IssmComm::GetRank();
+	int num_proc = IssmComm::GetSize();
+
+	/*Open handle to data on disk (one by one to avoid errors)*/
+	for(int i=0;i<num_proc;i++){
+		if(my_rank==i) fid = fopen(filename,format);
+		ISSM_MPI_Barrier(IssmComm::GetComm());
+	}
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing");
+
+	return fid;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/Print.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/Print.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/Print.h	(revision 18231)
@@ -0,0 +1,40 @@
+/*\file Print.h
+ *\brief: print I/O for ISSM
+ */
+
+#ifndef _ISSM_PRINT_H_
+#define _ISSM_PRINT_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include <string>
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+
+using namespace std;
+/*macros:*/
+/* _printf_{{{*/
+/* macro to print some string on all cpus */
+#define _printf_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs; \
+	  PrintfFunctionOnAllCpus(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+/* _printf0_ {{{*/
+/* macro to print some string only on cpu 0 */
+#define _printf0_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs; \
+	  PrintfFunctionOnCpu0(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+
+/*functions: */
+int PrintfFunctionOnCpu0(const string & message);
+int PrintfFunctionOnAllCpus(const string & message);
+
+#endif	
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/PrintfFunction.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/PrintfFunction.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/Print/PrintfFunction.cpp	(revision 18231)
@@ -0,0 +1,46 @@
+/*\file PrintfFunction.c
+ *\brief: this function is used by the _printf_ macro, to take into account the 
+ *fact we may be running on a cluster. 
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdarg.h>
+#include <cstdio>
+#ifdef _HAVE_ANDROID_NDK_
+#include <android/log.h>
+#endif
+#include "./Print.h"
+#include "../Comm/IssmComm.h"
+#include "../../String/sharedstring.h"
+#include "../../MemOps/MemOps.h"
+
+int PrintfFunctionOnCpu0(const string & message){
+	int  my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+		#ifdef _HAVE_ANDROID_JNI_
+		__android_log_print(ANDROID_LOG_INFO, "Native",message.c_str());
+		#else
+		ApiPrintf(message.c_str());
+		#endif
+	}
+	return 1;
+}
+int PrintfFunctionOnAllCpus(const string & message){
+
+	#ifdef _HAVE_ANDROID_JNI_
+	__android_log_print(ANDROID_LOG_INFO, "Native",message.c_str());
+	#else
+	ApiPrintf(message.c_str());
+	#endif
+
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/io.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/io.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/io/io.h	(revision 18231)
@@ -0,0 +1,18 @@
+/*\file io.h
+ *\brief: I/O for ISSM
+ */
+
+#ifndef _ISSM_IO_H_
+#define _ISSM_IO_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include "./Disk/diskio.h"
+#include "./Print/Print.h"
+#include "./Comm/IssmComm.h"
+
+#endif	/* _IO_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/shared.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/shared.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/shared/shared.h	(revision 18231)
@@ -0,0 +1,24 @@
+/* \file shared.h
+ * \brief: header file for all shared  routines.
+ */
+
+#ifndef _SHARED_H_
+#define _SHARED_H_
+
+#include "./FSanalyticals/fsanalyticals.h"
+#include "./MemOps/MemOps.h"
+#include "./Bamg/shared.h"
+#include "./Elements/elements.h"
+#include "./Enum/Enum.h"
+#include "./Exceptions/exceptions.h"
+#include "./io/io.h"
+#include "./Exp/exp.h"
+#include "./Matrix/matrix.h"
+#include "./Numerics/numerics.h"
+#include "./Sorting/sorting.h"
+#include "./String/sharedstring.h"
+#include "./Threads/issm_threads.h"
+#include "./TriMesh/trimesh.h"
+#include "./LatLong/latlong.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/convergence.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/convergence.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/convergence.cpp	(revision 18231)
@@ -0,0 +1,146 @@
+/*!\file: convergence.cpp
+ * \brief: figure out if convergence has been reached
+ */ 
+
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/shared.h"
+
+void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,Parameters* parameters){
+
+	/*output*/
+	bool converged=false;
+
+	/*intermediary*/
+	Vector<IssmDouble>* KU=NULL;
+	Vector<IssmDouble>* KUF=NULL;
+	Vector<IssmDouble>* KUold=NULL;
+	Vector<IssmDouble>* KUoldF=NULL;
+	Vector<IssmDouble>* duf=NULL;
+	IssmDouble ndu,nduinf,nu;
+	IssmDouble nKUF;
+	IssmDouble nKUoldF;
+	IssmDouble nF;
+	IssmDouble solver_residue,res;
+
+	/*convergence options*/
+	IssmDouble eps_res;
+	IssmDouble eps_rel;
+	IssmDouble eps_abs;
+	IssmDouble yts;
+
+	if(VerboseModule()) _printf0_("   checking convergence\n");
+
+	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from 
+	 * the get go: */
+	if(uf->IsEmpty()){
+		*pconverged=true;
+		return;
+	}
+
+	/*get convergence options*/
+	parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*Display solver caracteristics*/
+	if (VerboseConvergence()){
+
+		//compute KUF = KU - F = K*U - F
+		KU=uf->Duplicate(); Kff->MatMult(uf,KU);
+		KUF=KU->Duplicate(); KU->Copy(KUF); KUF->AYPX(pf,-1.0);
+
+		//compute norm(KUF), norm(F) and residue
+		nKUF=KUF->Norm(NORM_TWO);
+		nF=pf->Norm(NORM_TWO);
+		solver_residue=nKUF/nF;
+		_printf0_("\n" << "   solver residue: norm(KU-F)/norm(F)=" << solver_residue << "\n");
+
+		//clean up
+		delete KU;
+		delete KUF;
+	}
+
+	/*Force equilibrium (Mandatory)*/
+
+	//compute K[n]U[n-1]F = K[n]U[n-1] - F
+	_assert_(uf); _assert_(Kff);
+	KUold=uf->Duplicate(); Kff->MatMult(old_uf,KUold);
+	KUoldF=KUold->Duplicate();KUold->Copy(KUoldF); KUoldF->AYPX(pf,-1.0);
+	nKUoldF=KUoldF->Norm(NORM_TWO);
+	nF=pf->Norm(NORM_TWO);
+	res=nKUoldF/nF;
+	if (xIsNan<IssmDouble>(res)){
+		_printf0_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f\n");
+		_error_("mechanical equilibrium convergence criterion is NaN!");
+	}
+
+	//clean up
+	delete KUold;
+	delete KUoldF;
+
+	//print
+	if(res<eps_res){
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<< " < "<<eps_res*100<<" %\n");
+		converged=true;
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<<" > "<<eps_res*100<<" %\n");
+		converged=false;
+	}
+
+	/*Relative criterion (optional)*/
+	if (!xIsNan<IssmDouble>(eps_rel) || (VerboseConvergence())){
+
+		//compute norm(du)/norm(u)
+		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
+		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
+
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		delete duf;
+
+		//print
+		if (!xIsNan<IssmDouble>(eps_rel)){
+			if((ndu/nu)<eps_rel){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+			}
+			else{ 
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+				converged=false;
+			}
+		}
+		else _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " %\n");
+
+	}
+
+	/*Absolute criterion (Optional) = max(du)*/
+	if (!xIsNan<IssmDouble>(eps_abs) || (VerboseConvergence())){
+
+		//compute max(du)
+		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
+		ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		delete duf;
+
+		//print
+		if (!xIsNan<IssmDouble>(eps_abs)){
+			if ((nduinf*yts)<eps_abs){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " < " << eps_abs << " m/yr\n");
+			}
+			else{
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " > " << eps_abs << " m/yr\n");
+				converged=false;
+			}
+		}
+		else  _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " m/yr\n");
+
+	}
+
+	/*assign output*/
+	*pconverged=converged;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 18231)
@@ -0,0 +1,35 @@
+/*!\file: solutionsequence_adjoint_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_adjoint_linear(FemModel* femmodel){
+	/*This is axactly the same solutionsequence as solutionsequence_linear except that Reduceloadfromgtofx and Mergesolutionfromftogx
+	 * use the flag "true" so that all spc are taken as 0*/
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel);
+	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+	Reduceloadx(pf, Kfs, ys,true); delete Kfs; //true means spc = 0
+	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); delete Kff; delete pf; delete df;
+	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters,true); delete ys; //true means spc0
+	InputUpdateFromSolutionx(femmodel,ug);
+	delete ug; delete uf;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 18231)
@@ -0,0 +1,282 @@
+/*!\file: solutionsequence_hydro_nonlinear.cpp
+ * \brief: core of the hydro solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+/*FIXME, dirty hack to get the solutionsequence linear needed to compute the slopes*/
+#include "../solutionsequences/solutionsequences.h"
+
+void solutionsequence_hydro_nonlinear(FemModel* femmodel){
+	/*solution : */
+	Vector<IssmDouble>* ug_sed=NULL; 
+	Vector<IssmDouble>* uf_sed=NULL; 
+	Vector<IssmDouble>* uf_sed_sub_iter=NULL; 
+	Vector<IssmDouble>* ug_sed_main_iter=NULL;
+
+	Vector<IssmDouble>* ug_epl=NULL; 
+	Vector<IssmDouble>* uf_epl=NULL;
+	Vector<IssmDouble>* uf_epl_sub_iter=NULL; 
+	Vector<IssmDouble>* ug_epl_sub_iter=NULL;
+	Vector<IssmDouble>* ug_epl_main_iter=NULL;
+
+	Vector<IssmDouble>* ys=NULL; 
+	Vector<IssmDouble>* dug=NULL;
+	Vector<IssmDouble>* duf=NULL;
+
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
+
+	HydrologyDCInefficientAnalysis* inefanalysis = NULL;
+	HydrologyDCEfficientAnalysis* effanalysis = NULL;
+	
+	bool       sedconverged,eplconverged,hydroconverged;
+	bool       isefficientlayer;
+	int        constraints_converged;
+	int        num_unstable_constraints;
+	int        sedcount,eplcount,hydrocount;
+	int        hydro_maxiter;
+	IssmDouble sediment_kmax;
+	IssmDouble eps_hyd;
+	IssmDouble ndu_sed,nu_sed;
+	IssmDouble ndu_epl,nu_epl;
+
+	/*Recover parameters: */
+	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+	femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	femmodel->parameters->FindParam(&hydro_maxiter,HydrologydcMaxIterEnum);
+	femmodel->parameters->FindParam(&eps_hyd,HydrologydcRelTolEnum);
+
+	hydrocount=1;
+	hydroconverged=false;
+	/*We don't need the outer loop if only one layer is used*/
+	if(!isefficientlayer) hydroconverged=true;
+
+	/*Retrieve inputs as the initial state for the non linear iteration*/
+	GetSolutionFromInputsx(&ug_sed,femmodel);	
+	Reducevectorgtofx(&uf_sed, ug_sed, femmodel->nodes,femmodel->parameters);
+
+	if(isefficientlayer) {
+		inefanalysis = new HydrologyDCInefficientAnalysis();
+		effanalysis = new HydrologyDCEfficientAnalysis();
+		femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
+		GetSolutionFromInputsx(&ug_epl,femmodel);
+		/*Initialize the element mask*/
+		inefanalysis->ElementizeEplMask(femmodel);
+	}
+	/*The real computation starts here, outermost loop is on the two layer system*/
+	for(;;){
+
+		sedcount=1;
+		eplcount=1;
+
+		/*If there is two layers we need an outer loop value to compute convergence*/
+		if(isefficientlayer){
+			ug_sed_main_iter=ug_sed->Duplicate();
+			ug_sed->Copy(ug_sed_main_iter);
+			ug_epl_main_iter=ug_epl->Duplicate();
+			ug_epl->Copy(ug_epl_main_iter);
+		}
+		/*Loop on sediment layer to deal with transfer and head value*/
+		femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+		InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+		InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
+		femmodel->UpdateConstraintsx();
+		femmodel->parameters->SetParam(HydrologySedimentEnum,HydrologyLayerEnum);
+		
+		/*Reset constraint on the ZigZag Lock, this thing doesn't work, it have to disapear*/
+		ResetConstraintsx(femmodel);
+
+		/* {{{ *//*Treating the sediment*/
+		for(;;){
+			sedconverged=false;
+			uf_sed_sub_iter=uf_sed->Duplicate();_assert_(uf_sed_sub_iter);
+			uf_sed->Copy(uf_sed_sub_iter);
+			/* {{{ *//*Loop on the sediment layer to deal with the penalization*/
+			for(;;){
+				/* {{{ *//*Core of the computation*/
+				if(VerboseSolution()) _printf0_("Building Sediment Matrix...\n");
+				SystemMatricesx(&Kff,&Kfs,&pf,&df,&sediment_kmax,femmodel);
+				CreateNodalConstraintsx(&ys,femmodel->nodes,HydrologyDCInefficientAnalysisEnum);
+				Reduceloadx(pf,Kfs,ys); delete Kfs;
+				delete uf_sed;
+				Solverx(&uf_sed,Kff,pf,uf_sed_sub_iter,df,femmodel->parameters);
+				delete Kff; delete pf; delete df;
+				delete ug_sed;
+				Mergesolutionfromftogx(&ug_sed,uf_sed,ys,femmodel->nodes,femmodel->parameters); delete ys;
+				InputUpdateFromSolutionx(femmodel,ug_sed);
+				ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+				/* }}} */
+				if (!sedconverged){
+					if(VerboseConvergence()) _printf0_("   # Sediment unstable constraints = " << num_unstable_constraints << "\n");
+					if(num_unstable_constraints==0) sedconverged = true;
+					if (sedcount>=hydro_maxiter){
+						_error_("   maximum number of Sediment iterations (" << hydro_maxiter << ") exceeded");
+					}
+				}
+				/*Add an iteration and get out of the loop if the penalisation is converged*/
+				sedcount++;
+				if(sedconverged)break;
+			}
+		
+			/* }}} *//*End of the sediment penalization loop*/
+			/*Update EPL mask*/
+			if(isefficientlayer){
+				inefanalysis->ElementizeEplMask(femmodel);
+			}
+			sedconverged=false;
+			
+			/*Checking convegence on the value of the sediment head*/
+			duf=uf_sed_sub_iter->Duplicate();_assert_(duf);
+			uf_sed_sub_iter->Copy(duf);
+			duf->AYPX(uf_sed,-1.0);
+			ndu_sed=duf->Norm(NORM_TWO);
+			delete duf;
+			nu_sed=uf_sed_sub_iter->Norm(NORM_TWO);
+			if (xIsNan<IssmDouble>(ndu_sed) || xIsNan<IssmDouble>(nu_sed)) _error_("convergence criterion is NaN!");
+			if (ndu_sed==0.0 && nu_sed==0.0) nu_sed=1.0e-6; /*Hacking the case where the layer is empty*/
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Inner Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << "%, aiming lower than " << eps_hyd*10*100 << " %\n");
+			if((ndu_sed/nu_sed)<eps_hyd*10.){
+				if(VerboseConvergence()) _printf0_("   # Inner sediment convergence achieve \n");
+				sedconverged=true;
+			}
+			delete uf_sed_sub_iter;
+			if(sedconverged){
+				femmodel->parameters->SetParam(sediment_kmax,HydrologySedimentKmaxEnum);
+				InputUpdateFromConstantx(femmodel,sedconverged,ConvergedEnum);
+				InputUpdateFromSolutionx(femmodel,ug_sed);
+				InputUpdateFromConstantx(femmodel,sediment_kmax,HydrologySedimentKmaxEnum);
+				break;
+			}
+		}
+		/* }}} *//*End of the global sediment loop*/
+		/* {{{ *//*Now dealing with the EPL in the same way*/
+		if(isefficientlayer){
+			femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
+			/*updating mask*/
+			femmodel->HydrologyEPLupdateDomainx();
+			InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+			InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
+			femmodel->parameters->SetParam(HydrologyEfficientEnum,HydrologyLayerEnum);
+
+			for(;;){
+				eplconverged=false;
+				ug_epl_sub_iter=ug_epl->Duplicate();_assert_(ug_epl_sub_iter);
+				ug_epl->Copy(ug_epl_sub_iter);
+				/* {{{ *//*Retrieve the EPL head slopes and compute EPL Thickness*/
+				if(VerboseSolution()) _printf0_("computing EPL Head slope...\n");
+				inefanalysis->ElementizeEplMask(femmodel);
+				femmodel->SetCurrentConfiguration(L2ProjectionEPLAnalysisEnum);
+				femmodel->UpdateConstraintsL2ProjectionEPLx();
+				femmodel->parameters->SetParam(EplHeadSlopeXEnum,InputToL2ProjectEnum);
+				solutionsequence_linear(femmodel);
+				femmodel->parameters->SetParam(EplHeadSlopeYEnum,InputToL2ProjectEnum);
+				solutionsequence_linear(femmodel);
+				femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
+
+				effanalysis->ComputeEPLThickness(femmodel);
+
+				//updating mask after the computation of the epl thickness (Allow to close too thin EPL)
+				femmodel->HydrologyEPLupdateDomainx();
+				inefanalysis->ElementizeEplMask(femmodel);
+				/* }}} */
+					
+				if(VerboseSolution()) _printf0_("Building EPL Matrix...\n");
+				SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+				CreateNodalConstraintsx(&ys,femmodel->nodes,HydrologyDCEfficientAnalysisEnum);
+				Reduceloadx(pf,Kfs,ys); delete Kfs;
+				delete uf_epl;
+				Solverx(&uf_epl,Kff,pf,uf_epl_sub_iter,df,femmodel->parameters);
+				delete Kff; delete pf; delete df;
+				delete uf_epl_sub_iter;
+				uf_epl_sub_iter=uf_epl->Duplicate();
+				uf_epl->Copy(uf_epl_sub_iter);
+				delete ug_epl; 
+				Mergesolutionfromftogx(&ug_epl,uf_epl,ys,femmodel->nodes,femmodel->parameters); delete ys;
+				InputUpdateFromSolutionx(femmodel,ug_epl);
+				ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+						
+				dug=ug_epl_sub_iter->Duplicate();_assert_(dug);
+				ug_epl_sub_iter->Copy(dug);
+				dug->AYPX(ug_epl,-1.0);
+				ndu_epl=dug->Norm(NORM_TWO);
+				delete dug;
+				nu_epl=ug_epl_sub_iter->Norm(NORM_TWO);
+				if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("convergence criterion is NaN!");
+				if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Inner EPL Convergence criterion:" << ndu_epl/nu_epl*100 << "%, aiming lower than " << eps_hyd*10*100 << " %\n");
+				if((ndu_epl/nu_epl)<eps_hyd*10.) eplconverged=true;
+				if (eplcount>=hydro_maxiter){
+					_error_("   maximum number of EPL iterations (" << hydro_maxiter << ") exceeded");
+				}
+				eplcount++;
+				
+				delete ug_epl_sub_iter;
+				if(eplconverged){
+					if(VerboseSolution()) _printf0_("eplconverged...\n");
+					InputUpdateFromConstantx(femmodel,eplconverged,ConvergedEnum);
+					InputUpdateFromSolutionx(femmodel,ug_epl);
+					break;
+				}
+			}
+		}
+		/* }}} */ /*End of the global EPL loop*/
+
+		/* {{{ */ /*Now dealing with the convergence of the whole system*/
+		if(!hydroconverged){
+			//compute norm(du)/norm(u)
+			dug=ug_sed_main_iter->Duplicate(); _assert_(dug);
+			ug_sed_main_iter->Copy(dug);	
+			dug->AYPX(ug_sed,-1.0);
+			ndu_sed=dug->Norm(NORM_TWO); 
+			delete dug;
+			nu_sed=ug_sed_main_iter->Norm(NORM_TWO);
+			delete ug_sed_main_iter;
+			if (xIsNan<IssmDouble>(ndu_sed) || xIsNan<IssmDouble>(nu_sed)) _error_("Sed convergence criterion is NaN!");
+			if (ndu_sed==0.0 && nu_sed==0.0) nu_sed=1.0e-6; /*Hacking the case where the Sediment is used but empty*/
+			dug=ug_epl_main_iter->Duplicate();_assert_(dug); 
+			ug_epl_main_iter->Copy(dug); 
+			dug->AYPX(ug_epl,-1.0);
+			ndu_epl=dug->Norm(NORM_TWO); 
+			delete dug;
+			nu_epl=ug_epl_main_iter->Norm(NORM_TWO);
+			delete ug_epl_main_iter;
+			if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("EPL convergence criterion is NaN!");
+			if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
+			if (!xIsNan<IssmDouble>(eps_hyd)){
+				if ((ndu_epl/nu_epl)<eps_hyd && (ndu_sed/nu_sed)<(eps_hyd)){
+					if (VerboseConvergence()) _printf0_(setw(50) << left << "   Converged after, " << hydrocount << " iterations \n");
+					hydroconverged=true;
+				}
+				else{ 
+					if(VerboseConvergence()) _printf0_(setw(50) << left << "   Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << "%, aiming lower than " << eps_hyd*100 << " %\n");
+					if(VerboseConvergence()) _printf0_(setw(50) << left << "   EPL Convergence criterion:" << ndu_epl/nu_epl*100 << "%, aiming lower than " << eps_hyd*100 << " %\n");
+					hydroconverged=false;
+				}
+			}
+			else _printf0_(setw(50) << left << "   Convergence criterion:" << ndu_sed/nu_sed*100 << " %\n");
+			if (hydrocount>=hydro_maxiter){
+				_error_("   maximum number for hydrological global iterations (" << hydro_maxiter << ") exceeded");
+			}
+		}
+		hydrocount++;
+		if(hydroconverged)break;
+	}
+	/* }}} */
+	if(isefficientlayer)InputUpdateFromSolutionx(femmodel,ug_epl);
+	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+	InputUpdateFromSolutionx(femmodel,ug_sed);
+	/*Free ressources: */
+	delete ug_epl;
+	delete ug_sed;
+	delete uf_sed;
+	delete uf_epl;
+	delete uf_epl_sub_iter;
+	delete inefanalysis;
+	delete effanalysis;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la.cpp	(revision 18231)
@@ -0,0 +1,123 @@
+/*!\file: solutionsequence_la.cpp
+ * \brief: numerical core of la solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_la(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff     = NULL;
+	Matrix<IssmDouble>*  Kfs     = NULL;
+	Vector<IssmDouble>*  ug      = NULL;
+	Vector<IssmDouble>*  uf      = NULL;
+	Vector<IssmDouble>*  pf      = NULL;
+	Vector<IssmDouble>*  df      = NULL;
+	Vector<IssmDouble>*  ys      = NULL;
+	Vector<IssmDouble>*  pug     = NULL;
+	Vector<IssmDouble>*  pug_old = NULL;
+	IssmDouble           eps_rel,r,theta; // 0<theta<.5   -> .15<theta<.45
+	int                  configuration_type,max_nonlinear_iterations;
+	bool                 vel_converged      = false;
+	bool                 pressure_converged = false;
+
+	/*Create analysis*/
+	StressbalanceAnalysis* stressanalysis   = new StressbalanceAnalysis();
+	UzawaPressureAnalysis* pressureanalysis = new UzawaPressureAnalysis();
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+
+	/*Update constraints*/
+	femmodel->UpdateConstraintsx();
+
+	/*Convergence criterion*/
+	int  count = 0;
+	Vector<IssmDouble>* vel     = NULL;
+	Vector<IssmDouble>* vel_old = NULL;
+	GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
+	GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+
+	while(true){
+		count++;
+
+		/*save pointer to old velocity*/
+		delete vel_old;vel_old=vel;
+		delete pug_old;pug_old=pug; 
+		pressure_converged=false; vel_converged=false;
+
+		/*Solve KU=F*/
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		delete Kff; delete pf; delete df;
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
+
+		/*Update solution*/
+		InputUpdateFromSolutionx(femmodel,ug); delete ug;
+		GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
+
+		femmodel->SetCurrentConfiguration(UzawaPressureAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		delete Kff; delete pf; delete df;
+		Mergesolutionfromftogx(&pug, uf,ys,femmodel->nodes,femmodel->parameters); delete uf; delete ys;
+
+		/*Update solution*/
+		InputUpdateFromSolutionx(femmodel,pug); delete pug;
+		GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+
+		/*Check for convergence*/
+		Vector<IssmDouble>* dvel=vel_old->Duplicate(); vel_old->Copy(dvel); dvel->AYPX(vel,-1.0);
+		IssmDouble ndu=dvel->Norm(NORM_TWO);   delete dvel;
+		IssmDouble nu =vel_old->Norm(NORM_TWO);
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+		if((ndu/nu)<eps_rel){
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+			vel_converged=true;
+		}
+		else{ 
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+			vel_converged=false;
+		}
+		Vector<IssmDouble>* dup=pug_old->Duplicate(); pug_old->Copy(dup); dup->AYPX(pug,-1.0);
+		IssmDouble ndp=dup->Norm(NORM_TWO);   delete dup;
+		IssmDouble np =pug_old->Norm(NORM_TWO);
+		if (xIsNan<IssmDouble>(ndp) || xIsNan<IssmDouble>(np)) _error_("convergence criterion is NaN!");
+		if((ndp/np)<eps_rel){
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(dp)/norm(p)" << ndp/np*100 << " < " << eps_rel*100 << " %\n");
+			pressure_converged=true;
+		}
+		else{ 
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(dp/)/norm(p)" << ndp/np*100 << " > " << eps_rel*100 << " %\n");
+			pressure_converged=false;
+		}
+
+		if(pressure_converged && vel_converged) break;
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			break;
+		}
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	delete pug;  
+	delete pug_old;  
+	delete vel;  
+	delete vel_old;  
+	delete stressanalysis;
+	delete pressureanalysis;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la_theta.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 18231)
@@ -0,0 +1,102 @@
+/*!\file: solutionsequence_la_theta.cpp
+ * \brief: numerical core of la_theta solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_la_theta(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff    = NULL;
+	Matrix<IssmDouble>*  Kfs    = NULL;
+	Vector<IssmDouble>*  ug_old = NULL;
+	Vector<IssmDouble>*  ug     = NULL;
+	Vector<IssmDouble>*  uf     = NULL;
+	Vector<IssmDouble>*  pf     = NULL;
+	Vector<IssmDouble>*  df     = NULL;
+	Vector<IssmDouble>*  ys     = NULL;
+	IssmDouble           eps_rel,r,theta; // 0<theta<.5   -> .15<theta<.45
+	int                  configuration_type,max_nonlinear_iterations;
+
+	/*Create analysis*/
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&r,AugmentedLagrangianREnum);
+	femmodel->parameters->FindParam(&theta,AugmentedLagrangianThetaEnum);
+
+	/*Update constraints and initialize d and tau if necessary*/
+	femmodel->UpdateConstraintsx();
+	analysis->InitializeXTH(femmodel->elements,femmodel->parameters);
+
+	/*Convergence criterion*/
+	int  count = 0;
+	GetSolutionFromInputsx(&ug,femmodel);
+	Vector<IssmDouble>* vx     = NULL;
+	Vector<IssmDouble>* vx_old = NULL;
+	GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexEnum);
+
+	while(true){
+		count++;
+
+		/*save pointer to old velocity*/
+		delete ug_old;ug_old=ug;
+		delete vx_old;vx_old=vx;
+
+		/*Calculate d*/
+		if(theta>0.){
+			analysis->InputUpdateFromSolutionFSXTH_d(femmodel->elements,femmodel->parameters);
+		}
+
+		/*Solve KU=F*/
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		delete Kff; delete pf; delete df;
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
+
+		/*Update solution*/
+		InputUpdateFromSolutionx(femmodel,ug); 
+
+		/*Update d and tau accordingly*/
+		analysis->InputUpdateFromSolutionFSXTH_d(  femmodel->elements,femmodel->parameters);
+		analysis->InputUpdateFromSolutionFSXTH_tau(femmodel->elements,femmodel->parameters);
+		GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexEnum);
+
+		/*Check for convergence*/
+		//Vector<IssmDouble>* dug=ug_old->Duplicate(); ug_old->Copy(dug); dug->AYPX(ug,-1.0);
+		//IssmDouble ndu=dug->Norm(NORM_TWO);   delete dug;
+		//IssmDouble nu =ug_old->Norm(NORM_TWO);
+		Vector<IssmDouble>* dvx=vx_old->Duplicate(); vx_old->Copy(dvx); dvx->AYPX(vx,-1.0);
+		IssmDouble ndu=dvx->Norm(NORM_TWO);   delete dvx;
+		IssmDouble nu =vx_old->Norm(NORM_TWO);
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+		if((ndu/nu)<eps_rel){
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+			break;
+		}
+		else{ 
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+		}
+
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			break;
+		}
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	delete ug;  
+	delete ug_old;  
+	delete vx;  
+	delete vx_old;  
+	delete analysis;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_linear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 18231)
@@ -0,0 +1,38 @@
+/*!\file: solutionsequence_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_linear(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+	SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+	Reduceloadx(pf, Kfs, ys); delete Kfs;
+	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+	delete Kff; delete pf; delete df;
+//#ifdef  _HAVE_ADOLC_
+//        for (int i =0; i<uf->svector->M; ++i) {
+//          ADOLC_DUMP_MACRO(uf->svector->vector[i]);
+//        }
+//#endif
+	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
+	InputUpdateFromSolutionx(femmodel,ug); 
+	delete ug;  
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_newton.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 18231)
@@ -0,0 +1,115 @@
+/*!\file: solutionsequence_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_newton(FemModel* femmodel){
+
+	/*intermediary: */
+	bool   converged;
+	int    count,newton;
+	IssmDouble kmax;
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* old_ug = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* duf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* pJf    = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
+
+	/*parameters:*/
+	int max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
+	femmodel->UpdateConstraintsx();
+
+	count=1;
+	converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug,femmodel);
+	Reducevectorgtofx(&uf,ug,femmodel->nodes,femmodel->parameters);
+
+	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+	InputUpdateFromSolutionx(femmodel,ug);
+
+	for(;;){
+
+		delete old_ug;old_ug=ug;
+		delete old_uf;old_uf=uf;
+
+		/*Solver forward model*/
+		if(count==1 || newton==2){
+			SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+			CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+			Reduceloadx(pf,Kfs,ys);delete Kfs;
+			Solverx(&uf,Kff,pf,old_uf,df,femmodel->parameters);delete df; delete Kff; delete pf;
+			Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
+			InputUpdateFromSolutionx(femmodel,ug);
+			delete old_ug;old_ug=ug;
+			delete old_uf;old_uf=uf;
+		}
+		uf=old_uf->Duplicate(); old_uf->Copy(uf);
+
+		/*Prepare next iteration using Newton's method*/
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,&kmax,femmodel);delete df;
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf,Kfs,ys);delete Kfs;
+
+		pJf=pf->Duplicate();
+		Kff->MatMult(uf,pJf);
+		pJf->Scale(-1.0); pJf->AXPY(pf,+1.0);
+
+		CreateJacobianMatrixx(&Jff,femmodel,kmax);
+		Solverx(&duf,Jff,pJf,NULL,NULL,femmodel->parameters); delete Jff; delete pJf;
+		uf->AXPY(duf, 1.0); delete duf;
+		Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
+		InputUpdateFromSolutionx(femmodel,ug);
+
+		/*Check convergence*/
+		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); 
+		delete Kff; delete pf;
+		if(converged==true){	
+			int step; IssmDouble time;
+			bool max_iteration_state=false;
+			femmodel->parameters->FindParam(&time,TimeEnum);
+			femmodel->parameters->FindParam(&step,StepEnum);
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, step,time));
+			break;
+		}
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of Newton iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			int step; IssmDouble time;
+			bool max_iteration_state=true;
+			femmodel->parameters->FindParam(&time,TimeEnum);
+			femmodel->parameters->FindParam(&step,StepEnum);
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, step, time));
+			break;
+		}
+
+		count++;
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	/*clean-up*/
+	delete uf;
+	delete ug;
+	delete old_ug;
+	delete old_uf;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 18231)
@@ -0,0 +1,117 @@
+/*!\file: solutionsequence_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
+
+	Loads* savedloads=NULL;
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+
+	/*parameters:*/
+	int min_mechanical_constraints;
+	int max_nonlinear_iterations;
+	int configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	/*Were loads requested as output? : */
+	if(conserve_loads){
+		savedloads = static_cast<Loads*>(femmodel->loads->Copy());
+	}
+
+	count=1;
+	converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug,femmodel);
+	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
+
+	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+	InputUpdateFromSolutionx(femmodel,ug);
+
+	for(;;){
+
+		//save pointer to old velocity
+		delete old_uf;old_uf=uf;
+		delete ug;
+
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
+
+		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); delete Kff; delete pf; delete df;
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+		InputUpdateFromSolutionx(femmodel,ug);
+
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+		if(VerboseConvergence()) _printf0_("   number of unstable constraints: " << num_unstable_constraints << "\n");
+
+		//rift convergence
+		if (!constraints_converged) {
+			if (converged){
+				if (num_unstable_constraints <= min_mechanical_constraints) converged=true;
+				else converged=false;
+			}
+		}
+
+		/*Increase count: */
+		count++;
+		if(converged==true){
+			bool max_iteration_state=false;
+			int step; IssmDouble time;
+			femmodel->parameters->FindParam(&time,TimeEnum);
+			femmodel->parameters->FindParam(&step,StepEnum);
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, step, time));
+			break;
+		}
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			converged=true;
+			InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+			InputUpdateFromSolutionx(femmodel,ug);		
+			bool max_iteration_state=true;
+			int step; IssmDouble time;
+			femmodel->parameters->FindParam(&time,TimeEnum);
+			femmodel->parameters->FindParam(&step,StepEnum);
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, step, time));
+			break;
+		}
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	/*clean-up*/
+	if(conserve_loads){
+		delete femmodel->loads;
+		femmodel->loads=savedloads;
+	}
+	delete uf;
+	delete ug;
+	delete old_uf;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 18231)
@@ -0,0 +1,100 @@
+/*!\file: solutionsequence_FScoupling_nonlinear.cpp
+ * \brief: core of the coupling between FS and SSAHO
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Matrix<IssmDouble> *Kff_horiz    = NULL;
+	Matrix<IssmDouble> *Kfs_horiz    = NULL;
+	Vector<IssmDouble> *ug_horiz     = NULL;
+	Vector<IssmDouble> *uf_horiz     = NULL;
+	Vector<IssmDouble> *old_uf_horiz = NULL;
+	Vector<IssmDouble> *pf_horiz     = NULL;
+	Vector<IssmDouble> *df_horiz     = NULL;
+	Matrix<IssmDouble> *Kff_vert     = NULL;
+	Matrix<IssmDouble> *Kfs_vert     = NULL;
+	Vector<IssmDouble> *ug_vert      = NULL;
+	Vector<IssmDouble> *uf_vert      = NULL;
+	Vector<IssmDouble> *pf_vert      = NULL;
+	Vector<IssmDouble> *df_vert      = NULL;
+	Vector<IssmDouble> *ys           = NULL;
+	bool converged;
+	int  count;
+
+	/*parameters:*/
+	int  min_mechanical_constraints;
+	int  max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->UpdateConstraintsx();
+
+	count=1;
+	converged=false;
+
+	/*First get ug_horiz:*/
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	GetSolutionFromInputsx(&ug_horiz,femmodel);
+	Reducevectorgtofx(&uf_horiz, ug_horiz, femmodel->nodes,femmodel->parameters);
+
+	for(;;){
+
+		/*First stressbalance horiz:*/
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+		//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+		InputUpdateFromSolutionx(femmodel,ug_horiz);
+		delete ug_horiz;
+
+		//save pointer to old velocity
+		delete old_uf_horiz; old_uf_horiz=uf_horiz;
+
+		/*solve: */
+		SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf_horiz, Kfs_horiz, ys); delete Kfs_horiz;
+		Solverx(&uf_horiz, Kff_horiz, pf_horiz, old_uf_horiz, df_horiz,femmodel->parameters);
+		Mergesolutionfromftogx(&ug_horiz, uf_horiz,ys,femmodel->nodes,femmodel->parameters); delete ys;
+		InputUpdateFromSolutionx(femmodel,ug_horiz);
+
+		convergence(&converged,Kff_horiz,pf_horiz,uf_horiz,old_uf_horiz,femmodel->parameters); delete Kff_horiz; delete pf_horiz; delete df_horiz;
+
+		/*Second compute vertical velocity: */
+		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+		/*solve: */
+		SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert, &df_vert,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf_vert, Kfs_vert, ys); delete Kfs_vert;
+		Solverx(&uf_vert, Kff_vert, pf_vert, NULL, df_vert,femmodel->parameters); delete Kff_vert; delete pf_vert; delete df_vert;
+		Mergesolutionfromftogx(&ug_vert, uf_vert,ys,femmodel->nodes,femmodel->parameters);
+		delete uf_vert; 
+		delete ys; 
+		InputUpdateFromSolutionx(femmodel,ug_vert);
+		delete ug_vert;
+
+		/*Increase count: */
+		count++;
+		if(converged==true)break;
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			break;
+		}
+	}
+
+	/*clean-up*/
+	delete old_uf_horiz;
+	delete uf_horiz;
+	delete ug_horiz;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 18231)
@@ -0,0 +1,82 @@
+/*!\file: solutionsequence_thermal_nonlinear.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_thermal_nonlinear(FemModel* femmodel){
+
+	/*solution : */
+	Vector<IssmDouble>* tg=NULL; 
+	Vector<IssmDouble>* tf=NULL; 
+	Vector<IssmDouble>* tf_old=NULL; 
+	Vector<IssmDouble>* ys=NULL; 
+	IssmDouble melting_offset;
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
+
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+	int thermal_penalty_threshold;
+	int thermal_maxiter;
+
+	/*parameters:*/
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&thermal_penalty_threshold,ThermalPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&thermal_maxiter,ThermalMaxiterEnum);
+
+	count=1;
+	converged=false;
+
+	InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+	InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
+	femmodel->UpdateConstraintsx();
+
+	for(;;){
+
+		delete tf_old; tf_old=tf;
+		SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&tf, Kff, pf,tf_old, df, femmodel->parameters);
+		delete Kff;delete pf;delete tg; delete df;
+		Mergesolutionfromftogx(&tg, tf,ys,femmodel->nodes,femmodel->parameters); delete ys;
+		InputUpdateFromSolutionx(femmodel,tg);
+
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+
+		if (!converged){
+			if(VerboseConvergence()) _printf0_("   #unstable constraints = " << num_unstable_constraints << "\n");
+			if (num_unstable_constraints <= thermal_penalty_threshold)converged=true;
+			if (count>=thermal_maxiter){
+				converged=true;
+				_printf0_("   maximum number of iterations (" << thermal_maxiter << ") exceeded\n"); 
+			}
+		}
+		count++;
+
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+
+		if(converged)break;
+	}
+
+	InputUpdateFromSolutionx(femmodel,tg);
+	femmodel->parameters->SetParam(melting_offset,MeltingOffsetEnum);
+
+	/*Free ressources: */
+	delete tg;
+	delete tf;
+	delete tf_old;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequences.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/solutionsequences/solutionsequences.h	(revision 18231)
@@ -0,0 +1,27 @@
+/*
+ * solutionsequences.h: 
+ */
+
+#ifndef _SOLUTION_SEQUENCES_H_
+#define _SOLUTION_SEQUENCES_H_
+
+class FemModel;
+class Parameters;
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+#include "../shared/Numerics/types.h"
+
+void solutionsequence_thermal_nonlinear(FemModel* femmodel);
+void solutionsequence_hydro_nonlinear(FemModel* femmodel);
+void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solutionsequence_newton(FemModel* femmodel);
+void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solutionsequence_linear(FemModel* femmodel);
+void solutionsequence_la(FemModel* femmodel);
+void solutionsequence_la_theta(FemModel* femmodel);
+void solutionsequence_adjoint_linear(FemModel* femmodel);
+
+/*convergence*/
+void convergence(bool* pconverged, Matrix<IssmDouble>* K_ff,Vector<IssmDouble>* p_f,Vector<IssmDouble>* u_f,Vector<IssmDouble>* u_f_old,Parameters* parameters);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.cpp	(revision 18231)
@@ -0,0 +1,92 @@
+/*! \file ToolkitOptions.cpp
+ * \brief  file containing the methods for ToolkitOptions.h
+ */
+
+#include <string.h>
+#include "./ToolkitOptions.h"
+#include "../shared/Numerics/types.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../shared/MemOps/MemOps.h"
+
+void ToolkitOptions::Init(char* options){ /*{{{*/
+
+	/*First, avoid a leak: */
+	xDelete<char>(toolkitoptions);
+
+	/*copy options into toolkitoptions:*/
+	_assert_(options);
+	toolkitoptions= xNew<char>(strlen(options)+1); 
+	sprintf(toolkitoptions,   "%s",options);
+
+}/*}}}*/
+char* ToolkitOptions::GetToolkitType(){  /*{{{*/
+
+	/*Look for token: -toolkit, and return value:*/
+
+	return TokenValue(toolkitoptions,"toolkit");
+
+}/*}}}*/
+char* ToolkitOptions::GetToolkitOptionValue(const char* option){  /*{{{*/
+
+	return TokenValue(toolkitoptions,option);
+
+}/*}}}*/
+char* TokenValue(char* tokenlist,const char* target){ /*{{{*/
+
+	/*output:*/
+	char* value=NULL;
+
+	/*intermediary: */
+	char *token         = NULL;
+	char *tokenlistcopy = NULL;
+
+	/*First, because tokenizing destroys a string, copy what we have: */
+	_assert_(tokenlist);
+	tokenlistcopy= xNew<char>(strlen(tokenlist)+1); 
+	sprintf(tokenlistcopy,"%s",tokenlist);
+
+	/*Now go through list of tokens, and look for  target, return value: */
+	token=strtok(tokenlistcopy, " ");
+	while(token != NULL) {
+
+		/*Is this token starting with "-", if so, compare to our target: */
+		if (strncmp(token,"-",1)==0){
+			if (strcmp(token+1,target)==0){
+				/*Ok, we found our target. Get next token: */
+				token = strtok(NULL, " ");
+				/*This token could actually be another option start with "-", just be sure: */
+				if (strncmp(token,"-",1)==0){
+					/*ok, we hit another option, which means our target value is "":*/
+					value= xNew<char>(strlen("")+1); 
+					sprintf(value,"%s","");
+					continue;
+				}
+				else{
+					/*this token is the value we are looking for, copy: */
+					value= xNew<char>(strlen(token)+1); 
+					sprintf(value,"%s",token);
+				}
+			}
+			else{
+				/*we found the wrong target. Go to the next option: */
+				token = strtok(NULL, " ");
+				if (strncmp(token,"-",1)==0){
+					/*this is indeed an option, continue: */
+					continue;
+				}
+				else{
+					/*this is the value of the option, discard it: */
+				}
+			}
+		}
+		else _error_("token list should start with an option, not a value");
+
+		/*Get new token and continue*/
+		token = strtok(NULL, " ");
+	}
+
+	/*Clean up and return*/
+	xDelete<char>(tokenlistcopy);
+	return value;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/ToolkitOptions.h	(revision 18231)
@@ -0,0 +1,23 @@
+/* \file ToolkitOptions.h
+ * \brief  create a class with a static string of options, and static methods to access it
+ * This is a way of protecting access to the toolkit options, and to make it accessible everywhere
+ * in the code.
+ */
+
+#ifndef _TOOLKIT_OPTIONS_H
+#define _TOOLKIT_OPTIONS_H
+
+class ToolkitOptions {
+
+	private:
+		static char* toolkitoptions;
+
+	public:
+		static void Init(char* options);
+		static char* GetToolkitType(void);
+		static char* GetToolkitOptionValue(const char* option);
+};
+
+char* TokenValue(char* tokenlist,const char* target);
+
+#endif  /* _TOOLKIT_OPTIONS_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/AdolcEdf.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/AdolcEdf.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/AdolcEdf.h	(revision 18231)
@@ -0,0 +1,33 @@
+/*
+ * 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_)
+#include "adolc/adolc.h"
+
+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/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/adolcincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/adolcincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/adolc/adolcincludes.h	(revision 18231)
@@ -0,0 +1,10 @@
+/* \file adolcincludes.h
+ * \brief all includes for ADOLC layer
+ */
+
+#ifndef _ADOLC_PATCHES_INCLUDES_H_
+#define _ADOLC_PATCHES_INCLUDES_H_
+
+#include "./AdolcEdf.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/DenseGslSolve.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 18231)
@@ -0,0 +1,246 @@
+/*!\file DenseGslSolve.cpp
+ * \brief: solve dense matrix system with GSL library
+ */
+
+/*Header files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../adolc/adolcincludes.h"
+#include "./gslincludes.h"
+
+#ifdef _HAVE_GSL_
+#include <gsl/gsl_linalg.h>
+#endif
+
+/*}}}*/
+
+void DenseGslSolve(IssmPDouble** pX,IssmPDouble* A,IssmPDouble* B, int n){ /*{{{*/
+
+	/*Intermediary: */
+	IssmPDouble *X  = xNew<IssmPDouble>(n);
+	SolverxSeq(X,A,B,n);
+
+	/*allocate output pointers: */
+	*pX=X;
+}
+/*}}}*/
+void DenseGslSolve(IssmPDouble** px,IssmPDouble* Kff,int Kff_M,int Kff_N,IssmPDouble* pf,int pf_M,Parameters* parameters){ /*{{{*/
+
+	/*Intermediary: */
+
+	if(Kff_N!=pf_M)_error_("Right hand side vector of size " << pf_M << ", when matrix is of size " << Kff_M << "-" << Kff_N << " !");
+	if(Kff_M!=Kff_N)_error_("Stiffness matrix should be square!");
+
+	IssmPDouble *x  = xNew<IssmPDouble>(Kff_N);
+	SolverxSeq(x,Kff,pf,Kff_N);
+
+	/*allocate output pointers: */
+	*px=x;
+}
+/*}}}*/
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
+#ifdef _HAVE_GSL_
+	/*GSL Matrices and vectors: */
+	int              s;
+	gsl_matrix_view  a;
+	gsl_vector_view  b,x;
+	gsl_permutation *p = NULL;
+//	for (int i=0; i<n*n; ++i) std::cout << "SolverxSeq A["<< i << "]=" << A[i] << std::endl;
+//	for (int i=0; i<n; ++i) std::cout << "SolverxSeq b["<< i << "]=" << B[i] << std::endl;
+	/*A will be modified by LU decomposition. Use copy*/
+	double* Acopy = xNew<double>(n*n);
+	xMemCpy(Acopy,A,n*n);
+
+	/*Initialize gsl matrices and vectors: */
+	a = gsl_matrix_view_array (Acopy,n,n);
+	b = gsl_vector_view_array (B,n);
+	x = gsl_vector_view_array (X,n);
+
+	/*Run LU and solve: */
+	p = gsl_permutation_alloc (n);
+	gsl_linalg_LU_decomp (&a.matrix, p, &s);
+	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, &x.vector);
+
+	/*Clean up and assign output pointer*/
+	xDelete(Acopy);
+	gsl_permutation_free(p);
+#endif
+}
+/*}}}*/
+
+#ifdef _HAVE_ADOLC_
+int EDF_for_solverx(int n, IssmPDouble *x, int m, IssmPDouble *y){ /*{{{*/
+	SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
+	return 0;
+} /*}}}*/
+int EDF_fos_forward_for_solverx(int n, IssmPDouble *inVal, IssmPDouble *inDeriv, int m, IssmPDouble *outVal, IssmPDouble *outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+	//  for (int i=0; i<m*m; ++i) std::cout << "EDF_fos_forward_for_solverx A["<< i << "]=" << inVal[i] << std::endl;
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx b["<< i << "]=" << inVal[i+m*m] << std::endl;
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx x["<< i << "]=" << outVal[i] << std::endl;
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	// compute the RHS
+	double* r=xNew<double>(m);
+	for (int i=0; i<m; i++) {
+		r[i]=inDeriv[m*m+i]; // this is db[i]
+		for (int j=0;j<m; j++) {
+			r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
+		}
+	}
+	gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+	xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
+} /*}}}*/
+int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	double* r=xNew<double>(m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	for (int dir=0;dir<directionCount;++dir) {
+		// compute the RHS
+		for (int i=0; i<m; i++) {
+			r[i]=inDeriv[m*m+i][dir]; // this is db[i]
+			for (int j=0;j<m; j++) {
+				r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
+			}
+		}
+		gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+		gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+		// reuse r
+		xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
+		for (int i=0; i<m; i++) {
+			outDeriv[i][dir]=r[i];
+		}
+	}
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
+}
+/*}}}*/
+int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	// the adjoint of the solution is our right-hand side
+	gsl_vector_view x_bar=gsl_vector_view_array(dp_U,m);
+	// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+	gsl_vector_view b_bar=gsl_vector_view_array(dp_Z+m*m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+	// now do the adjoint of the matrix
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dp_Z[i*m+j]-=dp_Z[m*m+i]*dp_y[j];
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
+}
+/*}}}*/
+int EDF_fov_reverse_for_solverx(int m, int p, double **dpp_U, int n, double **dpp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	for (int weightsRowIndex=0;weightsRowIndex<p;++weightsRowIndex) {
+		// the adjoint of the solution is our right-hand side
+		gsl_vector_view x_bar=gsl_vector_view_array(dpp_U[weightsRowIndex],m);
+		// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+		gsl_vector_view b_bar=gsl_vector_view_array(dpp_Z[weightsRowIndex]+m*m,m);
+		gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+		// now do the adjoint of the matrix
+		for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dpp_Z[weightsRowIndex][i*m+j]-=dpp_Z[weightsRowIndex][m*m+i]*dp_y[j];
+	}
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
+}
+/*}}}*/
+void DenseGslSolve(/*output*/ IssmDouble** px,/*stiffness matrix:*/ IssmDouble* Kff, int Kff_M, int Kff_N, /*right hand side load vector: */ IssmDouble* pf, int pf_M, Parameters* parameters){ /*{{{*/
+
+	/*Intermediary: */
+
+	if(Kff_N!=pf_M)_error_("Right hand side vector of size " << pf_M << ", when matrix is of size " << Kff_M << "-" << Kff_N << " !");
+	if(Kff_M!=Kff_N)_error_("Stiffness matrix should be square!");
+
+	ensureContiguousLocations(Kff_N);
+	IssmDouble *x  = xNew<IssmDouble>(Kff_N);
+
+	SolverxSeq(x,Kff,pf,Kff_N,parameters);
+
+	/*allocate output pointers: */
+	*px=x;
+}
+/*}}}*/
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
+	// pack inputs to conform to the EDF-prescribed interface
+        // ensure a contiguous block of locations:
+        ensureContiguousLocations(n*(n+1));
+        IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
+        for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
+        for(int i=0; i<n;  i++)adoubleEDFin[i+n*n]=B[i];      // pack the right hand side
+        IssmPDouble* pdoubleEDFin=xNew<IssmPDouble>(n*(n+1)); // provide space to transfer inputs during call_ext_fct
+	IssmPDouble* pdoubleEDFout=xNew<IssmPDouble>(n);           // provide space to transfer outputs during call_ext_fct
+	// call the wrapped solver through the registry entry we retrieve from parameters
+	call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	             n*(n+1), pdoubleEDFin, adoubleEDFin,
+	             n, pdoubleEDFout,X);
+	// for(int i=0; i<n;  i++) {ADOLC_DUMP_MACRO(X[i]);}
+	xDelete(adoubleEDFin);
+	xDelete(pdoubleEDFin);
+	xDelete(pdoubleEDFout);
+}
+/*}}}*/
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/gslincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/gslincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/gsl/gslincludes.h	(revision 18231)
@@ -0,0 +1,37 @@
+/* \file gslsincludes.h
+ * \brief all includes for GSL layer
+ */
+
+#ifndef _GSL_INCLUDES_H_
+#define _GSL_INCLUDES_H_
+
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+/*}}}*/
+
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmMat;
+class Parameters;
+
+void DenseGslSolve(IssmPDouble** pX,IssmPDouble* A,IssmPDouble* B, int n);
+void DenseGslSolve(IssmDouble** pX,IssmDouble* Kff,int Kff_M,int Kff_N,IssmDouble* pf,int pf_M,Parameters* parameters);
+
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
+// call back functions:
+ADOLC_ext_fct EDF_for_solverx;
+ADOLC_ext_fct_fos_forward EDF_fos_forward_for_solverx;
+ADOLC_ext_fct_fos_reverse EDF_fos_reverse_for_solverx;
+ADOLC_ext_fct_fov_forward EDF_fov_forward_for_solverx;
+ADOLC_ext_fct_fov_reverse EDF_fov_reverse_for_solverx;
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/Bucket.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/Bucket.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/Bucket.h	(revision 18231)
@@ -0,0 +1,239 @@
+/*!\file Bucket.h
+ * \brief: header file for Bucket object
+ */
+
+#ifndef _BUCKET_H
+#define _BUCKET_H
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+#include "../toolkitsenums.h"
+/*}}}*/
+
+/*how many ISSM_MPI_Isend requests does it take to transfer the contents of a bucket to another cpu?*/
+#define MATRIXBUCKETSIZEOFREQUESTS 7 
+#define VECTORBUCKETSIZEOFREQUESTS 5 
+typedef enum {VECTOR_BUCKET, MATRIX_BUCKET} BucketType;
+template <class doubletype> class Bucket: public Object{
+
+	private: 
+		int type; //either a VECTOR_BUCKET or MATRIX_BUCKET
+		int m,n; /*size of local matrix we are storing*/
+		/*row and column indices of the matrix we are storing*/
+		int* idxm;
+		int* idxn; 
+		doubletype* values; /*local matrix*/
+		InsMode mode; /*mode of insertion for this bucket*/
+
+	public: 
+
+		/*constructors, destructors: */
+		Bucket(){ /*{{{*/
+			this->Initialize();
+		} /*}}}*/
+		Bucket(int min,int* idxmin,int nin,int* idxnin,doubletype* valuesin,InsMode modein){ /*{{{*/
+
+			this->Initialize();
+
+			this->type=MATRIX_BUCKET;
+			this->m=min;
+			this->n=nin;
+			this->mode=modein;
+			if(this->m){
+				this->idxm=xNew<int>(this->m); 
+				xMemCpy(this->idxm,idxmin,this->m);
+			}
+			if(this->n){
+				this->idxn=xNew<int>(this->n); 
+				xMemCpy(this->idxn,idxnin,this->n);
+			}
+			if(this->m*this->n){
+				this->values=xNew<doubletype>(this->n*this->m);
+				xMemCpy(this->values,valuesin,this->n*this->m);
+			}
+		} /*}}}*/
+		Bucket(int min,int* idxmin,doubletype* valuesin,InsMode modein){ /*{{{*/ 
+			this->Initialize();
+
+			this->type=VECTOR_BUCKET; 
+			this->m=min;
+			this->mode=modein;
+			if(this->m){
+				this->idxm=xNew<int>(this->m); 
+				xMemCpy(this->idxm,idxmin,this->m);
+
+				this->values=xNew<doubletype>(this->m);
+				xMemCpy(this->values,valuesin,this->m);
+			}
+		} /*}}}*/
+		~Bucket(){ /*{{{*/
+			xDelete<int>(idxm);
+			xDelete<int>(idxn);
+			xDelete<doubletype>(values);
+		} /*}}}*/
+		void Initialize(void){ /*{{{*/
+
+			this->type=0;
+			this->m=0;
+			this->n=0;
+			this->idxm=NULL;
+			this->idxn=NULL;
+			this->values=NULL;
+			mode=INS_VAL;
+
+		} /*}}}*/
+
+		/*object virtual functions definitions:*/
+		void    Echo(){ /*{{{*/
+			_printf_("Bucket echo (cpu #: "<<IssmComm::GetRank()<<")\n");
+			_printf_("bucket type: " << type << "\n");
+			_printf_("num rows: "<<this->m<<" num cols: "<<this->n << "\n");
+		} /*}}}*/
+		void    DeepEcho(){ /*{{{*/
+			int i,j;
+
+			_printf_("Bucket echo (cpu #: "<<IssmComm::GetRank()<<")\n");
+			_printf_("bucket type: " << type << "\n");
+			_printf_("num rows: "<<this->m<<" num cols: "<<this->n << "\n");
+			if(type==MATRIX_BUCKET){
+				for (i=0;i<this->m;i++){
+					_printf_("row "<<this->idxm[i]<<", column indices: \n");
+					for (j=0;j<this->n;j++){
+						_printf_(" "<<this->idxn[j] << "\n");
+					}
+					_printf_("values: \n");
+					for (j=0;j<this->n;j++){
+						_printf_(" "<<this->values[m*i+j] << "\n");
+					}
+				}
+			}
+			else if(type==VECTOR_BUCKET){
+				for (i=0;i<this->m;i++){
+					_printf_("row "<<this->idxm[i]<<", value " << this->values[i] << "\n");
+				}
+			}
+			else _error_("unknown type of bucket!");
+		}
+		/*}}}*/
+		int     Id(){ /*{{{*/
+			return -1;
+		} /*}}}*/
+		int     ObjectEnum(){ /*{{{*/
+			return -1;
+		} /*}}}*/
+		Object *copy()        {/*{{{*/
+			_error_("Not implemented yet (similar to Elements)"); };
+		/*}}}*/
+
+		/*specific routines of Bucket: */
+		void SpawnBucketsPerCpu(DataSet* bucketsofcpu_i,int rank_i,int* rowranks){ /*{{{*/
+
+			/*go through our idxm index of rows this bucket owns, and spawn buckets  
+			 *if these rows belong to cpu rank_i. Use rowranks to determine this.*/
+			for(int i=0;i<m;i++){
+				if (rowranks[idxm[i]]==rank_i){
+					/*This row belongs to cpu rank_i, so spawn a bucket with this row, and add it to the bucketsofcpu_i dataset: */
+					if(type==MATRIX_BUCKET){
+						bucketsofcpu_i->AddObject(new Bucket(1,idxm+i,n,idxn,values+n*i,mode));
+					}
+					else{
+						bucketsofcpu_i->AddObject(new Bucket(1,idxm+i,values+i,mode));
+					}
+				}
+			}
+
+		}; /*}}}*/
+		int BucketType(void){ /*{{{*/
+
+			return type;
+		};
+		/*}}}*/
+		void Marshall(int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu){ /*{{{*/
+
+			/*intermediary: */
+			int         i;
+			int         j;
+
+			/*buffers: */
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			doubletype *values_forcpu      = NULL;
+			int        *modes_forcpu       = NULL;
+
+			/*initialize buffers: */
+			row_indices_forcpu=*prow_indices_forcpu;
+			col_indices_forcpu=*pcol_indices_forcpu;
+			values_forcpu=*pvalues_forcpu;
+			modes_forcpu=*pmodes_forcpu;
+
+			/*fill buffers with out values and indices and modes: */
+			for(i=0;i<m;i++){
+				for(j=0;j<n;j++){
+					row_indices_forcpu[i*n+j]=idxm[i];
+					col_indices_forcpu[i*n+j]=idxn[j];
+					values_forcpu[i*n+j]=values[i*n+j];
+					modes_forcpu[i*n+j]=mode;
+				}
+			}
+
+			/*increment buffer for next Bucket who will marshall his data: */
+			row_indices_forcpu+=(m*n);
+			col_indices_forcpu+=(m*n);
+			values_forcpu+=(m*n);
+			modes_forcpu+=(m*n);
+
+			/*output modified buffers: */
+			*prow_indices_forcpu=row_indices_forcpu;
+			*pcol_indices_forcpu=col_indices_forcpu;
+			*pvalues_forcpu=values_forcpu;
+			*pmodes_forcpu=modes_forcpu;
+		};
+		/*}}}*/
+		void Marshall(int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu){ /*{{{*/
+
+			/*intermediary: */
+			int         i;
+
+			/*buffers: */
+			int        *row_indices_forcpu = NULL;
+			doubletype *values_forcpu      = NULL;
+			int        *modes_forcpu       = NULL;
+
+			/*initialize buffers: */
+			row_indices_forcpu=*prow_indices_forcpu;
+			values_forcpu=*pvalues_forcpu;
+			modes_forcpu=*pmodes_forcpu;
+
+			/*fill buffers with out values and indices and modes: */
+			for(i=0;i<m;i++){
+				row_indices_forcpu[i]=idxm[i];
+				values_forcpu[i]=values[i];
+				modes_forcpu[i]=mode;
+			}
+
+			/*increment buffer for next Bucket who will marshall his data: */
+			row_indices_forcpu+=m;
+			values_forcpu+=m;
+			modes_forcpu+=m;
+
+			/*output modified buffers: */
+			*prow_indices_forcpu=row_indices_forcpu;
+			*pvalues_forcpu=values_forcpu;
+			*pmodes_forcpu=modes_forcpu;
+		};
+		/*}}}*/
+		int MarshallSize(void){ /*{{{*/
+
+			if(type==MATRIX_BUCKET){
+				return m*n;
+			}
+			else{
+				return m;
+			}
+		};
+		/*}}}*/
+};
+
+#endif  /* _BUCKET_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsMat.h	(revision 18231)
@@ -0,0 +1,50 @@
+/*!\file:  IssmAbsMat.h
+ * \brief Main abstract class for the ISSM matrices.  This abstract class defines the pure virtual
+ * functions that each of its descendants need to implement, such as contructors, destructors, as well
+ * as matrix specific routines, such as SetValue, Assemple, MatMult, etc ...
+ * Descendants include among others:
+ * IssmDenseMat and IssmMpiDenseMat
+ *
+ */ 
+
+#ifndef _ISSM_ABS_MAT_H_
+#define _ISSM_ABS_MAT_H_
+
+/*Headers:*/
+#include "../toolkitsenums.h"
+#include "../../shared/Numerics/types.h"
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such vectors are useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types) */
+
+template <class doubletype> class IssmAbsVec;
+class Parameters;
+
+template <class doubletype> 
+class IssmAbsMat{
+
+	public:
+
+		/*IssmAbsMat constructors, destructors*/
+		virtual ~IssmAbsMat(){};
+
+		/*Functionality: */
+		virtual void Echo(void)=0;
+		virtual void Assemble(void)=0;
+		virtual doubletype Norm(NormMode mode)=0;
+		virtual void GetSize(int* pM,int* pN)=0;
+		virtual void GetLocalSize(int* pM,int* pN)=0;
+		virtual void MatMult(IssmAbsVec<doubletype>* X,IssmAbsVec<doubletype>* AX)=0;
+		virtual IssmAbsMat<doubletype>* Duplicate(void)=0;
+		virtual doubletype* ToSerial(void)=0;
+		virtual void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode)=0;
+		virtual void Convert(MatrixType type)=0;
+		#ifndef _HAVE_WRAPPERS_
+		virtual IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pf, Parameters* parameters)=0;
+		#endif
+};
+
+#endif //#ifndef _ISSM_ABS_MAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsVec.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsVec.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmAbsVec.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\file:  IssmAbsVec.h
+ * \brief Main abstract class for the ISSM vectors.  This abstract class defines the pure virtual
+ * functions that each of its descendants need to implement, such as contructors, destructors, as well
+ * as matrix specific routines, such as SetValue, Assemple, VecMult, etc ...
+ * Descendants include among others:
+ *	  IssmSeqVec and IssmMpiVec
+ *
+ */ 
+
+#ifndef _ISSM_ABS_VEC_H_
+#define _ISSM_ABS_VEC_H_
+
+/*Headers:*/
+#include "../toolkitsenums.h"
+#include "../../shared/Numerics/types.h"
+
+/*We need to template this class, in case we want to create Vectors that hold
+  IssmDouble* vector or IssmPDouble* vector. 
+  Such vectors are useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)
+*/
+template <class doubletype> 
+class IssmAbsVec{
+
+	public:
+
+		/*IssmAbsVec constructors, destructors*/
+		virtual ~IssmAbsVec(){};
+
+		/*IssmAbsVec specific routines*/
+		virtual void Echo(void)=0;
+		virtual void Assemble(void)=0;
+		virtual void SetValues(int ssize, int* list, doubletype* values, InsMode mode)=0;
+		virtual void SetValue(int dof, doubletype value, InsMode mode)=0;
+		virtual void GetValue(doubletype* pvalue,int dof)=0;
+		virtual void GetSize(int* pM)=0;
+		virtual void GetLocalSize(int* pM)=0;
+		virtual IssmAbsVec<doubletype>* Duplicate(void)=0;
+		virtual void Set(doubletype value)=0;
+		virtual void AXPY(IssmAbsVec* X, doubletype a)=0;
+		virtual void AYPX(IssmAbsVec* X, doubletype a)=0;
+		virtual doubletype* ToMPISerial(void)=0;
+		virtual void Copy(IssmAbsVec* to)=0;
+		virtual doubletype Norm(NormMode mode)=0;
+		virtual void Scale(doubletype scale_factor)=0;
+		virtual doubletype Dot(IssmAbsVec* input)=0;
+		virtual void PointwiseDivide(IssmAbsVec* x,IssmAbsVec* y)=0;
+};
+
+#endif //#ifndef _ISSM_ABS_VEC_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmDenseMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmDenseMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmDenseMat.h	(revision 18231)
@@ -0,0 +1,287 @@
+/*!\file:  IssmDenseMat.h
+ * \brief implementation of an ISSM matrix which run serially (1 cpu only), which is made of a fully dense 
+ * matrix. Internally, this dense matrix is just a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_DENSE_MAT_H_
+#define _ISSM_DENSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmSeqVec.h"
+#include "../../shared/shared.h"
+#include "../gsl/gslincludes.h"
+
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsVec;
+template <class doubletype> class IssmAbsMat;
+template <class doubletype> class IssmSeqVec;
+
+template <class doubletype> 
+class IssmDenseMat: public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N; 
+		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+
+		/*IssmDenseMat constructors, destructors*/
+		/*IssmDenseMat(){{{*/
+		IssmDenseMat(){
+
+			this->M=0;
+			this->N=0;
+			this->matrix=NULL;
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N){{{*/
+		IssmDenseMat(int pM,int pN){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N, doubletype sparsity){{{*/
+		IssmDenseMat(int pM,int pN, doubletype sparsity){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		IssmDenseMat(int m,int n,int pM,int pN,int* d_nnz,int* o_nnz){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(pM*pN) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
+		IssmDenseMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N){
+				this->matrix=xNewZeroInit<doubletype>(pM*pN);
+				xMemCpy<doubletype>(this->matrix,serial_mat,pM*pN);
+			}
+
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+		IssmDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*~IssmDenseMat(){{{*/
+		~IssmDenseMat(){
+
+			xDelete<doubletype>(this->matrix);
+			M=0;
+			N=0;
+		}
+		/*}}}*/
+
+		/*IssmAbsMat virtual functions*/
+		/*Echo{{{*/
+		void Echo(void){
+
+			int i,j;
+			_printf_("IssmDenseMat size " << this->M << "-" << this->N << "\n");
+			for(i=0;i<M;i++){
+				for(j=0;j<N;j++){
+					_printf_(this->matrix[N*i+j] << " ");
+				}
+				_printf_("\n");
+			}
+		}
+		/*}}}*/
+		/*Assemble{{{*/
+		void Assemble(void){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		/*Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					norm=0;
+					for(i=0;i<this->M;i++){
+						absolute=0;
+						for(j=0;j<this->N;j++){
+							absolute+=fabs(this->matrix[N*i+j]);
+						}
+						norm=max(norm,absolute);
+					}
+					return norm;
+					break; 
+				case NORM_FROB:
+					norm=0;
+					for(i=0;i<this->M;i++){
+						for(j=0;j<this->N;j++){
+							norm+=pow(this->matrix[N*i+j],2);
+						}
+					}
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*MatMult{{{*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+
+			/*We assume that the vectors coming in are of compatible type: */
+			int i,j;
+			int XM,AXM;
+			doubletype dummy;
+			IssmSeqVec<doubletype>* X=NULL;
+			IssmSeqVec<doubletype>* AX=NULL;
+
+			/*downcast X and AX: */
+			X=(IssmSeqVec<doubletype>*)Xin;
+			AX=(IssmSeqVec<doubletype>*)AXin;
+
+			/*Some checks first: */
+			X->GetSize(&XM);
+			AX->GetSize(&AXM);
+
+			if(M!=AXM)_error_("A and AX should have the same number of rows!");
+			if(N!=XM)_error_("A and X should have the same number of columns!");
+
+			for(i=0;i<M;i++){
+				dummy=0;
+				for(j=0;j<N;j++){
+					dummy+= this->matrix[N*i+j]*X->vector[j];
+				}
+				AX->vector[i]=dummy;
+			}
+
+		}
+		/*}}}*/
+		/*Duplicate{{{*/
+		IssmDenseMat<doubletype>* Duplicate(void){
+
+			doubletype dummy=0;
+
+			return new IssmDenseMat<doubletype>(this->matrix,this->M,this->N,dummy);
+
+		}
+		/*}}}*/
+		/*ToSerial{{{*/
+		doubletype* ToSerial(void){
+
+			doubletype* buffer=NULL;
+
+			if(this->M*this->N){
+				buffer=xNew<doubletype>(this->M*this->N);
+				xMemCpy<doubletype>(buffer,this->matrix,this->M*this->N);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		/*SetValues{{{*/
+		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){
+
+			int i,j;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]+=values[n*i+j];
+					break;
+				case INS_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]=values[n*i+j];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		/*Convert{{{*/
+		void Convert(MatrixType type){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			/*First off, we assume that the type of IssmAbsVec is IssmSeqVec. So downcast: */
+			IssmSeqVec<IssmDouble>* pf = NULL;
+			IssmSeqVec<IssmDouble> *uf = NULL;
+			IssmDouble* x=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmSeqVec<IssmDouble>*)pfin;
+
+			#ifdef _HAVE_GSL_
+			DenseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+			uf=new IssmSeqVec<IssmDouble>(x,this->N); xDelete(x);
+			return uf;
+			#else
+				_error_("GSL support not compiled in!");
+			#endif
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_DENSE_MAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMat.h	(revision 18231)
@@ -0,0 +1,256 @@
+/*!\file:  IssmMat.h
+ * \brief Main Matrix class for the Issm toolkit. 
+ */ 
+
+#ifndef _ISSM_MAT_H_
+#define _ISSM_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../ToolkitOptions.h"
+#include "./IssmToolkitUtils.h"
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices are useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)
+*/
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmDenseMat;
+template <class doubletype> class IssmMpiDenseMat;
+template <class doubletype> class IssmMpiSparseMat;
+class Parameters;
+
+template <class doubletype> 
+class IssmMat{
+
+	public:
+
+		IssmAbsMat<doubletype>* matrix; /*abstract matrix, which implements object orientation*/
+
+		/*IssmMat constructors, destructors*/
+		IssmMat(){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>();
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>();
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>();
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int M,int N){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int M,int N, doubletype sparsity){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N,sparsity);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N,sparsity);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N,sparsity);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(doubletype* serial_mat,int M,int N,doubletype sparsity){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(serial_mat,M,N,sparsity);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(serial_mat,M,N,sparsity);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(serial_mat,M,N,sparsity);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+
+		}
+		/*}}}*/
+		IssmMat(int M,int N, int connectivity, int numberofdofspernode){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				case MpiSparseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiSparseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					#else
+					_error_("MpiSparse matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		~IssmMat(){ /*{{{*/
+			delete matrix;
+		} /*}}}*/
+
+		/*Functionality: */
+		void Echo(void){  /*{{{*/
+			matrix->Echo();
+		} /*}}}*/
+		void Assemble(void){  /*{{{*/
+			matrix->Assemble();
+		} /*}}}*/
+		doubletype Norm(NormMode mode){ /*{{{*/
+			return matrix->Norm(mode);
+		}
+		/*}}}*/
+		void GetSize(int* pM,int* pN){ /*{{{*/
+			matrix->GetSize(pM,pN);
+		} /*}}}*/
+		void GetLocalSize(int* pM,int* pN){ /*{{{*/
+			matrix->GetLocalSize(pM,pN);
+		} /*}}}*/
+		void MatMult(IssmVec<doubletype>* X,IssmVec<doubletype>* AX){ /*{{{*/
+			matrix->MatMult(X->vector,AX->vector);
+		} /*}}}*/
+		IssmMat<doubletype>* Duplicate(void){ /*{{{*/
+
+			IssmMat<doubletype>* issmmatrix=NULL;
+
+			issmmatrix=new IssmMat<doubletype>();
+			issmmatrix->matrix=this->matrix->Duplicate();
+
+			return issmmatrix;
+		} /*}}}*/
+		doubletype* ToSerial(void){/*{{{*/
+			return matrix->ToSerial();
+		}/*}}}*/
+		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){/*{{{*/
+			matrix->SetValues(m,idxm,n,idxn,values,mode);
+		}/*}}}*/
+		void Convert(MatrixType type){/*{{{*/
+			matrix->convert(type);
+		}/*}}}*/
+		#ifndef _HAVE_WRAPPERS_
+		IssmVec<doubletype>* Solve(IssmVec<doubletype>* pf, Parameters* parameters){ /*{{{*/
+
+			IssmVec<doubletype>* outvector=NULL;
+
+			outvector=new IssmVec<doubletype>();
+
+			outvector->vector=this->matrix->Solve(pf->vector,parameters);
+
+			return outvector;
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSMMAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 18231)
@@ -0,0 +1,527 @@
+/*!\file:  IssmMpiDenseMat.h
+ * \brief implementation of parallel dense ISSM matrix. Internally, the parallel dense matrix is 
+ * split in rows across each cpu. Each matrix (representing a subset of rows) on each cpu is fully 
+ * dense, and is represented by a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_MPI_DENSE_MAT_H_
+#define _ISSM_MPI_DENSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+#include "../mumps/mumpsincludes.h"
+#include "./Bucket.h"
+#include "./IssmMpiVec.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+template <class doubletype> class IssmAbsMat;
+
+template <class doubletype> 
+class IssmMpiDenseMat:public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N;  //global size
+		int m;    //local number of rows
+		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global matrix.*/
+
+		/*IssmMpiDenseMat constructors, destructors*/
+		IssmMpiDenseMat(){/*{{{*/
+			this->M=0;
+			this->N=0;
+			this->m=0;
+			this->matrix=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		IssmMpiDenseMat(int Min,int Nin){/*{{{*/
+			this->Init(Min,Nin);
+		}
+		/*}}}*/
+		IssmMpiDenseMat(int pM,int pN, doubletype sparsity){/*{{{*/
+			/*no sparsity involved here, we are fully dense, so just use the previous constructor: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		IssmMpiDenseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){/*{{{*/
+			/*not needed, we are fully dense!: */
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+			this->m=min;
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N)this->matrix=xNewZeroInit<doubletype>(this->m*N);
+		}
+		/*}}}*/
+		IssmMpiDenseMat(doubletype* serial_mat,int Min,int Nin,doubletype sparsity){/*{{{*/
+
+			/*Here, we assume that the serial_mat is local to the local cpu, and that it has 
+			 * the correct size (m rows by N colums), n determined by DetermineLocalSize: */
+			this->buckets=new DataSet();
+			this->M=Min;
+			this->N=Nin;
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			this->matrix=NULL;
+			if(m*N){
+				this->matrix=xNewZeroInit<doubletype>(m*N);
+				xMemCpy<doubletype>(this->matrix,serial_mat,m*N);
+			}
+		}
+		/*}}}*/
+		IssmMpiDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){/*{{{*/
+			/*not needed, we are fully dense!: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		~IssmMpiDenseMat(){/*{{{*/
+			xDelete<doubletype>(this->matrix);
+			M=0;
+			N=0;
+			m=0;
+			delete this->buckets;
+		}
+		/*}}}*/
+		void Init(int Min,int Nin){/*{{{*/
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+
+			/*Figure out local number of rows: */
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N)this->matrix=xNewZeroInit<doubletype>(this->m*N);
+		}
+		/*}}}*/
+
+		/*IssmMpiDenseMat specific routines */
+		void Echo(void){/*{{{*/
+
+			int my_rank;
+			int i,j,k;
+
+			/*Do a synchronized dump across all the rows: */
+			my_rank=IssmComm::GetRank();
+			for(i=0;i<IssmComm::GetSize();i++){
+				if (my_rank==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for (j=0;j<this->m;j++){
+						_printf_("row " << j << ":");
+						for (k=0;k<this->N;k++){
+							if(this->matrix[j*this->N+k]!=0)_printf_("(" << k << "," << this->matrix[j*this->N+k] << ") ");
+						}
+						_printf_("\n");
+					}
+				}
+				ISSM_MPI_Barrier(IssmComm::GetComm());
+			}
+
+		}
+		/*}}}*/
+		void Assemble(){/*{{{*/
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
+
+			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&col_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			numvalues_fromcpu   = xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			col_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					col_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					col_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*Scatter values around: {{{*/
+			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( col_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, col_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+			}
+			/*}}}*/
+
+			/*Plug values into global matrix: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					if(mods[j]==ADD_VAL) *(matrix+N*(rows[j]-lower_row)+cols[j])+=values[j];
+					else *(matrix+N*(rows[j]-lower_row)+cols[j])=values[j];
+				}
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(col_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(cols);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(col_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+
+			doubletype norm,local_norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						absolute=0;
+						for(j=0;j<this->N;j++){
+							absolute+=fabs(this->matrix[N*i+j]);
+						}
+						local_norm=max(local_norm,absolute);
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return norm;
+					break; 
+				case NORM_FROB:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						for(j=0;j<this->N;j++){
+							local_norm+=pow(this->matrix[N*i+j],2);
+						}
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM=M;
+			*pN=N;
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
+			*pM=m;
+			*pN=N;
+		}
+		/*}}}*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){/*{{{*/
+
+			int         i,j;
+			doubletype *X_serial  = NULL;
+
+			/*A check on the types: */
+			if(IssmVecTypeFromToolkitOptions()!=MpiEnum)_error_("MatMult operation only possible with 'mpi' vectors");
+
+			/*Now that we are sure, cast vectors: */
+			IssmMpiVec<doubletype>* X=(IssmMpiVec<doubletype>*)Xin;
+			IssmMpiVec<doubletype>* AX=(IssmMpiVec<doubletype>*)AXin;
+
+			/*Serialize input Xin: */
+			X_serial=X->ToMPISerial();
+
+			/*Every cpu has a serial version of the input vector. Use it to do the Matrix-Vector multiply 
+			 *locally and plug it into AXin: */
+			for(i=0;i<this->m;i++){
+				for(j=0;j<this->N;j++){
+					AX->vector[i]+=this->matrix[i*N+j]*X_serial[j];
+				}
+			}
+
+			/*Free ressources: */
+			xDelete<doubletype>(X_serial);
+		}
+		/*}}}*/
+		IssmMpiDenseMat<doubletype>* Duplicate(void){/*{{{*/
+
+			IssmMpiDenseMat<doubletype>* dup=new IssmMpiDenseMat<doubletype>(this->matrix,this->M,this->N,0);
+			return dup;
+
+		}
+		/*}}}*/
+		doubletype* ToSerial(void){/*{{{*/
+			_error_("not supported yet!");
+		}
+		/*}}}*/
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){/*{{{*/
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the matrix on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(min,idxm,nin,idxn,values,mode));
+
+		}
+		/*}}}*/
+		void Convert(MatrixType type){/*{{{*/
+			_error_("not supported yet!");
+		}
+		/*}}}*/		
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			int        *temp_col_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			int        *col_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			col_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_col_indices_forcpu=col_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_col_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_col_indices_forcpu!=col_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pcol_indices_forcpu = col_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			/*output: */
+			IssmMpiVec<IssmDouble>* uf=NULL;
+			IssmMpiVec<IssmDouble>* pf=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmMpiVec<IssmDouble>*)pfin;
+
+			switch(IssmSolverTypeFromToolkitOptions()){
+				case MumpsEnum: {
+					/*Initialize output: */
+					uf=pf->Duplicate();
+					#ifdef _HAVE_MUMPS_
+					MpiDenseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
+					#else
+					_error_("IssmMpiDenseMat solver requires MUMPS solver");
+					#endif
+					return (IssmAbsVec<IssmDouble>*)uf;
+									 }
+				case GslEnum: {
+
+					IssmDouble* x=NULL;
+					#ifdef _HAVE_GSL_
+
+					DenseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+					uf=new IssmMpiVec<IssmDouble>(x,this->N); xDelete(x);
+
+					return (IssmAbsVec<IssmDouble>*)uf;
+					#else
+					_error_("GSL support not compiled in!");
+					#endif
+								  }
+				default:
+					_error_("solver type not supported yet!");
+			}
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_MPI_DENSE_MAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiSparseMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 18231)
@@ -0,0 +1,573 @@
+/*!\file:  IssmMpiSparseMat.h
+ * \brief implementation of parallel sparse ISSM matrix. Internally, the parallel sparse matrix is 
+ * split in rows across each cpu. Locally, on each cpu, the local matrix is represented by a vector of sparse rows.
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_MPI_SPARSE_MAT_H_
+#define _ISSM_MPI_SPARSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+#include "../mumps/mumpsincludes.h"
+#include "./Bucket.h"
+#include "./IssmMpiVec.h"
+#include "./SparseRow.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsMat;
+
+template <class doubletype> 
+class IssmMpiSparseMat:public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N;  //global size
+		int m;    //local number of rows
+		SparseRow<doubletype>** matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global matrix.*/
+		/*IssmMpiSparseMat constructors, destructors*/
+		IssmMpiSparseMat(){/*{{{*/
+			this->M=0;
+			this->N=0;
+			this->m=0;
+			this->matrix=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		IssmMpiSparseMat(int Min,int Nin){/*{{{*/
+			this->Init(Min,Nin);
+		}
+		/*}}}*/
+		IssmMpiSparseMat(int pM,int pN, doubletype sparsity){/*{{{*/
+			/*no sparsity involved here, the sparsity pattern is resolve during the assemble phase: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		IssmMpiSparseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){/*{{{*/
+
+			int i;
+
+			/*no sparsity involved here, the sparsity pattern is resolved at the assemble phase: */
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+			this->m=min;
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N){
+				this->matrix=xNew<SparseRow<doubletype>*>(m);
+				for(i=0;i<m;i++){
+					this->matrix[i]=new SparseRow<doubletype>(N);
+				}
+			}
+		}
+		/*}}}*/
+		IssmMpiSparseMat(int pM,int pN, int connectivity,int numberofdofspernode){/*{{{*/
+			/*this is not needed, sparsity pattern is resolved at assemble phase: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		void Init(int Min,int Nin){/*{{{*/
+			
+			int i;
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+
+			/*Figure out local number of rows: */
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N){
+				this->matrix=xNew<SparseRow<doubletype>*>(m);
+				for(i=0;i<m;i++){
+					this->matrix[i]=new SparseRow<doubletype>(N);
+				}
+			}
+		}
+		/*}}}*/
+		~IssmMpiSparseMat(){/*{{{*/
+			int i;
+
+			if(m*N){
+				for(i=0;i<m;i++){
+					delete this->matrix[i];
+				}
+				xDelete<SparseRow<doubletype>*>(this->matrix);
+			}
+			M=0;
+			N=0;
+			m=0;
+			delete this->buckets;
+		}
+		/*}}}*/
+
+		/*IssmMpiSparseMat specific routines */
+		void Echo(void){/*{{{*/
+
+			/*Do a synchronized dump across all the rows: */
+			int my_rank=IssmComm::GetRank();
+			for(int i=0;i<IssmComm::GetSize();i++){
+				if(my_rank==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for(int j=0;j<this->m;j++){
+						_printf_("row " << j << ":");
+						this->matrix[j]->Echo();
+						_printf_("\n");
+					}
+				}
+				ISSM_MPI_Barrier(IssmComm::GetComm());
+			}
+
+		}
+		/*}}}*/
+		void Assemble(){/*{{{*/
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			int           this_row_numvalues;
+			int*          this_row_cols       = NULL;
+			int*          this_row_mods       = NULL;
+			int*          numvalues_perrow    = NULL;
+			int           row;
+			
+			doubletype**  values_perrow       = NULL;
+			int**         cols_perrow         = NULL;
+			int**         mods_perrow         = NULL;
+			int*          counters_perrow     = NULL;
+			int           counter;
+
+			/*Early exit: */
+			if(this->M*this->N==0)return; //no need to assemble.
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
+
+			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&col_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			numvalues_fromcpu   = xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			col_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					col_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					col_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*Scatter values around: {{{*/
+			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( col_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, col_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+			}
+			/*}}}*/
+
+			/*Plug values into global matrix. To do so, we are going to first figure out how many overall values each sparse row is going to get, then we fill up these values, and give it to each sparse row: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+
+			/*Figure out how many values each row is going to get: */
+			numvalues_perrow=xNewZeroInit<int>(this->m);
+			for(i=0;i<num_procs;i++){ 
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				for(j=0;j<numvalues;j++)numvalues_perrow[rows[j]-lower_row]++;
+			}
+
+			/*Allocate all the values, cols and mods from each cpu: */
+			values_perrow=xNew<doubletype*>(this->m);
+			cols_perrow=xNew<int*>(this->m);
+			mods_perrow=xNew<int*>(this->m);
+			counters_perrow=xNewZeroInit<int>(this->m);
+
+			for(i=0;i<this->m;i++){
+				values_perrow[i]=xNewZeroInit<doubletype>(numvalues_perrow[i]);
+				cols_perrow[i]=xNewZeroInit<int>(numvalues_perrow[i]);
+				mods_perrow[i]=xNewZeroInit<int>(numvalues_perrow[i]);
+			}
+
+			/*collect:*/
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					row=rows[j]-lower_row;
+					counter=counters_perrow[row];
+					values_perrow[row][counter]=values[j];
+					cols_perrow[row][counter]=cols[j];
+					mods_perrow[row][counter]=mods[j];
+					counter=counters_perrow[row]++;
+				}
+			}
+					
+			/*Plug into matrix: */
+			for(i=0;i<this->m;i++){
+				this->matrix[i]->SetValues(numvalues_perrow[i],cols_perrow[i],values_perrow[i],mods_perrow[i]);
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(numvalues_perrow);
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(col_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(cols);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(col_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			
+			for(i=0;i<this->m;i++){
+				doubletype* values=values_perrow[i]; xDelete<doubletype>(values);
+				int* cols=cols_perrow[i]; xDelete<int>(cols);
+				int* mods=mods_perrow[i]; xDelete<int>(mods);
+			}
+			xDelete<int>(counters_perrow);
+			xDelete<doubletype*>(values_perrow);
+			xDelete<int*>(cols_perrow);
+			xDelete<int*>(mods_perrow);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+
+			doubletype norm,local_norm;
+			doubletype absolute;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						local_norm=max(local_norm,this->matrix[i]->Norm(mode));
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return norm;
+					break; 
+				case NORM_FROB:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						local_norm+=this->matrix[i]->Norm(mode);
+					}
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM=M;
+			*pN=N;
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
+			*pM=m;
+			*pN=N;
+		}
+		/*}}}*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){/*{{{*/
+
+			/*A check on the types: */
+			if(IssmVecTypeFromToolkitOptions()!=MpiEnum)_error_("MatMult operation only possible with 'mpi' vectors");
+
+			/*Now that we are sure, cast vectors: */
+			IssmMpiVec<doubletype>* X=(IssmMpiVec<doubletype>*)Xin;
+			IssmMpiVec<doubletype>* AX=(IssmMpiVec<doubletype>*)AXin;
+
+			/*Serialize input Xin: */
+			doubletype* X_serial=X->ToMPISerial();
+
+			/*Every cpu has a serial version of the input vector. Use it to do the Matrix-Vector multiply 
+			 *locally and plug it into AXin: */
+			for(int i=0;i<this->m;i++){
+				AX->vector[i]=this->matrix[i]->Mult(X_serial);
+			}
+
+			/*Free ressources: */
+			xDelete<doubletype>(X_serial);
+		}
+		/*}}}*/
+		IssmMpiSparseMat<doubletype>* Duplicate(void){/*{{{*/
+
+			_error_("not supported yet!");
+
+		}
+		/*}}}*/
+		doubletype* ToSerial(void){/*{{{*/
+			_error_("not supported yet!");
+		}
+		/*}}}*/
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){/*{{{*/
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the matrix on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(min,idxm,nin,idxn,values,mode));
+
+		}
+		/*}}}*/
+		void Convert(MatrixType type){/*{{{*/
+			_error_("not supported yet!");
+		}
+		/*}}}*/		
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			int        *temp_col_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			int        *col_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			col_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_col_indices_forcpu=col_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_col_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_col_indices_forcpu!=col_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pcol_indices_forcpu = col_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			/*output: */
+			IssmMpiVec<IssmDouble>* uf=NULL;
+			IssmMpiVec<IssmDouble>* pf=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmMpiVec<IssmDouble>*)pfin;
+
+			switch(IssmSolverTypeFromToolkitOptions()){
+				case MumpsEnum: {
+					/*Initialize output: */
+					uf=pf->Duplicate();
+					#ifdef _HAVE_MUMPS_
+					MpiSparseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
+					#else
+					_error_("IssmMpiSparseMat solver requires MUMPS solver");
+					#endif
+					return (IssmAbsVec<IssmDouble>*)uf;
+									 }
+				case GslEnum: {
+
+					IssmDouble* x=NULL;
+					#ifdef _HAVE_GSL_
+
+					_error_("not implemented yet!");
+					//SparseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+					uf=new IssmMpiVec<IssmDouble>(x,this->N); xDelete(x);
+
+					return (IssmAbsVec<IssmDouble>*)uf;
+					#else
+					_error_("GSL support not compiled in!");
+					#endif
+								  }
+				default:
+					_error_("solver type not supported yet!");
+			}
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_MPI_SPARSE_MAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiVec.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmMpiVec.h	(revision 18231)
@@ -0,0 +1,553 @@
+/*!\file:  IssmMpiVec.h
+ * \brief implementation of parallel dense ISSM vector. Internally, the parallel dense vector is 
+ * split in rows across each cpu. Each vector (representing a subset of rows) on each cpu is fully 
+ * dense, and is represented by a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsVec, 
+ * and the contructors required by IssmVec (see IssmVec.h)
+ */ 
+
+#ifndef _ISSM_MPI_VEC_H_
+#define _ISSM_MPI_VEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/io/io.h"
+#include "../mpi/issmmpi.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create vectors that hold IssmDouble* vector or IssmPDouble* vector. 
+  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+template <class doubletype> class IssmAbsVec;
+
+template <class doubletype> 
+class IssmMpiVec:public IssmAbsVec<doubletype>{
+
+	public:
+
+		int M; //global size
+		int m; //local number of rows
+		doubletype* vector;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global vector.*/
+
+		/*IssmMpiVec constructors, destructors*/
+		IssmMpiVec(){/*{{{*/
+
+			this->M=0;
+			this->m=0;
+			this->vector=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		IssmMpiVec(int Min){/*{{{*/
+			this->Init(Min,false);
+		}
+		/*}}}*/
+		IssmMpiVec(int min, int Min){/*{{{*/
+			this->Init(min,true);
+		}
+		/*}}}*/
+		IssmMpiVec(int Min, bool fromlocalsize){/*{{{*/
+			this->Init(Min,fromlocalsize);
+		}
+		/*}}}*/
+		IssmMpiVec(doubletype* buffer,int Min){/*{{{*/
+
+			this->Init(Min,false);
+
+			if(this->M){
+				this->vector=xNew<doubletype>(this->m);
+				xMemCpy<doubletype>(this->vector,buffer,this->m);
+			}
+		}
+		/*}}}*/
+		IssmMpiVec(doubletype* buffer,int Min,int min){/*{{{*/
+
+			this->vector=NULL;
+			this->buckets=new DataSet();
+			this->M=Min;
+			this->m=min;
+
+			if(this->m){
+				this->vector=xNew<doubletype>(this->m);
+				xMemCpy<doubletype>(this->vector,buffer,this->m);
+			}
+		}
+		/*}}}*/
+		void Init(int Min,bool fromlocalsize){/*{{{*/
+
+			this->buckets=new DataSet();
+
+			if(fromlocalsize){
+				this->m=Min;
+				this->M=DetermineGlobalSize(this->m,IssmComm::GetComm());
+			}
+			else{
+				this->M=Min;
+				this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+			}
+
+			/*Initialize pointer: */
+			this->vector=NULL;
+
+			/*Allocate: */
+			if (m)this->vector=xNewZeroInit<doubletype>(this->m);
+		}
+		/*}}}*/
+		~IssmMpiVec(){/*{{{*/
+			xDelete<doubletype>(this->vector);
+			this->M=0;
+			this->m=0;
+			delete buckets;
+		}
+		/*}}}*/
+
+		/*IssmMpiVec specific routines*/
+		void Echo(void){/*{{{*/
+
+			int i,j;
+
+			/*Do a synchronized dump across all the rows: */
+			for(i=0;i<IssmComm::GetSize();i++){
+				if (IssmComm::GetRank()==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for (j=0;j<this->m;j++){
+						_printf_("row " << j << " " << this->vector[j] << "\n");
+					}
+					_printf_("\n");
+				}
+				ISSM_MPI_Barrier(IssmComm::GetComm());
+			}
+		}
+		/*}}}*/
+		void Assemble(){/*{{{*/
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
+
+			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			numvalues_fromcpu   = xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*Scatter values around: {{{*/
+			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			for(i=0;i<num_procs;i++){
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+			}
+			/*}}}*/
+
+			/*Plug values into global vector: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					if(mods[j]==ADD_VAL) *(vector+(rows[j]-lower_row))+=values[j];
+					else *(vector+(rows[j]-lower_row))=values[j];
+				}
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the vector on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(ssize, list, values, mode));
+
+		}
+		/*}}}*/
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
+
+			/*we need to store the value we collect here in order to Assemble later. 
+			 * Indeed, the value we are collecting here most of the time will not belong 
+			 * to us, but to another part of the vector on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(1,&dof,&value, mode));
+		}
+		/*}}}*/
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
+			_error_("Get value on a MpiVec vector not implemented yet!");
+		}
+		/*}}}*/
+		void GetSize(int* pM){/*{{{*/
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM){/*{{{*/
+
+			*pM=this->m;
+
+		}
+		/*}}}*/
+		IssmMpiVec<doubletype>* Duplicate(void){/*{{{*/
+
+			return new IssmMpiVec<doubletype>(this->vector,this->M,this->m);
+
+		}
+		/*}}}*/
+		void Set(doubletype value){/*{{{*/
+
+			int i;
+			for(i=0;i<this->m;i++)this->vector[i]=value;
+
+		}
+		/*}}}*/
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmMpiVec* X=NULL;
+
+			X=(IssmMpiVec<doubletype>*)Xin;
+
+			/*y=a*x+y where this->vector is y*/
+			for(i=0;i<this->m;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
+
+		}
+		/*}}}*/
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmMpiVec* X=NULL;
+
+			X=(IssmMpiVec<doubletype>*)Xin;
+
+			/*y=x+a*y where this->vector is y*/
+			for(i=0;i<this->m;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype* ToMPISerial(void){/*{{{*/
+
+			/*communicator info: */
+			ISSM_MPI_Comm comm;
+			int num_procs;
+
+			/*ISSM_MPI_Allgatherv info: */
+			int  lower_row,upper_row;
+			int* recvcounts=NULL;
+			int* displs=NULL;
+
+			/*output: */
+			doubletype* buffer=NULL;
+
+			/*initialize comm info: */
+			comm=IssmComm::GetComm();
+			num_procs=IssmComm::GetSize();
+
+			/*Allocate: */
+			buffer=xNew<doubletype>(M);
+			recvcounts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+
+			/*recvcounts:*/
+			ISSM_MPI_Allgather(&this->m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+			/*get lower_row: */
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,this->m,comm);
+
+			/*displs: */
+			ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+			/*All gather:*/
+			ISSM_MPI_Allgatherv(this->vector, this->m, ISSM_MPI_DOUBLE, buffer, recvcounts, displs, ISSM_MPI_DOUBLE,comm);
+
+			/*free ressources: */
+			xDelete<int>(recvcounts);
+			xDelete<int>(displs);
+
+			/*return: */
+			return buffer;
+
+		}
+		/*}}}*/
+		void Copy(IssmAbsVec<doubletype>* toin){/*{{{*/
+
+			int i;
+
+			/*Assume toin is of the correct type, and downcast: */
+			IssmMpiVec* to=NULL;
+
+			to=(IssmMpiVec<doubletype>*)toin;
+
+			to->M=this->M;
+			for(i=0;i<this->m;i++)to->vector[i]=this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+
+			doubletype local_norm;
+			doubletype norm;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					//local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,fabs(this->vector[i]));
+					local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,this->vector[i]);
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return norm;
+					break;
+				case NORM_TWO:
+					local_norm=0; 
+					for(i=0;i<this->m;i++)local_norm+=pow(this->vector[i],2);
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+					return sqrt(norm);
+					break;
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		void Scale(doubletype scale_factor){/*{{{*/
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){/*{{{*/
+
+			int i;
+			doubletype local_dot=0;
+			doubletype dot=0;
+
+			/*Assume inputin is of the correct type, and downcast: */
+			IssmMpiVec* input=NULL;
+
+			input=(IssmMpiVec<doubletype>*)inputin;
+
+			for(i=0;i<this->m;i++)local_dot+=this->vector[i]*input->vector[i];
+
+			/*ISSM_MPI_SUM all the dots across the cluster: */
+			ISSM_MPI_Reduce(&local_dot, &dot, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+			ISSM_MPI_Bcast(&dot,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+			return dot;
+		}
+		/*}}}*/
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){/*{{{*/
+
+			int i;
+
+			/*Assume xin and yin are of the correct type, and downcast: */
+			IssmMpiVec* x=NULL;
+			IssmMpiVec* y=NULL;
+
+			x=(IssmMpiVec<doubletype>*)xin;
+			y=(IssmMpiVec<doubletype>*)yin;
+
+			/*pointwise w=x/y where this->vector is w: */
+			for(i=0;i<this->m;i++)this->vector[i]=x->vector[i]/y->vector[i];
+		}
+		/*}}}*/
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+};
+#endif //#ifndef _ISSM_MPI_VEC_H_	
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSeqVec.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSeqVec.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSeqVec.h	(revision 18231)
@@ -0,0 +1,275 @@
+/*!\file:  IssmSeqVec.h
+ * \brief implementation of an ISSM vector which run serially (1 cpu only), which is made of a fully dense 
+ * vector. Internally, this dense vector is just a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsVec, 
+ * and the contructors required by IssmVec (see IssmVec.h)
+ */ 
+
+#ifndef _ISSM_SEQ_VEC_H_
+#define _ISSM_SEQ_VEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create vectors that hold IssmDouble* vector or IssmPDouble* vector. 
+  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsVec;
+
+template <class doubletype> 
+class IssmSeqVec: public IssmAbsVec<doubletype>{
+
+	public:
+
+		doubletype* vector;
+		int M;
+
+		/*IssmSeqVec constructors, destructors*/
+		IssmSeqVec(){/*{{{*/
+
+			this->M=0;
+			this->vector=NULL;
+		}
+		/*}}}*/
+		IssmSeqVec(int pM){/*{{{*/
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		IssmSeqVec(int pm,int pM){/*{{{*/
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		IssmSeqVec(int pM,bool fromlocalsize){/*{{{*/
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		IssmSeqVec(doubletype* buffer,int pM){/*{{{*/
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M){
+				this->vector=xNew<doubletype>(pM);
+				xMemCpy<doubletype>(this->vector,buffer,pM);
+			}
+		}
+		/*}}}*/
+		~IssmSeqVec(){/*{{{*/
+			if(this->M)xDelete<doubletype>(this->vector);
+			M=0;
+		}
+		/*}}}*/
+
+		/*IssmSeqVec specific routines*/
+		void Echo(void){/*{{{*/
+
+			int i;
+			_printf_("IssmSeqVec size " << this->M << "\n");
+			for(i=0;i<M;i++){
+				_printf_(vector[i] << "\n ");
+			}
+		}
+		/*}}}*/
+		void Assemble(void){/*{{{*/
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
+
+			int i;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]+=values[i];
+					break;
+				case INS_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]=values[i];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
+
+			switch(mode){
+				case ADD_VAL:
+					this->vector[dof]+=value;
+					break;
+				case INS_VAL:
+					this->vector[dof]=value;
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+		}
+		/*}}}*/
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
+
+			*pvalue=this->vector[dof];
+
+		}
+		/*}}}*/
+		void GetSize(int* pM){/*{{{*/
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM){/*{{{*/
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		IssmSeqVec<doubletype>* Duplicate(void){/*{{{*/
+
+			return new IssmSeqVec<doubletype>(this->vector,this->M);
+
+		}
+		/*}}}*/
+		void Set(doubletype value){/*{{{*/
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=value;
+
+		}
+		/*}}}*/
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmSeqVec* X=NULL;
+
+			X=(IssmSeqVec<doubletype>*)Xin;
+
+			/*y=a*x+y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
+
+		}
+		/*}}}*/
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmSeqVec* X=NULL;
+
+			X=(IssmSeqVec<doubletype>*)Xin;
+
+			/*y=x+a*y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype* ToMPISerial(void){/*{{{*/
+
+			doubletype* buffer=NULL;
+
+			if(this->M){
+				buffer=xNew<doubletype>(this->M);
+				xMemCpy<doubletype>(buffer,this->vector,this->M);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		void Copy(IssmAbsVec<doubletype>* toin){/*{{{*/
+
+			int i;
+
+			/*Assume toin is of the correct type, and downcast: */
+			IssmSeqVec* to=NULL;
+
+			to=(IssmSeqVec<doubletype>*)toin;
+
+			to->M=this->M;
+			for(i=0;i<this->M;i++)to->vector[i]=this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+
+			doubletype norm;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					//norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
+					norm=0; for(i=0;i<this->M;i++)norm=max(norm,this->vector[i]);
+					return norm;
+					break;
+				case NORM_TWO:
+					norm=0; 
+					for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
+					return sqrt(norm);
+					break;
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		void Scale(doubletype scale_factor){/*{{{*/
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
+
+		}
+		/*}}}*/
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){/*{{{*/
+
+			int i;
+
+			/*Assume inputin is of the correct type, and downcast: */
+			IssmSeqVec* input=NULL;
+
+			input=(IssmSeqVec<doubletype>*)inputin;
+
+			doubletype dot=0;
+			for(i=0;i<this->M;i++)dot+=this->vector[i]*input->vector[i];
+			return dot;
+
+		}
+		/*}}}*/
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){/*{{{*/
+
+			int i;
+
+			/*Assume xin and yin are of the correct type, and downcast: */
+			IssmSeqVec* x=NULL;
+			IssmSeqVec* y=NULL;
+
+			x=(IssmSeqVec<doubletype>*)xin;
+			y=(IssmSeqVec<doubletype>*)yin;
+
+			/*pointwise w=x/y where this->vector is w: */
+			for(i=0;i<this->M;i++)this->vector[i]=x->vector[i]/y->vector[i];
+		}
+		/*}}}*/
+};
+#endif //#ifndef _ISSM_SEQ_VEC_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.cpp	(revision 18231)
@@ -0,0 +1,24 @@
+/*!\file IssmSolver
+ * \brief implementation of solver 
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+
+#include "../../shared/shared.h"
+#include "./issmtoolkit.h"
+
+void IssmSolve(IssmVec<IssmDouble>** pout,IssmMat<IssmDouble>* Kff, IssmVec<IssmDouble>* pf, Parameters* parameters){/*{{{*/
+
+	/*Let matrix decide, to retain object orientation: */
+	IssmVec<IssmDouble>* outvector=NULL;
+
+	outvector=Kff->Solve(pf,parameters);
+
+	*pout=outvector;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmSolver.h	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file:  IssmSolver.h
+ * \brief main hook up from Solver toolkit object to the ISSM toolkit
+ */ 
+
+#ifndef _ISSM_SOLVER_H_
+#define _ISSM_SOLVER_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+
+/*}}}*/
+
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmMat;
+class Parameters;
+
+void IssmSolve(IssmVec<IssmDouble>** puf,IssmMat<IssmDouble>* Kff, IssmVec<IssmDouble>* pf,Parameters* parameters);
+
+#endif 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 18231)
@@ -0,0 +1,115 @@
+/*!\file:  IssmToolkitUtils.cpp
+ * \brief utilities used throughout our ISSM toolkit
+ */ 
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/io/Comm/IssmComm.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../ToolkitOptions.h"
+#include "./IssmToolkitUtils.h"
+#include <string.h>
+/*}}}*/
+
+/*Routines: */
+int IssmMatTypeFromToolkitOptions(void){ /*{{{*/
+
+	char *mat_type      = NULL;
+	int   mat_type_enum;
+	int   num_procs     = 0;
+	bool  isparallel    = false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve matrix type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc matrix types: */
+	mat_type=ToolkitOptions::GetToolkitOptionValue("mat_type");
+
+	if (strcmp(mat_type,"mpidense")==0){
+		mat_type_enum=MpiDenseEnum;
+	}
+	else if (strcmp(mat_type,"mpisparse")==0){
+		mat_type_enum=MpiSparseEnum;
+	}
+	else if (strcmp(mat_type,"dense")==0){
+		if (isparallel) _error_("Dense matrix type not supported for parallel runs with num_procs>1");
+		else mat_type_enum=DenseEnum;
+	}
+	else _error_("matrix type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(mat_type);
+
+	/*return: */
+	return mat_type_enum;
+} /*}}}*/
+int IssmVecTypeFromToolkitOptions(void){ /*{{{*/
+
+	char* vec_type=NULL;
+	int   vec_type_enum;
+	int   num_procs=0;
+	bool  isparallel=false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve vector type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc vector types: */
+	vec_type=ToolkitOptions::GetToolkitOptionValue("vec_type");
+
+	if (strcmp(vec_type,"mpi")==0){
+		vec_type_enum=MpiEnum;
+	}
+	else if (strcmp(vec_type,"seq")==0){
+		if (isparallel) _error_("Dense vector type not supported for parallel runs with num_procs>1");
+		else vec_type_enum=SeqEnum;
+	}
+	else _error_("vector type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(vec_type);
+
+	/*return: */
+	return vec_type_enum;
+} /*}}}*/  
+int IssmSolverTypeFromToolkitOptions(void){ /*{{{*/
+
+	char* solver_type=NULL;
+	int   solver_type_enum;
+	int   num_procs=0;
+	bool  isparallel=false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve solver type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc vector types: */
+	solver_type=ToolkitOptions::GetToolkitOptionValue("solver_type");
+
+	if (strcmp(solver_type,"mumps")==0){
+		solver_type_enum=MumpsEnum;
+	}
+	else if (strcmp(solver_type,"gsl")==0){
+		if (isparallel) _error_("Gsl solver type not supported for parallel runs with num_procs>1");
+		else solver_type_enum=GslEnum;
+	}
+	else _error_("solver type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(solver_type);
+
+	/*return: */
+	return solver_type_enum;
+} /*}}}*/  
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 18231)
@@ -0,0 +1,22 @@
+/*!\file:  IssmToolkitUtils.h
+ * \brief routines used throughout the ISSM toolkit
+ */ 
+
+#ifndef _ISSM_TOOLKIT_UTILS_H_
+#define _ISSM_TOOLKIT_UTILS_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*}}}*/
+
+int IssmMatTypeFromToolkitOptions(void);
+int IssmVecTypeFromToolkitOptions(void);
+int IssmSolverTypeFromToolkitOptions(void);
+
+#endif //#ifndef _ISSMMAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmVec.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmVec.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/IssmVec.h	(revision 18231)
@@ -0,0 +1,204 @@
+/*!\file:  IssmVec.h
+ * \brief Main Vector class for the Issm toolkit. 
+ */ 
+
+#ifndef _ISSMVEC_H_
+#define _ISSMVEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "./IssmToolkitUtils.h"
+#include <math.h>
+/*}}}*/
+
+/*We need to template this class, in case we want to create Vectors that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such vectors are useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)
+*/
+int IssmVecTypeFromToolkitOptions(void);
+template <class doubletype> class IssmSeqVec;
+template <class doubletype> class IssmMpiVec;
+
+template <class doubletype> 
+class IssmVec{
+
+	public:
+
+		IssmAbsVec<doubletype>* vector; /*abstract vector, which implements object orientation*/
+
+		/*IssmVec constructors, destructors*/
+		IssmVec(){ /*{{{*/
+			this->vector=NULL;
+		}
+		/*}}}*/
+		IssmVec(int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(int m,int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(m,M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(m,M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(int M,bool fromlocalsize){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(M,fromlocalsize);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(M,fromlocalsize);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(doubletype* buffer,int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(buffer,M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(buffer,M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		~IssmVec(){/*{{{*/
+			delete this->vector;
+		}
+		/*}}}*/
+
+		/*IssmVec specific routines*/
+		void Echo(void){/*{{{*/
+			vector->Echo();
+		}
+		/*}}}*/
+		void Assemble(void){/*{{{*/
+			vector->Assemble();
+		}
+		/*}}}*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
+			vector->SetValues(ssize,list,values,mode);
+		}
+		/*}}}*/
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
+			vector->SetValue(dof,value,mode);
+		}
+		/*}}}*/
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
+			vector->GetValue(pvalue,dof);
+		}
+		/*}}}*/
+		void GetSize(int* pM){/*{{{*/
+			vector->GetSize(pM);
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM){/*{{{*/
+			vector->GetLocalSize(pM);
+		}
+		/*}}}*/
+		IssmVec<doubletype>* Duplicate(void){/*{{{*/
+
+			IssmVec<doubletype>* issmvector=NULL;
+
+			issmvector=new IssmVec<doubletype>();
+			issmvector->vector=this->vector->Duplicate();
+			this->vector->Copy(issmvector->vector);
+
+			return issmvector;
+		}
+		/*}}}*/
+		void Set(doubletype value){/*{{{*/
+			vector->Set(value);
+		}
+		/*}}}*/
+		void AXPY(IssmVec* X, doubletype a){/*{{{*/
+			vector->AXPY(X->vector,a);
+		}
+		/*}}}*/
+		void AYPX(IssmVec* X, doubletype a){/*{{{*/
+			vector->AYPX(X->vector,a);
+		}
+		/*}}}*/
+		doubletype* ToMPISerial(void){/*{{{*/
+			return vector->ToMPISerial();
+		}
+		/*}}}*/
+		void Copy(IssmVec* to){/*{{{*/
+			vector->Copy(to->vector);
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+			return vector->Norm(mode);
+		}
+		/*}}}*/
+		void Scale(doubletype scale_factor){/*{{{*/
+			vector->Scale(scale_factor);
+		}
+		/*}}}*/
+		doubletype Dot(IssmVec* input){/*{{{*/
+			return vector->Dot(input->vector);
+		}
+		/*}}}*/
+		void PointwiseDivide(IssmVec* x,IssmVec* y){/*{{{*/
+			vector->PointwiseDivide(x->vector,y->vector);
+		}
+		/*}}}*/
+};
+
+#endif //#ifndef _ISSMVEC_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/SparseRow.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/SparseRow.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/SparseRow.h	(revision 18231)
@@ -0,0 +1,154 @@
+/*!\file:  SparseRow: 
+ * \brief implementation of a sparse row, which can then be used to make a sparse matrix.
+ */ 
+
+#ifndef _SPARSE_ROW_H_
+#define _SPARSE_ROW_H_
+
+/*Headers:*/
+#include "../toolkitsenums.h"
+#include "../../shared/shared.h"
+
+template <class doubletype> 
+class SparseRow{
+
+	public:
+
+		int         M; //real size
+		int         ncols; //number of non-zeros 
+		int*        indices;
+		doubletype* values;
+		
+		/*SparseRow constructors, destructors*/
+		SparseRow(){ /*{{{*/
+			 M=0;
+			 ncols=0;
+			 indices=NULL;
+			 values=NULL;
+		} /*}}}*/
+		SparseRow(int in_M){/*{{{*/
+			
+			M=in_M;
+			ncols=0;
+			indices=NULL;
+			values=NULL;
+
+		} /*}}}*/
+		~SparseRow(){/*{{{*/
+			if(ncols){
+				xDelete<int>(indices);
+				xDelete<doubletype>(values);
+			}
+		} /*}}}*/
+
+		/*SparseRow specific routines*/
+		void Echo(){ /*{{{*/
+			int i;
+
+			for(i=0;i<ncols;i++){
+				_printf_("(" << indices[i] << "," << values[i] << ") ");
+			}
+		} /*}}}*/
+		void SetValues(int numvalues,int* cols,doubletype* vals, int* mods){ /*{{{*/
+
+			int count;
+			int i,j;
+
+			if(!M)_error_("unknow dimension for this sparse row!");
+
+			/*Deallocate if already allocated: */
+			if(ncols){
+				xDelete<int>(indices);
+				xDelete<doubletype>(values);
+			}
+
+			/*check numvalues: */
+			if(!numvalues)return;
+
+			/*Go through cols and resolve duplicates: */
+			for(i=0;i<numvalues;i++){
+				for(j=i+1;j<numvalues;j++){
+					if (cols[j]==cols[i]){
+						if (mods[j]==ADD_VAL){
+							vals[i]+=vals[j];
+						}
+						else vals[i]=vals[j];
+						cols[j]=-1;
+					}
+					/*Ensure that this value will not be used anymore: */
+				}
+			}
+
+			/*Now go through cols once more, and retrieve only what we need: */
+			ncols=0;
+			for(i=0;i<numvalues;i++)if(cols[i]>=0)ncols++;
+
+			/*Allocate and fill: */
+			indices=xNew<int>(ncols); _assert_(indices);
+			values=xNewZeroInit<doubletype>(ncols);  _assert_(values);
+			
+			count=0;
+			for(i=0;i<numvalues;i++){
+				if(cols[i]>=0){
+					indices[count]=cols[i];
+					values[count]=vals[i];
+					count++;
+				}
+			}
+		
+			if(count!=ncols)_error_("counter problem during set values operations");
+		} /*}}}*/
+		doubletype Norm(NormMode mode){ /*{{{*/
+
+			int i;
+			doubletype norm=0;
+
+			switch(mode){
+				case NORM_INF:
+					for(i=0;i<ncols;i++){
+						norm+=fabs(values[i]);
+					}
+					return norm;
+					break; 
+				case NORM_FROB:
+					for(i=0;i<ncols;i++){
+						norm+=pow(values[i],2);
+					}
+					return norm;
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		doubletype Mult(doubletype* X){ /*{{{*/
+
+			int i;
+			doubletype mult=0;
+
+			for(i=0;i<ncols;i++){
+				mult+=values[i]*X[indices[i]];
+			}
+			
+			return mult;
+		}
+		/*}}}*/
+		int Nnz(void){ /*{{{*/
+
+			return ncols;
+		}
+		/*}}}*/
+		void SetIrnJcnA(int* irn_loc,int* jcn_loc,doubletype* a_loc,int i_index,int count){/*{{{*/
+			int i;
+
+			for(i=0;i<ncols;i++){
+				irn_loc[count+i]=i_index;
+				jcn_loc[count+i]=indices[i]+1; //fortran indexing
+				a_loc[count+i]=values[i];
+			}
+		}
+		/*}}}*/
+};
+#endif //#ifndef _SPARSE_ROW_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/issmtoolkit.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/issmtoolkit.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/issm/issmtoolkit.h	(revision 18231)
@@ -0,0 +1,28 @@
+/* \file issmtoolkit.h
+ * \brief all includes for MPI layer
+ */
+
+#ifndef _ISSM_TOOLKIT_H_
+#define _ISSM_TOOLKIT_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmAbsMat.h"
+#include "./IssmAbsVec.h"
+#include "./IssmDenseMat.h"
+#include "./IssmMat.h"
+#include "./IssmSeqVec.h"
+#include "./IssmVec.h"
+#include "./IssmSolver.h"
+
+#ifdef _HAVE_MPI_
+#include "./IssmMpiDenseMat.h"
+#include "./IssmMpiSparseMat.h"
+#include "./IssmMpiVec.h"
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/metisincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/metisincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/metisincludes.h	(revision 18231)
@@ -0,0 +1,20 @@
+/* \file metisincludes.h
+ * \brief all includes from metis + our own patches
+ */
+
+#ifndef _METIS_INCLUDES_H_
+#define _METIS_INCLUDES_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Metis includes: */
+#include <metis.h>
+
+/*our own patches: */
+#include "patches/metispatches.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 18231)
@@ -0,0 +1,64 @@
+/*!\file METIS_PartMeshNodalPatch
+ * \brief common interface to Metis 4.0 and 5.0
+ */
+
+#include <config.h>
+#include "../metisincludes.h"
+#include "../../../shared/shared.h"
+
+void METIS_PartMeshNodalPatch(int* pnumberofelements,int* pnumberofnodes, int* index, int* petype, int* pnumflag, int* pnum_procs, int* pedgecut, int* epart, int* npart){
+
+	#if _METIS_VERSION_ == 4
+	/*Our interface originates in the Metis 4.0 version, hence identical calls*/
+	METIS_PartMeshNodal(pnumberofelements,pnumberofnodes, index, petype, pnumflag, pnum_procs, pedgecut, epart, npart); 
+	#elif _METIS_VERSION_ == 5
+	/*This interface is heavily changed. More options, different ways of meshing, etc ...: */ 
+	int i;
+
+	idx_t options[METIS_NOPTIONS];
+	idx_t objval;
+	idx_t* eptr=NULL;
+	idx_t  k=0;
+	real_t* tpwgts=NULL;
+
+	/*setup options: */
+	METIS_SetDefaultOptions(options);
+
+	options[METIS_OPTION_PTYPE]   = 1;
+	options[METIS_OPTION_OBJTYPE] = 0;
+	options[METIS_OPTION_CTYPE]   = 1;
+	options[METIS_OPTION_IPTYPE]  = 4;
+	options[METIS_OPTION_RTYPE]   = 1;
+	options[METIS_OPTION_DBGLVL]  = 0;
+	options[METIS_OPTION_UFACTOR] = 30;
+	options[METIS_OPTION_MINCONN] = 0;
+	options[METIS_OPTION_CONTIG]  = 0;
+	options[METIS_OPTION_SEED]    = -1;
+	options[METIS_OPTION_NITER]   = 10;
+	options[METIS_OPTION_NCUTS]   = 1;
+
+	/*create eptr: */
+	eptr=xNew<idx_t>((*pnumberofelements+1));
+	eptr[0]=0;
+	for(i=0;i<*pnumberofelements;i++){
+		k+=3;
+		eptr[i+1]=k;
+	}
+
+	/*create tpwgts: */
+	tpwgts=xNew<real_t>(*pnum_procs);
+	for(i=0;i<*pnum_procs;i++){
+		tpwgts[i]=1.0/(*pnum_procs);
+	}
+
+	METIS_PartMeshNodal(pnumberofelements,pnumberofnodes, eptr, index,
+			NULL, NULL, pnum_procs, tpwgts, options, &objval,epart, npart);
+
+	/*clean-up*/
+	xDelete<idx_t>(eptr);
+	xDelete<real_t>(tpwgts);
+
+	#else
+	_error_("METIS version not supported yet");
+	#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/metispatches.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/metispatches.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/metis/patches/metispatches.h	(revision 18231)
@@ -0,0 +1,28 @@
+/*\file metispatches.h
+ * \brief: our own patches for metis. Mainly to work through new apis from 4.0 to 5.0 version.
+ */
+
+#ifndef _METIS_PATCHES_H_
+#define _METIS_PATCHES_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+void METIS_PartMeshNodalPatch(int *, int *, int *, int *, int *, int *, int *, int *, int *); //Common interface we are using in ISSM.
+
+extern "C" {
+
+#if _METIS_VERSION_ == 4
+void METIS_PartMeshNodal(int *, int *, idxtype *, int *, int *, int *, int *, idxtype *, idxtype *);
+#endif
+#if _METIS_VERSION_ == 5
+int METIS_PartMeshNodal(idx_t*, idx_t*, idx_t*, idx_t*, idx_t*, idx_t*, idx_t*, real_t*, idx_t*, idx_t*, idx_t*, idx_t*);
+int METIS_SetDefaultOptions(idx_t *options);
+#endif
+
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp	(revision 18231)
@@ -0,0 +1,20 @@
+/* \file DetermineGlobalSize.cpp
+ * \brief: routine to determine global size from local size 
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+#include "../../../shared/Numerics/types.h"
+
+int DetermineGlobalSize(int local_size,ISSM_MPI_Comm comm){
+
+	/*output: */
+	int  global_size;
+
+	ISSM_MPI_Reduce(&local_size, &global_size, 1, ISSM_MPI_INT, ISSM_MPI_SUM, 0, comm);
+	ISSM_MPI_Bcast(&global_size,1,ISSM_MPI_INT,0,comm);
+
+	return global_size;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 18231)
@@ -0,0 +1,58 @@
+/* \file DetermineLocalSize.cpp
+ * \brief: routine to determine local size of a global petsc matrix or vector. 
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+
+int DetermineLocalSize(int global_size,ISSM_MPI_Comm comm){
+
+	/*output: */
+	int  local_size;
+
+	/*intermediary: */
+	int  i;
+	int  row_rest;
+	int* num_local_rows=NULL;
+
+	/*from MPI: */
+	int num_procs;
+	int my_rank;
+
+	/*recover my_rank*/
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+
+	/* TODO replace the following with ->
+
+	local_size=global_size/num_procs; // integer division
+	if (global_size%num_procs>my_rank) local_size++; // distribute the remainder
+	return local_size;
+
+	<- to here  */
+
+	/*We are  not bound by any library, just use what seems most logical*/
+	num_local_rows=xNew<int>(num_procs);    
+
+	for (i=0;i<num_procs;i++){
+		/*Here, we use floor. We under distribute rows. The rows 
+		  left  are then redistributed, therefore resulting in a 
+		  more even distribution.*/
+		num_local_rows[i]=(int)floor((double)global_size/(double)num_procs); 
+	}
+
+	/*There may be some rows left. Distribute evenly.*/ 
+	row_rest=global_size - num_procs*(int)floor((double)global_size/(double)num_procs);
+	for (i=0;i<row_rest;i++){
+		num_local_rows[i]++;
+	}
+	local_size=num_local_rows[my_rank];
+
+	/*free ressources: */
+	xDelete<int>(num_local_rows);
+
+	/*return size: */
+	return local_size;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 18231)
@@ -0,0 +1,46 @@
+/* \file DetermineRowRankFromLocalSize.cpp
+ * \brief: routine to determine, from local size of a matrix or vector (in terms of number 
+ * of rows), a vector of global size  which for each row of the matrix or vector, determines
+ * what cpu this row belong to.
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+#include "../../../shared/Numerics/types.h"
+
+int* DetermineRowRankFromLocalSize(int global_size,int localsize,ISSM_MPI_Comm comm){
+
+	/*intermediary: */
+	int i,j;
+	int my_rank=0;
+	int num_procs=0;
+	int lower_row,upper_row;
+
+	/*output: */
+	int* RowRank=NULL;
+
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+
+	/*allocate: */
+	RowRank=xNew<int>(global_size);
+
+	/*Gather all local_size values into alllocalsizes, for all cpus*/
+	int* alllocalsizes=xNew<int>(num_procs);
+	ISSM_MPI_Allgather(&localsize,1,ISSM_MPI_INT,alllocalsizes,1,ISSM_MPI_INT,comm);
+
+	/*From all localsizes, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+alllocalsizes[0];
+	for(j=lower_row;j<upper_row;j++)RowRank[j]=0;
+
+	for(i=1;i<num_procs;i++){
+		lower_row=lower_row+alllocalsizes[i-1];
+		upper_row=upper_row+alllocalsizes[i];
+		for(j=lower_row;j<upper_row;j++)RowRank[j]=i;
+	}
+	xDelete<int>(alllocalsizes);
+
+	return RowRank;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp	(revision 18231)
@@ -0,0 +1,45 @@
+/*! \file:  GetOwnershipBoundariesFromRange.cpp
+ *  \brief from a local range on each cpu, we determine what 
+ *  lower row and upper row from a matrix a cpu owns.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../../../shared/MemOps/MemOps.h"
+#include "../../../shared/io/Comm/IssmComm.h"
+
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,ISSM_MPI_Comm comm){
+
+	/*externals :*/
+	int my_rank;
+	int num_procs;
+
+	/*recover my_rank and num_procs:*/
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+
+	/*output: */
+	int lower_row,upper_row;
+
+	/*Gather all range values into allranges, for all nodes*/
+	int* allranges=xNew<int>(num_procs);
+	ISSM_MPI_Allgather(&range,1,ISSM_MPI_INT,allranges,1,ISSM_MPI_INT,comm);
+
+	/*From all ranges, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+allranges[0];
+	for(int i=1;i<=my_rank;i++){
+		lower_row=lower_row+allranges[i-1];
+		upper_row=upper_row+allranges[i];
+	}
+
+	/*Assign output*/
+	*plower_row=lower_row;
+	*pupper_row=upper_row;
+	xDelete<int>(allranges);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/commops.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/commops.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/commops/commops.h	(revision 18231)
@@ -0,0 +1,17 @@
+/*! \file mpipatches.h
+ *  \brief: prototype header for all ISSM add-ons to MPI
+ */
+
+#ifndef MPI_PATCHES_H_ 
+#define MPI_PATCHES_H_
+
+#include "../../../shared/Numerics/types.h" 
+#include "../../../shared/io/Comm/IssmComm.h"
+#include "../../mpi/issmmpi.h"
+
+int DetermineLocalSize(int global_size,ISSM_MPI_Comm comm);
+int* DetermineRowRankFromLocalSize(int global_size,int localsize,ISSM_MPI_Comm comm);
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,ISSM_MPI_Comm comm);
+int DetermineGlobalSize(int local_size,ISSM_MPI_Comm comm);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.cpp	(revision 18231)
@@ -0,0 +1,495 @@
+/* \file issmmpi.cpp
+ * \brief: implementation of all the mpi wrappers that ISSM requires. The goal is to control 
+ * which MPI layer we are using at compile time: the standard mpi, the autodiff mpi or no mpi at all.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cassert>
+#include <cstring> // for memcpy
+
+#include "./issmmpi.h"
+#include "../../shared/Numerics/types.h"
+
+#ifndef _HAVE_MPI_
+ISSM_MPI_Status ourIssmMPIStatusIgnore=0;
+size_t sizeHelper(ISSM_MPI_Datatype type) { /*{{{*/
+
+  switch(type) { 
+  case ISSM_MPI_CHAR: 
+    return sizeof(char);
+    break;
+  case ISSM_MPI_DOUBLE: 
+    return sizeof(double);
+    break;
+  case ISSM_MPI_INT: 
+    return sizeof(int);
+    break;
+  default: 
+    assert(0);
+    break;
+  }
+  return 0;
+}/*}}}*/
+#endif
+
+int ISSM_MPI_Allgather(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcount, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm) {  /*{{{*/
+  int rc=0;
+  assert(sendcount==recvcount || sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allgather(sendbuf,
+		    sendcount,
+		    sendtype,
+		    recvbuf,
+		    recvcount,
+		    recvtype,
+		    comm);
+# else
+  rc=MPI_Allgather(sendbuf,
+		   sendcount,
+		   sendtype,
+		   recvbuf,
+		   recvcount,
+		   recvtype,
+		   comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<sendcount;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*sendcount);
+#endif
+  return rc;
+} /*}}}*/
+int ISSM_MPI_Allgatherv(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm) {  /*{{{*/
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allgatherv(sendbuf,
+		     sendcount,
+		     sendtype,
+		     recvbuf,
+		     recvcounts,
+		     displs,
+		     recvtype,
+		     comm);
+# else
+  rc=MPI_Allgatherv(sendbuf,
+		    sendcount,
+		    sendtype,
+		    recvbuf,
+		    recvcounts,
+		    displs,
+		    recvtype,
+		    comm);
+# endif
+#else
+  assert(sendcount==recvcounts[0]); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)(recvbuf)+displs[0];
+    for(int i=0;i<sendcount;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy((char*)recvbuf+(sizeHelper(recvtype)*displs[0]),sendbuf,sizeHelper(sendtype)*sendcount);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Allreduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, ISSM_MPI_Comm comm){/*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allreduce(sendbuf,
+		    recvbuf,
+		    count,
+		    datatype,
+		    op,
+		    comm);
+# else
+  rc=MPI_Allreduce(sendbuf,
+		   recvbuf,
+		   count,
+		   datatype,
+		   op,
+		   comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (datatype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<count;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(datatype)*count);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Barrier(ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Barrier(comm);
+# else 
+  rc=MPI_Barrier(comm);
+# endif
+#else
+// do nothing
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Bcast(void *buffer, int count, ISSM_MPI_Datatype datatype, int root, ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Bcast(buffer, 
+		count,
+		datatype,
+		root,
+		comm);
+# else
+  rc=MPI_Bcast(buffer, 
+	       count,
+	       datatype,
+	       root,
+	       comm);
+# endif
+#else 
+// nothing to be done here 
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_free(ISSM_MPI_Comm *comm){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  assert(0); // to be implemented
+# else 
+  rc=MPI_Comm_free(comm);
+# endif
+#else
+// do nothing
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_rank(ISSM_MPI_Comm comm, int *rank){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+  rc=MPI_Comm_rank(comm,
+		   rank);
+#else
+  *rank=0;
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_size( ISSM_MPI_Comm comm, int *size){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+  rc=MPI_Comm_size(comm,
+		   size);
+#else
+  *size=1;
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Finalize(void){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Finalize_NT();
+# else
+  rc=MPI_Finalize();
+# endif
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Gather(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Gather(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnt,
+		 recvtype,
+		 root,
+		 comm);
+# else
+  rc=MPI_Gather(sendbuf,
+		sendcnt,
+		sendtype,
+		recvbuf,
+		recvcnt,
+		recvtype,
+		root,
+		comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<sendcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*sendcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Gatherv(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcnts, int *displs, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){/*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Gatherv(sendbuf,
+		  sendcnt,
+		  sendtype,
+		  recvbuf,
+		  recvcnts,
+		  displs,
+		  recvtype,
+		  root,
+		  comm);
+# else
+  rc=MPI_Gatherv(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnts,
+		 displs,
+		 recvtype,
+		 root,
+		 comm);
+# endif
+#else
+  assert(sendcnt==recvcnts[0]); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)(recvbuf)+displs[0];
+    for(int i=0;i<sendcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy((char*)recvbuf+(sizeHelper(recvtype)*displs[0]),sendbuf,sizeHelper(sendtype)*sendcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Init(int *argc, char ***argv){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Init_NT(argc,argv);
+# else
+  rc=MPI_Init(argc,argv);
+# endif
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Recv(void *buf, int count, ISSM_MPI_Datatype datatype, int source, int tag, ISSM_MPI_Comm comm, ISSM_MPI_Status *status){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Recv(buf, 
+	       count,
+	       datatype,
+	       source,
+	       tag,
+	       AMPI_FROM_SEND, // as long as there are no other variants
+	       comm,
+	       status);
+# else
+  rc=MPI_Recv(buf, 
+	      count,
+	      datatype,
+	      source,
+	      tag,
+	      comm,
+	      status);
+# endif
+#else 
+// nothing to be done here 
+// as long as nobody tries to do anything with 'status' 
+// we won't do anything to it here either
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Reduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Reduce(sendbuf,
+		 recvbuf,
+		 count,
+		 datatype,
+		 op,
+		 root,
+		 comm);
+# else
+  rc=MPI_Reduce(sendbuf,
+		recvbuf,
+		count,
+		datatype,
+		op,
+		root,
+		comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (datatype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<count;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(datatype)*count);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Scatter(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Scatter(sendbuf,
+		  sendcnt,
+		  sendtype,
+		  recvbuf,
+		  recvcnt,
+		  recvtype,
+		  root,
+		  comm);
+# else
+  rc=MPI_Scatter(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnt,
+		 recvtype,
+		 root,
+		 comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<recvcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*recvcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Scatterv(void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Scatterv(sendbuf,
+		   sendcnts,
+		   displs,
+		   sendtype,
+		   recvbuf,
+		   recvcnt,
+		   recvtype,
+		   root,
+		   comm);
+# else
+  rc=MPI_Scatterv(sendbuf,
+		  sendcnts,
+		  displs,
+		  sendtype,
+		  recvbuf,
+		  recvcnt,
+		  recvtype,
+		  root,
+		  comm);
+# endif
+#else
+  assert(sendcnts[0]==recvcnt); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)(sendbuf)+displs[0];
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<recvcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,(char*)sendbuf+(sizeHelper(sendtype)*displs[0]),sizeHelper(sendtype)*recvcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Send(void *buf, int count, ISSM_MPI_Datatype datatype, int dest, int tag, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Send(buf, 
+	       count,
+	       datatype,
+	       dest,
+	       tag,
+	       AMPI_TO_RECV, // as long as there are no other variants
+	       comm);
+# else
+  rc=MPI_Send(buf, 
+	      count,
+	      datatype,
+	      dest,
+	      tag,
+	      comm);
+# endif
+#else 
+// nothing to be done here 
+#endif
+  return rc;
+}/*}}}*/
+double ISSM_MPI_Wtime(void){/*{{{*/
+
+#ifdef _HAVE_MPI_
+	return MPI_Wtime();
+#else 
+	assert(0); // to be implemented
+	return 0.0;
+#endif
+}/*}}}*/
+void ISSM_MPI_ContiguousInAdolc(size_t aSize) { /*{{{*/
+
+#ifdef _HAVE_ADOLC_
+  ensureContiguousLocations(aSize);
+#endif
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mpi/issmmpi.h	(revision 18231)
@@ -0,0 +1,144 @@
+/* \file issmmpi.h
+ * \brief: header file that defines all the mpi wrappers that ISSM requires. The goal is to control 
+ * which MPI layer we are using at compile time: the standard mpi, the autodiff mpi or no mpi at all.
+ */
+
+#ifndef _ISSM_MPI_H_
+#define _ISSM_MPI_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstddef>
+#include <cassert>
+#include "../../shared/Numerics/types.h"
+
+#ifdef _HAVE_MPI_
+	/*Include header files: {{{*/
+	#ifdef _HAVE_AMPI_
+		#include <ampi/ampi.h>
+	#else 
+		#include <mpi.h>
+	#endif
+	/*}}}*/
+	/*MPI defines: *{{{*/
+	// types
+	typedef MPI_Comm             ISSM_MPI_Comm;
+	typedef MPI_Datatype         ISSM_MPI_Datatype;
+	typedef MPI_Op               ISSM_MPI_Op;
+	typedef MPI_Status           ISSM_MPI_Status;
+
+	// data types
+	#define ISSM_MPI_CHAR       MPI_CHAR
+	#ifdef _HAVE_AMPI_
+		#define ISSM_MPI_DOUBLE    AMPI_ADOUBLE // corresponds to IssmDouble
+	#else 
+		#define ISSM_MPI_DOUBLE    MPI_DOUBLE  // corresponds to IssmDouble 
+	#endif
+	#define ISSM_MPI_PDOUBLE    MPI_DOUBLE  // corresponds to IssmPDouble
+	#define ISSM_MPI_INT        MPI_INT
+
+	// operations
+	#define ISSM_MPI_MAX        MPI_MAX
+	#define ISSM_MPI_MIN        MPI_MIN
+	#define ISSM_MPI_PROD       MPI_PROD
+	#define ISSM_MPI_SUM        MPI_SUM
+
+	// others
+	#define ISSM_MPI_COMM_WORLD    MPI_COMM_WORLD
+	#define ISSM_MPI_STATUS_IGNORE MPI_STATUS_IGNORE
+	#define ISSM_MPI_ANY_TAG       MPI_ANY_TAG
+	#define ISSM_MPI_ANY_SOURCE    MPI_ANY_SOURCE
+
+    /*other include files: */
+	#include "./commops/commops.h"
+	/*}}}*/
+#else  
+	/*Our ISSM MPI defines: {{{*/
+	// types
+	typedef int                  ISSM_MPI_Comm;
+	typedef int                  ISSM_MPI_Datatype;
+	typedef int                  ISSM_MPI_Op;
+	typedef int                  ISSM_MPI_Status;
+
+	// data types
+	#define ISSM_MPI_CHAR       1
+	#define ISSM_MPI_DOUBLE     2
+	#define ISSM_MPI_PDOUBLE    3
+	#define ISSM_MPI_INT        4
+
+	// operations
+	#define ISSM_MPI_MAX        1
+	#define ISSM_MPI_MIN        2
+	#define ISSM_MPI_PROD       3
+	#define ISSM_MPI_SUM        4
+
+	// others
+	#define ISSM_MPI_COMM_WORLD    1
+	extern ISSM_MPI_Status ourIssmMPIStatusIgnore;
+	#define ISSM_MPI_STATUS_IGNORE &ourIssmMPIStatusIgnore
+	#define ISSM_MPI_ANY_TAG       2
+	#define ISSM_MPI_ANY_SOURCE    3
+	/*}}}*/
+# endif 
+
+template <class T> ISSM_MPI_Datatype TypeToMPIType(){assert(false);};
+template <> inline ISSM_MPI_Datatype TypeToMPIType<IssmDouble>(){return ISSM_MPI_DOUBLE;};
+template <> inline ISSM_MPI_Datatype TypeToMPIType<int>(){return ISSM_MPI_INT;};
+template <> inline ISSM_MPI_Datatype TypeToMPIType<char>(){return ISSM_MPI_CHAR;};
+template <class T> int ISSM_MPI_Bcast(T *buffer, int count,int root, ISSM_MPI_Comm comm){  /*{{{*/
+
+	int rc=0;
+
+	/*Get MPI type*/
+	ISSM_MPI_Datatype datatype = TypeToMPIType<T>();
+
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+	rc=AMPI_Bcast(buffer, 
+				count,
+				datatype,
+				root,
+				comm);
+# else
+	rc=MPI_Bcast(buffer, 
+				count,
+				datatype,
+				root,
+				comm);
+# endif
+#else 
+	// nothing to be done here 
+#endif
+	return rc;
+}/*}}}*/
+
+/* interfaces  {{{*/
+int ISSM_MPI_Allgather(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcount, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm);
+int ISSM_MPI_Allgatherv(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Allreduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Barrier(ISSM_MPI_Comm comm);
+int ISSM_MPI_Bcast(void *buffer, int count, ISSM_MPI_Datatype datatype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Comm_free(ISSM_MPI_Comm *comm);
+int ISSM_MPI_Comm_rank(ISSM_MPI_Comm comm, int *rank);
+int ISSM_MPI_Comm_size( ISSM_MPI_Comm comm, int *size);
+int ISSM_MPI_Finalize(void);
+int ISSM_MPI_Gather(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Gatherv(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcnts, int *displs, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Init(int *argc, char ***argv);
+int ISSM_MPI_Recv(void *buf, int count, ISSM_MPI_Datatype datatype, int source, int tag, ISSM_MPI_Comm comm, ISSM_MPI_Status *status);
+int ISSM_MPI_Reduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Scatter(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Scatterv(void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Send(void *buf, int count, ISSM_MPI_Datatype datatype, int dest, int tag, ISSM_MPI_Comm comm);
+double ISSM_MPI_Wtime(void);
+
+// special for Adol-C locations when buffers are allocated with new
+// this could end up in the xNew template specialized for adoubles 
+// so as to not litter the code with it.
+void ISSM_MPI_ContiguousInAdolc(size_t aSize);
+/*}}}*/
+
+#endif  //#ifndef _ISSM_MPI_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 18231)
@@ -0,0 +1,316 @@
+/*!\file MpiDenseMumpsSolve.cpp
+ * \brief: solve dense matrix system with MUMPS
+ */
+
+/*Header files: */
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/io/Comm/IssmComm.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../mpi/issmmpi.h"
+#include "../adolc/adolcincludes.h"
+#include "./mumpsincludes.h"
+
+/*Mumps header files: */
+#include <dmumps_c.h>
+
+void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc){ 
+	theMumpsStruc.par          = 1;  
+	theMumpsStruc.sym          = 0;
+	theMumpsStruc.comm_fortran = MPI_Comm_c2f(IssmComm::GetComm());
+	theMumpsStruc.job          = -1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsSettings(DMUMPS_STRUC_C &theMumpsStruc) { 
+	/*Control statements:{{{ */
+	theMumpsStruc.icntl[1-1] = 6; //error verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[2-1] = 0; //std verbose: default 1, 0 or negative -> suppressed
+	theMumpsStruc.icntl[3-1] = 0; //global information verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[4-1] = 0; //verbose everything: default is 4
+	theMumpsStruc.icntl[5-1] = 0;
+	theMumpsStruc.icntl[18-1] = 3;
+
+	theMumpsStruc.icntl[20-1] = 0;
+	theMumpsStruc.icntl[21-1] = 0;
+	theMumpsStruc.icntl[30-1] = 0;
+	/*}}}*/
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsAnalyze(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsAnalyze
+void MumpsFactorize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 2;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsFactorize
+void MumpsBacksubstitute(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 3;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded at least  by a call to MumpsInit
+void MumpsFinalize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = -2;
+	dmumps_c(&theMumpsStruc);
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc, IssmPDouble *a_loc, IssmPDouble *rhs, Parameters* parameters=0 /*unused here*/){
+	/*Initialize mumps*/
+	DMUMPS_STRUC_C theMumpsStruc;
+	MumpsInit(theMumpsStruc);
+	MumpsSettings(theMumpsStruc);
+
+	/*now setup the rest of theMumpsStruc */
+	theMumpsStruc.n=n;
+	theMumpsStruc.nz=nnz;
+	theMumpsStruc.nz_loc=local_nnz;
+	theMumpsStruc.irn_loc=irn_loc;
+	theMumpsStruc.jcn_loc=jcn_loc;
+	theMumpsStruc.a_loc=a_loc;
+	theMumpsStruc.rhs=rhs;
+	theMumpsStruc.nrhs=1;
+	theMumpsStruc.lrhs=1;
+
+	/*Solve system*/
+	MumpsAnalyze(theMumpsStruc);
+	MumpsFactorize(theMumpsStruc);
+	MumpsBacksubstitute(theMumpsStruc);
+	MumpsFinalize(theMumpsStruc);
+}
+
+#ifdef _HAVE_ADOLC_
+// prototype for active variant
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmDouble *a_loc,
+		IssmDouble *rhs,
+		Parameters* parameters);
+#endif 
+
+void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
+
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i,j;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
+	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if (uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if (uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
+	/*figure out number of non-zero entries: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0)local_nnz++;
+		}
+	}
+
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0){
+				irn_loc[count]=lower_row+i+1; //fortran indexing
+				jcn_loc[count]=j+1; //fortran indexing
+				a_loc[count]=Kff[i*Kff_N+j];
+				count++;
+			}
+		}
+	}
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+	/*displs: */
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+	/*Gather:*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
+
+	/*Cleanup*/
+	xDelete<int>(irn_loc);
+	xDelete<int>(jcn_loc);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
+	xDelete<int>(recvcounts);
+	xDelete<int>(displs);
+} /*}}}*/
+
+#ifdef _HAVE_ADOLC_
+
+int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *A=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+    local_irn[i]=iArr[3+i];
+    local_jcn[i]=iArr[3+local_nnz+i];
+    A[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_x[local_nnz+i];
+  }
+  MumpsSolve(n,nnz,local_nnz,local_irn,local_jcn,A,rhs_sol);
+  for (int i=0;i<n;++i) {
+    dp_y[i]=rhs_sol[i];
+  }
+  xDelete(rhs_sol);
+  xDelete(A);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 0;
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){
+  int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
+  int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
+  packedDimsSparseArr[0]=n;
+  packedDimsSparseArr[1]=nnz;
+  packedDimsSparseArr[2]=local_nnz;
+  for (int i=0;i<local_nnz;++i) {
+    packedDimsSparseArr[3+i]=irn_loc[i];
+    packedDimsSparseArr[3+local_nnz+i]=jcn_loc[i];
+  }
+  IssmDouble *pack_A_rhs=xNew<IssmDouble>(local_nnz+n);
+  for (int i=0;i<local_nnz;++i) { 
+    pack_A_rhs[i]=a_loc[i];
+  }
+  for (int i=0;i<n;++i) { 
+    pack_A_rhs[local_nnz+i]=rhs[i];
+  }
+  IssmPDouble *passivePack_A_rhs=xNew<IssmPDouble>(local_nnz+n);
+  IssmPDouble *passiveSol=xNew<IssmPDouble>(n);
+  IssmDouble *sol=xNew<IssmDouble>(n);
+  call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	       packedDimsSparseArrLength, packedDimsSparseArr,
+	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
+	       n, passiveSol,sol);
+  for (int i=0;i<n;++i) { 
+    rhs[i]=sol[i];
+  }
+  xDelete(sol);
+  xDelete(passiveSol);
+  xDelete(passivePack_A_rhs);
+  xDelete(pack_A_rhs);
+  xDelete(packedDimsSparseArr);
+}
+
+int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr, 
+			      int m, IssmPDouble *dp_U,
+			      int nPlusNz, IssmPDouble *dp_Z,
+			      IssmPDouble *dp_x, IssmPDouble *dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *a_loc=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+	  local_irn[i]=iArr[3+i];
+	  local_jcn[i]=iArr[3+local_nnz+i];
+	  a_loc[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_U[i];
+  }
+  DMUMPS_STRUC_C theMumpsStruc;
+  MumpsInit(theMumpsStruc);
+  MumpsSettings(theMumpsStruc);
+  theMumpsStruc.n=n;
+  theMumpsStruc.nz=nnz;
+  theMumpsStruc.nz_loc=local_nnz;
+  theMumpsStruc.irn_loc=local_irn;
+  theMumpsStruc.jcn_loc=local_jcn;
+  theMumpsStruc.a_loc=a_loc;
+  theMumpsStruc.rhs=rhs_sol;
+  theMumpsStruc.nrhs=1;
+  theMumpsStruc.lrhs=1;
+  theMumpsStruc.icntl[9-1] = 0; //solve for the transpose
+  MumpsAnalyze(theMumpsStruc);
+  MumpsFactorize(theMumpsStruc);
+  MumpsBacksubstitute(theMumpsStruc);
+  MumpsFinalize(theMumpsStruc);
+  // update the adjoint of the rhs:
+  for (int i=0;i<n;++i) {
+    dp_Z[local_nnz+i]+=rhs_sol[i];
+  }
+  // bcast dp_y (the solution of the forward system)
+  ISSM_MPI_Bcast(dp_y,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // bcast the adjoint of the right-hand-side, i.e. this solution
+  ISSM_MPI_Bcast(rhs_sol,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // update the adjoint of the matrix with the outer product of right-hand-side adjoint and the original solution
+  for (int i=0;i<local_nnz;++i) {
+    dp_Z[i]-=rhs_sol[iArr[3+i]-1]*dp_y[iArr[3+local_nnz+i]-1];
+  }
+  xDelete(rhs_sol);
+  xDelete(a_loc);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 3;
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MumpsSolve.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 18231)
@@ -0,0 +1,396 @@
+/*!\file MumpsSolve.cpp
+ * \brief: solve dense matrix system with MUMPS
+ */
+
+/*Header files: */
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/io/Comm/IssmComm.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../mpi/issmmpi.h"
+#include "../adolc/adolcincludes.h"
+#include "../issm/SparseRow.h"
+#include "./mumpsincludes.h"
+
+/*Mumps header files: */
+#include <dmumps_c.h>
+
+void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc){ 
+	theMumpsStruc.par          = 1;  
+	theMumpsStruc.sym          = 0;
+	theMumpsStruc.comm_fortran = MPI_Comm_c2f(IssmComm::GetComm());
+	theMumpsStruc.job          = -1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsSettings(DMUMPS_STRUC_C &theMumpsStruc) { 
+	/*Control statements:{{{ */
+	theMumpsStruc.icntl[1-1] = 6; //error verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[2-1] = 0; //std verbose: default 1, 0 or negative -> suppressed
+	theMumpsStruc.icntl[3-1] = 0; //global information verbose: default 6, 0 or negative -> suppressed
+	theMumpsStruc.icntl[4-1] = 0; //verbose everything: default is 4
+	theMumpsStruc.icntl[5-1] = 0;
+	theMumpsStruc.icntl[18-1] = 3;
+
+	theMumpsStruc.icntl[20-1] = 0;
+	theMumpsStruc.icntl[21-1] = 0;
+	theMumpsStruc.icntl[30-1] = 0;
+	/*}}}*/
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsAnalyze(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsAnalyze
+void MumpsFactorize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 2;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsFactorize
+void MumpsBacksubstitute(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 3;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded at least  by a call to MumpsInit
+void MumpsFinalize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = -2;
+	dmumps_c(&theMumpsStruc);
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc, IssmPDouble *a_loc, IssmPDouble *rhs, Parameters* parameters=0 /*unused here*/){
+	/*Initialize mumps*/
+	DMUMPS_STRUC_C theMumpsStruc;
+	MumpsInit(theMumpsStruc);
+	MumpsSettings(theMumpsStruc);
+
+	/*now setup the rest of theMumpsStruc */
+	theMumpsStruc.n=n;
+	theMumpsStruc.nz=nnz;
+	theMumpsStruc.nz_loc=local_nnz;
+	theMumpsStruc.irn_loc=irn_loc;
+	theMumpsStruc.jcn_loc=jcn_loc;
+	theMumpsStruc.a_loc=a_loc;
+	theMumpsStruc.rhs=rhs;
+	theMumpsStruc.nrhs=1;
+	theMumpsStruc.lrhs=1;
+
+	/*Solve system*/
+	MumpsAnalyze(theMumpsStruc);
+	MumpsFactorize(theMumpsStruc);
+	MumpsBacksubstitute(theMumpsStruc);
+	MumpsFinalize(theMumpsStruc);
+}
+
+#ifdef _HAVE_ADOLC_
+// prototype for active variant
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmDouble *a_loc,
+		IssmDouble *rhs,
+		Parameters* parameters);
+#endif 
+
+void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
+
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i,j;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
+	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if (uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if (uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
+	/*figure out number of non-zero entries: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0)local_nnz++;
+		}
+	}
+
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0){
+				irn_loc[count]=lower_row+i+1; //fortran indexing
+				jcn_loc[count]=j+1; //fortran indexing
+				a_loc[count]=Kff[i*Kff_N+j];
+				count++;
+			}
+		}
+	}
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+	/*displs: */
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+	/*Gather:*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
+
+	/*Cleanup*/
+	xDelete<int>(irn_loc);
+	xDelete<int>(jcn_loc);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
+	xDelete<int>(recvcounts);
+	xDelete<int>(displs);
+} /*}}}*/
+
+void MpiSparseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ SparseRow<IssmDouble>** Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
+
+	/*Variables*/
+	ISSM_MPI_Comm  comm;
+	int            num_procs;
+	int            i;
+	int            nnz,local_nnz;
+	int           *irn_loc    = NULL;
+	int           *jcn_loc    = NULL;
+	IssmDouble    *a_loc      = NULL;
+	int            count;
+	int            lower_row;
+	int            upper_row;
+	IssmDouble    *rhs        = NULL;
+	int           *recvcounts = NULL;
+	int           *displs     = NULL;
+
+	/*Communicator info */
+	num_procs = IssmComm::GetSize();
+	comm      = IssmComm::GetComm();
+
+	/*First, some checks*/
+	if(Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if(uf_M!=Kff_M || uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	if(uf_m!=Kff_m || uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
+
+	/*Initialize matrix */
+	/*figure out number of non-zero entries: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		local_nnz+=Kff[i]->Nnz();
+	}
+
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		Kff[i]->SetIrnJcnA(irn_loc,jcn_loc,a_loc,lower_row+i+1,count);
+		count+=Kff[i]->Nnz();
+	}
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
+
+	/*displs: */
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
+
+	/*Gather:*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,nnz,local_nnz,irn_loc,jcn_loc,a_loc,rhs,parameters);
+
+	/*Now scatter from cpu 0 to all other cpus*/
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
+
+	/*Cleanup*/
+	xDelete<int>(irn_loc);
+	xDelete<int>(jcn_loc);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
+	xDelete<int>(recvcounts);
+	xDelete<int>(displs);
+} /*}}}*/
+
+#ifdef _HAVE_ADOLC_
+
+int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *A=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+    local_irn[i]=iArr[3+i];
+    local_jcn[i]=iArr[3+local_nnz+i];
+    A[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_x[local_nnz+i];
+  }
+  MumpsSolve(n,nnz,local_nnz,local_irn,local_jcn,A,rhs_sol);
+  for (int i=0;i<n;++i) {
+    dp_y[i]=rhs_sol[i];
+  }
+  xDelete(rhs_sol);
+  xDelete(A);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 0;
+}
+
+void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){
+  int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
+  int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
+  packedDimsSparseArr[0]=n;
+  packedDimsSparseArr[1]=nnz;
+  packedDimsSparseArr[2]=local_nnz;
+  for (int i=0;i<local_nnz;++i) {
+    packedDimsSparseArr[3+i]=irn_loc[i];
+    packedDimsSparseArr[3+local_nnz+i]=jcn_loc[i];
+  }
+  IssmDouble *pack_A_rhs=xNew<IssmDouble>(local_nnz+n);
+  for (int i=0;i<local_nnz;++i) { 
+    pack_A_rhs[i]=a_loc[i];
+  }
+  for (int i=0;i<n;++i) { 
+    pack_A_rhs[local_nnz+i]=rhs[i];
+  }
+  IssmPDouble *passivePack_A_rhs=xNew<IssmPDouble>(local_nnz+n);
+  IssmPDouble *passiveSol=xNew<IssmPDouble>(n);
+  IssmDouble *sol=xNew<IssmDouble>(n);
+  call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	       packedDimsSparseArrLength, packedDimsSparseArr,
+	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
+	       n, passiveSol,sol);
+  for (int i=0;i<n;++i) { 
+    rhs[i]=sol[i];
+  }
+  xDelete(sol);
+  xDelete(passiveSol);
+  xDelete(passivePack_A_rhs);
+  xDelete(pack_A_rhs);
+  xDelete(packedDimsSparseArr);
+}
+
+int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr, 
+			      int m, IssmPDouble *dp_U,
+			      int nPlusNz, IssmPDouble *dp_Z,
+			      IssmPDouble *dp_x, IssmPDouble *dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *a_loc=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+	  local_irn[i]=iArr[3+i];
+	  local_jcn[i]=iArr[3+local_nnz+i];
+	  a_loc[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_U[i];
+  }
+  DMUMPS_STRUC_C theMumpsStruc;
+  MumpsInit(theMumpsStruc);
+  MumpsSettings(theMumpsStruc);
+  theMumpsStruc.n=n;
+  theMumpsStruc.nz=nnz;
+  theMumpsStruc.nz_loc=local_nnz;
+  theMumpsStruc.irn_loc=local_irn;
+  theMumpsStruc.jcn_loc=local_jcn;
+  theMumpsStruc.a_loc=a_loc;
+  theMumpsStruc.rhs=rhs_sol;
+  theMumpsStruc.nrhs=1;
+  theMumpsStruc.lrhs=1;
+  theMumpsStruc.icntl[9-1] = 0; //solve for the transpose
+  MumpsAnalyze(theMumpsStruc);
+  MumpsFactorize(theMumpsStruc);
+  MumpsBacksubstitute(theMumpsStruc);
+  MumpsFinalize(theMumpsStruc);
+  // update the adjoint of the rhs:
+  for (int i=0;i<n;++i) {
+    dp_Z[local_nnz+i]+=rhs_sol[i];
+  }
+  // bcast dp_y (the solution of the forward system)
+  ISSM_MPI_Bcast(dp_y,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // bcast the adjoint of the right-hand-side, i.e. this solution
+  ISSM_MPI_Bcast(rhs_sol,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // update the adjoint of the matrix with the outer product of right-hand-side adjoint and the original solution
+  for (int i=0;i<local_nnz;++i) {
+    dp_Z[i]-=rhs_sol[iArr[3+i]-1]*dp_y[iArr[3+local_nnz+i]-1];
+  }
+  xDelete(rhs_sol);
+  xDelete(a_loc);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 3;
+}
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/mumpsincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/mumpsincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/mumps/mumpsincludes.h	(revision 18231)
@@ -0,0 +1,31 @@
+/* \file mumpsincludes.h
+ * \brief all includes for MUMPS layer
+ */
+
+#ifndef _MUMPS_INCLUDES_H_
+#define _MUMPS_INCLUDES_H_
+
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+/*}}}*/
+
+class Parameters;
+template <class doubletype> class SparseRow;
+
+void MpiDenseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, IssmDouble* Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters);
+void MpiSparseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, SparseRow<IssmDouble>** Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters);
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+// call back functions:
+ADOLC_ext_fct_iArr mumpsSolveEDF;
+ADOLC_ext_fct_iArr_fos_reverse fos_reverse_mumpsSolveEDF;
+ADOLC_ext_fct_iArr_fov_reverse fov_reverse_mumpsSolveEDF;
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Matrix.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Matrix.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Matrix.h	(revision 18231)
@@ -0,0 +1,312 @@
+/*!\file:  Matrix.h
+ * \brief wrapper to matrix objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying matrix format.
+ */ 
+
+#ifndef _MATRIX_H_
+#define _MATRIX_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+#include "../../shared/Enum/Enum.h"
+#include "../petsc/petscincludes.h"
+#include "../issm/issmtoolkit.h"
+/*}}}*/
+
+enum matrixtype { PetscMatType, IssmMatType };
+
+template <class doubletype> class Vector;
+
+template <class doubletype> 
+class Matrix{
+
+	public:
+
+		int       type;
+		#ifdef _HAVE_PETSC_
+		PetscMat              *pmatrix;
+		#endif
+		IssmMat<doubletype>   *imatrix;
+
+		/*Matrix constructors, destructors*/
+		Matrix(){/*{{{*/
+			InitCheckAndSetType();
+		}
+		/*}}}*/
+		Matrix(int M,int N){/*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N);
+			}
+
+		}
+		/*}}}*/
+		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){/*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(m,n,M,N,d_nnz,o_nnz);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+			}
+
+		}
+		/*}}}*/
+		Matrix(int M,int N,double sparsity){/*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,sparsity);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N,sparsity);
+			}
+		}
+		/*}}}*/
+		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity){/*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(serial_mat,M,N,sparsity);
+			}
+
+		}
+		/*}}}*/
+		Matrix(int M,int N,int connectivity,int numberofdofspernode){/*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N,connectivity,numberofdofspernode);
+			}
+
+		}
+		/*}}}*/
+		~Matrix(){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				delete this->pmatrix;
+				#endif
+			}
+			else delete this->imatrix;
+
+		}
+		/*}}}*/
+		void InitCheckAndSetType(void){/*{{{*/
+
+			char* toolkittype=NULL;
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			imatrix=NULL;
+
+			/*retrieve toolkittype: */
+			toolkittype=ToolkitOptions::GetToolkitType();
+
+			/*set matrix type: */
+			if (strcmp(toolkittype,"petsc")==0){
+				#ifdef _HAVE_PETSC_
+				type=PetscMatType; 
+				#else
+				_error_("cannot create petsc matrix without PETSC compiled!");
+				#endif
+			}
+			else if(strcmp(toolkittype,"issm")==0){
+				/*let this choice stand:*/
+				type=IssmMatType;
+			}
+			else _error_("unknow toolkit type ");
+
+			/*Free ressources: */
+			xDelete<char>(toolkittype);
+		}
+		/*}}}*/
+
+		/*Matrix specific routines:*/
+		void Echo(void){/*{{{*/
+			_assert_(this);
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Echo();
+				#endif
+			}
+			else{
+				this->imatrix->Echo();
+			}
+
+		}
+		/*}}}*/
+		void AllocationInfo(void){/*{{{*/
+			_assert_(this);
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->AllocationInfo();
+				#endif
+			}
+			else{
+				//this->imatrix->AllocationInfo();
+				_error_("not supported yet");
+			}
+		}/*}}}*/
+		void Assemble(void){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Assemble();
+				#endif
+			}
+			else{
+				this->imatrix->Assemble();
+			}
+		}
+		/*}}}*/
+		IssmDouble Norm(NormMode norm_type){/*{{{*/
+
+			IssmDouble norm=0;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pmatrix->Norm(norm_type);
+				#endif
+			}
+			else{
+				norm=this->imatrix->Norm(norm_type);
+			}
+
+			return norm;
+		}
+		/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetSize(pM,pN);
+				#endif
+			}
+			else{
+				this->imatrix->GetSize(pM,pN);
+			}
+
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetLocalSize(pM,pN);
+				#endif
+			}
+			else{
+				this->imatrix->GetLocalSize(pM,pN);
+			}
+
+		}
+		/*}}}*/
+		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->MatMult(X->pvector,AX->pvector);
+				#endif
+			}
+			else{
+				this->imatrix->MatMult(X->ivector,AX->ivector);
+			}
+
+		}
+		/*}}}*/
+		Matrix<doubletype>* Duplicate(void){/*{{{*/
+
+			Matrix<doubletype>* output=new Matrix<doubletype>();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output->pmatrix=this->pmatrix->Duplicate();
+				#endif
+			}
+			else{
+				output->imatrix=this->imatrix->Duplicate();
+			}
+
+			return output;
+		}
+		/*}}}*/
+		doubletype* ToSerial(void){/*{{{*/
+
+			doubletype* output=NULL;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output=this->pmatrix->ToSerial();
+				#endif
+			}
+			else{
+				output=this->imatrix->ToSerial();
+			}
+
+			return output;
+		}
+		/*}}}*/
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->SetValues(m,idxm,n,idxn,values,mode);
+				#endif
+			}
+			else{
+				this->imatrix->SetValues(m,idxm,n,idxn,values,mode);
+			}
+		}
+		/*}}}*/
+		void Convert(MatrixType newtype){/*{{{*/
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Convert(newtype);
+				#endif
+			}
+			else{
+				this->imatrix->Convert(newtype);
+			}
+
+		}
+		/*}}}*/
+
+};
+
+#endif //#ifndef _MATRIX_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Solver.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Solver.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Solver.h	(revision 18231)
@@ -0,0 +1,86 @@
+/*!\file:  Solver.h
+ */ 
+
+#ifndef _SOLVER_CLASS_H_
+#define _SOLVER_CLASS_H_
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Matrix.h"
+#include "./Vector.h"
+#include "../issm/issmtoolkit.h"
+#include "../petsc/petscincludes.h"
+class Parameters;
+
+template <class doubletype> 
+class Solver{
+
+	private:
+		Matrix<doubletype>* Kff;
+		Vector<doubletype>* pf;
+		Vector<doubletype>* uf0;
+		Vector<doubletype>* df;
+		Parameters* parameters;
+
+	public:
+		/*Constructors, destructors:*/
+		Solver(){/*{{{*/
+		}
+		/*}}}*/
+		Solver(Matrix<doubletype>* Kff_in, Vector<doubletype>* pf_in, Vector<doubletype>* uf0_in,Vector<doubletype>* df_in, Parameters* parameters_in){/*{{{*/
+
+			/*In debugging mode, check that stiffness matrix and load vectors are not NULL (they can be empty)*/
+			_assert_(Kff_in);
+			_assert_(pf_in);
+
+			/*initialize fields: */
+			this->Kff=Kff_in;
+			this->pf=pf_in;
+			this->uf0=uf0_in;
+			this->df=df_in;
+			this->parameters=parameters_in;
+		}
+		/*}}}*/
+		~Solver(){/*{{{*/
+		}
+		/*}}}*/
+
+		/*Methods: */
+		Vector<doubletype>* Solve(void){ /*{{{*/
+
+			/*output: */
+			Vector<doubletype>* uf=NULL;
+
+			/*Initialize vector: */
+			uf=new Vector<doubletype>();
+
+			/*According to matrix type, use specific solvers: */
+			switch(Kff->type){
+				#ifdef _HAVE_PETSC_
+				case PetscMatType:{
+					PetscVec* uf0_vector = NULL;
+					PetscVec* df_vector  = NULL;
+					if(uf0) uf0_vector = uf0->pvector;
+					if(df)  df_vector  = df->pvector;
+					PetscSolve(&uf->pvector,Kff->pmatrix,pf->pvector,uf0_vector,df_vector,parameters);
+					break;
+								  }
+				#endif
+				case IssmMatType:{
+					IssmSolve(&uf->ivector,Kff->imatrix,pf->ivector,parameters);
+					break;
+								 }
+				default:
+					_error_("Matrix type: " << Kff->type << " not supported yet!");
+			}
+
+			/*allocate output pointer: */
+			return uf;
+		}
+		/*}}}*/
+};
+#endif //#ifndef _SOLVER_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Vector.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Vector.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/Vector.h	(revision 18231)
@@ -0,0 +1,353 @@
+/*!\file:  Vector.h
+ * \brief wrapper to vector objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying vector format.
+ */ 
+
+#ifndef _VECTOR_H_
+#define _VECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+#include "../../shared/Enum/Enum.h"
+#include "../petsc/petscincludes.h"
+#include "../issm/issmtoolkit.h"
+/*}}}*/
+
+enum vectortype { PetscVecType, IssmVecType };
+
+template <class doubletype> 
+class Vector{
+
+	public:
+
+		int  type;
+		#ifdef _HAVE_PETSC_
+		PetscVec* pvector;
+		#endif
+		IssmVec<doubletype>* ivector; 
+
+		/*Vector constructors, destructors */
+		Vector(){ /*{{{*/
+
+			InitCheckAndSetType();
+		}
+		/*}}}*/
+		Vector(int M,bool fromlocalsize=false){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(M,fromlocalsize);
+				#endif
+			}
+			else this->ivector=new IssmVec<doubletype>(M,fromlocalsize);
+
+		}
+		/*}}}*/
+		Vector(int m,int M){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+					this->pvector=new PetscVec(m,M);
+				 #endif
+			}
+			else this->ivector=new IssmVec<doubletype>(m,M);
+		}
+		/*}}}*/
+		Vector(doubletype* serial_vec,int M){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(serial_vec,M);
+				#endif
+			}
+			else this->ivector=new IssmVec<doubletype>(serial_vec,M);
+		}
+		/*}}}*/
+		~Vector(){ /*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				delete this->pvector;
+				#endif
+			}
+			else delete this->ivector;
+		}
+		/*}}}*/
+		#ifdef _HAVE_PETSC_
+		Vector(Vec petsc_vector){ /*{{{*/
+
+			this->type=PetscVecType;
+			this->ivector=NULL;
+			this->pvector=new PetscVec(petsc_vector);
+
+		}
+		/*}}}*/
+		#endif
+		void InitCheckAndSetType(void){ /*{{{*/
+
+			char* toolkittype=NULL;
+
+			#ifdef _HAVE_PETSC_
+			pvector=NULL;
+			#endif
+			ivector=NULL;
+
+			/*retrieve toolkittype: */
+			toolkittype=ToolkitOptions::GetToolkitType();
+
+			/*set vector type: */
+			if (strcmp(toolkittype,"petsc")==0){
+				#ifdef _HAVE_PETSC_
+				type=PetscVecType; 
+				#else
+				_error_("cannot create petsc vector without PETSC compiled!");
+				#endif
+			}
+			else if(strcmp(toolkittype,"issm")==0){
+				/*let this choice stand:*/
+				type=IssmVecType;
+			}
+			else _error_("unknow toolkit type ");
+
+			/*Free ressources: */
+			xDelete<char>(toolkittype);
+		}
+		/*}}}*/
+
+		/*Vector specific routines*/
+		void Echo(void){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Echo();
+				#endif
+			}
+			else this->ivector->Echo();
+
+		}
+		/*}}}*/
+		void Assemble(void){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Assemble();
+				#endif
+			}
+			else this->ivector->Assemble();
+
+		}
+		/*}}}*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){ _assert_(this);/*{{{*/
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValues(ssize,list,values,mode);
+				#endif
+			}
+			else this->ivector->SetValues(ssize,list,values,mode);
+
+		}
+		/*}}}*/
+		void SetValue(int dof, doubletype value, InsMode mode){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValue(dof,value,mode);
+				#endif
+			}
+			else this->ivector->SetValue(dof,value,mode);
+
+		}
+		/*}}}*/
+		void GetValue(doubletype* pvalue,int dof){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetValue(pvalue,dof);
+				#endif
+			}
+			else this->ivector->GetValue(pvalue,dof);
+
+		}
+		/*}}}*/
+		void GetSize(int* pM){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetSize(pM);
+				#endif
+			}
+			else this->ivector->GetSize(pM);
+
+		}
+		/*}}}*/
+		bool IsEmpty(void){/*{{{*/
+			int M;
+
+			_assert_(this);
+			this->GetSize(&M);
+
+			if(M==0) 
+				return true;
+			else
+				return false;
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetLocalSize(pM);
+				#endif
+			}
+			else this->ivector->GetLocalSize(pM);
+
+		}
+		/*}}}*/
+		Vector<doubletype>* Duplicate(void){_assert_(this);/*{{{*/
+
+			Vector<doubletype>* output=NULL;
+
+			output=new Vector<doubletype>();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				output->pvector=this->pvector->Duplicate();
+				#endif
+			}
+			else output->ivector=this->ivector->Duplicate();
+
+			return output;
+
+		}
+		/*}}}*/
+		void Set(doubletype value){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Set(value);
+				#endif
+			}
+			else this->ivector->Set(value);
+
+		}
+		/*}}}*/
+		void AXPY(Vector* X, doubletype a){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AXPY(X->pvector,a);
+				#endif
+			}
+			else this->ivector->AXPY(X->ivector,a);
+
+		}
+		/*}}}*/
+		void AYPX(Vector* X, doubletype a){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AYPX(X->pvector,a);
+				#endif
+			}
+			else this->ivector->AYPX(X->ivector,a);
+		}
+		/*}}}*/
+		doubletype* ToMPISerial(void){/*{{{*/
+
+			doubletype* vec_serial=NULL;
+
+			_assert_(this);
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				vec_serial=this->pvector->ToMPISerial();
+				#endif
+			}
+			else vec_serial=this->ivector->ToMPISerial();
+
+			return vec_serial;
+
+		}
+		/*}}}*/
+		void Copy(Vector* to){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Copy(to->pvector);
+				#endif
+			}
+			else this->ivector->Copy(to->ivector);
+		}
+		/*}}}*/
+		doubletype Max(void){_assert_(this);/*{{{*/
+
+			doubletype max=0;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				max=this->pvector->Max();
+				#endif
+			}
+			else _error_("operation not supported yet");
+			return max;
+		}
+		/*}}}*/
+		doubletype Norm(NormMode norm_type){_assert_(this);/*{{{*/
+
+			doubletype norm=0;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pvector->Norm(norm_type);
+				#endif
+			}
+			else norm=this->ivector->Norm(norm_type);
+			return norm;
+		}
+		/*}}}*/
+		void Scale(doubletype scale_factor){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Scale(scale_factor);
+				#endif
+			}
+			else this->ivector->Scale(scale_factor);
+		}
+		/*}}}*/
+		doubletype Dot(Vector* vector){_assert_(this);/*{{{*/
+
+			doubletype dot;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				dot=this->pvector->Dot(vector->pvector);
+				#endif
+			}
+			else dot=this->ivector->Dot(vector->ivector);
+			return dot;
+		}
+		/*}}}*/
+		void PointwiseDivide(Vector* x,Vector* y){_assert_(this);/*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->PointwiseDivide(x->pvector,y->pvector);
+				#endif
+			}
+			else this->ivector->PointwiseDivide(x->ivector,y->ivector);
+		}
+		/*}}}*/
+};
+#endif //#ifndef _VECTOR_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/toolkitobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/toolkitobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/objects/toolkitobjects.h	(revision 18231)
@@ -0,0 +1,13 @@
+
+/*!\file:  toolkitobjects.h
+ * \brief wrappers to toolkits
+ */ 
+
+#ifndef _TOOLKIT_OBJECTS_H_
+#define _TOOLKIT_OBJECTS_H_
+
+#include "./Vector.h"
+#include "./Matrix.h"
+#include "./Solver.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 18231)
@@ -0,0 +1,173 @@
+/*!\file PetscMat.cpp
+ * \brief: implementation of the PetscMat object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+/*}}}*/
+
+/*PetscMat constructors and destructor*/
+PetscMat::PetscMat(){/*{{{*/
+	this->matrix=NULL;
+	#ifdef _HAVE_ADOLC_
+	this->amatrix=NULL;
+	#endif
+
+}
+/*}}}*/
+PetscMat::PetscMat(int M,int N){/*{{{*/
+
+	this->matrix=NewMat(M,N,IssmComm::GetComm());
+}
+/*}}}*/
+PetscMat::PetscMat(int M,int N, IssmDouble sparsity){/*{{{*/
+
+	this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
+}
+/*}}}*/
+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);
+
+}
+/*}}}*/
+PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){/*{{{*/
+
+	int     i;
+	int* idxm=NULL;
+	int* idxn=NULL;
+
+	if(M)idxm=xNew<int>(M);
+	if(N)idxn=xNew<int>(N);
+
+	for(i=0;i<M;i++)idxm[i]=i;
+	for(i=0;i<N;i++)idxn[i]=i;
+
+	this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
+	MatSetValues(this->matrix,M,idxm,N,idxn,serial_mat,INSERT_VALUES);
+	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
+
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
+
+}
+/*}}}*/
+PetscMat::PetscMat(int M,int N, int connectivity,int numberofdofspernode){/*{{{*/
+
+	this->matrix=NewMat(M,N,connectivity,numberofdofspernode,IssmComm::GetComm());
+
+}
+/*}}}*/
+PetscMat::~PetscMat(){/*{{{*/
+	MatFree(&this->matrix);
+}
+/*}}}*/
+
+/*PetscMat specific routines: */
+void PetscMat::AllocationInfo(void){/*{{{*/
+
+	MatInfo info;
+	MatGetInfo(this->matrix,MAT_GLOBAL_SUM,&info);
+	_printf0_("=========================== Stiffness matrix allocation info ===========================\n");
+	_printf0_("\n");
+   _printf0_(" Block size  : "<<info.block_size << "\n");
+	_printf0_(" nz_allocated: "<<info.nz_allocated << "\n");
+	_printf0_(" nz_used     : "<<info.nz_used << "\n");
+	_printf0_(" nz_unneeded : "<<info.nz_unneeded<<" ("<<double(info.nz_unneeded)/double(info.nz_allocated)*100.<<"%)\n");
+	_printf0_("\n");
+	_printf0_("========================================================================================\n");
+}
+/*}}}*/
+void PetscMat::Echo(void){/*{{{*/
+
+	MatView(this->matrix,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+void PetscMat::Assemble(void){/*{{{*/
+
+	_assert_(this->matrix);
+	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
+
+}
+/*}}}*/
+IssmDouble PetscMat::Norm(NormMode mode){/*{{{*/
+
+	IssmDouble norm=0;
+	_assert_(this->matrix);
+	MatNorm(this->matrix,ISSMToPetscNormMode(mode),&norm);
+
+	return norm;
+
+}
+/*}}}*/
+void PetscMat::GetSize(int* pM,int* pN){/*{{{*/
+
+	_assert_(this->matrix);
+	MatGetSize(this->matrix,pM,pN);
+}
+/*}}}*/
+void PetscMat::GetLocalSize(int* pM,int* pN){/*{{{*/
+
+	_assert_(this->matrix);
+	MatGetLocalSize(this->matrix,pM,pN);
+
+}
+/*}}}*/
+void PetscMat::MatMult(PetscVec* X,PetscVec* AX){/*{{{*/
+
+	_assert_(this->matrix);
+	_assert_(X->vector);
+	MatMultPatch(this->matrix,X->vector,AX->vector,IssmComm::GetComm());
+
+}
+/*}}}*/
+PetscMat* PetscMat::Duplicate(void){/*{{{*/
+
+	PetscMat* output=new PetscMat();
+	_assert_(this->matrix);
+	MatDuplicate(this->matrix,MAT_COPY_VALUES,&output->matrix);
+
+	return output;
+
+}
+/*}}}*/
+IssmDouble* PetscMat::ToSerial(void){/*{{{*/
+
+	 IssmDouble* output=NULL;
+
+	 MatToSerial(&output,this->matrix,IssmComm::GetComm());
+	 return output;
+
+}
+/*}}}*/
+void PetscMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){/*{{{*/
+
+	PetscErrorCode ierr;
+	ierr = MatSetValues(this->matrix,m,idxm,n,idxn,values,ISSMToPetscInsertMode(mode));
+	if(ierr) _error_("PETSC's MatSetValues reported an error");
+
+}
+/*}}}*/
+void PetscMat::Convert(MatrixType type){/*{{{*/
+
+	MatConvert(this->matrix,ISSMToPetscMatrixType(type),MAT_REUSE_MATRIX,&this->matrix);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscMat.h	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\file:  PetscMat.h
+ * \brief wrapper to our own PetscMat object, which is needed to add AD capabilities (using ADOLC) 
+ * to a C-coded Petsc API. We are just wrapping the Petsc objects into C++ equivalent, so that 
+ * later, we can map all of the Petsc routines into Adolc equivalents.
+ */ 
+
+#ifndef _PETSCMAT_H_
+#define _PETSCMAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+#include "../../../shared/Numerics/types.h"
+
+/*}}}*/
+class PetscVec;
+
+class PetscMat{
+
+	public:
+		Mat matrix;
+
+		#ifdef _HAVE_ADOLC_
+		IssmDouble* amatrix;
+		#endif
+
+		/*PetscMat constructors, destructors*/
+		PetscMat();
+		PetscMat(int M,int N);
+		PetscMat(int M,int N,IssmDouble sparsity);
+		PetscMat(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*/
+		void AllocationInfo(void);
+		void Echo(void);
+		void Assemble(void);
+		IssmDouble Norm(NormMode norm_type);
+		void GetSize(int* pM,int* pN);
+		void GetLocalSize(int* pM,int* pN);
+		void MatMult(PetscVec* X,PetscVec* AX);
+		PetscMat* Duplicate(void);
+		IssmDouble* ToSerial(void);
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode);
+		void Convert(MatrixType type);
+};
+
+#endif //#ifndef _PETSCMAT_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 18231)
@@ -0,0 +1,230 @@
+/*!\file SolverxPetsc
+ * \brief Petsc implementation of solver
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./PetscSolver.h"
+#include "../../../shared/Numerics/Verbosity.h"
+#include "../../../shared/MemOps/MemOps.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../shared/io/Comm/IssmComm.h"
+#include "../../../shared/Enum/Enum.h"
+
+void	PetscSolve(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters){ /*{{{*/
+
+	PetscVec* uf=new PetscVec();
+
+	Vec uf0_vector = NULL;
+	Vec df_vector  = NULL;
+
+	if(uf0) uf0_vector = uf0->vector;
+	if(df)  df_vector  = df->vector;
+
+	SolverxPetsc(&uf->vector, Kff->matrix, pf->vector, uf0_vector, df_vector, parameters);
+
+	*puf=uf;
+
+}
+/*}}}*/
+void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters){ /*{{{*/
+
+	/*Output: */
+	Vec        uf               = NULL;
+
+	/*Intermediary: */
+	int        local_m,local_n,global_m,global_n;
+
+	/*Solver */
+	KSP        ksp              = NULL;
+	PC         pc               = NULL;
+	int        iteration_number;
+	int        solver_type;
+	bool       fromlocalsize    = true;
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	PetscTruth flag,flg;
+	#else
+	PetscBool flag,flg;
+	#endif
+
+	/*FS: */
+	IS         isv=NULL;
+	IS         isp=NULL;
+
+	#if _PETSC_MAJOR_ >= 3 
+	char ksp_type[50];
+	#endif
+
+	/*Display message*/
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(VerboseSolver())PetscOptionsPrint(stdout);
+	#else
+	if(VerboseSolver())PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);
+	#endif
+
+	/*First, check that f-set is not NULL, i.e. model is fully constrained:*/ 
+	_assert_(Kff);
+	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_n);
+	if(!global_n){
+		*puf=NewVec(0,IssmComm::GetComm()); return;
+	}
+
+	/*Initial guess */
+	/*Now, check that we are not giving an initial guess to the solver, if we are running a direct solver: */
+	#if _PETSC_MAJOR_ >= 3 
+	PetscOptionsGetString(PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
+	if (strcmp(ksp_type,"preonly")==0)uf0=NULL;
+	#endif
+
+	/*If initial guess for the solution exists, use it to create uf, otherwise, 
+	 * duplicate the right hand side so that the solution vector has the same structure*/
+	if(uf0){
+		VecDuplicate(uf0,&uf); VecCopy(uf0,uf);
+	}
+	else{
+		MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,IssmComm::GetComm(),fromlocalsize);
+	}
+
+	/*Process petsc options to see if we are using special types of external solvers*/
+	PetscOptionsDetermineSolverType(&solver_type);
+
+	/*Check the solver is available*/
+	if(solver_type==MUMPSPACKAGE_LU || solver_type==MUMPSPACKAGE_CHOL){
+		#if _PETSC_MAJOR_ >=3
+			#ifndef _HAVE_MUMPS_
+			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
+			#endif
+		#endif
+	}
+
+	/*Prepare solver*/
+	KSPCreate(IssmComm::GetComm(),&ksp);
+	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
+	KSPSetFromOptions(ksp);
+
+	#if _PETSC_MAJOR_==3
+	/*Specific solver?: */
+	KSPGetPC(ksp,&pc);
+	if (solver_type==MUMPSPACKAGE_LU){
+		#if _PETSC_MINOR_==1
+		PCFactorSetMatSolverPackage(pc,MAT_SOLVER_MUMPS);
+		#else
+		PCFactorSetMatSolverPackage(pc,MATSOLVERMUMPS);
+		#endif
+	}
+
+	/*FS: */
+	if (solver_type==FSSolverEnum){
+		/*Make indices out of doftypes: */
+		if(!df)_error_("need doftypes for FS solver!\n");
+		DofTypesToIndexSet(&isv,&isp,df,FSSolverEnum);
+
+		/*Set field splits: */
+		KSPGetPC(ksp,&pc);
+		#if _PETSC_MINOR_==1
+		PCFieldSplitSetIS(pc,isv);
+		PCFieldSplitSetIS(pc,isp);
+		#else
+		PCFieldSplitSetIS(pc,PETSC_NULL,isv);
+		PCFieldSplitSetIS(pc,PETSC_NULL,isp);
+		#endif
+
+	}
+	#endif
+
+	/*If there is an initial guess for the solution, use it
+	 * except if we are using the MUMPS direct solver
+	 * where any initial guess will crash Petsc*/
+	if (uf0){
+		if((solver_type!=MUMPSPACKAGE_LU) && (solver_type!=MUMPSPACKAGE_CHOL) && (solver_type!=SPOOLESPACKAGE_LU) && (solver_type!=SPOOLESPACKAGE_CHOL) && (solver_type!=SUPERLUDISTPACKAGE)){
+			KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
+		}
+	}
+
+	/*Solve: */
+	if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
+	KSPSolve(ksp,pf,uf);
+
+	/*Check convergence*/
+	KSPGetIterationNumber(ksp,&iteration_number);
+	if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
+
+	/*Free resources:*/
+	KSPFree(&ksp);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+} 
+/*}}}*/
+void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){ /*{{{*/
+
+	/*output: */
+	IS          isv=NULL;
+	IS          isp=NULL;
+
+	int         start,end;
+	IssmDouble*     df_local=NULL;
+	int         df_local_size;
+
+	int*     pressure_indices=NULL;
+	int*     velocity_indices=NULL;
+	int      pressure_num=0;
+	int      velocity_num=0;
+	int      pressure_count=0;
+	int      velocity_count=0;
+
+	if(typeenum==FSSolverEnum){
+
+		/*Ok, recover doftypes vector values and indices: */
+		VecGetOwnershipRange(df,&start,&end);
+		VecGetLocalSize(df,&df_local_size);
+		VecGetArray(df,&df_local);
+
+		pressure_num=0;
+		velocity_num=0;
+		for(int i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum)pressure_num++;
+			else velocity_num++;
+		}
+
+		/*Allocate indices: */
+		if(pressure_num)pressure_indices=xNew<int>(pressure_num);
+		if(velocity_num)velocity_indices=xNew<int>(velocity_num);
+
+		pressure_count=0;
+		velocity_count=0;
+		for(int i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum){
+				pressure_indices[pressure_count]=start+i;
+				pressure_count++;
+			}
+			if (df_local[i]==VelocityEnum){
+				velocity_indices[velocity_count]=start+i;
+				velocity_count++;
+			}
+		}
+		VecRestoreArray(df,&df_local);
+
+		/*Create indices sets: */
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,&isv);
+		#else
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
+		#endif
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(pressure_indices);
+	xDelete<int>(velocity_indices);
+
+	/*Assign output pointers:*/
+	*pisv=isv;
+	*pisp=isp;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscSolver.h	(revision 18231)
@@ -0,0 +1,24 @@
+/*!\file:  PetscMat.h
+ */ 
+
+#ifndef _PETSC_SOLVER_H_
+#define _PETSC_SOLVER_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+class Parameters;
+
+/*}}}*/
+
+void	PetscSolve(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters);
+void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters);
+void    DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
+
+#endif //#ifndef _PETSCSOLVER_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 18231)
@@ -0,0 +1,212 @@
+/*!\file PetscVec.cpp
+ * \brief: implementation of the PetscVec object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+/*}}}*/
+
+/*PetscVec constructors and destructor*/
+PetscVec::PetscVec(){/*{{{*/
+	this->vector=NULL;
+	#ifdef _HAVE_ADOLC_
+	this->avector=NULL;
+	#endif
+}
+/*}}}*/
+PetscVec::PetscVec(int M,bool fromlocalsize){/*{{{*/
+
+	this->vector=NewVec(M,IssmComm::GetComm(),fromlocalsize);
+
+}
+/*}}}*/
+PetscVec::PetscVec(int m,int M){/*{{{*/
+
+	VecCreate(IssmComm::GetComm(),&this->vector);
+	VecSetSizes(this->vector,m,M);
+	VecSetFromOptions(this->vector);
+	VecSet(this->vector,0.0);
+
+}
+/*}}}*/
+PetscVec::PetscVec(Vec petsc_vec){/*{{{*/
+
+	if(petsc_vec==NULL){
+		this->vector=NewVec(0,IssmComm::GetComm());
+	}
+	else{
+		/*copy vector*/
+		VecDuplicate(petsc_vec,&this->vector);
+		VecCopy(petsc_vec,this->vector);
+	}
+
+}
+/*}}}*/
+PetscVec::PetscVec(IssmDouble* serial_vec,int M){/*{{{*/
+
+	int* idxm=NULL;
+	if(M)idxm=xNew<int>(M);
+	for(int i=0;i<M;i++) idxm[i]=i;
+
+	this->vector=NewVec(M,IssmComm::GetComm());
+	VecSetValues(this->vector,M,idxm,serial_vec,INSERT_VALUES);
+	VecAssemblyBegin(this->vector);
+	VecAssemblyEnd(this->vector);
+
+	xDelete<int>(idxm);
+}
+/*}}}*/
+PetscVec::~PetscVec(){/*{{{*/
+    VecFree(&this->vector);
+}
+/*}}}*/
+
+/*PetscVec specific routines: */
+void PetscVec::Echo(void){/*{{{*/
+
+	_assert_(this->vector);
+	VecView(this->vector,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+void PetscVec::Assemble(void){/*{{{*/
+
+	_assert_(this->vector);
+	VecAssemblyBegin(this->vector); 
+	VecAssemblyEnd(this->vector);
+
+}
+/*}}}*/
+void PetscVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){/*{{{*/
+
+	_assert_(this->vector);
+	VecSetValues(this->vector,ssize,list,values,ISSMToPetscInsertMode(mode));
+
+}
+/*}}}*/
+void PetscVec::SetValue(int dof, IssmDouble value, InsMode mode){/*{{{*/
+
+	_assert_(this->vector);
+	VecSetValues(this->vector,1,&dof,&value,ISSMToPetscInsertMode(mode));
+
+}
+/*}}}*/
+void PetscVec::GetValue(IssmDouble* pvalue,int dof){/*{{{*/
+
+	_assert_(this->vector);
+	VecGetValues(this->vector,1,&dof,pvalue);
+
+}
+/*}}}*/
+void PetscVec::GetSize(int* pM){/*{{{*/
+
+	_assert_(this->vector);
+	VecGetSize(this->vector,pM);
+
+}
+/*}}}*/
+void PetscVec::GetLocalSize(int* pM){/*{{{*/
+
+	_assert_(this->vector);
+	VecGetLocalSize(this->vector,pM);
+
+}
+/*}}}*/
+PetscVec* PetscVec::Duplicate(void){/*{{{*/
+
+	_assert_(this->vector);
+	Vec vec_output=NULL;
+	VecDuplicate(this->vector,&vec_output);
+	PetscVec* output=new PetscVec(vec_output);
+	VecFree(&vec_output);
+
+	return output;
+}
+/*}}}*/
+void PetscVec::Set(IssmDouble value){/*{{{*/
+
+	_assert_(this->vector);
+	VecSet(this->vector,value);
+
+}
+/*}}}*/
+void PetscVec::AXPY(PetscVec* X, IssmDouble a){/*{{{*/
+
+	_assert_(this->vector);
+	VecAXPY(this->vector,a,X->vector);
+
+}
+/*}}}*/
+void PetscVec::AYPX(PetscVec* X, IssmDouble a){/*{{{*/
+
+	_assert_(this->vector);
+	VecAYPX(this->vector,a,X->vector);
+
+}
+/*}}}*/
+IssmDouble* PetscVec::ToMPISerial(void){/*{{{*/
+
+	IssmDouble* vec_serial=NULL;
+	VecToMPISerial(&vec_serial, this->vector,IssmComm::GetComm());
+	return vec_serial;
+
+}
+/*}}}*/
+void PetscVec::Copy(PetscVec* to){/*{{{*/
+
+	if(this->vector) VecCopy(this->vector,to->vector);
+
+}
+/*}}}*/
+IssmDouble PetscVec::Max(void){/*{{{*/
+
+	_assert_(this->vector);
+
+	IssmDouble max;
+	VecMax(this->vector,NULL,&max);
+	return max;
+
+}
+/*}}}*/
+IssmDouble PetscVec::Norm(NormMode mode){/*{{{*/
+
+	IssmDouble norm=0;
+	_assert_(this->vector);
+	VecNorm(this->vector,ISSMToPetscNormMode(mode),&norm);
+	return norm;
+
+}
+/*}}}*/
+void PetscVec::Scale(IssmDouble scale_factor){/*{{{*/
+
+	_assert_(this->vector);
+	VecScale(this->vector,scale_factor); 
+
+}
+/*}}}*/
+IssmDouble PetscVec::Dot(PetscVec* input){/*{{{*/
+
+	IssmDouble dot;
+	_assert_(this->vector);
+	VecDot(this->vector,input->vector,&dot);
+	return dot;
+
+}
+/*}}}*/
+void PetscVec::PointwiseDivide(PetscVec* x,PetscVec* y){/*{{{*/
+
+	_assert_(this->vector);
+	VecPointwiseDivide(this->vector,x->vector,y->vector);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/PetscVec.h	(revision 18231)
@@ -0,0 +1,60 @@
+/*!\file:  PetscVec.h
+ * \brief wrapper to our own PetscVec object, which is needed to add AD capabilities (using ADOLC) 
+ * to a C-coded Petsc API. We are just wrapping the Petsc objects into C++ equivalent, so that 
+ * later, we can map all of the Petsc routines into Adolc equivalents.
+ */ 
+
+#ifndef _PETSCVEC_H_
+#define _PETSCVEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+
+/*}}}*/
+
+class PetscVec{
+
+	public:
+		Vec vector;
+
+		#ifdef _HAVE_ADOLC_
+		IssmDouble* avector;
+		#endif
+
+		/*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*/
+		void        Echo(void);
+		void        Assemble(void);
+		void        SetValues(int ssize, int* list, IssmDouble* values, InsMode mode);
+		void        SetValue(int dof, IssmDouble value, InsMode  mode);
+		void        GetValue(IssmDouble* pvalue, int dof);
+		void        GetSize(int* pM);
+		void        GetLocalSize(int* pM);
+		PetscVec*   Duplicate(void);
+		void        Set(IssmDouble value);
+		void        AXPY(PetscVec* X, IssmDouble a);
+		void        AYPX(PetscVec* X, IssmDouble a);
+		IssmDouble* ToMPISerial(void);
+		void        Copy(PetscVec* to);
+		IssmDouble  Norm(NormMode norm_type);
+		IssmDouble  Max(void);
+		void        Scale(IssmDouble scale_factor);
+		void        PointwiseDivide(PetscVec* x,PetscVec* y);
+		IssmDouble  Dot(PetscVec* vector);
+};
+
+#endif //#ifndef _PETSCVEC_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/petscobjects.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/petscobjects.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/objects/petscobjects.h	(revision 18231)
@@ -0,0 +1,12 @@
+/* \file petscobjects.h
+ * \brief all includes for our own petsc object implementation
+ */
+
+#ifndef _PETSC_OBJECTS_H_
+#define _PETSC_OBJECTS_H_
+
+#include "./PetscMat.h"
+#include "./PetscVec.h"
+#include "./PetscSolver.h"
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/* \file ISSMToPetscInsertMode.cpp
+ * \brief: convert InsertMode from ISSM to Petsc
+ */
+
+#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>
+
+/*ISSM includes: */
+#include "../../toolkitsenums.h"
+#include "../../../shared/shared.h"
+
+InsertMode ISSMToPetscInsertMode(InsMode mode){
+
+	switch(mode){
+		case ADD_VAL:  
+			return ADD_VALUES;
+			break;
+		case INS_VAL:
+			return INSERT_VALUES;
+			break;
+		default: 
+			_error_("unknown insert mode!");
+			break;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/* \file ISSMToPetscMatrixType.cpp
+ * \brief: convert MatrixType from ISSM to Petsc
+ */
+
+#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>
+
+/*ISSM includes: */
+#include "../../toolkitsenums.h"
+#include "../../../shared/shared.h"
+
+MatType ISSMToPetscMatrixType(MatrixType type){
+
+	switch(type){
+		case DENSE_SEQUENTIAL:  
+			return MATSEQDENSE;
+			break;
+		case SPARSE_SEQUENTIAL:  
+			return MATSEQAIJ;
+			break;
+		default: 
+			_error_("unknown matrix type !");
+			break;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 18231)
@@ -0,0 +1,33 @@
+/* \file ISSMToPetscNormMode.cpp
+ * \brief: convert NormMode from ISSM to Petsc
+ */
+
+#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>
+
+/*ISSM includes: */
+#include "../../toolkitsenums.h"
+#include "../../../shared/shared.h"
+
+NormType ISSMToPetscNormMode(NormMode mode){
+
+	switch(mode){
+		case NORM_INF:  
+			return NORM_INFINITY;
+			break;
+		case NORM_TWO:  
+			return NORM_2;
+			break;
+		default: 
+			_error_("unknown norm !");
+			break;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/KSPFree.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file:  KSPFree.cpp
+ * \brief wrapper to KSPDestroy
+ */ 
+
+#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>
+
+void KSPFree(KSP* pksp){
+
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(*pksp)KSPDestroy(*pksp);
+	*pksp=NULL;
+	#else
+	if(*pksp)KSPDestroy(pksp);
+	*pksp=NULL;
+	#endif
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatFree.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 18231)
@@ -0,0 +1,26 @@
+/*!\file:  MatFree.cpp
+ * \brief wrapper to MatDestroy
+ */ 
+
+#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 MatFree(Mat* pmat){
+
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(*pmat)MatDestroy(*pmat);
+	*pmat=NULL;
+	#else
+	if(*pmat)MatDestroy(pmat);
+	*pmat=NULL;
+	#endif
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 18231)
@@ -0,0 +1,115 @@
+/*!\file:  MatMultPatch
+ * \brief: relocalize vector when MatMult yields non conforming object sizes errors.
+ */ 
+
+#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 "../../mpi/issmmpi.h"
+#include "../../../shared/shared.h"
+
+/*Function prototypes: */
+int MatMultCompatible(Mat A,Vec x,ISSM_MPI_Comm comm);
+void VecRelocalize(Vec* outvector,Vec vector,int m,ISSM_MPI_Comm comm);
+
+void MatMultPatch(Mat A,Vec X, Vec AX,ISSM_MPI_Comm comm){ //same prototype as MatMult in Petsc
+
+	int m,n;
+	Vec X_rel=NULL;
+
+	_assert_(A); _assert_(X);
+
+	if (MatMultCompatible(A,X,comm)){
+		MatMult(A,X,AX); 
+	}
+	else{
+		MatGetLocalSize(A,&m,&n);;
+		VecRelocalize(&X_rel,X,n,comm);
+		MatMult(A,X_rel,AX); ;
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		VecDestroy(X_rel);
+		#else
+		VecDestroy(&X_rel);
+		#endif
+	}
+}
+
+int MatMultCompatible(Mat A,Vec x,ISSM_MPI_Comm comm){
+
+	/*error management*/
+
+	int local_m,local_n;
+	int range;
+	int result=1;
+	int sumresult;
+	int num_procs;
+
+	/*recover num_procs:*/
+	ISSM_MPI_Comm_size(comm,&num_procs);
+
+	MatGetLocalSize(A,&local_m,&local_n);;
+	VecGetLocalSize(x,&range);;
+
+	if (local_n!=range)result=0;
+
+	/*synchronize result: */
+	ISSM_MPI_Reduce (&result,&sumresult,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm );
+	ISSM_MPI_Bcast(&sumresult,1,ISSM_MPI_INT,0,comm);                
+	if (sumresult!=num_procs){
+		result=0;
+	}
+	else{
+		result=1;
+	}
+	return result;
+}
+
+void VecRelocalize(Vec* poutvector,Vec vector,int m,ISSM_MPI_Comm comm){
+
+	/*vector index and vector values*/
+	int* index=NULL;
+	double* values=NULL;
+	int lower_row,upper_row,range;
+
+	/*output: */
+	Vec outvector=NULL;
+
+	/*Create outvector with local size m*/
+	VecCreate(comm,&outvector); ; 
+	VecSetSizes(outvector,m,PETSC_DECIDE); ; 
+	VecSetFromOptions(outvector); ; 
+
+	/*Go through vector, get values, and plug them into outvector*/
+	VecGetOwnershipRange(vector,&lower_row,&upper_row); ; 
+	upper_row--;
+	range=upper_row-lower_row+1;
+	if (range){
+		index=xNew<int>(range);
+		values=xNew<double>(range);
+		for (int i=0;i<range;i++){
+			*(index+i)=lower_row+i;
+		}
+		VecGetValues(vector,range,index,values);
+		VecSetValues(outvector,range,index,values,INSERT_VALUES);
+	}
+
+	/*Assemble outvector*/
+	VecAssemblyBegin(outvector);; 
+	VecAssemblyEnd(outvector);; 
+
+	/*Free ressources:*/
+	xDelete<int>(index);
+	xDelete<double>(values);	
+
+	/*Assign output pointers:*/
+	*poutvector=outvector;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatToSerial.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 18231)
@@ -0,0 +1,89 @@
+/*!\file MatToSerial.cpp
+ * \brief gather a Petsc Mat matrix onto cpu 0
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+void MatToSerial(double** poutmatrix,Mat matrix,ISSM_MPI_Comm comm){
+
+	int i;
+	int my_rank;
+	int num_procs;
+
+	/*Petsc variables*/
+	PetscInt lower_row,upper_row; 
+	int range;
+	int M,N; //size of matrix
+	ISSM_MPI_Status status;
+	int* idxm=NULL;
+	int* idxn=NULL; 
+	double* local_matrix=NULL; /*matrix local to each node used for temporary holding matrix values*/
+	int buffer[3];
+
+	/*recover my_rank and num_procs:*/
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+
+	/*Output*/
+	double* outmatrix=NULL;
+
+	/*get matrix size: */
+	MatGetSize(matrix,&M,&N);
+
+	/*partition: */
+	MatGetOwnershipRange(matrix,&lower_row,&upper_row);    
+	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;
+		}
+		for (i=0;i<range;i++){
+			*(idxm+i)=lower_row+i;
+		}
+
+		MatGetValues(matrix,range,idxm,N,idxn,local_matrix);     
+	}
+
+	/*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){ 
+			buffer[0]=my_rank;
+			buffer[1]=lower_row;
+			buffer[2]=range;
+			ISSM_MPI_Send(buffer,3,ISSM_MPI_INT,0,1,comm);   
+			if (range)ISSM_MPI_Send(local_matrix,N*range,ISSM_MPI_PDOUBLE,0,1,comm); 
+		}
+		if (my_rank==0){
+			ISSM_MPI_Recv(buffer,3,ISSM_MPI_INT,i,1,comm,&status); 
+			if (buffer[2])ISSM_MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],ISSM_MPI_PDOUBLE,i,1,comm,&status);
+		}
+	} 
+	if (my_rank==0){ 
+		//Still have the local_matrix on node 0 to take care of.
+		memcpy(outmatrix,local_matrix,N*range*sizeof(double));
+	} 
+
+	/*Assign output pointer: */
+	*poutmatrix=outmatrix;
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
+	xDelete<double>(local_matrix);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 18231)
@@ -0,0 +1,128 @@
+/*!\file:  NewMat.cpp
+ * \brief create matrix using the Petsc library
+ */ 
+
+#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 "./petscpatches.h"
+#include "../../../shared/shared.h"
+#include "../../mpi/issmmpi.h"
+
+/*NewMat(int M,int N){{{*/
+Mat NewMat(int M,int N,ISSM_MPI_Comm comm){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	double sparsity=.001; //default
+	int    m,n;
+	int    d_nz,o_nz,nnz;
+
+	/*Determine local sizes: */
+	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
+	o_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
+
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
+	MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	#else
+	MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	#endif
+
+	return outmatrix;
+}
+/*}}}*/
+/*NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm){{{*/
+Mat NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	int    m,n;
+	int    d_nz,o_nz;
+	int    nnz;
+
+	/*Determine local sizes: */
+	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
+	o_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
+
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
+	if(sparsity==1){
+		MatCreateDense(comm,m,n,M,N,NULL,&outmatrix); 
+	}
+	else{
+		MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	}
+	#else
+	MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	#endif
+
+	return outmatrix;
+}
+/*}}}*/
+/*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{*/
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode,ISSM_MPI_Comm comm){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	int    m,n;
+	int    d_nz,o_nz;
+
+	#if _PETSC_MAJOR_ >= 3 
+	#if defined(_HAVE_PETSCDEV_) || _PETSC_MINOR_ >=4
+	MatType type;
+	#else
+	const MatType type;
+	#endif
+	#else
+	MatType type;
+	#endif
+
+	/*Determine local sizes: */
+	m=DetermineLocalSize(M,comm);
+	n=DetermineLocalSize(N,comm);
+
+	/*Figure out number of non zeros per row: */
+	d_nz=(int)connectivity*numberofdofspernode/2;
+	o_nz=(int)connectivity*numberofdofspernode/2;
+
+	MatCreate(comm,&outmatrix);
+	MatSetSizes(outmatrix,m,n,M,N);
+	MatSetFromOptions(outmatrix);
+
+	/*preallocation  according to type: */
+	MatGetType(outmatrix,&type);
+
+	#if _PETSC_MAJOR_ == 2 
+	if((strcmp(type,"mpiaij")==0) || (strcmp(type,"aijmumps")==0)){
+		MatMPIAIJSetPreallocation(outmatrix,d_nz,NULL,o_nz,NULL);
+	}
+	#else
+	if((strcmp(type,"mpiaij")==0) || (strcmp(type,"mpidense")==0)){
+		MatMPIAIJSetPreallocation(outmatrix,d_nz,NULL,o_nz,NULL);
+	}
+	#endif
+
+	return outmatrix;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 18231)
@@ -0,0 +1,39 @@
+/*!\file NewVec.cpp
+ * \brief: create distributed 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"
+
+#include "./petscpatches.h"
+#include "../../mpi/issmmpi.h"
+
+Vec NewVec(int size,ISSM_MPI_Comm comm,bool fromlocalsize){
+
+	int local_size;
+
+	/*output: */
+	Vec vector=NULL;
+
+	/*determine local size of vector: */
+	if(fromlocalsize){
+		local_size=size;
+	}
+	else{
+		local_size=DetermineLocalSize(size,comm);
+	}
+
+	VecCreate(comm,&vector); 
+	VecSetSizes(vector,local_size,PETSC_DECIDE); 
+	VecSetFromOptions(vector); 
+
+	return vector;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 18231)
@@ -0,0 +1,67 @@
+/*!\file PetscOptionsDetermineSolverType.cpp: from the petsc options, determine what kind of solver
+ * we are using.
+ */
+
+#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 "./petscpatches.h"
+
+#include "../../../shared/shared.h"
+
+void PetscOptionsDetermineSolverType(int* psolver_type){
+
+	char option[100];
+   #if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	PetscTruth flag;
+	#else
+	PetscBool flag;
+	#endif
+
+	/*output: */
+	int solver_type=PETSCPACKAGE;
+
+	/*retrieve mat_type option: */
+	PetscOptionsGetString(PETSC_NULL,"-mat_type",&option[0],100,&flag);
+
+	if (strcmp(option,"aijmumps")==0){
+		solver_type=MUMPSPACKAGE_LU;
+	}
+	if (strcmp(option,"sbaijmumps")==0){
+		solver_type=MUMPSPACKAGE_CHOL;
+	}
+	if (strcmp(option,"aijspooles")==0){
+		solver_type=SPOOLESPACKAGE_LU;
+	}
+	if (strcmp(option,"sbaijspooles")==0){
+		solver_type=SPOOLESPACKAGE_CHOL;
+	}
+	if (strcmp(option,"superlu_dist")==0){
+		solver_type=SUPERLUDISTPACKAGE;
+	}
+	if (strcmp(option,"")==0){
+		solver_type=SUPERLUDISTPACKAGE;
+	}
+
+	#if _PETSC_MAJOR_ >= 3 
+	PetscOptionsGetString(PETSC_NULL,"-pc_factor_mat_solver_package",&option[0],100,&flag);
+	if (strcmp(option,"mumps")==0){
+		solver_type=MUMPSPACKAGE_LU;
+	}
+	#endif
+
+	PetscOptionsGetString(PETSC_NULL,"-issm_option_solver",&option[0],100,&flag);
+	if (strcmp(option,"FS")==0){
+		solver_type=FSSolverEnum;
+	}
+
+	*psolver_type=solver_type;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 18231)
@@ -0,0 +1,91 @@
+/*!\file PetscOptionsInsertMultipleString.cpp
+ * \brief: create distributed 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>
+
+#include "./petscpatches.h"
+
+#include "../../../shared/shared.h"
+
+void PetscOptionsInsertMultipleString(char* options_string){
+
+	/*The list of options is going to be pairs of the type "-option option_value"*/
+	#if _PETSC_MAJOR_ == 2
+		PetscToken *token=NULL ;
+	#else
+		PetscToken token=NULL;
+	#endif
+	char* first=NULL;
+	char* second=NULL;
+	size_t len;
+	int first_token=1;
+
+	PetscTokenCreate(options_string,' ',&token);
+	for (;;){
+
+		/*Read next tokens*/
+		if(first_token){
+			PetscTokenFind(token,&first);
+		}
+		PetscTokenFind(token,&second);
+
+		if (!first){
+			/*We are at the end of options*/
+			break;
+		}
+		if(!second){
+			/*We have no second value, just take first
+			 * and set the option, then end the token analysis.*/
+			if(first[0]!='-'){
+				/*This is not good, the option does not have '-'! Get out*/
+				_error_("Option " << first << " should be preceded by '-'!");
+			}
+			/*Reduce first to bare option value*/
+			PetscStrlen(first,&len);
+			while (len > 0 && first[len-1] == ' ') {
+				len--; first[len] = 0;
+			}
+			PetscOptionsSetValue(first,second);
+			break;
+		}
+		else{
+			/*Ok, we have a second token coming in. Is it another option, or 'first' option's value?*/
+			if (second[0]=='-'){
+				/*Second is another option, ignore it*/
+				PetscStrlen(first,&len);
+				while (len > 0 && first[len-1] == ' ' ) {
+					len--; first[len] = 0;
+				}
+				PetscOptionsSetValue(first,NULL);
+				/*Preparing next loop step*/
+				first=second;
+				first_token=0;
+			}
+			else{
+				/*Second is 'first' option's value*/
+				PetscStrlen(second,&len);
+				while (len > 0 && second[len-1] == ' ') {
+					len--; second[len] = 0;
+				}
+				PetscOptionsSetValue(first,second);
+				first_token=1;
+			}
+		}
+	}
+
+#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
+	PetscTokenDestroy(&token);
+#else
+	PetscTokenDestroy(token);
+#endif
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/SolverEnum.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 18231)
@@ -0,0 +1,17 @@
+/*!\file: SolverEnum.h
+ * \brief prototypes for SolverEnum.h
+ */ 
+
+#ifndef _SOLVERENUM_H_
+#define  _SOLVERENUM_H_
+
+typedef enum{
+	PETSCPACKAGE,
+	MUMPSPACKAGE_LU,
+	MUMPSPACKAGE_CHOL,
+	SPOOLESPACKAGE_LU,
+	SPOOLESPACKAGE_CHOL,
+	SUPERLUDISTPACKAGE,
+} EXTERNALPACKAGES; 
+
+#endif //ifndef _SOLVERENUM_H_
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecFree.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 18231)
@@ -0,0 +1,25 @@
+/*!\file:  VecFree.cpp
+ * \brief wrapper to VecDestroy
+ */ 
+
+#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>
+
+void VecFree(Vec* pvec){
+
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(*pvec)VecDestroy(*pvec);
+	#else
+	if(*pvec)VecDestroy(pvec);
+	#endif
+	*pvec=NULL;
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 18231)
@@ -0,0 +1,64 @@
+/*!\file:  VecMerge.cpp
+ * \brief merge vector B into A using partitioning vector A(row_partition_vector)=B;
+ */ 
+
+#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 "./petscpatches.h"
+
+#include "../../../shared/shared.h"
+
+void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size){
+
+	/*Petsc matrix*/
+	int lower_row,upper_row,range;
+	int* idxm=NULL;
+	double* values=NULL;
+
+	/*Vector sizes: */
+	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) ){
+		_error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
+	}
+
+	/*Get values from vector B and plug them into vector A, using the partitioning vector*/
+	VecGetOwnershipRange(B,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;
+
+	if (range){
+		/*This node owns rows of vector B, get them*/
+		idxm=xNew<int>(range);
+		values=xNew<double>(range);
+		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(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);
+	VecAssemblyEnd(A);
+
+	/*Free ressources:*/
+	xDelete<int>(idxm);
+	xDelete<double>(values);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 18231)
@@ -0,0 +1,96 @@
+/*!\file VecToMPISerial.cpp
+ * \brief gather a Petsc Vector spread across the cluster, onto node 0, and then broadcast to all nodes. 
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+int VecToMPISerial(double** pgathered_vector, Vec vector,ISSM_MPI_Comm comm){
+
+	int i;
+	int num_procs; 
+	int my_rank;
+
+	/*Petsc*/
+	ISSM_MPI_Status status;
+	PetscInt lower_row,upper_row; 
+	int range;
+	int * idxn=NULL; 
+	int buffer[3];
+
+	/*intermediary results*/
+	double* local_vector=NULL;
+
+	/*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*/
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+
+	VecGetSize(vector,&vector_size);
+	if(vector_size==0){
+		*pgathered_vector=NULL;
+		return 1;
+	}
+
+	/*Allocate gathered vector on all nodes .*/
+	gathered_vector=xNew<double>(vector_size);
+
+	/*Allocate local vectors*/
+	VecGetOwnershipRange(vector,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;    
+
+	if (range){
+		idxn=xNew<int>(range); 
+		for (i=0;i<range;i++){
+			*(idxn+i)=lower_row+i;
+		} 
+		local_vector=xNew<double>(range);
+		/*Extract values from MPI vector to serial local_vector on each node*/
+		VecGetValues(vector,range,idxn,local_vector); 
+	}
+
+	/*Now each node holds its local_vector containing range rows. 
+	 * We send this local_vector  to the gathered_vector on node 0*/
+	for (i=1;i<num_procs;i++){
+		if (my_rank==i){ 
+			buffer[0]=my_rank;
+			buffer[1]=lower_row;
+			buffer[2]=range;
+			ISSM_MPI_Send(buffer,3,ISSM_MPI_INT,0,1,comm);  
+			if (range)ISSM_MPI_Send(local_vector,range,ISSM_MPI_PDOUBLE,0,1,comm); 
+		}
+		if (my_rank==0){
+			ISSM_MPI_Recv(buffer,3,ISSM_MPI_INT,i,1,comm,&status); 
+			if (buffer[2])ISSM_MPI_Recv(gathered_vector+buffer[1],buffer[2],ISSM_MPI_PDOUBLE,i,1,comm,&status);
+		}
+	}
+
+	if (my_rank==0){ 
+		//Still have the local_vector on node 0 to take care of.
+		if (range)memcpy(gathered_vector+lower_row,local_vector,range*sizeof(double));
+	}
+
+	/*Now, broadcast gathered_vector from node 0 to other nodes: */
+	ISSM_MPI_Bcast(gathered_vector,vector_size,ISSM_MPI_PDOUBLE,0,comm);
+
+	/*Assign output pointers: */
+	*pgathered_vector=gathered_vector;
+
+	/*free ressources: */
+	xDelete<int>(idxn);
+	xDelete<double>(local_vector);
+
+	return 1;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/petscpatches.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/patches/petscpatches.h	(revision 18231)
@@ -0,0 +1,41 @@
+/*\file petscpatches.h
+ * \brief: our own patches for petsc use
+ */
+
+#ifndef _PETSC_PATCHES_H_
+#define _PETSC_PATCHES_H_
+
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
+#include <petscsys.h>
+
+#include "./SolverEnum.h"
+#include "../../toolkitsenums.h"
+#include "../../../shared/io/Comm/IssmComm.h"
+
+class Parameters;
+
+Vec NewVec(int size,ISSM_MPI_Comm comm,bool fromlocalsize=false);
+Mat NewMat(int M,int N,ISSM_MPI_Comm comm);
+Mat NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm);
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode, ISSM_MPI_Comm comm);
+
+int VecToMPISerial(double** pgathered_vector, Vec vector,ISSM_MPI_Comm comm);
+void MatFree(Mat* pmat);
+void ISFree(IS* pis);
+void VecFree(Vec* pvec);
+void KSPFree(KSP* pksp);
+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 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,ISSM_MPI_Comm comm);
+void MatToSerial(double** poutmatrix,Mat matrix,ISSM_MPI_Comm comm);
+Vec  SerialToVec(double* vector,int vector_size);
+InsertMode ISSMToPetscInsertMode(InsMode mode);
+NormType ISSMToPetscNormMode(NormMode mode);
+MatType ISSMToPetscMatrixType(MatrixType type);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/petscincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/petscincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/petsc/petscincludes.h	(revision 18231)
@@ -0,0 +1,21 @@
+/* \file petscincludes.h
+ * \brief all includes from Petsc + our own patches
+ */
+
+#ifndef _PETSC_INCLUDES_H_
+#define _PETSC_INCLUDES_H_
+
+#ifdef _HAVE_PETSC_
+
+/*Petsc includes: */
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
+#include <petscsys.h>
+
+/*our own patches: */
+#include "patches/petscpatches.h"
+#include "objects/petscobjects.h"
+
+#endif
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 18231)
@@ -0,0 +1,81 @@
+/*!\file:  CyclicalFactorization.cpp
+ * \brief given num_procs, finds the integers nprows and npcols so that nprows*npcols=num_procs and nprows-npcols is the smallest possible
+*/
+#include <math.h>
+
+#include "../../../shared/shared.h"
+
+int SmallestPrimeFactor(int* output,int input);
+
+int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs){
+
+	int nprows,npcols;
+	int last_diff;
+	int i;
+	int diff;
+
+	nprows=1; npcols=num_procs; last_diff=npcols-nprows;
+	for (i=1;i<=num_procs;i++){
+		if ((num_procs % i)==0){
+			diff=(int)fabs((double)(i-(num_procs/i)));
+			if (diff<last_diff){
+				nprows=i;npcols=num_procs/i;
+				last_diff=(int)fabs((double)(nprows-npcols));
+			}
+		}
+	}
+	/*Order nprows > npcols*/
+	if (nprows<npcols){
+		int temp=nprows;
+		nprows=npcols;
+		npcols=temp;
+	}
+
+	*pnprows=nprows;
+	*pnpcols=npcols;
+
+}
+
+int PrimeDecomp(int** pdecomp,int* pdecomp_size,int input){
+
+	int prime_factor;
+	int i;
+
+	int* decomp=xNew<int>(input);
+	*decomp=input;
+	for (i=0;i<input;i++){
+		SmallestPrimeFactor(&prime_factor,*(decomp+i));
+		if (prime_factor==*(decomp+i)){
+			*pdecomp_size=i;
+			break;
+		}
+		else{
+			*(decomp+i+1)=*(decomp+i)/prime_factor;
+			*(decomp+i)=prime_factor;
+		}
+	}
+	*pdecomp=decomp;
+}
+
+/*SmallestPrimeFactor: 
+	seeks the smallest prime factor in the prime factor decomposition 
+	of integer input
+*/
+int SmallestPrimeFactor(int* output,int input){
+
+	int found=0;
+	int i;
+
+	for (i=2;i<input;i++){
+		if ((input %i)==0){
+			found=i;
+			break;
+		}
+	}
+	if(found){
+		*output=found;
+	}
+	else{
+		*output=input;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 18231)
@@ -0,0 +1,126 @@
+/*!\file PlapackInvertMatrix.cpp
+ * \brief invert petsc matrix using Plapack
+ */
+
+/* petsc: */
+#include "../../petsc/petscincludes.h"
+
+/*plapack: */
+#include "../plapackincludes.h"
+
+/* Some fortran routines: */
+#include "../../scalapack/FortranMapping.h"
+
+void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,ISSM_MPI_Comm* pcomm_2d);
+
+int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm){ 
+	/*inv_A does not yet exist, inv_A was just allocated, that's all*/
+
+	/*Error management*/
+	int i;
+
+	/*input*/
+	int mA,nA;
+	int local_mA,local_nA;
+	int lower_row,upper_row;
+	MatType type;
+
+	/*Plapack: */
+	ISSM_MPI_Datatype   datatype;
+	ISSM_MPI_Comm       comm_2d;
+	PLA_Obj a=NULL;
+	PLA_Template   templ;	
+	double one=1.0;		
+	int ierror;
+	int nb,nb_alg;
+	int nprows,npcols;
+
+	/*Petsc to Plapack: */
+	double    *arrayA=NULL;
+	int* idxnA=NULL;
+
+	/*Verify that A is square*/
+	MatGetSize(*A,&mA,&nA);
+	MatGetLocalSize(*A,&local_mA,&local_nA);
+
+	/*Some dimensions checks: */
+	if (mA!=nA) _error_("trying to take the invert of a non-square matrix!");
+
+	/* Set default Plapack parameters */
+	//First find nprows*npcols=num_procs;
+	CyclicalFactorization(&nprows,&npcols,num_procs); 
+	//nprows=num_procs;
+	//npcols=1;
+	ierror = 0;
+	nb     = nA/num_procs;
+	if(nA - nb*num_procs) nb++; /* without cyclic distribution */
+
+	if (ierror){
+		PLA_Set_error_checking(ierror,PETSC_TRUE,PETSC_TRUE,PETSC_FALSE );
+	}
+	else {
+		PLA_Set_error_checking(ierror,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE );
+	}
+	nb_alg = 0;
+	if (nb_alg){
+		pla_Environ_set_nb_alg (PLA_OP_ALL_ALG,nb_alg);
+	}
+
+	/*Verify that plapack is not already initialized: */
+	if(PLA_Initialized(NULL)==TRUE)PLA_Finalize();
+	/* Create a 2D communicator */
+	PLA_Comm_1D_to_2D(comm,nprows,npcols,&comm_2d); 
+
+	/*Initlialize plapack: */
+	PLA_Init(comm_2d);
+
+	templ = NULL;
+	PLA_Temp_create(nb, 0, &templ);
+
+	/* Use suggested nb_alg if it is not provided by user */
+	if (nb_alg == 0){
+		PLA_Environ_nb_alg(PLA_OP_PAN_PAN,templ,&nb_alg);
+		pla_Environ_set_nb_alg(PLA_OP_ALL_ALG,nb_alg);
+	}
+
+	/* Set the datatype */
+	datatype = ISSM_MPI_DOUBLE;
+
+	/* Copy A into a*/
+	PLA_Matrix_create(datatype,mA,nA,templ,PLA_ALIGN_FIRST,PLA_ALIGN_FIRST,&a);  
+	PLA_Obj_set_to_zero(a);
+	/*Take array from A: use MatGetValues, because we are sure this routine works with 
+	any matrix type.*/
+	MatGetOwnershipRange(*A,&lower_row,&upper_row);
+	upper_row--; 
+	arrayA = xNew<double>(nA);
+	idxnA  = xNew<int>(nA);
+	for (i=0;i<nA;i++){
+		*(idxnA+i)=i;
+	}
+	PLA_API_begin();
+	PLA_Obj_API_open(a);  	
+	for (i=lower_row;i<=upper_row;i++){
+		MatGetValues(*A,1,&i,nA,idxnA,arrayA); 
+		PLA_API_axpy_matrix_to_global(1,nA, &one,(void *)arrayA,1,a,i,0); 
+	}
+	PLA_Obj_API_close(a); 
+	PLA_API_end(); 
+
+	/*Call the plapack invert routine*/
+	PLA_General_invert(PLA_METHOD_INV,a);
+
+	/*Translate Plapack a into Petsc invA*/
+	MatGetType(*A,&type);
+	PlapackToPetsc(inv_A,local_mA,local_nA,mA,nA,type,a,templ,nprows,npcols,nb);
+
+	/*Free ressources:*/
+	PLA_Obj_free(&a);
+	PLA_Temp_free(&templ);
+	xDelete<double>(arrayA);
+	xDelete<int>(idxnA);
+
+	/*Finalize PLAPACK*/
+	PLA_Finalize();
+	ISSM_MPI_Comm_free(&comm_2d);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 18231)
@@ -0,0 +1,95 @@
+/*!\file PlapackToPetsc.cpp
+ * \brief convert plapack matrix to petsc matrix
+ */
+
+#include "../../petsc/petscincludes.h"
+#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,COMM comm){
+
+	int i;
+
+	int lower_row,upper_row;
+	int* row_nodes=NULL;
+	int* col_nodes=NULL;
+	int* idxm=NULL;
+	int* idxn=NULL;
+	int myrow,mycol;
+	int count,idxm_count,idxn_count;
+	int d_nz,o_nz;
+	int i0,i1;
+	double* local_buffer=NULL;
+
+	/*Create matrix A (right now, we just have an allocated pointer A*/
+	if (strcasecmp_eq(type,MATMPIAIJ)){
+		/*See pretty large here, because we have no idea how many nnz per row*/
+		d_nz=nA/2;
+		o_nz=nA/2;
+		MatCreateMPIAIJ(comm,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
+	}
+	else if(strcasecmp_eq(type,MATMPIDENSE)){
+		MatCreateMPIDense(comm,local_mA,local_nA, mA,nA,PETSC_NULL,A); 
+	}
+
+	MatGetOwnershipRange(*A,&lower_row,&upper_row);
+	upper_row--;
+
+	/*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 
+	  use PLA_axpy_global_to_matrix to extract a local matrix, because this routine hangs when the 
+	  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);
+	col_nodes=xNew<int>(nA);
+	for (i=0;i<mA;i++){
+		i0=i/nb;
+		*(row_nodes+i)=i0%nprows;
+	}
+	for (i=0;i<nA;i++){
+		i0=i/nb;
+		i1=i0/nprows;
+		*(col_nodes+i)=i1%npcols;
+	}
+
+	PLA_Temp_comm_row_rank(templ,&mycol);
+	PLA_Temp_comm_col_rank(templ,&myrow);
+
+	idxm=xNew<int>(mA);
+	count=0;
+	for (i=0;i<mA;i++){
+		if(*(row_nodes+i)==myrow){
+			*(idxm+count)=i;
+			count++;
+		}
+	}
+	idxm_count=count;
+
+	idxn=xNew<int>(nA);
+	count=0;
+	for (i=0;i<nA;i++){
+		if(*(col_nodes+i)==mycol){
+			*(idxn+count)=i;
+			count++;
+		}
+	}
+	idxn_count=count;
+
+	/*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);
+	MatSetValues(*A,idxm_count,idxm,idxn_count,idxn,local_buffer,INSERT_VALUES);
+
+	/*assemble: */
+	MatAssemblyBegin(*A,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(*A,MAT_FINAL_ASSEMBLY);
+
+	/*Free ressources:*/
+	xDelete<int>(row_nodes);
+	xDelete<int>(col_nodes);
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/plapackpatches.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 18231)
@@ -0,0 +1,12 @@
+/*\file plapackpatches.h
+ * \brief: our own patches for plapack use
+ */
+
+#ifndef _PLAPACK_PATCHES_H_
+#define _PLAPACK_PATCHES_H_
+
+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);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/plapackincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/plapackincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/plapack/plapackincludes.h	(revision 18231)
@@ -0,0 +1,24 @@
+/* \file plapackincludes.h
+ * \brief all includes for Plapack + our own patches
+ */
+
+#ifndef _PLA_INCLUDES_H_
+#define _PLA_INCLUDES_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <PLA.h>
+
+/* missing Plapack prototypes: */
+int PLA_General_invert( int method, PLA_Obj A );
+
+/*our own patches: */
+#ifdef _HAVE_PETSC_
+#include "./patches/petscpatches.h"
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/scalapack/FortranMapping.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/scalapack/FortranMapping.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/scalapack/FortranMapping.h	(revision 18231)
@@ -0,0 +1,41 @@
+#ifndef _FORTRAN_MAPPING_H_
+#define _FORTRAN_MAPPING_H_
+/*
+ * Fortran_Mapping.h
+ *     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. 
+ * We had to look for these exact symbols in these libraries using nm | grep FORTRAN_NAME. In fact, the symbol naming is not well defined: see for example 
+ * numroc_ and blacs_gridinit__ (one underscore, then two). */
+
+#define BLACS_GRIDINFO(...) blacs_gridinfo__(__VA_ARGS__)
+#define SL_INIT(...) sl_init__(__VA_ARGS__)
+#define BLACS_GRIDEXIT(...) blacs_gridexit__(__VA_ARGS__)
+#define BLACS_EXIT(...) blacs_exit__(__VA_ARGS__) 
+#define DESCINIT(...) descinit_(__VA_ARGS__)
+#define NUMROC(...) numroc_(__VA_ARGS__)
+#define BLACS_GET(...) blacs_get__(__VA_ARGS__) 
+#define BLACS_GRIDINIT(...) blacs_gridinit__(__VA_ARGS__)
+#define BLACS_GRIDMAP(...) blacs_gridmap__(__VA_ARGS__)
+#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 
+ * ordering of matrices is column oriented*/
+
+void sl_init__(int*,int*,int*); 
+void blacs_exit__(int*);
+void blacs_gridinfo__(int*,int*,int*,int*,int*);
+void descinit_(int[9],int*,int*,int*,int*,int*,int*,int*,int*,int*);
+void blacs_gridexit__(int*);
+int numroc_(int*,int*,int*,int*,int*);
+void blacs_get__(int*,int*,int*);
+void blacs_gridinit__(int*,char*,int*,int*);
+void blacs_gridmap__(int*,int *,int*,int*,int*);
+
+/*LU factorization*/
+void pdgetrf_(int* M,int* N,double* A,int* IA,int* JA,int* DESCA,int* IPIV,int* INFOVAR);  
+void pdgetri_(int* N,double* A,int* IA,int* JA,int* DESCA,int* IPIV,double* WORK,int* LWORK,int* IWORK,int* LIWORK,int*	INFOVAR);
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkits.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkits.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkits.h	(revision 18231)
@@ -0,0 +1,40 @@
+/* \file toolkits.h
+ * \brief: this API allows use of external packages, provides patches, etc ...
+ */
+
+#ifndef _TOOLKITS_H_
+#define _TOOLKITS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_PETSC_
+#include "./petsc/petscincludes.h"
+#endif
+
+#include "./mpi/issmmpi.h"
+
+#ifdef _HAVE_METIS_
+#include "./metis/metisincludes.h"
+#endif
+
+#ifdef _HAVE_GSL_
+#include "./gsl/gslincludes.h"
+#endif
+
+#ifdef _HAVE_ADOLC_
+#include "./adolc/adolcincludes.h"
+#endif
+
+#ifdef _HAVE_TRIANGLE_
+#include "./triangle/triangleincludes.h"
+#endif
+
+#include "./objects/toolkitobjects.h"
+#include "./toolkitsenums.h"
+#include "./issm/issmtoolkit.h"
+#include "./ToolkitOptions.h"
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkitsenums.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkitsenums.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/toolkitsenums.h	(revision 18231)
@@ -0,0 +1,18 @@
+/* \file toolkitsenums.h
+ * \brief: enums that encompasse all of the toolkit APIs. This mainly maps into PETSC enums.
+ */
+
+#ifndef _TOOLKITSENUMS_H_
+#define _TOOLKITSENUMS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+typedef enum {INS_VAL, ADD_VAL} InsMode;
+typedef enum {NORM_INF,NORM_TWO,NORM_FROB} NormMode;
+typedef enum {DENSE_SEQUENTIAL,SPARSE_SEQUENTIAL} MatrixType;
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/triangle/triangleincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/triangle/triangleincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/c/toolkits/triangle/triangleincludes.h	(revision 18231)
@@ -0,0 +1,13 @@
+/* \file triangleincludes.h
+ * \brief all includes from triangle
+ */
+
+#ifndef _TRIANGLE_INCLUDES_H_
+#define _TRIANGLE_INCLUDES_H_
+
+#ifdef _C_ //only valid for iso C, not C++
+/*Triangle includes: */
+#include "triangle.h"
+#endif //#ifdef _C_
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/dox/issm.dox
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/dox/issm.dox	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/dox/issm.dox	(revision 18231)
@@ -0,0 +1,90 @@
+/** 
+  \mainpage ISSM C/C++ Source Code Browser
+
+  <BR>
+
+  <B> <I> Welcome ! </I> </B>
+
+  This is the searchable browsing tool for ISSM 
+  (the <a href="http://issm.jpl.nasa.gov">Ice Sheet System Model</a>).
+  
+  These pages were automatically generated by <a href="http://www.doxygen.org/">doxygen</a>, 
+  from the ISSM source code. 
+
+  Navigate the tabs above and browse through ISSM's 
+  C++ source code, files/directories, and data 
+  structures.
+
+  To find additional information regarding the use of
+  ISSM, its current release, or the ISSM team, please 
+  visit <a href="http://issm.jpl.nasa.gov">http://issm.jpl.nasa.gov</a>.
+
+  <BR>
+
+  <B> Helpful Links </B>
+
+  - Download ISSM <a href="http://issm.jpl.nasa.gov/download/">here</a>.
+
+  - ISSM Installation instructions for Linux/Mac OSX are found <a href="http://issm.jpl.nasa.gov/download/unix/">here</a>.
+  
+  - ISSM Installation instructions for Windows are found <a href="http://issm.jpl.nasa.gov/download/windows/">here</a>.
+
+  - For help using ISSM, see our online <a href="http://issm.jpl.nasa.gov/documentation/">Documentation</a>.
+  Other documentation is also available including simple tutorials 
+  and FAQ.
+
+  - A current publication list is kept <a href="http://issm.jpl.nasa.gov/publications/">here</a>.
+
+  - Contact us by e-mail at <a href="mailto:issm@jpl.nasa.gov">issm@jpl.nasa.gov</a>
+
+  <BR>
+  
+  <B> Code Stats</B>
+
+<table width="600px" rules=none border=0 bordercolor="#000000" cellpadding="3" align="center" style="border-collapse:collapse;">
+<tr>
+<th  bgcolor=#7AA9DD style="text-align:left;">Language</th><th  bgcolor=#7AA9DD style="text-align:right;">files</th><th  bgcolor=#7AA9DD style="text-align:right;">blank</th><th  bgcolor=#7AA9DD style="text-align:right;">comment</th><th  bgcolor=#7AA9DD style="text-align:right;">code</th><th  bgcolor=#7AA9DD style="text-align:right;">Total</th>
+</th>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">453</td><td  bgcolor=#FFFFFF style="text-align:right;">15861</td><td  bgcolor=#FFFFFF style="text-align:right;">18188</td><td  bgcolor=#FFFFFF style="text-align:right;">68849</td><td  bgcolor=#FFFFFF style="text-align:right;">102898</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1378</td><td  bgcolor=#C6E2FF style="text-align:right;">8341</td><td  bgcolor=#C6E2FF style="text-align:right;">16259</td><td  bgcolor=#C6E2FF style="text-align:right;">38645</td><td  bgcolor=#C6E2FF style="text-align:right;">63245</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">421</td><td  bgcolor=#FFFFFF style="text-align:right;">3504</td><td  bgcolor=#FFFFFF style="text-align:right;">3753</td><td  bgcolor=#FFFFFF style="text-align:right;">15489</td><td  bgcolor=#FFFFFF style="text-align:right;">22746</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">9</td><td  bgcolor=#C6E2FF style="text-align:right;">1588</td><td  bgcolor=#C6E2FF style="text-align:right;">151</td><td  bgcolor=#C6E2FF style="text-align:right;">11565</td><td  bgcolor=#C6E2FF style="text-align:right;">13304</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">144</td><td  bgcolor=#FFFFFF style="text-align:right;">2330</td><td  bgcolor=#FFFFFF style="text-align:right;">2559</td><td  bgcolor=#FFFFFF style="text-align:right;">9348</td><td  bgcolor=#FFFFFF style="text-align:right;">14237</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> XML </th><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">160</td><td  bgcolor=#C6E2FF style="text-align:right;">92</td><td  bgcolor=#C6E2FF style="text-align:right;">3075</td><td  bgcolor=#C6E2FF style="text-align:right;">3327</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Java </th><td  bgcolor=#FFFFFF style="text-align:right;">18</td><td  bgcolor=#FFFFFF style="text-align:right;">719</td><td  bgcolor=#FFFFFF style="text-align:right;">891</td><td  bgcolor=#FFFFFF style="text-align:right;">2321</td><td  bgcolor=#FFFFFF style="text-align:right;">3931</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Fortran  77 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">302</td><td  bgcolor=#C6E2FF style="text-align:right;">365</td><td  bgcolor=#C6E2FF style="text-align:right;">671</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">61</td><td  bgcolor=#FFFFFF style="text-align:right;">88</td><td  bgcolor=#FFFFFF style="text-align:right;">266</td><td  bgcolor=#FFFFFF style="text-align:right;">415</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> XSD </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">30</td><td  bgcolor=#C6E2FF style="text-align:right;">36</td><td  bgcolor=#C6E2FF style="text-align:right;">229</td><td  bgcolor=#C6E2FF style="text-align:right;">295</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">1</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">9</td><td  bgcolor=#FFFFFF style="text-align:right;">196</td><td  bgcolor=#FFFFFF style="text-align:right;">211</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Ant </th><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">16</td><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">103</td><td  bgcolor=#C6E2FF style="text-align:right;">126</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2441</td><td  bgcolor=#FFFFFF style="text-align:right;">32620</td><td  bgcolor=#FFFFFF style="text-align:right;">42335</td><td  bgcolor=#FFFFFF style="text-align:right;">150451</td><td  bgcolor=#FFFFFF style="text-align:right;">225406</td>
+</tr>
+</table>
+
+	<I> Copyright (C) 2014 </I>
+  */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/COPYING
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/COPYING	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/COPYING	(revision 18231)
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/Changelog_1.0.0.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/Changelog_1.0.0.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/Changelog_1.0.0.txt	(revision 18231)
@@ -0,0 +1,29 @@
+This is the changelog for Inishell release 1.0.0
+	*editing existing ini file:
+		+populate the GUI according to the values in an existing ini file
+		+show progress bar while loading
+		+Comments are preserved, nested template parameters properly handled, unknown keys are preserved
+
+	*usability improvements:
+		+the file dialogs remember the last path they pointed to
+		+add ".ini" extension when saving to a config file if necessary
+		+new icons, hoping to make their meaning clearer
+		+reset button on the GUI to revert to defaults
+
+	*layout improvements:
+		+fixed help text horizontal alignements issues
+		+the help text is now verticaly aligned with the top of the widget
+		+Notion of hierarchy for an easier handling of layout issues
+		+layout now consistent between Linux and Windows, still some small spacing differences with osX
+		+possibility to group parameters in a frame with a frame title
+
+	*bug fixes:
+		+default value in comboBox is honored
+		+mandatory comboBox properly handled on osX
+		+better help text handling
+
+	*others:
+		+keys are printed in the order they appear on the GUI
+		+code cleanup and optimizations
+		+add version information in MANIFEST and title bar
+		+clean up and reorganization in build.xml, add help and pack targets
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/License.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/License.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/License.txt	(revision 18231)
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/MANIFEST.MF
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/MANIFEST.MF	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/MANIFEST.MF	(revision 18231)
@@ -0,0 +1,14 @@
+Manifest-Version: 1.0
+Ant-Version: Apache Ant 1.8.4
+Created-By: 1.6.0_51-b11-457-11M4509 (Apple Inc.)
+Built-By: larour
+Built-On: 2014-04-14
+Built-At: 14:27:23
+Main-Class: main/GUIBuilder
+Specification-Title: INI file generator
+Specification-Version: 1.0.0-20140414
+Specification-Vendor: SLF, www.slf.ch
+Implementation-Title: INIshell ini creator
+Implementation-Version: 1.0.0
+Implementation-Vendor: SLF, www.slf.ch
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/build.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/build.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/build.xml	(revision 18231)
@@ -0,0 +1,126 @@
+<project name="inishell" default="help" basedir=".">
+	<description>
+	Build and run the inishell Application from the command line.
+	</description>
+
+
+	<!-- set global properties for the build -->
+	<property name="src" location="src"/>
+	<property name="examples" location="doc/examples"/>
+	<property name="build" location="build"/>
+	<property name="dist"  location="dist"/>
+	<property name="lib.dir" location="lib"/>
+	<tstamp prefix="build-info">
+		<format property="date" pattern="yyyy-MM-dd" locale="en" />
+		<format property="time" pattern="HH:mm:ss" locale="en" />
+		<format property="num-date" pattern="yyyyMMdd" locale="en" />
+	</tstamp>
+	<property name="version.num" value="1.0.0" />
+	<!--<buildnumber file="dist/build.num"/>-->
+	<!--<property name="version-number" value="${version.num}-${build.number}" />-->
+	<property name="version-number" value="${version.num}" />
+	<property name="version-full" value="${version.num}-${build-info.num-date}" />
+
+	<path id="classpath">
+		<fileset dir="${lib.dir}" includes="**/*.jar"/>
+	</path>
+
+
+	<!-- targets -->
+	<target name="help">
+		<echo>You can use the following targets:</echo>
+		<echo> </echo>
+		<echo>  help     : (default) Prints this message </echo>
+		<echo>  init     : create necessary directories</echo>
+		<echo>  clean    : Deletes work directories</echo>
+		<echo>  compile  : Compiles into class files</echo>
+		<echo>  dist     : pack all necessary files into a JAR file</echo>
+		<echo>  issm 	 : create inishell GUI using issm.xml</echo>
+		<echo>  snowpack : dist tailored for snowpack</echo>
+		<echo>  meteoio  : dist tailored for meteoio</echo>
+		<echo>  run      : run the previously compiled version</echo>
+		<echo>  pack     : pack all in a zip file for a release</echo>
+		<echo></echo>
+	</target>
+
+	<target name="init">
+		<mkdir dir="${build}"/>
+		<mkdir dir="${dist}"/>
+	</target>
+
+	<target name="snowpack" depends="init" description="Make doc/examples/snowpack_config.xml the default XML config">
+		<copy file="${examples}/snowpack_config.xml" tofile="${build}/resources/default_config.xml" overwrite="true"/>
+		<antcall target="dist"/>
+	</target>
+
+	<target name="meteoio" depends="init" description="Make doc/examples/meteoio_config.xml the default XML config">
+		<copy file="${examples}/meteoio_config.xml" tofile="${build}/resources/default_config.xml" overwrite="true"/>
+		<antcall target="dist"/>
+	</target>
+	
+	<target name="issm" depends="init" description="Make doc/examples/issm.xml the default XML config">
+		<copy file="./doc/examples/issm.xml" tofile="${build}/resources/default_config.xml" overwrite="true"/>
+		<antcall target="dist"/>
+	</target>
+
+	<target name="compile" depends="init" description="Compile from ${src} to ${build}">
+		<javac srcdir="${src}" destdir="${build}" includeantruntime="false">
+			<classpath>
+				<fileset dir="lib">
+				<include name="**/*.jar"/>
+				</fileset>
+			</classpath>
+		</javac>
+		<copy todir="${build}/resources">
+		<fileset dir="${src}/resources" includes="**"/>
+	</copy>
+	</target>
+
+	<target name="dist" depends="compile" description="generate the distribution" >
+		<!-- Create the distribution directory -->
+		<delete file="MANIFEST.MF"/>
+		<manifest file="MANIFEST.MF">
+			<attribute name="Built-By" value="${user.name}"/>
+			<attribute name="Built-On" value="${build-info.date}" />
+			<attribute name="Built-At" value="${build-info.time}" />
+			<attribute name="Main-Class" value="main/GUIBuilder"/>
+			<attribute name="Specification-Title" value="INI file generator"/>
+			<attribute name="Specification-Version" value="${version-full}"/>
+			<attribute name="Specification-Vendor" value="SLF, www.slf.ch"/>
+			<attribute name="Implementation-Title" value="INIshell ini creator"/>
+			<attribute name="Implementation-Version" value="${version-number}"/>
+			<attribute name="Implementation-Vendor" value="SLF, www.slf.ch"/>
+		</manifest>
+
+		<!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
+		<jar jarfile="${dist}/inishell.jar" basedir="${build}" manifest="MANIFEST.MF" index="true" >
+			<zipfileset src="${lib.dir}/miglayout-4.0.jar" includes="**/*.class"/>
+		</jar>
+	</target>
+
+	<target name="run" depends="dist">
+		<java fork="true" classname="main/GUIBuilder">
+			<classpath>
+				<path refid="classpath"/>
+				<path location="${dist}/inishell.jar"/>
+			</classpath>
+		</java>
+	</target>
+
+	<target name="clean" description="clean up" >
+		<!-- Delete the ${build} and ${dist} directory trees -->
+		<delete file="MANIFEST.MF"/>
+		<delete dir="${build}"/>
+		<delete dir="${dist}"/>
+	</target>
+
+	<target name="pack" depends="dist" description="pack for distribution">
+		<zip destfile="inishell-${version.num}.zip">
+			<zipfileset dir="doc/examples" prefix="inishell-${version.num}/doc/examples"/>
+			<zipfileset dir="dist" prefix="inishell-${version.num}/bin"/>
+			<zipfileset dir="." includes="inishell.sh" prefix="inishell-${version.num}/bin"/>
+			<zipfileset dir="." includes="Changelog_${version.num}.txt" prefix="inishell-${version.num}/doc"/>
+		</zip>
+	</target>
+
+</project>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema-0.1.1.xsd
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema-0.1.1.xsd	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema-0.1.1.xsd	(revision 18231)
@@ -0,0 +1,154 @@
+<?xml version="1.0"?>
+<!-- 
+*   
+*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*    	
+* -->
+<xsd:schema version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+  <xsd:element name="inishell_config" type="general" />
+  
+  <xsd:complexType name="general">
+    <xsd:choice maxOccurs="unbounded">
+      <xsd:element name="parameter" type="parametertype" />
+      <xsd:element name="parametergroup" type="pargroup" />
+      <xsd:element name="include" type="pathonly" /> 
+      <xsd:element name="frame" type="framegroup" /> 
+    </xsd:choice>
+    <xsd:attribute name="application" />
+  </xsd:complexType>
+
+  <xsd:complexType name="framegroup">
+    <xsd:choice minOccurs="1" maxOccurs="unbounded">
+      <xsd:element name="parameter" type="parametertype" />
+      <xsd:element name="reference" type="nameonly" />
+      <xsd:element name="section" type="nameonly"/>
+    </xsd:choice>
+    <xsd:attribute name="key" />
+    <xsd:attribute name="label" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="parametertype">
+    <xsd:complexContent>
+      <xsd:extension base="parbasetype">
+		<xsd:attribute name="key" type="xsd:string" use="required"/> 
+		<xsd:attribute name="default" type="xsd:string" />
+		<xsd:attribute name="counter" type="xsd:integer" />
+      </xsd:extension>
+    </xsd:complexContent>		
+  </xsd:complexType>
+  
+  <xsd:complexType name="nameonly">
+	<xsd:attribute name="name" />   
+  </xsd:complexType>
+
+  <xsd:complexType name="optionvalue">
+	<xsd:attribute name="value" />   
+  </xsd:complexType>
+
+  <xsd:complexType name="pathonly">
+	<xsd:attribute name="path" />   
+  </xsd:complexType>
+  
+  <xsd:complexType name="pargroup">
+	<xsd:choice minOccurs="1" maxOccurs="unbounded">
+	  <xsd:element name="parameter" type="parametertype" />
+	  <xsd:element name="reference" type="nameonly" />
+	  <xsd:element name="option" type="optionvalue" />
+	  <xsd:element name="frame" type="framegroup" /> 
+	</xsd:choice>
+	<xsd:attribute name="name" />
+  </xsd:complexType>
+
+  <xsd:complexType name="parbasetype">
+	<xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="section" type="nameonly"/>
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="replace" type="nameonly"/>
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="parameter" type="parametertype" />
+	  </xsd:sequence>
+	  <xsd:choice minOccurs="0" maxOccurs="unbounded">				
+		<xsd:element name="option" minOccurs="0">
+		  <xsd:complexType>
+			<xsd:complexContent>
+			  <xsd:extension base="parbasetype">
+				<xsd:attribute name="value" type="xsd:string" use="required" />
+				<xsd:attribute name="label" type="xsd:string" use="optional" />
+				<xsd:attribute name="default" type="xsd:boolean" use="optional"/>
+			  </xsd:extension>
+			</xsd:complexContent>
+		  </xsd:complexType>
+		</xsd:element>
+	  </xsd:choice>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="reference" type="nameonly" />
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="help" type="helptype"/>	
+	  </xsd:sequence>
+	</xsd:sequence>
+	
+	<xsd:attribute name="type" use="required">
+	  <xsd:simpleType>
+		<xsd:restriction base="xsd:string">
+		  <xsd:enumeration value="integer" />
+		  <xsd:enumeration value="integer+" />
+		  <xsd:enumeration value="decimal" />
+		  <xsd:enumeration value="path" />
+		  <xsd:enumeration value="file" />
+		  <xsd:enumeration value="choice" />
+		  <xsd:enumeration value="alternative" />
+		  <xsd:enumeration value="dropdown" />
+		  <xsd:enumeration value="string" />
+		  <xsd:enumeration value="combination" />
+		  <xsd:enumeration value="selector" />
+		</xsd:restriction>
+	  </xsd:simpleType>
+	</xsd:attribute>
+	
+	<xsd:attribute name="maximum" type="xsd:integer"/>
+	<xsd:attribute name="minimum" type="xsd:integer"/>
+	<xsd:attribute name="template" type="xsd:boolean" default="false" use="optional" />
+	<xsd:attribute name="optional" type="xsd:boolean" default="true" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="needstype">
+	<xsd:attribute name="type" type="xsd:string" use="required" />
+	<xsd:attribute name="name" type="xsd:string" use="required" />
+	
+	<xsd:attribute name="value" />
+	<xsd:attribute name="optional" type="xsd:boolean" />
+	<xsd:attribute name="minoccur" type="xsd:integer" />
+	<xsd:attribute name="maxoccur" type="xsd:string" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="baseType">
+	<xsd:sequence minOccurs="0" maxOccurs="1">
+	  <xsd:element name="help" type="helptype" />		
+	</xsd:sequence>
+	<xsd:attribute name="key" type="xsd:string" use="required" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="helptype" mixed="true">
+	<xsd:choice minOccurs="0" maxOccurs="unbounded">
+	  <xsd:element name="section" type="nameonly" />
+	  <xsd:element name="replace" type="nameonly" />
+	</xsd:choice>
+  </xsd:complexType> 
+</xsd:schema>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema.xsd
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema.xsd	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/config_schema.xsd	(revision 18231)
@@ -0,0 +1,141 @@
+<?xml version="1.0"?>
+<!-- 
+*   
+*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*    	
+* -->
+
+<xsd:schema version="1.0"
+xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+  <xsd:element name="inishell_config" type="general" />
+  
+	<xsd:complexType name="general">
+      <xsd:choice maxOccurs="unbounded">
+			<xsd:element name="parameter" type="parametertype" />
+			<xsd:element name="parametergroup" type="pargroup" />
+			<xsd:element name="include" type="pathonly" /> 
+      </xsd:choice>
+	  <xsd:attribute name="application" />
+    </xsd:complexType>
+	
+	<xsd:complexType name="parametertype">
+		<xsd:complexContent>
+			<xsd:extension base="parbasetype">
+				<xsd:attribute name="key" type="xsd:string" use="required"/> 
+				<xsd:attribute name="default" type="xsd:string" />
+				<xsd:attribute name="counter" type="xsd:integer" />
+			</xsd:extension>
+		</xsd:complexContent>		
+	</xsd:complexType>
+   
+   <xsd:complexType name="nameonly">
+		<xsd:attribute name="name" />   
+   </xsd:complexType>
+   
+   <xsd:complexType name="pathonly">
+		<xsd:attribute name="path" />   
+   </xsd:complexType>
+   
+	<xsd:complexType name="pargroup">
+		<xsd:choice minOccurs="1" maxOccurs="unbounded">
+			<xsd:element name="parameter" type="parametertype" />
+			<xsd:element name="reference" type="nameonly" />
+		</xsd:choice>
+		<xsd:attribute name="name" />
+	</xsd:complexType>
+  
+	
+	<xsd:complexType name="parbasetype">
+		<xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="section" type="nameonly"/>
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="replace" type="nameonly"/>
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="parameter" type="parametertype" />
+			</xsd:sequence>
+			<xsd:choice minOccurs="0" maxOccurs="unbounded">				
+				<xsd:element name="option" minOccurs="0">
+					<xsd:complexType>
+						<xsd:complexContent>
+							<xsd:extension base="parbasetype">
+								<xsd:attribute name="value" type="xsd:string" use="required" />
+								<xsd:attribute name="label" type="xsd:string" use="optional" />
+								<xsd:attribute name="default" type="xsd:boolean"/>
+							</xsd:extension>
+						</xsd:complexContent>
+					</xsd:complexType>
+				</xsd:element>
+			</xsd:choice>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="reference" type="nameonly" />
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="help" type="helptype"/>	
+			</xsd:sequence>
+		</xsd:sequence>
+		
+		<xsd:attribute name="type" use="required">
+		     <xsd:simpleType>
+				<xsd:restriction base="xsd:string">
+					<xsd:enumeration value="integer" />
+					<xsd:enumeration value="integer+" />
+					<xsd:enumeration value="decimal" />
+					<xsd:enumeration value="path" />
+					<xsd:enumeration value="file" />
+					<xsd:enumeration value="choice" />
+					<xsd:enumeration value="alternative" />
+					<xsd:enumeration value="string" />
+					<xsd:enumeration value="combination" />
+					<xsd:enumeration value="selector" />
+				</xsd:restriction>
+			</xsd:simpleType>
+		</xsd:attribute>
+		
+		<xsd:attribute name="maximum" type="xsd:integer"/>
+		<xsd:attribute name="minimum" type="xsd:integer"/>
+		<xsd:attribute name="template" type="xsd:boolean" default="false" use="optional" />
+		<xsd:attribute name="optional" type="xsd:boolean" default="true" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="needstype">
+		<xsd:attribute name="type" type="xsd:string" use="required" />
+		<xsd:attribute name="name" type="xsd:string" use="required" />
+	
+		<xsd:attribute name="value" />
+		<xsd:attribute name="optional" type="xsd:boolean" />
+		<xsd:attribute name="minoccur" type="xsd:integer" />
+		<xsd:attribute name="maxoccur" type="xsd:string" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="baseType">
+		<xsd:sequence minOccurs="0" maxOccurs="1">
+			<xsd:element name="help" type="helptype" />		
+		</xsd:sequence>
+		<xsd:attribute name="key" type="xsd:string" use="required" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="helptype" mixed="true">
+		<xsd:choice minOccurs="0" maxOccurs="unbounded">
+			<xsd:element name="section" type="nameonly" />
+			<xsd:element name="replace" type="nameonly" />
+		</xsd:choice>
+	</xsd:complexType>
+	
+</xsd:schema>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/default_config.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/default_config.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/default_config.xml	(revision 18231)
@@ -0,0 +1,1284 @@
+<inishell_config application="ISSM prototype">
+
+<!-- mesh -->
+<parameter key ="Dimension" type="alternative" optional="false">
+     <section name="mesh" />
+     <option value="0" type="string" default="true">
+        <help> dimension is 0 </help>
+     </option>
+     <option value="3" type="string">
+        <help> dimension is 3 </help>
+       <!-- Elements and vertices of the original 2d mesh -->
+          <parameter key ="x2d" type="double" default="N/A">
+              <help> vertices x coordinate [m] </help>
+          </parameter>
+          <parameter key ="y2d" type="double" default="N/A">
+              <help> vertices y coordinate [m] </help>
+          </parameter>
+          <parameter key ="elements2d" type="double" default="N/A">
+              <help> vertex indices of the mesh elements </help>
+          </parameter>
+          <parameter key ="numberofvertices2d" type="double" default="0">
+              <help> number of vertices </help>
+          </parameter>
+          <parameter key ="numberofelements2d" type="double" default="0">
+              <help> number of elements </help>
+          </parameter>
+     </option>
+     <help> select a mesh dimension 0(default) or 3 </help>
+</parameter>
+<frame key="1" label="Elements and vertices">
+<section name="mesh" />
+  <parameter key ="numberofelements" type="double" default="0">
+     <section name="mesh" />
+     <help> number of elements </help>
+  </parameter>
+  <parameter key ="numberofvertices" type="double" default="0">
+     <section name="mesh" />
+     <help> number of verticies </help>
+  </parameter>
+  <parameter key ="elements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertex indices of the mesh elements </help>
+  </parameter>
+  <parameter key ="x" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices x coordinate [m] </help>
+  </parameter>
+  <parameter key ="y" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices y coordinate [m] </help>
+  </parameter>
+  <parameter key ="z" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices z coordinate [m] </help>
+  </parameter>
+  <parameter key ="edges" type="double" default="N/A">
+     <section name="mesh" />
+     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>
+  </parameter>
+  <parameter key ="numberofedges" type="double" default="0">
+     <section name="mesh" />
+     <help> number of edges of the 2d mesh </help>
+  </parameter>
+</frame>
+<frame key="2" label="Properties">
+<section name="mesh" />
+  <parameter key ="selected dimension" type="double" default="0">
+     <section name="mesh" />
+     <help> mesh dimension </help>
+  </parameter>
+  <parameter key ="numberoflayers" type="double" default="0">
+     <section name="mesh" />
+     <help> number of extrusion layers </help>
+  </parameter>
+  <parameter key ="vertexonbed" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower vertices flags list </help>
+  </parameter>
+  <parameter key ="elementonbed" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower elements flags list </help>
+  </parameter>
+  <parameter key ="vertexonsurface" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper vertices flags list </help>
+  </parameter>
+  <parameter key ="elementonsurface" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper element flag list </help>
+  </parameter>
+  <parameter key ="uppervertex" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper vertex list (NaN for vertex on the upper surface) </help>
+  </parameter>
+  <parameter key ="upperelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper element list (NaN for element on the upper layer) </help>
+  </parameter>
+  <parameter key ="lowervertex" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower vertex list (NaN for vertex on the lower surface) </help>
+  </parameter>
+  <parameter key ="lowerelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower element list (NaN for element on the lower layer </help>
+  </parameter>
+  <parameter key ="vertexonboundary" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices on the boundary of the domain flag list </help>
+  </parameter>
+  <parameter key ="segments" type="double" default="N/A">
+     <section name="mesh" />
+     <help> edges on domain boundary (vertex1 vertex2 element) </help>
+  </parameter>
+  <parameter key ="segmentmarkers" type="double" default="N/A">
+     <section name="mesh" />
+     <help> number associated to each segment </help>
+  </parameter>
+  <parameter key ="vertexconnectivity" type="double" default="N/A">
+     <section name="mesh" />
+     <help> list of vertices connected to vertex_i </help>
+  </parameter>
+  <parameter key ="elementconnectivity" type="double" default="N/A">
+     <section name="mesh" />
+     <help> list of vertices connected to element_i </help>
+  </parameter>
+  <parameter key ="average_vertex_connectivity" type="double" default="25">
+     <section name="mesh" />
+     <help> average number of vertices connected to one vertex </help>
+  </parameter>
+</frame>
+<frame key="3" label="Extracted Model">
+<section name="mesh" />
+  <parameter key ="extractedvertices" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices extracted from the model </help>
+  </parameter>
+  <parameter key ="extractedelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> elements extracted from the model </help>
+  </parameter>
+</frame>
+<frame key="4" label="Projection">
+<section name="mesh" />
+  <parameter key ="lat" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices latitude [degrees] </help>
+  </parameter>
+  <parameter key ="long" type="double" default="N/A">
+     <section name="mesh" />
+     <help> verticies longitude [degrees] </help>
+  </parameter>
+  <parameter key ="hemisphere" type="double" default="N/A">
+     <section name="mesh" />
+     <help> Indicate hemisphere 'n' or 's' </help>
+  </parameter></frame>
+
+
+<!-- mask -->
+<parameter key ="groundedice_levelset" type="double" default="NaN">
+     <section name="mask" />
+     <help> is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if &amp;lt; 0 </help>
+</parameter>
+<parameter key ="ice_levelset" type="double" default="NaN">
+     <section name="mask" />
+     <help> presence of ice if > 0, icefront position if = 0, no ice if &amp;lt; 0 </help>
+</parameter>
+
+<!-- geometry -->
+<frame key="1" label="Geometry parameters">
+<section name="geometry" />
+<parameter key ="surface" type="path" optional="false">
+     <section name="geometry" />
+     <help> surface elevation [m] </help>
+</parameter>
+<parameter key ="thickness" type="path" optional="false">
+     <section name="geometry" />
+     <help> ice thickness [m] </help>
+</parameter>
+<parameter key ="bed" type="path" optional="false">
+     <section name="geometry" />
+     <help> bed elevation [m] </help>
+</parameter>
+<parameter key ="bathymetry" type="double" default="N/A">
+     <section name="geometry" />
+     <help> bathymetry elevation [m] </help>
+</parameter>
+<parameter key ="hydrostatic_ratio" type="double" default="N/A">
+     <section name="geometry" />
+     <help> coefficient for ice shelves; thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro </help>
+</parameter></frame>
+
+
+<!-- constants -->
+<parameter key ="g" type="double" default="9.81">
+     <section name="constants" />
+     <help> gravitational acceleration [m/s^2] </help>
+</parameter>
+<parameter key ="yts" type="double" default="31536000">
+     <section name="constants" />
+     <help> number of seconds in a year [s/yr] </help>
+</parameter>
+<parameter key ="referencetemperature" type="double" default="223.15">
+     <section name="constants" />
+     <help> reference temperature used in the enthalpy model [K] </help>
+</parameter>
+
+<!-- surfaceforcings(SMB) -->
+<parameter key ="mass_balance" type="double" default="NaN">
+     <section name="surfaceforcings(SMB)" />
+     <help> surface mass balance [m/yr ice eq] </help>
+</parameter>
+
+<!-- basalforcings -->
+<parameter key ="melting_rate" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> basal melting rate (positive if melting) [m/yr] </help>
+</parameter>
+<parameter key ="melting_rate_correction" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> additional melting applied to compensate for dh/dt [m/yr] </help>
+</parameter>
+<parameter key ="geothermalflux" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> geothermal heat flux [W/m^2] </help>
+</parameter>
+
+<!-- materials -->
+<parameter key ="rho_ice" type="double" default="917">
+     <section name="materials" />
+     <help> ice density [kg/m^3] </help>
+</parameter>
+<parameter key ="rho_water" type="double" default="1023">
+     <section name="materials" />
+     <help> ocean water density [kg/m^3] </help>
+</parameter>
+<parameter key ="rho_freshwater" type="double" default="1000">
+     <section name="materials" />
+     <help> fresh water density [kg/m^3] </help>
+</parameter>
+<parameter key ="mu_water" type="double" default="0.001787">
+     <section name="materials" />
+     <help> water viscosity [N s/m^2] </help>
+</parameter>
+<parameter key ="heatcapacity" type="double" default="2093">
+     <section name="materials" />
+     <help> heat capacity [J/kg/K] </help>
+</parameter>
+<parameter key ="latentheat" type="double" default="334000">
+     <section name="materials" />
+     <help> latent heat of fusion [J/kg] </help>
+</parameter>
+<parameter key ="thermalconductivity" type="double" default="2.4">
+     <section name="materials" />
+     <help> ice thermal conductivity [W/m/K] </help>
+</parameter>
+<parameter key ="temperateiceconductivity" type="double" default="0.24">
+     <section name="materials" />
+     <help> temperate ice thermal conductivity [W/m/K] </help>
+</parameter>
+<parameter key ="meltingpoint" type="double" default="273.15">
+     <section name="materials" />
+     <help> melting point of ice at 1atm in K </help>
+</parameter>
+<parameter key ="beta" type="double" default="9.8e-08">
+     <section name="materials" />
+     <help> rate of change of melting point with pressure [K/Pa] </help>
+</parameter>
+<parameter key ="mixed_layer_capacity" type="double" default="3974">
+     <section name="materials" />
+     <help> mixed layer capacity [W/kg/K] </help>
+</parameter>
+<parameter key ="thermal_exchange_velocity" type="double" default="0.0001">
+     <section name="materials" />
+     <help> thermal exchange velocity [m/s] </help>
+</parameter>
+<parameter key ="rheology_B" type="double" default="N/A">
+     <section name="materials" />
+     <help> flow law parameter [Pa/s^(1/n)] </help>
+</parameter>
+<parameter key ="rheology_n" type="double" default="N/A">
+     <section name="materials" />
+     <help> Glens flow law exponent </help>
+</parameter>
+<parameter key ="rheology_law" type="char" default="'Paterson'">
+     <section name="materials" />
+     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>
+</parameter>
+<parameter key ="lithosphere_shear_modulus" type="double" default="67000000000">
+     <section name="materials" />
+     <help> Lithosphere shear modulus [Pa] </help>
+</parameter>
+<parameter key ="lithosphere_density" type="double" default="3.32">
+     <section name="materials" />
+     <help> Lithosphere density [g/cm^-3] </help>
+</parameter>
+<parameter key ="mantle_shear_modulus" type="double" default="145000000000">
+     <section name="materials" />
+     <help> Mantle shear modulus [Pa] </help>
+</parameter>
+<parameter key ="mantle_density" type="double" default="3.34">
+     <section name="materials" />
+     <help> Mantle density [g/cm^-3] </help>
+</parameter>
+
+
+<!-- damage -->
+<!-- Note: this class depends on different input of law -->
+<parameter key ="law" type="alternative" optional="false">
+	<section name="damage" />
+	<option value="undamage" type="string" default="true">
+		<help> law = undamage </help>
+	</option>
+	<option value="pralong" type="string" default="false">
+		<help> law = pralong </help>
+		<parameter key ="stress_threshold" type="double" default="0">
+			<help> damage stress threshold [Pa] </help>
+		</parameter>
+		<parameter key ="c1" type="double" default="0">
+			<help> damage parameter 1 </help>
+		</parameter>
+		<parameter key ="c2" type="double" default="0">
+			<help> damage parameter 2 </help>
+		</parameter>
+		<parameter key ="c3" type="double" default="0">
+			<help> damage parameter 3 [W/m^2] </help>
+		</parameter>
+		<parameter key ="c4" type="double" default="0">
+			<help> damage parameter 4 </help>
+		</parameter>
+		<parameter key ="healing" type="double" default="0">
+			<help> damage healing parameter 1 </help>
+		</parameter>
+		<parameter key ="equiv_stress" type="double" default="0">
+			<help> 0: von Mises </help>
+		</parameter>
+		<parameter key ="requested_outputs" type="cell" default="{'default'}">
+			<help> additional outputs requested </help>
+		</parameter>
+	</option>
+	<help> damage law (string) from {"undamaged","pralong"} </help>
+</parameter>
+<parameter key ="D" type="double" default="0">
+     <section name="damage" />
+     <help> damage tensor (scalar) </help>
+</parameter>
+<parameter key ="law" type="char" default="undamaged">
+     <section name="damage" />
+     <help> damage law (string) from {"undamaged","pralong"} </help>
+</parameter>
+<parameter key ="spcdamage" type="double" default="NaN">
+     <section name="damage" />
+     <help> damage constraints (NaN means no constraint) </help>
+</parameter>
+<parameter key ="max_damage" type="double" default="0.99999">
+     <section name="damage" />
+     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="2">
+     <section name="damage" />
+     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>
+</parameter>
+<parameter key ="maxiter" type="double" default="100">
+     <section name="damage" />
+     <help> maximum number of non linear iterations </help>
+</parameter>
+<parameter key ="penalty_lock" type="double" default="0">
+     <section name="damage" />
+     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>
+</parameter>
+<parameter key ="penalty_threshold" type="double" default="0">
+     <section name="damage" />
+     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>
+</parameter>
+<parameter key ="penalty_factor" type="double" default="3">
+     <section name="damage" />
+     <help> scaling exponent (default is 3) </help>
+</parameter>
+
+
+<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->
+<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">
+<section name="friction" />
+<parameter key ="coefficient" type="double" default="N/A">
+     <section name="friction" />
+     <help> friction coefficient [SI] </help>
+</parameter>
+<parameter key ="p" type="double" default="N/A">
+     <section name="friction" />
+     <help> p exponent </help>
+</parameter>
+<parameter key ="q" type="double" default="N/A">
+     <section name="friction" />
+     <help> q exponent </help>
+</parameter></frame>
+
+
+<!-- flowequation -->
+<frame key="1" label="Flow equation parameters">
+<section name="flowequation" />
+<parameter key ="isSIA" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Shallow Ice Approximation (SIA) used ? </help>
+</parameter>
+<parameter key ="isSSA" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>
+</parameter>
+<parameter key ="isL1L2" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the L1L2 approximation used ? </help>
+</parameter>
+<parameter key ="isHO" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Higher-Order (HO) approximation used ? </help>
+</parameter>
+<parameter key ="isFS" type="double" default="0">
+     <section name="flowequation" />
+     <help> are the Full-FS (FS) equations used ? </help>
+</parameter>
+<parameter key ="fe_SSA" type="char" default="'P1'">
+     <section name="flowequation" />
+     <help> Finite Element for SSA  "P1", "P1bubble" "P1bubblecondensed" "P2" </help>
+</parameter>
+<parameter key ="fe_HO" type="char" default="'P1'">
+     <section name="flowequation" />
+     <help> Finite Element for HO   "P1" "P1bubble" "P1bubblecondensed" "P1xP2" "P2xP1" "P2" </help>
+</parameter>
+<parameter key ="fe_FS" type="char" default="'MINIcondensed'">
+     <section name="flowequation" />
+     <help> Finite Element for FS   "P1P1" (debugging only) "P1P1GLS" "MINIcondensed" "MINI" "TaylorHood" </help>
+</parameter>
+<parameter key ="vertex_equation" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> flow equation for each vertex </help>
+</parameter>
+<parameter key ="element_equation" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> flow equation for each element </help>
+</parameter>
+<parameter key ="borderSSA" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on SSAs border (for tiling) </help>
+</parameter>
+<parameter key ="borderHO" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on HOs border (for tiling) </help>
+</parameter>
+<parameter key ="borderFS" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on FS border (for tiling) </help>
+</parameter></frame>
+
+
+<!-- Timestepping -->
+<parameter key ="start_time" type="double" default="0">
+     <section name="timestepping" />
+     <help> simulation starting time [yr] </help>
+</parameter>
+<parameter key ="final_time" type="double" default="5">
+     <section name="timestepping" />
+     <help> final time to stop the simulation [yr] </help>
+</parameter>
+<parameter key ="time_step" type="double" default="0.5">
+     <section name="timestepping" />
+     <help> length of time steps [yr] </help>
+</parameter>
+<parameter key ="time_adapt" type="double" default="0">
+     <section name="timestepping" />
+     <help> use cfl condition to define time step ? (0 or 1)  </help>
+</parameter>
+<parameter key ="cfl_coefficient" type="double" default="0.5">
+     <section name="timestepping" />
+     <help> coefficient applied to cfl condition </help>
+</parameter>
+
+
+<!-- initialization -->
+<frame key="1" label="Initial field values">
+<section name="initialization" />
+<parameter key ="vx" type="double" default="NaN">
+     <section name="initialization" />
+     <help> x component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vy" type="double" default="NaN">
+     <section name="initialization" />
+     <help> y component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vz" type="double" default="NaN">
+     <section name="initialization" />
+     <help> z component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vel" type="double" default="NaN">
+     <section name="initialization" />
+     <help> velocity norm [m/yr] </help>
+</parameter>
+<parameter key ="pressure" type="double" default="NaN">
+     <section name="initialization" />
+     <help> pressure field [Pa] </help>
+</parameter>
+<parameter key ="temperature" type="double" default="NaN">
+     <section name="initialization" />
+     <help> fraction of water in the ice </help>
+</parameter>
+<parameter key ="waterfraction" type="double" default="NaN">
+     <section name="initialization" />
+     <help> ice thickness [m] </help>
+</parameter>
+<parameter key ="sediment_head" type="double" default="NaN">
+     <section name="initialization" />
+     <help> sediment water head of subglacial system [m] </help>
+</parameter>
+<parameter key ="epl_head" type="double" default="NaN">
+     <section name="initialization" />
+     <help> epl water head of subglacial system [m] </help>
+</parameter>
+<parameter key ="watercolumn" type="double" default="NaN">
+     <section name="initialization" />
+     <help> thickness of subglacial water [m] </help>
+</parameter></frame>
+
+
+<!-- rifts -->
+<parameter key ="riftstruct" type="double" default="NaN">
+     <section name="rifts" />
+     <help> structure containing all rift information (vertices coordinates, segments, type of melange, ...) </help>
+</parameter>
+<parameter key ="riftproperties" type="double" default="NaN">
+     <section name="rifts" />
+     <help> N/A </help>
+</parameter>
+
+
+<!-- Debug -->
+<parameter key ="valgrind" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> use Valgrind to debug (0 or 1) </help>
+</parameter>
+<parameter key ="gprof" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> use gnu-profiler to find out where the time is spent </help>
+</parameter>
+<parameter key ="profiling" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> enables profiling (memory, flops, time) </help>
+</parameter>
+
+<!-- verbose -->
+<parameter key ="mprocessor" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="module" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="solution" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="solver" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="convergence" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="control" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="qmu" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="autodiff" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+
+<!-- settings -->
+<parameter key ="results_on_nodes" type="double" default="0">
+     <section name="settings" />
+     <help> results are output for all the nodes of each element </help>
+</parameter>
+<parameter key ="io_gather" type="double" default="1">
+     <section name="settings" />
+     <help> I/O gathering strategy for result outputs (default 1) </help>
+</parameter>
+<parameter key ="lowmem" type="double" default="0">
+     <section name="settings" />
+     <help> is the memory limited ? (0 or 1) </help>
+</parameter>
+<parameter key ="output_frequency" type="double" default="1">
+     <section name="settings" />
+     <help> frequency at which results are saved in all solutions with multiple time_steps </help>
+</parameter>
+<parameter key ="waitonlock" type="double" default="Inf">
+     <section name="settings" />
+     <help> maximum number of minutes to wait for batch results (NaN to deactivate) </help>
+</parameter>
+<parameter key ="upload_server" type="char" default="N/A">
+     <section name="settings" />
+     <help> server hostname where model should be uploaded </help>
+</parameter>
+<parameter key ="upload_path" type="char" default="N/A">
+     <section name="settings" />
+     <help> path on server where model should be uploaded </help>
+</parameter>
+<parameter key ="upload_login" type="char" default="N/A">
+     <section name="settings" />
+     <help> server login </help>
+</parameter>
+<parameter key ="upload_port" type="double" default="0">
+     <section name="settings" />
+     <help> port login (default is 0) </help>
+</parameter>
+<parameter key ="upload_filename" type="char" default="N/A">
+     <section name="settings" />
+     <help> unique id generated when uploading the file to server </help>
+</parameter>
+
+<!-- generic -->
+<parameter key ="name" type="char" default="'XPS'">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="login" type="char" default="N/A">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="np" type="double" default="1">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="port" type="double" default="0">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="codepath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/bin">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="executionpath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/execution">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="etcpath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/etc">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrind" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/install/bin/valgrind">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrindlib" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/install/lib/libmpidebug.so">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrindsup" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/issm.supp">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="verbose" type="double" default="1">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+
+<!-- balancethickness -->
+<parameter key ="spcthickness" type="double" default="N/A">
+     <section name="balancethickness" />
+     <help> thickness constraints (NaN means no constraint) [m] </help>
+</parameter>
+<parameter key ="thickening_rate" type="double" default="N/A">
+     <section name="balancethickness" />
+     <help> ice thickening rate used in the mass conservation (dh/dt) [m/yr] </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="1">
+     <section name="balancethickness" />
+     <help> 0: None, 1: SU, 2: SSAs artificial diffusivity, 3:DG </help>
+</parameter>
+
+<!-- StressBalance solution parameters: -->
+<frame key="1" label="Convergence criteria">
+<section name="stressbalance" />
+<parameter key ="restol" type="double" default="0.0001">
+     <section name="stressbalance" />
+     <help> mechanical equilibrium residual convergence criterion </help>
+</parameter>
+<parameter key ="reltol" type="double" default="0.01">
+     <section name="stressbalance" />
+     <help> velocity relative convergence criterion, NaN: not applied </help>
+</parameter>
+<parameter key ="abstol" type="double" default="10">
+     <section name="stressbalance" />
+     <help> velocity absolute convergence criterion, NaN: not applied </help>
+</parameter>
+<parameter key ="isnewton" type="double" default="0">
+     <section name="stressbalance" />
+     <help> 0: Picards fixed point, 1: Newtons method, 2: hybrid </help>
+</parameter>
+<parameter key ="maxiter" type="double" default="100">
+     <section name="stressbalance" />
+     <help> maximum number of nonlinear iterations </help>
+</parameter>
+<parameter key ="viscosity_overshoot" type="double" default="0">
+     <section name="stressbalance" />
+     <help> over-shooting constant new=new+C*(new-old) </help>
+</parameter>
+</frame>
+<frame key="2" label="Boundary conditions">
+<section name="stressbalance" />
+<parameter key ="spcvx" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> x-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+<parameter key ="spcvy" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> y-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+<parameter key ="spcvz" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> z-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+</frame>
+<frame key="3" label="Rift options">
+<section name="stressbalance" />
+<parameter key ="rift_penalty_threshold" type="double" default="0">
+     <section name="stressbalance" />
+     <help> threshold for instability of mechanical constraints </help>
+</parameter>
+<parameter key ="rift_penalty_lock" type="double" default="10">
+     <section name="stressbalance" />
+     <help> number of iterations before rift penalties are locked </help>
+</parameter>
+</frame>
+<frame key="4" label="Other">
+<section name="stressbalance" />
+<parameter key ="shelf_dampening" type="double" default="0">
+     <section name="stressbalance" />
+     <help> use dampening for floating ice ? Only for FS model </help>
+</parameter>
+<parameter key ="FSreconditioning" type="double" default="10000000000000">
+     <section name="stressbalance" />
+     <help> multiplier for incompressibility equation. Only for FS model </help>
+</parameter>
+<parameter key ="referential" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> local referential </help>
+</parameter>
+<parameter key ="loadingforce" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> loading force applied on each point [N/m^3] </help>
+</parameter>
+<parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="stressbalance" />
+     <help> additional outputs requested </help>
+</parameter>
+</frame>
+
+
+<!-- groundingline -->
+<frame key="1" label="Grounding line migration parameters">
+<section name="groundingline" />
+<parameter key ="migration" type="char" default="'None'">
+     <section name="groundingline" />
+     <help> type of grounding line migration: "SoftMigration","AgressiveMigration" or "None" </help>
+</parameter>
+<parameter key ="melting_rate" type="double" default="0">
+     <section name="groundingline" />
+     <help> melting rate applied when previously grounded parts start floating [m/yr] </help>
+</parameter></frame>
+
+
+<!-- Hydrology -->
+<frame key="1" label="Hydrologyshreve solution parameters">
+<section name="hydrologyshreve" />
+<parameter key ="spcwatercolumn" type="double" default="N/A">
+     <section name="hydrologyshreve" />
+     <help> water thickness constraints (NaN means no constraint) [m] </help>
+</parameter>
+<parameter key ="n" type="double" default="0.02">
+     <section name="hydrologyshreve" />
+     <help> Manning roughness coefficient </help>
+</parameter>
+<parameter key ="CR" type="double" default="0.01">
+     <section name="hydrologyshreve" />
+     <help> tortuosity parameter </help>
+</parameter>
+<parameter key ="p" type="double" default="2">
+     <section name="hydrologyshreve" />
+     <help> dimensionless exponent in Manning velocity formula </help>
+</parameter>
+<parameter key ="q" type="double" default="1">
+     <section name="hydrologyshreve" />
+     <help> dimensionless exponent in Manning velocity formula </help>
+</parameter>
+<parameter key ="kn" type="double" default="0">
+     <section name="hydrologyshreve" />
+     <help> parameter in effective pressure formula </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="1">
+     <section name="hydrologyshreve" />
+     <help> artificial diffusivity (default is 1). can be more than 1 to increase diffusivity. </help>
+</parameter>
+</frame>
+<!-- masstransport -->
+<frame key="1" label="Masstransport solution parameters">
+<section name="masstransport" />
+  <parameter key ="spcthickness" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> thickness constraints (NaN means no constraint) [m] </help>
+  </parameter>
+  <parameter key ="calvingrate" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> calving rate at given location [m/a] </help>
+  </parameter>
+  <parameter key ="isfreesurface" type="double" default="0">
+     <section name="masstransport" />
+     <help> do we use free surfaces (FS only) are mass conservation </help>
+  </parameter>
+  <parameter key ="min_thickness" type="double" default="1">
+     <section name="masstransport" />
+     <help> minimum ice thickness allowed [m] </help>
+  </parameter>
+  <parameter key ="hydrostatic_adjustment" type="char" default="'Absolute'">
+     <section name="masstransport" />
+     <help> adjustment of ice shelves surface and bed elevations: 'Incremental' or 'Absolute'  </help>
+  </parameter>
+  <parameter key ="stabilization" type="double" default="1">
+     <section name="masstransport" />
+     <help> 0: no, 1:  artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin </help>
+  </parameter>
+</frame>
+<frame key="2" label="Penalty options">
+<section name="masstransport" />
+  <parameter key ="vertex_pairing" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> offset used by penalties: penalty = Kmax*10^offset </help>
+  </parameter>
+  <parameter key ="penalty_factor" type="double" default="3">
+     <section name="masstransport" />
+     <help> pairs of vertices that are penalized </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="masstransport" />
+     <help> additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- thermal -->
+<frame key="1" label="Thermal solution parameters">
+<section name="thermal" />
+  <parameter key ="spctemperature" type="double" default="N/A">
+     <section name="thermal" />
+     <help> temperature constraints (NaN means no constraint) [K] </help>
+  </parameter>
+  <parameter key ="penalty_threshold" type="double" default="0">
+     <section name="thermal" />
+     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>
+  </parameter>
+  <parameter key ="stabilization" type="double" default="1">
+     <section name="thermal" />
+     <help> maximum number of non linear iterations </help>
+  </parameter>
+  <parameter key ="maxiter" type="double" default="100">
+     <section name="thermal" />
+     <help> stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>
+  </parameter>
+  <parameter key ="penalty_lock" type="double" default="0">
+     <section name="thermal" />
+     <help> threshold to declare convergence of thermal solution (default is 0)  </help>
+  </parameter>
+  <parameter key ="penalty_factor" type="double" default="3">
+     <section name="thermal" />
+     <help> scaling exponent (default is 3) </help>
+  </parameter>
+  <parameter key ="isenthalpy" type="double" default="0">
+     <section name="thermal" />
+     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>
+  </parameter>
+  <parameter key ="isdynamicbasalspc" type="double" default="0">
+     <section name="thermal" />
+     <help> enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)  </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="thermal" />
+     <help> additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- steadystate -->
+<frame key="1" label="steadystate solution parameters">
+<section name="steadystate" />
+  <parameter key ="reltol" type="double" default="0.01">
+     <section name="steadystate" />
+     <help> relative tolerance criterion [K] </help>
+  </parameter>
+  <parameter key ="maxiter" type="double" default="100">
+     <section name="steadystate" />
+     <help> maximum number of iterations </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="steadystate" />
+     <help> additional requested outputs </help>
+  </parameter>
+</frame>
+<!-- transient -->
+<frame key="1" label="transient solution parameters">
+<section name="transient" />
+  <parameter key ="ismasstransport" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a masstransport solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isstressbalance" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a stressbalance solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isthermal" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a thermal solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isgroundingline" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether a groundingline migration is used in the transient </help>
+  </parameter>
+  <parameter key ="isgia" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether a postglacial rebound model is used in the transient </help>
+  </parameter>
+  <parameter key ="isdamage" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether damage evolution is used in the transient </help>
+  </parameter>
+  <parameter key ="islevelset" type="double" default="0">
+     <section name="transient" />
+     <help> LEVEL SET DESCRIPTION...  </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="transient" />
+     <help> list of additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- gia -->
+<frame key="1" label="gia parameters">
+<section name="gia" />
+  <parameter key ="mantle_viscosity" type="double" default="N/A">
+     <section name="gia" />
+     <help> mantle viscosity[Pa s] </help>
+  </parameter>
+  <parameter key ="lithosphere_thickness" type="double" default="N/A">
+     <section name="gia" />
+     <help> lithosphere thickness (km) </help>
+  </parameter>
+  <parameter key ="cross_section_shape" type="double" default="1">
+     <section name="gia" />
+     <help> 1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore </help>
+  </parameter>
+</frame>
+<!-- autodiff -->
+<frame key="1" label="automatic differentiation parameters">
+<section name="autodiff" />
+  <parameter key ="isautodiff" type="logical" optional="false">
+     <section name="autodiff" />
+         <option value="false" type="string" default="true"></option>
+     <help> indicates if the automatic differentiation is activated </help>
+  </parameter>
+  <parameter key ="dependents" type="cell" default="(0x0)">
+     <section name="autodiff" />
+     <help> list of dependent variables </help>
+  </parameter>
+  <parameter key ="independents" type="cell" default="(0x0)">
+     <section name="autodiff" />
+     <help> list of independent variables </help>
+  </parameter>
+  <parameter key ="driver" type="char" default="'fos_forward'">
+     <section name="autodiff" />
+     <help> ADOLC driver ('fos_forward' or 'fov_forward') </help>
+  </parameter>
+  <parameter key ="obufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of operations per buffer (==OBUFSIZE in usrparms.h)  </help>
+  </parameter>
+  <parameter key ="lbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of locations per buffer (==LBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="cbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of values per buffer (==CBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="tbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of taylors per buffer (&amp;lt;=TBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="gcTriggerRatio" type="double" default="2">
+     <section name="autodiff" />
+     <help> free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio </help>
+  </parameter>
+  <parameter key ="gcTriggerRatio" type="double" default="2">
+     <section name="autodiff" />
+     <help> free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize </help>
+  </parameter>
+</frame>
+<!-- flaim -->
+<frame key="1" label="Input:">
+<section name="flaim" />
+  <parameter key ="targets" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml output targets file </help>
+  </parameter>
+  <parameter key ="tracks" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml input tracks file </help>
+  </parameter>
+  <parameter key ="flightreqs" type="struct" default="N/A">
+     <section name="flaim" />
+     <help> structure of kml flight requirements (not used yet) </help>
+  </parameter>
+  <parameter key ="criterion" type="double" default="N/A">
+     <section name="flaim" />
+     <help> element or nodal criterion for flight path evaluation (metric) </help>
+  </parameter>
+</frame>
+<frame key="2" label="Arguments:">
+<section name="flaim" />
+  <parameter key ="gridsatequator" type="double" default="200000">
+     <section name="flaim" />
+     <help> number of grids at equator (determines resolution) </help>
+  </parameter>
+  <parameter key ="usevalueordering" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="true" type="string" default="true"></option>
+     <help> flag to consider target values for flight path evaluation </help>
+  </parameter>
+  <parameter key ="split_antimeridian" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="true" type="string" default="true"></option>
+     <help> flag to split polygons on the antimeridian </help>
+  </parameter>
+</frame>
+<frame key="3" label="Optimization:">
+<section name="flaim" />
+  <parameter key ="path_optimize" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="false" type="string" default="true"></option>
+     <help> optimize? (default false) </help>
+  </parameter>
+  <parameter key ="opt_ndir" type="double" default="1">
+     <section name="flaim" />
+     <help> number of directions to test when moving a point.  If this value = 1, a random direction is tested. A value > 1 results in directions equally spaced from [0, 2*PI] being tested. For example, 4 would result in directions [0, PI/2, PI, 3PI/2] </help>
+  </parameter>
+  <parameter key ="opt_dist" type="double" default="25">
+     <section name="flaim" />
+     <help> specifies the distance in km (default 25) to move a randomly selected path point on each iteration </help>
+  </parameter>
+  <parameter key ="opt_niter" type="double" default="30000">
+     <section name="flaim" />
+     <help> number of iterations (default 30,000) to run for flightplan optimization, i.e. the number of times to randomly select a point and move it. </help>
+  </parameter>
+</frame>
+<frame key="4" label="Output:">
+<section name="flaim" />
+  <parameter key ="solution" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml solution file </help>
+  </parameter>
+  <parameter key ="quality" type="double" default="0">
+     <section name="flaim" />
+     <help> quality of kml solution </help>
+  </parameter>
+</frame>
+<!-- inversion -->
+<frame key="1" label="inversion parameters">
+<section name="inversion" />
+  <parameter key ="iscontrol" type="double" default="0">
+     <section name="inversion" />
+     <help> is inversion activated? </help>
+  </parameter>
+  <parameter key ="incomplete_adjoint" type="double" default="1">
+     <section name="inversion" />
+     <help> 1: linear viscosity, 0: non-linear viscosity </help>
+  </parameter>
+  <parameter key ="control_parameters" type="cell" default="{'FrictionCoefficient'}">
+     <section name="inversion" />
+     <help> ex: {'FrictionCoefficient'}, or {'MaterialsRheologyBbar'} </help>
+  </parameter>
+  <parameter key ="nsteps" type="double" default="20">
+     <section name="inversion" />
+     <help> number of optimization searches </help>
+  </parameter>
+  <parameter key ="cost_functions" type="double" default="101">
+     <section name="inversion" />
+     <help> indicate the type of response for each optimization step  </help>
+  </parameter>
+  <parameter key ="cost_functions_coefficients" type="double" default="N/A">
+     <section name="inversion" />
+     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>
+  </parameter>
+  <parameter key ="cost_function_threshold" type="double" default="N/A">
+     <section name="inversion" />
+     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>
+  </parameter>
+  <parameter key ="maxiter_per_step" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> maximum iterations during each optimization step  </help>
+  </parameter>
+  <parameter key ="gradient_scaling" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> scaling factor on gradient direction during optimization, for each optimization step </help>
+  </parameter>
+  <parameter key ="step_threshold" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> decrease threshold for misfit, default is 30% </help>
+  </parameter>
+  <parameter key ="min_parameters" type="double" default="N/A">
+     <section name="inversion" />
+     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>
+  </parameter>
+  <parameter key ="max_parameters" type="double" default="N/A">
+     <section name="inversion" />
+     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>
+  </parameter>
+  <parameter key ="vx_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity x component [m/yr] </help>
+  </parameter>
+  <parameter key ="vy_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity y component [m/yr]  </help>
+  </parameter>
+  <parameter key ="vel_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity magnitude [m/yr] </help>
+  </parameter>
+  <parameter key ="thickness_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed thickness [m]) </help>
+  </parameter>
+</frame>
+<frame key="2" label="Available cost functions">
+<section name="inversion" />
+  <parameter key ="SurfaceAbsVelMisfit" type="string" default="101">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceRelVelMisfit" type="string" default="102">
+     <section name="inversion" />
+     <help>   </help>
+  </parameter>
+  <parameter key ="SurfaceLogVelMisfit" type="string" default="103">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceLogVxVyMisfit" type="string" default="104">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceAverageVelMisfit" type="string" default="105">
+     <section name="inversion" />
+     <help>   </help>
+  </parameter>
+  <parameter key ="ThicknessAbsMisfit" type="string" default="106">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="DragCoefficientAbsGradient" type="string" default="107">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="RheologyBbarAbsGradient" type="string" default="108">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="ThicknessAbsGradient" type="string" default="109">
+     <section name="inversion" />
+     <help> </help>
+  </parameter>
+</frame>
+<!-- qmu -->
+<frame key="1" label="qmu parameters">
+<section name="qmu" />
+  <parameter key ="isdakota" type="double" default="0">
+     <section name="qmu" />
+     <help> is qmu analysis activated? </help>
+  </parameter>
+  <parameter key ="variables" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (arrays of each variable class) </help>
+  </parameter>
+  <parameter key ="responses" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (arrays of each response class) </help>
+  </parameter>
+  <parameter key ="numberofresponses" type="double" default="0">
+     <section name="qmu" />
+     <help> number of responses </help>
+  </parameter>
+  <parameter key ="params" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (array of method-independent parameters)  </help>
+  </parameter>
+  <parameter key ="results" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (information from dakota files) </help>
+  </parameter>
+  <parameter key ="partition" type="double" default="N/A">
+     <section name="qmu" />
+     <help> user provided mesh partitioning, defaults to metis if not specified </help>
+  </parameter>
+  <parameter key ="numberofpartitions" type="double" default="0">
+     <section name="qmu" />
+     <help> number of partitions for semi-discrete qmu  </help>
+  </parameter>
+  <parameter key ="variabledescriptors" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="responsedescriptors" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>
+  </parameter>
+  <parameter key ="method" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> array of dakota_method class </help>
+  </parameter>
+  <parameter key ="mass_flux_profile_directory" type="double" default="N/A">
+     <section name="qmu" />
+     <help> directory for mass flux profiles </help>
+  </parameter>
+  <parameter key ="mass_flux_profiles" type="double" default="N/A">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="mass_flux_segments" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="adjacency" type="double" default="N/A">
+     <section name="qmu" />
+     <help> additional outputs requested </help>
+  </parameter>
+  <parameter key ="vertex_weight" type="double" default="N/A">
+     <section name="qmu" />
+     <help> weight applied to each mesh vertex </help>
+  </parameter>
+</frame>
+<!-- outputdefinition -->
+<frame key="1" label="outputdefinition">
+<section name="outputdefinition" />
+  <parameter key ="definitions" type="cell" default="(0x0)">
+     <section name="outputdefinition" />
+     <help> list of potential outputs that can be requested, but which need additional data to be defined </help>
+  </parameter>
+</frame>
+<!-- miscellaneous -->
+<frame key="1" label="miscellaneous parameters">
+<section name="miscellaneous" />
+  <parameter key ="notes" type="char" default="N/A">
+     <section name="miscellaneous" />
+     <help> notes in a cell of strings </help>
+  </parameter>
+  <parameter key ="name" type="char" default="N/A">
+     <section name="miscellaneous" />
+     <help> model name </help>
+  </parameter>
+  <parameter key ="dummy" type="struct" default="N/A">
+     <section name="miscellaneous" />
+     <help> empty field to store some data </help>
+  </parameter>
+</frame>
+
+
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/icons/readme.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/icons/readme.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/build/resources/icons/readme.txt	(revision 18231)
@@ -0,0 +1,10 @@
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+This copyright and license notice covers the images in this directory.
+************************************************************************
+
+TITLE:	Crystal Project Icons
+AUTHOR:	Everaldo Coelho
+SITE:	http://www.everaldo.com
+CONTACT: everaldo@everaldo.com
+
+Copyright (c)  2006-2007  Everaldo Coelho.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/io.ini
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/io.ini	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/io.ini	(revision 18231)
@@ -0,0 +1,180 @@
+[General]
+PLUGINPATH	= ../../lib/plugins ;super
+BUFF_CHUNK_SIZE = 30
+BUFF_BEFORE	= 1.5
+
+[Input]
+COORDSYS	= CH1903
+TIME_ZONE	= 1
+; COORDSYS	= PROJ4
+; COORDPARAM	= 21781
+
+#reading ARC dem
+DEM		= ARC
+DEMFILE  	= ./input/surface-grids/Switzerland_1000m.asc
+
+#reading ARPS dem
+; DEM		= ARPS
+; DEMFILE 	= ./wgrt10r2_vw4.asc
+; ARPS_X 	= 653400
+; ARPS_Y 	= 112204
+
+#reading PGM image as dem
+; DEM		= PGM
+; DEMFILE	= ./Switzerland.pgm
+; PGM_XCOORD	= 479500.
+; PGM_YCOORD	= 73500.
+; PGM_CELLSIZE	= 1000.
+; PGM_MIN	= 193.
+; PGM_MAX	= 4204.
+
+; LANDUSE	= ARC
+; LANDUSEFILE	= ch_as97.asc
+
+#Alpine3D traditional inputs -> A3D plugin
+; METEO		= A3D
+; METEOPATH	= ./input/meteo
+
+#Borma
+; METEO		= BORMA
+; METEOPATH	= ./input/xml
+; NROFSTATIONS	= 1
+; STATION1	= 00.00.00.2
+
+#Snowpack input
+; METEO		= SNOWPACK
+; METEOPATH	= input
+; METAFILE	= IMIS_Extracted_Info.txt ;metadata for all stations
+; STATION1  	= MST96_RR.inp
+
+#SMET meteorological file format
+METEO		= SMET
+METEOPATH	= ./input/meteo
+STATION1	= FLU2.smet
+STATION2	= FIR2.smet
+STATION3	= FRA2.smet
+STATION4	= GLA2.smet
+STATION5	= ILI2.smet
+STATION6	= OTT2.smet
+STATION7	= TUJ3.smet
+
+#IMIS network database input -> IMIS plugin
+; METEO		= IMIS
+; DBNAME		= sdbo
+; DBUSER		= XXX
+; DBPASS		= XXX
+; NROFSTATIONS	= 4
+; STATION1	= MORN2
+; STATION2	= DAV3
+; STATION3	= KLO2
+; STATION4	= *SAM0
+
+#GEOtop traditional inputs -> GEOTOP plugin
+; METEO		 = GEOTOP
+; METEOPATH       = meteo/
+; METEOPREFIX     = _meteo
+
+#GSN direct input -> GSN plugin
+; METEO		= GSN
+; ENDPOINT	= http://montblanc.slf.ch:22001/services/A3DWebService
+; STATION1	= wan_sen14_2008
+; STATION2	= wan2
+
+[Output]
+COORDSYS	= CH1903
+TIME_ZONE 	= 1
+
+GRID2D		= ARC
+GRID2DPATH	= ./
+
+; GRID2D		= PNG
+; GRID2DPATH	= ./
+; PNG_MIN_SIZE	= 800x600
+; PNG_WORLD_FILE	= true
+; PNG_AUTOSCALE	= false
+; PNG_SCALING	= nearest
+
+METEO		= SMET
+METEOPATH	= ./
+
+[Filters]
+TA::filter1	= min_max
+TA::arg1	= 240 320
+
+RH::filter1	= min_max
+RH::arg1 	= 0.01 1.2
+RH::filter2	= min_max
+RH::arg2	= soft 0.05 1.0
+
+HNW::filter1	= min
+HNW::arg1	= -0.1
+HNW::filter2	= min
+HNW::arg2	= soft 0.
+
+ISWR::filter1	= min_max
+ISWR::arg1	= -10. 1500.
+ISWR::filter2	= min
+ISWR::arg2	= soft 0.
+
+RSWR::filter1	= min_max
+RSWR::arg1 	= -10 1500
+RSWR::filter2	= min
+RSWR::arg2	= soft 0
+
+#for TA between 240 and 320 K
+ILWR::filter1	= min_max
+ILWR::arg1	= 188 600
+ILWR::filter2	= min_max
+ILWR::arg2	= soft 200 400
+
+#we need to consider time with no snow -> TSS>0
+#min(TSS) in db since 1998: -50C
+TSS::filter1	= min_max
+TSS::arg1	= 200 320
+
+#idem
+TSG::filter1	= min_max
+TSG::arg1	= 200 320
+
+HS::filter1	= min
+HS::arg1	= soft 0.0
+HS::filter2	= rate
+HS::arg2	= 5.55e-5 ;0.20 m/h
+
+VW::filter1	= min_max
+VW::arg1	= -2 70
+VW::filter2	= min_max
+VW::arg2	= soft 0.2 50.0
+
+[Interpolations1D]
+WINDOW_SIZE	= 86400
+
+TA::resample	= linear
+
+RH::resample	= linear
+
+HS::resample	= linear
+
+VW::resample	= nearest_neighbour
+VW::args	= extrapolate
+
+HNW::resample	= linear
+
+[Interpolations2D]
+TA::algorithms	= IDW_LAPSE CST_LAPSE
+TA::cst_lapse	= -0.008
+TA::idw_lapse	= -0.008 soft
+
+RH::algorithms	= RH IDW_LAPSE CST
+
+HNW::algorithms	= IDW_LAPSE CST_LAPSE CST
+HNW::cst_lapse	= 0.0005 frac
+
+VW::algorithms	= IDW_LAPSE CST
+
+P::algorithms	= STD_PRESS
+
+ILWR::algorithms = CST_LAPSE
+ILWR::cst_lapse = -0.03125
+
+RSWR::algorithms = IDW CST
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/issm.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/issm.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/issm.xml	(revision 18231)
@@ -0,0 +1,1284 @@
+<inishell_config application="ISSM prototype">
+
+<!-- mesh -->
+<parameter key ="Dimension" type="alternative" optional="false">
+     <section name="mesh" />
+     <option value="0" type="string" default="true">
+        <help> dimension is 0 </help>
+     </option>
+     <option value="3" type="string">
+        <help> dimension is 3 </help>
+       <!-- Elements and vertices of the original 2d mesh -->
+          <parameter key ="x2d" type="double" default="N/A">
+              <help> vertices x coordinate [m] </help>
+          </parameter>
+          <parameter key ="y2d" type="double" default="N/A">
+              <help> vertices y coordinate [m] </help>
+          </parameter>
+          <parameter key ="elements2d" type="double" default="N/A">
+              <help> vertex indices of the mesh elements </help>
+          </parameter>
+          <parameter key ="numberofvertices2d" type="double" default="0">
+              <help> number of vertices </help>
+          </parameter>
+          <parameter key ="numberofelements2d" type="double" default="0">
+              <help> number of elements </help>
+          </parameter>
+     </option>
+     <help> select a mesh dimension 0(default) or 3 </help>
+</parameter>
+<frame key="1" label="Elements and vertices">
+<section name="mesh" />
+  <parameter key ="numberofelements" type="double" default="0">
+     <section name="mesh" />
+     <help> number of elements </help>
+  </parameter>
+  <parameter key ="numberofvertices" type="double" default="0">
+     <section name="mesh" />
+     <help> number of verticies </help>
+  </parameter>
+  <parameter key ="elements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertex indices of the mesh elements </help>
+  </parameter>
+  <parameter key ="x" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices x coordinate [m] </help>
+  </parameter>
+  <parameter key ="y" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices y coordinate [m] </help>
+  </parameter>
+  <parameter key ="z" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices z coordinate [m] </help>
+  </parameter>
+  <parameter key ="edges" type="double" default="N/A">
+     <section name="mesh" />
+     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>
+  </parameter>
+  <parameter key ="numberofedges" type="double" default="0">
+     <section name="mesh" />
+     <help> number of edges of the 2d mesh </help>
+  </parameter>
+</frame>
+<frame key="2" label="Properties">
+<section name="mesh" />
+  <parameter key ="selected dimension" type="double" default="0">
+     <section name="mesh" />
+     <help> mesh dimension </help>
+  </parameter>
+  <parameter key ="numberoflayers" type="double" default="0">
+     <section name="mesh" />
+     <help> number of extrusion layers </help>
+  </parameter>
+  <parameter key ="vertexonbed" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower vertices flags list </help>
+  </parameter>
+  <parameter key ="elementonbed" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower elements flags list </help>
+  </parameter>
+  <parameter key ="vertexonsurface" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper vertices flags list </help>
+  </parameter>
+  <parameter key ="elementonsurface" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper element flag list </help>
+  </parameter>
+  <parameter key ="uppervertex" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper vertex list (NaN for vertex on the upper surface) </help>
+  </parameter>
+  <parameter key ="upperelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> upper element list (NaN for element on the upper layer) </help>
+  </parameter>
+  <parameter key ="lowervertex" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower vertex list (NaN for vertex on the lower surface) </help>
+  </parameter>
+  <parameter key ="lowerelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> lower element list (NaN for element on the lower layer </help>
+  </parameter>
+  <parameter key ="vertexonboundary" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices on the boundary of the domain flag list </help>
+  </parameter>
+  <parameter key ="segments" type="double" default="N/A">
+     <section name="mesh" />
+     <help> edges on domain boundary (vertex1 vertex2 element) </help>
+  </parameter>
+  <parameter key ="segmentmarkers" type="double" default="N/A">
+     <section name="mesh" />
+     <help> number associated to each segment </help>
+  </parameter>
+  <parameter key ="vertexconnectivity" type="double" default="N/A">
+     <section name="mesh" />
+     <help> list of vertices connected to vertex_i </help>
+  </parameter>
+  <parameter key ="elementconnectivity" type="double" default="N/A">
+     <section name="mesh" />
+     <help> list of vertices connected to element_i </help>
+  </parameter>
+  <parameter key ="average_vertex_connectivity" type="double" default="25">
+     <section name="mesh" />
+     <help> average number of vertices connected to one vertex </help>
+  </parameter>
+</frame>
+<frame key="3" label="Extracted Model">
+<section name="mesh" />
+  <parameter key ="extractedvertices" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices extracted from the model </help>
+  </parameter>
+  <parameter key ="extractedelements" type="double" default="N/A">
+     <section name="mesh" />
+     <help> elements extracted from the model </help>
+  </parameter>
+</frame>
+<frame key="4" label="Projection">
+<section name="mesh" />
+  <parameter key ="lat" type="double" default="N/A">
+     <section name="mesh" />
+     <help> vertices latitude [degrees] </help>
+  </parameter>
+  <parameter key ="long" type="double" default="N/A">
+     <section name="mesh" />
+     <help> verticies longitude [degrees] </help>
+  </parameter>
+  <parameter key ="hemisphere" type="double" default="N/A">
+     <section name="mesh" />
+     <help> Indicate hemisphere 'n' or 's' </help>
+  </parameter></frame>
+
+
+<!-- mask -->
+<parameter key ="groundedice_levelset" type="double" default="NaN">
+     <section name="mask" />
+     <help> is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if &amp;lt; 0 </help>
+</parameter>
+<parameter key ="ice_levelset" type="double" default="NaN">
+     <section name="mask" />
+     <help> presence of ice if > 0, icefront position if = 0, no ice if &amp;lt; 0 </help>
+</parameter>
+
+<!-- geometry -->
+<frame key="1" label="Geometry parameters">
+<section name="geometry" />
+<parameter key ="surface" type="path" optional="false">
+     <section name="geometry" />
+     <help> surface elevation [m] </help>
+</parameter>
+<parameter key ="thickness" type="path" optional="false">
+     <section name="geometry" />
+     <help> ice thickness [m] </help>
+</parameter>
+<parameter key ="bed" type="path" optional="false">
+     <section name="geometry" />
+     <help> bed elevation [m] </help>
+</parameter>
+<parameter key ="bathymetry" type="double" default="N/A">
+     <section name="geometry" />
+     <help> bathymetry elevation [m] </help>
+</parameter>
+<parameter key ="hydrostatic_ratio" type="double" default="N/A">
+     <section name="geometry" />
+     <help> coefficient for ice shelves; thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro </help>
+</parameter></frame>
+
+
+<!-- constants -->
+<parameter key ="g" type="double" default="9.81">
+     <section name="constants" />
+     <help> gravitational acceleration [m/s^2] </help>
+</parameter>
+<parameter key ="yts" type="double" default="31536000">
+     <section name="constants" />
+     <help> number of seconds in a year [s/yr] </help>
+</parameter>
+<parameter key ="referencetemperature" type="double" default="223.15">
+     <section name="constants" />
+     <help> reference temperature used in the enthalpy model [K] </help>
+</parameter>
+
+<!-- surfaceforcings(SMB) -->
+<parameter key ="mass_balance" type="double" default="NaN">
+     <section name="surfaceforcings(SMB)" />
+     <help> surface mass balance [m/yr ice eq] </help>
+</parameter>
+
+<!-- basalforcings -->
+<parameter key ="melting_rate" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> basal melting rate (positive if melting) [m/yr] </help>
+</parameter>
+<parameter key ="melting_rate_correction" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> additional melting applied to compensate for dh/dt [m/yr] </help>
+</parameter>
+<parameter key ="geothermalflux" type="double" default="NaN">
+     <section name="basalforcings" />
+     <help> geothermal heat flux [W/m^2] </help>
+</parameter>
+
+<!-- materials -->
+<parameter key ="rho_ice" type="double" default="917">
+     <section name="materials" />
+     <help> ice density [kg/m^3] </help>
+</parameter>
+<parameter key ="rho_water" type="double" default="1023">
+     <section name="materials" />
+     <help> ocean water density [kg/m^3] </help>
+</parameter>
+<parameter key ="rho_freshwater" type="double" default="1000">
+     <section name="materials" />
+     <help> fresh water density [kg/m^3] </help>
+</parameter>
+<parameter key ="mu_water" type="double" default="0.001787">
+     <section name="materials" />
+     <help> water viscosity [N s/m^2] </help>
+</parameter>
+<parameter key ="heatcapacity" type="double" default="2093">
+     <section name="materials" />
+     <help> heat capacity [J/kg/K] </help>
+</parameter>
+<parameter key ="latentheat" type="double" default="334000">
+     <section name="materials" />
+     <help> latent heat of fusion [J/kg] </help>
+</parameter>
+<parameter key ="thermalconductivity" type="double" default="2.4">
+     <section name="materials" />
+     <help> ice thermal conductivity [W/m/K] </help>
+</parameter>
+<parameter key ="temperateiceconductivity" type="double" default="0.24">
+     <section name="materials" />
+     <help> temperate ice thermal conductivity [W/m/K] </help>
+</parameter>
+<parameter key ="meltingpoint" type="double" default="273.15">
+     <section name="materials" />
+     <help> melting point of ice at 1atm in K </help>
+</parameter>
+<parameter key ="beta" type="double" default="9.8e-08">
+     <section name="materials" />
+     <help> rate of change of melting point with pressure [K/Pa] </help>
+</parameter>
+<parameter key ="mixed_layer_capacity" type="double" default="3974">
+     <section name="materials" />
+     <help> mixed layer capacity [W/kg/K] </help>
+</parameter>
+<parameter key ="thermal_exchange_velocity" type="double" default="0.0001">
+     <section name="materials" />
+     <help> thermal exchange velocity [m/s] </help>
+</parameter>
+<parameter key ="rheology_B" type="double" default="N/A">
+     <section name="materials" />
+     <help> flow law parameter [Pa/s^(1/n)] </help>
+</parameter>
+<parameter key ="rheology_n" type="double" default="N/A">
+     <section name="materials" />
+     <help> Glens flow law exponent </help>
+</parameter>
+<parameter key ="rheology_law" type="char" default="'Paterson'">
+     <section name="materials" />
+     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>
+</parameter>
+<parameter key ="lithosphere_shear_modulus" type="double" default="67000000000">
+     <section name="materials" />
+     <help> Lithosphere shear modulus [Pa] </help>
+</parameter>
+<parameter key ="lithosphere_density" type="double" default="3.32">
+     <section name="materials" />
+     <help> Lithosphere density [g/cm^-3] </help>
+</parameter>
+<parameter key ="mantle_shear_modulus" type="double" default="145000000000">
+     <section name="materials" />
+     <help> Mantle shear modulus [Pa] </help>
+</parameter>
+<parameter key ="mantle_density" type="double" default="3.34">
+     <section name="materials" />
+     <help> Mantle density [g/cm^-3] </help>
+</parameter>
+
+
+<!-- damage -->
+<!-- Note: this class depends on different input of law -->
+<parameter key ="law" type="alternative" optional="false">
+	<section name="damage" />
+	<option value="undamage" type="string" default="true">
+		<help> law = undamage </help>
+	</option>
+	<option value="pralong" type="string" default="false">
+		<help> law = pralong </help>
+		<parameter key ="stress_threshold" type="double" default="0">
+			<help> damage stress threshold [Pa] </help>
+		</parameter>
+		<parameter key ="c1" type="double" default="0">
+			<help> damage parameter 1 </help>
+		</parameter>
+		<parameter key ="c2" type="double" default="0">
+			<help> damage parameter 2 </help>
+		</parameter>
+		<parameter key ="c3" type="double" default="0">
+			<help> damage parameter 3 [W/m^2] </help>
+		</parameter>
+		<parameter key ="c4" type="double" default="0">
+			<help> damage parameter 4 </help>
+		</parameter>
+		<parameter key ="healing" type="double" default="0">
+			<help> damage healing parameter 1 </help>
+		</parameter>
+		<parameter key ="equiv_stress" type="double" default="0">
+			<help> 0: von Mises </help>
+		</parameter>
+		<parameter key ="requested_outputs" type="cell" default="{'default'}">
+			<help> additional outputs requested </help>
+		</parameter>
+	</option>
+	<help> damage law (string) from {"undamaged","pralong"} </help>
+</parameter>
+<parameter key ="D" type="double" default="0">
+     <section name="damage" />
+     <help> damage tensor (scalar) </help>
+</parameter>
+<parameter key ="law" type="char" default="undamaged">
+     <section name="damage" />
+     <help> damage law (string) from {"undamaged","pralong"} </help>
+</parameter>
+<parameter key ="spcdamage" type="double" default="NaN">
+     <section name="damage" />
+     <help> damage constraints (NaN means no constraint) </help>
+</parameter>
+<parameter key ="max_damage" type="double" default="0.99999">
+     <section name="damage" />
+     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="2">
+     <section name="damage" />
+     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>
+</parameter>
+<parameter key ="maxiter" type="double" default="100">
+     <section name="damage" />
+     <help> maximum number of non linear iterations </help>
+</parameter>
+<parameter key ="penalty_lock" type="double" default="0">
+     <section name="damage" />
+     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>
+</parameter>
+<parameter key ="penalty_threshold" type="double" default="0">
+     <section name="damage" />
+     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>
+</parameter>
+<parameter key ="penalty_factor" type="double" default="3">
+     <section name="damage" />
+     <help> scaling exponent (default is 3) </help>
+</parameter>
+
+
+<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->
+<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">
+<section name="friction" />
+<parameter key ="coefficient" type="double" default="N/A">
+     <section name="friction" />
+     <help> friction coefficient [SI] </help>
+</parameter>
+<parameter key ="p" type="double" default="N/A">
+     <section name="friction" />
+     <help> p exponent </help>
+</parameter>
+<parameter key ="q" type="double" default="N/A">
+     <section name="friction" />
+     <help> q exponent </help>
+</parameter></frame>
+
+
+<!-- flowequation -->
+<frame key="1" label="Flow equation parameters">
+<section name="flowequation" />
+<parameter key ="isSIA" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Shallow Ice Approximation (SIA) used ? </help>
+</parameter>
+<parameter key ="isSSA" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>
+</parameter>
+<parameter key ="isL1L2" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the L1L2 approximation used ? </help>
+</parameter>
+<parameter key ="isHO" type="double" default="0">
+     <section name="flowequation" />
+     <help> is the Higher-Order (HO) approximation used ? </help>
+</parameter>
+<parameter key ="isFS" type="double" default="0">
+     <section name="flowequation" />
+     <help> are the Full-FS (FS) equations used ? </help>
+</parameter>
+<parameter key ="fe_SSA" type="char" default="'P1'">
+     <section name="flowequation" />
+     <help> Finite Element for SSA  "P1", "P1bubble" "P1bubblecondensed" "P2" </help>
+</parameter>
+<parameter key ="fe_HO" type="char" default="'P1'">
+     <section name="flowequation" />
+     <help> Finite Element for HO   "P1" "P1bubble" "P1bubblecondensed" "P1xP2" "P2xP1" "P2" </help>
+</parameter>
+<parameter key ="fe_FS" type="char" default="'MINIcondensed'">
+     <section name="flowequation" />
+     <help> Finite Element for FS   "P1P1" (debugging only) "P1P1GLS" "MINIcondensed" "MINI" "TaylorHood" </help>
+</parameter>
+<parameter key ="vertex_equation" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> flow equation for each vertex </help>
+</parameter>
+<parameter key ="element_equation" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> flow equation for each element </help>
+</parameter>
+<parameter key ="borderSSA" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on SSAs border (for tiling) </help>
+</parameter>
+<parameter key ="borderHO" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on HOs border (for tiling) </help>
+</parameter>
+<parameter key ="borderFS" type="double" default="N/A">
+     <section name="flowequation" />
+     <help> vertices on FS border (for tiling) </help>
+</parameter></frame>
+
+
+<!-- Timestepping -->
+<parameter key ="start_time" type="double" default="0">
+     <section name="timestepping" />
+     <help> simulation starting time [yr] </help>
+</parameter>
+<parameter key ="final_time" type="double" default="5">
+     <section name="timestepping" />
+     <help> final time to stop the simulation [yr] </help>
+</parameter>
+<parameter key ="time_step" type="double" default="0.5">
+     <section name="timestepping" />
+     <help> length of time steps [yr] </help>
+</parameter>
+<parameter key ="time_adapt" type="double" default="0">
+     <section name="timestepping" />
+     <help> use cfl condition to define time step ? (0 or 1)  </help>
+</parameter>
+<parameter key ="cfl_coefficient" type="double" default="0.5">
+     <section name="timestepping" />
+     <help> coefficient applied to cfl condition </help>
+</parameter>
+
+
+<!-- initialization -->
+<frame key="1" label="Initial field values">
+<section name="initialization" />
+<parameter key ="vx" type="double" default="NaN">
+     <section name="initialization" />
+     <help> x component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vy" type="double" default="NaN">
+     <section name="initialization" />
+     <help> y component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vz" type="double" default="NaN">
+     <section name="initialization" />
+     <help> z component of velocity [m/yr] </help>
+</parameter>
+<parameter key ="vel" type="double" default="NaN">
+     <section name="initialization" />
+     <help> velocity norm [m/yr] </help>
+</parameter>
+<parameter key ="pressure" type="double" default="NaN">
+     <section name="initialization" />
+     <help> pressure field [Pa] </help>
+</parameter>
+<parameter key ="temperature" type="double" default="NaN">
+     <section name="initialization" />
+     <help> fraction of water in the ice </help>
+</parameter>
+<parameter key ="waterfraction" type="double" default="NaN">
+     <section name="initialization" />
+     <help> ice thickness [m] </help>
+</parameter>
+<parameter key ="sediment_head" type="double" default="NaN">
+     <section name="initialization" />
+     <help> sediment water head of subglacial system [m] </help>
+</parameter>
+<parameter key ="epl_head" type="double" default="NaN">
+     <section name="initialization" />
+     <help> epl water head of subglacial system [m] </help>
+</parameter>
+<parameter key ="watercolumn" type="double" default="NaN">
+     <section name="initialization" />
+     <help> thickness of subglacial water [m] </help>
+</parameter></frame>
+
+
+<!-- rifts -->
+<parameter key ="riftstruct" type="double" default="NaN">
+     <section name="rifts" />
+     <help> structure containing all rift information (vertices coordinates, segments, type of melange, ...) </help>
+</parameter>
+<parameter key ="riftproperties" type="double" default="NaN">
+     <section name="rifts" />
+     <help> N/A </help>
+</parameter>
+
+
+<!-- Debug -->
+<parameter key ="valgrind" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> use Valgrind to debug (0 or 1) </help>
+</parameter>
+<parameter key ="gprof" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> use gnu-profiler to find out where the time is spent </help>
+</parameter>
+<parameter key ="profiling" type="logical" optional="false">
+     <section name="debug" />
+        <option value="false" type="string" default="true"></option>
+     <help> enables profiling (memory, flops, time) </help>
+</parameter>
+
+<!-- verbose -->
+<parameter key ="mprocessor" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="module" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="solution" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="solver" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="convergence" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="control" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="qmu" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="true" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+<parameter key ="autodiff" type="logical" optional="false">
+     <section name="verbose" />
+        <option value="false" type="string" default="true"></option>
+     <help>  </help>
+</parameter>
+
+<!-- settings -->
+<parameter key ="results_on_nodes" type="double" default="0">
+     <section name="settings" />
+     <help> results are output for all the nodes of each element </help>
+</parameter>
+<parameter key ="io_gather" type="double" default="1">
+     <section name="settings" />
+     <help> I/O gathering strategy for result outputs (default 1) </help>
+</parameter>
+<parameter key ="lowmem" type="double" default="0">
+     <section name="settings" />
+     <help> is the memory limited ? (0 or 1) </help>
+</parameter>
+<parameter key ="output_frequency" type="double" default="1">
+     <section name="settings" />
+     <help> frequency at which results are saved in all solutions with multiple time_steps </help>
+</parameter>
+<parameter key ="waitonlock" type="double" default="Inf">
+     <section name="settings" />
+     <help> maximum number of minutes to wait for batch results (NaN to deactivate) </help>
+</parameter>
+<parameter key ="upload_server" type="char" default="N/A">
+     <section name="settings" />
+     <help> server hostname where model should be uploaded </help>
+</parameter>
+<parameter key ="upload_path" type="char" default="N/A">
+     <section name="settings" />
+     <help> path on server where model should be uploaded </help>
+</parameter>
+<parameter key ="upload_login" type="char" default="N/A">
+     <section name="settings" />
+     <help> server login </help>
+</parameter>
+<parameter key ="upload_port" type="double" default="0">
+     <section name="settings" />
+     <help> port login (default is 0) </help>
+</parameter>
+<parameter key ="upload_filename" type="char" default="N/A">
+     <section name="settings" />
+     <help> unique id generated when uploading the file to server </help>
+</parameter>
+
+<!-- generic -->
+<parameter key ="name" type="char" default="'XPS'">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="login" type="char" default="N/A">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="np" type="double" default="1">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="port" type="double" default="0">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="codepath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/bin">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="executionpath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/execution">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="etcpath" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/etc">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrind" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/install/bin/valgrind">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrindlib" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/install/lib/libmpidebug.so">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="valgrindsup" type="char" default=":/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk:/home/casper/work/issm/trunk/externalpackages/valgrind/issm.supp">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+<parameter key ="verbose" type="double" default="1">
+     <section name="cluster" />
+     <help> N/A </help>
+</parameter>
+
+<!-- balancethickness -->
+<parameter key ="spcthickness" type="double" default="N/A">
+     <section name="balancethickness" />
+     <help> thickness constraints (NaN means no constraint) [m] </help>
+</parameter>
+<parameter key ="thickening_rate" type="double" default="N/A">
+     <section name="balancethickness" />
+     <help> ice thickening rate used in the mass conservation (dh/dt) [m/yr] </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="1">
+     <section name="balancethickness" />
+     <help> 0: None, 1: SU, 2: SSAs artificial diffusivity, 3:DG </help>
+</parameter>
+
+<!-- StressBalance solution parameters: -->
+<frame key="1" label="Convergence criteria">
+<section name="stressbalance" />
+<parameter key ="restol" type="double" default="0.0001">
+     <section name="stressbalance" />
+     <help> mechanical equilibrium residual convergence criterion </help>
+</parameter>
+<parameter key ="reltol" type="double" default="0.01">
+     <section name="stressbalance" />
+     <help> velocity relative convergence criterion, NaN: not applied </help>
+</parameter>
+<parameter key ="abstol" type="double" default="10">
+     <section name="stressbalance" />
+     <help> velocity absolute convergence criterion, NaN: not applied </help>
+</parameter>
+<parameter key ="isnewton" type="double" default="0">
+     <section name="stressbalance" />
+     <help> 0: Picards fixed point, 1: Newtons method, 2: hybrid </help>
+</parameter>
+<parameter key ="maxiter" type="double" default="100">
+     <section name="stressbalance" />
+     <help> maximum number of nonlinear iterations </help>
+</parameter>
+<parameter key ="viscosity_overshoot" type="double" default="0">
+     <section name="stressbalance" />
+     <help> over-shooting constant new=new+C*(new-old) </help>
+</parameter>
+</frame>
+<frame key="2" label="Boundary conditions">
+<section name="stressbalance" />
+<parameter key ="spcvx" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> x-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+<parameter key ="spcvy" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> y-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+<parameter key ="spcvz" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> z-axis velocity constraint (NaN means no constraint) [m/yr] </help>
+</parameter>
+</frame>
+<frame key="3" label="Rift options">
+<section name="stressbalance" />
+<parameter key ="rift_penalty_threshold" type="double" default="0">
+     <section name="stressbalance" />
+     <help> threshold for instability of mechanical constraints </help>
+</parameter>
+<parameter key ="rift_penalty_lock" type="double" default="10">
+     <section name="stressbalance" />
+     <help> number of iterations before rift penalties are locked </help>
+</parameter>
+</frame>
+<frame key="4" label="Other">
+<section name="stressbalance" />
+<parameter key ="shelf_dampening" type="double" default="0">
+     <section name="stressbalance" />
+     <help> use dampening for floating ice ? Only for FS model </help>
+</parameter>
+<parameter key ="FSreconditioning" type="double" default="10000000000000">
+     <section name="stressbalance" />
+     <help> multiplier for incompressibility equation. Only for FS model </help>
+</parameter>
+<parameter key ="referential" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> local referential </help>
+</parameter>
+<parameter key ="loadingforce" type="double" default="N/A">
+     <section name="stressbalance" />
+     <help> loading force applied on each point [N/m^3] </help>
+</parameter>
+<parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="stressbalance" />
+     <help> additional outputs requested </help>
+</parameter>
+</frame>
+
+
+<!-- groundingline -->
+<frame key="1" label="Grounding line migration parameters">
+<section name="groundingline" />
+<parameter key ="migration" type="char" default="'None'">
+     <section name="groundingline" />
+     <help> type of grounding line migration: "SoftMigration","AgressiveMigration" or "None" </help>
+</parameter>
+<parameter key ="melting_rate" type="double" default="0">
+     <section name="groundingline" />
+     <help> melting rate applied when previously grounded parts start floating [m/yr] </help>
+</parameter></frame>
+
+
+<!-- Hydrology -->
+<frame key="1" label="Hydrologyshreve solution parameters">
+<section name="hydrologyshreve" />
+<parameter key ="spcwatercolumn" type="double" default="N/A">
+     <section name="hydrologyshreve" />
+     <help> water thickness constraints (NaN means no constraint) [m] </help>
+</parameter>
+<parameter key ="n" type="double" default="0.02">
+     <section name="hydrologyshreve" />
+     <help> Manning roughness coefficient </help>
+</parameter>
+<parameter key ="CR" type="double" default="0.01">
+     <section name="hydrologyshreve" />
+     <help> tortuosity parameter </help>
+</parameter>
+<parameter key ="p" type="double" default="2">
+     <section name="hydrologyshreve" />
+     <help> dimensionless exponent in Manning velocity formula </help>
+</parameter>
+<parameter key ="q" type="double" default="1">
+     <section name="hydrologyshreve" />
+     <help> dimensionless exponent in Manning velocity formula </help>
+</parameter>
+<parameter key ="kn" type="double" default="0">
+     <section name="hydrologyshreve" />
+     <help> parameter in effective pressure formula </help>
+</parameter>
+<parameter key ="stabilization" type="double" default="1">
+     <section name="hydrologyshreve" />
+     <help> artificial diffusivity (default is 1). can be more than 1 to increase diffusivity. </help>
+</parameter>
+</frame>
+<!-- masstransport -->
+<frame key="1" label="Masstransport solution parameters">
+<section name="masstransport" />
+  <parameter key ="spcthickness" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> thickness constraints (NaN means no constraint) [m] </help>
+  </parameter>
+  <parameter key ="calvingrate" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> calving rate at given location [m/a] </help>
+  </parameter>
+  <parameter key ="isfreesurface" type="double" default="0">
+     <section name="masstransport" />
+     <help> do we use free surfaces (FS only) are mass conservation </help>
+  </parameter>
+  <parameter key ="min_thickness" type="double" default="1">
+     <section name="masstransport" />
+     <help> minimum ice thickness allowed [m] </help>
+  </parameter>
+  <parameter key ="hydrostatic_adjustment" type="char" default="'Absolute'">
+     <section name="masstransport" />
+     <help> adjustment of ice shelves surface and bed elevations: 'Incremental' or 'Absolute'  </help>
+  </parameter>
+  <parameter key ="stabilization" type="double" default="1">
+     <section name="masstransport" />
+     <help> 0: no, 1:  artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin </help>
+  </parameter>
+</frame>
+<frame key="2" label="Penalty options">
+<section name="masstransport" />
+  <parameter key ="vertex_pairing" type="double" default="N/A">
+     <section name="masstransport" />
+     <help> offset used by penalties: penalty = Kmax*10^offset </help>
+  </parameter>
+  <parameter key ="penalty_factor" type="double" default="3">
+     <section name="masstransport" />
+     <help> pairs of vertices that are penalized </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="masstransport" />
+     <help> additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- thermal -->
+<frame key="1" label="Thermal solution parameters">
+<section name="thermal" />
+  <parameter key ="spctemperature" type="double" default="N/A">
+     <section name="thermal" />
+     <help> temperature constraints (NaN means no constraint) [K] </help>
+  </parameter>
+  <parameter key ="penalty_threshold" type="double" default="0">
+     <section name="thermal" />
+     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>
+  </parameter>
+  <parameter key ="stabilization" type="double" default="1">
+     <section name="thermal" />
+     <help> maximum number of non linear iterations </help>
+  </parameter>
+  <parameter key ="maxiter" type="double" default="100">
+     <section name="thermal" />
+     <help> stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>
+  </parameter>
+  <parameter key ="penalty_lock" type="double" default="0">
+     <section name="thermal" />
+     <help> threshold to declare convergence of thermal solution (default is 0)  </help>
+  </parameter>
+  <parameter key ="penalty_factor" type="double" default="3">
+     <section name="thermal" />
+     <help> scaling exponent (default is 3) </help>
+  </parameter>
+  <parameter key ="isenthalpy" type="double" default="0">
+     <section name="thermal" />
+     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>
+  </parameter>
+  <parameter key ="isdynamicbasalspc" type="double" default="0">
+     <section name="thermal" />
+     <help> enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)  </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="thermal" />
+     <help> additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- steadystate -->
+<frame key="1" label="steadystate solution parameters">
+<section name="steadystate" />
+  <parameter key ="reltol" type="double" default="0.01">
+     <section name="steadystate" />
+     <help> relative tolerance criterion [K] </help>
+  </parameter>
+  <parameter key ="maxiter" type="double" default="100">
+     <section name="steadystate" />
+     <help> maximum number of iterations </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="steadystate" />
+     <help> additional requested outputs </help>
+  </parameter>
+</frame>
+<!-- transient -->
+<frame key="1" label="transient solution parameters">
+<section name="transient" />
+  <parameter key ="ismasstransport" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a masstransport solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isstressbalance" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a stressbalance solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isthermal" type="double" default="1">
+     <section name="transient" />
+     <help> indicates whether a thermal solution is used in the transient </help>
+  </parameter>
+  <parameter key ="isgroundingline" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether a groundingline migration is used in the transient </help>
+  </parameter>
+  <parameter key ="isgia" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether a postglacial rebound model is used in the transient </help>
+  </parameter>
+  <parameter key ="isdamage" type="double" default="0">
+     <section name="transient" />
+     <help> indicates whether damage evolution is used in the transient </help>
+  </parameter>
+  <parameter key ="islevelset" type="double" default="0">
+     <section name="transient" />
+     <help> LEVEL SET DESCRIPTION...  </help>
+  </parameter>
+  <parameter key ="requested_outputs" type="cell" default="{'default'}">
+     <section name="transient" />
+     <help> list of additional outputs requested </help>
+  </parameter>
+</frame>
+<!-- gia -->
+<frame key="1" label="gia parameters">
+<section name="gia" />
+  <parameter key ="mantle_viscosity" type="double" default="N/A">
+     <section name="gia" />
+     <help> mantle viscosity[Pa s] </help>
+  </parameter>
+  <parameter key ="lithosphere_thickness" type="double" default="N/A">
+     <section name="gia" />
+     <help> lithosphere thickness (km) </help>
+  </parameter>
+  <parameter key ="cross_section_shape" type="double" default="1">
+     <section name="gia" />
+     <help> 1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore </help>
+  </parameter>
+</frame>
+<!-- autodiff -->
+<frame key="1" label="automatic differentiation parameters">
+<section name="autodiff" />
+  <parameter key ="isautodiff" type="logical" optional="false">
+     <section name="autodiff" />
+         <option value="false" type="string" default="true"></option>
+     <help> indicates if the automatic differentiation is activated </help>
+  </parameter>
+  <parameter key ="dependents" type="cell" default="(0x0)">
+     <section name="autodiff" />
+     <help> list of dependent variables </help>
+  </parameter>
+  <parameter key ="independents" type="cell" default="(0x0)">
+     <section name="autodiff" />
+     <help> list of independent variables </help>
+  </parameter>
+  <parameter key ="driver" type="char" default="'fos_forward'">
+     <section name="autodiff" />
+     <help> ADOLC driver ('fos_forward' or 'fov_forward') </help>
+  </parameter>
+  <parameter key ="obufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of operations per buffer (==OBUFSIZE in usrparms.h)  </help>
+  </parameter>
+  <parameter key ="lbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of locations per buffer (==LBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="cbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of values per buffer (==CBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="tbufsize" type="double" default="524288">
+     <section name="autodiff" />
+     <help> Number of taylors per buffer (&amp;lt;=TBUFSIZE in usrparms.h) </help>
+  </parameter>
+  <parameter key ="gcTriggerRatio" type="double" default="2">
+     <section name="autodiff" />
+     <help> free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio </help>
+  </parameter>
+  <parameter key ="gcTriggerRatio" type="double" default="2">
+     <section name="autodiff" />
+     <help> free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize </help>
+  </parameter>
+</frame>
+<!-- flaim -->
+<frame key="1" label="Input:">
+<section name="flaim" />
+  <parameter key ="targets" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml output targets file </help>
+  </parameter>
+  <parameter key ="tracks" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml input tracks file </help>
+  </parameter>
+  <parameter key ="flightreqs" type="struct" default="N/A">
+     <section name="flaim" />
+     <help> structure of kml flight requirements (not used yet) </help>
+  </parameter>
+  <parameter key ="criterion" type="double" default="N/A">
+     <section name="flaim" />
+     <help> element or nodal criterion for flight path evaluation (metric) </help>
+  </parameter>
+</frame>
+<frame key="2" label="Arguments:">
+<section name="flaim" />
+  <parameter key ="gridsatequator" type="double" default="200000">
+     <section name="flaim" />
+     <help> number of grids at equator (determines resolution) </help>
+  </parameter>
+  <parameter key ="usevalueordering" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="true" type="string" default="true"></option>
+     <help> flag to consider target values for flight path evaluation </help>
+  </parameter>
+  <parameter key ="split_antimeridian" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="true" type="string" default="true"></option>
+     <help> flag to split polygons on the antimeridian </help>
+  </parameter>
+</frame>
+<frame key="3" label="Optimization:">
+<section name="flaim" />
+  <parameter key ="path_optimize" type="logical" optional="false">
+     <section name="flaim" />
+         <option value="false" type="string" default="true"></option>
+     <help> optimize? (default false) </help>
+  </parameter>
+  <parameter key ="opt_ndir" type="double" default="1">
+     <section name="flaim" />
+     <help> number of directions to test when moving a point.  If this value = 1, a random direction is tested. A value > 1 results in directions equally spaced from [0, 2*PI] being tested. For example, 4 would result in directions [0, PI/2, PI, 3PI/2] </help>
+  </parameter>
+  <parameter key ="opt_dist" type="double" default="25">
+     <section name="flaim" />
+     <help> specifies the distance in km (default 25) to move a randomly selected path point on each iteration </help>
+  </parameter>
+  <parameter key ="opt_niter" type="double" default="30000">
+     <section name="flaim" />
+     <help> number of iterations (default 30,000) to run for flightplan optimization, i.e. the number of times to randomly select a point and move it. </help>
+  </parameter>
+</frame>
+<frame key="4" label="Output:">
+<section name="flaim" />
+  <parameter key ="solution" type="char" default="N/A">
+     <section name="flaim" />
+     <help> name of kml solution file </help>
+  </parameter>
+  <parameter key ="quality" type="double" default="0">
+     <section name="flaim" />
+     <help> quality of kml solution </help>
+  </parameter>
+</frame>
+<!-- inversion -->
+<frame key="1" label="inversion parameters">
+<section name="inversion" />
+  <parameter key ="iscontrol" type="double" default="0">
+     <section name="inversion" />
+     <help> is inversion activated? </help>
+  </parameter>
+  <parameter key ="incomplete_adjoint" type="double" default="1">
+     <section name="inversion" />
+     <help> 1: linear viscosity, 0: non-linear viscosity </help>
+  </parameter>
+  <parameter key ="control_parameters" type="cell" default="{'FrictionCoefficient'}">
+     <section name="inversion" />
+     <help> ex: {'FrictionCoefficient'}, or {'MaterialsRheologyBbar'} </help>
+  </parameter>
+  <parameter key ="nsteps" type="double" default="20">
+     <section name="inversion" />
+     <help> number of optimization searches </help>
+  </parameter>
+  <parameter key ="cost_functions" type="double" default="101">
+     <section name="inversion" />
+     <help> indicate the type of response for each optimization step  </help>
+  </parameter>
+  <parameter key ="cost_functions_coefficients" type="double" default="N/A">
+     <section name="inversion" />
+     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>
+  </parameter>
+  <parameter key ="cost_function_threshold" type="double" default="N/A">
+     <section name="inversion" />
+     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>
+  </parameter>
+  <parameter key ="maxiter_per_step" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> maximum iterations during each optimization step  </help>
+  </parameter>
+  <parameter key ="gradient_scaling" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> scaling factor on gradient direction during optimization, for each optimization step </help>
+  </parameter>
+  <parameter key ="step_threshold" type="double" default="(20x1)">
+     <section name="inversion" />
+     <help> decrease threshold for misfit, default is 30% </help>
+  </parameter>
+  <parameter key ="min_parameters" type="double" default="N/A">
+     <section name="inversion" />
+     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>
+  </parameter>
+  <parameter key ="max_parameters" type="double" default="N/A">
+     <section name="inversion" />
+     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>
+  </parameter>
+  <parameter key ="vx_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity x component [m/yr] </help>
+  </parameter>
+  <parameter key ="vy_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity y component [m/yr]  </help>
+  </parameter>
+  <parameter key ="vel_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed velocity magnitude [m/yr] </help>
+  </parameter>
+  <parameter key ="thickness_obs" type="double" default="N/A">
+     <section name="inversion" />
+     <help> observed thickness [m]) </help>
+  </parameter>
+</frame>
+<frame key="2" label="Available cost functions">
+<section name="inversion" />
+  <parameter key ="SurfaceAbsVelMisfit" type="string" default="101">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceRelVelMisfit" type="string" default="102">
+     <section name="inversion" />
+     <help>   </help>
+  </parameter>
+  <parameter key ="SurfaceLogVelMisfit" type="string" default="103">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceLogVxVyMisfit" type="string" default="104">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="SurfaceAverageVelMisfit" type="string" default="105">
+     <section name="inversion" />
+     <help>   </help>
+  </parameter>
+  <parameter key ="ThicknessAbsMisfit" type="string" default="106">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="DragCoefficientAbsGradient" type="string" default="107">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="RheologyBbarAbsGradient" type="string" default="108">
+     <section name="inversion" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="ThicknessAbsGradient" type="string" default="109">
+     <section name="inversion" />
+     <help> </help>
+  </parameter>
+</frame>
+<!-- qmu -->
+<frame key="1" label="qmu parameters">
+<section name="qmu" />
+  <parameter key ="isdakota" type="double" default="0">
+     <section name="qmu" />
+     <help> is qmu analysis activated? </help>
+  </parameter>
+  <parameter key ="variables" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (arrays of each variable class) </help>
+  </parameter>
+  <parameter key ="responses" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (arrays of each response class) </help>
+  </parameter>
+  <parameter key ="numberofresponses" type="double" default="0">
+     <section name="qmu" />
+     <help> number of responses </help>
+  </parameter>
+  <parameter key ="params" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (array of method-independent parameters)  </help>
+  </parameter>
+  <parameter key ="results" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> (information from dakota files) </help>
+  </parameter>
+  <parameter key ="partition" type="double" default="N/A">
+     <section name="qmu" />
+     <help> user provided mesh partitioning, defaults to metis if not specified </help>
+  </parameter>
+  <parameter key ="numberofpartitions" type="double" default="0">
+     <section name="qmu" />
+     <help> number of partitions for semi-discrete qmu  </help>
+  </parameter>
+  <parameter key ="variabledescriptors" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="responsedescriptors" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>
+  </parameter>
+  <parameter key ="method" type="struct" default="N/A">
+     <section name="qmu" />
+     <help> array of dakota_method class </help>
+  </parameter>
+  <parameter key ="mass_flux_profile_directory" type="double" default="N/A">
+     <section name="qmu" />
+     <help> directory for mass flux profiles </help>
+  </parameter>
+  <parameter key ="mass_flux_profiles" type="double" default="N/A">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="mass_flux_segments" type="cell" default="(0x0)">
+     <section name="qmu" />
+     <help>  </help>
+  </parameter>
+  <parameter key ="adjacency" type="double" default="N/A">
+     <section name="qmu" />
+     <help> additional outputs requested </help>
+  </parameter>
+  <parameter key ="vertex_weight" type="double" default="N/A">
+     <section name="qmu" />
+     <help> weight applied to each mesh vertex </help>
+  </parameter>
+</frame>
+<!-- outputdefinition -->
+<frame key="1" label="outputdefinition">
+<section name="outputdefinition" />
+  <parameter key ="definitions" type="cell" default="(0x0)">
+     <section name="outputdefinition" />
+     <help> list of potential outputs that can be requested, but which need additional data to be defined </help>
+  </parameter>
+</frame>
+<!-- miscellaneous -->
+<frame key="1" label="miscellaneous parameters">
+<section name="miscellaneous" />
+  <parameter key ="notes" type="char" default="N/A">
+     <section name="miscellaneous" />
+     <help> notes in a cell of strings </help>
+  </parameter>
+  <parameter key ="name" type="char" default="N/A">
+     <section name="miscellaneous" />
+     <help> model name </help>
+  </parameter>
+  <parameter key ="dummy" type="struct" default="N/A">
+     <section name="miscellaneous" />
+     <help> empty field to store some data </help>
+  </parameter>
+</frame>
+
+
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/meteoio_config.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/meteoio_config.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/meteoio_config.xml	(revision 18231)
@@ -0,0 +1,919 @@
+<inishell_config application="Meteo IO">
+
+	<!-- General Parameters -->
+	<parameter key="BUFF_CHUNK_SIZE" type="integer" default="30">
+		<section name="general" />
+		<help>Size in days of a chunk of data to read at once.</help>
+	</parameter>
+
+	<parameter key="BUFF_BEFORE" type="decimal" default="1.5">
+		<section name="general" />
+		<help>Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the
+		beginning of the buffer (therefore, it takes a value in days).</help>
+	</parameter>
+
+	<!-- Coordinate systems, time zones -->
+	<parameter key="COORDSYS" type="alternative" optional="false">
+		<section name="input" />
+		<section name="output" />
+		<option value="CH1903" type="string" default="true">
+			<help>coordinates in the Swiss Grid &lt;a href="http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf"&gt;http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UTM" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the zone with the zone letter (for example, 32T)</help>
+			</parameter>
+			<help>UTM coordinates, see &lt;a href="http://www.oc.nps.edu/oc2902w/maps/utmups.pdf"&gt;http://www.oc.nps.edu/oc2902w/maps/utmups.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UPS" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the hemisphere (either N or S)</help>
+			</parameter>
+			<help>Universal Polar Stereographic coordinates, see &lt;a href="https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system"&gt;https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system&lt;/a&gt;</help>
+		</option>
+		<option value="PROJ4" type="string">
+			<parameter key="COORDPARAM" type="string" optional="false" />
+			<help>external library: see &lt;a href="http://trac.osgeo.org/proj/"&gt;http://trac.osgeo.org/proj/&lt;/a&gt;</help>
+		</option>
+		<option value="LOCAL"  type="string">
+			<help>uses the horizontal and vertical distance from a reference point</help>
+		</option>
+		<help>coordinate system</help>
+	</parameter>
+
+	<parameter key="TIME_ZONE" type="integer+" default="+1" maximum="14" minimum="-12" optional="false">
+		<section name="input" />
+		<section name="output" />
+	</parameter>
+
+	<!-- Datatypes: special pts -->
+	<parameter key="SPECIALPTS" type="alternative">
+		<section name="input" />
+		<option value="A3D" type="string">
+			<parameter key="SPECIALPTSFILE" type="file" optional="false">
+				<help>a path+file name to the a file containing grid coordinates of special points of interest (for special outputs)</help>
+			</parameter>
+		</option>
+		<option value="SMET" type="string">
+			<parameter key="SPECIALPTSFILE" type="file" optional="false">
+				<help>a path+file name to the a file containing grid coordinates of special points of interest (for special outputs)</help>
+			</parameter>
+		</option>
+	</parameter>
+
+	<!-- Datatypes: Meteo Data -->
+	<parameter key="METEO" type="alternative">
+		<section name="input" />
+		<section name="output" />
+
+		<option value="A3D" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="BORMA" type="string">
+			<section name="input" />
+			<reference name="BORMA" />
+		</option>
+		<option value="COSMO" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="GEOTOP" type="string">
+			<section name="input" />
+			<reference name="GEOTOP_IN" />
+		</option>
+		<option value="GEOTOP" type="string">
+			<section name="output" />
+			<reference name="GEOTOP_OUT" />
+		</option>
+		<option value="GRIB" type="string">
+			<section name="input" />
+			<reference name="GRIB_METEO" />
+		</option>
+		<option value="GSN" type="string">
+			<section name="input" />
+			<reference name="GSN" />
+		</option>
+		<option value="IMIS" type="string">
+			<section name="input" />
+			<reference name="IMIS" />
+		</option>
+		<option value="SMET" type="string">
+			<section name="input" />
+			<reference name="SMET_IN" />
+		</option>
+		<option value="SMET" type="string">
+			<section name="output" />
+			<reference name="SMET_OUT" />
+		</option>
+		<option value="SNOWPACK" type="string">
+			<section name="input" />
+			<reference name="SNIO_IN" />
+		</option>
+		<option value="SNOWPACK" type="string">
+			<section name="output" />
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string representing path where SNOWPACK files should be saved</help>
+			</parameter>
+		</option>
+
+		<help>plugin for METEO data </help>
+	</parameter>
+
+	<parameter key="Add Meteo parameter copy" type="selector">
+		<section name="input"/>
+		<parameter key="COPY::%" type="string" optional="false" template="true">
+		  <help>The name of the parameter to copy (e.g. TA, RH, VW, ISWR, etc)</help>
+		</parameter>
+	</parameter>
+
+	<!-- Datatypes: DEM -->
+	<frame key="dem_frame" label="Digital Elevation Model">
+	<section name="input"/>
+		<parameter key="DEM" type="alternative">
+			<section name="input" />
+			<option value="ARC" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+			</option>
+			<option value="ARPS" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<parameter key="ARPS_XCOORD" type="decimal" optional="false">
+					<help>x coordinate of the lower left corner of the grids</help>
+				</parameter>
+				<parameter key="ARPS_YCOORD" type="decimal" optional="false">
+					<help>y coordinate of the lower left corner of the grids</help>
+				</parameter>
+			</option>
+			<option value="GRASS" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+			</option>
+			<option value="GRIB" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<parameter key="GRIB_DEM_UPDATE" type="alternative" optional="true">
+					<option value="TRUE" type="string" />
+					<option value="FALSE" type="string" />
+					<help>recompute slope/azimuth from the elevations when reading a DEM (default=false, that is we use the slope and azimuth included in the GRIB file)</help>
+				</parameter>
+			</option>
+			<option value="PGM" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<reference name="PGM_IN" />
+			</option>
+
+			<help>plugin for Digital Elevation Model data </help>
+		</parameter>
+	</frame>
+
+	<!-- Datatypes: Landuse -->
+	<parameter key="LANDUSE" type="alternative">
+		<section name="input" />
+		<option value="ARC" type="string">
+			<parameter key="LANDUSEFILE" type="file" optional="false">
+				<help>File containing a grid of landuse codes</help>
+			</parameter>
+		</option>
+
+		<help>plugin for land cover data </help>
+	</parameter>
+
+	<!-- Datatypes: Grids -->
+	<parameter key="GRID2D" type="alternative">
+		<section name="input" />
+		<section name="output" />
+		<option value="ARC" type="string">
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="ARC" />
+		</option>
+		<option value="ARPS" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="ARPS" />
+		</option>
+		<option value="GRASS" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+		</option>
+		<option value="GRIB" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="GRIB_GRIDS" />
+		</option>
+		<option value="PGM" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="PGM_IN" />
+		</option>
+		<option value="PGM" type="string">
+			<section name="output" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+		</option>
+		<option value="PNG" type="string">
+			<section name="output" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="PNG" />
+		</option>
+		<help>plugin for 2D gridded data </help>
+	</parameter>
+
+	<!--Parameter group for list of stations -->
+	<parametergroup name="stationgroup_files">
+		<parameter key="STATION#" type="file" counter="1" optional="false">
+			<help>filename for station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_names">
+		<parameter key="STATION#" type="string" counter="1" optional="false">
+			<help>station id for the given station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_pos">
+		<parameter key="STATION#" type="string" counter="1">
+			<help>Coordinates are given as "lat lon" or "xcoord ycoord epsg_code"</help>
+		</parameter>
+	</parametergroup>
+
+	<!-- Plugins for Meteo Data-->
+	<parametergroup name="BORMA">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the xml files</help>
+		</parameter>
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="IMIS">
+		<parameter key="DBNAME" type="string" optional="false">
+			<help>database name, as provided by your database administrator</help>
+		</parameter>
+		<parameter key="DBUSER" type="string" optional="false">
+			<help>database user name</help>
+		</parameter>
+		<parameter key="DBPASS" type="string" optional="false">
+			<help>database password associated with the user name</help>
+		</parameter>
+		<parameter key="USEANETZ" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: use ANETZ stations to provide precipitations for normal IMIS stations.
+		  Each IMIS station is associated with one or two ANETZ stations and does a weighted
+		  average to get what should be its local precipitations</help>
+		</parameter>
+		<parameter key="USE_IMIS_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: if set to false (default), all IMIS precipitation will be deleted (since IMIS stations don't have heated rain gauges, their precipitation measurements are not good in winter conditions). If set to true, it is strongly advised to use a FilterHNWMelt filter to detect snow melting in the rain gauge and perform winter conditions detection in the application.</help>
+		</parameter>
+		<parameter key="USE_SNOWPACK_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>if set to true, the SNOWPACK simulated Snow Water Equivalent from the database will be used to compute HNW. Data gaps greater than 3 hours on SWE will lead to unchanged hnw while all data that can properly be computed will overwrite hnw. (default=false)</help>
+		</parameter>
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="GRIB_METEO">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the grib files</help>
+		</parameter>
+		<parameter key="METEOEXT" type="string" optional="true">
+			<help>grib file extension, or none for no file extension (default: .grb)</help>
+		</parameter>
+
+		<reference name="stationgroup_pos" />
+	</parametergroup>
+
+	<parametergroup name="GEOTOP_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the data files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="false">
+			<help>absolute filename of the geotop.inpts file</help>
+		</parameter>
+		<parameter key="METEOPREFIX" type="string" optional="true">
+			<help>prefix to append when generating a file name for reading</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GEOTOP_OUT">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the data files</help>
+		</parameter>
+		<parameter key="METEOSEQ" type="string" optional="false">
+			<help>specifiy in which order the columns should be printed out</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GSN">
+		<parameter key="ENDPOINT" type="string" optional="false">
+			<help>webserver running GSN with its port number and full path. For example:
+			http://montblanc.slf.ch:22001/services/A3DWebService</help>
+		</parameter>
+		<parameter key="PROXY" type="string" optional="true">
+			<help>Should the connection go through a proxy? This is useful for servers
+			filtering on domains but usually not necessary.</help>
+		</parameter>
+		<parameter key="PROXYPORT" type="string" optional="true" />
+		<parameter key="PROXYUSER" type="string" optional="true" />
+		<parameter key="PROXYPASS" type="string" optional="true" />
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="SMET_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the smet files</help>
+		</parameter>
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<parametergroup name="SMET_OUT">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string representing path where SMET files should be saved</help>
+		</parameter>
+		<parameter key="METEOPARAM" type="alternative">
+		  <option value="ASCII" type="string" default="true">
+		    <help>Write ASCII SMET files</help>
+		  </option>
+		  <option value="BINARY" type="string">
+		    <help>Write BINARY SMET files</help>
+		  </option>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="SNIO_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the SNOWPACK files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="true">
+			<help>filename of the meta data file (in METEOPATH)</help>
+		</parameter>
+
+		<parameter key="NUMBER_MEAS_TEMPERATURES" type="integer+" minimum="0" default="0">
+		  <help>the number of measured snow temperatures provided</help>
+		</parameter>
+
+		<parameter key="NUMBER_OF_SOLUTES" type="integer+" minimum="0" default="0">
+		  <help>the number of solutes for which input data are provided</help>
+		</parameter>
+
+		<parameter key="RSWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="ISWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="VW_DRIFT" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: wind velocity to use for blowing and drifting snow is provided</help>
+		</parameter>
+		<parameter key="RHO_HN" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: measured new snow density is provided</help>
+		</parameter>
+
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<!-- Plugins for Gridded Data-->
+	<parametergroup name="ARC">
+		<parameter key="A3D_VIEW" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate names compatible with Alpine3D's grid viewer?</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grid file extension, or none for no file extension (default: .asc)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="ARPS">
+		<parameter key="ARPS_XCOORD" type="decimal" optional="false">
+			<help>x coordinate of the lower left corner of the grids</help>
+		</parameter>
+		<parameter key="ARPS_YCOORD" type="decimal" optional="false">
+			<help>y coordinate of the lower left corner of the grids</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grid file extension, or none for no file extension (default: .asc)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GRIB_GRIDS">
+		<parameter key="GRID2DPREFIX" type="string" optional="true">
+			<help>prefix to append when generating a file name for reading (ie: something like "laf" for Cosmo-Analysis-full domain)</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grib file extension, or none for no file extension (default: .grb)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="PNG">
+		<parameter key="PNG_WORLD_FILE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a world file for each output file? This file contains the geolocalization information</help>
+		</parameter>
+		<parameter key="PNG_LEGEND" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a legend?</help>
+		</parameter>
+		<parameter key="PNG_AUTOSCALE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>autoscale color scale?</help>
+		</parameter>
+		<parameter key="PNG_SCALING" type="alternative" optional="true">
+			<option value="nearest" type="string" />
+			<option value="bilinear" type="string" />
+			<help>scaling algorithm (default=bilinear)</help>
+		</parameter>
+		<parameter key="PNG_MIN_SIZE" type="string" optional="false">
+			<help>minimum dimensions of the PNG, like 640x480</help>
+		</parameter>
+		<parameter key="PNG_MAX_SIZE" type="string" optional="false">
+			<help>maximum dimensions of the PNG, like 1024x768</help>
+		</parameter>
+		<parameter key="PNG_INDEXED" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a color indexed file (default=true)</help>
+		</parameter>
+		<parameter key="PNG_SPEED_OPTIMIZE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>optimize for speed (default=false)</help>
+		</parameter>
+		<parameter key="PNG_NR_LEVELS" type="integer+" default="+30" maximum="255" minimum="6" optional="true">
+			<help>number of colors in the palette (default=30)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="PGM_IN">
+		<parameter key="PGM_XCOORD" type="decimal" optional="false">
+			<help>lower left x coordinate</help>
+		</parameter>
+		<parameter key="PGM_YCOORD" type="decimal" optional="false">
+			<help>lower left y coordinate</help>
+		</parameter>
+		<parameter key="PGM_CELLSIZE" type="decimal" optional="false">
+			<help>cellsize in meters</help>
+		</parameter>
+		<parameter key="PGM_MIN" type="decimal" optional="false">
+			<help>minimum value in real world coordinates to match with the minimum value read out of the PGM file (such minimum being greater than 0 because 0 is NODATA)</help>
+		</parameter>
+		<parameter key="PGM_MAX" type="decimal" optional="false">
+			<help>maximum value in real world coordinates to match with the maximum value read out of the PGM file</help>
+		</parameter>
+	</parametergroup>
+
+	<!-- Meteo Parameters for Filters, resampling, spatial interpolations-->
+	<parametergroup name="METEOIOPARAMETERS">
+		<option value="TA"/>
+		<option value="RH"/>
+		<option value="VW"/>
+		<option value="DW"/>
+		<option value="VW_MAX"/>
+		<option value="ISWR"/>
+		<option value="RSWR"/>
+		<option value="ILWR"/>
+		<option value="HS"/>
+		<option value="HNW"/>
+		<option value="TSG"/>
+		<option value="TSS"/>
+		<option value="P"/>
+	</parametergroup>
+
+	<!-- Filters -->
+	<parameter key="Add/Remove Filter" type="selector">
+		<section name="filters" />
+
+		<parameter key="%::filter#" type="alternative" counter="1" template="true">
+			<section name="filters" />
+
+			<option label="MeanAvg" value="mean_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+
+			<option label="MedianAvg" value="median_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="decimal" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median average processing. The median average filter returns the median value of all values within a user given time window.</help>
+			</option>
+
+			<option label="Std Deviation Filter" value="std_dev" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Standard deviation filter. Values outside of mean ± 2 std_dev are rejected.</help>
+			</option>
+
+			<option label="MAD" value="mad" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median Absolute Deviation. Values outside of median ± 3 σ_MAD are rejected. &lt;br&gt;
+			  See http://en.wikipedia.org/wiki/Median_absolute_deviation for more information.</help>
+			</option>
+
+			<option label="Tukey 53H Filter" value="Tukey" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      The keyword "soft" maybe added, if the window position is allowed to be adjusted to the data present.
+			      The two arguments may be preceded by the keywords "left", "center" or "right", indicating the window position.
+			    </help>
+			  </parameter>
+			  <help>Tukey 53H method A smooth time sequence is generated from the median, substracted from the original signal and
+			  compared with the standard deviation. see "Despiking Acoustic Doppler Velocimeter Data", Derek G. Goring and Vladimir
+			  L. Nikora, Journal of Hydraulic Engineering, 128, 1, 2002 The deviation factor coeffecient is currently hard-coded as k=1.5. </help>
+			</option>
+
+			<option label="Wind Averaging Filter" value="wind_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Wind vector averaging. This calculates the vector average over a user given time period. Each wind vector
+			  within this period is added and the final sum is normalized by the number of vectors that have been added. </help>
+			</option>
+
+			<option label="Exponential Smoothing" value="exp_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <option label="alpha:" value="0.8" type="decimal" minimum="0" maximum="1"/>
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Alpha needs to be provided as last argument. Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Exponential smooting processing, exponential moving average s_0 = x_0 s_n = alpha*x_(t-1) + (1-alpha)*s_t-1</help>
+			</option>
+
+			<option label="Weighted Moving Average Smoothing" value="wma_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Weighted moving average smoothing such as: WMA = (1*X1 + 2*X2 + ... + n*Xn) / sum_of_weights</help>
+			</option>
+
+			<option label="Min Range Filter" value="min" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data smaller than the min would be
+			    assigned the minimum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Min range filter. Reject all values smaller than the min.</help>
+			</option>
+
+			<option label="Max Range Filter" value="max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be
+			    assigned the maximum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Max range filter. Reject all values greater than the max.</help>
+			</option>
+
+			<option label="MinMax (2 or 4 arguments)" value="min_max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Min adjust to:" value="" type="decimal" />
+			    <option label="Max adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be assigned
+			    the maximum permissible value and all data smaller than the min would be assigned the minimum
+			    permissible value or an optional extra set of two user provided values</help>
+			  </parameter>
+			  <help>Reject all values greater than the max or smaller than the min. &lt;br&gt;</help>
+			</option>
+
+			<option label="Rate Filter (1 argument)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the absolute value of the maximum permissible rate of change (per seconds)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Rate Filter (2 arguments)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Min:" value="0.0" type="decimal" minimum="0" maximum="1" />
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the minimum and maximum permissible rate of change (per second)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Unheated Rain Gauge Filter" value="Unheated_RainGauge" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="RH threshold:" value="0.5" type="decimal" minimum="0" maximum="1" />
+			    <option label="Delta_T threshold:" value="3.0" type="decimal" minimum="0" maximum="20" />
+			  </parameter>
+			  <help>Filters out snow melting in an unheated rain gauge. This filter can ONLY be applied to precipitation. Non-zero measurements are accepted only if they take place when the relative humidity is greater than RH_threshold and (TA-TSS) smaller than Delta_T_threshold, otherwise they get reset to 0. If none of these conditions could be tested (for lack of data), then the precipitation is reset to nodata (or left unchanged if "soft" has been selected).</help>
+			</option>
+
+			<option label="WMO Undercatch Filter" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Gage type" type="dropdown">
+					<option value="Nipher" type="string" />
+					<option value="Tretyakov" type="string" />
+					<option value="US8sh" type="string" />
+					<option value="US8unsh" type="string" />
+					<option value="Hellmann" type="string" />
+					<option value="Hellmannsh" type="string" />
+				</option>
+			  </parameter>
+			  <help>This implements the standard methods for precipitation correction as described in "WMO Solid Precipitation Measurement Intercomparison", B. Goodison, P. Louie and D. Yang, 872, 1998 as well as the overview given by "Literature Study on the Correction of Precipitation Measurements", Annette Wagner, 2009. The correction parameters for the shielded Hellmann gauge (German version) are from "Wind-induced Precipitation Undercatch of the Hellmann Gauges", Daqing Yang et al, Nordic Hydrology, 30, 1999, pp 57-80.</help>
+			</option>
+
+			<option label="WMO Undercatch Filter - simplified" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Kind" type="dropdown">
+					<option value="Cst" type="string" />
+				</option>
+				<option label="Snow factor:" value="1.3" type="decimal" minimum="0" maximum="5" />
+				<option label="Mixed prec factor:" value="1.1" type="decimal" minimum="0" maximum="5" />
+			  </parameter>
+			  <help>This applies a constant correction factor to the precipitation, one for pure snow and one for mixed precipitation. The following thresholds are used: pure snow below -2 C; mixed precipitation between -2 and +2 C; pure rain above 2 C. These threshold can be changed (see online documentation).</help>
+			</option>
+
+			<option label="Unventillated temperature sensor" value="Unventilated_T" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="albedo:" value="0.23" type="decimal" />
+			    <option value="soft" type="choice" />
+			    <help>If the "soft" option is given, the albedo has a value different according to snow (or no snow) on the ground</help>
+			  </parameter>
+			  <help>This implements the correction described in (Reina Nakamura, 2005) with an albedo dependency as introduced in (Huwald, 2009)</help>
+			</option>
+
+			<option label="Add an offset" value="add" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="offset:" value="0." type="decimal" />
+			  </parameter>
+			  <help>This adds a given offset to the data.</help>
+			</option>
+
+			<option label="Multiply by a factor" value="mult" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="factor:" value="1." type="decimal" />
+			  </parameter>
+			  <help>This multiplies the data by a given factor.</help>
+			</option>
+
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+	<!-- 1D Interpolation -->
+	<parameter key="WINDOW_SIZE" type="integer+" minimum="1" default="43200">
+		<section name="Interpolations1D" />
+		<help>Affects resampling: expresses (in seconds) how far a valid point can be
+		searched for when re-interpolating a missing value</help>
+	</parameter>
+
+	<parameter key="Add/Remove 1D Interpolation" type="selector">
+		<section name="Interpolations1D" />
+
+		<parameter key="%::resample" type="alternative" template="true">
+			<section name="Interpolations1D" />
+			<option label="No Interpolation" value="none" type="string" />
+			<option label="Nearest Neighbour" value="nearest_neighbour" type="string" />
+			<option label="Linear" value="linear" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="extrapolate" type="choice" />
+			    <help>
+			      If "extrapolate" is added, then data *outside* of the original date range can be interpolated.
+			      Otherwise, a data point will only be calculated between the original date range.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+			<option label="Accumulate" value="accumulate" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="strict" type="choice" />
+			    <option label="Seconds:" value="900" type="integer" minimum="1" />
+			    <help>Accumulation period (in seconds). This must usually match the model time step. if enabling "strict", nodatas will propagate (ie. a single nodata in the input will force the re-accumulated value to be nodata). Otherwise, all valid values are aggregated and only pure nodata intervals produce a nodata in the output.</help>
+			  </parameter>
+			  <help>Accumulation over a user given period (filter argument, in seconds -
+			  should coincide with your calculation step!).</help>
+			</option>
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+	<!-- 2D Interpolation -->
+	<parameter key="Add/Remove 2D Interpolation" type="selector">
+		<section name="Interpolations2D" />
+
+		<parameter key="%::algorithms" type="choice" template="true">
+			<section name="Interpolations2D" />
+			<option value="STD_PRESS" type="choice">
+				<help>Generate a standard atmosphere pressure as a function of the cell's elevation</help>
+			</option>
+			<option value="CST" type="choice">
+				<help>Fill the grid with the average over all the stations</help>
+			</option>
+			<option value="CST_LAPSE" type="choice">
+			  <parameter key="%::cst_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Detrend the measured data, fill the grid with the average over all the stations, reapply the elevation trend</help>
+			</option>
+			<option value="IDW" type="choice">
+				<help>Inverse Distance Weighted average</help>
+			</option>
+			<option value="IDW_LAPSE" type="choice">
+			  <parameter key="%::idw_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Detrend the measured data, apply Inverse Distance Weighted average, reapply elevation trend</help>
+			</option>
+			<option value="LIDW_LAPSE" type="choice">
+			  <parameter key="%::lidw_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Same as IDW_LAPSE, but only considering a given number of neighboring stations</help>
+			</option>
+			<option value="RH" type="choice">
+				<help>Computes the dew point temperature, distribute it with IDW_LAPSE, recompute RH at each pixel</help>
+			</option>
+			<option value="ILWR" type="choice">
+				<help>Compute emissivity, distribute it with IDW_LAPSE, recompute ILWR at each pixel</help>
+			</option>
+			<option value="WIND_CURV" type="choice">
+				<help>Distribute wind velocity with IDW_LAPSE, then apply correction factors as a function of local slope and curvature</help>
+			</option>
+			<option value="HNW_SNOW" type="choice">
+				<parameter key="%::hnw_snow" type="combination">
+				<option value="IDW_LAPSE" type="dropdown">
+					<option value="CST" type="string" />
+					<option value="CST_LAPSE" type="string" />
+					<option value="IDW" type="string" />
+					<option value="IDW_LAPSE" type="string" />
+					<option value="ODKRIG" type="string" />
+				</option>
+				<help>Base algorithm (do not forget to add the options for the base algorithm)</help>
+				</parameter>
+				<help>Distribute precipitation with a base algorithm (IDW_LAPSE by default), then reduce/remove precipitation on
+				steep slopes and correct with the local curvature. This is to simulate snow redistribution processes.</help>
+			</option>
+			<option value="USER" type="choice">
+			  <parameter key="%::user" type="path" optional="false"/>
+			  <help>User provided grids, named as {numeric date}_{capitalized meteo parameter}.asc</help>
+			</option>
+			<option value="ODKRIG" type="choice">
+			  <parameter key="%::odkrig" type="combination">
+			  	<option value="" type="dropdown">
+					<option value="LINVARIO" type="string" />
+					<option value="EXPVARIO" type="string" />
+					<option value="SPHERICVARIO" type="string" />
+					<option value="RATQUADVARIO" type="string" />
+				</option>
+				<help>Variogram model</help>
+			  </parameter>
+			  <help>Ordinary kriging (EXPERIMENTAL)</help>
+			</option>
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/min_example.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/min_example.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/min_example.xml	(revision 18231)
@@ -0,0 +1,40 @@
+<inishell_config>
+	<parameter key="SOME_PARAMETER" type="string">
+		<section name="section1" />
+		<section name="section2" />
+		<help>
+			This is a parameter that asks for a string value and that is present in
+			both the section "section1" and "section2".
+		</help>
+	</parameter>
+	
+	<parameter key="NESTED_PARAMETERS" type="alternative" optional="false">
+		<section name="section1" />
+		<option value="NONE" type="string" />
+		<option value="ONE" type="string">
+			<parameter key="SOME_INTEGER" type="integer" 
+				minimum="-1" maximum="10" default="2">
+				<help>
+					The value for this parameter may be an integer between -1 and 10.
+					The default value is 2.
+					The user may use the + and - buttons to increment/decrement 
+					the number or type the number into the text field.</help>
+				</parameter>
+		</option>
+		<option value="TWO" type="string">
+			<reference name="a_group_that_can_be_referenced" />
+			<help>Here is a reference to two parameters.</help>
+		</option>
+		<help>
+			This parameter belongs to section1. 
+			When the "null" option is selected, the dropdown menu appears
+			red because this parameter is non-optional.
+			When the value "ONE" is selected a nested parameter "SOME_INTEGER" appears. 
+		</help>
+	</parameter>
+	
+	<parametergroup name="a_group_that_can_be_referenced">
+		<parameter key="SOME_FILE" type="file" />
+		<parameter key="A_PATH" type="path" />
+	</parametergroup>
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/snowpack_config.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/snowpack_config.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/doc/examples/snowpack_config.xml	(revision 18231)
@@ -0,0 +1,1084 @@
+<inishell_config application="SNOWPACK">
+	<!-- <include path="doc/examples/meteoio_config.xml" /> -->
+
+	<!-- General Parameters -->
+	<parameter key="BUFF_CHUNK_SIZE" type="integer" default="30">
+		<section name="general" />
+		<help>Size in days of a chunk of data to read at once.</help>
+	</parameter>
+
+	<parameter key="BUFF_BEFORE" type="decimal" default="1.5">
+		<section name="general" />
+		<help>Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the
+		beginning of the buffer (therefore, it takes a value in days).</help>
+	</parameter>
+
+	<!-- Coordinate systems, time zones -->
+	<parameter key="COORDSYS" type="alternative" optional="false">
+		<section name="input" />
+		<section name="output" />
+		<option value="CH1903" type="string">
+			<help>coordinates in the Swiss Grid &lt;a href="http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf"&gt;http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UTM" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the zone with the zone letter (for example, 32T)</help>
+			</parameter>
+			<help>UTM coordinates, see &lt;a href="http://www.oc.nps.edu/oc2902w/maps/utmups.pdf"&gt;http://www.oc.nps.edu/oc2902w/maps/utmups.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UPS" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the hemisphere (either N or S)</help>
+			</parameter>
+			<help>Universal Polar Stereographic coordinates, see &lt;a href="https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system"&gt;https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system&lt;/a&gt;</help>
+		</option>
+		<option value="PROJ4" type="string">
+			<parameter key="COORDPARAM" type="string" optional="false" />
+			<help>external library: see &lt;a href="http://trac.osgeo.org/proj/"&gt;http://trac.osgeo.org/proj/&lt;/a&gt;</help>
+		</option>
+		<option value="LOCAL"  type="string">
+			<help>uses the horizontal and vertical distance from a reference point</help>
+		</option>
+		<help>coordinate system</help>
+	</parameter>
+
+	<parameter key="TIME_ZONE" type="integer+" default="+1" maximum="14" minimum="-12" optional="false">
+		<section name="input" />
+		<section name="output" />
+	</parameter>
+
+	<!-- Datatypes: Meteo Data -->
+	<frame key="meteo_frame" label="Meteorological Data">
+	<section name="input"/>
+	<parameter key="METEO" type="alternative" optional="false">
+		<section name="input" />
+
+		<option value="A3D" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="BORMA" type="string">
+			<section name="input" />
+			<reference name="BORMA" />
+		</option>
+		<option value="COSMO" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="GEOTOP" type="string">
+			<section name="input" />
+			<reference name="GEOTOP_IN" />
+		</option>
+		<option value="GRIB" type="string">
+			<section name="input" />
+			<reference name="GRIB_METEO" />
+		</option>
+		<option value="GSN" type="string">
+			<section name="input" />
+			<reference name="GSN" />
+		</option>
+		<option value="IMIS" type="string">
+			<section name="input" />
+			<reference name="IMIS" />
+		</option>
+		<option value="SMET" type="string">
+			<section name="input" />
+			<reference name="SMET_IN" />
+		</option>
+		<option value="SNOWPACK" type="string">
+			<section name="input" />
+			<reference name="SNIO_IN" />
+		</option>
+
+		<help>plugin for METEO data </help>
+	</parameter>
+	<parameter key="Add Meteo parameter copy" type="selector">
+		<section name="input"/>
+		<parameter key="COPY::%" type="string" optional="false" template="true">
+			<help>The name of the parameter to copy (e.g. TA, RH, VW, ISWR, etc)</help>
+		</parameter>
+		<help>Copy a meteo parameter into a new one (you should not need this)</help>
+	</parameter>
+	</frame>
+
+	<!-- Extra Input Parameters -->
+	<frame key="snow_frame" label="Initial Snow Profiles">
+	<section name="input"/>
+	<parameter key="SNOWPATH" type="path" default="./current_snow">
+		<section name="input" />
+		<help>Path to the land surface and snow input parameters</help>
+	</parameter>
+	<parameter key="SNOW" type="alternative" default="SMET" optional="true">
+		<section name="input" />
+		<option value="SNOWPACK" type="string" />
+		<option value="SMET" type="string" />
+		<help>Plugin to use for reading SNO data</help>
+	</parameter>
+	<parameter key="SNOWFILE#" type="file" counter="1" optional="false">
+		<section name="input" />
+		<help>file name for the initial profile for station number #</help>
+	</parameter>
+	<!-- <parameter key="NUMBER_OF_SOLUTES" type="integer" default="0" minimum="0" maximum="0">
+		<section name="input" />
+		<help>SNOWPACK can transport an arbitrary number of trace components in its snow and water phases [special use]</help>
+	</parameter> -->
+	</frame>
+
+	<!-- Output Parameters -->
+	<parameter key="METEOPATH" type="path" default="./output">
+		<section name="output" />
+		<help>Path to the outputs (this path MUST exist, it won't be created)</help>
+	</parameter>
+	<parameter key="EXPERIMENT" type="string" optional="false">
+		<section name="output" />
+		<help>Option to give an additional simulation specific output name to the run in addition to "STATION_NAME")</help>
+	</parameter>
+	<frame key="TS_frame" label="Time Series">
+	<section name="output"/>
+	<parameter key="TS_WRITE" type="alternative" optional="false">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write meteo data out?</help>
+	</parameter>
+	<parameter key="TS_START" type="decimal" default="0" minimum="0" maximum="360">
+		<section name="output" />
+		<help>When to start writing meteo data out (offset, in days)</help>
+	</parameter>
+	<parameter key="TS_DAYS_BETWEEN" type="decimal" default="4.1666e-2" minimum="0" maximum="360">
+		<section name="output" />
+		<help>How often to write meteo data out (in days: 3 hours=.125, 1 hour=4.1666e-2)</help>
+	</parameter>
+	<parameter key="AVGSUM_TIME_SERIES" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>If AVGSUM_TIME_SERIES is set, mean fluxes and cumulated masses since last dump are written, else current energy fluxes, cumulated masses over last COMPUTATION_STEP_LENGTH (recommended setting in operational mode).</help>
+	</parameter>
+	<parameter key="CUMSUM_MASS" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>If CUMSUM_MASS is set, current value of cumulated masses since begin of run are dumped. Precipitations (rain and snow, rain) are always dumped as rates (kg m-2 h-1).</help>
+	</parameter>
+	<parameter key="PRECIP_RATES" type="alternative" optional="true" default="TRUE">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write precipitation as rates (kg m-2 h-1, default) or as sums over the output time step. Please note that the units label in the output file and in SN_GUI &lt;b&gt;will remain kg m-2 h-1&lt;/b&gt; and will therefore not match sums.</help>
+	</parameter>
+	</frame>
+	<frame key="profiles_frame" label="Snow Profiles">
+	<section name="output"/>
+	<parameter key="PROFILE" type="alternative" default="ASCII" optional="false">
+		<section name="output" />
+		<option value="ASCII" type="string" />
+		<option value="IMIS" type="string" />
+		<option value="ASCII IMIS" type="string" />
+		<help>How to write the profiles (default: ASCII)</help>
+	</parameter>
+	<parameter key="PROF_WRITE" type="alternative" optional="false">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write profile data out?</help>
+	</parameter>
+	<parameter key="PROF_START" type="decimal" default="0" minimum="0" maximum="360">
+		<section name="output" />
+		<help>When to start writing profile data out (offset, in days)</help>
+	</parameter>
+	<parameter key="PROF_DAYS_BETWEEN" type="decimal" default="4.1666e-2" minimum="0" maximum="360">
+		<section name="output" />
+		<help>How often to write profile data out (in days: 3 hours=.125, 1 hour=4.1666e-2)</help>
+	</parameter>
+	<parameter key="HARDNESS_IN_NEWTON" type="alternative" default="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write the hand hardness in newtons (default) or as index</help>
+	</parameter>
+	<parameter key="CLASSIFY_PROFILE" type="alternative" default="false">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Classify the profile (default=false)? This is according to Schweizer, J. and M. Luetschg, &lt;i&gt;Characteristics of human-triggered avalanches&lt;/i&gt;, 2001, Cold Reg. Sci. Technol. &lt;b&gt;33&lt;/b&gt;(2-3)</help>
+	</parameter>
+	</frame>
+	<frame key="sno_frame" label="Status files">
+	<section name="output"/>
+	<parameter key="SNOW" type="alternative" default="SMET" optional="true">
+		<section name="output" />
+		<option value="SNOWPACK" type="string" />
+		<option value="SMET" type="string" />
+		<help>Plugin to use for reading SNO data</help>
+	</parameter>
+	<parameter key="BACKUP_DAYS_BETWEEN" type="decimal" default="365" minimum="0">
+		<section name="output" />
+		<help>Dump snow files every BACKUP_DAYS_BETWEEN days</help>
+	</parameter>
+	<parameter key="FIRST_BACKUP" type="decimal" default="400" minimum="0">
+		<section name="output" />
+		<help>First dump of sno files happens at end of run or after FIRST_BACKUP days, whichever happens first</help>
+	</parameter>
+	</frame>
+
+	<frame key="switch_frame" label="Outputs Selection">
+	<section name="output"/>
+	<parameter key="OUT_CANOPY" type="alternative" default="FALSE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write canopy data out? To be set to TRUE only if CANOPY=TRUE</help>
+	</parameter>
+	<parameter key="OUT_HAZ" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write hazard data out? This must be FALSE for Alpine3D</help>
+	</parameter>
+	<parameter key="OUT_HEAT" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write turbulent fluxes out?</help>
+	</parameter>
+	<parameter key="OUT_T" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write snow/soil temperatures out?</help>
+	</parameter>
+	<!-- <parameter key="OUT_LOAD" type="alternative" default="FALSE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write solutes load data out?</help>
+	</parameter> -->
+	<parameter key="OUT_LW" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write long wave radiation out?</help>
+	</parameter>
+	<parameter key="OUT_SW" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write short wave radiation out?</help>
+	</parameter>
+	<parameter key="OUT_MASS" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write mass balance terms out?</help>
+	</parameter>
+	<parameter key="OUT_METEO" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write meteo parameters out?</help>
+	</parameter>
+	<parameter key="OUT_STAB" type="alternative" default="TRUE" optional="true">
+		<section name="output" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Write stability parameters out?</help>
+	</parameter>
+	</frame>
+
+
+	<!-- Snowpack Parameters -->
+	<frame key="sn_parameters_frame" label="Model Parameters">
+	<section name="Snowpack"/>
+	<parameter key="CALCULATION_STEP_LENGTH" type="decimal" default="15" minimum="5" maximum="180">
+		<section name="Snowpack" />
+		<help>Internal time step (in minutes) used for model simulation. Please note that this MUST be the same as HNW::accumulate (the latter being in seconds) if re-acumulating precipitation, otherwise it would lead to wrong results.</help>
+	</parameter>
+	<parameter key="ROUGHNESS_LENGTH" type="decimal" default="0.002">
+		<section name="Snowpack" />
+		<help>Aerodynamic roughness length as a parameter for the Monin-Obukhov bulk formulation; A typical value for complex terrain is 0.01 m and for snow covered flat sites 0.001 m.</help>
+	</parameter>
+	<parameter key="HEIGHT_OF_METEO_VALUES" type="decimal" default="5.0">
+		<section name="Snowpack" />
+		<help>The instrument height (or model layer height) for meteorological input data except for wind, which may be at a different height; note that height is above ground for a standard SNOWPACK application but above surface (snow or ground) for Alpine3D applications.</help>
+	</parameter>
+	<parameter key="HEIGHT_OF_WIND_VALUE" type="decimal" default="5.0">
+		<section name="Snowpack" />
+		<help>The instrument height (or model layer height) for wind input data; note that height is above ground for a standard SNOWPACK application but above surface (snow or ground) for Alpine3D applications</help>
+	</parameter>
+	</frame>
+	<frame key="sn_switch_frame" label="Models Selection">
+	<section name="Snowpack"/>
+	<parameter key="ENFORCE_MEASURED_SNOW_HEIGHTS" type="alternative" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Input mode by which a measurement of snow depth is used to drive the snow cover mass balance</help>
+	</parameter>
+	<parameter key="SW_MODE" type="integer" default="0" minimum="0" maximum="2" optional="false">
+		<section name="Snowpack" />
+		<help>Define the shortwave radiation input: &lt;ol&gt; &lt;li value="0"&gt;Incoming shortwave radiation is measured and albedo estimated by the model;&lt;/li&gt; &lt;li&gt;Reflected shortwave radiation is available as input and albedo is estimated by the model (IMIS standard);&lt;/li&gt; &lt;li&gt;Incoming and reflected shortwave radiation are both measured and the albedo is estimated from both measurements subject to plausibility checks.&lt;/li&gt; &lt;/ol&gt;</help>
+	</parameter>
+	<parameter key="NEUTRAL" type="integer" default="1" minimum="-1" maximum="1" optional="false">
+		<section name="Snowpack" />
+		<help>Select the atmospheric stability correction model:&lt;ol&gt; &lt;li value="-1"&gt; use a simplified Richardson number stability correction;&lt;/li&gt; &lt;li&gt;assume standard Monin-Obukhov bulk formulation for surface exchange iteration with Paulson, Stearns and Weidner (can be used with BC_CHANGE=0); &lt;/li&gt; &lt;li&gt; force Monin-Obukhov formulation to assume neutral conditions regardless of the actual stratification; it has been shown to work well in complex terrain settings. It should be used with BC_CHANGE=1, i.e., Dirichlet bc but also is recommended with Neumann b.c., i.e., BC_CHANGE=0.&lt;/li&gt; &lt;/ol&gt;</help>
+	</parameter>
+	<parameter key="CANOPY" type="alternative" default="FALSE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Switch to tell the model that canopy is present (note that Canopy parameters should then be provided in the *.sno file)</help>
+	</parameter>
+	<parameter key="MEAS_TSS" type="alternative" default="TRUE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>A measured surface temperature is available and can be reliably used for various consistency tests (it needs to be set to true if enabling CHANGE_BC).</help>
+	</parameter>
+	<parameter key="CHANGE_BC" type="alternative" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Use measured surface temperature as Dirichlet temperature BC for sub-freezing snowpacks and switch to Neumann only for melting snowpacks. If set to false, assumes Neumann boundary conditions.</help>
+	</parameter>
+	<parameter key="THRESH_CHANGE_BC" type="decimal" default="-1.3">
+		<section name="Snowpack" />
+		<help>Threshold value (small number below freezing), which switches from Dirichlet to Neumann BCs if CHANGE_BC is selected</help>
+	</parameter>
+	</frame>
+	<frame key="sn_slopes_frame" label="Virtual slopes">
+	<section name="Snowpack"/>
+	<parameter key="NUMBER_SLOPES" type="alternative" default="1" optional="false">
+		<section name="Snowpack" />
+		<option value="1" type="string" />
+		<option value="5" type="string" />
+		<option value="3" type="string" />
+		<option value="9" type="string" />
+		<help>Based on meteorological input from a (flat field) automatic station or numerical weather model, up to 8 expositions can be calculated in addition to the flat field if the corresponding *.sno files are provided. For example, if you provide a flat field *.snow file (mandatory), which is named KLO3.sno and you want 4 slopes to be calculated the corresponding slope files should be named KLO21.sno, …,KLO24.sno</help>
+	</parameter>
+	<parameter key="INCOMING_LONGWAVE" type="alternative" default="FALSE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Use the provided incoming long wave on the virtual slopes?</help>
+	</parameter>
+	<parameter key="SNOW_REDISTRIBUTION" type="alternative" default="FALSE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Specifies if redistribution of snow is allowed from (upwind) expositions to lee slopes. In case just the flat field is calculated, snow erosion is enabled but only for "ENFORCE_MEASURED_SNOW_HEIGHTS".</help>
+	</parameter>
+	</frame>
+	<frame key="soil_frame" label="Soil Modeling">
+	<section name="Snowpack"/>
+	<parameter key="SNP_SOIL" type="alternative" default="TRUE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Soil layers as defined by the *.sno files are included in the simulation</help>
+	</parameter>
+	<parameter key="SOIL_FLUX" type="alternative" default="FALSE" optional="false">
+		<section name="Snowpack" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Assume that the lower temperature boundary condition is given by GEO_HEAT (Neumann) and not by a measured temperature</help>
+	</parameter>
+	<parameter key="GEO_HEAT" type="decimal" default="0.06">
+		<section name="Snowpack" />
+		<help>Constant geothermal heat flux at great) depth W m-2): Lower flux boundary condition for temperature equation if BC is Neumann</help>
+	</parameter>
+	</frame>
+
+
+	<!-- SnowpackAdvanced Parameters -->
+	<parameter key="ASSUME_RESPONSIBILITY" type="alternative" default="AGREE">
+		<section name="SnowpackAdvanced" />
+		<option value="AGREE" type="string" />
+		<help>&lt;font color="FF0000"&gt;The keys in this section deeply affect the operation of the SNOWPACK model. This could lead to unexpected behavior or surprising results. If you are not an experienced Snowpack user, please do NOT change any keys below!&lt;/font&gt;</help>
+	</parameter>
+	<parameter key="VARIANT" type="alternative">
+		<section name="SnowpackAdvanced" />
+		<option value="DEFAULT" type="string" />
+		<option value="JAPAN" type="string" />
+		<option value="ANTARTICA" type="string" />
+		<!-- <option value="CALIBRATION" type="string" /> -->
+		<help>variant selection (includes a choice of specific models)</help>
+	</parameter>
+	<!-- <parameter key="RESEARCH" type="alternative" optional="true" default="TRUE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>research_mode</help>
+	</parameter> -->
+	<!-- <parameter key="NUMBER_FIXED_RATES" type="integer" default="0">
+		<section name="SnowpackAdvanced" />
+		<help>number_fixed_rates</help>
+	</parameter> -->
+	<parameter key="PERP_TO_SLOPE" type="alternative" optional="true" default="FALSE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>perp_to_slope</help>
+	</parameter>
+	<frame key="wind_frame" label="Wind Handling">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="PREVAILING_WIND_DIR" type="decimal" default="0">
+		<section name="SnowpackAdvanced" />
+		<help>Shifts the origin of the wind rose for snow redistribution and slope simulations: e.g. choose 45° to have NE/SE/SW/NW</help>
+	</parameter>
+	<parameter key="WIND_SCALING_FACTOR" type="decimal" default="1.0" minimum="0" maximum="2">
+		<section name="SnowpackAdvanced" />
+		<help>Scaling factor to apply to wind values in case of drifting snow</help>
+	</parameter>
+	</frame>
+	<frame key="hnw_frame" label="Precipitation Handling">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="FORCE_RH_WATER" type="alternative" optional="true">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Tell the model that relative humidity values are with respect to water regardless of the temperature</help>
+	</parameter>
+	<parameter key="THRESH_RAIN" type="decimal" default="1.2">
+		<section name="SnowpackAdvanced" />
+		<help>Temperature threshold for rain/snow transition</help>
+	</parameter>
+	<parameter key="THRESH_RH" type="decimal" default="0.5">
+		<section name="SnowpackAdvanced" />
+		<help>If ENFORCE_MEASURED_SNOW_HEIGHTS, relative humidity threshold for precipitation to occur</help>
+	</parameter>
+	<parameter key="THRESH_DT_AIR_SNOW" type="decimal" default="3.0">
+		<section name="SnowpackAdvanced" />
+		<help>If ENFORCE_MEASURED_SNOW_HEIGHTS, (TA-TSS) threshold for precipitation to occur</help>
+	</parameter>
+	</frame>
+	<frame key="hoar_frame" label="Hoar Handling">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="HOAR_THRESH_RH" type="decimal" default="0.97">
+		<section name="SnowpackAdvanced" />
+		<help>Relative humidity threshold above which no surface hoar is allowed to form (because at very high humidity, typically no hoar crystals can form)</help>
+	</parameter>
+	<parameter key="HOAR_THRESH_VW" type="decimal" default="3.5">
+		<section name="SnowpackAdvanced" />
+		<help>Wind speed threshold above which no surface hoar is allowed to form (because it will drift away)</help>
+	</parameter>
+	<parameter key="HOAR_DENSITY_BURIED" type="decimal" default="125.0">
+		<section name="SnowpackAdvanced" />
+		<help>Define the initial density for surface hoar at the time it gets buried by new snow</help>
+	</parameter>
+	<parameter key="HOAR_MIN_SIZE_BURIED" type="decimal" default="2.0">
+		<section name="SnowpackAdvanced" />
+		<help>Define a threshold below which any traces of surface hoar will not be given a separate hoar layer when buried.</help>
+	</parameter>
+	<parameter key="HOAR_DENSITY_SURF" type="decimal" default="100.0">
+		<section name="SnowpackAdvanced" />
+		<help>Assumed density of surface hoar while exposed at the surface and not buried</help>
+	</parameter>
+	</frame>
+	<frame key="temps_frame" label="Temperatures Handling">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="FIXED_POSITIONS" type="string" default="">
+		<section name="SnowpackAdvanced" />
+		<help>positions of temperatur sensors in snow or soil: positive values refer to heigths measured from the ground surface (snow only), negative values refer to depths measured from either the ground surface or the snow surface in case no soil layers are present. A sensor must at least be covered by MIN_DEPTH_SUBSURF (m) snow for its temperature to be output.</help>
+	</parameter>
+	<!-- <parameter key="MAX_NUMBER_MEAS_TEMPERATURES" type="integer" default="5">
+		<section name="SnowpackAdvanced" />
+		<help></help>
+	</parameter> -->
+	<parameter key="MIN_DEPTH_SUBSURF" type="decimal" default="0.07">
+		<section name="SnowpackAdvanced" />
+		<help>Minimum snow depth above a temperature sensor to accept the measurement</help>
+	</parameter>
+	<parameter key="T_CRAZY_MIN" type="decimal" default="210.">
+		<section name="SnowpackAdvanced" />
+		<help>If you go to Antarctica or the tropics you may expect different reasonable temperatures</help>
+	</parameter>
+	<parameter key="T_CRAZY_MAX" type="decimal" default="340.">
+		<section name="SnowpackAdvanced" />
+		<help>If you go to Antarctica or the tropics you may expect different reasonable temperatures</help>
+	</parameter>
+	</frame>
+	<frame key="sn_models_frame" label="Models Selection">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="HN_DENSITY_MODEL" type="alternative" default="LEHNING_NEW">
+		<section name="SnowpackAdvanced" />
+		<option value="LEHNING_NEW" type="string" />
+		<option value="ZWART" type="string" />
+		<option value="BELLAIRE" type="string" />
+		<option value="LEHNING_OLD" type="string" />
+		<option value="PAHAUT" type="string" />
+		<help>Choice of new snow density model (diverse statistical models)</help>
+	</parameter>
+	<parameter key="HN_DENSITY" type="string" default="PARAMETERIZED">
+		<section name="SnowpackAdvanced" />
+		<help>Fixed value to be used as new snow density if a constant density model is chosen, otherwise the choices are "PARAMETERIZED" "EVENT" "MEASURED"</help>
+	</parameter>
+	<parameter key="METAMORPHISM_MODEL" type="alternative">
+		<section name="SnowpackAdvanced" />
+		<option value="DEFAULT" type="string" />
+		<option value="NIED" type="string" />
+		<help>metamorphism_model</help>
+	</parameter>
+	<parameter key="NEW_SNOW_GRAIN_RAD" type="decimal" default="0.15">
+		<section name="SnowpackAdvanced" />
+		<help>new_snow_grain_rad</help>
+	</parameter>
+	<parameter key="STRENGTH_MODEL" type="alternative">
+		<section name="SnowpackAdvanced" />
+		<option value="DEFAULT" type="string" />
+		<option value="NIED" type="string" />
+		<help>strength_model</help>
+	</parameter>
+	<parameter key="VISCOSITY_MODEL" type="alternative">
+		<section name="SnowpackAdvanced" />
+		<option value="DEFAULT" type="string" />
+		<option value="NIED" type="string" />
+		<help>viscosity_model</help>
+	</parameter>
+	<parameter key="HARDNESS_MODEL" type="alternative">
+		<section name="SnowpackAdvanced" />
+		<option value="MONTI" type="string" />
+		<option value="BELLAIRE" type="string" />
+		<option value="ASARC" type="string" />
+		<help>hardness_model</help>
+	</parameter>
+	<parameter key="DOORSCHOT" type="alternative" optional="true" default="FALSE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Choose the Doorschot saltation model over the simple Sorenson parameterization</help>
+	</parameter>
+	<parameter key="MULTISTREAM" type="alternative" optional="true">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Select a multi stream model for shortwave radiation penetration into the snow cover</help>
+	</parameter>
+	<parameter key="FIXED_ALBEDO" type="alternative" optional="true">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Force the model to work with a fixed albedo</help>
+	</parameter>
+	<!-- <parameter key="SURFACECODE" type="alternative" optional="true">
+		<section name="SnowpackAdvanced" />
+		<option value="NEUMANN_BC" type="string" />
+		<option value="DIRICHLET_BC" type="string" />
+		<help>Select the boundary conditions to use</help>
+	</parameter> -->
+	</frame>
+	<frame key="sn_extra_frame" label="Extra Models Selection">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="DETECT_GRASS" type="alternative" optional="true" default="TRUE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Identify grass growing under the snow height sensor. This usually works well but might sometimes lead to problems</help>
+	</parameter>
+	<parameter key="PLASTIC" type="alternative" optional="true" default="FALSE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Switch to tell the model that a impermeable layer should be simulated on top of some snow or ice: this requires that the *.sno file contains this layer, which is characterized via the soil parameters; the option has successfully been used to simulate snow and ice protection using geo-textiles and saw dust.</help>
+	</parameter>
+	<parameter key="JAM" type="alternative" optional="true" default="FALSE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>If switched on, you can also simulate ponding on impermeable ice surfaces below the snow cover</help>
+	</parameter>
+	<parameter key="WATER_LAYER" type="alternative" optional="true" default="FALSE">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Assuming an impermeable surface such as on a road or on geo-textiles (e.g. for snow farming), a liquid water layer is allowed to form on this surface</help>
+	</parameter>
+	</frame>
+	<frame key="elements_frame" label="Elements Handling">
+	<section name="SnowpackAdvanced"/>
+	<parameter key="HEIGHT_NEW_ELEM" type="decimal" default="0.02">
+		<section name="SnowpackAdvanced" />
+		<help>Standard size of a new element added to the stack of elements (layers) during snowfall events</help>
+	</parameter>
+	<parameter key="MINIMUM_L_ELEMENT" type="decimal" default="0">
+		<section name="SnowpackAdvanced" />
+		<help>Threshold value for enforcing the layer to be merged with the layer above or below</help>
+	</parameter>
+	<parameter key="COMBINE_ELEMENTS" type="alternative" optional="true">
+		<section name="SnowpackAdvanced" />
+		<option value="TRUE" type="string" />
+		<option value="FALSE" type="string" />
+		<help>Combine neighboring elements based on a set of similarity conditions which are hard-coded</help>
+	</parameter>
+	</frame>
+
+	<!--Parameter group for list of stations -->
+	<parametergroup name="stationgroup_files">
+		<parameter key="STATION#" type="file" counter="1" optional="false">
+			<help>filename for station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_names">
+		<parameter key="STATION#" type="string" counter="1" optional="false">
+			<help>station id for the given station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_pos">
+		<parameter key="STATION#" type="string" counter="1">
+			<help>Coordinates are given as "lat lon" or "xcoord ycoord epsg_code"</help>
+		</parameter>
+	</parametergroup>
+
+	<!-- Plugins for Meteo Data-->
+	<parametergroup name="BORMA">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the xml files</help>
+		</parameter>
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="IMIS">
+		<parameter key="DBNAME" type="string" optional="false">
+			<help>database name, as provided by your database administrator</help>
+		</parameter>
+		<parameter key="DBUSER" type="string" optional="false">
+			<help>database user name</help>
+		</parameter>
+		<parameter key="DBPASS" type="string" optional="false">
+			<help>database password associated with the user name</help>
+		</parameter>
+		<parameter key="USEANETZ" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: use ANETZ stations to provide precipitations for normal IMIS stations.
+		  Each IMIS station is associated with one or two ANETZ stations and does a weighted
+		  average to get what should be its local precipitations</help>
+		</parameter>
+		<parameter key="USE_IMIS_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: if set to false (default), all IMIS precipitation will be deleted (since IMIS stations don't have heated rain gauges, their precipitation measurements are not good in winter conditions). If set to true, it is strongly advised to use a FilterHNWMelt filter to detect snow melting in the rain gauge and perform winter conditions detection in the application.</help>
+		</parameter>
+		<parameter key="USE_SNOWPACK_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>if set to true, the SNOWPACK simulated Snow Water Equivalent from the database will be used to compute HNW. Data gaps greater than 3 hours on SWE will lead to unchanged hnw while all data that can properly be computed will overwrite hnw. (default=false)</help>
+		</parameter>
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="GRIB_METEO">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the grib files</help>
+		</parameter>
+		<parameter key="METEOEXT" type="string" optional="true">
+			<help>grib file extension, or none for no file extension (default: .grb)</help>
+		</parameter>
+
+		<reference name="stationgroup_pos" />
+	</parametergroup>
+
+	<parametergroup name="GEOTOP_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the data files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="false">
+			<help>absolute filename of the geotop.inpts file</help>
+		</parameter>
+		<parameter key="METEOPREFIX" type="string" optional="true">
+			<help>prefix to append when generating a file name for reading</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GSN">
+		<parameter key="ENDPOINT" type="string" optional="false">
+			<help>webserver running GSN with its port number and full path. For example:
+			http://montblanc.slf.ch:22001/services/A3DWebService</help>
+		</parameter>
+		<parameter key="PROXY" type="string" optional="true">
+			<help>Should the connection go through a proxy? This is useful for servers
+			filtering on domains but usually not necessary.</help>
+		</parameter>
+		<parameter key="PROXYPORT" type="string" optional="true" />
+		<parameter key="PROXYUSER" type="string" optional="true" />
+		<parameter key="PROXYPASS" type="string" optional="true" />
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="SMET_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the smet files</help>
+		</parameter>
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<parametergroup name="SNIO_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the SNOWPACK files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="true">
+			<help>filename of the meta data file (in METEOPATH)</help>
+		</parameter>
+		<parameter key="NUMBER_MEAS_TEMPERATURES" type="integer+" minimum="0" default="0">
+		  <help>the number of measured snow temperatures that are provided</help>
+		</parameter>
+		<parameter key="NUMBER_OF_SOLUTES" type="integer+" minimum="0" default="0">
+		  <help>the number of solutes for which input data are provided</help>
+		</parameter>
+
+		<parameter key="RSWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="ISWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="VW_DRIFT" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: wind velocity to use for blowing and drifting snow is provided</help>
+		</parameter>
+		<parameter key="RHO_HN" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: measured new snow density is provided</help>
+		</parameter>
+
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<!-- Meteo Parameters for Filters, resampling, spatial interpolations-->
+	<parametergroup name="METEOIOPARAMETERS">
+		<option value="TA"/>
+		<option value="RH"/>
+		<option value="VW"/>
+		<option value="DW"/>
+		<option value="VW_MAX"/>
+		<option value="ISWR"/>
+		<option value="RSWR"/>
+		<option value="ILWR"/>
+		<option value="HS"/>
+		<option value="HNW"/>
+		<option value="TSG"/>
+		<option value="TSS"/>
+		<option value="P"/>
+	</parametergroup>
+
+	<!-- Filters -->
+	<parameter key="Add/Remove Filter" type="selector">
+		<section name="filters" />
+
+		<parameter key="%::filter#" type="alternative" counter="1" template="true">
+			<section name="filters" />
+
+			<option label="MeanAvg" value="mean_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+
+
+			<option label="MedianAvg" value="median_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="decimal" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median average processing. The median average filter returns the median value of all values within a user given time window.</help>
+			</option>
+
+			<option label="Std Deviation Filter" value="std_dev" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Standard deviation filter. Values outside of mean ± 2 std_dev are rejected.</help>
+			</option>
+
+			<option label="MAD" value="mad" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median Absolute Deviation. Values outside of median ± 3 σ_MAD are rejected. &lt;br&gt;
+			  See http://en.wikipedia.org/wiki/Median_absolute_deviation for more information.</help>
+			</option>
+
+			<option label="Tukey 53H Filter" value="Tukey" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      The keyword "soft" maybe added, if the window position is allowed to be adjusted to the data present.
+			      The two arguments may be preceded by the keywords "left", "center" or "right", indicating the window position.
+			    </help>
+			  </parameter>
+			  <help>Tukey 53H method A smooth time sequence is generated from the median, substracted from the original signal and
+			  compared with the standard deviation. see "Despiking Acoustic Doppler Velocimeter Data", Derek G. Goring and Vladimir
+			  L. Nikora, Journal of Hydraulic Engineering, 128, 1, 2002 The deviation factor coeffecient is currently hard-coded as k=1.5. </help>
+			</option>
+
+			<option label="Wind Averaging Filter" value="wind_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Wind vector averaging. This calculates the vector average over a user given time period. Each wind vector
+			  within this period is added and the final sum is normalized by the number of vectors that have been added. </help>
+			</option>
+
+			<option label="Exponential Smoothing" value="exp_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <option label="alpha:" value="0.8" type="decimal" minimum="0" maximum="1"/>
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Alpha needs to be provided as last argument. Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Exponential smooting processing, exponential moving average s_0 = x_0 s_n = alpha*x_(t-1) + (1-alpha)*s_t-1</help>
+			</option>
+
+			<option label="Weighted Moving Average Smoothing" value="wma_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Weighted moving average smoothing such as: WMA = (1*X1 + 2*X2 + ... + n*Xn) / sum_of_weights</help>
+			</option>
+
+			<option label="Min Range Filter" value="min" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data smaller than the min would be
+			    assigned the minimum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Min range filter. Reject all values smaller than the min.</help>
+			</option>
+
+			<option label="Max Range Filter" value="max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be
+			    assigned the maximum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Max range filter. Reject all values greater than the max.</help>
+			</option>
+
+			<option label="MinMax (2 or 4 arguments)" value="min_max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Min adjust to:" value="" type="decimal" />
+			    <option label="Max adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be assigned
+			    the maximum permissible value and all data smaller than the min would be assigned the minimum
+			    permissible value or an optional extra set of two user provided values</help>
+			  </parameter>
+			  <help>Reject all values greater than the max or smaller than the min. &lt;br&gt;</help>
+			</option>
+
+			<option label="Rate Filter (1 argument)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the absolute value of the maximum permissible rate of change (per seconds)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Rate Filter (2 arguments)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Min:" value="0.0" type="decimal" minimum="0" maximum="1" />
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the minimum and maximum permissible rate of change (per second)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Unheated Rain Gauge Filter" value="Unheated_RainGauge" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="RH threshold:" value="0.5" type="decimal" minimum="0" maximum="1" />
+			    <option label="Delta_T threshold:" value="3.0" type="decimal" minimum="0" maximum="20" />
+			  </parameter>
+			  <help>Filters out snow melting in an unheated rain gauge. This filter can ONLY be applied to precipitation. Non-zero measurements are accepted only if they take place when the relative humidity is greater than RH_threshold and (TA-TSS) smaller than Delta_T_threshold, otherwise they get reset to 0. If none of these conditions could be tested (for lack of data), then the precipitation is reset to nodata (or left unchanged if "soft" has been selected).</help>
+			</option>
+
+			<option label="WMO Undercatch Filter" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Gage type" type="dropdown">
+					<option value="Nipher" type="string" />
+					<option value="Tretyakov" type="string" />
+					<option value="US8sh" type="string" />
+					<option value="US8unsh" type="string" />
+					<option value="Hellmann" type="string" />
+					<option value="Hellmannsh" type="string" />
+				</option>
+			  </parameter>
+			  <help>This implements the standard methods for precipitation correction as described in "WMO Solid Precipitation Measurement Intercomparison", B. Goodison, P. Louie and D. Yang, 872, 1998 as well as the overview given by "Literature Study on the Correction of Precipitation Measurements", Annette Wagner, 2009. The correction parameters for the shielded Hellmann gauge (German version) are from "Wind-induced Precipitation Undercatch of the Hellmann Gauges", Daqing Yang et al, Nordic Hydrology, 30, 1999, pp 57-80.</help>
+			</option>
+
+			<option label="WMO Undercatch Filter - simplified" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Kind" type="dropdown">
+					<option value="Cst" type="string" />
+				</option>
+				<option label="Snow factor:" value="1.3" type="decimal" minimum="0" maximum="5" />
+				<option label="Mixed precipitation factor:" value="1.1" type="decimal" minimum="0" maximum="5" />
+			  </parameter>
+			  <help>This applies a constant correction factor to the precipitation, one for pure snow and one for mixed precipitation. The following thresholds are used: pure snow below -2 C; mixed precipitation between -2 and +2 C; pure rain above 2 C. These threshold can be changed (see online documentation).</help>
+			</option>
+
+			<option label="Unventillated temperature sensor" value="Unventilated_T" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="albedo:" value="0.23" type="decimal" />
+			    <option value="soft" type="choice" />
+			    <help>If the "soft" option is given, the albedo has a value different according to snow (or no snow) on the ground</help>
+			  </parameter>
+			  <help>This implements the correction described in (Reina Nakamura, 2005) with an albedo dependency as introduced in (Huwald, 2009)</help>
+			</option>
+
+			<option label="Add an offset" value="add" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="offset:" value="0." type="decimal" />
+			  </parameter>
+			  <help>This adds a given offset to the data.</help>
+			</option>
+
+			<option label="Multiply by a factor" value="mult" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="factor:" value="1." type="decimal" />
+			  </parameter>
+			  <help>This multiplies the data by a given factor.</help>
+			</option>
+
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+	<!-- 1D Interpolation -->
+	<parameter key="WINDOW_SIZE" type="integer+" minimum="1" default="43200">
+		<section name="Interpolations1D" />
+		<help>Affects resampling: expresses (in seconds) how far a valid point can be
+		searched for when re-interpolating a missing value</help>
+	</parameter>
+
+	<parameter key="Add/Remove 1D Interpolation" type="selector">
+		<section name="Interpolations1D" />
+
+		<parameter key="%::resample" type="alternative" template="true">
+			<section name="Interpolations1D" />
+			<option label="No Interpolation" value="none" type="string" />
+			<option label="Nearest Neighbour" value="nearest_neighbour" type="string" />
+			<option label="Linear" value="linear" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="extrapolate" type="choice" />
+			    <help>
+			      If "extrapolate" is added, then data *outside* of the original date range can be interpolated.
+			      Otherwise, a data point will only be calculated between the original date range.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+			<option label="Accumulate" value="accumulate" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="strict" type="choice" />
+			    <option label="Seconds:" value="900" type="integer" minimum="1" />
+			    <help>Accumulation period (in seconds). This must usually match the model time step. if enabling "strict", nodatas will propagate (ie. a single nodata in the input will force the re-accumulated value to be nodata). Otherwise, all valid values are aggregated and only pure nodata intervals produce a nodata in the output.</help>
+			  </parameter>
+			  <help>Accumulation over a user given period (filter argument, in seconds -
+			  should coincide with your calculation step!).</help>
+			</option>
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/inishell.sh
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/inishell.sh	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/inishell.sh	(revision 18231)
@@ -0,0 +1,8 @@
+#/bin/bash
+#This is just the necessary command line to run a jar file
+
+#recover file name: 
+xmlfilename=$1
+
+#call inishell
+java -jar dist/inishell.jar $xmlfilename
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/AlternativePanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/AlternativePanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/AlternativePanel.java	(revision 18231)
@@ -0,0 +1,177 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ItemEvent;
+
+import javax.swing.JComboBox;
+import javax.swing.JOptionPane;
+import java.util.HashMap;
+import javax.swing.*;
+import java.awt.*;
+
+import main.GUI;
+
+import org.w3c.dom.Element;
+
+/**
+ * The AlternativePanel contains a dropdown list with alternatives to choose from.
+ *
+ * @author Thomas Egger
+ *
+ */
+public class AlternativePanel extends OptionPanel {
+
+	private static final long serialVersionUID = 4468480774697888798L;
+	private final JComboBox box;
+
+	private String setKey = null, setValue = null;
+	private boolean doSet = false;
+	private HashMap setMap;
+
+	/**
+	 * Constructor for the AlternativePanel
+	 *
+	 * @param element the <parameter ...> element for which the panel is created.
+	 * @throws GUIBuildException
+	 */
+	public AlternativePanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent);
+
+		box = new JComboBox(labels);
+		box.insertItemAt("", 0);     //Add an empty label
+		box.setVisible(true);
+		box.setSelectedIndex(0);
+		box.addItemListener(this);
+
+		//Issue 263: On OSX the box.setBackground method does not function without this tweak:
+		if (System.getProperty("os.name").equals("Mac OS X")) 
+		    box.setRenderer(new ColorCellRenderer(box.getPreferredSize().width));
+
+		if (!optional) box.setBackground(GUI.WARNING_BACKGROUND_COLOR);
+
+		if (defaultTrues.size() > 1) {
+			throw new GUIBuildException("Element " + getHashKey() + " has multiple default values");
+		} else if (defaultTrues.size() == 1) {
+			box.setSelectedItem(defaultTrues.getFirst());
+		}
+
+		this.add(box, "cell 1 0, growx, ay top, wrap");
+	}
+
+	@Override
+	public void close() {
+		this.box.setSelectedIndex(0);
+	}
+
+	@Override
+	public String getValue() {
+
+		if (box.getSelectedIndex() != 0) {
+			//String selectedString = (String) box.getSelectedItem();
+			int index = box.getSelectedIndex() - 1;
+			if (index < 0)
+				return "";
+
+			return values[index];
+		}
+
+		if (!isOptional()) {
+			JOptionPane.showMessageDialog(null, "No option was selected for "
+									+ getKey() + " (section '" + getSection().toUpperCase() + "')"
+									+ ".\nA value is required. Your .ini-file is probably incorrect.",
+									"Problem when building .ini file",
+									JOptionPane.WARNING_MESSAGE);
+		}
+
+		return null;
+	}
+
+	@Override
+	public synchronized void set(HashMap hm, String key, String value) {
+		doSet = true;
+		setKey = key;
+		setValue = value;
+		setMap = hm;
+
+		if (!hm.containsKey(hashKey)) return;
+		String val = ((String)hm.get(hashKey)).toUpperCase();
+
+		//System.out.println("\tAP: Setting AlternativePanel: " + hashKey + " = " + val);
+
+		for (int ii=0; ii<values.length; ii++) { //loop through all existant items
+			if (val.equals(values[ii].toUpperCase())) { //compare to val
+				this.box.setSelectedIndex(ii+1);
+				break;
+			}
+		}
+	}
+
+	@Override
+	public synchronized void itemStateChanged(ItemEvent arg0) {
+		//Deal with help text
+		help.setText("");
+
+		if ((box.getSelectedIndex() > 0) && (helptexts[box.getSelectedIndex()-1] != null)) {
+			help.setText("<html>" + helptexts[box.getSelectedIndex()-1] + "</html>");
+		} else {
+			if (helptext != null) 
+				help.setText("<html>" + helptext + "</html>");
+		}
+
+		//handle selected Item
+		final String selectedOption = (String) arg0.getItem();
+		if (selectedOption == "") {
+			if (!optional) {
+				box.setBackground(GUI.WARNING_BACKGROUND_COLOR);
+			}
+		} else {
+			if (!optional) {
+				box.setBackground(GUI.NORMAL_BACKGROUND_COLOR);
+			}
+			//System.out.println("\tDOSET of AlternativePanel: " + doSet);
+			super.handleItemEvent(arg0, selectedOption, doSet, setMap, setKey, setValue);
+			doSet = false;
+			setKey = null;
+			setMap = null;
+			setValue = null;
+		}
+	}
+}
+
+class ColorCellRenderer implements ListCellRenderer {
+	protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
+	private Dimension preferredSize = new Dimension(0, 18);
+
+	public ColorCellRenderer(int width) {
+		width -= 50;
+
+		if (width < 100) width = 100; //Default size on OSX
+	
+		preferredSize = new Dimension(width, 18);
+	}
+
+	public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
+		JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
+		renderer.setPreferredSize(preferredSize);
+		return renderer;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CheckBoxPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CheckBoxPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CheckBoxPanel.java	(revision 18231)
@@ -0,0 +1,139 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import main.*;
+
+import java.awt.Color;
+import java.awt.event.ItemEvent;
+import java.util.HashMap;
+
+import javax.swing.JCheckBox;
+import javax.swing.JOptionPane;
+import javax.swing.JLabel;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+public class CheckBoxPanel extends OptionPanel {
+
+	private static final long serialVersionUID = 552186457208697362L;
+	private final JCheckBox[] boxes;
+	String concat;
+	private String setKey = null, setValue = null;
+	private boolean doSet = false;
+	private HashMap setMap;
+
+
+	/**
+	 * Constructor for a panel that can hold a number of checkboxes to compose
+	 * the value for a key/value set.
+	 *
+	 * @param element
+	 * @throws GUIBuildException
+	 */
+	public CheckBoxPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent);
+
+		concat = "";
+		boxes = new JCheckBox[values.length];
+		for (int i = 0; i < values.length; i++) {
+			boxes[i] = new JCheckBox(values[i]);
+
+			this.add(boxes[i], "cell 1 " + i + ", wrap, ay top");
+
+			String extra = "";
+			if (i > 0)
+				extra = ", gapleft 12";
+
+			this.add(ControlledPanel.createHelpPane(this.helptexts[i]), "cell 6 "+ i +", width 200:400:400, wrap" + extra);
+
+			boxes[i].setBackground(Color.white);
+			boxes[i].setVisible(true);
+			boxes[i].addItemListener(this);
+			if (defaultTrues.contains(values[i])) {
+				boxes[i].setSelected(true);
+				concat += values[i] + " ";
+			}
+		}
+	}
+
+	@Override
+	public void close() {
+		for (final JCheckBox box : boxes)
+			box.setSelected(false);
+	}
+
+	@Override
+	public String getValue() {
+		if (!isOptional() && concat.equals("")) {
+			JOptionPane.showMessageDialog(null, "No option was selected for "
+									+ getKey() + " (section '" + getSection().toUpperCase() + "')"
+									+ ".\nA value is required. Your .ini-file is probably incorrect.",
+									"Problem when building .ini file",
+									JOptionPane.WARNING_MESSAGE);
+		}
+
+		if (concat.equals("")) return null;
+		else	return concat.trim();
+	}
+
+	public synchronized void set(HashMap hm, String key, String value) {
+		String val = ((String)hm.get(hashKey)).toUpperCase();
+		//System.out.println("\tABOUT TO CHANGE CHECKBOXPANEL KEY: " + key + "  VAL: " + val);
+
+		String[] tokens = val.split("\\s+");
+		for (final JCheckBox box : boxes) {
+			box.setSelected(false);
+			
+			for (final String token : tokens) {
+				if (token.equals(box.getText())) {
+					//System.out.println("\t\tSelecting Checkbox: " + token);
+					doSet = true;
+					setKey = key;
+					setValue = value;
+					setMap = hm;
+					box.setSelected(true);
+				}
+			}
+		}
+	}
+
+
+	@Override
+	public synchronized void itemStateChanged(ItemEvent arg0) {
+		final String selectedOption = ((JCheckBox) arg0.getItemSelectable()).getText();
+
+		if (arg0.getStateChange() == ItemEvent.SELECTED) {
+			concat += selectedOption + " ";
+		} else {
+			concat = concat.replaceAll(new String(" " + selectedOption + " "), " ");
+			concat = concat.replaceFirst(new String("^" + selectedOption + " "), ""); //at the beginning of the concat
+		}
+
+		//super.handleItemEvent(arg0, selectedOption);
+		super.handleItemEvent(arg0, selectedOption, doSet, setMap, setKey, setValue);
+		doSet = false;
+		setKey = null;
+		setMap = null;
+		setValue = null;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CombinedPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CombinedPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/CombinedPanel.java	(revision 18231)
@@ -0,0 +1,267 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ItemEvent;
+import java.text.NumberFormat;
+import java.util.*;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+
+import javax.swing.JCheckBox;
+import javax.swing.JComponent;
+import javax.swing.JFormattedTextField;
+import javax.swing.JTextField;
+import javax.swing.JLabel;
+import javax.swing.JComboBox;
+
+import main.XMLHelper;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import net.miginfocom.swing.MigLayout;
+
+/**
+ * @brief The CombinedPanel may contain other panels, such as check and drop down boxes and text fields
+ *
+ * @author Thomas Egger
+ */
+public class CombinedPanel extends OptionPanel {
+	enum Type { CHOICE, INTEGER, DECIMAL, STRING, DROPDOWN }
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = -6751282938445852408L;;
+
+	private final LinkedList<JComponent> valueComponents;
+
+	/**
+	 * Constructor for a panel that can hold text, numbers and check boxes. It
+	 * corresponds to the parameter type "combination" in the configuration file
+	 * and its subcomponents correspond to the option values.
+	 *
+	 * @param element
+	 * @throws GUIBuildException
+	 */
+	public CombinedPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent, false); //doing layout by itself
+
+		//System.out.println("Hierarchy: Parent: " + parent.getKey() + ": "+ parent.getHierarchy() + "  own: " + getHierarchy());
+
+		int column1 = 200;
+		column1 -= getHierarchy() * 5;
+		this.setLayout(new MigLayout("gapx 6, wrap 8, ins n 5 n n", "["+column1+"!][78!][78!][78!][78!][78!][78!][20!][200:400:400]", ""));
+
+		this.add(jlabel, "gapleft " + getHierarchy() * 5);
+		this.add(help, "cell 8 0, wrap");
+
+		valueComponents = new LinkedList<JComponent>();
+
+		final Element[] optionElements = XMLHelper.getElementArray(element, "option");
+
+		byte lblcounter = 0;
+
+		DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance();
+		DecimalFormatSymbols custom = new DecimalFormatSymbols();
+		custom.setDecimalSeparator('.');
+		format.setDecimalFormatSymbols(custom);
+		format.setGroupingUsed(false);
+
+		DecimalFormat integerFormat = (DecimalFormat)DecimalFormat.getIntegerInstance();
+		integerFormat.setGroupingUsed(false);
+
+		int row = 0;
+		int column = 1;
+		
+		for (int i=0;i<optionElements.length;i++) {
+			final Type optionType = Type.valueOf(optionElements[i].getAttribute("type").toUpperCase());
+			final String initialValue = optionElements[i].getAttribute("value");
+			final String label = optionElements[i].getAttribute("label");
+
+			JComponent component = null;
+			JLabel lblcomponent  = null;
+
+			NodeList nodelist = optionElements[i].getChildNodes();
+
+			switch (optionType) {
+			case INTEGER:
+				component = new JFormattedTextField(integerFormat);
+				((JFormattedTextField)component).setColumns(8);
+				if ((initialValue != null) && (!initialValue.equals("")))
+					((JFormattedTextField)component).setValue(new Integer(initialValue));
+				break;
+			case DECIMAL:
+				component = new JFormattedTextField(format);
+				((JFormattedTextField)component).setColumns(8);
+				if ((initialValue != null) && (!initialValue.equals("")))
+					((JFormattedTextField)component).setValue((new Double(initialValue)));
+				break;
+			case STRING:
+				component = new JTextField(10);
+				((JTextField)component).setText(initialValue);
+				break;
+			case CHOICE:
+				component = new JCheckBox(optionElements[i].getAttribute("value"));
+				((JCheckBox)component).addItemListener(this);
+				break;
+			case DROPDOWN:
+				component = new JComboBox();
+
+				for (int jj = 0; jj < nodelist.getLength(); jj++) {
+					if (nodelist.item(jj).getNodeType() == Node.ELEMENT_NODE) {
+						((JComboBox)component).addItem(((Element)nodelist.item(jj)).getAttribute("value"));
+					}
+				}
+
+				((JComboBox)component).setSelectedItem(optionElements[i].getAttribute("value"));
+				((JComboBox)component).addItemListener(this);
+				break;
+			}
+			
+			int width = 1;
+
+			if ((label != null) && (!label.equals(""))){
+				if (label.length() > 12) width = 2; //for oversize labels
+
+				if (column+width >= 7) { 
+					column = 1; 
+					row++; 
+				}
+				lblcomponent = new JLabel(label);
+				valueComponents.add(lblcomponent);
+				
+				//System.out.println("component: " + component.getClass() + ");
+				//System.out.println("component: " + lblcomponent.getClass() + "  size: " + lblcomponent.getWidth() + "  col: " + column + " row: " + row);
+				this.add(lblcomponent, "cell " + column + " " + row + " " + width + " 1");
+				column += width;
+				width = 1;
+				lblcomponent.setVisible(true);
+			}
+
+			if (column >= 7) { 
+				column = 1; 
+				row++; 
+			}
+			//System.out.println("component: " + component.getClass() + "  size: " + component.getWidth() + "  col: " + column + " row: " + row);
+			this.add(component, "cell " + column + " " + row + " " + width + " 1");
+			column++;
+
+			valueComponents.add(component);
+			component.setVisible(true);
+		}
+		
+		//System.out.println("\t-->Instantiated one Combined Panel with " + optionElements.length + " components");
+	}
+
+	@Override
+	public void close() {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void set(HashMap hm, String inkey, String invalue) {
+		if (!hm.containsKey(hashKey)) return;
+		String val = (String)hm.get(hashKey);
+
+		//System.out.println("\tSetting CombinedPanel: " + hashKey + " = " + val);
+		//System.out.println("\tThis CombinedPanel has the key: " + this.getKey() + "  should be: " + inkey + " val: " + invalue);
+
+		//Now loop through valueComponents and see if the value string can be matched
+		if (val == null) return;
+
+		String[] tokens = val.split("\\s+");
+		int counter = 0;
+
+		//System.out.println("\t\tLooking at VAL param: " + val);
+		for (final JComponent comp : valueComponents) {
+			boolean digested = false;
+			if (tokens.length <= counter) break;
+			//System.out.println("\t\tLooking at USER param: " + tokens[counter]);
+
+			if (comp.getClass() == JCheckBox.class) {
+				String cbString = ((JCheckBox) comp).getText();
+				if (tokens[counter].equals(cbString)) {
+					((JCheckBox) comp).setSelected(true);
+					digested = true;
+				}
+			} else if (comp.getClass() == JComboBox.class) {
+				JComboBox box = (JComboBox) comp;
+
+				for (int ii=0; ii<box.getItemCount(); ii++) {
+					String itemString = (String) box.getItemAt(ii);
+					if (itemString.equals(tokens[counter])) {
+						box.setSelectedIndex(ii);
+						digested = true;
+					}
+				}
+			} else if (comp.getClass() == JTextField.class) {
+				((JTextField) comp).setText(tokens[counter]);
+				digested = true;
+			} else if (comp.getClass() == JFormattedTextField.class) {
+				((JFormattedTextField) comp).setText(tokens[counter]);
+				digested = true;
+			}
+
+			if ((comp.getClass() != JLabel.class) && (digested))
+				counter++;
+		}
+	}
+
+	@Override
+	public String getValue() {
+		String value = "";
+
+		for (final JComponent comp : valueComponents) {
+			if (comp.getClass() == JTextField.class) {
+				value += ((JTextField) comp).getText();
+			} else if (comp.getClass() == JFormattedTextField.class) {
+				value += ((JFormattedTextField) comp).getText();
+			} else if (comp.getClass() == JCheckBox.class) {
+				if (((JCheckBox) comp).isSelected())
+					value += ((JCheckBox) comp).getText();
+			} else if (comp.getClass() == JComboBox.class) {
+				value += ((String)((JComboBox)comp).getSelectedItem());
+			}
+
+			if (value.length() > 0)
+				value += " ";
+		}
+
+		if (value.equals("")) return null;
+		else	return value;
+	}
+
+	@Override
+	public void itemStateChanged(ItemEvent arg0) {
+		String selectedOption = null;
+
+		if (arg0.getItemSelectable().getClass() == JCheckBox.class) {
+			selectedOption = ((JCheckBox) arg0.getItemSelectable()).getText();
+			super.handleItemEvent(arg0, selectedOption);
+		} else if (arg0.getItemSelectable().getClass() == JComboBox.class) {
+			selectedOption = ((String)((JComboBox)arg0.getItemSelectable()).getSelectedItem());
+			//HACK: should call super...
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/ControlledPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/ControlledPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/ControlledPanel.java	(revision 18231)
@@ -0,0 +1,285 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Font;
+
+import javax.swing.JEditorPane;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSeparator;
+import javax.swing.*;
+import java.util.HashMap;
+import javax.swing.border.*;
+
+import main.GUI;
+import main.GUIBuilder;
+import main.XMLHelper;
+import net.miginfocom.swing.MigLayout;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * Abstract class for JPanels that are maintained with their key and designated
+ * section and can return their current value.
+ */
+public abstract class ControlledPanel extends JPanel {
+
+	private static final long serialVersionUID = 1L;
+
+	private int dependencies;
+
+	protected JLabel jlabel;
+
+	protected String section;
+	protected String key;
+	protected String label;
+	protected String hashKey;
+
+	protected Element element;
+
+	protected boolean optional;
+	protected String replace;
+
+	protected int hierarchy;
+	protected String helptext;
+	protected JEditorPane help;
+
+	/**
+	 * Constructor for a controlled panel.
+	 *
+	 * @param element
+	 */
+	public ControlledPanel(Element element, ControlledPanel parent) {
+		this(element, parent, true);
+	}
+
+	public ControlledPanel(Element element, ControlledPanel parent, boolean doLayout) {
+		super();
+		initialize(element, parent);
+
+		if (doLayout) {
+			int column1 = 200;
+			column1 -= getHierarchy() * 5; //Indentation for the label, 5px per hierarchy level
+
+			setLayout(new MigLayout("gapx 6, wrap 8, top, ins n 5 n n", "["+ column1 + "!][100!][100!][100!][100!][100!][300:400:400]", ""));
+			add(jlabel, "growx, ay top, gaptop 5, gapleft " + getHierarchy() * 5);
+			add(help, "cell 6 0, wrap");
+		}
+	}
+
+	private void initialize(Element element, ControlledPanel parent) {
+		dependencies = 0;
+
+		this.element = element;
+		this.key = element.getAttribute("key");
+		this.label = this.key;
+
+		this.section = element.getAttribute("section");
+		this.hashKey = this.section.toUpperCase() + "::" + this.key.toUpperCase();
+		this.optional = element.getAttribute("optional").equals("true");
+
+		jlabel = new JLabel(this.label + ":      ");
+		jlabel.setForeground(GUI.LABEL_COLOR);
+
+		this.setBackground(Color.white);
+		this.setVisible(true);
+
+		/* Add help to the right side of the panel. */
+		helptext = XMLHelper.getChildElementContent(element, "help");
+		help = ControlledPanel.createHelpPane("<html>"+helptext+"</html>");
+		if (helptext != null) help.setText(helptext);		
+
+		if (parent != null) {
+			setHierarchy(parent.getHierarchy() + 1);
+		} else {
+			setHierarchy(0);
+		}
+	}
+
+	/**
+	 * Creates a ControlledPanel for a parameter that matches its type. (i.e.
+	 * radio buttons for an option parameter, ...
+	 *
+	 * @param element
+	 * @return the Controlled Panel
+	 * @throws GUIBuildException
+	 */
+	public static ControlledPanel createSingleParameterPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		ControlledPanel panel;
+
+		//System.out.println("IN create: " + XMLHelper.getString((Node)element));
+
+		if (element.hasAttribute("counter")) {
+			panel = new DuplicatorPanel(element, parent);
+		} else if (element.getTagName().equals("frame")) {
+			panel = new FramePanel(element, parent);
+		} else if (element.getAttribute("type").equals("path")	|| element.getAttribute("type").equals("file")) {
+			panel = new PathPanel(element, parent);
+		} else if (element.getAttribute("type").equals("alternative") || element.getAttribute("type").equals("logical")) {
+			panel = new AlternativePanel(element, parent);
+		} else if (element.getAttribute("type").equals("choice")) {
+			panel = new CheckBoxPanel(element, parent);
+		} else if (element.getAttribute("type").equals("integer") || element.getAttribute("type").equals("integer+")){
+			panel = new IntegerPanel(element, parent);
+		} else if (element.getAttribute("type").equals("decimal")) {
+			panel = new DecimalPanel(element, parent);
+		} else if (element.getAttribute("type").equals("double")) {
+			panel = new TextfieldPanel(element, parent);
+		} else if (element.getAttribute("type").equals("string") || element.getAttribute("type").equals("char") || element.getAttribute("type").equals("cell")){
+			panel = new TextfieldPanel(element, parent);
+		} else if (element.getAttribute("type").equals("combination")) {
+			panel = new CombinedPanel(element, parent);
+		} else if (element.getAttribute("type").equals("selector")) {
+			panel = new SelectorPanel(element, parent);
+		} else {
+			throw new GUIBuildException("Cannot create a GUI panel for a parameter of type " + element.getAttribute("type"));
+		}
+
+		return panel;
+	}
+
+	public static JEditorPane createHelpPane(String helptext){
+		JEditorPane help = new JEditorPane();
+		help.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
+		help.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
+		help.setEditable(false);
+		help.setContentType("text/html");
+		help.setForeground(Color.GRAY);
+		help.addHyperlinkListener(GUIBuilder.gui);
+
+		if (helptext!=null) {
+			help.setText("<html>"+helptext+"</html>");
+		} else {
+			help.setText("<html></html>");
+		}
+
+		return help;
+	}
+
+	public void setHierarchy(int val) {
+		hierarchy = val;		
+	}
+
+	public int getHierarchy() {
+		return hierarchy;
+	}
+
+	/**
+	 * This method should be called when the panel is removed.
+	 */
+	public abstract void close();
+
+	/**
+	 * @return the GUI component.
+	 */
+	public Component getComponent() {
+		return this;
+	}
+
+	/**
+	 * @return the number of dependencies on the panel.
+	 */
+	public int getDependencies() {
+		return dependencies;
+	}
+
+	/**
+	 * @return the key of the corresponding key / value set
+	 */
+	public String getKey() {
+		return key;
+	}
+
+	/**
+	 * @return the current value of the key / value set null if the key value
+	 *         set should not be printed
+	 */
+	public abstract String getValue();
+
+	/**
+	 * This method should be called when another panel depends needs this panel
+	 * to exist.
+	 */
+	public synchronized void hold() {
+		this.dependencies++;
+	}
+
+	/**
+	 * @return true if dependencies on this panel exist
+	 * @throws GUIBuildException
+	 */
+	public synchronized boolean isNeeded() throws GUIBuildException {
+		if (dependencies == 0) {
+			return false;
+		} else if (dependencies > 0) {
+			return true;
+		} else {
+			throw new GUIBuildException("Inplausible number of dependencies on panel");
+		}
+	}
+
+	/**
+	 * @return true if a value for the underlying parameter is optional
+	 */
+	public boolean isOptional() {
+		return optional;
+	}
+
+	/**
+	 * This method should be called when a panel no longer needs this panel to
+	 * exist. The panel will be removed if no dependency exists.
+	 */
+	public synchronized void release() {
+		this.dependencies--;
+	}
+
+	public void set(HashMap hm, String key, String value) {
+		System.out.println("Set not implemented for ControlledPanel: " + serialVersionUID);
+	}
+
+	public String getHashKey() {
+		return hashKey;
+	}
+
+	/**
+	 * This method sets a new key for a panel and changes its label.
+	 *
+	 * @param key
+	 *            the new key
+	 */
+	public void setKey(String key) {
+		this.key = key;
+		element.setAttribute("key", key);
+		jlabel.setText(this.label + ":      ");
+	}
+
+	/**
+	 * Getter method for the section.
+	 * @return the section
+	 */
+	public String getSection() {
+		return section;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DecimalPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DecimalPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DecimalPanel.java	(revision 18231)
@@ -0,0 +1,133 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.util.HashMap;
+
+import java.text.DecimalFormat;
+import java.text.ParseException;
+import java.text.DecimalFormatSymbols;
+import javax.swing.JFormattedTextField;
+
+import org.w3c.dom.Element;
+
+public class DecimalPanel extends TextfieldPanel implements ActionListener, FocusListener{
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = 1555742510677354674L;
+	double defaultvalue;
+	double maximumvalue;
+	double minimumvalue;
+
+	JFormattedTextField textfield;
+
+	public DecimalPanel(Element element, ControlledPanel parent) {
+		super(element, parent);
+		this.remove(super.textfield);
+
+		DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance();
+		DecimalFormatSymbols custom = new DecimalFormatSymbols();
+		custom.setDecimalSeparator('.');
+		format.setDecimalFormatSymbols(custom);
+		format.setGroupingUsed(false);
+
+		textfield = new JFormattedTextField(format);
+		textfield.addActionListener(this);
+		textfield.addFocusListener(this);
+		this.add(textfield,"cell 1 0, growx, ay top, gaptop 3");
+		textfield.setVisible(true);
+		this.invalidate();
+		defaultvalue = 0.0;
+		maximumvalue = Double.MAX_VALUE;
+		minimumvalue = Double.MIN_VALUE;
+
+
+		if(element.hasAttribute("minimum")){
+			minimumvalue = Double.parseDouble(element.getAttribute("minimum"));
+		}
+		if(element.hasAttribute("maximum")){
+			maximumvalue = Double.parseDouble(element.getAttribute("maximum"));
+		}
+		if(element.hasAttribute("default")){
+			defaultvalue = Double.parseDouble(element.getAttribute("default"));
+		}
+		setToDefaultValue();
+	}
+
+	private void setToDefaultValue() {
+		textfield.setValue(new Double(defaultvalue));
+		this.invalidate();
+	}
+
+	private void checkValue(){
+		try {
+			textfield.commitEdit();
+		} catch (ParseException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		double currentvalue = ((Number)textfield.getValue()).doubleValue();
+		if(currentvalue > maximumvalue){
+			textfield.setValue(new Double(maximumvalue));
+		}
+		else if(currentvalue<minimumvalue){
+			textfield.setValue(new Double(minimumvalue));
+		}
+	}
+
+	public String getValue(){
+		return textfield.getValue().toString();
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		String val = (String)hm.get(hashKey);
+		if (val != null) {
+			try {
+				Double.parseDouble(val);
+				textfield.setText(val);
+			} catch (Exception e) {} //Do nothing if conversion fails
+		}
+	}
+
+	@Override
+	public void focusGained(FocusEvent arg0) {
+		checkValue();
+
+	}
+
+	@Override
+	public void focusLost(FocusEvent arg0) {
+		checkValue();
+
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent arg0) {
+		checkValue();
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DuplicatorPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DuplicatorPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/DuplicatorPanel.java	(revision 18231)
@@ -0,0 +1,175 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.*;
+
+import javax.swing.JButton;
+
+import main.GUIBuilder;
+import main.XMLHelper;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class DuplicatorPanel extends ControlledPanel implements ActionListener {
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = 6801877538909126920L;
+	JButton addButton;
+	Element clone;
+
+	JButton removeButton;
+
+	public DuplicatorPanel(Element element, ControlledPanel parent) {
+		super(element, parent);
+
+		addButton = new JButton("+");
+		this.add(addButton, "cell 1 0, split 2, grow");
+		addButton.addActionListener(this);
+
+		removeButton = new JButton("-");
+		this.add(removeButton, "cell 1 0, grow, wrap");
+		removeButton.addActionListener(this);
+
+		clone = (Element) element.cloneNode(true);
+		clone.removeAttribute("counter");
+		clone.setAttribute("counted", "true");
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent arg0) {
+		if (arg0.getSource() == addButton) {
+			add();
+		} else if (arg0.getSource() == removeButton) {
+			remove();
+		}
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		//System.out.println("Trying to add DUPLICATOR Panel: " + key + " ... " + value + "  HashKey: " + this.getHashKey());
+
+		if (key.indexOf('#') == -1) {
+			ControlledPanel child = add(true, hm, key, value);
+			child.set(hm, key, value);
+		}
+	}
+
+	public ControlledPanel add() {
+		return add(false, null, null, null);
+	}
+
+	public ControlledPanel add(boolean doSet, HashMap hm, String key, String value) {
+
+		final Element child = (Element) this.clone.cloneNode(true);
+		final int counter = Integer.parseInt(element.getAttribute("counter"));
+		element.setAttribute("counter", (counter + 1) + "");
+
+		// child.setAttribute("key",element.getAttribute("key").replaceAll("#",counter+""));
+
+		//System.out.println("\t-->Adding a child panel to DUPLICATOR with key: " + key + "  val: " + value + "  HASH: " + this.getHashKey() + "  hier: " + this.getHierarchy());
+
+		recursiveKeyReplace(child, counter + "");
+		element.appendChild(child);
+
+		ControlledPanel childPanel = null;
+		try {
+			childPanel = ControlledPanel.createSingleParameterPanel(child, this);
+			childPanel.setKey(childPanel.getKey());
+			GUIBuilder.gui.addToTab(childPanel, section, this);
+			childPanel.hold();
+			GUIBuilder.control(childPanel);
+			GUIBuilder.recursiveBuild(child, this, doSet, hm, key, value);
+
+		} catch (final GUIBuildException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		}
+
+		this.invalidate();
+		
+		return childPanel;
+	}
+
+	@Override
+	public void close() {
+		boolean doRemove = true;
+
+		do {
+			doRemove = remove();
+		} while (doRemove);
+	}
+
+	@Override
+	public String getValue() {
+		return null;
+	}
+
+	public boolean remove() {
+		final int counter = Integer.parseInt(element.getAttribute("counter")) - 1;
+		final String childKey = element.getAttribute("key").replace("#", counter + "");
+		final Element child = XMLHelper.getCertainChildElement(element, "parameter", "key", childKey);
+
+		if (child == null) return false;
+
+		element.removeChild(child);
+		element.setAttribute("counter", (counter) + "");
+
+		final ControlledPanel childPanel = GUIBuilder.panelControl.get(section, childKey);
+
+		if (childPanel != null) {
+			childPanel.release();
+			childPanel.close();
+
+			try {
+				if (!childPanel.isNeeded()) {
+					GUIBuilder.gui.removeFromTab(childPanel, section, this);
+				}
+			} catch (final GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+
+		this.invalidate();
+
+		return true;
+	}
+
+	private void recursiveKeyReplace(Element element, String string) {
+		if (element.hasAttribute("key")) {
+			element.setAttribute("key", element.getAttribute("key").replaceAll("#", string));
+		}
+		final NodeList nodelist = element.getChildNodes();
+		for (int i = 0; i < nodelist.getLength(); i++) {
+			if (nodelist.item(i).getNodeType() == Node.ELEMENT_NODE) {
+				recursiveKeyReplace(((Element) nodelist.item(i)), string);
+			}
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/FramePanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/FramePanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/FramePanel.java	(revision 18231)
@@ -0,0 +1,71 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import main.GUIBuilder;
+import main.XMLHelper;
+
+import java.util.HashMap;
+import javax.swing.JPanel;
+import javax.swing.border.*;
+import javax.swing.BorderFactory;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import net.miginfocom.swing.MigLayout;
+
+public class FramePanel extends ControlledPanel {
+
+	private static final long serialVersionUID = 1987664773406118295L;
+	protected String title = "";
+
+	/**
+	 *
+	 *
+	 * @param element
+	 * @throws GUIBuildException
+	 */
+	public FramePanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent, false);
+		this.setLayout(new MigLayout("wrap 8, top, ins n 5 n n", "[200!][100!][100!][100!][100!][100!][300:400:400]", ""));
+
+		if (parent == null)	hierarchy = 1;
+
+		title = element.getAttribute("label");
+
+		Border mytitledborder = BorderFactory.createTitledBorder(title);
+		//Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
+		this.setBorder(mytitledborder);
+
+		this.invalidate();
+	}
+
+	@Override
+	public String getValue() {
+		return null;
+	}
+	
+	@Override
+	public void close() {
+
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/GUIBuildException.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/GUIBuildException.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/GUIBuildException.java	(revision 18231)
@@ -0,0 +1,33 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+public class GUIBuildException extends Exception {
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = 1L;
+
+	public GUIBuildException(String message) {
+		super(message);
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/IntegerPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/IntegerPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/IntegerPanel.java	(revision 18231)
@@ -0,0 +1,246 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.*;
+import java.util.HashMap;
+
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+import javax.swing.SwingConstants;
+
+import org.w3c.dom.Element;
+
+/**
+ * A panel that maintains a number in an editable textfield,
+ * optionally with a maximum and minimum value.
+ * @author korhammer
+ *
+ */
+/**
+ * @author korhammer
+ *
+ */
+public class IntegerPanel extends TextfieldPanel implements ActionListener, FocusListener {
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = -8959578535487185306L;
+
+	private int defaultvalue;
+	private int maximumvalue;
+	private int minimumvalue;
+
+	private boolean printPlus;
+
+	private final JButton down;
+	private final JButton up;
+
+	/**
+	 * Constructor for a NumberPanel.
+	 *
+	 * @param element
+	 * @throws GUIBuildException
+	 */
+	public IntegerPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent);
+
+		setDefaultvalue(0);
+		minimumvalue = Integer.MIN_VALUE;
+		maximumvalue = Integer.MAX_VALUE;
+		printPlus = false;
+
+		if (element.getAttribute("type").equals("integer+")) {
+			setPrintplus(true);
+		} else {
+			setPrintplus(false);
+		}
+
+		if (element.hasAttribute("default")) {
+			setDefaultvalue(element.getAttribute("default"));
+		}
+		if (element.hasAttribute("maximum")) {
+			setMaximumvalue(element.getAttribute("maximum"));
+		}
+		if (element.hasAttribute("minimum")) {
+			setMinimumvalue(element.getAttribute("minimum"));
+		}
+
+		textfield.setColumns(4);
+		textfield.invalidate();
+		textfield.setHorizontalAlignment(SwingConstants.RIGHT);
+
+		up = new JButton("+");
+		up.addActionListener(this);
+		down = new JButton("-");
+		down.addActionListener(this);
+		this.add(up, "split 2, growx, ay top");
+		this.add(down, "growx, ay top");
+		textfield.addActionListener(this);
+		textfield.addFocusListener(this);
+
+	}
+
+	/**
+	 * Parses a String to an integer. Different from the standard methods as it
+	 * handles the + sign e.g. in time zones.
+	 *
+	 * @param text
+	 * @return the parsed number
+	 * @throws NumberFormatException
+	 */
+	private static int parse(String text) throws NumberFormatException {
+
+		final char first = text.charAt(0);
+
+		if (first == '+')
+			return Integer.parseInt(text.substring(1));
+		if (first == '-')
+			return Integer.parseInt(text);
+		return Integer.parseInt(text);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see
+	 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
+	 */
+	@Override
+	public void actionPerformed(ActionEvent e) {
+		if (e.getSource() == up) {
+			manipulateNumber(1);
+		} else if (e.getSource() == down) {
+			manipulateNumber(-1);
+		} else if (e.getSource() == textfield) {
+			parseTextfield();
+		}
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		String val = (String)hm.get(hashKey);
+		if (val != null) {
+			try {
+				Integer.parseInt(val);
+				textfield.setText(val);
+			} catch (Exception e) {} //Do nothing if conversion fails
+		}
+	}
+
+	@Override
+	public void focusGained(FocusEvent arg0) {
+
+	}
+
+	@Override
+	public void focusLost(FocusEvent arg0) {
+		parseTextfield();
+	}
+
+	/**
+	 * Manipulates the number in the text field by parsing it, adding the
+	 * increment and writing it back into the textfield.
+	 *
+	 * @param increment
+	 */
+	public void manipulateNumber(int increment) {
+		int number;
+
+		try {
+			number = parseTextfield();
+		} catch (final NumberFormatException nfe) {
+			return;
+		}
+
+		if (number + increment <= maximumvalue
+				&& number + increment >= minimumvalue) {
+			number += increment;
+		} else if (number + increment < minimumvalue) {
+			number = minimumvalue;
+		} else if (number + increment > maximumvalue) {
+			number = maximumvalue;
+		}
+
+		printToTextfield(number);
+	}
+
+	/**
+	 * Calls the parse method on the textfield.
+	 *
+	 * @return
+	 * @throws NumberFormatException
+	 */
+	public int parseTextfield() throws NumberFormatException {
+		try {
+			return parse(textfield.getText());
+		} catch (final NumberFormatException nfe) {
+			JOptionPane.showMessageDialog(null, "The textfield " + getKey()
+					+ " does not contain a number.");
+			throw nfe;
+		}
+	}
+
+	/**
+	 * Prints a number to the text field optionally with a plus sign.
+	 *
+	 * @param number
+	 */
+	public void printToTextfield(int number) {
+		if (this.printPlus && number > 0) {
+			textfield.setText("+" + number);
+		} else {
+			textfield.setText("" + number);
+		}
+		checkBgColor();
+	}
+
+	public void setDefaultvalue(int defaultvalue) {
+		this.defaultvalue = defaultvalue;
+		this.printToTextfield(defaultvalue);
+	}
+
+	public void setDefaultvalue(String defaultvalue) {
+		this.defaultvalue = parse(defaultvalue);
+		this.printToTextfield(this.defaultvalue);
+	}
+
+	public void setMaximumvalue(int maximumvalue) {
+		this.maximumvalue = maximumvalue;
+	}
+
+	public void setMaximumvalue(String maximumvalue) {
+		this.maximumvalue = parse(maximumvalue);
+	}
+
+	public void setMinimumvalue(int minimumvalue) {
+		this.minimumvalue = minimumvalue;
+	}
+
+	public void setMinimumvalue(String minimumvalue) {
+		this.minimumvalue = parse(minimumvalue);
+	}
+
+	public void setPrintplus(boolean printPlus) {
+		this.printPlus = printPlus;
+		printToTextfield(parse(textfield.getText()));
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/OptionPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/OptionPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/OptionPanel.java	(revision 18231)
@@ -0,0 +1,144 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.util.LinkedList;
+import java.util.HashMap;
+import javax.swing.event.EventListenerList;
+
+import main.GUIBuilder;
+import main.XMLHelper;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * A ControlledPanel that maintains a group of choices and invokes panel
+ * creation according to the current choices.
+ *
+ * @author korhammer et egger
+ *
+ */
+public abstract class OptionPanel extends ControlledPanel implements ItemListener {
+
+	private static final long serialVersionUID = 88L;
+
+	protected LinkedList<String> defaultTrues;
+	protected EventListenerList listenerList;
+
+	protected String[] values;
+	protected String[] labels;
+	protected String[] helptexts;
+
+	/**
+	 * The constructor for an OptionPanel.
+	 *
+	 * @param element
+	 *            : The xml element which the OptionPanel is created for.
+	 * @throws GUIBuildException
+	 */
+	public OptionPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		this(element, parent, true);
+	}
+
+	public OptionPanel(Element element, ControlledPanel parent, boolean doLayout) throws GUIBuildException {
+		super(element, parent, doLayout);
+		
+		String elementdefault = "";
+
+		if (element.hasAttribute("default"))
+			elementdefault = element.getAttribute("default");
+
+		listenerList = new EventListenerList();
+
+		final Element[] options = XMLHelper.getElementArray(element, "option");
+		defaultTrues = new LinkedList<String>();
+
+		values = new String[options.length];
+		labels = new String[options.length];
+		helptexts = new String[options.length];
+
+		for (int i=0;i<options.length;i++) {
+			values[i] = options[i].getAttribute("value");
+			labels[i] = options[i].getAttribute("label");
+
+			if (labels[i] == "")
+				labels[i] = values[i];
+
+			if (elementdefault.equals(values[i]))
+				defaultTrues.add(values[i]);
+
+			if (options[i].hasAttribute("default") && options[i].getAttribute("default").equals("true"))
+				defaultTrues.add(values[i]);
+
+			helptexts[i] = XMLHelper.getChildElementContent(options[i],"help");
+		}
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		//System.out.println("Trying to change OptionPanel");
+		//ControlledPanel child = add("TA2");
+		//child.set(element);
+	}
+
+
+	/**
+	 * Invokes the appropriate build or destruct methods when changes are made
+	 * to choices.
+	 *
+	 * @param arg0
+	 * @param selectedOption
+	 */
+	public void handleItemEvent(ItemEvent arg0, String selectedOption) {
+		handleItemEvent(arg0, selectedOption, false, null, null, null);
+	}
+
+	public void handleItemEvent(ItemEvent arg0, String selectedOption, boolean doSet, HashMap hm, String setKey, String setValue) {
+		Element optionElement = XMLHelper.getCertainChildElement(this.element, "option", "label", selectedOption);
+
+		if (optionElement == null)
+			optionElement = XMLHelper.getCertainChildElement(this.element, "option", "value", selectedOption);
+
+		//System.out.println("XML of handleItem("+arg0.getItemSelectable().getClass().toString()+"): " + XMLHelper.getString((Node)optionElement));//this.element));
+
+		if (arg0.getStateChange() == ItemEvent.SELECTED) {
+			try {
+				GUIBuilder.recursiveBuild(optionElement, this, doSet, hm, setKey, setValue);
+			} catch (final GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+
+		} else {
+			try {
+				GUIBuilder.recursiveDestruct(optionElement, this);
+			} catch (final GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/PathPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/PathPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/PathPanel.java	(revision 18231)
@@ -0,0 +1,118 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.HashMap;
+
+import javax.swing.JButton;
+import javax.swing.JFileChooser;
+import javax.swing.JPanel;
+
+import org.w3c.dom.Element;
+
+public class PathPanel extends TextfieldPanel implements ActionListener {
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = 1486664773406118295L;
+
+	JButton select_button;
+
+	/**
+	 * Creates a panel with a text field and a file / path chooser button.
+	 *
+	 * @param element
+	 * @throws GUIBuildException
+	 */
+	public PathPanel(Element element, ControlledPanel parent) throws GUIBuildException {
+		super(element, parent);
+
+		if (element.getAttribute("type").equals("path")) {
+			select_button = new JButton("Select Path");
+		} else if (element.getAttribute("type").equals("file")) {
+			select_button = new JButton("Select File");
+		} else {
+			throw new GUIBuildException("PathPanel is not applicable for parameter types other than 'file' and 'path'.");
+		}
+
+		this.remove(textfield);
+		this.add(textfield, "cell 1 0, growx, span2");
+
+		select_button.addActionListener(this);
+		select_button.setActionCommand("open chooser");
+		select_button.setVisible(true);
+		this.add(select_button, "cell 3 0, growx, wrap");
+
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent event) {
+		if (event.getActionCommand().equals("open chooser") && event.getSource() == this.select_button) {
+			try {
+				chooseFile();
+			} catch (final GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		String val = (String)hm.get(hashKey);
+		if (val != null) textfield.setText(val);
+		this.checkBgColor();
+	}
+
+	/**
+	 * Opens the file chooser dialog and writes the path / filepath into the
+	 * texfield.
+	 *
+	 * @throws GUIBuildException
+	 */
+	public void chooseFile() throws GUIBuildException {
+		final JFileChooser filechooser = new JFileChooser(System.getProperty("user.dir"));
+
+		if (element.getAttribute("type").equals("path")) {
+			filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+		} else if (element.getAttribute("type").equals("file")) {
+			filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+		} else {
+			throw new GUIBuildException("PathPanel is not applicable for parameter types other than 'file' and 'path'.");
+		}
+
+		final int returnVal = filechooser.showOpenDialog(new JPanel());
+
+		if (returnVal == JFileChooser.APPROVE_OPTION) {
+			if (element.getAttribute("type").equals("path")) {
+				textfield.setText(filechooser.getSelectedFile().getAbsolutePath());
+			} else {
+				textfield.setText(filechooser.getSelectedFile().getName());
+			}
+
+			checkBgColor();
+		}
+	}
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/SelectorPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/SelectorPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/SelectorPanel.java	(revision 18231)
@@ -0,0 +1,233 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+ *
+ *   INIshell is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation, either version 3 of the License, or
+ *   (at your option) any later version.
+ *
+ *   INIshell is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package gui_elements;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+
+
+import main.GUIBuilder;
+import main.XMLHelper;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * This class introduces more flexibility into the inishell interface:
+ * The SelectorPanel offers the user to add a specific parameter to
+ * the interface.
+ *
+ * @author Thomas Egger
+ */
+public class SelectorPanel extends ControlledPanel implements ActionListener {
+
+	private static final long serialVersionUID = 8610877538909126920L;
+
+	String[] parameters;
+
+	JButton addButton;
+	JButton removeButton;
+	Element template;
+	String  templateKey;
+	HashMap<String, ControlledPanel> mapOfParameters;
+	ControlledPanel cp = null;
+
+	public SelectorPanel(Element element, ControlledPanel parent) {
+		super(element, parent);
+		templateKey = ""; //will store the pattern of the key
+
+		addButton = new JButton("+");
+		this.add(addButton, "cell 1 0, split 2, grow");
+		addButton.addActionListener(this);
+
+		removeButton = new JButton("-");
+		this.add(removeButton, "cell 1 0, grow, wrap");
+		removeButton.addActionListener(this);
+
+		//The following lines try to extract the template key (e.g. %::filters#, %::resample, COPY::%)
+		final NodeList nodelist = element.getChildNodes();
+		for (int ii = 0; ii < nodelist.getLength(); ii++) {
+			if (nodelist.item(ii).getNodeType() == Node.ELEMENT_NODE) {
+				Element currentElement = (Element)nodelist.item(ii);
+				if (currentElement.getAttribute("template").equals("true")){
+					template = (Element)currentElement.cloneNode(true);
+					templateKey = template.getAttribute("key");
+					template.setAttribute("template", "false");
+				}
+			}
+		}
+
+		final Element[] options = XMLHelper.getElementArray(element, "option");
+		parameters = new String[options.length + 1];
+		for (int ii=0; ii < options.length; ii++) {
+			parameters[ii] = options[ii].getAttribute("value");
+		}
+		parameters[options.length] = "Other...";
+
+		key = templateKey; //IMPORTANT: this changes the key only, not the label!
+		hashKey = this.getSection().toUpperCase() + "::" + this.getKey().toUpperCase();
+		mapOfParameters  = new HashMap<String, ControlledPanel>();
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent arg0) {
+		if (arg0.getSource() == addButton) {
+			add();
+		} else if (arg0.getSource() == removeButton) {
+			remove();
+		}
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		//HACK
+		//System.out.println("\tKEY: " + key + "  VAL: " + value);
+
+		String myKey = this.section.toUpperCase() + "::" + templateKey.toUpperCase().replace("%","([a-zA-Z0-9_]+)");
+		myKey = myKey.replace("#","[1-9]+[0-9]*"); //all integer numbers from 1 to infinity
+		//System.out.println("PATTERN: " + myKey);
+		String myKey2 = key.replaceAll(myKey, "$1");
+		String myKey3 = key.replaceAll(myKey, "$0");
+
+		//System.out.println("HUHUI: " + templateKey + " --- " + myKey2 + " -- " + myKey3);
+
+		boolean toAdd = true;
+		if (mapOfParameters.get(myKey2) != null) toAdd = false; //Parameter already exists
+
+		if (toAdd) {
+			ControlledPanel child = add(myKey2, true, hm, key, value);
+			cp = child;
+			if (child != null) child.set(hm, key, value);
+		} else {
+			if (cp != null) cp.set(hm, key, value);
+		}
+	}
+
+	public void add() {
+		String param = "";
+		String choice = "Other...";
+
+		if (parameters.length > 1)
+			choice = (String)JOptionPane.showInputDialog(this, "Add a parameter", "Add", JOptionPane.QUESTION_MESSAGE, null, parameters, null);
+
+		if (choice == null) return;
+
+		if (choice.equals("Other...")) {
+			param = JOptionPane.showInputDialog(this, "Enter the name of a meteo parameter\n(e.g. VW_AVG, P2");
+		} else {
+			param = choice;
+		}
+
+		add(param, false, null, null, null);
+	}
+
+	public ControlledPanel add(String param, boolean doSet, HashMap hm, String key, String value) {
+		//System.out.println("Trying to add SelectorPanel: " + key + " ... " + value);
+
+		if ((param == null) || (param.length() == 0)) return null;
+		param = param.toUpperCase();
+
+		if (mapOfParameters.get(param) != null) return null; //Parameter already exists
+
+		Element child = (Element)template.cloneNode(true);
+		recursiveKeyReplace(child, param);
+		element.appendChild(child);
+
+		ControlledPanel childPanel = null;
+		try {
+			childPanel = ControlledPanel.createSingleParameterPanel(child, this);
+			childPanel.setKey(childPanel.getKey());
+			GUIBuilder.gui.addToTab(childPanel, section, this);
+			childPanel.hold();
+			GUIBuilder.control(childPanel);
+			GUIBuilder.recursiveBuild(child, this, doSet, hm, key, value);
+
+			mapOfParameters.put(param, childPanel);
+		} catch (final GUIBuildException e1) {
+			e1.printStackTrace();
+		}
+
+		this.invalidate();
+
+		return childPanel;
+	}
+
+	@Override
+	public void close() {
+
+	}
+
+	@Override
+	public String getValue() {
+		return null;
+	}
+
+	public void remove() {
+		if (mapOfParameters.size() == 0) return;
+
+		String choice = (String)JOptionPane.showInputDialog(this, "Remove a parameter", "Remove", JOptionPane.QUESTION_MESSAGE, null, mapOfParameters.keySet().toArray(), null);
+
+		if (choice == null) return; //nothing to do
+
+		String childKey = templateKey.replaceAll("%", choice);
+		final Element child = XMLHelper.getCertainChildElement(element, "parameter", "key", childKey);
+
+		if (child == null) return;
+
+		try { //this makes sure that all child nodes are destroyed
+			GUIBuilder.recursiveDestruct(child, this);
+			element.removeChild(child);
+			final ControlledPanel childPanel = GUIBuilder.panelControl.get(section, childKey);
+
+			childPanel.release();
+			childPanel.close();
+
+			if (!childPanel.isNeeded())
+				GUIBuilder.gui.removeFromTab(childPanel, section, this);
+
+			mapOfParameters.remove(choice);
+		} catch (final GUIBuildException e) {
+			e.printStackTrace();
+		}
+
+		this.invalidate();
+	}
+
+	private void recursiveKeyReplace(Element element, String string) {
+		if (element.hasAttribute("key"))
+			element.setAttribute("key", element.getAttribute("key").replaceAll("%", string));
+
+		final NodeList nodelist = element.getChildNodes();
+		for (int i = 0; i < nodelist.getLength(); i++) {
+			if (nodelist.item(i).getNodeType() == Node.ELEMENT_NODE) {
+				recursiveKeyReplace(((Element) nodelist.item(i)), string);
+			}
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/TextfieldPanel.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/TextfieldPanel.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/gui_elements/TextfieldPanel.java	(revision 18231)
@@ -0,0 +1,129 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package gui_elements;
+
+import main.GUI;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.util.HashMap;
+
+import javax.swing.JTextField;
+import javax.swing.JOptionPane;
+
+import org.w3c.dom.Element;
+
+/**
+ * A panel that contains a textfield.
+ *
+ * @author korhammer et egger
+ *
+ */
+public class TextfieldPanel extends ControlledPanel implements KeyListener {
+
+	private static final long serialVersionUID = 1L;
+	private String defaultText;
+
+	protected JTextField textfield;
+
+	/**
+	 * The constructor for a TextfieldPanel.
+	 *
+	 * @param element
+	 */
+	public TextfieldPanel(Element element, ControlledPanel parent) {
+		super(element, parent);
+		textfield = new JTextField(10);
+		textfield.setVisible(true);
+		this.add(textfield, "width 250:100:400, cell 1 0, growx, ay top, gaptop 3");
+		textfield.addKeyListener(this);
+
+		defaultText = "";
+		if (element.hasAttribute("default")) {
+			defaultText = element.getAttribute("default");
+		}
+		textfield.setText(defaultText);
+
+		if (!optional)
+			textfield.setBackground(GUI.WARNING_BACKGROUND_COLOR);
+
+		this.checkBgColor();
+		textfield.invalidate();
+	}
+
+
+
+	@Override
+	public void close() {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void set(HashMap hm, String key, String value) {
+		//System.out.println("\tI'm changing the label of the TextField with key '" + this.getKey() + "'");
+		String val = (String)hm.get(hashKey);
+		if (val != null) textfield.setText(val);
+		this.checkBgColor();
+	}
+
+	@Override
+	public String getValue() {
+		String thetext = textfield.getText();
+
+		if (!isOptional() && thetext.equals("")) {
+			JOptionPane.showMessageDialog(null, "No value was entered for "
+									+ getKey() + " (section '" + getSection().toUpperCase() + "')"
+									+ ".\nA value is required. Your .ini-file is probably incorrect.",
+									"Problem when building .ini file",
+									JOptionPane.WARNING_MESSAGE);
+		}
+
+		if (thetext.equals(""))
+			return null;
+
+		return thetext;
+	}
+
+	/** Handle the key typed event from the text field. */
+	public void keyTyped(KeyEvent e) {}
+
+	/** Handle the key-pressed event from the text field. */
+	public void keyPressed(KeyEvent e) {}
+
+	/** Handle the key-released event from the text field. */
+	public void keyReleased(KeyEvent e) {
+		checkBgColor();
+	}
+
+	public void checkBgColor() {
+		String text = textfield.getText();
+		
+		if (!optional) {
+			if (text.length() > 0) {
+				textfield.setBackground(GUI.NORMAL_BACKGROUND_COLOR);
+			} else {
+				textfield.setBackground(GUI.WARNING_BACKGROUND_COLOR);
+			}
+			textfield.invalidate();
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUI.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUI.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUI.java	(revision 18231)
@@ -0,0 +1,548 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package main;
+
+import gui_elements.ControlledPanel;
+import gui_elements.GUIBuildException;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Desktop;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowListener;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.LinkedList;
+
+import javax.swing.BoxLayout;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JEditorPane;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.JToolBar;
+import javax.swing.event.HyperlinkEvent;
+import javax.swing.event.HyperlinkListener;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import java.io.*;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+
+import net.miginfocom.swing.MigLayout;
+
+/**
+ * The GUI created by the author.
+ *
+ * @author korhammer et egger
+ *
+ */
+public class GUI extends JFrame implements WindowListener, ActionListener, HyperlinkListener {
+
+	/**
+	 *
+	 */
+	private static final long serialVersionUID = -2428732881181670225L;
+	public static PanelNode rootNode = null;
+
+	private static String title = GUI.class.getPackage().getImplementationTitle() + " " + GUI.class.getPackage().getImplementationVersion();
+
+	public static final Color LABEL_COLOR = Color.decode("#000080");
+	public static Color NORMAL_BACKGROUND_COLOR = Color.decode("#EEEEEE");
+	public static Color WARNING_BACKGROUND_COLOR = Color.decode("#FF0011");
+
+	public static ImageIcon openicon = new ImageIcon(GUI.class.getClassLoader().getResource("resources/icons/xml_open.png"));
+	public static ImageIcon openiniicon = new ImageIcon(GUI.class.getClassLoader().getResource("resources/icons/fileopen.png"));
+	public static ImageIcon exporticon = new ImageIcon(GUI.class.getClassLoader().getResource("resources/icons/filesave.png"));
+	public static ImageIcon previewicon = new ImageIcon(GUI.class.getClassLoader().getResource("resources/icons/kghostview.png"));
+	public static ImageIcon reseticon = new ImageIcon(GUI.class.getClassLoader().getResource("resources/icons/reset.png"));
+
+	private final JButton createbutton;
+	private final JButton previewButton;
+	private final JButton openbutton;
+	private final JButton openinibutton;
+	private final JButton resetbutton;
+
+	private final JTabbedPane tabpane;
+	private final JToolBar toolbar;
+	private HashMap<String,JPanel> tabpanels;
+
+	private String configFilePath, iniFilePath;
+
+	/*
+	 * Creates a window with the static components of the GUI, i.e. components
+	 * that do not depend on the configuration file.
+	 */
+	public GUI() throws GUIBuildException {
+		super(title);
+
+		configFilePath = System.getProperty("user.dir");
+		iniFilePath = System.getProperty("user.dir");
+
+		tabpanels = new HashMap<String,JPanel>();
+
+		Dimension screenDim = new Dimension(1280, 800);
+		Dimension maxDim = null;
+
+		if (this.getMaximizedBounds() == null) {
+			Toolkit tk = Toolkit.getDefaultToolkit();
+			maxDim = tk.getScreenSize();
+			this.setMaximizedBounds(new Rectangle(0, 0, (int)maxDim.getWidth(), (int)maxDim.getHeight()));
+		} else {
+			maxDim = this.getMaximizedBounds().getSize();
+		}
+
+		if (maxDim.height < screenDim.height) {
+			screenDim.height = maxDim.height;
+			if (screenDim.height > 100)
+				screenDim.height -= 25;
+		}
+
+		if (maxDim.width < screenDim.width) {
+			screenDim.width = maxDim.width;
+			if (screenDim.width > 100)
+				screenDim.width -= 25;
+		}
+
+		this.setSize(screenDim);
+		//this.setExtendedState(MAXIMIZED_BOTH);
+		this.setVisible(true);
+		this.setLayout(new BorderLayout());
+
+		this.toolbar = new JToolBar();
+		toolbar.setLayout(new BoxLayout(toolbar, 1));
+		toolbar.setFloatable(false);
+		this.setVisible(true);
+		this.add(toolbar, BorderLayout.WEST);
+
+		this.tabpane = new JTabbedPane();
+		this.add(tabpane);
+		tabpane.setVisible(true);
+
+		this.openbutton = new JButton(openicon);
+		this.openbutton.setActionCommand("open config");
+		this.openbutton.setToolTipText("Open XML-configuration");
+		openbutton.addActionListener(this);
+		toolbar.add(this.openbutton);
+
+		this.openinibutton = new JButton(openiniicon);
+		this.openinibutton.setActionCommand("open ini");
+		this.openinibutton.setToolTipText("Open existing INI file");
+		openinibutton.addActionListener(this);
+		toolbar.add(this.openinibutton);
+
+		this.resetbutton = new JButton(reseticon);
+		this.resetbutton.setActionCommand("reset");
+		this.resetbutton.setToolTipText("Reset Interface");
+		resetbutton.addActionListener(this);
+		toolbar.add(this.resetbutton);
+
+		this.createbutton = new JButton(exporticon);
+		this.createbutton.setActionCommand("write config");
+		this.createbutton.setToolTipText("Write to INI-file");
+		createbutton.addActionListener(this);
+		toolbar.add(this.createbutton);
+
+		this.previewButton = new JButton(previewicon);
+		this.previewButton.setActionCommand("preview");
+		this.previewButton.setToolTipText("Preview INI-file");
+		previewButton.addActionListener(this);
+		toolbar.add(previewButton);
+
+		this.addWindowListener(this);
+
+		rootNode = new PanelNode("");
+	}
+
+	/**
+	 * Writes the application name into the GUI window title bar.
+	 *
+	 * @param application
+	 */
+	public void setApplicationForTitle(String application){
+		if(application.equals("")){
+			this.setTitle(title);
+		}
+		else{
+			this.setTitle(title + " for "+application);
+		}
+	}
+
+	public void hideOpenButton(){
+		openbutton.setVisible(false);
+	}
+
+	/**
+	 * Closes all tabs.
+	 */
+	public void closeAllTabs(){
+		tabpane.removeAll();
+	}
+
+	/**
+	 * Adds a component to the tab specified and creates the tab if it does not
+	 * already exist.
+	 *
+	 * @param comp
+	 * @param tabName
+	 * @throws GUIBuildException
+	 */
+	public void addToTab(ControlledPanel comp, String tabName, ControlledPanel parentPanel) throws GUIBuildException {
+		tabName = Character.toUpperCase(tabName.charAt(0)) + tabName.substring(1).toLowerCase();
+
+		String section = ((ControlledPanel)comp).getSection().toUpperCase();
+		String key = section + "::" + ((ControlledPanel)comp).getKey();//((ControlledPanel)comp).getHashKey();
+		//System.out.println("\tPanel: " + ((ControlledPanel)comp).getHashKey() + "   Section: " + ((ControlledPanel)comp).getSection());
+
+		PanelNode sectionNode = rootNode.getChild(section);
+		if (sectionNode == null) {
+			PanelNode tmp = new PanelNode(section);
+			//System.out.println("\t--Adding section '" + section + "' to tree");
+			sectionNode = rootNode.add(tmp);
+		}
+
+		if (parentPanel != null) {
+			//System.out.println("\tLooking for node: " + parentPanel.getHashKey());
+			sectionNode = sectionNode.get(parentPanel.getSection().toUpperCase() + "::" + parentPanel.getKey());
+		}
+
+		if (sectionNode != null) {
+			PanelNode keyNode = sectionNode.get(key);
+			if (keyNode == null) {
+				PanelNode tmp = new PanelNode(key);
+				keyNode = sectionNode.add(tmp);
+				//System.out.println("\t--Adding key '" + key + "' to tree as leaf to " + sectionNode.getData());
+			}
+		}
+
+		JPanel tab;
+		if (tabpane.indexOfTab(tabName) == -1) {
+
+			tab = new JPanel();
+			tab.setBackground(Color.white);
+			tab.setVisible(true);
+			tab.setLayout(new MigLayout("wrap 1"));
+
+			JScrollPane scrollpane = new JScrollPane(tab);
+			tabpane.add(tabName, scrollpane);
+			tabpanels.put(tabName, tab);
+
+		} else {
+			tab = tabpanels.get(tabName);
+		}
+
+		if (parentPanel != null && containsPanel(tab, parentPanel)) {
+			parentPanel.add(comp, "span");
+		} else {
+			tab.add(comp);
+		}
+
+		//JViewport jv = ((JScrollPane)tabpane.getComponentAt(tabpane.indexOfTab(tabName))).getViewport();
+		//jv.setViewPosition(new Point(0,0));
+
+		this.validate();
+	}
+
+	public void removeFromTab(ControlledPanel parameterPanel, String section, ControlledPanel parentPanel) {
+		final String tabTitle = section.substring(0, 1).toUpperCase() + section.substring(1).toLowerCase();
+		final int index = tabpane.indexOfTab(tabTitle);
+
+		final Container container = (Container) tabpane.getComponentAt(index);
+
+		//System.out.println("Removing Panel: " + parameterPanel.getHashKey());
+		PanelNode tmp = rootNode.get(parameterPanel.getSection().toUpperCase() + "::" + parameterPanel.getKey());
+		tmp.getParent().remove(tmp);
+
+		if (parentPanel != null && containsPanel(container, parentPanel)) {
+			parentPanel.remove(parameterPanel);
+		} else {
+			container.remove(parameterPanel);
+		}
+
+		GUIBuilder.panelControl.remove(section, parameterPanel.getKey());
+
+		container.repaint();
+		this.validate();
+	}
+
+	public boolean containsPanel(Container container, JPanel panel) {
+
+		for (final Component component : container.getComponents()) {
+			if (component == panel)
+				return true;
+			if (containsPanel((Container) component, panel))
+				return true;
+		}
+		return false;
+	}
+
+	@Override
+	public void actionPerformed(ActionEvent e) {
+		if (e.getActionCommand().equals("write config") && GUIBuilder.application!=null ) {
+			GUIBuilder.panelControl.setRootNode(rootNode);
+
+			try {
+				GUIBuilder.printIOFile();
+			} catch (final IOException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			} catch (final GUIBuildException e2) {
+				// TODO Auto-generated catch block
+				e2.printStackTrace();
+			}
+		} else if (e.getActionCommand().equals("preview") && GUIBuilder.application!=null) {
+			GUIBuilder.panelControl.setRootNode(rootNode);
+			previewINIFile();
+		} else if (e.getActionCommand().equals("reset") && GUIBuilder.application!=null) {
+			resetGUI();
+		} else if( (e.getActionCommand().equals("open config"))) {
+			openFile();
+		} else if( (e.getActionCommand().equals("open ini"))) {
+			openINIFile();
+		}
+	}
+
+	public void resetGUI() {
+		try {
+			int returnval = GUIBuilder.closeFile();
+			if (returnval == JOptionPane.CANCEL_OPTION) return;
+			GUIBuilder.buildGUI(GUIBuilder.currentConfigFile);
+		} catch (GUIBuildException e) {
+			e.printStackTrace();
+		}
+	}
+
+	public void previewINIFile(){
+		JFrame frame = new JFrame();
+		frame.setSize(600,800);
+		frame.setVisible(true);
+		//frame.setLayout(new BorderLayout());
+
+		JEditorPane pane = new JEditorPane();
+
+		pane.setText(GUIBuilder.panelControl.toString());
+		pane.setVisible(true);
+		pane.setEditable(false);
+
+		JScrollPane scrollPane = new JScrollPane(pane);
+		scrollPane.setVisible(true);
+		frame.add(scrollPane);
+
+		frame.validate();
+		frame.repaint();
+	}
+
+	public void openINIFile(){
+		final FileNameExtensionFilter inifilter = new FileNameExtensionFilter(".ini files", "ini");
+		final JFileChooser filechooser = new JFileChooser(iniFilePath);
+		filechooser.setFileFilter(inifilter);
+		final int returnval = filechooser.showOpenDialog(new JPanel());
+
+		HashMap<String, String> hm = new HashMap<String, String>();
+		HashMap<String, String> comments = new HashMap<String, String>();
+		HashMap<String, String> added_comments = new HashMap<String, String>();
+
+		if (returnval == JFileChooser.APPROVE_OPTION) {
+			final String path = filechooser.getSelectedFile().toString();
+			if (filechooser.getSelectedFile().isDirectory()) return;
+
+			iniFilePath = filechooser.getSelectedFile().getParent();
+
+			System.out.println("Opening INI file: " + path);
+
+			try {
+				BufferedReader br = new BufferedReader(new FileReader(path));
+				String line;
+
+				String section = "GENERAL::";
+				String clines = "";
+
+				while((line = br.readLine()) != null) {
+					int offset = line.indexOf(";");
+					int offset2 = line.indexOf("#");
+
+					if ((offset2 != -1) && (offset != -1)) {
+						if (offset2 < offset) offset = offset2;
+					} else if ((offset2 != -1) && (offset == -1)) {
+						offset = offset2;
+					}
+
+					String comment = null;
+				     //System.out.println("CLINES" + clines);
+					if (offset != -1) {
+						//System.out.println("COMMENT: " + line.substring(offset));
+						comment = line.substring(offset);
+					} else {
+						//System.out.println("COMMENTLESS");
+					}
+
+					if (-1 != offset) line = line.substring(0, offset);
+
+					offset = line.indexOf("#");
+					if (-1 != offset) line = line.substring(0, offset);
+
+					line = line.trim(); //take away ws
+
+					if (line.length()>1) {
+
+						if (line.charAt(0) == '[') {
+							offset = line.indexOf("]");
+							if ((offset == -1) || (offset <= 1)) continue;
+
+							if (!clines.equals("")) {
+								int lbr = clines.indexOf("\n");
+								clines = clines.substring(0, lbr);
+								//System.out.println("Adding the precomment: " + clines);
+								comments.put(section, clines);
+								clines = "";
+							}
+
+							section = line.substring(1, offset).toUpperCase() + "::";
+							//System.out.println("New Section: " + section);
+
+						} else {
+							String[] tokens = line.split("=");
+							if (tokens.length == 2) {
+								String key = tokens[0].trim();
+								String value = tokens[1].trim();
+								if (key.length() > 0) {
+									hm.put(section + key.toUpperCase(), value);
+									if (comment != null) added_comments.put(section + key.toUpperCase(), comment);
+									if (!clines.equals("")) {
+										//System.out.println("Adding the precomment: " + clines);
+										comments.put(section + key.toUpperCase(), clines);
+										clines = "";
+									}
+								}
+							}
+						}
+
+						//System.out.println(line);
+					} else {
+						//it was a comment line only, associate it with the next key
+						if (comment != null) clines += comment;
+						clines += "\n";
+					}
+				}
+				br.close();
+
+				GUIBuilder.setValues(hm, added_comments, comments);
+			} catch (Exception e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+			}
+		}
+	}
+
+	public void openFile(){
+		/* If a configuration is already open, ask for close. */
+		final FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter(".xml files", "xml");
+		final JFileChooser filechooser = new JFileChooser(configFilePath);
+		filechooser.setFileFilter(xmlfilter);
+		final int returnval = filechooser.showOpenDialog(new JPanel());
+		if (returnval == JFileChooser.APPROVE_OPTION) {
+			if(GUIBuilder.application != null){
+				final int returnval2 = GUIBuilder.closeFile();
+				if (returnval2 == JOptionPane.CANCEL_OPTION) return;
+			}
+
+			final String path = filechooser.getSelectedFile().toString();
+			if (filechooser.getSelectedFile().isDirectory()) return;
+
+			configFilePath = filechooser.getSelectedFile().getParent();
+
+			try {
+				GUIBuilder.buildGUI(path);
+			} catch (GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+	}
+
+	@Override
+	public void windowActivated(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void windowClosed(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void windowClosing(WindowEvent e) {
+		System.exit(NORMAL);
+
+	}
+
+	@Override
+	public void windowDeactivated(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void windowDeiconified(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void windowIconified(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void windowOpened(WindowEvent e) {
+		// TODO Auto-generated method stub
+
+	}
+
+	@Override
+	public void hyperlinkUpdate(HyperlinkEvent e) {
+
+		if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
+		      try {
+				Desktop.getDesktop().browse(e.getURL().toURI());
+			} catch (IOException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			} catch (URISyntaxException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			}
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUIBuilder.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUIBuilder.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/GUIBuilder.java	(revision 18231)
@@ -0,0 +1,391 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package main;
+
+import gui_elements.ControlledPanel;
+import gui_elements.GUIBuildException;
+
+import java.io.IOException;
+
+import javax.swing.ProgressMonitor;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.filechooser.FileNameExtensionFilter;
+
+import java.util.*;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * The main class to build the .ini file creator. Upon construction it reads an
+ * XML file and creates the corresponding GUI. Maintains an ElementControl
+ * object.
+ *
+ * @author korhammer et egger
+ *
+ */
+public class GUIBuilder {
+	public static ProgressMonitor monitor;
+
+	public static final String xsd = GUIBuilder.class.getClassLoader().getResource("resources/config_schema-0.1.1.xsd").toString();
+	public static String res_filepath = GUIBuilder.class.getClassLoader().getResource("resources/default_config.xml").toString(); //the default config to start with
+	public static Document doc;
+
+	public static GUI gui;
+	public static PanelControl panelControl;
+
+	public static String application;
+	public static String currentConfigFile;
+
+	public static String saveFilePath = System.getProperty("user.dir");
+
+
+	private static String getFileExtension(final String file_and_path) {
+		final String file_sep = System.getProperty("file.separator");
+
+		// get filename without path
+		final int fileSepIndex = file_and_path.lastIndexOf(file_sep);
+		if (fileSepIndex == -1) {
+			return "";
+		}
+		final String filename = file_and_path.substring(fileSepIndex+1); //remove path
+
+		// get the extension from the filename
+		final int extIndex = filename.lastIndexOf(".");
+		if (extIndex == -1)
+			return "";
+
+		return filename.substring(extIndex+1);
+	}
+
+	/**
+	 * The main method. Opens the GUI Builder with a menu bar on the side.
+	 * If an XML filepath is handed over as an argument,
+	 * the XML file is opened.
+	 *
+	 * @param args
+	 * @throws GUIBuildException
+	 */
+	public static void main(String args[]) throws GUIBuildException {
+
+		new GUIBuilder();
+
+		if ((args.length != 0) && (args[0].length() > 0))
+			res_filepath = args[0]; //User may provice xml file as first argument
+
+		buildGUI(res_filepath);
+		//gui.hideOpenButton();
+	}
+
+	/**
+	 * Builds a GUI from the XML-file specified with validation through
+	 * the specified schema.
+	 *
+	 * @param filepath
+	 * @param schemapath
+	 * @throws GUIBuildException
+	 */
+	public GUIBuilder()	throws GUIBuildException {
+		if (System.getProperty("mrj.version") != null) {  //detect if running on mac
+			System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Inishell");
+			System.setProperty("apple.awt.brushMetalLook", "true");
+		}
+		gui = new GUI();
+	}
+
+	public static void setComments(HashMap<String, String> added_comments, HashMap<String, String> comments) {
+		panelControl.setComments(added_comments, comments);
+	}
+
+	/**
+	 * Builds the gui for a filepath that can either be handed over as an argument
+	 * on application start or chosen by using the open button.
+	 *
+	 * @param filepath
+	 * @throws GUIBuildException
+	 */
+	public static void buildGUI(String filepath) throws GUIBuildException{
+		currentConfigFile = filepath;
+
+		doc = XMLHelper.readXML(filepath, xsd);
+		doc = XMLHelper.resolveReferences(doc);
+
+		application = doc.getDocumentElement().getAttribute("application");
+
+		gui.setApplicationForTitle(application);
+
+		panelControl = new PanelControl();
+
+		final Element root = doc.getDocumentElement();
+		recursiveBuild(root, null, false);
+	}
+
+
+	public static void setValues(final HashMap<String, String> hm, final HashMap<String, String> added_comments, final HashMap<String, String> comments) {
+		if (hm == null) return;
+
+		monitor = new ProgressMonitor(gui, "Loading INI file", "0 out of " + panelControl.order.size() + " sections loaded", 0, panelControl.order.size());
+		monitor.setMillisToPopup(0);
+
+		Thread myrunner = new Thread() {
+				public void run() {
+					int progress_counter = 0; //Effectively counts the sections already parsed into the GUI
+					try {
+						final int returnval = GUIBuilder.closeFile();
+						if (returnval == JOptionPane.CANCEL_OPTION) return;
+						monitor.setProgress(progress_counter);
+
+						GUIBuilder.buildGUI(currentConfigFile);
+					} catch (GUIBuildException e) {
+						e.printStackTrace();
+					}
+
+					gui.setEnabled(false); //Disable user interaction while the ProgressMonitor is on
+
+					HashSet<String> usedKeys = new HashSet<String>(); //save all keys that were used from the HashMap
+					HashSet<String> unusedKeys = new HashSet<String>(); //save all keys that were used from the HashMap
+
+					Iterator<Map.Entry<String, TreeMap<String, ControlledPanel>>> sectionIterator = panelControl.panels.entrySet().iterator();
+					while (sectionIterator.hasNext()) {
+						progress_counter++;
+						monitor.setProgress(progress_counter);
+						monitor.setNote(progress_counter + " out of " + panelControl.order.size() + " sections loaded");
+
+						if (monitor.isCanceled()) { //user cancelled loading
+							monitor.close();
+							gui.setEnabled(true);
+							break; //HACK, should reset the whole environment before breaking
+						}
+
+						Map.Entry<String, TreeMap<String, ControlledPanel>> entry = sectionIterator.next();
+						TreeMap<String, ControlledPanel> value = entry.getValue();
+
+						List<String> sectionKeys = new ArrayList<String>(hm.keySet()); //all keys as defined in the existing ini
+						String sectionKey = entry.getKey().toUpperCase() + "::"; //The section string
+						filterList(sectionKey, sectionKeys); //filter keys for current section only (optimization)
+
+						LinkedList<ControlledPanel> todos = new LinkedList<ControlledPanel>();
+						LinkedList<String> keys = new LinkedList<String>();
+						LinkedList<String> values = new LinkedList<String>();
+
+						do {
+							todos.clear();
+							keys.clear();
+							values.clear();
+
+							Iterator<Map.Entry<String, ControlledPanel>> keyIterator = value.entrySet().iterator();
+							while(keyIterator.hasNext()) { //go through all keys of current section
+								final ControlledPanel mypanel = keyIterator.next().getValue();
+								//System.out.println("\t" + mypanel.getKey());
+
+								String pattern = mypanel.getHashKey();
+								pattern = pattern.replace("%","[a-zA-Z0-9_]+");
+								pattern = pattern.replace("#","[1-9]+[0-9]*"); //all integer numbers from 1 to infinity
+								//System.out.println("Current pattern: " + pattern);
+
+								//Loop through all defined keys of this section and compare them with pattern
+								Iterator<String> keyit = sectionKeys.iterator();
+								while (keyit.hasNext()) {
+									final String currkey = keyit.next();
+									//System.out.println("sectionKeys contains: " + currkey);
+
+									if ((!usedKeys.contains(currkey)) && currkey.matches(pattern)) {
+										//Add mypanel to list of todos
+										//System.out.println("Adding panel for " + currkey);
+										todos.add(mypanel);
+										keys.add(currkey);
+										values.add(hm.get(currkey));
+
+										usedKeys.add(currkey);
+									}
+								}
+							}
+
+							for (int jj = 0; jj < todos.size(); jj++) {
+								//System.out.println("--> SETTING " + keys.get(jj) + "  = " +values.get(jj));
+								todos.get(jj).set(hm, keys.get(jj), values.get(jj));
+							}
+						} while (todos.size() != 0);
+
+						if (progress_counter == panelControl.order.size()) gui.setEnabled(true);
+					}
+
+					//Now find out all keys that were not used in the hashmap
+					for (String key : hm.keySet()) {
+						if (!usedKeys.contains(key)) {
+							//System.out.println("Unknown key = " + key);
+							unusedKeys.add(key);
+							panelControl.setUnusedKeys(key, hm.get(key));
+						}
+					}
+
+					setComments(added_comments, comments);
+				}
+			};//thread
+		myrunner.start();
+	}
+
+	private static void filterList(String filter, List<String> list) {
+		for (Iterator<String> it=list.iterator(); it.hasNext();) {
+			final String next = it.next();
+			if (!next.startsWith(filter)) {
+				it.remove();
+			}
+		}
+	}
+
+	public static int closeFile(){
+		final int returnval = JOptionPane.showConfirmDialog(new JPanel(),
+				"You will lose all changes made to the current ini-file. " +
+				"Do you want this?", "Inishell is already open for " + application, JOptionPane.OK_CANCEL_OPTION);
+
+
+
+		if (returnval == JOptionPane.OK_OPTION) {
+			gui.closeAllTabs();
+			gui.rootNode = new PanelNode("");
+			application = null;
+			doc = null;
+			panelControl = null;
+		}
+
+		return returnval;
+	}
+
+
+	/**
+	 * Puts the specified panel into the panel control.
+	 * @param panel
+	 */
+	public static void control(ControlledPanel panel) {
+		final String section = panel.getSection();
+		panelControl.put(section, panel);
+	}
+
+
+	/**
+	 * Recursively traverses all children of the specified element
+	 * and builds the corresponding panels.
+	 *
+	 * @param parentElement
+	 * @param parentPanel
+	 * @throws GUIBuildException
+	 */
+	public static void recursiveBuild(Element parentElement, ControlledPanel parentPanel, boolean doSet) throws GUIBuildException {
+		recursiveBuild(parentElement, parentPanel, doSet, null, null, null);
+	}
+
+
+	public static void recursiveBuild(Element parentElement, ControlledPanel parentPanel, boolean doSet, HashMap hm, String key, String value) throws GUIBuildException {
+
+		/* get all child elements for the root */
+		final String[] tags = {"parameter", "frame"};
+		final Element[] parameterElements = XMLHelper.getElementArray(parentElement, tags);
+
+		for (final Element element : parameterElements) {
+			final String section = element.getAttribute("section");
+			ControlledPanel parameterPanel;
+
+			if (!panelControl.contains(section, element.getAttribute("key"))) {
+				//System.out.println("Adding through recursiveBuild: " + element.getAttribute("key"));
+				parameterPanel = ControlledPanel.createSingleParameterPanel(element, parentPanel);
+				parameterPanel.setKey(parameterPanel.getKey());
+
+				if (!element.getAttribute("template").equals("true")) {
+					//if (doSet) System.out.println("\tSETTING component key: " + key + "  value: " + value);
+					if (doSet) parameterPanel.set(hm, parameterPanel.getKey(), value);
+
+					gui.addToTab(parameterPanel, section, parentPanel);
+					control(parameterPanel);
+				}
+			} else {
+				parameterPanel = panelControl.get(section, element.getAttribute("key"));
+			}
+
+			parameterPanel.hold();
+			recursiveBuild(element, parameterPanel, doSet);
+		}
+
+		gui.validate();
+	}
+
+	/**
+	 * Recursively destructs child elements of the specified root.
+	 *
+	 * @param rootElement
+	 * @param rootPanel
+	 * @throws GUIBuildException
+	 */
+	public static void recursiveDestruct(Element rootElement, ControlledPanel rootPanel)
+		throws GUIBuildException {
+
+		/* get all child elements for the root */
+		final Element[] parameterElements = XMLHelper.getElementArray(rootElement, "parameter");
+
+		for (final Element element : parameterElements) {
+			final String section = element.getAttribute("section");
+			final ControlledPanel parameterPanel = panelControl.get(section, element.getAttribute("key"));
+			recursiveDestruct(element, parameterPanel);
+
+			parameterPanel.release();
+			parameterPanel.close();
+
+			if (!parameterPanel.isNeeded()) {
+				gui.removeFromTab(parameterPanel, section, rootPanel);
+			}
+
+		}
+
+		gui.validate();
+	}
+
+
+	/**
+	 * Opens a prompt for the path to save the ini file to. Then prints the ini
+	 * to the path specified.
+	 *
+	 * @throws IOException
+	 * @throws GUIBuildException
+	 */
+	public static void printIOFile() throws IOException, GUIBuildException {
+		final FileNameExtensionFilter inifilter = new FileNameExtensionFilter(".ini files", "ini");
+
+		final JFileChooser filechooser = new JFileChooser(saveFilePath);
+		filechooser.setFileFilter(inifilter);
+
+		final int returnval = filechooser.showSaveDialog(new JPanel());
+
+		if (returnval == JFileChooser.APPROVE_OPTION) {
+			String path = filechooser.getSelectedFile().getAbsolutePath();
+			final String ext = getFileExtension(path).toLowerCase();
+			if(!ext.equals("ini")) {
+				path += ".ini";
+			}
+
+			if (filechooser.getSelectedFile().isDirectory()) return;
+			saveFilePath = filechooser.getSelectedFile().getParent();
+
+			panelControl.printToFile(path);
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelControl.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelControl.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelControl.java	(revision 18231)
@@ -0,0 +1,248 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package main;
+
+import gui_elements.ControlledPanel;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.Iterator;
+
+/**
+ * Class that maintains all ControlledPanels so that values can be retrieved
+ * from panels, ini-files can be written. And a panel is not multiply created.
+ *
+ * @author korhammer
+ *
+ */
+public class PanelControl {
+
+	LinkedList<String> order;
+	HashMap<String, TreeMap<String, ControlledPanel>> panels;
+	HashMap<String, String> comments = null;
+	HashMap<String, String> added_comments = null;
+	HashMap<String, HashMap<String, String>> unusedKeys = null;
+	PanelNode rootNode = null;
+
+	/**
+	 * Constructor for the panel control.
+	 */
+	public PanelControl() {
+		panels = new HashMap<String, TreeMap<String, ControlledPanel>>();
+		order = new LinkedList<String>();
+
+		unusedKeys = new HashMap<String, HashMap<String, String>>();
+	}
+
+	public PanelControl(PanelControl p) {
+		panels = new HashMap<String, TreeMap<String, ControlledPanel>>(p.panels);
+		order = new LinkedList<String>(p.order);
+		if (added_comments != null)
+			added_comments = new HashMap<String, String>(p.added_comments);
+
+		if (comments != null)
+			comments = new HashMap<String, String>(p.comments);
+	}
+
+	public void setUnusedKeys(String key, String value) {
+		//Parse key
+		int offset = key.indexOf("::");
+		String section = key.substring(0, offset);
+		String sectionkey = key.substring(offset + 2);
+
+		HashMap<String, String> hm = unusedKeys.get(section);
+		if (hm == null) unusedKeys.put(section, new HashMap<String, String>());
+
+		unusedKeys.get(section).put(sectionkey, value);
+	}
+
+	public void setComments(HashMap<String, String> inaddedcomments, HashMap<String, String> incomments) {
+		this.added_comments = new HashMap<String, String>(inaddedcomments);
+		this.comments = new HashMap<String, String>(incomments);
+	}
+
+	/**
+	 * @param section
+	 * @param key
+	 * @return true if a panel with such key is maintained in the specified
+	 *         section
+	 */
+	public boolean contains(String section, String key) {
+		if (!panels.containsKey(section))
+			return false;
+
+		return panels.get(section).containsKey(key);
+	}
+
+	/**
+	 *
+	 * @param section
+	 * @param key
+	 * @return the panel with the specified section / key pair
+	 */
+	public ControlledPanel get(String section, String key) {
+		return panels.get(section).get(key);
+	}
+
+	/**
+	 * Prints the ini-file at the specified path.
+	 *
+	 * @param path
+	 */
+	public void printToFile(String path) {
+		/* create file */
+		final File file = new File(path);
+
+		try {
+			final FileWriter writer = new FileWriter(file);
+
+			writer.write(this.toString());
+			writer.close();
+		} catch (final IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * Adds the panel to the specified section.
+	 *
+	 * @param section
+	 * @param panel
+	 */
+	public void put(String section, ControlledPanel panel) {
+		final String key = panel.getKey();
+		if (!panels.containsKey(section)) {
+			order.add(section);
+			panels.put(section, new TreeMap<String, ControlledPanel>());
+		}
+		panels.get(section).put(key, panel);
+	}
+
+	/**
+	 * Removes the panel with the specified section and key.
+	 *
+	 * @param section
+	 * @param key
+	 * @return the panel
+	 */
+	public ControlledPanel remove(String section, String key) {
+		return panels.get(section).remove(key);
+	}
+
+	/**
+	 * Prints the maintained panels to a string.
+	 *
+	 * @return an ini-file-like structure
+	 */
+	public void setRootNode(PanelNode inrootNode) {
+		rootNode = inrootNode;
+	}
+
+	public String extractKey(String instring) {
+		int offset = instring.indexOf("::");
+		if (offset == -1) return null;
+
+		return instring.substring(offset+2);
+	}
+
+	@Override
+	public String toString() {
+		String out = "";
+
+		for (final String section : order) {
+			/* create section */
+			final String sectionstring = "[" + section.toUpperCase() + "]\n";
+			String keyvaluestring = "";
+
+			/* print section */
+			LinkedList<String> keys = new LinkedList<String>();
+			PanelNode sectionNode = rootNode.get(section.toUpperCase());
+			if (sectionNode != null) sectionNode.getKeyList(keys);
+
+			//final Set<String> keys = panels.get(section).keySet();
+			for (final String hashKey : keys) {
+				String key = extractKey(hashKey);
+				if (key == null) continue;
+
+				final String value = panels.get(section).get(key).getValue();
+				if (value != null) {
+					if ((comments != null) && comments.containsKey(hashKey.toUpperCase())) {
+						String precomments =  comments.get(hashKey.toUpperCase());
+						if (!precomments.equals(""))
+						 	keyvaluestring += precomments;						
+					}
+
+					keyvaluestring += key + "\t=\t" + value;					
+
+					if ((added_comments != null) && added_comments.containsKey(hashKey.toUpperCase()))
+						keyvaluestring += "\t" + added_comments.get(hashKey.toUpperCase());
+
+					keyvaluestring += "\n";
+				}
+			}
+
+			//Add unused keys
+			HashMap<String, String> extra = unusedKeys.get(section.toUpperCase());
+			if (extra != null) {
+				if (!keyvaluestring.equals("")) keyvaluestring += "\n";
+
+				for (String extrakey : extra.keySet()) {
+					String hashKey = section.toUpperCase() + "::" + extrakey.toUpperCase();
+					if ((comments != null) && comments.containsKey(hashKey)) {
+						String precomments =  comments.get(hashKey);
+						if (!precomments.equals(""))
+						 	keyvaluestring += precomments;						
+					}
+				
+					keyvaluestring += extrakey + "\t=\t" + extra.get(extrakey);
+
+					if ((added_comments != null) && added_comments.containsKey(hashKey))
+					    keyvaluestring += "\t" + added_comments.get(hashKey);
+
+					keyvaluestring += "\n";
+				}
+			}
+			
+			//check if there aren't any comments in that section
+			String hashKey = section.toUpperCase() + "::";
+			if ((comments != null) && comments.containsKey(hashKey)) {
+				String precomments =  comments.get(hashKey);
+				if (!precomments.equals("")) {
+					if (precomments.indexOf("\n") == -1) precomments += "\n";
+					keyvaluestring = precomments + keyvaluestring + "\n";
+				}
+			}
+			
+			/* add section only if keys / values are printed */
+			if (!keyvaluestring.equals("")) {
+				out += sectionstring + keyvaluestring + "\n";
+			}
+		}
+
+		return out;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelNode.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelNode.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/PanelNode.java	(revision 18231)
@@ -0,0 +1,69 @@
+package main;
+
+import java.util.List;
+import java.util.LinkedList;
+
+public class PanelNode {
+	private String data;
+	private PanelNode parent;
+	private LinkedList<PanelNode> children = new LinkedList<PanelNode>();
+
+	public PanelNode(String indata) {
+		data = indata;
+		parent = null;
+	}
+
+	public PanelNode(PanelNode p) {
+		data = p.data;
+		parent = p.parent;
+		children = new LinkedList<PanelNode>(p.children);
+	}
+
+	public String getData() {
+		return data;
+	}
+
+	public PanelNode getChild(String data) {
+		for (PanelNode child : children) {
+			if (child.data.equals(data))
+				return child;
+		}
+
+		return null;
+	}
+
+	public PanelNode add(PanelNode c) {
+		c.parent = this;
+		children.add(c);
+
+		return children.getLast();
+	}
+
+	public PanelNode get(String searchstring) {
+		if (data.equals(searchstring)) return this;
+
+		for (PanelNode child : children) {
+			PanelNode tmp = child.get(searchstring);
+			if (tmp != null) return tmp;
+		}
+
+		return null; //Nothing found in subtree
+	}
+
+	public boolean remove(PanelNode tmp) {
+		return children.remove(tmp);
+	}
+
+	public PanelNode getParent() {
+		return parent;
+	}
+
+	public void getKeyList(LinkedList<String> keyList) {
+		if ((data.indexOf('#') == -1) && (data.indexOf('%') == -1))
+			keyList.add(data);
+
+		for (PanelNode child : children) {
+			child.getKeyList(keyList);
+		}
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/XMLHelper.java
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/XMLHelper.java	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/main/XMLHelper.java	(revision 18231)
@@ -0,0 +1,525 @@
+/***********************************************************************************/
+/*  Copyright 2012 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
+/***********************************************************************************/
+/*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+package main;
+
+import gui_elements.GUIBuildException;
+
+import java.io.IOException;
+import java.util.LinkedList;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+//for the XML printing
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.*;
+import java.io.StringWriter;
+
+public class XMLHelper {
+
+	/**
+	 * Find the parameter values for which the element should be cloned
+	 * e.g. for section tags.
+	 *
+	 * @param element
+	 * @param tagName
+	 * @param attributeName
+	 * @param parentArgument
+	 * @return the
+	 */
+	public static String[] findApplicableValues(Element element,
+			String tagName, String attributeName, String parentArgument) {
+
+		final String[] argumentsFromElement = getAttributesFromChildren(
+				element, tagName, attributeName);
+
+		/*
+		 * If no such arguments are specified for the current element but there
+		 * are for the parent element, take that of the parent.
+		 */
+		if (argumentsFromElement.length == 0 && parentArgument != null)
+			return new String[] { parentArgument };
+		else if ((argumentsFromElement.length > 0 && parentArgument != null)) {
+			if (getCertainChildElement(element, tagName, attributeName,
+					parentArgument) != null)
+				return new String[] { parentArgument };
+			else
+				/*
+				 * The empty intersection is an empty array so that his case can
+				 * be handled differently from the null case below.
+				 */
+				return new String[0];
+		}
+
+		/*
+		 * If no arguments are specified for the parent use all element
+		 * arguments.
+		 */
+		else if (argumentsFromElement.length > 0 && parentArgument == null)
+			return argumentsFromElement;
+		else if (argumentsFromElement.length == 0 && parentArgument == null)
+			return null;
+		return null;
+	}
+
+	/**
+	 * Get all children of an element that have a certain element tag and
+	 * extract the values for a certain attribute.
+	 *
+	 * @param parent
+	 *            the parent element
+	 * @param tag
+	 *            the element tag
+	 * @param attribute
+	 *            the attribute name
+	 *
+	 * @return a String array with the attribute values
+	 */
+	public static String[] getAttributesFromChildren(Element parent, String tag, String attribute) {
+		final Element[] elements = getElementArray(parent, tag);
+
+		final String[] attributes = new String[elements.length];
+		for (int i = 0; i < elements.length; i++) {
+			attributes[i] = elements[i].getAttribute(attribute);
+		}
+		return attributes;
+	}
+
+	/**
+	 * Returns the first child element that has the specified element tag and
+	 * the value for the specified attribute.
+	 *
+	 * @param parent
+	 * @param tag
+	 * @param attribute
+	 * @param value
+	 * @return the first child element that meets the criteria
+	 */
+	public static Element getCertainChildElement(Element parent, String tag,
+			String attribute, String value) {
+		final Element[] allElements = getElementArray(parent, tag);
+		for (final Element element : allElements) {
+			if (element.hasAttribute(attribute)) {
+				if (element.getAttribute(attribute).equals(value))
+					return element;
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * For the specified element gets the text that is contained in the first
+	 * child that has a certain element name.
+	 *
+	 *
+	 * @param parent
+	 *            the parent element
+	 * @param tag
+	 *            the element tag for the child
+	 * @return the text content
+	 */
+	public static String getChildElementContent(Element parent, String tag) {
+		final Element[] elements = getElementArray(parent, tag);
+		if (elements.length == 0)
+			return null;
+
+		return elements[0].getTextContent();
+	}
+
+
+
+	/**
+	 * @param parent
+	 * @param tag
+	 * @return all child elements of the parent with the specified tag
+	 */
+	public static Element[] getElementArray(Element parent, String tag) {
+		if (!parent.hasChildNodes())
+			return new Element[0];
+
+		final NodeList nodeList = parent.getChildNodes();
+		final LinkedList<Element> elementlist = new LinkedList<Element>();
+		for (int i = 0; i < nodeList.getLength(); i++) {
+
+			final Node element = nodeList.item(i);
+			if (element.getNodeType() == Node.ELEMENT_NODE && ((Element) element).getTagName().equals(tag)) {
+				elementlist.add((Element) element);
+			}
+		}
+		final Element[] elements = new Element[elementlist.size()];
+
+		return elementlist.toArray(elements);
+	}
+
+	public static Element[] getElementArray(Element parent, String[] tags) {
+		if (!parent.hasChildNodes())
+			return new Element[0];
+
+		final NodeList nodeList = parent.getChildNodes();
+		final LinkedList<Element> elementlist = new LinkedList<Element>();
+		for (int ii = 0; ii < nodeList.getLength(); ii++) {
+
+			final Node element = nodeList.item(ii);
+			if (element.getNodeType() == Node.ELEMENT_NODE) {
+				//Loop through all possible tags
+				for (int jj=0; jj<tags.length; jj++) {
+					if (((Element) element).getTagName().equals(tags[jj])) {
+						elementlist.add((Element) element);
+						break;
+					}
+				}
+			}
+		}
+
+		final Element[] elements = new Element[elementlist.size()];
+		return elementlist.toArray(elements);
+	}
+
+	/**
+	 * Prints the Document object to the console. as XML.
+	 *
+	 * @param doc
+	 */
+	public static String printToScreen(Document doc) {
+
+		final javax.xml.transform.TransformerFactory tfactory = TransformerFactory
+				.newInstance();
+
+		javax.xml.transform.Transformer xform;
+		try {
+			xform = tfactory.newTransformer();
+
+			final javax.xml.transform.Source src = new javax.xml.transform.dom.DOMSource(
+					doc);
+
+			final java.io.StringWriter writer = new java.io.StringWriter();
+			final javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(
+					writer);
+
+			xform.transform(src, result);
+
+			return writer.toString();
+
+		} catch (final TransformerConfigurationException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (final TransformerException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		return null;
+	}
+
+
+
+	/**
+	 * Reads an XML file and writes it into a Document structure.
+	 *
+	 * @param filepath
+	 * @param xsdpath
+	 *            the path of the W3 XML schema that the file is based on.
+	 * @throws GUIBuildException
+	 */
+	public static Document readXML(String filepath, String xsdpath)
+			throws GUIBuildException {
+
+		/* read XML file and write it into Document structure */
+
+		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+		dbf.setIgnoringComments(true);
+		dbf.setValidating(true);
+		dbf.setIgnoringElementContentWhitespace(true);
+
+		dbf.setAttribute(
+				"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
+				"http://www.w3.org/2001/XMLSchema");
+		dbf.setAttribute(
+				"http://java.sun.com/xml/jaxp/properties/schemaSource", xsdpath);
+
+
+		DocumentBuilder db;
+		Document doc;
+
+		try {
+
+			db = dbf.newDocumentBuilder();
+			doc = db.parse(filepath);
+		} catch (final ParserConfigurationException e) {
+			throw new GUIBuildException(e.getMessage());
+		} catch (final SAXException e) {
+			throw new GUIBuildException(e.getMessage());
+		} catch (final IOException e) {
+			throw new GUIBuildException(e.getMessage());
+		}
+
+		doc.normalize();
+		doc.normalizeDocument();
+
+		resolveIncludes(doc, xsdpath);
+		resolveReferences(doc);
+		recursivelyResolveSections(doc.getDocumentElement(), null);
+		recursivelyResolveReplaces(doc.getDocumentElement(), null);
+
+		return doc;
+	}
+
+	/**
+	 * This method recursively traverses the document tree and replaces all
+	 * parameters that contain replace elements with the corresponding number of
+	 * cloned elements.
+	 *
+	 * @param current
+	 *            the current element
+	 * @param parentReplace
+	 *
+	 */
+	public static void recursivelyResolveReplaces(Element current,
+			String parentReplace) {
+
+		final String[] replacements = XMLHelper.findApplicableValues(
+				current, "replace", "name", parentReplace);
+
+		/* delete replace children */
+		final Element[] replaceChildren = XMLHelper.getElementArray(current,
+				"replace");
+		for (final Element replace : replaceChildren) {
+			current.removeChild(replace);
+		}
+
+		if (replacements == null) {
+			final NodeList childNodes = current.getChildNodes();
+			final Node[] nodes = new Node[childNodes.getLength()];
+			for (int i = 0; i < childNodes.getLength(); i++) {
+				nodes[i] = childNodes.item(i);
+			}
+
+			for (final Node node : nodes) {
+				if (node.getNodeType() == Node.ELEMENT_NODE) {
+					XMLHelper.recursivelyResolveReplaces((Element) node,
+							parentReplace);
+				}
+			}
+		} else if (replacements.length == 0) {
+			current.getParentNode().removeChild(current);
+		} else if (replacements != null) {
+			/* clone element */
+			for (final String replace : replacements) {
+				final Element clone = (Element) current.cloneNode(true);
+				clone.setAttribute("key",
+						clone.getAttribute("key").replaceAll("%", replace));
+				clone.setAttribute("replaced", replace);
+				current.getParentNode().appendChild(clone);
+
+				/* Recursion: Do not do recursion on NodeList as it is updated */
+				final NodeList childNodes = clone.getChildNodes();
+				final Node[] nodes = new Node[childNodes.getLength()];
+				for (int i = 0; i < childNodes.getLength(); i++) {
+					nodes[i] = childNodes.item(i);
+				}
+
+				for (final Node node : nodes) {
+					if (node.getNodeType() == Node.ELEMENT_NODE) {
+						XMLHelper.recursivelyResolveReplaces((Element) node,
+								replace);
+					}
+				}
+
+			}
+			current.getParentNode().removeChild(current);
+		}
+	}
+
+	/**
+	 * This method recursively traverses the document tree and replaces all
+	 * parameters that contain section elements with the corresponding number of
+	 * cloned elements.
+	 *
+	 * @param current
+	 */
+	public static void recursivelyResolveSections(Element current,
+			String parentSection) {
+
+		final String[] sections = XMLHelper.findApplicableValues(current,
+				"section", "name", parentSection);
+
+
+		final Element[] sectionChildren = XMLHelper.getElementArray(current,
+				"section");
+		for (final Element section : sectionChildren) {
+			current.removeChild(section);
+		}
+
+		if (sections == null) {
+			final NodeList childNodes = current.getChildNodes();
+			final Node[] nodes = new Node[childNodes.getLength()];
+			for (int i = 0; i < childNodes.getLength(); i++) {
+				nodes[i] = childNodes.item(i);
+			}
+
+			for (final Node node : nodes) {
+				if (node.getNodeType() == Node.ELEMENT_NODE) {
+					XMLHelper.recursivelyResolveSections((Element) node,
+							parentSection);
+				}
+			}
+		} else if (sections != null) {
+			/* clone element */
+			for (final String section : sections) {
+				final Element clone = (Element) current.cloneNode(true);
+				clone.setAttribute("section", section);
+
+				current.getParentNode().appendChild(clone);
+
+				/* Recursion: Do not do recursion on NodeList as it is updated */
+				final NodeList childNodes = clone.getChildNodes();
+				final Node[] nodes = new Node[childNodes.getLength()];
+				for (int i = 0; i < childNodes.getLength(); i++) {
+					nodes[i] = childNodes.item(i);
+				}
+
+				for (final Node node : nodes) {
+					if (node.getNodeType() == Node.ELEMENT_NODE) {
+						XMLHelper.recursivelyResolveSections((Element) node,
+								section);
+					}
+				}
+
+			}
+			current.getParentNode().removeChild(current);
+		}
+	}
+
+	/**
+	 * Parses an XML file as specified in the path of an "include" element and
+	 * replaces the include element with the content of the XML file.
+	 *
+	 * @param doc
+	 */
+	public static Document resolveIncludes(Document doc, String xsdpath) {
+		final NodeList include = doc.getElementsByTagName("include");
+
+		for (int i = 0; i < include.getLength(); i++) {
+
+			final String includePath = ((Element) include.item(i))
+					.getAttribute("path");
+
+			try {
+				final Document partialDocument = readXML(includePath, xsdpath);
+
+				final NodeList children = partialDocument.getChildNodes()
+						.item(0).getChildNodes();
+				final Node parent = include.item(i).getParentNode();
+
+				for (int j = 0; j < children.getLength(); j++) {
+					final Node imported = doc
+							.importNode(children.item(j), true);
+					parent.appendChild(imported);
+				}
+
+				// parent.replaceChild(fragment, include.item(i));
+			} catch (final GUIBuildException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+
+		}
+
+		return doc;
+	}
+
+	/**
+	 * Manipulates the document structure, so that "reference" elements are
+	 * replaced by the corresponding "parametergroup".
+	 *
+	 * @param doc
+	 * @return
+	 */
+	public static Document resolveReferences(Document doc) {
+
+		final NodeList references = doc.getElementsByTagName("reference");
+		final NodeList parametergroups = doc.getElementsByTagName("parametergroup");
+
+		while (references.getLength() != 0) {
+
+			final Element referenceElement = (Element) references.item(0);
+
+			final Element parent = (Element) referenceElement.getParentNode();
+
+			parent.removeChild(referenceElement);
+
+			for (int i = 0; i < parametergroups.getLength(); i++) {
+
+				final Node parametergroupElement = parametergroups.item(i);
+
+				if (((Element) parametergroupElement).getAttribute("name")
+						.equals(referenceElement.getAttribute("name"))) {
+					final NodeList children = parametergroupElement
+							.getChildNodes();
+
+					for (int j = 0; j < children.getLength(); j++) {
+						final Node clone = children.item(j).cloneNode(true);
+						parent.appendChild(clone);
+					}
+				}
+			}
+		}
+
+		while (parametergroups.getLength() != 0) {
+			parametergroups.item(0).getParentNode()
+					.removeChild(parametergroups.item(0));
+		}
+
+		return doc;
+	}
+
+
+	/**
+	 * @brief  The funciton expects a Node element as argument and transform the XML
+	 *         (sub)tree starting with the given Node into a string
+	 * @return A string representing the (sub)tree starting with node
+	 * @author Thomas Egger
+	 */
+	public static String getString(Node node){
+		String str = "";
+
+		try {
+			Transformer transformer = TransformerFactory.newInstance().newTransformer();
+			StringWriter buffer = new StringWriter();
+			transformer.transform(new DOMSource(node), new StreamResult(buffer));
+			str = buffer.toString();
+		} catch (Exception ex) {
+			throw new RuntimeException("Error converting to String", ex);
+		}
+
+		return str;
+	}
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema-0.1.1.xsd
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema-0.1.1.xsd	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema-0.1.1.xsd	(revision 18231)
@@ -0,0 +1,154 @@
+<?xml version="1.0"?>
+<!-- 
+*   
+*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*    	
+* -->
+<xsd:schema version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+  <xsd:element name="inishell_config" type="general" />
+  
+  <xsd:complexType name="general">
+    <xsd:choice maxOccurs="unbounded">
+      <xsd:element name="parameter" type="parametertype" />
+      <xsd:element name="parametergroup" type="pargroup" />
+      <xsd:element name="include" type="pathonly" /> 
+      <xsd:element name="frame" type="framegroup" /> 
+    </xsd:choice>
+    <xsd:attribute name="application" />
+  </xsd:complexType>
+
+  <xsd:complexType name="framegroup">
+    <xsd:choice minOccurs="1" maxOccurs="unbounded">
+      <xsd:element name="parameter" type="parametertype" />
+      <xsd:element name="reference" type="nameonly" />
+      <xsd:element name="section" type="nameonly"/>
+    </xsd:choice>
+    <xsd:attribute name="key" />
+    <xsd:attribute name="label" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="parametertype">
+    <xsd:complexContent>
+      <xsd:extension base="parbasetype">
+		<xsd:attribute name="key" type="xsd:string" use="required"/> 
+		<xsd:attribute name="default" type="xsd:string" />
+		<xsd:attribute name="counter" type="xsd:integer" />
+      </xsd:extension>
+    </xsd:complexContent>		
+  </xsd:complexType>
+  
+  <xsd:complexType name="nameonly">
+	<xsd:attribute name="name" />   
+  </xsd:complexType>
+
+  <xsd:complexType name="optionvalue">
+	<xsd:attribute name="value" />   
+  </xsd:complexType>
+
+  <xsd:complexType name="pathonly">
+	<xsd:attribute name="path" />   
+  </xsd:complexType>
+  
+  <xsd:complexType name="pargroup">
+	<xsd:choice minOccurs="1" maxOccurs="unbounded">
+	  <xsd:element name="parameter" type="parametertype" />
+	  <xsd:element name="reference" type="nameonly" />
+	  <xsd:element name="option" type="optionvalue" />
+	  <xsd:element name="frame" type="framegroup" /> 
+	</xsd:choice>
+	<xsd:attribute name="name" />
+  </xsd:complexType>
+
+  <xsd:complexType name="parbasetype">
+	<xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="section" type="nameonly"/>
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="replace" type="nameonly"/>
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="parameter" type="parametertype" />
+	  </xsd:sequence>
+	  <xsd:choice minOccurs="0" maxOccurs="unbounded">				
+		<xsd:element name="option" minOccurs="0">
+		  <xsd:complexType>
+			<xsd:complexContent>
+			  <xsd:extension base="parbasetype">
+				<xsd:attribute name="value" type="xsd:string" use="required" />
+				<xsd:attribute name="label" type="xsd:string" use="optional" />
+				<xsd:attribute name="default" type="xsd:boolean" use="optional"/>
+			  </xsd:extension>
+			</xsd:complexContent>
+		  </xsd:complexType>
+		</xsd:element>
+	  </xsd:choice>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="reference" type="nameonly" />
+	  </xsd:sequence>
+	  <xsd:sequence minOccurs="0" maxOccurs="unbounded">
+		<xsd:element name="help" type="helptype"/>	
+	  </xsd:sequence>
+	</xsd:sequence>
+	
+	<xsd:attribute name="type" use="required">
+	  <xsd:simpleType>
+		<xsd:restriction base="xsd:string">
+		  <xsd:enumeration value="integer" />
+		  <xsd:enumeration value="integer+" />
+		  <xsd:enumeration value="decimal" />
+		  <xsd:enumeration value="path" />
+		  <xsd:enumeration value="file" />
+		  <xsd:enumeration value="choice" />
+		  <xsd:enumeration value="alternative" />
+		  <xsd:enumeration value="dropdown" />
+		  <xsd:enumeration value="string" />
+		  <xsd:enumeration value="combination" />
+		  <xsd:enumeration value="selector" />
+		</xsd:restriction>
+	  </xsd:simpleType>
+	</xsd:attribute>
+	
+	<xsd:attribute name="maximum" type="xsd:integer"/>
+	<xsd:attribute name="minimum" type="xsd:integer"/>
+	<xsd:attribute name="template" type="xsd:boolean" default="false" use="optional" />
+	<xsd:attribute name="optional" type="xsd:boolean" default="true" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="needstype">
+	<xsd:attribute name="type" type="xsd:string" use="required" />
+	<xsd:attribute name="name" type="xsd:string" use="required" />
+	
+	<xsd:attribute name="value" />
+	<xsd:attribute name="optional" type="xsd:boolean" />
+	<xsd:attribute name="minoccur" type="xsd:integer" />
+	<xsd:attribute name="maxoccur" type="xsd:string" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="baseType">
+	<xsd:sequence minOccurs="0" maxOccurs="1">
+	  <xsd:element name="help" type="helptype" />		
+	</xsd:sequence>
+	<xsd:attribute name="key" type="xsd:string" use="required" />
+  </xsd:complexType>
+  
+  <xsd:complexType name="helptype" mixed="true">
+	<xsd:choice minOccurs="0" maxOccurs="unbounded">
+	  <xsd:element name="section" type="nameonly" />
+	  <xsd:element name="replace" type="nameonly" />
+	</xsd:choice>
+  </xsd:complexType> 
+</xsd:schema>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema.xsd
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema.xsd	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/config_schema.xsd	(revision 18231)
@@ -0,0 +1,141 @@
+<?xml version="1.0"?>
+<!-- 
+*   
+*	This file is part of INIshell.
+*
+*   INIshell is free software: you can redistribute it and/or modify
+*   it under the terms of the GNU General Public License as published by
+*   the Free Software Foundation, either version 3 of the License, or
+*   (at your option) any later version.
+*
+*   INIshell is distributed in the hope that it will be useful,
+*   but WITHOUT ANY WARRANTY; without even the implied warranty of
+*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+*   GNU General Public License for more details.
+*
+*   You should have received a copy of the GNU General Public License
+*   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
+*    	
+* -->
+
+<xsd:schema version="1.0"
+xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+  <xsd:element name="inishell_config" type="general" />
+  
+	<xsd:complexType name="general">
+      <xsd:choice maxOccurs="unbounded">
+			<xsd:element name="parameter" type="parametertype" />
+			<xsd:element name="parametergroup" type="pargroup" />
+			<xsd:element name="include" type="pathonly" /> 
+      </xsd:choice>
+	  <xsd:attribute name="application" />
+    </xsd:complexType>
+	
+	<xsd:complexType name="parametertype">
+		<xsd:complexContent>
+			<xsd:extension base="parbasetype">
+				<xsd:attribute name="key" type="xsd:string" use="required"/> 
+				<xsd:attribute name="default" type="xsd:string" />
+				<xsd:attribute name="counter" type="xsd:integer" />
+			</xsd:extension>
+		</xsd:complexContent>		
+	</xsd:complexType>
+   
+   <xsd:complexType name="nameonly">
+		<xsd:attribute name="name" />   
+   </xsd:complexType>
+   
+   <xsd:complexType name="pathonly">
+		<xsd:attribute name="path" />   
+   </xsd:complexType>
+   
+	<xsd:complexType name="pargroup">
+		<xsd:choice minOccurs="1" maxOccurs="unbounded">
+			<xsd:element name="parameter" type="parametertype" />
+			<xsd:element name="reference" type="nameonly" />
+		</xsd:choice>
+		<xsd:attribute name="name" />
+	</xsd:complexType>
+  
+	
+	<xsd:complexType name="parbasetype">
+		<xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="section" type="nameonly"/>
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="replace" type="nameonly"/>
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="parameter" type="parametertype" />
+			</xsd:sequence>
+			<xsd:choice minOccurs="0" maxOccurs="unbounded">				
+				<xsd:element name="option" minOccurs="0">
+					<xsd:complexType>
+						<xsd:complexContent>
+							<xsd:extension base="parbasetype">
+								<xsd:attribute name="value" type="xsd:string" use="required" />
+								<xsd:attribute name="label" type="xsd:string" use="optional" />
+								<xsd:attribute name="default" type="xsd:boolean"/>
+							</xsd:extension>
+						</xsd:complexContent>
+					</xsd:complexType>
+				</xsd:element>
+			</xsd:choice>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="reference" type="nameonly" />
+			</xsd:sequence>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="help" type="helptype"/>	
+			</xsd:sequence>
+		</xsd:sequence>
+		
+		<xsd:attribute name="type" use="required">
+		     <xsd:simpleType>
+				<xsd:restriction base="xsd:string">
+					<xsd:enumeration value="integer" />
+					<xsd:enumeration value="integer+" />
+					<xsd:enumeration value="decimal" />
+					<xsd:enumeration value="path" />
+					<xsd:enumeration value="file" />
+					<xsd:enumeration value="choice" />
+					<xsd:enumeration value="alternative" />
+					<xsd:enumeration value="string" />
+					<xsd:enumeration value="combination" />
+					<xsd:enumeration value="selector" />
+				</xsd:restriction>
+			</xsd:simpleType>
+		</xsd:attribute>
+		
+		<xsd:attribute name="maximum" type="xsd:integer"/>
+		<xsd:attribute name="minimum" type="xsd:integer"/>
+		<xsd:attribute name="template" type="xsd:boolean" default="false" use="optional" />
+		<xsd:attribute name="optional" type="xsd:boolean" default="true" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="needstype">
+		<xsd:attribute name="type" type="xsd:string" use="required" />
+		<xsd:attribute name="name" type="xsd:string" use="required" />
+	
+		<xsd:attribute name="value" />
+		<xsd:attribute name="optional" type="xsd:boolean" />
+		<xsd:attribute name="minoccur" type="xsd:integer" />
+		<xsd:attribute name="maxoccur" type="xsd:string" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="baseType">
+		<xsd:sequence minOccurs="0" maxOccurs="1">
+			<xsd:element name="help" type="helptype" />		
+		</xsd:sequence>
+		<xsd:attribute name="key" type="xsd:string" use="required" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="helptype" mixed="true">
+		<xsd:choice minOccurs="0" maxOccurs="unbounded">
+			<xsd:element name="section" type="nameonly" />
+			<xsd:element name="replace" type="nameonly" />
+		</xsd:choice>
+	</xsd:complexType>
+	
+</xsd:schema>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/default_config.xml
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/default_config.xml	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/default_config.xml	(revision 18231)
@@ -0,0 +1,919 @@
+<inishell_config application="Meteo IO">
+
+	<!-- General Parameters -->
+	<parameter key="BUFF_CHUNK_SIZE" type="integer" default="30">
+		<section name="general" />
+		<help>Size in days of a chunk of data to read at once.</help>
+	</parameter>
+
+	<parameter key="BUFF_BEFORE" type="decimal" default="1.5">
+		<section name="general" />
+		<help>Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the
+		beginning of the buffer (therefore, it takes a value in days).</help>
+	</parameter>
+
+	<!-- Coordinate systems, time zones -->
+	<parameter key="COORDSYS" type="alternative" optional="false">
+		<section name="input" />
+		<section name="output" />
+		<option value="CH1903" type="string" default="true">
+			<help>coordinates in the Swiss Grid &lt;a href="http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf"&gt;http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UTM" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the zone with the zone letter (for example, 32T)</help>
+			</parameter>
+			<help>UTM coordinates, see &lt;a href="http://www.oc.nps.edu/oc2902w/maps/utmups.pdf"&gt;http://www.oc.nps.edu/oc2902w/maps/utmups.pdf&lt;/a&gt;</help>
+		</option>
+		<option value="UPS" type="string">
+			<parameter key="COORDPARAM" type="string">
+				<help>specify the hemisphere (either N or S)</help>
+			</parameter>
+			<help>Universal Polar Stereographic coordinates, see &lt;a href="https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system"&gt;https://en.wikipedia.org/wiki/Universal_Polar_Stereographic_coordinate_system&lt;/a&gt;</help>
+		</option>
+		<option value="PROJ4" type="string">
+			<parameter key="COORDPARAM" type="string" optional="false" />
+			<help>external library: see &lt;a href="http://trac.osgeo.org/proj/"&gt;http://trac.osgeo.org/proj/&lt;/a&gt;</help>
+		</option>
+		<option value="LOCAL"  type="string">
+			<help>uses the horizontal and vertical distance from a reference point</help>
+		</option>
+		<help>coordinate system</help>
+	</parameter>
+
+	<parameter key="TIME_ZONE" type="integer+" default="+1" maximum="14" minimum="-12" optional="false">
+		<section name="input" />
+		<section name="output" />
+	</parameter>
+
+	<!-- Datatypes: special pts -->
+	<parameter key="SPECIALPTS" type="alternative">
+		<section name="input" />
+		<option value="A3D" type="string">
+			<parameter key="SPECIALPTSFILE" type="file" optional="false">
+				<help>a path+file name to the a file containing grid coordinates of special points of interest (for special outputs)</help>
+			</parameter>
+		</option>
+		<option value="SMET" type="string">
+			<parameter key="SPECIALPTSFILE" type="file" optional="false">
+				<help>a path+file name to the a file containing grid coordinates of special points of interest (for special outputs)</help>
+			</parameter>
+		</option>
+	</parameter>
+
+	<!-- Datatypes: Meteo Data -->
+	<parameter key="METEO" type="alternative">
+		<section name="input" />
+		<section name="output" />
+
+		<option value="A3D" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="BORMA" type="string">
+			<section name="input" />
+			<reference name="BORMA" />
+		</option>
+		<option value="COSMO" type="string">
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string containing the path to the meteorological files</help>
+			</parameter>
+		</option>
+		<option value="GEOTOP" type="string">
+			<section name="input" />
+			<reference name="GEOTOP_IN" />
+		</option>
+		<option value="GEOTOP" type="string">
+			<section name="output" />
+			<reference name="GEOTOP_OUT" />
+		</option>
+		<option value="GRIB" type="string">
+			<section name="input" />
+			<reference name="GRIB_METEO" />
+		</option>
+		<option value="GSN" type="string">
+			<section name="input" />
+			<reference name="GSN" />
+		</option>
+		<option value="IMIS" type="string">
+			<section name="input" />
+			<reference name="IMIS" />
+		</option>
+		<option value="SMET" type="string">
+			<section name="input" />
+			<reference name="SMET_IN" />
+		</option>
+		<option value="SMET" type="string">
+			<section name="output" />
+			<reference name="SMET_OUT" />
+		</option>
+		<option value="SNOWPACK" type="string">
+			<section name="input" />
+			<reference name="SNIO_IN" />
+		</option>
+		<option value="SNOWPACK" type="string">
+			<section name="output" />
+			<parameter key="METEOPATH" type="path" optional="false">
+				<help>string representing path where SNOWPACK files should be saved</help>
+			</parameter>
+		</option>
+
+		<help>plugin for METEO data </help>
+	</parameter>
+
+	<parameter key="Add Meteo parameter copy" type="selector">
+		<section name="input"/>
+		<parameter key="COPY::%" type="string" optional="false" template="true">
+		  <help>The name of the parameter to copy (e.g. TA, RH, VW, ISWR, etc)</help>
+		</parameter>
+	</parameter>
+
+	<!-- Datatypes: DEM -->
+	<frame key="dem_frame" label="Digital Elevation Model">
+	<section name="input"/>
+		<parameter key="DEM" type="alternative">
+			<section name="input" />
+			<option value="ARC" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+			</option>
+			<option value="ARPS" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<parameter key="ARPS_XCOORD" type="decimal" optional="false">
+					<help>x coordinate of the lower left corner of the grids</help>
+				</parameter>
+				<parameter key="ARPS_YCOORD" type="decimal" optional="false">
+					<help>y coordinate of the lower left corner of the grids</help>
+				</parameter>
+			</option>
+			<option value="GRASS" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+			</option>
+			<option value="GRIB" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<parameter key="GRIB_DEM_UPDATE" type="alternative" optional="true">
+					<option value="TRUE" type="string" />
+					<option value="FALSE" type="string" />
+					<help>recompute slope/azimuth from the elevations when reading a DEM (default=false, that is we use the slope and azimuth included in the GRIB file)</help>
+				</parameter>
+			</option>
+			<option value="PGM" type="string">
+				<parameter key="DEMFILE" type="file" optional="false">
+					<help>For reading the data as a DEMObject</help>
+				</parameter>
+				<reference name="PGM_IN" />
+			</option>
+
+			<help>plugin for Digital Elevation Model data </help>
+		</parameter>
+	</frame>
+
+	<!-- Datatypes: Landuse -->
+	<parameter key="LANDUSE" type="alternative">
+		<section name="input" />
+		<option value="ARC" type="string">
+			<parameter key="LANDUSEFILE" type="file" optional="false">
+				<help>File containing a grid of landuse codes</help>
+			</parameter>
+		</option>
+
+		<help>plugin for land cover data </help>
+	</parameter>
+
+	<!-- Datatypes: Grids -->
+	<parameter key="GRID2D" type="alternative">
+		<section name="input" />
+		<section name="output" />
+		<option value="ARC" type="string">
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="ARC" />
+		</option>
+		<option value="ARPS" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="ARPS" />
+		</option>
+		<option value="GRASS" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+		</option>
+		<option value="GRIB" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="GRIB_GRIDS" />
+		</option>
+		<option value="PGM" type="string">
+			<section name="input" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="PGM_IN" />
+		</option>
+		<option value="PGM" type="string">
+			<section name="output" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+		</option>
+		<option value="PNG" type="string">
+			<section name="output" />
+			<parameter key="GRID2DPATH" type="path" optional="false">
+				<help>string representing path where grid files should be read from</help>
+			</parameter>
+			<reference name="PNG" />
+		</option>
+		<help>plugin for 2D gridded data </help>
+	</parameter>
+
+	<!--Parameter group for list of stations -->
+	<parametergroup name="stationgroup_files">
+		<parameter key="STATION#" type="file" counter="1" optional="false">
+			<help>filename for station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_names">
+		<parameter key="STATION#" type="string" counter="1" optional="false">
+			<help>station id for the given station number # </help>
+		</parameter>
+	</parametergroup>
+	<parametergroup name="stationgroup_pos">
+		<parameter key="STATION#" type="string" counter="1">
+			<help>Coordinates are given as "lat lon" or "xcoord ycoord epsg_code"</help>
+		</parameter>
+	</parametergroup>
+
+	<!-- Plugins for Meteo Data-->
+	<parametergroup name="BORMA">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the xml files</help>
+		</parameter>
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="IMIS">
+		<parameter key="DBNAME" type="string" optional="false">
+			<help>database name, as provided by your database administrator</help>
+		</parameter>
+		<parameter key="DBUSER" type="string" optional="false">
+			<help>database user name</help>
+		</parameter>
+		<parameter key="DBPASS" type="string" optional="false">
+			<help>database password associated with the user name</help>
+		</parameter>
+		<parameter key="USEANETZ" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: use ANETZ stations to provide precipitations for normal IMIS stations.
+		  Each IMIS station is associated with one or two ANETZ stations and does a weighted
+		  average to get what should be its local precipitations</help>
+		</parameter>
+		<parameter key="USE_IMIS_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: if set to false (default), all IMIS precipitation will be deleted (since IMIS stations don't have heated rain gauges, their precipitation measurements are not good in winter conditions). If set to true, it is strongly advised to use a FilterHNWMelt filter to detect snow melting in the rain gauge and perform winter conditions detection in the application.</help>
+		</parameter>
+		<parameter key="USE_SNOWPACK_HNW" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>if set to true, the SNOWPACK simulated Snow Water Equivalent from the database will be used to compute HNW. Data gaps greater than 3 hours on SWE will lead to unchanged hnw while all data that can properly be computed will overwrite hnw. (default=false)</help>
+		</parameter>
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="GRIB_METEO">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the grib files</help>
+		</parameter>
+		<parameter key="METEOEXT" type="string" optional="true">
+			<help>grib file extension, or none for no file extension (default: .grb)</help>
+		</parameter>
+
+		<reference name="stationgroup_pos" />
+	</parametergroup>
+
+	<parametergroup name="GEOTOP_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the data files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="false">
+			<help>absolute filename of the geotop.inpts file</help>
+		</parameter>
+		<parameter key="METEOPREFIX" type="string" optional="true">
+			<help>prefix to append when generating a file name for reading</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GEOTOP_OUT">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the data files</help>
+		</parameter>
+		<parameter key="METEOSEQ" type="string" optional="false">
+			<help>specifiy in which order the columns should be printed out</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GSN">
+		<parameter key="ENDPOINT" type="string" optional="false">
+			<help>webserver running GSN with its port number and full path. For example:
+			http://montblanc.slf.ch:22001/services/A3DWebService</help>
+		</parameter>
+		<parameter key="PROXY" type="string" optional="true">
+			<help>Should the connection go through a proxy? This is useful for servers
+			filtering on domains but usually not necessary.</help>
+		</parameter>
+		<parameter key="PROXYPORT" type="string" optional="true" />
+		<parameter key="PROXYUSER" type="string" optional="true" />
+		<parameter key="PROXYPASS" type="string" optional="true" />
+
+		<reference name="stationgroup_names" />
+	</parametergroup>
+
+	<parametergroup name="SMET_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the smet files</help>
+		</parameter>
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<parametergroup name="SMET_OUT">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string representing path where SMET files should be saved</help>
+		</parameter>
+		<parameter key="METEOPARAM" type="alternative">
+		  <option value="ASCII" type="string" default="true">
+		    <help>Write ASCII SMET files</help>
+		  </option>
+		  <option value="BINARY" type="string">
+		    <help>Write BINARY SMET files</help>
+		  </option>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="SNIO_IN">
+		<parameter key="METEOPATH" type="path" optional="false">
+			<help>string containing the path to the SNOWPACK files</help>
+		</parameter>
+		<parameter key="METAFILE" type="file" optional="true">
+			<help>filename of the meta data file (in METEOPATH)</help>
+		</parameter>
+
+		<parameter key="NUMBER_MEAS_TEMPERATURES" type="integer+" minimum="0" default="0">
+		  <help>the number of measured snow temperatures provided</help>
+		</parameter>
+
+		<parameter key="NUMBER_OF_SOLUTES" type="integer+" minimum="0" default="0">
+		  <help>the number of solutes for which input data are provided</help>
+		</parameter>
+
+		<parameter key="RSWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="ISWR_INP" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		</parameter>
+		<parameter key="VW_DRIFT" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: wind velocity to use for blowing and drifting snow is provided</help>
+		</parameter>
+		<parameter key="RHO_HN" type="alternative" optional="true">
+		  <option value="TRUE" type="string" />
+		  <option value="FALSE" type="string" />
+		  <help>OPTIONAL: measured new snow density is provided</help>
+		</parameter>
+
+		<reference name="stationgroup_files" />
+	</parametergroup>
+
+	<!-- Plugins for Gridded Data-->
+	<parametergroup name="ARC">
+		<parameter key="A3D_VIEW" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate names compatible with Alpine3D's grid viewer?</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grid file extension, or none for no file extension (default: .asc)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="ARPS">
+		<parameter key="ARPS_XCOORD" type="decimal" optional="false">
+			<help>x coordinate of the lower left corner of the grids</help>
+		</parameter>
+		<parameter key="ARPS_YCOORD" type="decimal" optional="false">
+			<help>y coordinate of the lower left corner of the grids</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grid file extension, or none for no file extension (default: .asc)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="GRIB_GRIDS">
+		<parameter key="GRID2DPREFIX" type="string" optional="true">
+			<help>prefix to append when generating a file name for reading (ie: something like "laf" for Cosmo-Analysis-full domain)</help>
+		</parameter>
+		<parameter key="GRID2DEXT" type="string" optional="true">
+			<help>grib file extension, or none for no file extension (default: .grb)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="PNG">
+		<parameter key="PNG_WORLD_FILE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a world file for each output file? This file contains the geolocalization information</help>
+		</parameter>
+		<parameter key="PNG_LEGEND" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a legend?</help>
+		</parameter>
+		<parameter key="PNG_AUTOSCALE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>autoscale color scale?</help>
+		</parameter>
+		<parameter key="PNG_SCALING" type="alternative" optional="true">
+			<option value="nearest" type="string" />
+			<option value="bilinear" type="string" />
+			<help>scaling algorithm (default=bilinear)</help>
+		</parameter>
+		<parameter key="PNG_MIN_SIZE" type="string" optional="false">
+			<help>minimum dimensions of the PNG, like 640x480</help>
+		</parameter>
+		<parameter key="PNG_MAX_SIZE" type="string" optional="false">
+			<help>maximum dimensions of the PNG, like 1024x768</help>
+		</parameter>
+		<parameter key="PNG_INDEXED" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>generate a color indexed file (default=true)</help>
+		</parameter>
+		<parameter key="PNG_SPEED_OPTIMIZE" type="alternative" optional="true">
+			<option value="TRUE" type="string" />
+			<option value="FALSE" type="string" />
+			<help>optimize for speed (default=false)</help>
+		</parameter>
+		<parameter key="PNG_NR_LEVELS" type="integer+" default="+30" maximum="255" minimum="6" optional="true">
+			<help>number of colors in the palette (default=30)</help>
+		</parameter>
+	</parametergroup>
+
+	<parametergroup name="PGM_IN">
+		<parameter key="PGM_XCOORD" type="decimal" optional="false">
+			<help>lower left x coordinate</help>
+		</parameter>
+		<parameter key="PGM_YCOORD" type="decimal" optional="false">
+			<help>lower left y coordinate</help>
+		</parameter>
+		<parameter key="PGM_CELLSIZE" type="decimal" optional="false">
+			<help>cellsize in meters</help>
+		</parameter>
+		<parameter key="PGM_MIN" type="decimal" optional="false">
+			<help>minimum value in real world coordinates to match with the minimum value read out of the PGM file (such minimum being greater than 0 because 0 is NODATA)</help>
+		</parameter>
+		<parameter key="PGM_MAX" type="decimal" optional="false">
+			<help>maximum value in real world coordinates to match with the maximum value read out of the PGM file</help>
+		</parameter>
+	</parametergroup>
+
+	<!-- Meteo Parameters for Filters, resampling, spatial interpolations-->
+	<parametergroup name="METEOIOPARAMETERS">
+		<option value="TA"/>
+		<option value="RH"/>
+		<option value="VW"/>
+		<option value="DW"/>
+		<option value="VW_MAX"/>
+		<option value="ISWR"/>
+		<option value="RSWR"/>
+		<option value="ILWR"/>
+		<option value="HS"/>
+		<option value="HNW"/>
+		<option value="TSG"/>
+		<option value="TSS"/>
+		<option value="P"/>
+	</parametergroup>
+
+	<!-- Filters -->
+	<parameter key="Add/Remove Filter" type="selector">
+		<section name="filters" />
+
+		<parameter key="%::filter#" type="alternative" counter="1" template="true">
+			<section name="filters" />
+
+			<option label="MeanAvg" value="mean_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+
+			<option label="MedianAvg" value="median_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="decimal" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median average processing. The median average filter returns the median value of all values within a user given time window.</help>
+			</option>
+
+			<option label="Std Deviation Filter" value="std_dev" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Standard deviation filter. Values outside of mean ± 2 std_dev are rejected.</help>
+			</option>
+
+			<option label="MAD" value="mad" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Median Absolute Deviation. Values outside of median ± 3 σ_MAD are rejected. &lt;br&gt;
+			  See http://en.wikipedia.org/wiki/Median_absolute_deviation for more information.</help>
+			</option>
+
+			<option label="Tukey 53H Filter" value="Tukey" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      The keyword "soft" maybe added, if the window position is allowed to be adjusted to the data present.
+			      The two arguments may be preceded by the keywords "left", "center" or "right", indicating the window position.
+			    </help>
+			  </parameter>
+			  <help>Tukey 53H method A smooth time sequence is generated from the median, substracted from the original signal and
+			  compared with the standard deviation. see "Despiking Acoustic Doppler Velocimeter Data", Derek G. Goring and Vladimir
+			  L. Nikora, Journal of Hydraulic Engineering, 128, 1, 2002 The deviation factor coeffecient is currently hard-coded as k=1.5. </help>
+			</option>
+
+			<option label="Wind Averaging Filter" value="wind_avg" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			    </help>
+			  </parameter>
+			  <help>Wind vector averaging. This calculates the vector average over a user given time period. Each wind vector
+			  within this period is added and the final sum is normalized by the number of vectors that have been added. </help>
+			</option>
+
+			<option label="Exponential Smoothing" value="exp_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <option label="alpha:" value="0.8" type="decimal" minimum="0" maximum="1"/>
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Alpha needs to be provided as last argument. Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Exponential smooting processing, exponential moving average s_0 = x_0 s_n = alpha*x_(t-1) + (1-alpha)*s_t-1</help>
+			</option>
+
+			<option label="Weighted Moving Average Smoothing" value="wma_smoothing" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option value="center" type="dropdown">
+			      <option value="left" type="string" />
+			      <option value="center" type="string" />
+			      <option value="right" type="string" />
+			    </option>
+			    <option label="# of points:" value="1" type="integer" minimum="1" />
+			    <option label="Duration:" value="0" type="integer" minimum="0" />
+			    <help>
+			      Activate "soft" if the window position is allowed to be adjusted, window position maybe left, center or right.
+			      Minimal number of points in window and minimal time interval spanning the window (seconds) are required.
+			      Please note that the standard filter works with a left window!
+			    </help>
+			  </parameter>
+			  <help>Weighted moving average smoothing such as: WMA = (1*X1 + 2*X2 + ... + n*Xn) / sum_of_weights</help>
+			</option>
+
+			<option label="Min Range Filter" value="min" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data smaller than the min would be
+			    assigned the minimum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Min range filter. Reject all values smaller than the min.</help>
+			</option>
+
+			<option label="Max Range Filter" value="max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be
+			    assigned the maximum permissible value or another value given as an extra argument</help>
+			  </parameter>
+			  <help>Max range filter. Reject all values greater than the max.</help>
+			</option>
+
+			<option label="MinMax (2 or 4 arguments)" value="min_max" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="Min:" value="" type="decimal" />
+			    <option label="Max:" value="" type="decimal" />
+			    <option label="Min adjust to:" value="" type="decimal" />
+			    <option label="Max adjust to:" value="" type="decimal" />
+			    <help>The keyword "soft" maybe added, in such a case all data greater than the max would be assigned
+			    the maximum permissible value and all data smaller than the min would be assigned the minimum
+			    permissible value or an optional extra set of two user provided values</help>
+			  </parameter>
+			  <help>Reject all values greater than the max or smaller than the min. &lt;br&gt;</help>
+			</option>
+
+			<option label="Rate Filter (1 argument)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the absolute value of the maximum permissible rate of change (per seconds)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Rate Filter (2 arguments)" value="rate" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="Min:" value="0.0" type="decimal" minimum="0" maximum="1" />
+			    <option label="Max:" value="1.0" type="decimal" minimum="0" maximum="1" />
+			    <help>the minimum and maximum permissible rate of change (per second)</help>
+			  </parameter>
+			  <help>Rate of change filter. Calculate the change rate (ie: slope) between two points, if it is above a user given value, reject the point.</help>
+			</option>
+
+			<option label="Unheated Rain Gauge Filter" value="Unheated_RainGauge" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option value="soft" type="choice" />
+			    <option label="RH threshold:" value="0.5" type="decimal" minimum="0" maximum="1" />
+			    <option label="Delta_T threshold:" value="3.0" type="decimal" minimum="0" maximum="20" />
+			  </parameter>
+			  <help>Filters out snow melting in an unheated rain gauge. This filter can ONLY be applied to precipitation. Non-zero measurements are accepted only if they take place when the relative humidity is greater than RH_threshold and (TA-TSS) smaller than Delta_T_threshold, otherwise they get reset to 0. If none of these conditions could be tested (for lack of data), then the precipitation is reset to nodata (or left unchanged if "soft" has been selected).</help>
+			</option>
+
+			<option label="WMO Undercatch Filter" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Gage type" type="dropdown">
+					<option value="Nipher" type="string" />
+					<option value="Tretyakov" type="string" />
+					<option value="US8sh" type="string" />
+					<option value="US8unsh" type="string" />
+					<option value="Hellmann" type="string" />
+					<option value="Hellmannsh" type="string" />
+				</option>
+			  </parameter>
+			  <help>This implements the standard methods for precipitation correction as described in "WMO Solid Precipitation Measurement Intercomparison", B. Goodison, P. Louie and D. Yang, 872, 1998 as well as the overview given by "Literature Study on the Correction of Precipitation Measurements", Annette Wagner, 2009. The correction parameters for the shielded Hellmann gauge (German version) are from "Wind-induced Precipitation Undercatch of the Hellmann Gauges", Daqing Yang et al, Nordic Hydrology, 30, 1999, pp 57-80.</help>
+			</option>
+
+			<option label="WMO Undercatch Filter - simplified" value="undercatch_wmo" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option value="Kind" type="dropdown">
+					<option value="Cst" type="string" />
+				</option>
+				<option label="Snow factor:" value="1.3" type="decimal" minimum="0" maximum="5" />
+				<option label="Mixed prec factor:" value="1.1" type="decimal" minimum="0" maximum="5" />
+			  </parameter>
+			  <help>This applies a constant correction factor to the precipitation, one for pure snow and one for mixed precipitation. The following thresholds are used: pure snow below -2 C; mixed precipitation between -2 and +2 C; pure rain above 2 C. These threshold can be changed (see online documentation).</help>
+			</option>
+
+			<option label="Unventillated temperature sensor" value="Unventilated_T" type="string">
+			  <parameter key="%::arg#" type="combination">
+			    <option label="albedo:" value="0.23" type="decimal" />
+			    <option value="soft" type="choice" />
+			    <help>If the "soft" option is given, the albedo has a value different according to snow (or no snow) on the ground</help>
+			  </parameter>
+			  <help>This implements the correction described in (Reina Nakamura, 2005) with an albedo dependency as introduced in (Huwald, 2009)</help>
+			</option>
+
+			<option label="Add an offset" value="add" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="offset:" value="0." type="decimal" />
+			  </parameter>
+			  <help>This adds a given offset to the data.</help>
+			</option>
+
+			<option label="Multiply by a factor" value="mult" type="string">
+			  <parameter key="%::arg#" type="combination">
+				<option label="factor:" value="1." type="decimal" />
+			  </parameter>
+			  <help>This multiplies the data by a given factor.</help>
+			</option>
+
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+	<!-- 1D Interpolation -->
+	<parameter key="WINDOW_SIZE" type="integer+" minimum="1" default="43200">
+		<section name="Interpolations1D" />
+		<help>Affects resampling: expresses (in seconds) how far a valid point can be
+		searched for when re-interpolating a missing value</help>
+	</parameter>
+
+	<parameter key="Add/Remove 1D Interpolation" type="selector">
+		<section name="Interpolations1D" />
+
+		<parameter key="%::resample" type="alternative" template="true">
+			<section name="Interpolations1D" />
+			<option label="No Interpolation" value="none" type="string" />
+			<option label="Nearest Neighbour" value="nearest_neighbour" type="string" />
+			<option label="Linear" value="linear" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="extrapolate" type="choice" />
+			    <help>
+			      If "extrapolate" is added, then data *outside* of the original date range can be interpolated.
+			      Otherwise, a data point will only be calculated between the original date range.
+			    </help>
+			  </parameter>
+			  <help>Mean average processing. The mean average filter returns the mean value of all values within a user given time window.</help>
+			</option>
+			<option label="Accumulate" value="accumulate" type="string">
+			  <parameter key="%::args" type="combination">
+			    <option value="strict" type="choice" />
+			    <option label="Seconds:" value="900" type="integer" minimum="1" />
+			    <help>Accumulation period (in seconds). This must usually match the model time step. if enabling "strict", nodatas will propagate (ie. a single nodata in the input will force the re-accumulated value to be nodata). Otherwise, all valid values are aggregated and only pure nodata intervals produce a nodata in the output.</help>
+			  </parameter>
+			  <help>Accumulation over a user given period (filter argument, in seconds -
+			  should coincide with your calculation step!).</help>
+			</option>
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+
+	<!-- 2D Interpolation -->
+	<parameter key="Add/Remove 2D Interpolation" type="selector">
+		<section name="Interpolations2D" />
+
+		<parameter key="%::algorithms" type="choice" template="true">
+			<section name="Interpolations2D" />
+			<option value="STD_PRESS" type="choice">
+				<help>Generate a standard atmosphere pressure as a function of the cell's elevation</help>
+			</option>
+			<option value="CST" type="choice">
+				<help>Fill the grid with the average over all the stations</help>
+			</option>
+			<option value="CST_LAPSE" type="choice">
+			  <parameter key="%::cst_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Detrend the measured data, fill the grid with the average over all the stations, reapply the elevation trend</help>
+			</option>
+			<option value="IDW" type="choice">
+				<help>Inverse Distance Weighted average</help>
+			</option>
+			<option value="IDW_LAPSE" type="choice">
+			  <parameter key="%::idw_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Detrend the measured data, apply Inverse Distance Weighted average, reapply elevation trend</help>
+			</option>
+			<option value="LIDW_LAPSE" type="choice">
+			  <parameter key="%::lidw_lapse" type="combination">
+			    <option label="Lapse Rate:" value="0.008" type="decimal" optional="false" />
+			    <option value="" type="dropdown">
+			      <option value="" type="string" />
+			      <option value="soft" type="string" />
+			      <option value="frac" type="string" />
+			    </option>
+			  </parameter>
+			  <help>Same as IDW_LAPSE, but only considering a given number of neighboring stations</help>
+			</option>
+			<option value="RH" type="choice">
+				<help>Computes the dew point temperature, distribute it with IDW_LAPSE, recompute RH at each pixel</help>
+			</option>
+			<option value="ILWR" type="choice">
+				<help>Compute emissivity, distribute it with IDW_LAPSE, recompute ILWR at each pixel</help>
+			</option>
+			<option value="WIND_CURV" type="choice">
+				<help>Distribute wind velocity with IDW_LAPSE, then apply correction factors as a function of local slope and curvature</help>
+			</option>
+			<option value="HNW_SNOW" type="choice">
+				<parameter key="%::hnw_snow" type="combination">
+				<option value="IDW_LAPSE" type="dropdown">
+					<option value="CST" type="string" />
+					<option value="CST_LAPSE" type="string" />
+					<option value="IDW" type="string" />
+					<option value="IDW_LAPSE" type="string" />
+					<option value="ODKRIG" type="string" />
+				</option>
+				<help>Base algorithm (do not forget to add the options for the base algorithm)</help>
+				</parameter>
+				<help>Distribute precipitation with a base algorithm (IDW_LAPSE by default), then reduce/remove precipitation on
+				steep slopes and correct with the local curvature. This is to simulate snow redistribution processes.</help>
+			</option>
+			<option value="USER" type="choice">
+			  <parameter key="%::user" type="path" optional="false"/>
+			  <help>User provided grids, named as {numeric date}_{capitalized meteo parameter}.asc</help>
+			</option>
+			<option value="ODKRIG" type="choice">
+			  <parameter key="%::odkrig" type="combination">
+			  	<option value="" type="dropdown">
+					<option value="LINVARIO" type="string" />
+					<option value="EXPVARIO" type="string" />
+					<option value="SPHERICVARIO" type="string" />
+					<option value="RATQUADVARIO" type="string" />
+				</option>
+				<help>Variogram model</help>
+			  </parameter>
+			  <help>Ordinary kriging (EXPERIMENTAL)</help>
+			</option>
+		</parameter>
+
+		<reference name="METEOIOPARAMETERS" />
+	</parameter>
+</inishell_config>
Index: /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/icons/readme.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/icons/readme.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/java/src/resources/icons/readme.txt	(revision 18231)
@@ -0,0 +1,10 @@
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+This copyright and license notice covers the images in this directory.
+************************************************************************
+
+TITLE:	Crystal Project Icons
+AUTHOR:	Everaldo Coelho
+SITE:	http://www.everaldo.com
+CONTACT: everaldo@everaldo.com
+
+Copyright (c)  2006-2007  Everaldo Coelho.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/Makefile.am	(revision 18231)
@@ -0,0 +1,83 @@
+#To generate list of directories
+#
+#find . -type d -exec ls -d {} \;
+
+bin_SCRIPTS = 
+if WRAPPERS
+if MATLAB
+if !DEVELOPMENT
+bin_SCRIPTS += ./qmu/*.m \
+					./qmu/setupdesign/*.m \
+					./qmu/plot/*.m \
+					./qmu/examples/*.m \
+					./kml/*.m \
+					./enum/*.m \
+					./dev/issmversion.m \
+					./classes/*.m \
+					./classes/qmu/*.m \
+					./classes/qmu/@dakota_method/*.m \
+					./classes/clusters/*.m \
+					./consistency/*.m \
+					./array/*.m \
+					./boundaryconditions/*.m \
+					./exp/*.m \
+					./exp/operation/*.m \
+					./geometry/*.m \
+					./interp/*.m \
+					./coordsystems/*.m \
+					./mech/*.m \
+					./mesh/*.m \
+					./mesh/planet/*.m \
+					./mesh/rifts/*.m \
+					./miscellaneous/*.m \
+					./os/*.m \
+					./plot/*.m \
+					./plot/colormaps/*.m \
+					./string/*.m \
+					./contrib/massbalance/*.m \
+					./contrib/ecco/*.m \
+					./contrib/hydrology/*.m \
+					./contrib/hack/*.m \
+					./contrib/gslib/*.m \
+					./contrib/uci/*.m \
+					./contrib/oasis/*.m \
+					./contrib/bamg/*.m \
+					./extrusion/*.m \
+					./inversions/*.m \
+					./io/*.m \
+					./parameterization/*.m \
+					./partition/*.m \
+					./print/*.m \
+					./regional/*.m \
+					./solve/*.m \
+					./solvers/*.m \
+					./materials/*.m
+endif
+endif
+if PYTHON
+if !DEVELOPMENT
+bin_SCRIPTS += ./enum/*.py \
+					./classes/*.py \
+					./classes/clusters/*.py \
+					./consistency/*.py \
+					./dev/issmversion.py \
+					./boundaryconditions/*.py \
+					./exp/*.py \
+					./geometry/*.py \
+					./coordsystems/*.py \
+					./interp/*.py \
+					./mech/*.py \
+					./mesh/*.py \
+					./mesh/rifts/*.py \
+					./miscellaneous/*.py \
+					./os/*.py \
+					./plot/*.py \
+					./extrusion/*.py \
+					./io/*.py \
+					./parameterization/*.py \
+					./solve/*.py \
+					./solvers/*.py \
+					./materials/*.py
+endif
+endif
+endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allempty.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allempty.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allempty.m	(revision 18231)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty cell array if all array elements are empty
+%
+%  function [cout]=allempty(cin)
+%
+function [cout]=allempty(cin)
+
+if ~nargin
+    help allempty
+    return
+end
+
+for j=1:numel(cin)
+    if ~isempty(cin{j})
+        cout=cin;
+        return
+    end
+end
+cout={};
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allequal.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allequal.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allequal.m	(revision 18231)
@@ -0,0 +1,70 @@
+%
+%  function to return an empty array if all array elements are
+%  equal to the given value, which may also be empty but not nan.
+%
+%  (note that by definition, nan is not equal to nan.  this could
+%  be changed by using isequalwithequalnans.)
+%
+%  function [aout]=allequal(ain,aval)
+%
+function [aout]=allequal(ain,aval)
+
+if ~nargin
+    help allequal
+    return
+end
+
+aout=ain;
+
+if     islogical(ain) && islogical(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=logical([]);
+
+elseif isnumeric(ain) && isnumeric(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=[];
+
+elseif ischar(ain) && ischar(aval)
+    for i=1:size(ain,1)
+        if ~strcmp(ain(i,:),aval)
+            return
+        end
+    end
+    aout='';
+
+elseif iscell(ain)
+    if     islogical(aval)
+        for i=1:numel(ain)
+            if ~islogical(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif isnumeric(aval)
+        for i=1:numel(ain)
+            if ~isnumeric(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif ischar(aval)
+        for i=1:size(ain,1)
+            if ~ischar(ain{i}) || ~strcmp(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allnan.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allnan.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/allnan.m	(revision 18231)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty double array if all array elements are NaN
+%
+%  function [dout]=allnan(din)
+%
+function [dout]=allnan(din)
+
+if ~nargin
+    help allnan
+    return
+end
+
+for i=1:numel(din)
+    if ~isnan(din(i))
+        dout=din;
+        return
+    end
+end
+dout=[];
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/any2str.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/any2str.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/any2str.m	(revision 18231)
@@ -0,0 +1,22 @@
+%
+%  function to convert anything to a string
+%
+%  function [svec]=any2str(a,alim)
+%
+function [svec]=any2str(a,alim)
+
+if ~exist('alim','var') || (numel(a) <= alim)
+    if iscell(a)
+        svec=string_cell(a);
+    else
+        if (numel(a) > 1) && ~ischar(a)
+            svec=string_vec(a);
+        else
+            svec=item2str(a);
+        end
+    end
+else
+	svec=[string_size(a) ' ''' class(a) ''''];
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_numel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_numel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_numel.m	(revision 18231)
@@ -0,0 +1,35 @@
+%
+%  function to find a number of elements from a list of arrays.
+%  
+%  [asize]=array_numel(varargin)
+%
+%  see array_size to check the number and shape of elements, if
+%  multiple indices will be used.
+%
+function [anum]=array_numel(varargin)
+
+anum=1;
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        inum=numel(cellstr(varargin{iarg}));
+    else
+        inum=numel(varargin{iarg});
+    end
+
+    if ~isequal(inum,1)
+        if isequal(anum,1)
+            anum=inum;
+        else
+            if ~isequal(inum,anum)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent number of elements.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent number of elements.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_size.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_size.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/array_size.m	(revision 18231)
@@ -0,0 +1,35 @@
+%
+%  function to find an array size from a list of arrays.
+%  
+%  [asize]=array_size(varargin)
+%
+%  see array_numel to check only the number of elements, if
+%  single indices will be used.
+%
+function [asize]=array_size(varargin)
+
+asize=[1 1];
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        isize=size(cellstr(varargin{iarg}));
+    else
+        isize=size(varargin{iarg});
+    end
+
+    if ~isequal(isize,[1 1])
+        if isequal(asize,[1 1])
+            asize=isize;
+        else
+            if ~isequal(isize,asize)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent size.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent size.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/find_string.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/find_string.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/find_string.m	(revision 18231)
@@ -0,0 +1,18 @@
+%
+%  function to find a string in a cell array
+%  (could probably be replaced by matlab strmatch)
+%  
+%  [ifound]=find_string(cells,str)
+%
+function [ifound]=find_string(cells,str)
+
+ifound=false;
+
+for i=1:numel(cells)
+    if ischar(cells{i}) && strcmp(cells{i},str)
+        ifound=i;
+        return
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/item2str.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/item2str.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/item2str.m	(revision 18231)
@@ -0,0 +1,31 @@
+%
+%  function to convert an item to a string
+%
+%  function [svec]=item2str(a)
+%
+function [svec]=item2str(a)
+
+if     islogical(a)
+    if a
+        svec='true';
+    else
+        svec='false';
+    end
+elseif ischar(a)
+    svec=['''' a ''''];
+elseif isnumeric(a)
+    svec=num2str(a);
+else
+    if ~isempty(inputname(1))
+        warning('item2str:item_unrecog',...
+            'Item ''%s'' is of unrecognized type ''%s''.',...
+            inputname(1),class(a));
+    else
+        warning('item2str:item_unrecog',...
+            'Item %d is of unrecognized type ''%s''.',...
+            1,class(a));
+    end
+    return
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/rotateticklabel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/rotateticklabel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/rotateticklabel.m	(revision 18231)
@@ -0,0 +1,69 @@
+function th=rotateticklabel(h,rot,demo)
+%ROTATETICKLABEL rotates tick labels
+%   TH=ROTATETICKLABEL(H,ROT) is the calling form where H is a handle to
+%   the axis that contains the XTickLabels that are to be rotated. ROT is
+%   an optional parameter that specifies the angle of rotation. The default
+%   angle is 90. TH is a handle to the text objects created. For long
+%   strings such as those produced by datetick, you may have to adjust the
+%   position of the axes so the labels don't get cut off.
+%
+%   Of course, GCA can be substituted for H if desired.
+%
+%   TH=ROTATETICKLABEL([],[],'demo') shows a demo figure.
+%
+%   Known deficiencies: if tick labels are raised to a power, the power
+%   will be lost after rotation.
+%
+%   See also datetick.
+
+%   Written Oct 14, 2005 by Andy Bliss
+%   Copyright 2005 by Andy Bliss
+
+%DEMO:
+if nargin==3
+    x=[now-.7 now-.3 now];
+    y=[20 35 15];
+    figure
+    plot(x,y,'.-')
+    datetick('x',0,'keepticks')
+    h=gca;
+    set(h,'position',[0.13 0.35 0.775 0.55])
+    rot=90;
+end
+
+%set the default rotation if user doesn't specify
+if nargin==1
+    rot=90;
+end
+%make sure the rotation is in the range 0:360 (brute force method)
+while rot>360
+    rot=rot-360;
+end
+while rot<0
+    rot=rot+360;
+end
+%get current tick labels
+a=get(h,'XTickLabel');
+%erase current tick labels from figure
+set(h,'XTickLabel',[]);
+%get tick label positions
+b=get(h,'XTick');
+c=get(h,'YTick');
+%make new tick labels
+%  must consider yscale (jes, 9/14/10)
+switch lower(get(h,'YScale'))
+    case 'linear'
+        if rot<180
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    case 'log'
+        if rot<180
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    otherwise
+        set(h,'XTickLabel',a);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/str2int.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/str2int.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/str2int.m	(revision 18231)
@@ -0,0 +1,45 @@
+%
+%  function to find and read the first or last positive integer
+%  in a character string.
+%
+%  function [aint]=str2int(astr,cfl)
+%
+function [aint]=str2int(astr,cfl)
+
+aint=[];
+
+if     ~exist('cfl','var') || strncmpi(cfl,'f',1)
+    i=1;
+
+    while (i <= length(astr))
+        if (astr(i) >= '0' && astr(i) <= '9')
+            aint=sscanf(astr(i:length(astr)),'%d',[1,1]);
+            return
+        else
+            i=i+1;
+        end
+	end
+
+elseif strncmpi(cfl,'l',1)
+    i=length(astr);
+    ifound=false;
+
+    while (i >= 1)
+        if     (astr(i) >= '0' && astr(i) <= '9')
+            ifound=true;
+            i=i-1;
+        elseif ~ifound
+            i=i-1;
+        else
+            aint=sscanf(astr(i+1:length(astr)),'%d',[1,1]);
+            return
+        end
+	end
+
+    if ifound
+        aint=sscanf(astr,'%d',[1,1]);
+        return
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_cell.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_cell.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_cell.m	(revision 18231)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of a cell array
+%
+%  function [svec]=string_cell(a)
+%
+function [svec]=string_cell(a)
+
+if ~nargin
+    help string_cell
+    return
+end
+
+if (numel(a) == 0)
+    svec='{}';
+    return
+end
+
+%  assemble string for output
+
+svec ='{';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a{i}) ' '];
+end
+svec=[svec item2str(a{end}) '}'];
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_dim.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_dim.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_dim.m	(revision 18231)
@@ -0,0 +1,72 @@
+%
+%  function to return the string dimension of an array element
+%
+%  function [sdim]=string_dim(a,idim,varargin)
+%
+function [sdim]=string_dim(a,idim,varargin)
+
+if ~nargin
+    help string_dim
+    return
+end
+
+%  check for scalar
+
+if (numel(a) == 1) && (idim == 1)
+    sdim='';
+    return
+end
+
+%  check for overflow
+
+if (idim > numel(a))
+    if ~isempty(inputname(1))
+        error('Index %d exceeds number of elements in array ''%s''.',...
+            idim,inputname(1));
+    else
+        error('Index %d exceeds number of elements in array %d.',...
+            idim,1);
+    end
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-2
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            sdim =['(' num2str(idim) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+index=zeros(size(asize));
+aprod=prod(asize);
+idim =idim-1;
+
+%  calculate indices base 0 and convert to base 1
+
+%  note that ind2sub might be useful, except that it requires a list
+%  of scalars rather than a vector for output.
+
+for i=length(asize):-1:1
+    aprod=aprod/asize(i);
+    index(i)=floor(idim/aprod);
+    idim=idim-index(i)*aprod;
+end
+index=index+1;
+
+%  assemble string for output
+
+sdim ='(';
+for i=1:length(asize)-1;
+    sdim =[sdim num2str(index(i)) ','];
+end
+sdim =[sdim num2str(index(end)) ')'];
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_size.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_size.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_size.m	(revision 18231)
@@ -0,0 +1,38 @@
+%
+%  function to return the string size of an array
+%
+%  function [ssize]=string_size(a,varargin)
+%
+function [ssize]=string_size(a,varargin)
+
+if ~nargin
+    help string_size
+    return
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-1
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            ssize =['(' num2str(numel(a)) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+
+%  assemble string for output
+
+ssize ='(';
+for i=1:length(asize)-1;
+    ssize =[ssize num2str(asize(i)) 'x'];
+end
+ssize =[ssize num2str(asize(end)) ')'];
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_vec.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_vec.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/string_vec.m	(revision 18231)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of an vector
+%
+%  function [svec]=string_vec(a)
+%
+function [svec]=string_vec(a)
+
+if ~nargin
+    help string_vec
+    return
+end
+
+if (numel(a) == 0)
+    svec='[]';
+    return
+end
+
+%  assemble string for output
+
+svec ='[';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a(i)) ' '];
+end
+svec=[svec item2str(a(end)) ']'];
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_class.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_class.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_class.m	(revision 18231)
@@ -0,0 +1,30 @@
+%
+%  function to find the structural fields of a specified class
+%  
+%  [sclasso]=struc_class(sclass,cstr)
+%
+function [sclasso]=struc_class(sclass,cstr)
+
+%  collect only the objects of the appropriate class
+
+if     isa(sclass,cstr)
+    if ~isempty(inputname(1))
+        sclasso.(inputname(1))=sclass;
+    else
+        sclasso.(cstr)        =sclass;
+    end
+
+elseif isstruct(sclass)
+    fnames=fieldnames(sclass);
+    for i=1:numel(fnames)
+        if isa(sclass.(fnames{i}),cstr)
+            sclasso.(fnames{i})=sclass.(fnames{i});
+        end
+    end
+end
+
+if ~exist('sclasso','var')
+    sclasso=struct([]);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_desc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_desc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/array/struc_desc.m	(revision 18231)
@@ -0,0 +1,61 @@
+%
+%  function to find the structures with the specified descriptors
+%  
+%  [sarrayo]=struc_desc(sarray,varargin)
+%
+function [sarrayo]=struc_desc(sarray,varargin)
+
+if ~isfield(sarray,'descriptor')
+    if ~isempty(inputname(1))
+        error('Field ''descriptor'' not found in array ''%s''.',inputname(1));
+    else
+        error('Field ''descriptor'' not found in array %d.',1);
+    end
+end
+
+sarrayo=struct([]);
+
+for iarg=1:nargin-1
+    if     iscell(varargin{iarg})
+        desc=        varargin{iarg};
+    elseif ischar(varargin{iarg})
+        desc=cellstr(varargin{iarg});
+    end
+
+    for i=1:length(desc)
+        sarrayoi=struc_desci(sarray,desc{i});
+        if ~isempty(sarrayoi)
+            if isempty(sarrayo)
+                sarrayo       =sarrayoi;
+            else
+                sarrayo(end+1)=sarrayoi;
+            end
+        end
+    end
+end
+
+%  if nothing found, return whole array
+
+if isempty(sarrayo)
+    sarrayo=sarray;
+end
+
+end
+
+%
+%  function to find the structure with the specified descriptor
+%  
+function [sarrayo]=struc_desci(sarray,str)
+
+sarrayo=struct([]);
+
+for i=1:numel(sarray)
+    if strcmp(sarray(i).descriptor,str)
+        sarrayo=sarray(i);
+        return
+    end
+end
+
+warning(['String ''' str ''' not found in array ''' inputname(1) '''.']);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.m	(revision 18231)
@@ -0,0 +1,51 @@
+function smb=PattynSMB(md,Tf)
+%PATTYNSMB- Compute SMB over Antarctica (from Pattyn 2006, pg. 18, "GRANTISM: An ExcelTM model for Greenland and 
+%           Antarctic ice-sheet response to climate changes")
+%
+%   Usage:
+%      md=PattynSMB(md,Tf)
+%
+%      where Tf is a background forcing temperature ("an anomalous temperature relative to the present conditions)
+%
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+ 
+% Tma    : Mean annual surface temperature in [deg C]
+% Tms    : Mean summer temperature in [deg C]
+% h      : Surface/bedrock elevation (I assume in meters but paper does not specify)
+% phi    : Latitude in degrees SOUTH
+% lambda : Longitude in degrees WEST
+% Tf     : Background forcing temperature ("an anomalous temperature relative to the present conditions)
+% ACCdot : Accumulation rate in units of [m/a] ice equivalent
+% ABLdot : Surface ablation rate in [m/a] ice equivalent
+
+	%Double check lat and long exist:
+	if isnan(md.mesh.lat),
+		error('PattynSMB error message: md.mesh.lat field required');
+	end
+
+	%Delta Temperature forcing 
+	if (nargin==1),
+		Tf=0; 
+	end
+
+	% Calculate mean annual surface temperature, Eqn (11)
+	% Here, -0.012 is the atmospheric Lapse rate from sea level in deg/m.
+	% It is multiplied by surface elevation from sea level
+	Tma = -15.15 - 0.012*md.geometry.surface;
+
+	%% Calculate summer temperature, Eqn (12)
+	%% No melting at PIG in mean conditions - need about 6 degress Tf to start having a negative yearly SMB
+	Tms = 16.81 - 0.00692*md.geometry.surface - 0.27937*abs(md.mesh.lat) + Tf;
+
+	%% Calculate Accumulation perturbation with Tf forcing, Eqn (9)
+	ACCdot = 2.5*2.^((Tma+Tf)/10.) - 2.5*2.^(Tma/10.);
+
+	%% Calculate Ablation, Eqn (10) (use for both Antarctica & Greenland), max melt is 10m/a
+	ABLdot=zeros(size(ACCdot));
+	pos=Tms>=0;
+	ABLdot(pos)=min(1.4*Tms(Tms>=0),10);
+
+	smb=ACCdot-ABLdot;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/PattynSMB.py	(revision 18231)
@@ -0,0 +1,50 @@
+import os
+import numpy as npy
+def PattynSMB(md,Tf):
+	"""
+    PATTYNSMB- Compute SMB over Antarctica (from Pattyn 2006, pg. 18, "GRANTISM: An ExcelTM model for Greenland 
+	and Antarctic ice-sheet response to climate changes")
+
+    Usage:
+      md=PattynSMB(md,Tf)
+
+      where Tf is a background forcing temperature ("an anomalous temperature relative to the present conditions)
+
+
+    See also: SETICESHELFBC, SETMARINEICESHEETBC
+	"""
+ 
+	# Tma    : Mean annual surface temperature in [deg C]
+	# Tms    : Mean summer temperature in [deg C]
+	# h      : Surface/bedrock elevation (I assume in meters but paper does not specify)
+	# phi    : Latitude in degrees SOUTH
+	# lambda : Longitude in degrees WEST
+	# Tf     : Background forcing temperature ("an anomalous temperature relative to the present conditions)
+	# ACCdot : Accumulation rate in units of [m/a] ice equivalent
+	# ABLdot : Surface ablation rate in [m/a] ice equivalent
+
+	#Double check lat and long exist:
+	if npy.any(npy.isnan(md.mesh.lat)): 
+		raise IOError('PattynSMB error message: md.mesh.lat field required')
+
+	# Calculate mean annual surface temperature, Eqn (11)
+	# Here, -0.012 is the atmospheric Lapse rate from sea level in deg/m.
+	# It is multiplied by surface elevation from sea level
+	Tma = -15.15 - 0.012*md.geometry.surface
+	
+
+	# Calculate summer temperature, Eqn (12)
+	# No melting at PIG in mean conditions - need about 6 degress Tf to start having a negative yearly SMB
+	Tms = 16.81 - 0.00692*md.geometry.surface - 0.27937*npy.abs(md.mesh.lat) + Tf
+	Tms= Tms[0]
+
+	# Calculate Accumulation perturbation with Tf forcing, Eqn (9)
+	ACCdot = 2.5*2**((Tma+Tf)/10.) - 2.5*2**(Tma/10.)
+
+	# Calculate Ablation, Eqn (10) (use for both Antarctica & Greenland), max melt is 10m/a
+	ABLdot=0.*npy.ones(md.mesh.numberofvertices)
+	pos=npy.nonzero(Tms>=0)
+	ABLdot[pos]=npy.minimum(1.4*Tms[pos],10)
+
+	smb=ACCdot-ABLdot
+	return smb[0]
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.m	(revision 18231)
@@ -0,0 +1,55 @@
+function md=SetIceSheetBC(md)
+%SETICESHEETBC - Create the boundary conditions for stressbalance and thermal models for an IceSheet with no Ice Front
+%
+%   Usage:
+%      md=SetIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet
+pos=find(md.mesh.vertexonboundary);
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+md.stressbalance.spcvz(pos)=0;
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for stressbalance model: spc set as zero');
+end
+
+%No ice front: do nothing
+
+%Initialize surface and basal forcings
+md.surfaceforcings = initialize(md.surfaceforcings,md);
+md.basalforcings   = initialize(md.basalforcings,md);
+
+%Deal with other boundary conditions
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	if isprop(md.mesh,'vertexonsurface')
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=50.*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceSheetBC.py	(revision 18231)
@@ -0,0 +1,59 @@
+import os
+import numpy
+from ContourToMesh import ContourToMesh
+
+def SetIceSheetBC(md):
+	"""
+	SETICESHEETBC - Create the boundary conditions for stressbalance 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.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvx[pos]=0
+	md.stressbalance.spcvy[pos]=0
+	md.stressbalance.spcvz[pos]=0
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+
+	#Dirichlet Values
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		print "      boundary conditions for stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print "      boundary conditions for stressbalance model: spc set as zero"
+
+	#No ice front -> do nothing
+
+	#Create zeros basalforcings and surfaceforcings
+	md.surfaceforcings.initialize(md)
+	md.basalforcings.initialize(md)
+
+	#Deal with other boundary conditions
+	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.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=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))
+		if hasattr(md.mesh,'vertexonsurface'):
+			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/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.m	(revision 18231)
@@ -0,0 +1,88 @@
+function md=SetIceShelfBC(md,varargin)
+%SETICESHELFBC - Create the boundary conditions for stressbalance and thermal models for a  Ice Shelf with Ice Front
+%
+%   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
+%   must be given in input)
+%   Dirichlet BC are used elsewhere for stressbalance
+%
+%   Usage:
+%      md=SetIceShelfBC(md,varargin)
+%
+%   Example:
+%      md=SetIceShelfBC(md);
+%      md=SetIceShelfBC(md,'Front.exp');
+%
+%   See also: SETICESHEETBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile), error(['SetIceShelfBC error message: ice front file ' icefrontfile ' not found']); end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	nodeonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+elseif nargin==1,
+	nodeonicefront=zeros(md.mesh.numberofvertices,1);
+else
+	help SetIceShelfBC
+	error('bad usage');
+end
+pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+
+%Ice front position: 
+md.mask.ice_levelset(find(nodeonicefront))=0;
+
+%First find segments that are not completely on the front
+if strcmp(elementtype(md.mesh),'Penta'),
+	numbernodesfront=4;
+elseif strcmp(elementtype(md.mesh),'Tria'),
+	numbernodesfront=2;
+else
+	error('mesh type not supported yet');
+end
+segmentsfront=md.mask.ice_levelset(md.mesh.segments(:,1:numbernodesfront))==0;
+segments=find(sum(segmentsfront,2)~=numbernodesfront);
+%Find all nodes for these segments and spc them
+pos=md.mesh.segments(segments,1:numbernodesfront);
+md.stressbalance.spcvx(pos(:))=0;
+md.stressbalance.spcvy(pos(:))=0;
+md.stressbalance.spcvz(pos(:))=0;
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for stressbalance model: spc set as zero');
+end
+
+%Initialize surface and basal forcings
+md.surfaceforcings = initialize(md.surfaceforcings,md);
+md.basalforcings   = initialize(md.basalforcings,md);
+
+%Deal with other boundary conditions
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	if isprop(md.mesh,'vertexonsurface'),
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetIceShelfBC.py	(revision 18231)
@@ -0,0 +1,101 @@
+import os
+import numpy
+from ContourToMesh import ContourToMesh
+import MatlabFuncs as m
+
+def SetIceShelfBC(md,icefrontfile=''):
+	"""
+	SETICESHELFBC - Create the boundary conditions for stressbalance and thermal models for a  Ice Shelf with Ice Front
+
+	   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+	   must be given in input)
+	   Dirichlet BC are used elsewhere for stressbalance
+
+	   Usage:
+	      md=SetIceShelfBC(md,varargin)
+
+	   Example:
+	      md=SetIceShelfBC(md);
+	      md=SetIceShelfBC(md,'Front.exp');
+
+	   See also: SETICESHEETBC, SETMARINEICESHEETBC
+	"""
+
+	#node on Dirichlet (boundary and ~icefront)
+	if icefrontfile:
+		if not os.path.exists(icefrontfile):
+			raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
+		[nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
+		nodeonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))
+	else:
+		nodeonicefront=numpy.zeros((md.mesh.numberofvertices),bool)
+
+#	pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+	pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]
+	md.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+
+	#Icefront position
+	pos=numpy.nonzero(nodeonicefront)[0]
+	md.mask.ice_levelset[pos]=0
+
+	#First find segments that are not completely on the front
+	if m.strcmp(md.mesh.elementtype(),'Penta'):
+		numbernodesfront=4;
+	elif m.strcmp(md.mesh.elementtype(),'Tria'):
+		numbernodesfront=2;
+	else:
+		raise	error('mesh type not supported yet')
+	if any(md.mask.ice_levelset<=0):
+		values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
+		segmentsfront=1-values
+		numpy.sum(segmentsfront,axis=1)!=numbernodesfront
+		segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
+		#Find all nodes for these segments and spc them
+		pos=md.mesh.segments[segments,0:-1]-1
+	else:
+		pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.stressbalance.spcvx[pos]=0
+	md.stressbalance.spcvy[pos]=0
+	md.stressbalance.spcvz[pos]=0
+																													   
+	#Dirichlet Values
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		#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 stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print "      boundary conditions for stressbalance model: spc set as zero"
+
+	#Create zeros basalforcings and surfaceforcings
+	md.surfaceforcings.initialize(md)
+	md.basalforcings.initialize(md)
+
+	#Deal with other boundary conditions
+	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.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=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))
+		if hasattr(md.mesh,'vertexonsurface'):
+			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"
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 18231)
@@ -0,0 +1,108 @@
+function md=SetMarineIceSheetBC(md,varargin)
+%SETICEMARINESHEETBC - Create the boundary conditions for stressbalance and thermal models for a  Marine Ice Sheet with Ice Front
+%
+%   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+%   can be given in input, or it will be deduced as onfloatingice & onboundary)
+%   Dirichlet BC are used elsewhere for stressbalance
+%
+%   Usage:
+%      md=SetMarineIceSheetBC(md,icefrontfile)
+%      md=SetMarineIceSheetBC(md)
+%
+%   Example:
+%      md=SetMarineIceSheetBC(md,'Front.exp')
+%      md=SetMarineIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	%User provided Front.exp, use it
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile)
+		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
+	end
+	[path,name,ext]=fileparts(icefrontfile);
+	if strcmp(ext,'.shp'),
+		contours=shpread(icefrontfile);
+	elseif strcmp(ext,'.exp'),
+		contours=expread(icefrontfile);
+	end
+	incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,contours,'node',2);
+	vertexonicefront=double(md.mesh.vertexonboundary & incontour);
+else
+	%Guess where the ice front is
+	pos=find(sum(md.mask.groundedice_levelset(md.mesh.elements)<0.,2) >0.);
+	vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+	vertexonfloatingice(md.mesh.elements(pos,:))=1.;
+	vertexonicefront=double(md.mesh.vertexonboundary & vertexonfloatingice);
+end
+pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+if isempty(pos),
+	warning('SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually')
+end
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+
+%Position of ice front
+md.mask.ice_levelset(find(vertexonicefront))=0;
+
+%First find segments that are not completely on the front
+if strcmp(elementtype(md.mesh),'Penta'),
+	numbernodesfront=4;
+elseif strcmp(elementtype(md.mesh),'Tria'),
+	numbernodesfront=2;
+else
+	error('mesh type not supported yet');
+end
+segmentsfront=md.mask.ice_levelset(md.mesh.segments(:,1:numbernodesfront))==0;
+segments=find(sum(segmentsfront,2)~=numbernodesfront);
+%Find all nodes for these segments and spc them
+pos=md.mesh.segments(segments,1:numbernodesfront);
+md.stressbalance.spcvx(pos(:))=0;
+md.stressbalance.spcvy(pos(:))=0;
+md.stressbalance.spcvz(pos(:))=0; % FIXME probably shouldn't spc vertical velocity here
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for stressbalance model: spc set as zero');
+end
+
+md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
+pos=find(md.mesh.vertexonboundary);
+md.hydrology.spcwatercolumn(pos,1)=1;
+
+%Initialize surface and basal forcings
+md.surfaceforcings = initialize(md.surfaceforcings,md);
+md.basalforcings   = initialize(md.basalforcings,md);
+
+%Deal with other boundary conditions
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	if isprop(md.mesh,'vertexonsurface'),
+		pos=find(md.mesh.vertexonsurface);
+		md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	end
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+		md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.))=50.*10.^-3; %50mW/m2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 18231)
@@ -0,0 +1,111 @@
+import os
+import numpy
+from ContourToMesh import ContourToMesh
+import MatlabFuncs as m
+
+def SetMarineIceSheetBC(md,icefrontfile=''):
+	"""
+	SETICEMARINESHEETBC - Create the boundary conditions for stressbalance and thermal models for a  Marine Ice Sheet with Ice Front
+
+	   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+	   can be given in input, or it will be deduced as onfloatingice & onboundary)
+	   Dirichlet BC are used elsewhere for stressbalance
+
+	   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)
+		[incontour,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
+		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))
+	else:
+		#Guess where the ice front is
+		vertexonfloatingice=numpy.zeros((md.mesh.numberofvertices,1))
+		pos=numpy.nonzero(numpy.sum(md.mask.groundedice_levelset[md.mesh.elements-1]<0.,axis=1) >0.)[0]
+		vertexonfloatingice[md.mesh.elements[pos].astype(int)-1]=1.
+		vertexonicefront=numpy.logical_and(numpy.reshape(md.mesh.vertexonboundary,(-1,1)),vertexonfloatingice>0.)
+
+#	pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+	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.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+
+	#Position of ice front
+	pos=numpy.nonzero(vertexonicefront)[0]
+	md.mask.ice_levelset[pos]=0
+
+	#First find segments that are not completely on the front
+	if m.strcmp(md.mesh.elementtype(),'Penta'):
+		numbernodesfront=4
+	elif m.strcmp(md.mesh.elementtype(),'Tria'):
+		numbernodesfront=2
+	else:
+			raise StandardError("Mesh type not supported")
+	if any(md.mask.ice_levelset<=0):
+		values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
+		segmentsfront=1-values
+		numpy.sum(segmentsfront,axis=1)!=numbernodesfront
+		segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
+		#Find all nodes for these segments and spc them
+		pos=md.mesh.segments[segments,0:-1]-1
+	else:
+		pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.stressbalance.spcvx[pos]=0
+	md.stressbalance.spcvy[pos]=0
+	md.stressbalance.spcvz[pos]=0
+
+	#Dirichlet Values
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		print "      boundary conditions for stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print "      boundary conditions for stressbalance model: spc set as zero"
+
+	md.hydrology.spcwatercolumn=numpy.zeros((md.mesh.numberofvertices,2))
+	pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.hydrology.spcwatercolumn[pos,0]=1
+
+	#Create zeros basalforcings and surfaceforcings
+	md.surfaceforcings.initialize(md)
+	md.basalforcings.initialize(md)
+
+	#Deal with other boundary conditions
+	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.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.damage.spcdamage=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))
+		if hasattr(md.mesh,'vertexonsurface'):
+			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.groundedice_levelset>0.)]=50.*10.**-3    #50mW/m2
+	else:
+		print "      no thermal boundary conditions created: no observed temperature found"
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.m	(revision 18231)
@@ -0,0 +1,58 @@
+%SMB Class definition
+%
+%   Usage:
+%      SMB=SMB();
+
+classdef SMB
+	properties (SetAccess=public) 
+		mass_balance = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- surfaceforcings(SMB) -->');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="mass_balance" type="',class(obj.mass_balance),'" default="',obj.mass_balance,'">','     <section name="surfaceforcings(SMB)" />','     <help> surface mass balance [m/yr ice eq] </help>','</parameter>');
+           
+        end % }}}
+		function obj = SMB(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.mass_balance=project3d(md,'vector',self.mass_balance,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.mass_balance)
+				self.mass_balance=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.mass_balance specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.mass_balance','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters:'));
+			fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMB.py	(revision 18231)
@@ -0,0 +1,53 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+from project3d import project3d
+
+class SMB(object):
+	"""
+	SMB Class definition
+
+	   Usage:
+	      SMB=SMB();
+	"""
+
+	def __init__(self): # {{{
+		self.mass_balance = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters:"
+		string="%s\n%s"%(string,fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.mass_balance=project3d(md,'vector',self.mass_balance,'type','node');
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.mass_balance)):
+			self.mass_balance=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.mass_balance specified: values set as zero"
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.mass_balance','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.mass_balance','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.m	(revision 18231)
@@ -0,0 +1,80 @@
+%SMBcomponents Class definition
+%
+%   Usage:
+%      SMBcomponents=SMBcomponents();
+
+classdef SMBcomponents
+	properties (SetAccess=public) 
+		accumulation = NaN;
+		runoff = NaN;
+		evaporation = NaN;
+	end
+	methods
+		function obj = SMBcomponents(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.accumulation=project3d(md,'vector',self.accumulation,'type','node');
+			self.runoff=project3d(md,'vector',self.runoff,'type','node');
+			self.evaporation=project3d(md,'vector',self.evaporation,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.accumulation)
+				self.accumulation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.accumulation specified: values set as zero');
+			end
+			if isnan(self.evaporation)
+				self.evaporation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.evaporation specified: values set as zero');
+			end
+			if isnan(self.runoff)
+				self.runoff=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.runoff specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.runoff','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters (SMB=accumulation-runoff-evaporation) :'));
+			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(obj,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]');
+			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBcomponents.py	(revision 18231)
@@ -0,0 +1,80 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from project3d import *
+from WriteData import *
+
+class SMBcomponents(object):
+	"""
+	SMBcomponents Class definition
+
+	   Usage:
+	      SMBcomponents=SMBcomponents();
+	"""
+
+	def __init__(self): # {{{
+		self.accumulation = float('NaN')
+		self.runoff = float('NaN')
+		self.evaporation = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters (SMB=accumulation-runoff-evaporation) :"
+		string="%s\n%s"%(string,fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'evaporation','mount of ice lost to evaporative processes [m/yr ice eq]'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.mass_balance=project3d(md,'vector',self.accumulation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.runoff,'type','node');
+		self.mass_balance=project3d(md,'vector',self.evaporation,'type','node');
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.accumulation)):
+			self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.accumulation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.runoff)):
+			self.runoff=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.runoff specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.evaporation)):
+			self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.evaporation specified: values set as zero"
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.runoff','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.m	(revision 18231)
@@ -0,0 +1,68 @@
+%SMBgradients Class definition
+%
+%   Usage:
+%      SMBgradients=SMBgradients();
+
+classdef SMBgradients
+	properties (SetAccess=public) 
+		href   = NaN;
+		smbref = NaN;
+		b_pos  = NaN;
+		b_neg  = NaN;
+	end
+	methods
+		function obj = SMBgradients(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			%Nothing for now
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			%Nothing done for now
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Nothing for now
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.href','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.b_pos','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.b_neg','forcing',1,'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters:'));
+
+			disp(sprintf('\n   SMB gradients parameters:'));
+			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,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated');
+			fielddisplay(obj,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBgradientsEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBgradients.py	(revision 18231)
@@ -0,0 +1,62 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+from project3d import project3d
+
+class SMBgradients(object):
+	"""
+	SMBgradients Class definition
+
+	   Usage:
+	      SMBgradients=SMBgradients();
+	"""
+
+	def __init__(self): # {{{
+		self.href    = float('NaN')
+		self.smbref  = float('NaN')
+		self.b_pos   = float('NaN')
+		self.b_neg   = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters:"
+
+		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,'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,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated'))
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		#Nothing for now
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		#Nothing for now
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.href','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.b_pos','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.b_neg','forcing',1,'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBgradientsEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBhenning.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBhenning.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBhenning.m	(revision 18231)
@@ -0,0 +1,52 @@
+%SMBhenning Class definition
+%
+%   Usage:
+%      SMBhenning=SMBhenning();
+
+classdef SMBhenning
+	properties (SetAccess=public) 
+		smbref = NaN;
+	end
+	methods
+		function obj = SMBhenning(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.smbref=project3d(md,'vector',self.smbref,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.smbref)
+				self.smbref=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.smbref specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.smbref','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters:'));
+			fielddisplay(obj,'smbref','reference smb from which deviation is calculated [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBhenningEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.m	(revision 18231)
@@ -0,0 +1,94 @@
+%SMBmeltcomponents Class definition
+%
+%   Usage:
+%      SMBmeltcomponents=SMBmeltcomponents();
+
+classdef SMBmeltcomponents
+	properties (SetAccess=public) 
+		accumulation = NaN;
+		evaporation = NaN;
+		melt = NaN;
+		refreeze = NaN;
+	end
+	methods
+		function obj = SMBmeltcomponents(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.accumulation=project3d(md,'vector',self.accumulation,'type','node');
+			self.evaporation=project3d(md,'vector',self.evaporation,'type','node');
+			self.melt=project3d(md,'vector',self.melt,'type','node');
+			self.refreeze=project3d(md,'vector',self.refreeze,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.accumulation)
+				self.accumulation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.accumulation specified: values set as zero');
+			end
+			if isnan(self.evaporation)
+				self.evaporation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.evaporation specified: values set as zero');
+			end
+			if isnan(self.refreeze)
+				self.refreeze=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.refreeze specified: values set as zero');
+			end
+			if isnan(self.melt)
+				self.melt=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.melt specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.refreeze','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.melt','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters with melt (SMB=accumulation-evaporation-melt+refreeze) :'));
+			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+			fielddisplay(obj,'melt','amount of ice melt in ice column [m/yr ice eq]');
+			fielddisplay(obj,'refreeze','amount of ice melt refrozen in ice column [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBmeltcomponents.py	(revision 18231)
@@ -0,0 +1,93 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from project3d import *
+from WriteData import *
+
+class SMBmeltcomponents(object):
+	"""
+	SMBmeltcomponents Class definition
+
+	   Usage:
+	      SMBmeltcomponents=SMBmeltcomponents();
+	"""
+
+	def __init__(self): # {{{
+		self.accumulation = float('NaN')
+		self.runoff = float('NaN')
+		self.evaporation = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters with melt (SMB=accumulation-evaporation-melt+refreeze) :"
+		string="%s\n%s"%(string,fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'evaporation','mount of ice lost to evaporative processes [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'melt','amount of ice melt in the ice column [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'refreeze','amount of ice melt refrozen in the ice column [m/yr ice eq]'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.mass_balance=project3d(md,'vector',self.accumulation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.evaporation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.melt,'type','node');
+		self.mass_balance=project3d(md,'vector',self.refreeze,'type','node');
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.accumulation)):
+			self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.accumulation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.evaporation)):
+			self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.evaporation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.melt)):
+			self.melt=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.melt specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.refreeze)):
+			self.refreeze=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.refreeze specified: values set as zero"
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.melt','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.refreeze','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.m	(revision 18231)
@@ -0,0 +1,106 @@
+%SMBpdd Class definition
+%
+%   Usage:
+%      SMBpdd=SMBpdd();
+
+classdef SMBpdd
+	properties (SetAccess=public) 
+		precipitation             = NaN;
+		monthlytemperatures       = NaN;
+		desfac                    = 0.5;
+		s0p                       = 0;
+		isdelta18o                = 0;
+		delta18o                  = NaN;
+		delta18o_surface          = NaN;
+		temperatures_presentday   = NaN;
+		temperatures_lgm          = NaN;
+		precipitations_presentday = NaN;
+	end
+	methods
+		function obj = SMBpdd(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.precipitation=project3d(md,'vector',self.precipitation,'type','node');
+			self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node');
+			if(self.isdelta18o),self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node');end
+			if(self.isdelta18o),self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node');end
+			if(self.isdelta18o),self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node');end
+
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.precipitation),
+				self.precipitation=zeros(md.mesh.numberofvertices,1);
+				disp('      no SMBpdd.precipitation specified: values set as zero');
+			end
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		  obj.isdelta18o = 0;
+		  obj.desfac     = 0.5;
+		  obj.s0p        = 0;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.desfac','<=',1,'numel',1);
+				md = checkfield(md,'fieldname','surfaceforcings.s0p','>=',0,'numel',1);
+				if(obj.isdelta18o==0)
+					md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitation','forcing',1,'NaN',1);
+				else
+					md = checkfield(md,'fieldname','surfaceforcings.delta18o','NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.delta18o_surface','NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters:'));
+
+			disp(sprintf('\n   PDD and deltaO18 parameters:'));
+			fielddisplay(obj,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)');
+			fielddisplay(obj,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]');
+			fielddisplay(obj,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]');
+			fielddisplay(obj,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated');
+			fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]');
+			fielddisplay(obj,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'delta18o','delta18o, required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBpddEnum(),'format','Integer');
+
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','desfac','format','Double');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','s0p','format','Double');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','isdelta18o','format','Boolean');
+			if obj.isdelta18o
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','delta18o_surface','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','delta18o','format','DoubleMat','mattype',1);
+			else
+				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			end
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/SMBpdd.py	(revision 18231)
@@ -0,0 +1,108 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+from project3d import project3d
+
+class SMBpdd(object):
+	"""
+	SMBpdd Class definition
+
+	   Usage:
+	      SMBpdd=SMBpdd();
+	"""
+
+	def __init__(self): # {{{
+		self.precipitation             = float('NaN')
+		self.monthlytemperatures       = float('NaN')
+		self.desfac                    = 0.
+		self.s0p                       = 0.
+		self.isdelta18o                = 0
+		self.delta18o                  = float('NaN')
+		self.delta18o_surface          = float('NaN')
+		self.temperatures_presentday   = float('NaN')
+		self.temperatures_lgm          = float('NaN')
+		self.precipitations_presentday = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated'))
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.precipitation=project3d(md,'vector',self.precipitation,'type','node');
+		self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node');
+		if self.isdelta18o: self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node')
+		if self.isdelta18o: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node')
+		if self.isdelta18o: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.precipitation)):
+			self.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMBpdd.precipitation specified: values set as zero"
+
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		  
+		#pdd method not used in default mode
+		self.isdelta18o = 0
+		self.desfac     = 0.5
+		self.s0p        = 0.
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.desfac','<=',1,'numel',[1]);
+			md = checkfield(md,'fieldname','surfaceforcings.s0p','>=',0,'numel',[1]);
+			if not self.isdelta18o:
+				md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','forcing',1,'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitation','forcing',1,'NaN',1)
+			else:
+				md = checkfield(md,'fieldname','surfaceforcings.delta18o','NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.delta18o_surface','NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBpddEnum(),'format','Integer');
+
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','isdelta18o','format','Boolean')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','desfac','format','Double');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0p','format','Double');
+		if self.isdelta18o:
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o_surface','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o','format','DoubleMat','mattype',1)
+		else:
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.m	(revision 18231)
@@ -0,0 +1,260 @@
+%AUTODIFF class definition
+%
+%   Usage:
+%      autodiff=autodiff();
+
+classdef autodiff
+	properties (SetAccess=public)  
+		% {{{ 
+		isautodiff   = false;
+		dependents   = {};
+		independents = {};
+		driver       = 'fos_forward';
+		obufsize     = NaN;
+		lbufsize     = NaN;
+		cbufsize     = NaN;
+		tbufsize     = NaN;
+		gcTriggerRatio = NaN;
+		gcTriggerMaxSize = NaN;
+		end
+		%}}}
+	methods
+     	function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- autodiff -->\n');            
+                    
+            % automatic differentiation parameters 
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="automatic differentiation parameters">','<section name="autodiff" />');                    
+                fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="isautodiff" type="',class(obj.isautodiff),'" optional="false">','     <section name="autodiff" />','         <option value="',convert2str(obj.isautodiff),'" type="string" default="true"></option>','     <help> indicates if the automatic differentiation is activated </help>','  </parameter>');
+             
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dependents" type="',class(obj.dependents),'" default="',convert2str(obj.dependents),'">','     <section name="autodiff" />','     <help> list of dependent variables </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="independents" type="',class(obj.independents),'" default="',convert2str(obj.independents),'">','     <section name="autodiff" />','     <help> list of independent variables </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="driver" type="',class(obj.driver),'" default="',convert2str(obj.driver),'">','     <section name="autodiff" />','     <help> ADOLC driver (''fos_forward'' or ''fov_forward'') </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="obufsize" type="',class(obj.obufsize),'" default="',convert2str(obj.obufsize),'">','     <section name="autodiff" />','     <help> Number of operations per buffer (==OBUFSIZE in usrparms.h)  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lbufsize" type="',class(obj.lbufsize),'" default="',convert2str(obj.lbufsize),'">','     <section name="autodiff" />','     <help> Number of locations per buffer (==LBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cbufsize" type="',class(obj.cbufsize),'" default="',convert2str(obj.cbufsize),'">','     <section name="autodiff" />','     <help> Number of values per buffer (==CBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tbufsize" type="',class(obj.tbufsize),'" default="',convert2str(obj.tbufsize),'">','     <section name="autodiff" />','     <help> Number of taylors per buffer (&amp;lt;=TBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(obj.gcTriggerRatio),'" default="',convert2str(obj.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(obj.gcTriggerRatio),'" default="',convert2str(obj.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize </help>','  </parameter>');
+            
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = autodiff(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+		obj.obufsize     = 524288;
+		obj.lbufsize     = 524288;
+		obj.cbufsize     = 524288;
+		obj.tbufsize     = 524288;
+		obj.gcTriggerRatio=2.0;
+		obj.gcTriggerMaxSize=65536;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return 
+			if ~obj.isautodiff, return; end
+
+			%Driver value:
+			md = checkfield(md,'fieldname','autodiff.driver','values',{'fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'});
+			
+			%buffer values: 
+			md = checkfield(md,'fieldname','autodiff.obufsize','>=',16);
+			md = checkfield(md,'fieldname','autodiff.lbufsize','>=',16);
+			md = checkfield(md,'fieldname','autodiff.cbufsize','>=',16);
+			md = checkfield(md,'fieldname','autodiff.tbufsize','>=',16);
+			md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',0);
+			md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536);
+
+			%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:'));
+			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
+			fielddisplay(obj,'dependents','list of dependent variables');
+			fielddisplay(obj,'independents','list of independent variables');
+			fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
+			fielddisplay(obj,'obufsize','Number of operations per buffer (==OBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'lbufsize','Number of locations per buffer (==LBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'cbufsize','Number of values per buffer (==CBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'tbufsize','Number of taylors per buffer (<=TBUFSIZE in usrparms.h)');
+			fielddisplay(obj,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
+			fielddisplay(obj,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','driver','format','String');
+
+			%early return
+			if ~obj.isautodiff,
+				WriteData(fid,'data',false,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
+				WriteData(fid,'data',false,'enum',AutodiffKeepEnum(),'format','Boolean');
+				return;
+			end
+
+			%buffer sizes {{{
+			WriteData(fid,'object',obj,'fieldname','obufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','lbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','cbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','tbufsize','format','Double');
+			WriteData(fid,'object',obj,'fieldname','gcTriggerRatio','format','Double');
+			WriteData(fid,'object',obj,'fieldname','gcTriggerMaxSize','format','Double');
+			%}}}
+			%process dependent variables {{{
+			num_dependent_objects=numel(obj.dependents);
+			WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer');
+
+			if(num_dependent_objects),
+				names={};
+				types=zeros(num_dependent_objects,1);
+				indices=zeros(num_dependent_objects,1);
+
+				for i=1:num_dependent_objects,
+					dep=obj.dependents{i};
+
+					names{i}=dep.name;
+					types(i)=dep.typetoscalar();
+					indices(i)=dep.index;
+				end
+				WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray');
+				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 % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/autodiff.py	(revision 18231)
@@ -0,0 +1,215 @@
+import numpy
+from dependent import dependent
+from independent import independent
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class autodiff(object):
+	"""
+	AUTODIFF class definition
+
+	   Usage:
+	      autodiff=autodiff();
+	"""
+	def __init__(self,*args):    # {{{
+		self.isautodiff   = False
+		self.dependents   = []
+		self.independents = []
+		self.driver       = 'fos_forward'
+		self.obufsize     = float('NaN')
+		self.lbufsize     = float('NaN')
+		self.cbufsize     = float('NaN')
+		self.tbufsize     = float('NaN')
+		self.gcTriggerMaxSize     = float('NaN')
+		self.gcTriggerRatio     = float('NaN')
+		if not len(args):
+			self.setdefaultparameters()
+		else:
+			raise RuntimeError("constructor not supported")
+	# }}}
+	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')")
+		s+="%s\n" % fielddisplay(self,'obufsize',"Number of operations per buffer (==OBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'lbufsize',"Number of locations per buffer (==LBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'cbufsize',"Number of values per buffer (==CBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'tbufsize',"Number of taylors per buffer (<=TBUFSIZE in usrparms.h)")
+		s+="%s\n" % fielddisplay(self,'gcTriggerRatio',"free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio")
+		s+="%s\n" % fielddisplay(self,'gcTriggerMaxSize',"free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize)")
+
+		return s
+	# }}}
+	def setdefaultparameters(self):    # {{{
+		
+		self.obufsize     = 524288
+		self.lbufsize     = 524288
+		self.cbufsize     = 524288
+		self.tbufsize     = 524288
+		self.gcTriggerRatio=2.0
+		self.gcTriggerMaxSize=65536
+		return self
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return 
+		if not self.isautodiff:
+			return md 
+		
+		md = checkfield(md,'fieldname','autodiff.obufsize','>=',524288)
+		md = checkfield(md,'fieldname','autodiff.lbufsize','>=',524288)
+		md = checkfield(md,'fieldname','autodiff.cbufsize','>=',524288)
+		md = checkfield(md,'fieldname','autodiff.tbufsize','>=',524288)
+		md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',2.0)
+		md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',2000000)
+
+		#Driver value:
+		md = checkfield(md,'fieldname','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
+	# }}}
+	def marshall(self,md,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
+			
+		#buffer sizes {{{
+		WriteData(fid,'object',self,'fieldname','obufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','lbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','cbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','tbufsize','format','Double');
+		WriteData(fid,'object',self,'fieldname','gcTriggerRatio','format','Double');
+		WriteData(fid,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
+		#}}}
+		#process dependent variables {{{
+		num_dependent_objects=len(self.dependents)
+		WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer')
+
+		if num_dependent_objects:
+			names=[]
+			types=numpy.zeros(num_dependent_objects)
+			indices=numpy.zeros(num_dependent_objects)
+
+			for i,dep in enumerate(self.dependents):
+				names[i]=dep.name
+				types[i]=dep.typetoscalar()
+				indices[i]=dep.index
+
+			WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray')
+			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/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.m	(revision 18231)
@@ -0,0 +1,66 @@
+%BALANCETHICKNESS class definition
+%
+%   Usage:
+%      balancethickness=balancethickness();
+
+classdef balancethickness
+	properties (SetAccess=public) 
+		spcthickness      = NaN;
+		thickening_rate   = NaN;
+		stabilization     = 0;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- balancethickness -->');
+            
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcthickness" type="',   	class(obj.spcthickness),'" default="',        convert2str(obj.spcthickness),'">',	'     <section name="balancethickness" />','     <help> thickness constraints (NaN means no constraint) [m] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="thickening_rate" type="', 	class(obj.thickening_rate),'" default="',            convert2str(obj.thickening_rate),'">',     '     <section name="balancethickness" />','     <help> ice thickening rate used in the mass conservation (dh/dt) [m/yr] </help>','</parameter>');
+            
+            % balancethickness drop-down (1,2, or 3)
+            fprintf(fid,'%s\n%s\n%s\n',        '<parameter key ="stabilization" type="alternative" optional="false">','     <section name="balancethickness" />','     <help> 0: None, 1: SU, 2: SSAs artificial diffusivity, 3:DG </help>');
+            fprintf(fid,'%s\n','       <option value="1" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n','       <option value="2" type="string" default="false"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="3" type="string" default="false"> </option>','</parameter>');
+
+        end % }}}
+		function obj = balancethickness(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization used
+			obj.stabilization=1;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			%Early return
+			if solution~=BalancethicknessSolutionEnum(), return; end
+
+			md = checkfield(md,'fieldname','balancethickness.spcthickness');
+			md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices 1],'NaN',1);
+			md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1 1],'values',[0 1 2 3]);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   balance thickness solution parameters:'));
+
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt) [m/yr]');
+			fielddisplay(obj,'stabilization','0: None, 1: SU, 2: SSA''s artificial diffusivity, 3:DG');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness.py	(revision 18231)
@@ -0,0 +1,57 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class balancethickness(object):
+	"""
+	BALANCETHICKNESS class definition
+
+	   Usage:
+	      balancethickness=balancethickness();
+	"""
+
+	def __init__(self): # {{{
+		self.spcthickness      = float('NaN')
+		self.thickening_rate   = float('NaN')
+		self.stabilization     = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   balance thickness solution parameters:' 
+		
+		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization',"0: None, 1: SU, 2: SSA's artificial diffusivity, 3:DG"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Type of stabilization used
+		self.stabilization=1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		#Early return
+		if not solution==BalancethicknessSolutionEnum():
+			return md
+
+		md = checkfield(md,'fieldname','balancethickness.spcthickness')
+		md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1)
+		md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1],'values',[0,1,2,3])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness2.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness2.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/balancethickness2.m	(revision 18231)
@@ -0,0 +1,62 @@
+%BALANCETHICKNESS2 class definition
+%
+%   Usage:
+%      balancethickness2=balancethickness2();
+
+classdef balancethickness2
+	properties (SetAccess=public) 
+		spcpotential         = NaN;
+		apparent_massbalance = NaN;
+		nux                  = NaN;
+		nuy                  = NaN;
+		vx_obs               = NaN;
+		vy_obs               = NaN;
+		thickness_obs        = NaN;
+	end
+	methods
+		function obj = balancethickness2(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			%Early return
+			if solution~=Balancethickness2SolutionEnum(), return; end
+
+			md = checkfield(md,'fieldname','balancethickness.spcpotential','size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','balancethickness.apparent_massbalance','size',[md.mesh.numberofvertices 1],'NaN',1);
+			md = checkfield(md,'fieldname','balancethickness.nux','size',[md.mesh.numberofvertices 1],'NaN',1,'>',0,'<=',1);
+			md = checkfield(md,'fieldname','balancethickness.nuy','size',[md.mesh.numberofvertices 1],'NaN',1,'>',0,'<=',1);
+			md = checkfield(md,'fieldname','balancethickness.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			md = checkfield(md,'fieldname','balancethickness.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			md = checkfield(md,'fieldname','balancethickness.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'>=',0);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   balance thickness solution parameters:'));
+
+			fielddisplay(obj,'spcpotential','potential constraints (NaN means no constraint)');
+			fielddisplay(obj,'apparent_massbalance','Apparent mass balance [m/yr]');
+			fielddisplay(obj,'nux','vx_bar = nux vx_s (in ]0 1])');
+			fielddisplay(obj,'nuy','vy_bar = nuy vy_s (in ]0 1])');
+			fielddisplay(obj,'vx_obs','observed vx');
+			fielddisplay(obj,'vy_obs','observed vy');
+			fielddisplay(obj,'thickness_obs','observed H');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','spcpotential','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','apparent_massbalance','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','nux','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','nuy','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','vx_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','vy_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','thickness_obs','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.m	(revision 18231)
@@ -0,0 +1,51 @@
+%BAMGGEOM class definition
+%
+%   Usage:
+%      bamggeom(varargin)
+
+classdef bamggeom
+	properties (SetAccess=public) 
+		% {{{
+		Vertices=[];
+		Edges=[];
+		TangentAtEdges=[];
+		Corners=[];
+		RequiredVertices=[];
+		RequiredEdges=[];
+		CrackedEdges=[];
+		SubDomains=[];
+		% }}}
+	end
+	methods
+		function bg = bamggeom(varargin)% {{{
+		%BAMGGEOM - constructor for bamggeom object
+		%
+		%   Usage:
+		%      bamggeom = bamggeom(varargin)
+
+		switch nargin
+			case 0
+				% if no input arguments, create a default object
+
+			case 1
+
+				bg=bamggeom;
+				object=varargin{1};
+				fields=fieldnames(object);
+				for i=1:length(fields)
+					field=fields{i};
+					if ismember(field,properties('bamggeom')),
+						bg.(field)=object.(field);
+					end
+				end
+
+			otherwise
+				error('bamggeom constructor error message: unknown type of constructor call');
+			end
+		end%}}}
+		function display(bg)% {{{
+			disp(sprintf('\n%s = \n',inputname(1)));
+			disp(struct(bg))
+		end%}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamggeom.py	(revision 18231)
@@ -0,0 +1,45 @@
+import numpy
+
+class bamggeom(object):
+	"""
+	BAMGGEOM class definition
+
+	   Usage:
+	      bamggeom(varargin)
+	"""
+
+	def __init__(self,*args):    # {{{
+		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):
+			# if no input arguments, create a default object
+			pass
+
+		elif len(args) == 1:
+			object=args[0]
+			for field in object.iterkeys():
+				if field in vars(self):
+					setattr(self,field,object[field])
+
+		else:
+			raise TypeError("bamggeom constructor error message: unknown type of constructor call")
+	# }}}
+	def __repr__(self):    # {{{
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    Vertices: %s\n" % str(self.Vertices)
+		s+="    Edges: %s\n" % str(self.Edges)
+		s+="    TangentAtEdges: %s\n" % str(self.TangentAtEdges)
+		s+="    Corners: %s\n" % str(self.Corners)
+		s+="    RequiredVertices: %s\n" % str(self.RequiredVertices)
+		s+="    RequiredEdges: %s\n" % str(self.RequiredEdges)
+		s+="    CrackedEdges: %s\n" % str(self.CrackedEdges)
+		s+="    SubDomains: %s\n" % str(self.SubDomains)
+		return s
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.m	(revision 18231)
@@ -0,0 +1,55 @@
+%BAMGMESH class definition
+%
+%   Usage:
+%      bamgmesh(varargin)
+
+classdef bamgmesh
+	properties (SetAccess=public) 
+		% {{{
+		Vertices=[];
+		Edges=[];
+		Triangles=[];
+		Quadrilaterals=[];
+		IssmEdges=[];
+		IssmSegments=[];
+		VerticesOnGeomVertex=[];
+		VerticesOnGeomEdge=[];
+		EdgesOnGeomEdge=[];
+		SubDomains=[];
+		SubDomainsFromGeom=[];
+		ElementConnectivity=[];
+		NodalConnectivity=[];
+		NodalElementConnectivity=[];
+		CrackedVertices=[];
+		CrackedEdges=[];
+		% }}}
+	end
+	methods
+		function bg = bamgmesh(varargin)% {{{
+
+		switch nargin
+			case 0
+				% if no input arguments, create a default object
+
+			case 1
+
+				bg=bamgmesh;
+				object=varargin{1};
+				fields=fieldnames(object);
+				for i=1:length(fields)
+					field=fields{i};
+					if ismember(field,properties('bamgmesh')),
+						bg.(field)=object.(field);
+					end
+				end
+
+			otherwise
+				error('bamgmesh constructor error message: unknown type of constructor call');
+			end
+		end%}}}
+		function display(bm)% {{{
+			disp(sprintf('\n%s = \n',inputname(1)));
+			disp(struct(bm))
+		end%}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/bamgmesh.py	(revision 18231)
@@ -0,0 +1,61 @@
+import numpy
+
+class bamgmesh(object):
+	"""
+	BAMGMESH class definition
+
+	   Usage:
+	      bamgmesh(varargin)
+	"""
+
+	def __init__(self,*args):    # {{{
+		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):
+			# if no input arguments, create a default object
+			pass
+
+		elif len(args) == 1:
+			object=args[0]
+			for field in object.iterkeys():
+				if field in vars(self):
+					setattr(self,field,object[field])
+
+		else:
+			raise TypeError("bamgmesh constructor error message: unknown type of constructor call")
+	# }}}
+	def __repr__(self):    # {{{
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    Vertices: %s\n" % str(self.Vertices)
+		s+="    Edges: %s\n" % str(self.Edges)
+		s+="    Triangles: %s\n" % str(self.Triangles)
+		s+="    Quadrilaterals: %s\n" % str(self.Quadrilaterals)
+		s+="    IssmEdges: %s\n" % str(self.IssmEdges)
+		s+="    IssmSegments: %s\n" % str(self.IssmSegments)
+		s+="    VerticesOnGeomVertex: %s\n" % str(self.VerticesOnGeomVertex)
+		s+="    VerticesOnGeomEdge: %s\n" % str(self.VerticesOnGeomEdge)
+		s+="    EdgesOnGeomEdge: %s\n" % str(self.EdgesOnGeomEdge)
+		s+="    SubDomains: %s\n" % str(self.SubDomains)
+		s+="    SubDomainsFromGeom: %s\n" % str(self.SubDomainsFromGeom)
+		s+="    ElementConnectivity: %s\n" % str(self.ElementConnectivity)
+		s+="    NodalConnectivity: %s\n" % str(self.NodalConnectivity)
+		s+="    NodalElementConnectivity: %s\n" % str(self.NodalElementConnectivity)
+		s+="    CrackedVertices: %s\n" % str(self.CrackedVertices)
+		s+="    CrackedEdges: %s\n" % str(self.CrackedEdges)
+		return s
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.m	(revision 18231)
@@ -0,0 +1,78 @@
+%BASAL FORCINGS class definition
+%
+%   Usage:
+%      basalforcings=basalforcings();
+
+classdef basalforcings
+	properties (SetAccess=public) 
+		groundedice_melting_rate  = NaN;
+		floatingice_melting_rate  = NaN;
+		geothermalflux            = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- basalforcings -->');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
+             
+        end % }}}
+		function obj = basalforcings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.groundedice_melting_rate),
+				self.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.groundedice_melting_rate specified: values set as zero');
+			end
+
+			if isnan(self.floatingice_melting_rate),
+				self.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.floatingice_melting_rate specified: values set as zero');
+			end
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   basal forcings parameters:'));
+
+			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'floatingice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/basalforcings.py	(revision 18231)
@@ -0,0 +1,72 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import numpy
+
+class basalforcings(object):
+	"""
+	BASAL FORCINGS class definition
+
+	   Usage:
+	      basalforcings=basalforcings();
+	"""
+
+	def __init__(self): # {{{
+		self.groundedice_melting_rate  = float('NaN')
+		self.floatingice_melting_rate  = float('NaN')
+		self.geothermalflux            = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   basal forcings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"floatingice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
+		return string
+		#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
+			self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.floatingice_melting_rate)):
+			self.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.floatingice_melting_rate specified: values set as zero"
+
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+
+		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/README	(revision 18231)
@@ -0,0 +1,12 @@
+This directory holds classes corresponding to every cluster 
+that can be used. 
+
+Why classes? 
+Because handling the specificity of every cluster is hard in a general 
+code. Having classes with generic methods, such as: BuildQueueScript, 
+LaunchQueueJob,  and internal data corresponding to every cluster's specificity 
+is much more manageable and powerful.
+
+How to add your cluster? 
+use an existing cluster script, such as pfe.m, and rename it to your cluster name.
+update the methods.
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/acenet.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/acenet.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/acenet.m	(revision 18231)
@@ -0,0 +1,108 @@
+%ACENET class definition
+%
+%   Usage:
+%      cluster=acenet();
+%      cluster=acenet('np',3);
+%      cluster=acenet('np',3,'login','username');
+
+classdef acenet
+    properties (SetAccess=public) 
+		 % {{{
+		 name='glacdyn.ace-net.ca'
+		 %name='placentia.ace-net.ca'
+		 %name='brasdor.ace-net.ca'
+		 login='klemorza';
+		 np=10;
+		 port=0;
+		 queue='shortq';
+		 time=10;
+		 % codepath='/usr/local/issm-r11321/bin'; % this one is for issm on acenet global
+		 codepath='/home/klemorza/issm/trunk-jpl/bin'; % this one is for issm on my acenet directory
+		 executionpath='/home/klemorza/issm/trunk-jpl/execution';
+		 %}}}
+	 end
+	 methods
+		 function cluster=acenet(varargin) % {{{
+			 %use provided options to change fields
+			 options=pairoptions(varargin{:});
+
+			 %initialize cluster using user settings if provided
+			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			 %OK get other fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'debug','shortq','longq'};
+			 queue_requirements_time=[60*1 60*3 60*17];
+			 queue_requirements_np=[32 128 256];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+			 fprintf(fid,'#$ -cwd\n');
+          fprintf(fid,'#$ -N issm\n');
+          fprintf(fid,'#$ -l h_rt=96:0:0\n');
+          fprintf(fid,'#$ -pe ompi* %i\n',cluster.np);
+          fprintf(fid,'#$ -j y\n');
+          fprintf(fid,'module purge\n');
+          fprintf(fid,'module load gcc openmpi/gcc\n');
+          fprintf(fid,'module load issm\n');
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+          fprintf(fid,'\n');
+          fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+                   cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/castor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/castor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/castor.m	(revision 18231)
@@ -0,0 +1,100 @@
+%CASTOR class definition
+%
+%   Usage:
+%      cluster=castor();
+%      cluster=castor('np',3);
+%      cluster=castor('np',3,'login','username');
+
+classdef castor
+    properties (SetAccess=public) 
+		 % {{{
+		 name='castor'
+		 login='username';
+		 np   =128;
+		 port=0;
+		 queue='shortc';
+		 time=180;
+		 codepath='/workp/edw/issm-2.0/bin'
+		 executionpath='/workp/edw/Testing/Execution'
+		 %}}}
+	 end
+	 methods
+		 function cluster=castor(varargin) % {{{
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'shortc','longc'};
+			 queue_requirements_time=[180 720];
+			 queue_requirements_np=[128 128];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/sh\n');
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l ncpus=%i\n',cluster.np);
+			 if ~isempty(queue),
+				 fprintf(fid,'#PBS -q %s\n',cluster.queue);
+			 end
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
+			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cloud.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cloud.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cloud.m	(revision 18231)
@@ -0,0 +1,100 @@
+%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,'source %s%s\n',cluster.codepath,'/../etc/environment.sh');
+				fprintf(fid,'cd %s\n',[cluster.executionpath '/' dirname]);
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog > /dev/stdout | tee %s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+			else
+				fprintf(fid,'source %s%s\n',cluster.codepath,'/../etc/environment.sh');
+				fprintf(fid,'cd %s\n',[cluster.executionpath '/' dirname]);
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog > /dev/stdout | tee %s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+				%fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+			end
+		end
+		%}}}
+		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
+			system(compressstring);
+
+			if isempty(cluster.login),
+				error('cloud BuildQueueScript: login should be supplied!');
+			end
+			disp('uploading input file and queueing script');
+			issmstscpout(cluster.name,cluster.executionpath,cluster.login,{[dirname '.tar.gz']});
+
+			if cluster.interactive, 
+				disp('sending files to remote cluster. once done, please log into cluster and launch job');
+				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz '];
+			else
+				disp('launching solution sequence on remote cluster');
+				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub  ' modelname '.queue '];
+			end
+			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/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cosmos.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cosmos.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/cosmos.m	(revision 18231)
@@ -0,0 +1,100 @@
+%COSMOS class definition
+%
+%   Usage:
+%      cluster=cosmos();
+%      cluster=cosmos('np',3);
+%      cluster=cosmos('np',3,'login','username');
+
+classdef cosmos
+    properties (SetAccess=public) 
+		 % {{{
+		 name='cosmos'
+		 login='username';
+		 np=128;
+		 port=0;
+		 queue='shortq';
+		 time=3*60;
+		 codepath='/work00/edw/issm-2.0/bin';
+		 executionpath='/work00/edw/Execution';
+		 %}}}
+	 end
+	 methods
+		 function cluster=cosmos(varargin) % {{{
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'debug','shortq','longq'};
+			 queue_requirements_time=[60*1 60*3 60*17];
+			 queue_requirements_np=[32 128 256];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+			 fprintf(fid,'#PBS -l select=%i:ncpus=1\n',cluster.np);
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l walltime=%i\n',time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -q %s\n',queue);
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
+			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'ulimit -s unlimited\n');
+			 fprintf(fid,'ulimit -c 0\n');
+			 fprintf(fid,'/opt/mpich/gm/intel10.1/bin/mpiexec -np %i %s/issm.exe %s %s %s',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/discover.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/discover.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/discover.m	(revision 18231)
@@ -0,0 +1,193 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=discover();
+%      cluster=discover('np',3);
+%      cluster=discover('np',3,'login','username');
+
+classdef discover 
+    properties (SetAccess=public)  
+		 % {{{
+		 name=oshostname();
+		 login='';
+		 numnodes=20;
+		 cpuspernode=8; 
+		 port=0;
+		 queue='general';
+		 time=12*60;
+		 processor='west';
+		 codepath='';
+		 executionpath='';
+		 interactive=0;
+		 bbftp=0;
+		 numstreams=8;
+		 hyperthreading=0;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=discover(varargin) % {{{
+
+			 %initialize cluster using default settings if provided
+			 if (exist('discover_settings')==2), discover_settings; end
+
+			 %use provided options to change fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    numnodes: %i',cluster.numnodes));
+			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			 disp(sprintf('    np: %i',cluster.cpuspernode*cluster.numnodes));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    processor: %s',cluster.processor));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    interactive: %i',cluster.interactive));
+			 disp(sprintf('    hyperthreading: %i',cluster.hyperthreading));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'general_long','general','general_small','debug'};
+			 queue_requirements_time=[24*60 12*60 12*60 60];
+			 queue_requirements_np=[516 1024 16 32];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+
+			 if ( strcmpi(cluster.queue,'general') & cluster.cpuspernode*cluster.numnodes < 17)
+				 md = checkmessage(md,'cpus must be greater than 17 for general queue');
+			 end
+			 %now, check cluster.cpuspernode according to processor type
+			 if ( strcmpi(cluster.processor,'neha')),
+				 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
+					 md = checkmessage(md,'cpuspernode should be between 1 and 8 for ''neha'' processors');
+				 end
+			 elseif strcmpi(cluster.processor,'west'),
+				 if ((cluster.cpuspernode>12 ) | (cluster.cpuspernode<1)),
+					 md = checkmessage(md,'cpuspernode should be between 1 and 12 for ''west'' processors');
+				 end
+			 else
+				 md = checkmessage(md,'unknown processor type, should be ''neha'' or ''west'' ');
+			 end
+
+			 %Miscelaneous
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+%			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l select=%i:mpiprocs=%i:proc=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
+			 fprintf(fid,'#PBS -l walltime=%i:00\n',cluster.time); %SLURM walltime is in minutes:
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -W group_list=s1010\n');
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',[cluster.executionpath '/' dirname '/' modelname]);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',[cluster.executionpath '/' dirname '/' modelname]);
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+			 fprintf(fid,'module purge\n');
+			 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');
+			 fprintf(fid,'export PATH="$PATH:."\n\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpirun -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 if ~isvalgrind,
+					 fprintf(fid,'mpirun -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+				 else
+					 fprintf(fid,'mpirun -np %i valgrind --leak-check=full %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+				 end
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.run '  modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 if cluster.interactive,
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
+			 else 
+				 directory=cluster.executionpath;
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpout(cluster.name,directory,cluster.login,cluster.port,{[dirname '.tar.gz']});
+			 else
+				 issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
+			 end
+
+			 %lauch command, to be executed via ssh
+			 if ~cluster.interactive, 
+				 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 else
+				 launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' dirname '.tar.gz'];
+			 end
+
+			 disp('launching solution sequence on remote cluster');
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end
+		 %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 if ~cluster.interactive,
+				 directory=[cluster.executionpath '/' dirname '/'];
+			 else
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+			 else
+				 issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, filelist);
+			 end
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/gemini.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/gemini.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/gemini.m	(revision 18231)
@@ -0,0 +1,101 @@
+%GEMINI class definition
+%
+%   Usage:
+%      cluster=gemini();
+%      cluster=gemini('np',3);
+%      cluster=gemini('np',3,'login','username');
+
+classdef gemini
+    properties (SetAccess=public) 
+	% {{{
+		name='gemini'
+		login='username';
+		np=50;
+		port=0;
+		queue='debug';
+		time=60;
+		codepath='/workg/edw/issm-2.0/bin'
+		executionpath='/workg/edw/Testing/Execution'
+	%}}}
+    end
+    methods
+		 function cluster=gemini(varargin) % {{{
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'debug','shortg','longg'};
+			 queue_requirements_time=[60 180 720];
+			 queue_requirements_np=[50 50 50];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/sh\n');
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l ncpus=%i\n',cluster.np);
+			 if ~isempty(queue),
+				 fprintf(fid,'#PBS -q %s\n',cluster.queue);
+			 end
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
+
+			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.m	(revision 18231)
@@ -0,0 +1,247 @@
+%GENERIC cluster class definition
+%
+%   Usage:
+%      cluster=generic('name','astrid','np',3);
+%      cluster=generic('name',oshostname(),'np',3,'login','username');
+
+classdef generic
+	properties (SetAccess=public) 
+		% {{{
+		name='';
+		login='';
+		np=1;
+		port=0;
+		interactive=1;
+		codepath=[issmdir() '/bin'];
+		etcpath=[issmdir() '/etc'];
+		executionpath=[issmdir() '/execution'];
+		valgrind=[issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
+		valgrindlib=[issmdir() '/externalpackages/valgrind/install/lib/libmpidebug.so'];
+		valgrindsup=[issmdir() '/externalpackages/valgrind/issm.supp'];
+		verbose=1;
+		shell='/bin/sh';
+		%}}}
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- generic -->');
+            
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="name" type="',class(obj.name),'" default="',convert2str(obj.name),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="login" type="',class(obj.login),'" default="',convert2str(obj.login),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="np" type="',class(obj.np),'" default="',convert2str(obj.np),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="port" type="',class(obj.port),'" default="',convert2str(obj.port),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="codepath" type="',class(obj.codepath),'" default="',convert2str(obj.codepath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+             
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="executionpath" type="',class(obj.executionpath),'" default="',convert2str(obj.executionpath),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="etcpath" type="',class(obj.etcpath),'" default="',convert2str(obj.etcpath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrind" type="',class(obj.valgrind),'" default="',convert2str(obj.valgrind),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindlib" type="',class(obj.valgrindlib),'" default="',convert2str(obj.valgrindlib),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindsup" type="',class(obj.valgrindsup),'" default="',convert2str(obj.valgrindsup),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="verbose" type="',class(obj.verbose),'" default="',convert2str(obj.verbose),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+             
+        end % }}}
+		function cluster=generic(varargin) % {{{
+
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
+
+			%get name
+			cluster.name=getfieldvalue(options,'name',oshostname());
+
+			%initialize cluster using user settings if provided
+			if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			%OK get other fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    login: %s',cluster.login));
+			disp(sprintf('    np: %i',cluster.np));
+			disp(sprintf('    port: %i',cluster.port));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    etcpath: %s',cluster.executionpath));
+			disp(sprintf('    valgrind: %s',cluster.valgrind));
+			disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
+			disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
+			disp(sprintf('    verbose: %s',cluster.verbose));
+			disp(sprintf('    shell: %s',cluster.shell));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+			if cluster.np<1
+				md = checkmessage(md,['number of processors should be at least 1']);
+			end
+			if isnan(cluster.np),
+				md = checkmessage(md,'number of processors should not be NaN!');
+			end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			if ~ispc(),
+
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!%s\n',cluster.shell);
+				if ~isvalgrind,
+					if cluster.interactive
+						if IssmConfig('_HAVE_MPI_'),
+							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s \n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+						else
+							fprintf(fid,'%s/issm.exe %s %s %s ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+						end
+					else
+						if IssmConfig('_HAVE_MPI_'),
+							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						end
+					end
+				elseif isgprof,
+					fprintf(fid,'\n gprof %s/issm.exe gmon.out > %s.performance',cluster.codepath,modelname);
+				else
+					%Add --gen-suppressions=all to get suppression lines
+					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+					if ismac, 
+						if IssmConfig('_HAVE_MPI_'),
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+						end
+					else
+						if IssmConfig('_HAVE_MPI_'),
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						end
+					end
+				end
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
+
+			else % Windows
+
+				fid=fopen([modelname '.bat'],'w');
+				fprintf(fid,'@echo off\n');
+
+				warning('parallel runs not allowed yet in Windows. Defaulting to 1 cpus');
+				cluster.np=1;
+
+				if cluster.np>1,
+					fprintf(fid,'"C:\\Program Files\\MPICH2\\bin\\mpiexec.exe" -n %i "%s/issm.exe" %s ./ %s ',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s ./ %s ',cluster.codepath,EnumToString(solution),modelname);
+				end
+				fclose(fid);
+			end
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			if ~ispc(),
+
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!/bin/sh\n');
+				if ~isvalgrind,
+					if cluster.interactive
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s ',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+					else
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+					end
+				elseif isgprof,
+					fprintf(fid,'\n gprof %s/kriging.exe gmon.out > %s.performance',cluster.codepath,modelname);
+				else
+					%Add --gen-suppressions=all to get suppression lines
+					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+					fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',...
+						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+				end
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
+
+			else % Windows
+
+				fid=fopen([modelname '.bat'],'w');
+				fprintf(fid,'@echo off\n');
+				if cluster.interactive
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' modelname],modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,EnumToString(solution),[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+				end
+				fclose(fid);
+			end
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			if ~ispc,
+
+				%figure out what shell extension we will use:
+				if isempty(strfind(cluster.shell,'csh')),
+					shellext='sh';
+				else
+					shellext='csh';
+				end
+
+				%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);
+
+				if cluster.verbose, disp('uploading input file and queueing script'); end
+				issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+				if cluster.verbose, disp('launching solution sequence on remote cluster'); end
+				launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			else
+				system([modelname '.bat']);
+			end
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			if ispc(),
+				%do nothing
+				return;
+			end
+
+			%copy files from cluster to current directory
+			directory=[cluster.executionpath '/' dirname '/'];
+			issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+		end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/generic.py	(revision 18231)
@@ -0,0 +1,191 @@
+import socket
+import os
+import math
+import subprocess
+from IssmConfig import IssmConfig
+from EnumToString import EnumToString
+from issmdir import issmdir
+from pairoptions import pairoptions
+from issmssh import issmssh
+from issmscpin import issmscpin
+from issmscpout import issmscpout
+import MatlabFuncs as m
+
+class generic(object):
+	"""
+	GENERIC cluster class definition
+ 
+	   Usage:
+	      cluster=generic('name','astrid','np',3);
+	      cluster=generic('name',oshostname(),'np',3,'login','username');
+	"""
+
+	def __init__(self,*args):    # {{{
+
+		self.name=''
+		self.login=''
+		self.np=1
+		self.port=0
+		self.interactive=1
+		self.codepath=issmdir()+'/bin'
+		self.executionpath=issmdir()+'/execution'
+		self.valgrind=issmdir()+'/externalpackages/valgrind/install/bin/valgrind'
+		self.valgrindlib=issmdir()+'/externalpackages/valgrind/install/lib/libmpidebug.so'
+		self.valgrindsup=issmdir()+'/externalpackages/valgrind/issm.supp'
+
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#get name
+		self.name=socket.gethostname()
+
+		#initialize cluster using user settings if provided
+		if os.path.exists(self.name+'_settings.py'):
+			execfile(self.name+'_settings.py',globals())
+
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+	# }}}
+	def __repr__(self):    # {{{
+		#  display the object
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    name: %s\n" % self.name
+		s+="    login: %s\n" % self.login
+		s+="    np: %i\n" % self.np
+		s+="    port: %i\n" % self.port
+		s+="    codepath: %s\n" % self.codepath
+		s+="    executionpath: %s\n" % self.executionpath
+		s+="    valgrind: %s\n" % self.valgrind
+		s+="    valgrindlib: %s\n" % self.valgrindlib
+		s+="    valgrindsup: %s\n" % self.valgrindsup
+		return s
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if self.np<1:
+			md = checkmessage(md,'number of processors should be at least 1')
+		if math.isnan(self.np):
+			md = checkmessage(md,'number of processors should not be NaN!')
+
+		return md
+	# }}}
+	def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof):    # {{{
+
+		#write queuing script 
+		if not m.ispc():
+
+			fid=open(modelname+'.queue','w')
+			fid.write('#!/bin/sh\n')
+			if not isvalgrind:
+				if self.interactive: 
+					if IssmConfig('_HAVE_MPI_')[0]:
+						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+					else:
+						fid.write('%s/issm.exe %s %s/%s %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+				else:
+					if IssmConfig('_HAVE_MPI_')[0]:
+						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+					else:
+						fid.write('%s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+			elif isgprof:
+				fid.write('\n gprof %s/issm.exe gmon.out > %s.performance' % (self.codepath,modelname))
+			else:
+				#Add --gen-suppressions=all to get suppression lines
+				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
+				if IssmConfig('_HAVE_MPI_')[0]:
+					fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
+							(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+				else:	
+					fid.write('%s --leak-check=full --suppressions=%s %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
+							(self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+
+			if not io_gather:    #concatenate the output files:
+				fid.write('\ncat %s.outbin.* > %s.outbin' % (modelname,modelname))
+			fid.close()
+
+		else:    # Windows
+
+			fid=open(modelname+'.bat','w')
+			fid.write('@echo off\n')
+			if self.interactive:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+			fid.close()
+
+		#in interactive mode, create a run file, and errlog and outlog file
+		if self.interactive:
+			fid=open(modelname+'.errlog','w')
+			fid.close()
+			fid=open(modelname+'.outlog','w')
+			fid.close()
+	# }}}
+	def BuildKrigingQueueScript(self,modelname,solution,io_gather,isvalgrind,isgprof):    # {{{
+
+		#write queuing script 
+		if not m.ispc():
+
+			fid=open(modelname+'.queue','w')
+			fid.write('#!/bin/sh\n')
+			if not isvalgrind:
+				if self.interactive:
+					fid.write('mpiexec -np %i %s/kriging.exe %s/%s %s ' % (self.np,self.codepath,self.executionpath,modelname,modelname))
+				else:
+					fid.write('mpiexec -np %i %s/kriging.exe %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,self.executionpath,modelname,modelname,modelname,modelname))
+			elif isgprof:
+				fid.write('\n gprof %s/kriging.exe gmon.out > %s.performance' & (self.codepath,modelname))
+			else:
+				#Add --gen-suppressions=all to get suppression lines
+				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
+				fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/kriging.exe %s/%s %s 2> %s.errlog >%s.outlog ' % \
+					(self.np,self.valgrind,self.valgrindsup,self.codepath,self.executionpath,modelname,modelname,modelname,modelname))
+			if not io_gather:    #concatenate the output files:
+				fid.write('\ncat %s.outbin.* > %s.outbin' % (modelname,modelname))
+			fid.close()
+
+		else:    # Windows
+
+			fid=open(modelname+'.bat','w')
+			fid.write('@echo off\n')
+			if self.interactive:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname,modelname))
+			fid.close()
+
+		#in interactive mode, create a run file, and errlog and outlog file
+		if self.interactive:
+			fid=open(modelname+'.errlog','w')
+			fid.close()
+			fid=open(modelname+'.outlog','w')
+			fid.close()
+	# }}}
+	def LaunchQueueJob(self,modelname,dirname,filelist):    # {{{
+
+		#compress the files into one zip.
+		compressstring='tar -zcf %s.tar.gz ' % dirname
+		for file in filelist:
+			compressstring += ' %s' % file
+		if self.interactive:
+			compressstring += ' %s.errlog %s.outlog ' % (modelname,modelname)
+		subprocess.call(compressstring,shell=True)
+
+		print 'uploading input file and queueing script'
+		issmscpout(self.name,self.executionpath,self.login,self.port,[dirname+'.tar.gz'])
+
+		print 'launching solution sequence on remote cluster'
+		launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && chmod 777 %s.queue && ./%s.queue' % \
+			(self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname)
+		issmssh(self.name,self.login,self.port,launchcommand)
+	# }}}
+	def Download(self,dirname,filelist):     # {{{
+
+		if m.ispc():
+			#do nothing
+			return
+
+		#copy files from cluster to current directory
+		directory='%s/%s/' % (self.executionpath,dirname)
+		issmscpin(self.name,self.login,self.port,directory,filelist)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/greenplanet.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/greenplanet.m	(revision 18231)
@@ -0,0 +1,169 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=greenplanet();
+%      cluster=greenplanet('np',3);
+%      cluster=greenplanet('np',3,'login','username');
+
+classdef greenplanet
+    properties (SetAccess=public)  
+		 % {{{
+		 name='greenplanet'
+		 login='';
+		 numnodes=20;
+		 cpuspernode=8; 
+		 port=8000;
+		 queue='c6145';
+		 codepath='';
+		 executionpath='';
+		 interactive=0;
+		 time=24*60;
+		 memory=2;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=greenplanet(varargin) % {{{
+
+			 %initialize cluster using default settings if provided
+			 if (exist('greenplanet_settings')==2), greenplanet_settings; end
+
+			 %use provided options to change fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    numnodes: %i',cluster.numnodes));
+			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			 disp(sprintf('    np: %i',cluster.cpuspernode*cluster.numnodes));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    interactive: %i',cluster.interactive));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    memory: %i',cluster.memory));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'c6145','default'};
+			 queue_requirements_time=[Inf Inf];
+			 queue_requirements_np=[80 80];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,1)
+
+			 %Miscelaneous
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -l nodes=%i:ppn=%i\n',cluster.numnodes,cluster.cpuspernode);
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60);%walltime is in seconds.
+			 fprintf(fid,'#PBS -l mem=%igb\n',cluster.memory);
+			 fprintf(fid,'#PBS -m bea\n');
+			 fprintf(fid,'#PBS -M mmorligh@uci.edu\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 %fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -l nodes=%i:ppn=%i\n',cluster.numnodes, ...
+							 cluster.cpuspernode);
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -l mem=%igb\n',cluster.memory);
+			 fprintf(fid,'#PBS -m bea\n');
+			 fprintf(fid,'#PBS -M mmorligh@uci.edu\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			  launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+											 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pfe.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pfe.m	(revision 18231)
@@ -0,0 +1,266 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=pfe();
+%      cluster=pfe('np',3);
+%      cluster=pfe('np',3,'login','username');
+
+classdef pfe
+    properties (SetAccess=public)  
+		 % {{{
+		 name           = 'pfe'
+		 login          = '';
+		 numnodes       = 20;
+		 cpuspernode    = 8;
+		 port           = 1025;
+		 queue          = 'long';
+		 time           = 12*60;
+		 processor      = 'neh';
+		 codepath       = '';
+		 executionpath  = '';
+		 grouplist     = 's1010';
+		 interactive    = 0;
+		 bbftp          = 0;
+		 numstreams     = 8;
+		 hyperthreading = 0;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=pfe(varargin) % {{{
+
+			 %initialize cluster using default settings if provided
+			 if (exist('pfe_settings')==2), pfe_settings; end
+
+			 %use provided options to change fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    numnodes: %i',cluster.numnodes));
+			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			 disp(sprintf('    np: %i',cluster.cpuspernode*cluster.numnodes));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    processor: %s',cluster.processor));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    grouplist: %s',cluster.grouplist));
+			 disp(sprintf('    interactive: %i',cluster.interactive));
+			 disp(sprintf('    hyperthreading: %i',cluster.hyperthreading));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'long','normal','debug','devel','alphatst@pbspl233'};
+			 queue_requirements_time=[5*24*60 8*60 2*60 2*60 24*60];
+			 queue_requirements_np=[2048 2048 150 150 2048];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+
+			 %now, check cluster.cpuspernode according to processor type
+			 if (strcmpi(cluster.processor,'har') | strcmpi(cluster.processor,'neh')),
+				 if cluster.hyperthreading,
+					 if ((cluster.cpuspernode>16 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 16 for ''neh'' and ''har'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 8 for ''neh'' and ''har'' processors');
+					 end
+				 end
+			 elseif strcmpi(cluster.processor,'wes'),
+				 if cluster.hyperthreading,
+					 if ((cluster.cpuspernode>24 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 24 for ''wes'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>12 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 12 for ''wes'' processors');
+					 end
+				 end
+			 elseif strcmpi(cluster.processor,'ivy'),
+				 if cluster.hyperthreading,
+					 if ((cluster.cpuspernode>40 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 40 for ''ivy'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>20 ) | (cluster.cpuspernode<1)),
+						 md = checkmessage(md,'cpuspernode should be between 1 and 20 for ''ivy'' processors');
+					 end
+				 end
+
+			 else
+				 md = checkmessage(md,'unknown processor type, should be ''neh'',''wes'' or ''har'' or ''ivy''');
+			 end
+
+			 %Miscelaneous
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+			 if isempty(cluster.grouplist), md = checkmessage(md,'grouplist empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+%			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l select=%i:ncpus=%i:model=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -W group_list=%s\n',cluster.grouplist);
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+			 fprintf(fid,'module load comp-intel/2013.1.117\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
+			 fprintf(fid,'export PATH="$PATH:."\n\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 if ~isvalgrind,
+					 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/Interactive' num2str(cluster.interactive)],modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/Interactive' num2str(cluster.interactive)],modelname);
+				 end
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+			 %			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l select=%i:ncpus=%i:model=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -W group_list=%s\n',cluster.grouplist);
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+			 fprintf(fid,'module load comp-intel/2013.1.117\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
+			 fprintf(fid,'export PATH="$PATH:."\n');
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,modelname);
+			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname); %FIXME
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 if ~isvalgrind,
+					 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+				 end
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.run '  modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 if cluster.interactive,
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
+			 else 
+				 directory=cluster.executionpath;
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpout(cluster.name,directory,cluster.login,cluster.port,{[dirname '.tar.gz']});
+			 else
+				 issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
+			 end
+
+			 %lauch command, to be executed via ssh
+			 if ~cluster.interactive, 
+				 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 else
+				 launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' dirname '.tar.gz'];
+			 end
+
+			 disp('launching solution sequence on remote cluster');
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end
+		 %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 if ~cluster.interactive,
+				 directory=[cluster.executionpath '/' dirname '/'];
+			 else
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+			 else
+				 issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, filelist);
+			 end
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pollux.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pollux.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/clusters/pollux.m	(revision 18231)
@@ -0,0 +1,100 @@
+%POLLUX class definition
+%
+%   Usage:
+%      cluster=pollux();
+%      cluster=pollux('np',3);
+%      cluster=pollux('np',3,'login','username');
+
+classdef pollux
+    properties (SetAccess=public) 
+		 % {{{
+		 name='pollux'
+		 login='username';
+		 np=128;
+		 port=0;
+		 queue='shortp';
+		 time=180;
+		 codepath='/workc/edw/issm-2.0/bin'
+		 executionpath='/workc/edw/Testing/Execution'
+		 %}}}
+	 end
+	 methods
+		 function cluster=pollux(varargin) % {{{
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'shortp','longp'};
+			 queue_requirements_time=[180 720];
+			 queue_requirements_np=[128 128];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/sh\n');
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l ncpus=%i\n',cluster.np);
+			 if ~isempty(queue),
+				 fprintf(fid,'#PBS -q %s\n',cluster.queue);
+			 end
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
+			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.m	(revision 18231)
@@ -0,0 +1,61 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      constants=constants();
+
+classdef constants
+	properties (SetAccess=public) 
+		g                    = 0;
+		yts                  = 0;
+		referencetemperature = 0;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- constants -->');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="g" type="',class(obj.g),'" default="',num2str(obj.g),'">','     <section name="constants" />','     <help> gravitational acceleration [m/s^2] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="yts" type="',class(obj.yts),'" default="',num2str(obj.yts),'">','     <section name="constants" />','     <help> number of seconds in a year [s/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="referencetemperature" type="',class(obj.referencetemperature),'" default="',num2str(obj.referencetemperature),'">','     <section name="constants" />','     <help> reference temperature used in the enthalpy model [K] </help>','</parameter>');
+		end % }}}
+		function obj = constants(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%acceleration due to gravity (m/s^2)
+			obj.g=9.81;
+
+			%converstion from year to seconds
+			obj.yts=365*24*3600;
+
+			%the reference temperature for enthalpy model (cf Aschwanden)
+			obj.referencetemperature=223.15;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+%			md = checkfield(md,'fieldname','constants.g','>',0,'size',[1 1]);
+			md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1 1]);
+			md = checkfield(md,'fieldname','constants.referencetemperature','size',[1 1]);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   constants parameters:'));
+
+			fielddisplay(obj,'g','gravitational acceleration [m/s^2]');
+			fielddisplay(obj,'yts','number of seconds in a year [s/yr]');
+			fielddisplay(obj,'referencetemperature','reference temperature used in the enthalpy model [K]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','g','format','Double');
+			WriteData(fid,'object',obj,'fieldname','yts','format','Double');
+			WriteData(fid,'object',obj,'fieldname','referencetemperature','format','Double');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/constants.py	(revision 18231)
@@ -0,0 +1,57 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class constants(object):
+	"""
+	CONSTANTS class definition
+
+	   Usage:
+	      constants=constants();
+	"""
+
+	def __init__(self): # {{{
+		self.g                    = 0
+		self.yts                  = 0
+		self.referencetemperature = 0
+		
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   constants parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration [m/s^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year [s/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model [K]"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#acceleration due to gravity (m/s^2)
+		self.g=9.81
+
+		#converstion from year to seconds
+		self.yts=365*24*3600
+
+		#the reference temperature for enthalpy model (cf Aschwanden)
+		self.referencetemperature=223.15
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','constants.g','>',0,'size',[1])
+		md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1])
+		md = checkfield(md,'fieldname','constants.referencetemperature','size',[1])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','g','format','Double')
+		WriteData(fid,'object',self,'fieldname','yts','format','Double')
+		WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.m	(revision 18231)
@@ -0,0 +1,255 @@
+%DAMAGEICE class definition
+%
+%   Usage:
+%      damage=damage();
+
+classdef damage
+	properties (SetAccess=public)  
+		%damage 
+		isdamage            = 0;
+		D                   = NaN;
+		law                 = 0;
+		spcdamage           = NaN; 
+		max_damage          = 0;
+	
+		%numerical
+		stabilization       = 0;
+		maxiter             = 0;
+		elementinterp       = '';
+		penalty_threshold   = 0;
+		penalty_lock        = 0;
+		penalty_factor      = 0;
+		
+		%general parameters for evolution law: 
+		stress_threshold    = 0;
+		c1                  = 0;
+		c2                  = 0;
+		c3                  = 0;
+		c4                  = 0;
+		healing             = 0;
+		equiv_stress		  = 0;
+		requested_outputs   = {};
+	end
+	methods
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- damage -->');
+			fprintf(fid, '%s\n', '<!-- Note: this class depends on different input of law -->');
+
+			%fprintf(fid,'%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="logical"',           '" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			% drop-down 
+			fprintf(fid,'%s%s%s%s%s\n\t%s\n','<parameter key ="law" type="','alternative','" optional="','false','">','<section name="damage" />');
+
+			% law = 'undamage'
+			fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="undamage" type="','string','" default="','true','">','<help> law = undamage </help>');
+			% footer for option
+			fprintf(fid,'\t%s\n%s\n','</option>');
+
+			% law = 'pralong'
+			fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="pralong" type="','string','" default="','false','">','<help> law = pralong </help>');
+
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',   '<parameter key ="stress_threshold" type="',class(obj.stress_threshold),'" default="',num2str(obj.stress_threshold),'">','<help> damage stress threshold [Pa] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',	'<parameter key ="c1" type="', class(obj.c1),'" default="',   num2str(obj.c1),'">',   '<help> damage parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c2" type="',          class(obj.c2),'" default="',            num2str(obj.c2),'">','<help> damage parameter 2 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c3" type="',          class(obj.c3),'" default="',            num2str(obj.c3),'">','<help> damage parameter 3 [W/m^2] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c4" type="',            class(obj.c4),'" default="',              num2str(obj.c4),'">','<help> damage parameter 4 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="healing" type="', class(obj.healing),'" default="',   num2str(obj.healing),'">','<help> damage healing parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="equiv_stress" type="',          class(obj.equiv_stress),'" default="',convert2str(obj.equiv_stress),'">','<help> 0: von Mises </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="requested_outputs" type="',          class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','<help> additional outputs requested </help>','</parameter>');
+
+
+			% footer for option
+			fprintf(fid,'\t%s\n%s\n','</option>');
+
+
+			% footer for drop-down
+			fprintf(fid,'\t%s\n%s\n%s','<help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="D" type="',              class(obj.D),'" default="',                  num2str(obj.D),'">',              '     <section name="damage" />','     <help> damage tensor (scalar) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="',            class(obj.law),'" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="spcdamage" type="',      class(obj.spcdamage),'" default="',          num2str(obj.spcdamage),'">',            '     <section name="damage" />','     <help> damage constraints (NaN means no constraint) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="max_damage" type="',     class(obj.max_damage),'" default="',         num2str(obj.max_damage),'">',            '     <section name="damage" />','     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>','</parameter>');
+
+			% stabilization (0,1, or 2) drop-down
+			fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="alternative" optional="false">','     <section name="damage" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
+			fprintf(fid, '%s\n', '       <option value="0" type="string" default="true"></option>');
+			fprintf(fid, '%s\n', '       <option value="1" type="string" default="false"></option>');
+			fprintf(fid, '%s\n', '       <option value="2" type="string" default="false"></option>');
+			fprintf(fid, '%s\n','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',             class(obj.maxiter),'" default="',   num2str(obj.maxiter),'">',   '     <section name="damage" />','     <help> maximum number of non linear iterations </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_lock" type="',        class(obj.penalty_lock),'" default="',            num2str(obj.penalty_lock),'">',            '     <section name="damage" />','     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_threshold" type="',   class(obj.penalty_threshold),'" default="',            num2str(obj.penalty_threshold),'">',            '     <section name="damage" />','     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_factor" type="',      class(obj.penalty_factor),'" default="',            num2str(obj.penalty_factor),'">',            '     <section name="damage" />','     <help> scaling exponent (default is 3) </help>','</parameter>');
+
+		end % }}}
+        
+		function obj = damage(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('damage');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%damage parameters: 
+			obj.isdamage=0;
+			obj.D=0;
+			obj.law=0;
+			
+			obj.max_damage=1-1e-5; %if damage reaches 1, solve becomes singular, as viscosity becomes nil
+		
+			%Type of stabilization used
+			obj.stabilization=2;
+			
+			%Maximum number of iterations
+			obj.maxiter=100;
+
+			%finite element interpolation
+			obj.elementinterp='P1';
+
+			%factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+			
+			%stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)
+			obj.penalty_lock=0;
+			
+			%threshold to declare convergence of thermal solution (default is 0)
+			obj.penalty_threshold=0;
+		
+			%damage evolution parameters 
+			obj.stress_threshold=0;
+			obj.healing=0;
+			obj.c1=0;
+			obj.c2=0;
+			obj.c3=0;
+			obj.c4=0;
+			obj.equiv_stress=0;
+
+			 %output default:
+			 obj.requested_outputs={'default'};
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			
+			md = checkfield(md,'fieldname','damage.isdamage','values',[1,0]);
+			if obj.isdamage,
+				md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2]);
+				md = checkfield(md,'fieldname','damage.D','>=',0,'<=',obj.max_damage,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','damage.spcdamage','forcing',1);
+				md = checkfield(md,'fieldname','damage.max_damage','<',1,'>=',0);
+				md = checkfield(md,'fieldname','damage.stabilization','numel',[1],'values',[0 1 2]);
+				md = checkfield(md,'fieldname','damage.maxiter','>=0',0);
+				md = checkfield(md,'fieldname','damage.elementinterp','values',{'P1','P2'});
+				md = checkfield(md,'fieldname','damage.penalty_factor','>=',0);
+				md = checkfield(md,'fieldname','damage.penalty_lock','>=',0);
+				md = checkfield(md,'fieldname','damage.penalty_threshold','>=',0);
+			end
+
+			if (obj.law==1 | obj.law==2),
+				md = checkfield(md,'fieldname','damage.healing','>=',0);
+				md = checkfield(md,'fieldname','damage.c1','>=',0);
+				md = checkfield(md,'fieldname','damage.c2','>=',0);
+				md = checkfield(md,'fieldname','damage.c3','>=',0);
+				md = checkfield(md,'fieldname','damage.c4','>=',0);
+				md = checkfield(md,'fieldname','damage.stress_threshold','>=',0);
+				md = checkfield(md,'fieldname','damage.equiv_stress','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1);
+			elseif (obj.law~=0),
+				if (solution==DamageEvolutionSolutionEnum),
+					error('Invalid evolution law (md.damage.law) for a damage solution');
+				end
+			end
+		end % }}}
+		function list=defaultoutputs(self,md) % {{{
+
+			if strcmp(domaintype(md.mesh),'2Dhorizontal'),
+            list = {'DamageDbar'};
+         else
+            list = {'DamageD'};
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Damage:\n'));
+
+			fielddisplay(obj,'isdamage','is damage mechanics being used? {true,false}');
+			if obj.isdamage,
+				fielddisplay(obj,'law','damage law {''0: undamaged'',''1: pralong''}');
+				fielddisplay(obj,'D','damage tensor (scalar)');
+				fielddisplay(obj,'spcdamage','damage constraints (NaN means no constraint)');
+				fielddisplay(obj,'max_damage','maximum possible damage (0<=max_damage<1)');
+				
+				fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
+				fielddisplay(obj,'maxiter','maximum number of non linear iterations');
+				fielddisplay(obj,'elementinterp','interpolation scheme for finite elements {''P1'',''P2''}');
+				fielddisplay(obj,'penalty_lock','stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+				fielddisplay(obj,'penalty_threshold','threshold to declare convergence of damage evolution solution (default is 0)');
+				fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
+			end
+
+			if (obj.law==1 | obj.law==2),
+				fielddisplay(obj,'c1','damage parameter 1');
+				fielddisplay(obj,'c2','damage parameter 2');
+				fielddisplay(obj,'c3','damage parameter 3');
+				fielddisplay(obj,'c4','damage parameter 4');
+				fielddisplay(obj,'healing','damage healing parameter');
+				fielddisplay(obj,'stress_threshold','damage stress threshold [Pa]');
+				fielddisplay(obj,'equiv_stress','0: von Mises, 1: max principal');
+				fielddisplay(obj,'requested_outputs','additional outputs requested');
+			end
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+		
+			WriteData(fid,'object',obj,'fieldname','isdamage','format','Boolean');
+			if obj.isdamage,
+				WriteData(fid,'object',obj,'fieldname','law','format','Integer');
+				WriteData(fid,'object',obj,'fieldname','D','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',obj,'fieldname','max_damage','format','Double');
+
+				WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+				WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+				WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(obj.elementinterp),'format','Integer');
+				WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
+				WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
+				WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			end
+	
+			if (obj.law==1 | obj.law==2),
+				WriteData(fid,'object',obj,'fieldname','c1','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c2','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c3','format','Double');
+				WriteData(fid,'object',obj,'fieldname','c4','format','Double');
+				WriteData(fid,'object',obj,'fieldname','stress_threshold','format','Double');
+				WriteData(fid,'object',obj,'fieldname','healing','format','Double');
+				WriteData(fid,'object',obj,'fieldname','equiv_stress','format','Integer');
+			end
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			if obj.isdamage,
+				WriteData(fid,'data',outputs,'enum',DamageEvolutionRequestedOutputsEnum,'format','StringArray');
+			end
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/damage.py	(revision 18231)
@@ -0,0 +1,190 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class damage(object):
+	"""
+	DAMAGE class definition
+
+	   Usage:
+	      damage=damage()
+	"""
+
+	def __init__(self,*args):    # {{{
+			
+		#damage: 
+		self.isdamage           = 0.
+		self.D						= float('NaN')
+		self.law						= float('NaN')
+		self.spcdamage				= float('NaN')
+		self.max_damage			= float('NaN')
+		
+		#numerical
+		self.stabilization		= float('NaN')
+		self.maxiter				= float('NaN')
+		self.elementinterp      = ''
+		self.penalty_threshold	= float('NaN')
+		self.penalty_lock			= float('NaN')
+		self.penalty_factor		= float('NaN')
+
+		#general parameters for evolution law: 
+		self.stress_threshold   = float('NaN')
+		self.c1                 = float('NaN')
+		self.c2                 = float('NaN')
+		self.c3                 = float('NaN')
+		self.c4                 = float('NaN')
+		self.healing				= float('NaN')
+		self.equiv_stress       = float('NaN')
+		self.requested_outputs  = []
+
+		if not len(args):
+			self.setdefaultparameters()
+		else:
+			raise RuntimeError("constructor not supported")
+
+	# }}}
+	def __repr__(self):    # {{{
+		s ='   Damage:\n'
+		
+		s+="%s\n" % fielddisplay(self,"isdamage","is damage mechanics being used? [0 (default) or 1]")
+		if self.isdamage:
+			s+="%s\n" % fielddisplay(self,"D","damage tensor (scalar for now)")
+			s+="%s\n" % fielddisplay(self,"law","damage law ['0: undamaged','1: pralong']")
+			s+="%s\n" % fielddisplay(self,"spcdamage","damage constraints (NaN means no constraint)")
+			s+="%s\n" % fielddisplay(self,"max_damage","maximum possible damage (0<=max_damage<1)")
+
+			s+="%s\n" % fielddisplay(self,"stabilization","0: no, 1: artificial_diffusivity, 2: SUPG")
+			s+="%s\n" % fielddisplay(self,"maxiter","maximum number of non linear iterations")
+			s+="%s\n" %	fielddisplay(self,"elementinterp","interpolation scheme for finite elements [''P1'',''P2'']")
+			s+="%s\n" % fielddisplay(self,"penalty_lock","stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)")
+			s+="%s\n" % fielddisplay(self,"penalty_threshold","threshold to declare convergence of damage evolution solution (default is 0)")
+			s+="%s\n" % fielddisplay(self,"penalty_factor","scaling exponent (default is 3)")
+
+		if self.law== 1 or self.law == 2:
+			s+="%s\n" % fielddisplay(self,"c1","damage parameter 1 ")
+			s+="%s\n" % fielddisplay(self,"c2","damage parameter 2 ")
+			s+="%s\n" % fielddisplay(self,"c3","damage parameter 3 ")
+			s+="%s\n" % fielddisplay(self,"c4","damage parameter 4 ")
+			s+="%s\n" % fielddisplay(self,"stress_threshold","damage stress threshold [Pa]")
+			s+="%s\n" % fielddisplay(self,"healing","damage healing parameter")
+			s+="%s\n" % fielddisplay(self,"equiv_stress","0: von Mises, 1: max principal")
+			s+="%s\n" % fielddisplay(self,'requested_outputs','additional outputs requested')
+
+		return s
+	# }}}
+	def setdefaultparameters(self):    # {{{
+
+		#damage parameters: 
+		self.isdamage=0
+		self.D=0
+		self.law=0
+
+		self.max_damage=1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil
+		
+		#Type of stabilization used
+		self.stabilization=2
+			
+		#Maximum number of iterations
+		self.maxiter=100
+
+		#finite element interpolation
+		self.elementinterp='P1'
+
+		#factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+			
+		#stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)
+		self.penalty_lock=0
+			
+		#threshold to declare convergence of thermal solution (default is 0)
+		self.penalty_threshold=0
+		
+		#damage evolution parameters 
+		self.stress_threshold=0
+		self.c1=0
+		self.c2=0
+		self.c3=0
+		self.c4=0
+		self.healing=0
+		self.equiv_stress=0
+
+		#output default:
+		self.requested_outputs=['default']
+
+		return self
+	# }}}
+	def defaultoutputs(self,md): # {{{
+		
+		if md.mesh.domaintype().lower()=='2dhorizontal':
+			list = ['DamageDbar']
+		else:
+			list = ['DamageD']
+		return list
+
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','damage.isdamage','numel',[1],'values',[0,1])
+		if self.isdamage:
+			md = checkfield(md,'fieldname','damage.D','>=',0,'<=',self.max_damage,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','damage.max_damage','<',1,'>=',0)
+			md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2])
+			md = checkfield(md,'fieldname','damage.spcdamage','forcing',1)
+			md = checkfield(md,'fieldname','damage.stabilization','numel',[1],'values',[0,1,2])
+			md = checkfield(md,'fieldname','damage.maxiter','>=0',0)
+			md = checkfield(md,'fieldname','damage.elementinterp','values',['P1','P2'])
+			md = checkfield(md,'fieldname','damage.penalty_factor','>=0',0)
+			md = checkfield(md,'fieldname','damage.penalty_lock','>=0',0)
+			md = checkfield(md,'fieldname','damage.penalty_threshold','>=0',0)
+
+		if self.law == 1 or self.law == 2:
+			md = checkfield(md,'fieldname','damage.healing','>=',0)
+			md = checkfield(md,'fieldname','damage.c1','>=',0)
+			md = checkfield(md,'fieldname','damage.c2','>=',0)
+			md = checkfield(md,'fieldname','damage.c3','>=',0)
+			md = checkfield(md,'fieldname','damage.c4','>=',0)
+			md = checkfield(md,'fieldname','damage.stress_threshold','>=',0)
+			md = checkfield(md,'fieldname','damage.healing','>=',0)
+			md = checkfield(md,'fieldname','damage.equiv_stress','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1)
+		elif self.law != 0:
+			if (solution==DamageEvolutionSolutionEnum):
+				raise RuntimeError('Invalid evolution law (md.damage.law) for a damage solution')
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','isdamage','format','Boolean')
+		if self.isdamage:
+			WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','law','format','Integer')
+			WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','max_damage','format','Double')
+			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+			WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+			WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(self.elementinterp)[0],'format','Integer')
+			WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
+			WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+			WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+
+		if self.law==1 or self.law==2:
+			WriteData(fid,'object',self,'fieldname','c1','format','Double')
+			WriteData(fid,'object',self,'fieldname','c2','format','Double')
+			WriteData(fid,'object',self,'fieldname','c3','format','Double')
+			WriteData(fid,'object',self,'fieldname','c4','format','Double')
+			WriteData(fid,'object',self,'fieldname','stress_threshold','format','Double')
+			WriteData(fid,'object',self,'fieldname','healing','format','Double')
+			WriteData(fid,'object',self,'fieldname','equiv_stress','format','Integer')
+			
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',DamageEvolutionRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.m	(revision 18231)
@@ -0,0 +1,48 @@
+%DEBUG class definition
+%
+%   Usage:
+%      debug=debug();
+
+classdef debug
+	properties (SetAccess=public) 
+		valgrind = false;
+		gprof    = false;
+		profiling = false;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- Debug -->');
+            
+            %valgrind drop-down (0 or 1)
+			fprintf(fid,'%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="valgrind" type="alternative" optional="false">','     <section name="debug" />','     <help> use Valgrind to debug (0 or 1) </help>');
+            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
+          
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="gprof" type="',              class(obj.gprof),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(obj.gprof),'" type="string" default="true"></option>','     <help> use gnu-profiler to find out where the time is spent </help>','</parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="profiling" type="',              class(obj.profiling),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(obj.profiling),'" type="string" default="true"></option>','     <help> enables profiling (memory, flops, time) </help>','</parameter>');
+        end % }}}
+		function obj = debug(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+				end
+			end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   debug parameters:'));
+
+			fielddisplay(obj,'valgrind','use Valgrind to debug (0 or 1)');
+			fielddisplay(obj,'gprof','use gnu-profiler to find out where the time is spent');
+			fielddisplay(obj,'profiling','enables profiling (memory, flops, time)');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','profiling','format','Boolean');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/debug.py	(revision 18231)
@@ -0,0 +1,34 @@
+from fielddisplay import fielddisplay
+from WriteData import *
+
+class debug(object):
+	"""
+	DEBUG class definition
+
+	   Usage:
+	      debug=debug();
+	"""
+
+	def __init__(self): # {{{
+		self.valgrind  = False
+		self.gprof     = False
+		self.profiling = False
+		
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   debug parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"valgrind","use Valgrind to debug (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"gprof","use gnu-profiler to find out where the time is spent"))
+		string="%s\n%s"%(string,fielddisplay(self,'profiling','enables profiling (memory, flops, time)'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','profiling','format','Boolean')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.m	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/dependent.py	(revision 18231)
@@ -0,0 +1,88 @@
+import os.path
+import numpy
+from pairoptions import pairoptions
+from fielddisplay import fielddisplay
+import MatlabFuncs as m
+from EnumDefinitions import *
+from MeshProfileIntersection import MeshProfileIntersection
+
+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/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.m	(revision 18231)
@@ -0,0 +1,109 @@
+%FLAIM class definition
+%
+%   Usage:
+%      flaim=flaim();
+
+classdef flaim
+	properties (SetAccess=public) 
+		targets            = ''
+		tracks             = ''
+		flightreqs         = struct()
+		criterion          = NaN
+		gridsatequator     = 200000
+		usevalueordering   = true
+		split_antimeridian = true
+		solution           = ''
+		quality            = 0
+		path_optimize      = false
+		opt_ndir           = 1
+		opt_dist           = 25
+		opt_niter          = 30000
+	end
+	methods
+  	 	function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- flaim -->\n');            
+                    
+            % Input
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Input:">','<section name="flaim" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="targets" type="',class(obj.targets),'" default="',convert2str(obj.targets),'">','     <section name="flaim" />','     <help> name of kml output targets file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tracks" type="',class(obj.tracks),'" default="',convert2str(obj.tracks),'">','     <section name="flaim" />','     <help> name of kml input tracks file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="flightreqs" type="',class(obj.flightreqs),'" default="',convert2str(obj.flightreqs),'">','     <section name="flaim" />','     <help> structure of kml flight requirements (not used yet) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="criterion" type="',class(obj.criterion),'" default="',convert2str(obj.criterion),'">','     <section name="flaim" />','     <help> element or nodal criterion for flight path evaluation (metric) </help>','  </parameter>');
+        	fprintf(fid,'%s\n%s\n','</frame>');    
+            
+            % Arguments
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Arguments:">','<section name="flaim" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gridsatequator" type="',class(obj.gridsatequator),'" default="',convert2str(obj.gridsatequator),'">','     <section name="flaim" />','     <help> number of grids at equator (determines resolution) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="usevalueordering" type="',class(obj.usevalueordering),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.usevalueordering),'" type="string" default="true"></option>','     <help> flag to consider target values for flight path evaluation </help>','  </parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="split_antimeridian" type="',class(obj.split_antimeridian),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.split_antimeridian),'" type="string" default="true"></option>','     <help> flag to split polygons on the antimeridian </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');   
+            
+            % Optimization
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Optimization:">','<section name="flaim" />');                    
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="path_optimize" type="',class(obj.path_optimize),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.path_optimize),'" type="string" default="true"></option>','     <help> optimize? (default false) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_ndir" type="',class(obj.opt_ndir),'" default="',convert2str(obj.opt_ndir),'">','     <section name="flaim" />','     <help> number of directions to test when moving a point.  If this value = 1, a random direction is tested. A value > 1 results in directions equally spaced from [0, 2*PI] being tested. For example, 4 would result in directions [0, PI/2, PI, 3PI/2] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_dist" type="',class(obj.opt_dist),'" default="',convert2str(obj.opt_dist),'">','     <section name="flaim" />','     <help> specifies the distance in km (default 25) to move a randomly selected path point on each iteration </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_niter" type="',class(obj.opt_niter),'" default="',convert2str(obj.opt_niter),'">','     <section name="flaim" />','     <help> number of iterations (default 30,000) to run for flightplan optimization, i.e. the number of times to randomly select a point and move it. </help>','  </parameter>');
+        	fprintf(fid,'%s\n%s\n','</frame>');     
+            
+            % Output
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Output:">','<section name="flaim" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="solution" type="',class(obj.solution),'" default="',convert2str(obj.solution),'">','     <section name="flaim" />','     <help> name of kml solution file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="quality" type="',class(obj.quality),'" default="',convert2str(obj.quality),'">','     <section name="flaim" />','     <help> quality of kml solution </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');              
+        
+        end % }}}
+		function obj = flaim(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=FlaimSolutionEnum(), return; end
+
+			md = checkfield(md,'fieldname','flaim.tracks','file',1);
+			if any(isnan(md.flaim.criterion)) || isempty(md.flaim.criterion)
+				md = checkfield(md,'fieldname','flaim.targets','file',1);
+			else
+				md = checkfield(md,'fieldname','flaim.criterion','numel',[md.mesh.numberofvertices md.mesh.numberofelements]);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+
+			disp(sprintf('   FLAIM - Flight Line Adaptation using Ice sheet Modeling:')); 
+
+			disp(sprintf('\n      Input:'));
+			fielddisplay(obj,'targets'            ,'name of kml output targets file ');
+			fielddisplay(obj,'tracks'             ,'name of kml input tracks file ');
+			fielddisplay(obj,'flightreqs'         ,'structure of kml flight requirements (not used yet)');
+			fielddisplay(obj,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)');
+
+			disp(sprintf('\n      Arguments:'));
+			fielddisplay(obj,'gridsatequator'     ,'number of grids at equator (determines resolution)');
+			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)');
+			fielddisplay(obj,'opt_ndir'     ,{'number of directions to test when moving a point.  If this value = 1, a random direction is tested.',...
+											  'A value > 1 results in directions equally spaced from [0, 2*PI] being tested.',...
+											  'For example, 4 would result in directions [0, PI/2, PI, 3PI/2].'});
+			fielddisplay(obj,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration');
+			fielddisplay(obj,'opt_niter'     ,{'number of iterations (default 30,000) to run for flightplan optimization',...
+											   'i.e. the number of times to randomly select a point and move it.'});
+
+			disp(sprintf('\n      Output:'));
+			fielddisplay(obj,'solution'           ,'name of kml solution file');
+			fielddisplay(obj,'quality'            ,'quality of kml solution');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flaim.py	(revision 18231)
@@ -0,0 +1,72 @@
+import numpy
+from collections import OrderedDict
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class flaim(object):
+	"""
+	FLAIM class definition
+
+	   Usage:
+	      flaim=flaim();
+	"""
+
+	def __init__(self): # {{{
+		self.targets            = ''
+		self.tracks             = ''
+		self.flightreqs         = OrderedDict()
+		self.criterion          = float('NaN')
+		self.gridsatequator     = 200000
+		self.usevalueordering   = True
+		self.split_antimeridian = True
+		self.solution           = ''
+		self.quality            = 0
+		self.path_optimize      = False
+		self.opt_ndir           = 1
+		self.opt_dist           = 25
+		self.opt_niter          = 30000
+		#}}}
+	def __repr__(self): # {{{
+		string='   FLAIM - Flight Line Adaptation using Ice sheet Modeling:'
+
+		string="%s\n\n%s"%(string,'      Input:')
+		string="%s\n%s"%(string,fielddisplay(self,'targets'            ,'name of kml output targets file '))
+		string="%s\n%s"%(string,fielddisplay(self,'tracks'             ,'name of kml input tracks file '))
+		string="%s\n%s"%(string,fielddisplay(self,'flightreqs'         ,'structure of kml flight requirements (not used yet)'))
+		string="%s\n%s"%(string,fielddisplay(self,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)'))
+
+		string="%s\n\n%s"%(string,'      Arguments:')
+		string="%s\n%s"%(string,fielddisplay(self,'gridsatequator'     ,'number of grids at equator (determines resolution)'))
+		string="%s\n%s"%(string,fielddisplay(self,'usevalueordering'   ,'flag to consider target values for flight path evaluation'))
+		string="%s\n%s"%(string,fielddisplay(self,'split_antimeridian' ,'flag to split polygons on the antimeridian'))
+		
+		string="%s\n\n%s"%(string,'      Optimization:')
+		string="%s\n%s"%(string,fielddisplay(self,'path_optimize'     ,'optimize? (default false)'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_ndir'     ,['number of directions to test when moving a point.  If this value = 1, a random direction is tested.',\
+										  'A value > 1 results in directions equally spaced from [0, 2*PI] being tested.',\
+										  'For example, 4 would result in directions [0, PI/2, PI, 3PI/2].']))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_niter'     ,['number of iterations (default 30,000) to run for flightplan optimization',\
+										   'i.e. the number of times to randomly select a point and move it.']))
+
+		string="%s\n\n%s"%(string,'      Output:')
+		string="%s\n%s"%(string,fielddisplay(self,'solution'           ,'name of kml solution file'))
+		string="%s\n%s"%(string,fielddisplay(self,'quality'            ,'quality of kml solution'))
+		return string
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==FlaimSolutionEnum():
+			return md
+
+		md = checkfield(md,'fieldname','flaim.tracks','file',1)
+		if numpy.any(numpy.isnan(md.flaim.criterion)) or not md.flaim.criterion:
+			md = checkfield(md,'fieldname','flaim.targets','file',1)
+		else:
+			md = checkfield(md,'fieldname','flaim.criterion','numel',[md.mesh.numberofvertices,md.mesh.numberofelements])
+
+		return md
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.m	(revision 18231)
@@ -0,0 +1,229 @@
+%FLOWEQUATION class definition
+%
+%   Usage:
+%      flowequation=flowequation();
+
+classdef flowequation
+	properties (SetAccess=public) 
+		isSIA                     = 0;
+		isSSA                     = 0;
+		isL1L2                    = 0;
+		isHO                      = 0;
+		isFS                      = 0;
+		fe_SSA                    = '';
+		fe_HO                     = '';
+		fe_FS                     = '';
+		augmented_lagrangian_r    = 1.;
+		augmented_lagrangian_rhop = 1.;
+		XTH_theta                 = 0.;
+		vertex_equation           = NaN;
+		element_equation          = NaN;
+		borderSSA                 = NaN;
+		borderHO                  = NaN;
+		borderFS                  = NaN;
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of this class and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(obj)
+				disp('Recovering flowequation from older version');
+				objstruct = obj;
+				obj = structtoobj(flowequation(),objstruct);
+
+				%2013 July 23rd
+				if isfield(objstruct,'ishutter'),      obj.isSIA     = objstruct.ishutter;       end; 
+				if isfield(objstruct,'ismacayeal'),    obj.isSSA     = objstruct.ismacayeal;     end; 
+				if isfield(objstruct,'ispattyn'),      obj.isHO      = objstruct.ispattyn;       end; 
+				if isfield(objstruct,'isstokes'),      obj.isFS      = objstruct.isstokes;       end; 
+				if isfield(objstruct,'bordermacayeal'),obj.borderSSA = objstruct.bordermacayeal; end; 
+				if isfield(objstruct,'borderpattyn'),  obj.borderHO  = objstruct.borderpattyn;   end; 
+				if isfield(objstruct,'borderstokes'),  obj.borderFS  = objstruct.borderstokes;   end; 
+			end
+
+		end% }}}
+	end
+	methods
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- flowequation -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Flow equation parameters">','<section name="flowequation" />');                    
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSIA" type="',              class(obj.isSIA),'" default="',                  convert2str(obj.isSIA),'">',              '     <section name="flowequation" />','     <help> is the Shallow Ice Approximation (SIA) used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSSA" type="',            class(obj.isSSA),'" default="',                convert2str(obj.isSSA),'">',   '     <section name="flowequation" />','     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isL1L2" type="',      class(obj.isL1L2),'" default="',          convert2str(obj.isL1L2),'">',            '     <section name="flowequation" />','     <help> is the L1L2 approximation used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isHO" type="',     class(obj.isHO),'" default="',         convert2str(obj.isHO),'">',            '     <section name="flowequation" />','     <help> is the Higher-Order (HO) approximation used ? </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isFS" type="',       class(obj.isFS),'" default="',              convert2str(obj.isFS),'">',              '     <section name="flowequation" />','     <help> are the Full-FS (FS) equations used ? </help>','</parameter>');
+
+			% fe_SSA drop-down (P1, P1bubble, P1bubblecondensed, P2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="fe_SSA" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for SSA  "P1", "P1bubble" "P1bubblecondensed" "P2" </help>');
+			fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
+
+			%fe_HO drop-down (P1, P1bubble, P1bubblecondensed, P1xP2, P2xP1, P2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_HO" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for HO   "P1" "P1bubble" "P1bubblecondensed" "P1xP2" "P2xP1" "P2" </help>');
+			fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1xP2" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P2xP1" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
+
+			% fe_FS drop-down (P1P1, P1P1GLS, MINIcondensed, MINI, TaylowHood)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_FS" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for FS   "P1P1" (debugging only) "P1P1GLS" "MINIcondensed" "MINI" "TaylorHood" </help>');
+			fprintf(fid,'%s\n','       <option value="P1P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1P1GLS" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="MINIcondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="MINI" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="TaylorHood" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="vertex_equation" type="',      class(obj.vertex_equation),'" default="',            convert2str(obj.vertex_equation),'">',            '     <section name="flowequation" />','     <help> flow equation for each vertex </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="element_equation" type="',            class(obj.element_equation),'" default="',              convert2str(obj.element_equation),'">',              '     <section name="flowequation" />','     <help> flow equation for each element </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="borderSSA" type="', class(obj.borderSSA),'" default="',   convert2str(obj.borderSSA),'">',   '     <section name="flowequation" />','     <help> vertices on SSAs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="borderHO" type="',          class(obj.borderHO),'" default="',            convert2str(obj.borderHO),'">',            '     <section name="flowequation" />','     <help> vertices on HOs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="borderFS" type="',          class(obj.borderFS),'" default="',            convert2str(obj.borderFS),'">',            '     <section name="flowequation" />','     <help> vertices on FS border (for tiling) </help>','</parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function obj = flowequation(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%P1 for SSA
+			obj.fe_SSA= 'P1';
+
+			%P1 for HO
+			obj.fe_HO= 'P1';
+
+			%MINI condensed element for FS by default
+			obj.fe_FS = 'MINIcondensed';
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(StressbalanceAnalysisEnum(),analyses),
+
+				md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2','P2bubble'});
+				md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'});
+				md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'});
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',0.5);
+				md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				if strcmp(domaintype(md.mesh),'2Dhorizontal')
+					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
+					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
+				elseif strcmp(domaintype(md.mesh),'2Dvertical')
+					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[2,4,5]);
+					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[2,4,5]);
+				elseif strcmp(domaintype(md.mesh),'3D'),
+					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
+					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
+				else
+					error('Case not supported yet');
+				end
+				if ~(obj.isSIA || obj.isSSA || obj.isL1L2 || obj.isHO || obj.isFS),
+					md = checkmessage(md,['no element types set for this model']);
+				end
+			end
+			if ismember(StressbalanceSIAAnalysisEnum(),analyses),
+				if any(obj.element_equation==1),
+					if(obj.vertex_equation & md.mask.groundedice_levelset<0.),
+						disp(sprintf('\n !!! Warning: SIA''s model is not consistent on ice shelves !!!\n'));
+					end
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   flow equation parameters:'));
+
+			fielddisplay(obj,'isSIA','is the Shallow Ice Approximation (SIA) used ?');
+			fielddisplay(obj,'isSSA','is the Shelfy-Stream Approximation (SSA) used ?');
+			fielddisplay(obj,'isL1L2','is the L1L2 approximation used ?');
+			fielddisplay(obj,'isHO','is the Higher-Order (HO) approximation used ?');
+			fielddisplay(obj,'isFS','are the Full-FS (FS) equations used ?');
+			fielddisplay(obj,'fe_SSA','Finite Element for SSA  ''P1'', ''P1bubble'' ''P1bubblecondensed'' ''P2''');
+			fielddisplay(obj,'fe_HO', 'Finite Element for HO   ''P1'' ''P1bubble'' ''P1bubblecondensed'' ''P1xP2'' ''P2xP1'' ''P2''');
+			fielddisplay(obj,'fe_FS', 'Finite Element for FS   ''P1P1'' (debugging only) ''P1P1GLS'' ''MINIcondensed'' ''MINI'' ''TaylorHood'' ''XTaylorHood''');
+			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
+			fielddisplay(obj,'element_equation','flow equation for each element');
+			fielddisplay(obj,'borderSSA','vertices on SSA''s border (for tiling)');
+			fielddisplay(obj,'borderHO','vertices on HO''s border (for tiling)');
+			fielddisplay(obj,'borderFS','vertices on FS'' border (for tiling)');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','isSIA','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isSSA','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isL1L2','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isHO','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isFS','format','Boolean');
+			WriteData(fid,'enum',FlowequationFeSSAEnum(),'data',StringToEnum(obj.fe_SSA),'format','Integer');
+			WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(obj.fe_HO) ,'format','Integer');
+			WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(obj.fe_FS) ,'format','Integer');
+			WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',obj.augmented_lagrangian_r ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',obj.augmented_lagrangian_rhop ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',obj.XTH_theta ,'format','Double');
+			WriteData(fid,'object',obj,'fieldname','borderSSA','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','borderHO','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','borderFS','format','DoubleMat','mattype',1);
+			%convert approximations to enums
+			data=obj.vertex_equation;
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
+			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
+			pos=find(data==3); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==4); data(pos,end)=HOApproximationEnum();
+			pos=find(data==5); data(pos,end)=FSApproximationEnum();
+
+			pos=find(data==6); data(pos,end)=SSAHOApproximationEnum();
+			pos=find(data==7); data(pos,end)=HOFSApproximationEnum();
+			pos=find(data==8); data(pos,end)=SSAFSApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
+			data=obj.element_equation;
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
+			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
+			pos=find(data==3); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==4); data(pos,end)=HOApproximationEnum();
+			pos=find(data==5); data(pos,end)=FSApproximationEnum();
+
+			pos=find(data==6); data(pos,end)=SSAHOApproximationEnum();
+			pos=find(data==7); data(pos,end)=SSAFSApproximationEnum();
+			pos=find(data==8); data(pos,end)=HOFSApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/flowequation.py	(revision 18231)
@@ -0,0 +1,144 @@
+import numpy
+import copy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class flowequation(object):
+	"""
+	FLOWEQUATION class definition
+
+	   Usage:
+	      flowequation=flowequation();
+	"""
+
+	def __init__(self): # {{{
+		
+		self.isSIA                     = 0
+		self.isSSA                     = 0
+		self.isL1L2                    = 0
+		self.isHO                      = 0
+		self.isFS                      = 0
+		self.fe_SSA                    = ''
+		self.fe_HO                     = ''
+		self.fe_FS                     = ''
+		self.augmented_lagrangian_r    = 1.
+		self.augmented_lagrangian_rhop = 1.
+		self.XTH_theta                 = 0.
+		self.vertex_equation           = float('NaN')
+		self.element_equation          = float('NaN')
+		self.borderSSA                 = float('NaN')
+		self.borderHO                  = float('NaN')
+		self.borderFS                  = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   flow equation parameters:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'isSIA',"is the Shallow Ice Approximation (SIA) used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isSSA',"is the Shelfy-Stream Approximation (SSA) used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isL1L2',"are L1L2 equations used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isHO',"is the Higher-Order (HO) approximation used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isFS',"are the Full-FS (FS) equations used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_SSA',"Finite Element for SSA: 'P1', 'P1bubble' 'P1bubblecondensed' 'P2'"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO:  'P1' 'P1bubble' 'P1bubblecondensed' 'P1xP2' 'P2xP1' 'P2'"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS:  'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood' 'LATaylorHood' 'XTaylorHood'"))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_equation',"flow equation for each vertex"))
+		string="%s\n%s"%(string,fielddisplay(self,'element_equation',"flow equation for each element"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderSSA',"vertices on SSA's border (for tiling)"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderHO',"vertices on HO's border (for tiling)"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderFS',"vertices on FS' border (for tiling)"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+
+		#P1 for SSA
+		self.fe_SSA= 'P1';
+
+		#P1 for HO
+		self.fe_HO= 'P1';
+
+		#MINI condensed element for FS by default
+		self.fe_FS = 'MINIcondensed';
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if StressbalanceAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
+			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
+			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
+			md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',.5)
+			if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
+			elif m.strcmp(md.mesh.domaintype(),'3D'):
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
+			else:
+				raise RuntimeError('mesh type not supported yet')
+			if not (self.isSIA or self.isSSA or self.isL1L2 or self.isHO or self.isFS):
+				md.checkmessage("no element types set for this model")
+
+		if StressbalanceSIAAnalysisEnum() in analyses:
+			if any(self.element_equation==1):
+				if numpy.any(numpy.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
+					print "\n !!! Warning: SIA's model is not consistent on ice shelves !!!\n"
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isSIA','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isSSA','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isL1L2','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isHO','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isFS','format','Boolean')
+		WriteData(fid,'enum',FlowequationFeSSAEnum(),'data',StringToEnum(self.fe_SSA)[0],'format','Integer')
+		WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO)[0] ,'format','Integer')
+		WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS)[0] ,'format','Integer')
+		WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',self.augmented_lagrangian_r ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',self.augmented_lagrangian_rhop ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',self.XTH_theta ,'format','Double')
+		WriteData(fid,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1)
+		#convert approximations to enums
+		data=copy.deepcopy(self.vertex_equation)
+		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
+		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
+		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
+		data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==4)]=HOApproximationEnum()
+		data[numpy.nonzero(data==5)]=FSApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
+		data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
+		data[numpy.nonzero(data==8)]=SSAFSApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
+		data=copy.deepcopy(self.element_equation)
+		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
+		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
+		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
+		data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==4)]=HOApproximationEnum()
+		data[numpy.nonzero(data==5)]=FSApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
+		data[numpy.nonzero(data==7)]=SSAFSApproximationEnum()
+		data[numpy.nonzero(data==8)]=HOFSApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.m	(revision 18231)
@@ -0,0 +1,59 @@
+%FRICTION class definition
+%
+%   Usage:
+%      friction=friction();
+
+classdef friction
+	properties (SetAccess=public) 
+		coefficient = NaN;
+		p           = NaN;
+		q           = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="friction" />');   
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(obj.coefficient),'" default="',     	convert2str(obj.coefficient),'">',              '     <section name="friction" />','     <help> friction coefficient [SI] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(obj.p),'" default="',                 convert2str(obj.p),'">',   '     <section name="friction" />','     <help> p exponent </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(obj.q),'" default="',                 convert2str(obj.q),'">',            '     <section name="friction" />','     <help> q exponent </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = friction(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'fieldname','friction.coefficient','forcing',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)'));
+			fielddisplay(obj,'coefficient','friction coefficient [SI]');
+			fielddisplay(obj,'p','p exponent');
+			fielddisplay(obj,'q','q exponent');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',FrictionLawEnum,'data',1,'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','coefficient','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			%WriteData(fid,'object',obj,'fieldname','coefficient','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','p','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','q','format','DoubleMat','mattype',2);
+			
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/friction.py	(revision 18231)
@@ -0,0 +1,51 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class friction(object):
+	"""
+	FRICTION class definition
+
+	   Usage:
+	      friction=friction();
+	"""
+
+	def __init__(self): # {{{
+		self.coefficient = float('NaN')
+		self.p           = float('NaN')
+		self.q           = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)"
+
+		string="%s\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
+		string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','friction.coefficient','forcing',1,'NaN',1)
+		md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',FrictionLawEnum(),'data',1,'format','Integer')
+		WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.m	(revision 18231)
@@ -0,0 +1,54 @@
+%FRICTIONWEERTMAN class definition
+%
+%   Usage:
+%      frictionweertman=frictionweertman();
+
+classdef frictionweertman
+	properties (SetAccess=public) 
+		C = NaN;
+		m = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="frictionweertman" />');   
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(obj.coefficient),'" default="',     	convert2str(obj.coefficient),'">',              '     <section name="frictionweertman" />','     <help> frictionweertman coefficient [SI] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(obj.p),'" default="',                 convert2str(obj.p),'">',   '     <section name="frictionweertman" />','     <help> p exponent </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(obj.q),'" default="',                 convert2str(obj.q),'">',            '     <section name="frictionweertman" />','     <help> q exponent </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = frictionweertman(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'fieldname','frictionweertman.C','forcing',1,'NaN',1);
+			md = checkfield(md,'fieldname','frictionweertman.m','NaN',1,'size',[md.mesh.numberofelements 1]);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('Weertman sliding law parameters: Sigma_b = C^2 * |u_b|^(1/m-1) * u_b'));
+			fielddisplay(obj,'coefficient','friction coefficient [SI]');
+			fielddisplay(obj,'m','m exponent');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',FrictionLawEnum,'data',1,'format','Integer');
+			WriteData(fid,'class','friction','object',obj,'fieldname','C','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'class','friction','object',obj,'fieldname','m','format','DoubleMat','mattype',2);
+			
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/frictionweertman.py	(revision 18231)
@@ -0,0 +1,47 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class frictionweertman(object):
+	"""
+	FRICTIONWEERTMAN class definition
+
+	   Usage:
+	      frictionweertman=frictionweertman();
+	"""
+
+	def __init__(self): # {{{
+		self.C = float('NaN')
+		self.m = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="Weertman sliding law parameters: Sigma_b = C^2 * |u_b|^(1/m-1) * u_b"
+
+		string="%s\n%s"%(string,fielddisplay(self,"C","friction coefficient [SI]"))
+		string="%s\n%s"%(string,fielddisplay(self,"m","m exponent"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','friction.C','forcing',1,'NaN',1)
+		md = checkfield(md,'fieldname','friction.m','NaN',1,'size',[md.mesh.numberofelements])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',FrictionLawEnum(),'data',2,'format','Integer')
+		WriteData(fid,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1)
+		WriteData(fid,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.m	(revision 18231)
@@ -0,0 +1,91 @@
+%GEOMETRY class definition
+%
+%   Usage:
+%      geometry=geometry();
+
+classdef geometry
+	properties (SetAccess=public) 
+		surface           = NaN;
+		thickness         = NaN;
+		base              = NaN;
+		bed               = NaN;
+		hydrostatic_ratio = NaN;
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. Update old properties here
+
+			%2014 March 26th
+			if isstruct(obj),
+				disp('WARNING: updating geometry');
+				disp('         md.geometry.bed        is now md.geometry.base');
+				disp('         md.geometry.bathymetry is now md.geometry.bed');
+				obj2=obj;
+				obj=geometry();
+				obj.surface    = obj2.surface;
+				obj.thickness  = obj2.thickness;
+				obj.base       = obj2.bed;
+				obj.bed        = obj2.bathymetry;
+			end
+
+		end% }}}
+	end
+	methods
+        %function createxml(obj,fid)
+        function createxml(obj, fid)% {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- geometry -->');
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Geometry parameters">','<section name="geometry" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="surface" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> surface elevation [m] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thickness" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> ice thickness [m] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bed" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> bed elevation [m] </help>','</parameter>');
+            %fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bathymetry" type="',class(obj.bathymetry),'" default="',convert2str(obj.bathymetry),'">','     <section name="geometry" />','     <help> bathymetry elevation [m] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="hydrostatic_ratio" type="',class(obj.hydrostatic_ratio),'" default="',convert2str(obj.hydrostatic_ratio),'">','     <section name="geometry" />','     <help> coefficient for ice shelves; thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = geometry(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if (solution==TransientSolutionEnum() & md.transient.isgia) | (solution==GiaSolutionEnum()),
+				md = checkfield(md,'fieldname','geometry.thickness','forcing',1,'NaN',1,'>=',0);
+			else
+				md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+				if any((obj.thickness-obj.surface+obj.base)>10^-9),
+					md = checkmessage(md,['equality thickness=surface-base violated']);
+				end 
+				if solution==TransientSolutionEnum() & md.transient.isgroundingline,
+					md = checkfield(md,'fieldname','geometry.bed','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   geometry parameters:'));
+
+			fielddisplay(obj,'surface','ice upper surface elevation [m]');
+			fielddisplay(obj,'thickness','ice thickness [m]');
+			fielddisplay(obj,'base','ice base elevation [m]');
+			fielddisplay(obj,'bed','bed elevation [m]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
+			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'data',obj.base,'format','DoubleMat','mattype',1,'enum',BaseEnum());
+			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
+			WriteData(fid,'object',obj,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/geometry.py	(revision 18231)
@@ -0,0 +1,55 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class geometry(object):
+	"""
+	GEOMETRY class definition
+
+	   Usage:
+	      geometry=geometry();
+	"""
+
+	def __init__(self): # {{{
+		self.surface           = float('NaN')
+		self.thickness         = float('NaN')
+		self.base               = float('NaN')
+		self.bed        = float('NaN')
+		self.hydrostatic_ratio = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+
+		string="   geometry parameters:"
+		string="%s\n%s"%(string,fielddisplay(self,'surface','ice upper surface elevation [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness','ice thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'base','ice base elevation [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'bed','bed elevation [m]'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0,'forcing',1)
+		if any((self.thickness-self.surface+self.base)>10**-9):
+			md.checkmessage("equality thickness=surface-base violated")
+		if solution==TransientSolutionEnum() and md.transient.isgroundingline:
+			md = checkfield(md,'fieldname','geometry.bed','NaN',1,'size',[md.mesh.numberofvertices])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
+		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'data',self.base,'format','DoubleMat','mattype',1,'enum',BaseEnum())
+		WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
+		WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.m	(revision 18231)
@@ -0,0 +1,76 @@
+%GIA class definition
+%
+%   Usage:
+%      gia=gia();
+
+classdef gia
+	properties (SetAccess=public) 
+		mantle_viscosity              = NaN;
+		lithosphere_thickness         = NaN;
+		cross_section_shape           = 0;
+	end
+	methods
+         function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- gia -->\n');            
+                    
+            % gia solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="gia parameters">','<section name="gia" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mantle_viscosity" type="',class(obj.mantle_viscosity),'" default="',convert2str(obj.mantle_viscosity),'">','     <section name="gia" />','     <help> mantle viscosity[Pa s] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lithosphere_thickness" type="',class(obj.lithosphere_thickness),'" default="',convert2str(obj.lithosphere_thickness),'">','     <section name="gia" />','     <help> lithosphere thickness (km) </help>','  </parameter>');
+            %cross_section_shape drop-down (1 o r 2)
+            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="cross_section_shape" type="alternative" optional="false">','     <section name="gia" />','     <help> 1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore </help>');
+            fprintf(fid,'%s\n','       <option value="1" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+            
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = gia(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+		obj.cross_section_shape=1; %square as default (see iedge in GiaDeflectionCorex)
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ~ismember(GiaAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'fieldname','gia.mantle_viscosity','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			md = checkfield(md,'fieldname','gia.lithosphere_thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			md = checkfield(md,'fieldname','gia.cross_section_shape','numel',[1],'values',[1,2]);
+
+			%be sure that if we are running a masstransport ice flow model coupled with gia, that thickness forcings 
+			%are not provided into the future.
+			if solution==TransientSolutionEnum() & md.transient.ismasstransport & md.transient.isgia,
+				%figure out if thickness is a transient forcing: 
+				if size(md.geometry.thickness,1)==md.mesh.numberofvertices+1,
+					%recover the furthest time "in time": 
+					if(thickness(end,end)~=md.timestepping.start_time),
+						md = checkmessage(md,['if ismasstransport is on, transient thickness forcing'...
+							' for the gia model should not be provided in the future.'...
+							' Synchronize your start_time to correspond to the most recent transient'...
+							' thickness forcing timestep']);
+					end
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   gia parameters:'));
+
+			fielddisplay(obj,'mantle_viscosity','mantle viscosity[Pa s]');
+			fielddisplay(obj,'lithosphere_thickness','lithosphere thickness (km)');
+			fielddisplay(obj,'cross_section_shape','1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10^3); %from km to m
+			WriteData(fid,'object',obj,'fieldname','cross_section_shape','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/gia.py	(revision 18231)
@@ -0,0 +1,58 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class gia(object):
+	"""
+	GIA class definition
+
+	   Usage:
+	      gia=gia();
+	"""
+
+	def __init__(self): # {{{
+		self.mantle_viscosity              = float('NaN');
+		self.lithosphere_thickness         = float('NaN');
+		self.cross_section_shape           = 0;
+	
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   gia solution parameters:' 
+		
+		string="%s\n%s"%(string,fielddisplay(self,'mantle_viscosity','mantle viscosity constraints (NaN means no constraint) (Pa s)'))
+		string="%s\n%s"%(string,fielddisplay(self,'lithosphere_thickness','lithosphere thickness constraints (NaN means no constraint) (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'cross_section_shape',"1: square-edged, 2: elliptical-edged surface"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+
+		self.cross_section_shape=1; 
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		# Early return 
+		if (GiaAnalysisEnum() not in  analyses):
+			return md 
+		
+		md = checkfield(md,'fieldname','gia.mantle_viscosity','NaN',1,'size',[md.mesh.numberofvertices,1],'>',0)
+		md = checkfield(md,'fieldname','gia.lithosphere_thickness','NaN',1,'size',[md.mesh.numberofvertices,1],'>',0)
+		md = checkfield(md,'fieldname','gia.cross_section_shape','numel',[1],'values',[1,2])
+
+		#be sure that if we are running a masstransport ice flow model coupled with gia, that thickness forcings 
+		#are not provided into the future.
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
+		WriteData(fid,'object',self,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10.**3.);
+		WriteData(fid,'object',self,'fieldname','cross_section_shape','format','Integer');
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.m	(revision 18231)
@@ -0,0 +1,67 @@
+%GROUNDINGLINE class definition
+%
+%   Usage:
+%      groundingline=groundingline();
+
+classdef groundingline
+	properties (SetAccess=public) 
+		migration    = '';
+	end
+	methods
+         function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- groundingline -->');
+            
+            % Convergence criteria          
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Grounding line migration parameters">','<section name="groundingline" />');  
+			
+            % migration (SoftMigration, AggressiveMigration, or None)drop-down
+            fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="migration" type="alternative" optional="false">','     <section name="groundingline" />','     <help> type of grounding line migration: "SoftMigration","AggressiveMigration" or "None" </help>');
+            fprintf(fid,'%s\n','       <option value="SoftMigration" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n','       <option value="AggressiveMigration" type="string" default="false"> </option>');
+            fprintf(fid, '%s\n%s\n','       <option value="None" type="string" default="false"></option>','</parameter>');
+
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = groundingline(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of migration
+			obj.migration='None';
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','groundingline.migration','values',{'None' 'AggressiveMigration' 'SoftMigration' 'SubelementMigration' 'SubelementMigration2' 'Contact' 'None'});
+
+			if ~strcmp(obj.migration,'None'),
+				if isnan(md.geometry.bed),
+					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
+				end
+				pos=find(md.mask.groundedice_levelset>0.);
+				if any(abs(md.geometry.base(pos)-md.geometry.bed(pos))>10^-10),
+					md = checkmessage(md,['bathymetry not equal to bed on grounded ice!']);
+				end
+				if any(md.geometry.bed - md.geometry.base > 10^-9),
+					md = checkmessage(md,['bathymetry superior to bed on floating ice!']);
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   grounding line migration parameters:'));
+			fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'' or ''None''');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/groundingline.py	(revision 18231)
@@ -0,0 +1,54 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class groundingline(object):
+	"""
+	GROUNDINGLINE class definition
+
+	   Usage:
+	      groundingline=groundingline();
+	"""
+
+	def __init__(self): # {{{
+		self.migration=''
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   grounding line migration parameters:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'',''SubelementMigration'',''SubelementMigration2'',''Contact'',''None'''))
+		return string
+		#}}}	
+	def setdefaultparameters(self): # {{{
+
+		#Type of migration
+		self.migration='None'
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','groundingline.migration','values',['None','AggressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2','Contact'])
+
+		if not m.strcmp(self.migration,'None'):
+			if numpy.any(numpy.isnan(md.geometry.bed)):
+				md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
+			pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
+			if any(numpy.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
+				md.checkmessage("bathymetry not equal to bed on grounded ice!")
+			if any(md.geometry.bed - md.geometry.base > 10**-9):
+				md.checkmessage("bathymetry superior to bed on floating ice!")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.m	(revision 18231)
@@ -0,0 +1,201 @@
+%Hydrologydc class definition
+%
+%   Usage:
+%      hydrologydc=hydrologydc();
+
+classdef hydrologydc
+	properties (SetAccess=public) 
+		water_compressibility    = 0;
+		isefficientlayer         = 0;
+		penalty_factor           = 0;
+		penalty_lock             = 0;
+		rel_tol                  = 0;
+		max_iter                 = 0;
+		sedimentlimit_flag       = 0;
+		sedimentlimit            = 0;
+		transfer_flag            = 0;
+		leakage_factor           = 0;
+		basal_moulin_input       = NaN;
+
+		spcsediment_head         = NaN;
+		sediment_transmitivity   = NaN;
+		sediment_compressibility = 0;
+		sediment_porosity        = 0;
+		sediment_thickness       = 0;
+
+
+		spcepl_head              = NaN;
+		mask_eplactive_node      = NaN;
+		epl_compressibility      = 0;
+		epl_porosity             = 0;
+		epl_initial_thickness    = 0;
+		epl_max_thickness    = 0;
+		epl_conductivity         = 0;
+  end
+	methods
+		% {{{ function obj = hydrologydc(varargin) 
+		function obj = hydrologydc(varargin) 
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+	    end
+		end 
+		% }}}
+		function self = initialize(self,md) % {{{
+			if isnan(self.basal_moulin_input),
+				self.basal_moulin_input=zeros(md.mesh.numberofvertices,1);
+				disp('      no hydrology.basal_moulin_input specified: values set as zero');
+			end
+
+		end % }}}
+		% {{{ function obj = setdefaultparameters(obj) 
+		function obj = setdefaultparameters(obj) 
+
+		%Parameters from de Fleurian 2014
+			obj.water_compressibility    = 5.04e-10;
+			obj.isefficientlayer         = 1;
+			obj.penalty_factor           = 3;
+			obj.rel_tol                  = 1.0e-06;
+			obj.max_iter                 = 100;
+			obj.sedimentlimit_flag       = 0;
+			obj.sedimentlimit            = 0;
+			obj.transfer_flag            = 0;
+			obj.leakage_factor           = 10.0;
+
+			obj.sediment_compressibility = 1.0e-08;
+			obj.sediment_porosity        = 0.4;
+			obj.sediment_thickness       = 20.0;
+			obj.sediment_transmitivity   = 8.0e-04;
+
+			obj.epl_compressibility      = 1.0e-08;
+			obj.epl_porosity             = 0.4;
+			obj.epl_initial_thickness    = 1.0;
+			obj.epl_max_thickness    = 5.0;
+			obj.epl_conductivity         = 8.0e-02;
+
+		end 
+		% }}}
+		% {{{ function md = checkconsistency(obj,md,solution,analyses) 
+		function md = checkconsistency(obj,md,solution,analyses) 
+		%Early return
+			if ~ismember(HydrologyDCInefficientAnalysisEnum(),analyses) & ~ismember(HydrologyDCEfficientAnalysisEnum(),analyses),
+				return;
+			end
+
+			md = checkfield(md,'fieldname','hydrology.water_compressibility','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.isefficientlayer','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','hydrology.penalty_factor','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.rel_tol','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3]);
+			md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0 1]);
+			if obj.sedimentlimit_flag==1,
+				md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0,'numel',1);
+	    end
+			if obj.transfer_flag==1,
+				md = checkfield(md,'fieldname','hydrology.leakage_factor','>',0,'numel',1);
+	    end
+			md = checkfield(md,'fieldname','hydrology.basal_moulin_input','NaN',1,'forcing',1);
+
+			md = checkfield(md,'fieldname','hydrology.spcsediment_head','forcing',1);
+			md = checkfield(md,'fieldname','hydrology.sediment_compressibility','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices 1]);
+
+			if obj.isefficientlayer==1,
+				md = checkfield(md,'fieldname','hydrology.spcepl_head','forcing',1);
+				md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_initial_thickness','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_max_thickness','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_conductivity','>',0,'numel',1);
+	    end
+		end 
+		% }}}
+		% {{{ function disp(obj)
+		function disp(obj) 
+			disp(sprintf('   hydrology Dual Porous Continuum Equivalent parameters:'));
+			disp(sprintf('   - general parameters'));
+			fielddisplay(obj,'water_compressibility','compressibility of water [Pa^-1]');
+			fielddisplay(obj,'isefficientlayer','do we use an efficient drainage system [1: true; 0: false]');
+			fielddisplay(obj,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]');
+			fielddisplay(obj,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+			fielddisplay(obj,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]');
+			fielddisplay(obj,'max_iter','maximum number of nonlinear iteration');
+			fielddisplay(obj,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer');
+			disp(sprintf('%55s  0: no limit',' '));
+			disp(sprintf('%55s  1: user defined: %s',' ','sedimentlimit'));
+			disp(sprintf('%55s  2: hydrostatic pressure',' '));
+			disp(sprintf('%55s  3: normal stress',' '));
+			if obj.sedimentlimit_flag==1,
+				fielddisplay(obj,'sedimentlimit','user defined upper limit for the inefficient layer [m]');
+	    end
+			fielddisplay(obj,'transfer_flag',['what kind of transfer method is applied between the layers']);
+			disp(sprintf('%55s  0: no transfer',' '));
+			disp(sprintf('%55s  1: constant leakage factor: %s',' ','leakage_factor'));
+			if obj.transfer_flag==1,
+				fielddisplay(obj,'leakage_factor','user defined leakage factor [m]');
+	    end
+			fielddisplay(obj,'basal_moulin_input','Figure out what it is');
+			disp(sprintf('   - for the sediment layer'));
+			fielddisplay(obj,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]');
+			fielddisplay(obj,'sediment_compressibility','sediment compressibility [Pa^-1]');
+			fielddisplay(obj,'sediment_porosity','sediment [dimensionless]');
+			fielddisplay(obj,'sediment_thickness','sediment thickness [m]');
+			fielddisplay(obj,'sediment_transmitivity','sediment transmitivity [m^2/s]');
+
+			if obj.isefficientlayer==1,
+				disp(sprintf('   - for the epl layer'));
+				fielddisplay(obj,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]');
+				fielddisplay(obj,'mask_eplactive_node','active (1) or not (0) EPL');
+				fielddisplay(obj,'epl_compressibility','epl compressibility [Pa^-1]');
+				fielddisplay(obj,'epl_porosity','epl [dimensionless]');
+				fielddisplay(obj,'epl_initial_thickness','epl initial thickness [m]');
+				fielddisplay(obj,'epl_max_thickness','epl maximal thickness [m]');
+				fielddisplay(obj,'epl_conductivity','epl conductivity [m^2/s]');
+	    end
+
+		end 
+		% }}}
+		% {{{ function marshall(obj,md,fid) 
+		function marshall(obj,md,fid) 
+			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','water_compressibility','format','Double');
+			WriteData(fid,'object',obj,'fieldname','isefficientlayer','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','rel_tol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','max_iter','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','sedimentlimit_flag','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','transfer_flag','format','Integer');
+			if obj.sedimentlimit_flag==1,
+				WriteData(fid,'object',obj,'fieldname','sedimentlimit','format','Double');
+	    end
+			if obj.transfer_flag==1,
+				WriteData(fid,'object',obj,'fieldname','leakage_factor','format','Double');
+	    end
+			WriteData(fid,'object',obj,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+
+			WriteData(fid,'object',obj,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','sediment_compressibility','format','Double');			
+			WriteData(fid,'object',obj,'fieldname','sediment_porosity','format','Double');			
+			WriteData(fid,'object',obj,'fieldname','sediment_thickness','format','Double');
+			WriteData(fid,'object',obj,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1');		
+
+			if obj.isefficientlayer==1,	
+				WriteData(fid,'object',obj,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);	
+				WriteData(fid,'object',obj,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','epl_compressibility','format','Double');			
+				WriteData(fid,'object',obj,'fieldname','epl_porosity','format','Double');			
+				WriteData(fid,'object',obj,'fieldname','epl_initial_thickness','format','Double');
+				WriteData(fid,'object',obj,'fieldname','epl_max_thickness','format','Double');
+				WriteData(fid,'object',obj,'fieldname','epl_conductivity','format','Double');
+			end
+		end 
+% }}}
+  end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologydc.py	(revision 18231)
@@ -0,0 +1,175 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class hydrologydc(object):
+    """
+    Hydrologydc class definition
+    
+    Usage:
+    hydrologydc=hydrologydc();
+    """
+
+    def __init__(self): # {{{
+		self.water_compressibility    = 0
+		self.isefficientlayer         = 0
+		self.penalty_factor           = 0
+		self.penalty_lock             = 0
+		self.rel_tol                  = 0
+		self.max_iter                 = 0
+		self.sedimentlimit_flag       = 0
+		self.sedimentlimit            = 0
+		self.transfer_flag            = 0
+		self.leakage_factor           = 0
+
+		self.spcsediment_head         = float('NaN')
+		self.sediment_transmitivity   = float('NaN')
+		self.sediment_compressibility = 0
+		self.sediment_porosity        = 0
+		self.sediment_thickness       = 0
+
+
+		self.spcepl_head              = float('NaN')
+		self.mask_eplactive_node      = float('NaN')
+		self.epl_compressibility      = 0
+		self.epl_porosity             = 0
+		self.epl_initial_thickness    = 0
+		self.epl_conductivity         = 0
+                
+		#set defaults
+		self.setdefaultparameters()
+                #}}}
+                
+	def __repr__(self): # {{{
+            string='   hydrology Dual Porous Continuum Equivalent parameters:'
+            string='   - general parameters'
+            string="%s\n%s"%(string,fielddisplay(self,'water_compressibility','compressibility of water [Pa^-1]'))
+            string="%s\n%s"%(string,fielddisplay(self,'isefficientlayer','do we use an efficient drainage system [1: true 0: false]'))
+            string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]'))
+            string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
+            string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]'))
+            string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration'))
+            string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer'))
+            string='%55s  0: no limit',' '
+            string='%55s  1: user defined: %s',' ','sedimentlimit'
+            string='%55s  2: hydrostatic pressure',' '
+            string='%55s  3: normal stress',' '
+
+            if self.sedimentlimit_flag==1:
+                string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]'))
+                string="%s\n%s"%(string,fielddisplay(self,'transfer_flag',['what kind of transfer method is applied between the layers']))
+                string='%55s  0: no transfer',' '
+                string='%55s  1: constant leakage factor: %s',' ','leakage_factor'
+                
+            if self.transfer_flag is 1:
+                string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]'))
+                string='   - for the sediment layer'
+                string="%s\n%s"%(string,fielddisplay(self,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]'))
+                string="%s\n%s"%(string,fielddisplay(self,'sediment_compressibility','sediment compressibility [Pa^-1]'))
+                string="%s\n%s"%(string,fielddisplay(self,'sediment_porosity','sediment [dimensionless]'))
+                string="%s\n%s"%(string,fielddisplay(self,'sediment_thickness','sediment thickness [m]'))
+                string="%s\n%s"%(string,fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]'))
+            
+            if self.isefficientlayer==1:
+                string='   - for the epl layer'
+                string="%s\n%s"%(string,fielddisplay(self,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]'))
+                string="%s\n%s"%(string,fielddisplay(self,'mask_eplactive_node','active (1) or not (0) EPL'))
+                string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]'))
+                string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]'))
+                string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))
+                string="%s\n%s"%(string,fielddisplay(self,'epl_conductivity','epl conductivity [m^2/s]'))
+            
+            #}}}
+    def setdefaultparameters(self): #{{{ 
+        
+        #Parameters from de Fleurian 2014
+        self.water_compressibility    = 5.04e-10
+        self.isefficientlayer         = 1
+        self.penalty_factor           = 3
+        self.rel_tol                  = 1.0e-06
+        self.max_iter                 = 100
+        self.sedimentlimit_flag       = 0
+        self.sedimentlimit            = 0
+        self.transfer_flag            = 0
+        self.leakage_factor           = 10.0
+        
+        self.sediment_compressibility = 1.0e-08
+        self.sediment_porosity        = 0.4
+        self.sediment_thickness       = 20.0
+        self.sediment_transmitivity   = 8.0e-04
+        
+        self.epl_compressibility      = 1.0e-08
+        self.epl_porosity             = 0.4
+        self.epl_initial_thickness    = 1.0
+        self.epl_conductivity         = 8.0e-02
+        
+        return self
+    # }}}
+    
+    def checkconsistency(self,md,solution,analyses): #{{{ 
+        
+        #Early return
+        if HydrologyDCInefficientAnalysisEnum() not in analyses:
+            return md
+
+        md = checkfield(md,'fieldname','hydrology.water_compressibility','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.isefficientlayer','numel',[1],'values',[0 1])
+        md = checkfield(md,'fieldname','hydrology.penalty_factor','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.rel_tol','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3])
+        md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0 1])
+        
+        if self.sedimentlimit_flag==1:
+            md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0,'numel',1)
+    
+        if self.transfer_flag==1:
+            md = checkfield(md,'fieldname','hydrology.leakage_factor','>',0,'numel',1)
+            
+        md = checkfield(md,'fieldname','hydrology.spcsediment_head','forcing',1)
+        md = checkfield(md,'fieldname','hydrology.sediment_compressibility','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0,'numel',1)
+        md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices 1])
+        if self.isefficientlayer==1:
+            md = checkfield(md,'fieldname','hydrology.spcepl_head','forcing',1)
+            md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices 1],'values',[0 1])
+            md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0,'numel',1)
+            md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0,'numel',1)
+            md = checkfield(md,'fieldname','hydrology.epl_initial_thickness','>',0,'numel',1)
+            md = checkfield(md,'fieldname','hydrology.epl_conductivity','>',0,'numel',1)
+
+        # }}}
+    def marshall(self,md,fid): #{{{ 
+        WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer')
+        WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double')
+        WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean')
+        WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+        WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+        WriteData(fid,'object',self,'fieldname','rel_tol','format','Double')
+        WriteData(fid,'object',self,'fieldname','max_iter','format','Integer')
+        WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
+        WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer')
+
+        if self.sedimentlimit_flag==1:
+            WriteData(fid,'object',self,'fieldname','sedimentlimit','format','Double')
+
+        if self.transfer_flag==1:
+            WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double')
+
+        WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+        WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double')
+        WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double')			
+        WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double')
+        WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1)		
+
+        if self.isefficientlayer==1:	
+            WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)	
+            WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1)
+            WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double')			
+            WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double')			
+            WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double')
+            WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double')
+# }}}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.m	(revision 18231)
@@ -0,0 +1,61 @@
+%HYDROLOGYSHREVE class definition
+%
+%   Usage:
+%      hydrologyshreve=hydrologyshreve();
+
+classdef hydrologyshreve
+	properties (SetAccess=public) 
+		spcwatercolumn = NaN;
+		stabilization  = 0;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- Hydrology -->');
+            
+            % Convergence criteria            
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Hydrologyshreve solution parameters">','<section name="hydrologyshreve" />');                    
+            
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcwatercolumn" type="',      class(obj.spcwatercolumn),'" default="',        convert2str(obj.spcwatercolumn),'">',	'     <section name="hydrologyshreve" />','     <help> water thickness constraints (NaN means no constraint) [m] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="',         class(obj.stabilization),'" default="',           convert2str(obj.stabilization),'">',	'     <section name="hydrologyshreve" />','     <help> artificial diffusivity (default is 1). can be more than 1 to increase diffusivity. </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = hydrologyshreve(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(obj,varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
+			obj.stabilization=1;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(HydrologyShreveAnalysisEnum(),analyses)
+				return;
+			end
+
+			md = checkfield(md,'fieldname','hydrology.spcwatercolumn','forcing',1);
+			md = checkfield(md,'fieldname','hydrology.stabilization','>=',0);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   hydrologyshreve solution parameters:'));
+			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
+		end % }}}
+	end
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/hydrologyshreve.py	(revision 18231)
@@ -0,0 +1,51 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class hydrologyshreve(object):
+	"""
+	HYDROLOGYSHREVE class definition
+
+	   Usage:
+	      hydrologyshreve=hydrologyshreve();
+	"""
+
+	def __init__(self): # {{{
+		self.spcwatercolumn = float('NaN')
+		self.stabilization  = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   hydrologyshreve solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
+		self.stabilization=1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		#Early return
+		if HydrologyShreveAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','hydrology.spcwatercolumn','forcing',1)
+		md = checkfield(md,'fieldname','hydrology.stabilization','>=',0)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.m	(revision 18231)
@@ -0,0 +1,73 @@
+%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,'fieldname',['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 scalartype=typetoscalar(obj) % {{{
+			if strcmpi(obj.type,'scalar'),
+				scalartype=0;
+			elseif strcmpi(obj.type,'vertex'),
+				scalartype=1;
+			elseif strcmpi(obj.type,'matrix'),
+				scalartype=1;
+			else error([obj.type ' not supported yet!']);
+			end
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/independent.py	(revision 18231)
@@ -0,0 +1,70 @@
+import numpy
+from pairoptions import pairoptions
+from fielddisplay import fielddisplay
+import MatlabFuncs as m
+from EnumDefinitions 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,'fieldname',"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/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.m	(revision 18231)
@@ -0,0 +1,140 @@
+%INITIALIZATION class definition
+%
+%   Usage:
+%      initialization=initialization();
+
+classdef initialization
+	properties (SetAccess=public) 
+		vx            = NaN;
+		vy            = NaN;
+		vz            = NaN;
+		vel           = NaN;
+		pressure      = NaN;
+		temperature   = NaN;
+		waterfraction = NaN;
+		sediment_head = NaN;
+		epl_head      = NaN;
+		epl_thickness = NaN;
+		watercolumn   = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- initialization -->');
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Initial field values">','<section name="initialization" />');                    
+            
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vx" type="',class(obj.vx),'" default="',obj.vx,'">','     <section name="initialization" />','     <help> x component of velocity [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vy" type="',class(obj.vy),'" default="',obj.vy,'">','     <section name="initialization" />','     <help> y component of velocity [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vz" type="',class(obj.vz),'" default="',obj.vz,'">','     <section name="initialization" />','     <help> z component of velocity [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vel" type="',class(obj.vel),'" default="',obj.vel,'">','     <section name="initialization" />','     <help> velocity norm [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="pressure" type="',class(obj.pressure),'" default="',obj.pressure,'">','     <section name="initialization" />','     <help> pressure field [Pa] </help>','</parameter>');
+        	 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperature" type="',class(obj.temperature),'" default="',obj.temperature,'">','     <section name="initialization" />','     <help> fraction of water in the ice </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="waterfraction" type="',class(obj.waterfraction),'" default="',obj.waterfraction,'">','     <section name="initialization" />','     <help> ice thickness [m] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="sediment_head" type="',class(obj.sediment_head),'" default="',obj.sediment_head,'">','     <section name="initialization" />','     <help> sediment water head of subglacial system [m] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="epl_head" type="',class(obj.epl_head),'" default="',obj.epl_head,'">','     <section name="initialization" />','     <help> epl water head of subglacial system [m] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="watercolumn" type="',class(obj.watercolumn),'" default="',obj.watercolumn,'">','     <section name="initialization" />','     <help> thickness of subglacial water [m] </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        end % }}}
+		function obj = initialization(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			if ismember(StressbalanceAnalysisEnum(),analyses)
+				if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
+					md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses) & solution==BalancethicknessSolutionEnum,
+				md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				%Triangle with zero velocity
+				if any(sum(abs(md.initialization.vx(md.mesh.elements)),2)==0 & sum(abs(md.initialization.vy(md.mesh.elements)),2)==0)
+					md = checkmessage(md,'at least one triangle has all its vertices with a zero velocity');
+				end
+			end
+			if ismember(ThermalAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				if dimension(md.mesh)==3
+					md = checkfield(md,'fieldname','initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+				md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy)
+				md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(HydrologyShreveAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologyshreve'),
+					md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(HydrologyDCInefficientAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologydc'),
+					md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(HydrologyDCEfficientAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologydc'),
+					if md.hydrology.isefficientlayer==1,
+						md = checkfield(md,'fieldname', ...
+														'initialization.epl_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
+						md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					end
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   initial field values:'));
+
+			fielddisplay(obj,'vx','x component of velocity [m/yr]');
+			fielddisplay(obj,'vy','y component of velocity [m/yr]');
+			fielddisplay(obj,'vz','z component of velocity [m/yr]');
+			fielddisplay(obj,'vel','velocity norm [m/yr]');
+			fielddisplay(obj,'pressure','pressure field [Pa]');
+			fielddisplay(obj,'temperature','temperature [K]');
+			fielddisplay(obj,'waterfraction','fraction of water in the ice');
+			fielddisplay(obj,'sediment_head','sediment water head of subglacial system [m]');
+			fielddisplay(obj,'epl_head','epl water head of subglacial system [m]');
+			fielddisplay(obj,'epl_thickness','epl layer thickness [m]');
+			fielddisplay(obj,'watercolumn','thickness of subglacial water [m]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'data',obj.vx,'format','DoubleMat','mattype',1,'enum',VxEnum,'scale',1./yts);
+			WriteData(fid,'data',obj.vy,'format','DoubleMat','mattype',1,'enum',VyEnum,'scale',1./yts);
+			WriteData(fid,'data',obj.vz,'format','DoubleMat','mattype',1,'enum',VzEnum,'scale',1./yts);
+			WriteData(fid,'data',obj.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum);
+			WriteData(fid,'data',obj.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum);
+			WriteData(fid,'data',obj.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
+			WriteData(fid,'data',obj.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum);
+			WriteData(fid,'data',obj.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum);
+			WriteData(fid,'data',obj.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum);
+			WriteData(fid,'data',obj.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
+
+			if md.thermal.isenthalpy,
+				tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
+				pos  = find(md.initialization.temperature>tpmp);
+				enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
+				enthalpy(pos) = md.materials.heatcapacity*tpmp(pos) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction(pos);
+				WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
+			end
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/initialization.py	(revision 18231)
@@ -0,0 +1,98 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class initialization(object):
+	"""
+	INITIALIZATION class definition
+
+	   Usage:
+	      initialization=initialization();
+	"""
+
+	def __init__(self): # {{{
+		
+		self.vx            = float('NaN')
+		self.vy            = float('NaN')
+		self.vz            = float('NaN')
+		self.vel           = float('NaN')
+		self.pressure      = float('NaN')
+		self.temperature   = float('NaN')
+		self.waterfraction = float('NaN')
+		self.watercolumn   = float('NaN')
+		self.sediment_head  = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   initial field values:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vz','z component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel','velocity norm [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature [K]'))
+		string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_head','sediment water head of subglacial system [m]'))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if StressbalanceAnalysisEnum() in analyses:
+			if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
+				md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+				md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			#Triangle with zero velocity
+			if numpy.any(numpy.logical_and(numpy.sum(numpy.abs(md.initialization.vx[md.mesh.elements-1]),axis=1)==0,\
+			                               numpy.sum(numpy.abs(md.initialization.vy[md.mesh.elements-1]),axis=1)==0)):
+				md.checkmessage("at least one triangle has all its vertices with a zero velocity")
+		if ThermalAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			if md.mesh.dimension()==3:
+				md = checkfield(md,'fieldname','initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices])
+		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy):
+			md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
+		if HydrologyShreveAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum(),'scale',1./yts)
+		WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum(),'scale',1./yts)
+		WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum(),'scale',1./yts)
+		WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
+		WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
+		WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
+		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
+		WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum())
+
+		if md.thermal.isenthalpy:
+			tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
+			pos  = numpy.nonzero(md.initialization.temperature > tpmp)[0]
+			enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
+			enthalpy[pos] = md.materials.heatcapacity*tpmp[pos].reshape(-1,1) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,1)
+			WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
+
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.m	(revision 18231)
@@ -0,0 +1,239 @@
+%INVERSION class definition
+%
+%   Usage:
+%      inversion=inversion();
+
+classdef inversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		incomplete_adjoint          = 0
+		control_parameters          = NaN
+		nsteps                      = 0
+		maxiter_per_step            = NaN
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		gradient_scaling            = NaN
+		cost_function_threshold     = 0
+		min_parameters              = NaN
+		max_parameters              = NaN
+		step_threshold              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+	end
+	methods
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '<!-- inversion -->\n');            
+
+			% inversion parameters
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="inversion parameters">','<section name="inversion" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscontrol" type="',class(obj.iscontrol),'" default="',convert2str(obj.iscontrol),'">','     <section name="inversion" />','     <help> is inversion activated? </help>','  </parameter>');
+
+			% incompleteadjoing drop-down (0 or 1)
+			fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="incomplete_adjoint" type="alternative" optional="false">','     <section name="inversion" />','     <help> 1: linear viscosity, 0: non-linear viscosity </help>');
+			fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="control_parameters" type="',class(obj.control_parameters),'" default="',convert2str(obj.control_parameters),'">','     <section name="inversion" />','     <help> ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''} </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="nsteps" type="',class(obj.nsteps),'" default="',convert2str(obj.nsteps),'">','     <section name="inversion" />','     <help> number of optimization searches </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions" type="',class(obj.cost_functions),'" default="',convert2str(obj.cost_functions),'">','     <section name="inversion" />','     <help> indicate the type of response for each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions_coefficients" type="',class(obj.cost_functions_coefficients),'" default="',convert2str(obj.cost_functions_coefficients),'">','     <section name="inversion" />','     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_function_threshold" type="',class(obj.cost_function_threshold),'" default="',convert2str(obj.cost_function_threshold),'">','     <section name="inversion" />','     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter_per_step" type="',class(obj.maxiter_per_step),'" default="',convert2str(obj.maxiter_per_step),'">','     <section name="inversion" />','     <help> maximum iterations during each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gradient_scaling" type="',class(obj.gradient_scaling),'" default="',convert2str(obj.gradient_scaling),'">','     <section name="inversion" />','     <help> scaling factor on gradient direction during optimization, for each optimization step </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="step_threshold" type="',class(obj.step_threshold),'" default="',convert2str(obj.step_threshold),'">','     <section name="inversion" />','     <help> decrease threshold for misfit, default is 30% </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_parameters" type="',class(obj.min_parameters),'" default="',convert2str(obj.min_parameters),'">','     <section name="inversion" />','     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="max_parameters" type="',class(obj.max_parameters),'" default="',convert2str(obj.max_parameters),'">','     <section name="inversion" />','     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vx_obs" type="',class(obj.vx_obs),'" default="',convert2str(obj.vx_obs),'">','     <section name="inversion" />','     <help> observed velocity x component [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vy_obs" type="',class(obj.vy_obs),'" default="',convert2str(obj.vy_obs),'">','     <section name="inversion" />','     <help> observed velocity y component [m/yr]  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vel_obs" type="',class(obj.vel_obs),'" default="',convert2str(obj.vel_obs),'">','     <section name="inversion" />','     <help> observed velocity magnitude [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="thickness_obs" type="',class(obj.thickness_obs),'" default="',convert2str(obj.thickness_obs),'">','     <section name="inversion" />','     <help> observed thickness [m]) </help>','  </parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Available cost functions">','<section name="inversion" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAbsVelMisfit" type="','string','" default="','101','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceRelVelMisfit" type="','string','" default="','102','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVelMisfit" type="','string','" default="','103','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVxVyMisfit" type="','string','" default="','104','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAverageVelMisfit" type="','string','" default="','105','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsMisfit" type="','string','" default="','106','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="DragCoefficientAbsGradient" type="','string','" default="','107','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="RheologyBbarAbsGradient" type="','string','" default="','108','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsGradient" type="','string','" default="','109','">','     <section name="inversion" />','     <help> </help>','  </parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+		end % }}}       
+		function obj = inversion(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(inversion(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%default is incomplete adjoint for now
+			obj.incomplete_adjoint=1;
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			obj.control_parameters={'FrictionCoefficient'};
+
+			%number of steps in the control methods
+			obj.nsteps=20;
+
+			%maximum number of iteration in the optimization algorithm for
+			%each step
+			obj.maxiter_per_step=20*ones(obj.nsteps,1);
+
+			%the inversed parameter is updated as follows:
+			%new_par=old_par + gradient_scaling(n)*C*gradient with C in [0 1];
+			%usually the gradient_scaling must be of the order of magnitude of the 
+			%inversed parameter (10^8 for B, 50 for drag) and can be decreased
+			%after the first iterations
+			obj.gradient_scaling=50*ones(obj.nsteps,1);
+
+			%several responses can be used:
+			obj.cost_functions=101;
+
+			%step_threshold is used to speed up control method. When
+			%misfit(1)/misfit(0) < obj.step_threshold, we go directly to
+			%the next step
+			obj.step_threshold=.7*ones(obj.nsteps,1); %30 per cent decrement.
+
+			%cost_function_threshold is a criteria to stop the control methods.
+			%if J[n]-J[n-1]/J[n] < criteria, the control run stops
+			%NaN if not applied
+			obj.cost_function_threshold=NaN; %not activated
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~obj.iscontrol, return; end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessNux' 'BalancethicknessNuy' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.nsteps','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
+			md = checkfield(md,'fieldname','inversion.step_threshold','size',[md.inversion.nsteps 1]);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.gradient_scaling','size',[md.inversion.nsteps num_controls]);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			%Only SSA, HO and FS are supported right now
+			if solution==StressbalanceSolutionEnum()
+				if ~(md.flowequation.isSSA || md.flowequation.isHO || md.flowequation.isFS),
+					md = checkmessage(md,['inversion can only be performed for SSA, HO or FS ice flow models']);
+				end
+			end
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   inversion parameters:'));
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'nsteps','number of optimization searches');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(obj,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied');
+			fielddisplay(obj,'maxiter_per_step','maximum iterations during each optimization step');
+			fielddisplay(obj,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step');
+			fielddisplay(obj,'step_threshold','decrease threshold for misfit, default is 30%');
+			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',InversionTypeEnum(),'data',0,'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','incomplete_adjoint','format','Boolean');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'fieldname','nsteps','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','maxiter_per_step','format','IntMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','gradient_scaling','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','cost_function_threshold','format','Double');
+			WriteData(fid,'object',obj,'fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','step_threshold','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','thickness_obs','format','DoubleMat','mattype',1);
+
+			%process control parameters
+			num_control_parameters=numel(obj.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(obj.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(obj.cost_functions,2);
+			data=obj.cost_functions;
+			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversion.py	(revision 18231)
@@ -0,0 +1,197 @@
+import numpy
+import copy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class inversion(object):
+	"""
+	INVERSION class definition
+
+	   Usage:
+	      inversion=inversion()
+	"""
+
+	def __init__(self): # {{{
+		self.iscontrol                   = 0
+		self.incomplete_adjoint          = 0
+		self.control_parameters          = float('NaN')
+		self.nsteps                      = 0
+		self.maxiter_per_step            = float('NaN')
+		self.cost_functions              = float('NaN')
+		self.cost_functions_coefficients = float('NaN')
+		self.gradient_scaling            = float('NaN')
+		self.cost_function_threshold     = 0
+		self.min_parameters              = float('NaN')
+		self.max_parameters              = float('NaN')
+		self.step_threshold              = float('NaN')
+		self.vx_obs                      = float('NaN')
+		self.vy_obs                      = float('NaN')
+		self.vz_obs                      = float('NaN')
+		self.vel_obs                     = float('NaN')
+		self.thickness_obs               = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   inversion parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'iscontrol','is inversion activated?'))
+		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
+		string="%s\n%s"%(string,fielddisplay(self,'nsteps','number of optimization searches'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter_per_step','maximum iterations during each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'step_threshold','decrease threshold for misfit, default is 30%'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
+		string="%s\n%s"%(string,'Available cost functions:')
+		string="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit')
+		string="%s\n%s"%(string,'   102: SurfaceRelVelMisfit')
+		string="%s\n%s"%(string,'   103: SurfaceLogVelMisfit')
+		string="%s\n%s"%(string,'   104: SurfaceLogVxVyMisfit')
+		string="%s\n%s"%(string,'   105: SurfaceAverageVelMisfit')
+		string="%s\n%s"%(string,'   201: ThicknessAbsMisfit')
+		string="%s\n%s"%(string,'   501: DragCoefficientAbsGradient')
+		string="%s\n%s"%(string,'   502: RheologyBbarAbsGradient')
+		string="%s\n%s"%(string,'   503: ThicknessAbsGradient')
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#default is incomplete adjoint for now
+		self.incomplete_adjoint=1
+
+		#parameter to be inferred by control methods (only
+		#drag and B are supported yet)
+		self.control_parameters='FrictionCoefficient'
+
+		#number of steps in the control methods
+		self.nsteps=20
+
+		#maximum number of iteration in the optimization algorithm for
+		#each step
+		self.maxiter_per_step=20*numpy.ones(self.nsteps)
+
+		#the inversed parameter is updated as follows:
+		#new_par=old_par + gradient_scaling(n)*C*gradient with C in [0 1];
+		#usually the gradient_scaling must be of the order of magnitude of the 
+		#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,1))
+
+		#several responses can be used:
+		self.cost_functions=101
+
+		#step_threshold is used to speed up control method. When
+		#misfit(1)/misfit(0) < self.step_threshold, we go directly to
+		#the next step
+		self.step_threshold=.7*numpy.ones(self.nsteps) #30 per cent decrement
+
+		#cost_function_threshold is a criteria to stop the control methods.
+		#if J[n]-J[n-1]/J[n] < criteria, the control run stops
+		#NaN if not applied
+		self.cost_function_threshold=float('NaN')    #not activated 
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not self.iscontrol:
+			return md
+
+		num_controls=numpy.size(md.inversion.control_parameters)
+		num_costfunc=numpy.size(md.inversion.cost_functions)
+
+		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
+		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
+		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','DamageDbar','Vx','Vy'])
+		md = checkfield(md,'fieldname','inversion.nsteps','numel',[1],'>=',0)
+		md = checkfield(md,'fieldname','inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
+		md = checkfield(md,'fieldname','inversion.step_threshold','size',[md.inversion.nsteps])
+		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
+		md = checkfield(md,'fieldname','inversion.gradient_scaling','size',[md.inversion.nsteps,num_controls])
+		md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
+		md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
+
+		#Only SSA, HO and FS are supported right now
+		if solution==StressbalanceSolutionEnum():
+			if not (md.flowequation.isSSA or md.flowequation.isHO or md.flowequation.isFS):
+				md.checkmessage("'inversion can only be performed for SSA, HO or FS ice flow models");
+
+		if solution==BalancethicknessSolutionEnum():
+			md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1)
+		else:
+			md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1)
+			md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',InversionTypeEnum(),'data',0,'format','Integer')
+		WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean')
+		if not self.iscontrol:
+			return
+		WriteData(fid,'object',self,'fieldname','nsteps','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_function_threshold','format','Double')
+		WriteData(fid,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
+
+		#process 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=numpy.size(self.cost_functions)
+		data=copy.deepcopy(self.cost_functions)
+		pos=[i for i,x in enumerate(self.cost_functions) if x==101];
+		for i in pos: data[i]=SurfaceAbsVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==102];
+		for i in pos: data[i]=SurfaceRelVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==103];
+		for i in pos: data[i]=SurfaceLogVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==104];
+		for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
+		pos=[i for i,x in enumerate(self.cost_functions) if x==105];
+		for i in pos: data[i]=SurfaceAverageVelMisfitEnum()    
+		pos=[i for i,x in enumerate(self.cost_functions) if x==201];
+		for i in pos: data[i]=ThicknessAbsMisfitEnum()         
+		pos=[i for i,x in enumerate(self.cost_functions) if x==501];
+		for i in pos: data[i]=DragCoefficientAbsGradientEnum() 
+		pos=[i for i,x in enumerate(self.cost_functions) if x==502];
+		for i in pos: data[i]=RheologyBbarAbsGradientEnum()    
+		pos=[i for i,x in enumerate(self.cost_functions) if x==503];
+		for i in pos: data[i]=ThicknessAbsGradientEnum()       
+		pos=[i for i,x in enumerate(self.cost_functions) if x==504];
+		for i in pos: data[i]=ThicknessAlongGradientEnum()     
+		pos=[i for i,x in enumerate(self.cost_functions) if x==505];
+		for i in pos: data[i]=ThicknessAcrossGradientEnum()    
+		WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversionvalidation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversionvalidation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/inversionvalidation.m	(revision 18231)
@@ -0,0 +1,146 @@
+%INVERSIONVALIDATION class definition
+%
+%   Usage:
+%      inversionvalidation=inversionvalidation();
+
+classdef inversionvalidation
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		incomplete_adjoint          = 0
+		control_parameters          = NaN
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		min_parameters              = NaN
+		max_parameters              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+	end
+	methods
+		function obj = inversionvalidation(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(inversionvalidation(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%default is incomplete adjoint for now
+			self.incomplete_adjoint=1;
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			self.control_parameters={'FrictionCoefficient'};
+
+			%several responses can be used:
+			self.cost_functions=101;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~obj.iscontrol, return; end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
+					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   inversionvalidation parameters:'));
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'enum',InversionTypeEnum(),'data',3,'format','Integer');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+				mattype=2; 
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+
+			%process control parameters
+			num_control_parameters=numel(obj.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(obj.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(obj.cost_functions,2);
+			data=obj.cost_functions;
+			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.m	(revision 18231)
@@ -0,0 +1,97 @@
+%LINEAR BASAL FORCINGS class definition
+%
+%   Usage:
+%      linearbasalforcings=linearbasalforcings();
+
+classdef linearbasalforcings
+	properties (SetAccess=public) 
+		groundedice_melting_rate  = NaN;
+		deepwater_melting_rate    = NaN;
+		deepwater_elevation       = NaN;
+		upperwater_elevation      = NaN;
+		geothermalflux            = NaN;
+	end
+	methods
+     function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- basalforcings -->');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
+             
+        end % }}}
+		function obj = linearbasalforcings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(linearbasalforcings(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.groundedice_melting_rate),
+				self.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.groundedice_melting_rate specified: values set as zero');
+			end
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%default values for melting parameterization
+			obj.deepwater_melting_rate = 50;
+			obj.deepwater_elevation    = -800;
+			obj.upperwater_elevation   = -400;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+			end
+			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   basal forcings parameters:'));
+
+			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'deepwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]');
+			fielddisplay(obj,'deepwater_elevation','elevation of ocean deepwater [m]');
+			fielddisplay(obj,'upperwater_elevation','elevation of ocean upperwater [m]');
+			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+			floatingice_melting_rate(find(md.geometry.base<=md.basalforcings.deepwater_elevation))=md.basalforcings.deepwater_melting_rate;
+			pos=find(md.geometry.base>md.basalforcings.deepwater_elevation & md.geometry.base<md.basalforcings.upperwater_elevation);
+			floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate*(md.geometry.base(pos)-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation);
+			WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
+			WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','deepwater_melting_rate','format','Double','enum',BasalforcingsDeepwaterMeltingRateEnum(),'scale',1./yts)
+			WriteData(fid,'object',obj,'fieldname','deepwater_elevation','format','Double','enum',BasalforcingsDeepwaterElevationEnum())
+			WriteData(fid,'object',obj,'fieldname','upperwater_elevation','format','Double','enum',BasalforcingsUpperwaterElevationEnum())
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/linearbasalforcings.py	(revision 18231)
@@ -0,0 +1,108 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import numpy
+
+class linearbasalforcings(object):
+	"""
+	LINEAR BASAL FORCINGS class definition
+
+	   Usage:
+	      basalforcings=linearbasalforcings();
+	"""
+
+	def __init__(self,*args): # {{{
+
+		if not len(args):
+			print 'empty init'
+			self.groundedice_melting_rate  = float('NaN')
+			self.deepwater_melting_rate    = 0.
+			self.deepwater_elevation       = 0.
+			self.upperwater_elevation      = 0.
+			self.geothermalflux            = float('NaN')
+
+			#set defaults
+			self.setdefaultparameters()
+		elif len(args)==1 and args[0].__module__=='basalforcings':
+			print 'converting basalforings to linearbasalforcings'
+			inv=args[0]
+			self.groundedice_melting_rate  = inv.groundedice_melting_rate
+			self.geothermalflux            = inv.geothermalflux
+			self.deepwater_melting_rate    = 0.
+			self.deepwater_elevation       = 0.
+			self.upperwater_elevation      = 0.
+
+			#set defaults
+			self.setdefaultparameters()
+		else:
+			raise Exception('constructor not supported')
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   linear basal forcings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"deepwater_melting_rate","basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"deepwater_elevation","elevation of ocean deepwater [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"upperwater_elevation","elevation of ocean upper water [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
+		return string
+		#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
+			self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
+
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+		self.deepwater_melting_rate   = 50.0
+		self.deepwater_elevation      = -800.0
+		self.upperwater_elevation     = -400.0
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+
+		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
+		pos=numpy.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
+		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate
+		pos=numpy.nonzero(numpy.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
+		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate*(md.geometry.base[pos]-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation)
+
+		WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','enum',BasalforcingsDeepwaterMeltingRateEnum(),'format','Double','scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','deepwater_elevation','enum',BasalforcingsDeepwaterElevationEnum(),'format','Double')
+		WriteData(fid,'object',self,'fieldname','upperwater_elevation','enum',BasalforcingsUpperwaterElevationEnum(),'format','Double')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.m	(revision 18231)
@@ -0,0 +1,176 @@
+%M1QN3INVERSION class definition
+%
+%   Usage:
+%      m1qn3inversion=m1qn3inversion();
+
+classdef m1qn3inversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		incomplete_adjoint          = 0
+		control_parameters          = NaN
+		maxsteps                    = 0
+		maxiter                     = 0
+		dxmin                       = 0;
+		gttol                       = 0;
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		min_parameters              = NaN
+		max_parameters              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+
+	end
+	methods
+		function obj = m1qn3inversion(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(m1qn3inversion(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%default is incomplete adjoint for now
+			self.incomplete_adjoint=1;
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			self.control_parameters={'FrictionCoefficient'};
+
+			%number of iterations
+			self.maxsteps=20;
+			self.maxiter=40;
+
+			%several responses can be used:
+			self.cost_functions=101;
+
+			%m1qn3 parameters
+			self.dxmin  = 0.1;
+			self.gttol = 1e-4;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~obj.iscontrol, return; end
+
+			if ~IssmConfig('_HAVE_M1QN3_'),
+				md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with M1QN3']);
+			end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
+			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
+					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   m1qn3inversion parameters:'));
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(obj,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(obj,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
+			fielddisplay(obj,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'enum',InversionTypeEnum(),'data',2,'format','Integer');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','dxmin','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','gttol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+				mattype=2;
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+
+			%process control parameters
+			num_control_parameters=numel(obj.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(obj.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(obj.cost_functions,2);
+			data=obj.cost_functions;
+			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/m1qn3inversion.py	(revision 18231)
@@ -0,0 +1,193 @@
+import numpy
+import copy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class m1qn3inversion(object):
+	'''
+	M1QN3 class definition
+
+   Usage:
+      m1qn3inversion=m1qn3inversion()
+	'''
+
+	def __init__(self,*args): # {{{
+
+		if not len(args):
+			print 'empty init'
+			self.iscontrol                   = 0
+			self.incomplete_adjoint          = 0
+			self.control_parameters          = float('NaN')
+			self.maxsteps                    = 0
+			self.maxiter                     = 0
+			self.dxmin                       = 0.
+			self.gttol                       = 0.
+			self.cost_functions              = float('NaN')
+			self.cost_functions_coefficients = float('NaN')
+			self.min_parameters              = float('NaN')
+			self.max_parameters              = float('NaN')
+			self.vx_obs                      = float('NaN')
+			self.vy_obs                      = float('NaN')
+			self.vz_obs                      = float('NaN')
+			self.vel_obs                     = float('NaN')
+			self.thickness_obs               = float('NaN')
+
+			#set defaults
+			self.setdefaultparameters()
+		elif len(args)==1 and args[0].__module__=='inversion':
+			print 'converting inversion to m1qn3inversion'
+			inv=args[0]
+			self.iscontrol                   = inv.iscontrol
+			self.incomplete_adjoint          = inv.incomplete_adjoint
+			self.control_parameters          = inv.control_parameters
+			self.maxsteps                    = inv.nsteps
+			self.cost_functions              = inv.cost_functions
+			self.cost_functions_coefficients = inv.cost_functions_coefficients
+			self.min_parameters              = inv.min_parameters
+			self.max_parameters              = inv.max_parameters
+			self.vx_obs                      = inv.vx_obs
+			self.vy_obs                      = inv.vy_obs
+			self.vz_obs                      = inv.vz_obs
+			self.vel_obs                     = inv.vel_obs
+			self.thickness_obs               = inv.thickness_obs
+		else:
+			raise Exception('constructor not supported')
+		#}}}
+	def __repr__(self): # {{{
+		string='   m1qn3inversion parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'iscontrol','is inversion activated?'))
+		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','ex: [''FrictionCoefficient''], or [''MaterialsRheologyBbar'']'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)'))
+		string="%s\n%s"%(string,fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical'))
+		string="%s\n%s"%(string,fielddisplay(self,'gttol','||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
+		string="%s\n%s"%(string,'Available cost functions:')
+		string="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit')
+		string="%s\n%s"%(string,'   102: SurfaceRelVelMisfit')
+		string="%s\n%s"%(string,'   103: SurfaceLogVelMisfit')
+		string="%s\n%s"%(string,'   104: SurfaceLogVxVyMisfit')
+		string="%s\n%s"%(string,'   105: SurfaceAverageVelMisfit')
+		string="%s\n%s"%(string,'   201: ThicknessAbsMisfit')
+		string="%s\n%s"%(string,'   501: DragCoefficientAbsGradient')
+		string="%s\n%s"%(string,'   502: RheologyBbarAbsGradient')
+		string="%s\n%s"%(string,'   503: ThicknessAbsGradient')
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#default is incomplete adjoint for now
+		self.incomplete_adjoint=1
+
+		#parameter to be inferred by control methods (only
+		#drag and B are supported yet)
+		self.control_parameters='FrictionCoefficient'
+
+		#number of iterations
+		self.maxsteps=20
+		self.maxiter=40
+
+		#several responses can be used:
+		self.cost_functions=101
+
+		#m1qn3 parameters
+		self.dxmin  = 0.1
+		self.gttol = 1e-4
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not self.iscontrol:
+			return md
+
+		num_controls=numpy.size(md.inversion.control_parameters)
+		num_costfunc=numpy.size(md.inversion.cost_functions)
+
+		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
+		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
+		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','DamageDbar','Vx','Vy','Thickness'])
+		md = checkfield(md,'fieldname','inversion.maxsteps','numel',[1],'>=',0)
+		md = checkfield(md,'fieldname','inversion.maxiter','numel',[1],'>=',0)
+		md = checkfield(md,'fieldname','inversion.dxmin','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','inversion.gttol','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
+		md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
+		md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
+
+		if solution==BalancethicknessSolutionEnum():
+			md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1)
+		else:
+			md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1)
+			md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
+		WriteData(fid,'enum',InversionTypeEnum(),'data',2,'format','Integer')
+		if not self.iscontrol:
+			return
+		WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
+		WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
+		WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'class','inversion','fieldname','dxmin','format','Double')
+		WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double')
+		WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
+
+		#process 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=numpy.size(self.cost_functions)
+		data=copy.deepcopy(self.cost_functions)
+		pos=[i for i,x in enumerate(self.cost_functions) if x==101];
+		for i in pos: data[i]=SurfaceAbsVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==102];
+		for i in pos: data[i]=SurfaceRelVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==103];
+		for i in pos: data[i]=SurfaceLogVelMisfitEnum()        
+		pos=[i for i,x in enumerate(self.cost_functions) if x==104];
+		for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
+		pos=[i for i,x in enumerate(self.cost_functions) if x==105];
+		for i in pos: data[i]=SurfaceAverageVelMisfitEnum()    
+		pos=[i for i,x in enumerate(self.cost_functions) if x==201];
+		for i in pos: data[i]=ThicknessAbsMisfitEnum()         
+		pos=[i for i,x in enumerate(self.cost_functions) if x==501];
+		for i in pos: data[i]=DragCoefficientAbsGradientEnum() 
+		pos=[i for i,x in enumerate(self.cost_functions) if x==502];
+		for i in pos: data[i]=RheologyBbarAbsGradientEnum()    
+		pos=[i for i,x in enumerate(self.cost_functions) if x==503];
+		for i in pos: data[i]=ThicknessAbsGradientEnum()       
+		pos=[i for i,x in enumerate(self.cost_functions) if x==504];
+		for i in pos: data[i]=ThicknessAlongGradientEnum()     
+		pos=[i for i,x in enumerate(self.cost_functions) if x==505];
+		for i in pos: data[i]=ThicknessAcrossGradientEnum()    
+		WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.m	(revision 18231)
@@ -0,0 +1,72 @@
+%MASK class definition
+%
+%   Usage:
+%      mask=mask();
+
+classdef mask
+	properties (SetAccess=public) 
+		groundedice_levelset = NaN;
+		ice_levelset         = NaN;
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. Update old properties here
+
+			%2014 February 5th
+			if numel(obj.ice_levelset)>1 & all(obj.ice_levelset>=0),
+				disp('WARNING: md.mask.ice_levelset>=0, you probably need to change the sign of this levelset');
+			end
+
+		end% }}}
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- mask -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="groundedice_levelset" type="',class(obj.groundedice_levelset),'" default="',obj.groundedice_levelset,'">','     <section name="mask" />','     <help> is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if &amp;lt; 0 </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="ice_levelset" type="',class(obj.ice_levelset),'" default="',obj.ice_levelset,'">','     <section name="mask" />','     <help> presence of ice if > 0, icefront position if = 0, no ice if &amp;lt; 0 </help>','</parameter>');
+		end % }}}
+		function obj = mask(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices 1]);
+			isice=(md.mask.ice_levelset<=0);
+			if sum(isice)==0,
+				warning('no ice present in the domain');
+			end
+			if max(md.mask.ice_levelset)<0,
+				warning('no ice front provided');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   masks:'));
+
+			fielddisplay(obj,'groundedice_levelset','is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0');
+			fielddisplay(obj,'ice_levelset','presence of ice if < 0, icefront position if = 0, no ice if > 0');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','ice_levelset','format','DoubleMat','mattype',1);
+
+			% get mask of vertices of elements with ice
+			isice=md.mask.ice_levelset<=0.;
+			vlist = zeros(md.mesh.numberofvertices,1);
+			pos=find(sum(isice(md.mesh.elements),2)>0);
+			vlist(md.mesh.elements(pos,:))=1;
+			WriteData(fid,'data',vlist,'enum',IceMaskNodeActivationEnum(),'format','DoubleMat','mattype',1);
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mask.py	(revision 18231)
@@ -0,0 +1,52 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class mask(object):
+	"""
+	MASK class definition
+
+	   Usage:
+	      mask=mask();
+	"""
+
+	def __init__(self): # {{{
+		self.ice_levelset         = float('NaN')
+		self.groundedice_levelset = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   masks:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_levelset","is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0"))
+		string="%s\n%s"%(string,fielddisplay(self,"ice_levelset","presence of ice if < 0, icefront position if = 0, no ice if > 0"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
+		isice=numpy.array(md.mask.ice_levelset<=0,int)
+		if numpy.sum(isice)==0:
+			raise TypeError("no ice present in the domain")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1)
+
+		# get mask of vertices of elements with ice
+		isice=numpy.array(md.mask.ice_levelset<0.,int)
+		vlist = numpy.zeros((md.mesh.numberofvertices,1), dtype=int)
+		pos=numpy.nonzero(numpy.sum(isice[md.mesh.elements-1],axis=1))[0]
+		vlist[md.mesh.elements[pos,:]-1]=1
+		WriteData(fid,'data',vlist,'enum',IceMaskNodeActivationEnum(),'format','DoubleMat','mattype',1);
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.m	(revision 18231)
@@ -0,0 +1,64 @@
+%MASSFLUXATGATE class definition
+%
+%   Usage:
+%      massfluxatgate=massfluxatgate();
+%      massfluxatgate=massfluxatgate('GateName','PathToExpFile');
+
+classdef massfluxatgate
+	properties (SetAccess=public)  
+		%massfluxatgate 
+		name                = '';
+		profilename            = ''; 
+	end
+	properties (SetAccess=private)  
+		segments            = NaN;
+	end
+	methods
+		function obj = massfluxatgate(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj.name=varargin{1};
+				case 2
+					obj.name=varargin{1};
+					obj.profilename=varargin{2};
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			
+			if ~ischar(obj.name),
+				error('massfluxatgate error message: ''name'' field should be a string!');
+			end
+			if ~ischar(obj.profilename),
+				error('massfluxatgate error message: ''profilename'' field should be a string!');
+			end
+
+			%check the profilename points to a file!: 
+			if exist(obj.profilename,'file')~=2,
+				error('massfluxatgate error message: file name for profile corresponding to gate does not point to a legitimate file on disk!');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Massfluxatgate:\n'));
+
+			fielddisplay(obj,'name','identifier for this massfluxatgate response');
+			fielddisplay(obj,'profilename','name of file (shapefile or argus file) defining a profile (or gate)');
+			
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+		%before marshalling, we need to create the segments out of the profilename: 
+		obj.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,obj.profilename);
+
+		%ok, marshall name and segments: 
+		WriteData(fid,'object',obj,'fieldname','name','format','String');
+		WriteData(fid,'object',obj,'fieldname','segments','format','DoubleMat','mattype',1);
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/massfluxatgate.py	(revision 18231)
@@ -0,0 +1,55 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+from MeshProfileIntersection import MeshProfileIntersection
+import os
+
+class massfluxatgate(object):
+	"""
+	MASSFLUXATEGATE class definition
+
+	   Usage:
+		  massfluxatgate=massfluxatgate('GateName','PathToExpFile')
+	"""
+
+	def __init__(self,name,profilename): # {{{
+		self.name           = name
+		self.profilename    = profilename
+		self.segments       = float('NaN')
+
+		#}}}
+	def __repr__(self): # {{{
+
+		string="   Massfluxatgate:"
+		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response'))
+		string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		if  not isinstance(self.name, basestring):
+			raise RuntimeError("massfluxatgate error message: 'name' field should be a string!")
+			
+		if  not isinstance(self.profilename, basestring):
+			raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!") 
+		
+		#check the profilename points to a file!: 
+		if not os.path.isfile(self.profilename):
+			raise RuntimeError("massfluxatgate error message: file name for profile corresponding to gate does not point to a legitimate file on disk!")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		
+		#before marshalling, we need to create the segments out of the profilename: 
+		self.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,self.profilename)[0]
+
+		#ok, marshall name and segments: 
+		WriteData(fid,'object',self,'fieldname','name','format','String')
+		WriteData(fid,'object',self,'fieldname','segments','format','DoubleMat','mattype',1)
+
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.m	(revision 18231)
@@ -0,0 +1,172 @@
+%MASSTRANSPORT class definition
+%
+%   Usage:
+%      masstransport=masstransport();
+
+classdef masstransport
+	properties (SetAccess=public) 
+		 spcthickness           = NaN;
+		 calvingrate            = NaN;
+		 isfreesurface          = 0;
+		 min_thickness          = 0;
+		 hydrostatic_adjustment = 0;
+		 stabilization          = 0;
+		 vertex_pairing         = NaN;
+		 penalty_factor         = 0;
+		 requested_outputs      = {};
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of this class and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(obj)
+				disp('Recovering masstransport from older version');
+				objstruct = obj;
+				obj = structtoobj(masstransport(),objstruct);
+			end
+		end% }}}
+	end
+	methods
+         function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- masstransport -->\n');            
+                    
+            % Masstransport solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Masstransport solution parameters">','<section name="masstransport" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="spcthickness" type="',class(obj.spcthickness),'" default="',convert2str(obj.spcthickness),'">','     <section name="masstransport" />','     <help> thickness constraints (NaN means no constraint) [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="calvingrate" type="',class(obj.calvingrate),'" default="',convert2str(obj.calvingrate),'">','     <section name="masstransport" />','     <help> calving rate at given location [m/a] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isfreesurface" type="',class(obj.isfreesurface),'" default="',convert2str(obj.isfreesurface),'">','     <section name="masstransport" />','     <help> do we use free surfaces (FS only) are mass conservation </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_thickness" type="',class(obj.min_thickness),'" default="',convert2str(obj.min_thickness),'">','     <section name="masstransport" />','     <help> minimum ice thickness allowed [m] </help>','  </parameter>');
+            
+            % hydrostatic_adjustment drop-down (incremental or absolute )
+            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="hydrostatic_adjustment" type="alternative" optional ="false">','     <section name="masstransport" />','     <help> adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute''  </help>');
+            fprintf(fid,'%s\n','       <option value="Incremental" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="Absolute" type="string" default="false"> </option>','</parameter>');
+            
+            %stabilization drop-down (0, 1, 2, or 3)
+            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="stabilization" type="alternative" optional="false">','     <section name="masstransport" />','     <help> 0: no, 1:  artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin </help>');
+            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
+            fprintf(fid,'%s\n','       <option value="2" type="string" default="false"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="3" type="string" default="false"> </option>','</parameter>');
+
+            fprintf(fid,'%s\n%s\n','</frame>');    
+            
+            %Penalty options
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Penalty options">','<section name="masstransport" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertex_pairing" type="',class(obj.vertex_pairing),'" default="',convert2str(obj.vertex_pairing),'">','     <section name="masstransport" />','     <help> offset used by penalties: penalty = Kmax*10^offset </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_factor" type="',class(obj.penalty_factor),'" default="',convert2str(obj.penalty_factor),'">','     <section name="masstransport" />','     <help> pairs of vertices that are penalized </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="masstransport" />','     <help> additional outputs requested </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        
+        end % }}}
+		function obj = masstransport(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('masstransport');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			list = {'Thickness','Surface','Base'};
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
+			obj.stabilization=1;
+
+			%Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+
+			%Minimum ice thickness that can be used
+			obj.min_thickness=1;
+
+			%Hydrostatic adjustment
+			obj.hydrostatic_adjustment='Absolute';
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(MasstransportAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.ismasstransport==0), return; end
+
+			md = checkfield(md,'fieldname','masstransport.spcthickness','forcing',1);
+			if(ismember(LevelsetAnalysisEnum(), analyses) & md.transient.islevelset)
+				md = checkfield(md,'fieldname','masstransport.calvingrate','NaN',1,'size',[md.mesh.numberofvertices 1],'>=',0);
+			end
+
+			md = checkfield(md,'fieldname','masstransport.isfreesurface','values',[0 1]);
+			md = checkfield(md,'fieldname','masstransport.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
+			md = checkfield(md,'fieldname','masstransport.stabilization','values',[0 1 2 3]);
+			md = checkfield(md,'fieldname','masstransport.min_thickness','>',0);
+			md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Masstransport solution parameters:'));
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(obj,'calvingrate','calving rate at given location [m/a]');
+			fielddisplay(obj,'isfreesurface','do we use free surfaces (FS only) are mass conservation');
+			fielddisplay(obj,'min_thickness','minimum ice thickness allowed [m]');
+			fielddisplay(obj,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' ');
+			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin');
+
+			disp(sprintf('\n      %s','Penalty options:'));
+			fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
+			fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.*24.*3600.;
+
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','calvingrate','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','isfreesurface','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
+			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum());
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum,'format','StringArray');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/masstransport.py	(revision 18231)
@@ -0,0 +1,102 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class masstransport(object):
+	"""
+	MASSTRANSPORT class definition
+
+	   Usage:
+	      masstransport=masstransport();
+	"""
+
+	def __init__(self): # {{{
+		self.spcthickness           = float('NaN')
+		self.calvingrate            = float('NaN')
+		self.isfreesurface          = 0
+		self.min_thickness          = 0
+		self.hydrostatic_adjustment = 0
+		self.stabilization          = 0
+		self.vertex_pairing         = float('NaN')
+		self.penalty_factor         = 0
+		self.requested_outputs      = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   Masstransport solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'calvingrate','calving rate at given location [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'isfreesurface','do we use free surfaces (FS only) are mass conservation'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum ice thickness allowed [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+
+		return string
+		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		return ['Thickness','Surface','Base']
+
+	#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
+		self.stabilization=1
+
+		#Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+
+		#Minimum ice thickness that can be used
+		self.min_thickness=1
+
+		#Hydrostatic adjustment
+		self.hydrostatic_adjustment='Absolute'
+
+		#default output
+		self.requested_outputs=['default']
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (MasstransportAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
+			return md
+
+		md = checkfield(md,'fieldname','masstransport.spcthickness','forcing',1)
+		if LevelsetAnalysisEnum() in analyses and md.transient.islevelset:
+			md = checkfield(md,'fieldname','masstransport.calvingrate','NaN',1,'size',[md.mesh.numberofvertices],'>=',0)
+		md = checkfield(md,'fieldname','masstransport.isfreesurface','values',[0,1])
+		md = checkfield(md,'fieldname','masstransport.hydrostatic_adjustment','values',['Absolute','Incremental'])
+		md = checkfield(md,'fieldname','masstransport.stabilization','values',[0,1,2,3])
+		md = checkfield(md,'fieldname','masstransport.min_thickness','>',0)
+		md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.*24.*3600.
+
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','isfreesurface','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
+		WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum())
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.m	(revision 18231)
@@ -0,0 +1,197 @@
+%MATDAMAGEICE class definition
+%
+%   Usage:
+%      matdamageice=matdamageice();
+
+classdef matdamageice
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		temperateiceconductivity   = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_law = '';
+
+		%gia: 
+		lithosphere_shear_modulus  = 0.;
+		lithosphere_density        = 0.;
+		mantle_shear_modulus       = 0.;
+		mantle_density             = 0.;
+
+	end
+	methods
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '<!-- materials -->\n');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(obj.rho_ice),'" default="',convert2str(obj.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(obj.rho_water),'" default="',convert2str(obj.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(obj.rho_freshwater),'" default="',convert2str(obj.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(obj.mu_water),'" default="',convert2str(obj.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(obj.heatcapacity),'" default="',convert2str(obj.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(obj.latentheat),'" default="',convert2str(obj.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(obj.thermalconductivity),'" default="',convert2str(obj.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(obj.temperateiceconductivity),'" default="',convert2str(obj.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(obj.meltingpoint),'" default="',convert2str(obj.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(obj.beta),'" default="',convert2str(obj.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(obj.mixed_layer_capacity),'" default="',convert2str(obj.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(obj.thermal_exchange_velocity),'" default="',convert2str(obj.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(obj.rheology_B),'" default="',convert2str(obj.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(obj.rheology_n),'" default="',convert2str(obj.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_law" type="',class(obj.rheology_law),'" default="',convert2str(obj.rheology_law),'">','     <section name="materials" />','     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(obj.lithosphere_shear_modulus),'" default="',convert2str(obj.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(obj.lithosphere_density),'" default="',convert2str(obj.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(obj.mantle_shear_modulus),'" default="',convert2str(obj.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(obj.mantle_density),'" default="',convert2str(obj.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
+
+
+		end % }}}
+		function obj = matdamageice(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('matdamageice');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%ice density (kg/m^3)
+			obj.rho_ice=917.;
+
+			%ocean water density (kg/m^3)
+			obj.rho_water=1023.;
+
+			%fresh water density (kg/m^3)
+			obj.rho_freshwater=1000.;
+
+			%water viscosity (N.s/m^2)
+			obj.mu_water=0.001787;  
+
+			%ice heat capacity cp (J/kg/K)
+			obj.heatcapacity=2093.;
+
+			%ice latent heat of fusion L (J/kg)
+			obj.latentheat=3.34*10^5;
+
+			%ice thermal conductivity (W/m/K)
+			obj.thermalconductivity=2.4;
+			
+			%wet ice thermal conductivity (W/m/K)
+			obj.temperateiceconductivity=.24;
+
+			%the melting point of ice at 1 atmosphere of pressure in K
+			obj.meltingpoint=273.15;
+
+			%rate of change of melting point with pressure (K/Pa)
+			obj.beta=9.8*10^-8;
+
+			%mixed layer (ice-water interface) heat capacity (J/kg/K)
+			obj.mixed_layer_capacity=3974.;
+
+			%thermal exchange velocity (ice-water interface) (m/s)
+			obj.thermal_exchange_velocity=1.00*10^-4;
+
+			%Rheology law: what is the temperature dependence of B with T
+			%available: none, paterson and arrhenius
+			obj.rheology_law='Paterson';
+
+			% GIA:
+			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
+			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			obj.mantle_density             = 3.34;       % (g/cm^-3)
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			md = checkfield(md,'fieldname','materials.rho_ice','>',0);
+			md = checkfield(md,'fieldname','materials.rho_water','>',0);
+			md = checkfield(md,'fieldname','materials.rho_freshwater','>',0);
+			md = checkfield(md,'fieldname','materials.mu_water','>',0);
+			md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','materials.rheology_law','values',{'None' 'Cuffey' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
+
+			if ismember(GiaAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Materials:'));
+
+			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(obj,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
+			fielddisplay(obj,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
+			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(obj,'latentheat','latent heat of fusion [J/kg]');
+			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
+			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','temperateiceconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matdamageice.py	(revision 18231)
@@ -0,0 +1,150 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import MaterialsEnum, MatdamageiceEnum, MaterialsRheologyLawEnum, MaterialsRhoSeawaterEnum
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class matdamageice(object):
+	"""
+	MATICE class definition
+
+	   Usage:
+	      matdamagice=matdamageice();
+	"""
+
+	def __init__(self): # {{{
+		self.rho_ice                   = 0.
+		self.rho_water                 = 0.
+		self.rho_freshwater            = 0.
+		self.mu_water                  = 0.
+		self.heatcapacity              = 0.
+		self.latentheat                = 0.
+		self.thermalconductivity       = 0.
+		self.temperateiceconductivity  = 0.
+		self.meltingpoint              = 0.
+		self.beta                      = 0.
+		self.mixed_layer_capacity      = 0.
+		self.thermal_exchange_velocity = 0.
+		self.rheology_B                = float('NaN')
+		self.rheology_n                = float('NaN')
+		self.rheology_law              = ''
+
+		#gia: 
+		self.lithosphere_shear_modulus  = 0.
+		self.lithosphere_density        = 0.
+		self.mantle_shear_modulus       = 0.
+		self.mantle_density             = 0.
+
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   Materials:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"temperateiceconductivity","temperate ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+		string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		#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
+
+		#temperate ice thermal conductivity (W/m/K)
+		self.temperateiceconductivity=0.24
+
+		#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'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10  # (Pa)
+		self.lithosphere_density        = 3.32        # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
+		self.mantle_density             = 3.34        # (g/cm^-3)
+
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','materials.rho_ice','>',0)
+		md = checkfield(md,'fieldname','materials.rho_water','>',0)
+		md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
+		md = checkfield(md,'fieldname','materials.mu_water','>',0)
+		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','materials.rheology_law','values',['None','Cuffey','Paterson','Arrhenius','LliboutryDuval'])
+		md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]);
+		return md
+	# }}}
+	def marshall(self,md,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','enum',MaterialsRhoSeawaterEnum(),'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','temperateiceconductivity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
+		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.m	(revision 18231)
@@ -0,0 +1,204 @@
+%MATICE class definition
+%
+%   Usage:
+%      matice=matice();
+
+classdef matice
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		temperateiceconductivity   = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_law = '';
+
+		%gia: 
+		lithosphere_shear_modulus  = 0.;
+		lithosphere_density        = 0.;
+		mantle_shear_modulus       = 0.;
+		mantle_density             = 0.;
+
+	end
+	methods
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '<!-- materials -->\n');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(obj.rho_ice),'" default="',convert2str(obj.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(obj.rho_water),'" default="',convert2str(obj.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(obj.rho_freshwater),'" default="',convert2str(obj.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(obj.mu_water),'" default="',convert2str(obj.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(obj.heatcapacity),'" default="',convert2str(obj.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(obj.latentheat),'" default="',convert2str(obj.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(obj.thermalconductivity),'" default="',convert2str(obj.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(obj.temperateiceconductivity),'" default="',convert2str(obj.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(obj.meltingpoint),'" default="',convert2str(obj.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(obj.beta),'" default="',convert2str(obj.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(obj.mixed_layer_capacity),'" default="',convert2str(obj.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(obj.thermal_exchange_velocity),'" default="',convert2str(obj.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(obj.rheology_B),'" default="',convert2str(obj.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(obj.rheology_n),'" default="',convert2str(obj.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
+
+			% rheology_law drop-down
+			fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="rheology_law" type="alternative" optional="false">','     <section name="materials" />','     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>');
+			fprintf(fid,'%s\n','       <option value="None" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="Paterson" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="Arrhenius" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="LliboutryDuval" type="string" default="false"> </option>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(obj.lithosphere_shear_modulus),'" default="',convert2str(obj.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(obj.lithosphere_density),'" default="',convert2str(obj.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(obj.mantle_shear_modulus),'" default="',convert2str(obj.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(obj.mantle_density),'" default="',convert2str(obj.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
+
+
+		end % }}}
+		function obj = matice(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('matice');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%ice density (kg/m^3)
+			obj.rho_ice=917.;
+
+			%ocean water density (kg/m^3)
+			obj.rho_water=1023.;
+
+			%fresh water density (kg/m^3)
+			obj.rho_freshwater=1000.;
+
+			%water viscosity (N.s/m^2)
+			obj.mu_water=0.001787;  
+
+			%ice heat capacity cp (J/kg/K)
+			obj.heatcapacity=2093.;
+
+			%ice latent heat of fusion L (J/kg)
+			obj.latentheat=3.34*10^5;
+
+			%ice thermal conductivity (W/m/K)
+			obj.thermalconductivity=2.4;
+			
+			%wet ice thermal conductivity (W/m/K)
+			obj.temperateiceconductivity=.24;
+
+			%the melting point of ice at 1 atmosphere of pressure in K
+			obj.meltingpoint=273.15;
+
+			%rate of change of melting point with pressure (K/Pa)
+			obj.beta=9.8*10^-8;
+
+			%mixed layer (ice-water interface) heat capacity (J/kg/K)
+			obj.mixed_layer_capacity=3974.;
+
+			%thermal exchange velocity (ice-water interface) (m/s)
+			obj.thermal_exchange_velocity=1.00*10^-4;
+
+			%Rheology law: what is the temperature dependence of B with T
+			%available: none, paterson and arrhenius
+			obj.rheology_law='Paterson';
+
+			% GIA:
+			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
+			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			obj.mantle_density             = 3.34;       % (g/cm^-3)
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			md = checkfield(md,'fieldname','materials.rho_ice','>',0);
+			md = checkfield(md,'fieldname','materials.rho_water','>',0);
+			md = checkfield(md,'fieldname','materials.rho_freshwater','>',0);
+			md = checkfield(md,'fieldname','materials.mu_water','>',0);
+			md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','materials.rheology_law','values',{'None' 'Cuffey' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
+
+			if ismember(GiaAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Materials:'));
+
+			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(obj,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
+			fielddisplay(obj,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
+			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(obj,'latentheat','latent heat of fusion [J/kg]');
+			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
+			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','temperateiceconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/matice.py	(revision 18231)
@@ -0,0 +1,150 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class matice(object):
+	"""
+	MATICE class definition
+
+	   Usage:
+	      matice=matice();
+	"""
+
+	def __init__(self): # {{{
+		self.rho_ice                   = 0.
+		self.rho_water                 = 0.
+		self.rho_freshwater            = 0.
+		self.mu_water                  = 0.
+		self.heatcapacity              = 0.
+		self.latentheat                = 0.
+		self.thermalconductivity       = 0.
+		self.temperateiceconductivity  = 0.
+		self.meltingpoint              = 0.
+		self.beta                      = 0.
+		self.mixed_layer_capacity      = 0.
+		self.thermal_exchange_velocity = 0.
+		self.rheology_B                = float('NaN')
+		self.rheology_n                = float('NaN')
+		self.rheology_law              = ''
+
+		#gia: 
+		self.lithosphere_shear_modulus  = 0.
+		self.lithosphere_density        = 0.
+		self.mantle_shear_modulus       = 0.
+		self.mantle_density             = 0.
+
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   Materials:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"temperateiceconductivity","temperate ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+		string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		#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
+
+		#temperate ice thermal conductivity (W/m/K)
+		self.temperateiceconductivity=0.24
+
+		#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'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10  # (Pa)
+		self.lithosphere_density        = 3.32        # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
+		self.mantle_density             = 3.34        # (g/cm^-3)
+
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','materials.rho_ice','>',0)
+		md = checkfield(md,'fieldname','materials.rho_water','>',0)
+		md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
+		md = checkfield(md,'fieldname','materials.mu_water','>',0)
+		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','materials.rheology_law','values',['None','Cuffey','Paterson','Arrhenius','LliboutryDuval'])
+		md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]);
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'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','temperateiceconductivity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
+		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.m	(revision 18231)
@@ -0,0 +1,171 @@
+%MESH2D class definition
+%
+%   Usage:
+%      mesh2d=mesh2d();
+
+classdef mesh2d
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		elements                    = NaN
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonboundary            = NaN
+
+		edges                       = NaN
+		segments                    = NaN
+		segmentmarkers              = NaN
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+
+		extractedvertices           = NaN
+		extractedelements           = NaN
+	end
+	methods
+		function self = mesh2d(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=mesh2d();
+					object=varargin{1};
+					fields=fieldnames(object);
+					for i=1:length(fields)
+						field=fields{i};
+						if ismember(field,properties('mesh2d')),
+							self.(field)=object.(field);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements 3]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
+			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+
+			switch(solution),
+				case ThermalSolutionEnum(),
+					md = checkmessage(md,'thermal not supported for 2d mesh');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   2D tria Mesh (horizontal):')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'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');
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Extracted model:'));
+			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
+			fielddisplay(obj,'extractedelements','elements extracted from the model');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- 2D tria Mesh (horizontal) -->\n');
+            
+            %elements and vertices
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Elements and vertices">','<section name="mesh" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','     <section name="mesh" />','     <help> number of elements </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','     <section name="mesh" />','     <help> number of vertices </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','     <section name="mesh" />','     <help> vertex indices of the mesh elements </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(obj.edges),'" default="',convert2str(obj.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(obj.numberofedges),'" default="',convert2str(obj.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+     
+            % properties
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(obj.segments),'" default="',convert2str(obj.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(obj.segmentmarkers),'" default="',convert2str(obj.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            %extracted model
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Extracted Model">','<section name="mesh" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh" />','     <help> vertices extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh" />','     <help> elements extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            %projection
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Projection">','<section name="mesh" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+            % choice (hemisphere) 'n' or 's'
+            fprintf(fid,'%s\n%s\n%s\n','  <parameter key ="hemisphere" type="alternative" optional="false">','     <section name="mesh" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>');
+            fprintf(fid,'%s\n','       <option value="n" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n','       <option value="s" type="string" default="false"> </option>');
+            fprintf(fid,'%s\n','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        
+        end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
+		end % }}}
+		function t = domaintype(obj) % {{{
+			t = '2Dhorizontal';
+		end % }}}
+		function d = dimension(obj) % {{{
+			d = 2;
+		end % }}}
+		function s = elementtype(obj) % {{{
+			s = 'Tria';
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2d.py	(revision 18231)
@@ -0,0 +1,120 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+import MatlabFuncs as m
+from WriteData import WriteData
+
+class mesh2d(object):
+	"""
+	MESH2D class definition
+
+	   Usage:
+	      mesh2d=mesh2d();
+	"""
+
+	def __init__(self): # {{{
+		self.x                           = float('NaN');
+		self.y                           = float('NaN');
+		self.elements                    = float('NaN');
+		self.numberofelements            = 0;
+		self.numberofvertices            = 0;
+		self.numberofedges               = 0;
+		
+		self.lat                         = float('NaN');
+		self.long                        = float('NaN');
+		self.hemisphere                  = float('NaN');
+
+		self.vertexonboundary            = float('NaN');
+		self.edges                       = float('NaN');
+		self.segments                    = float('NaN');
+		self.segmentmarkers              = float('NaN');
+		self.vertexconnectivity          = float('NaN');
+		self.elementconnectivity         = float('NaN');
+		self.average_vertex_connectivity = 0;
+
+		self.extractedvertices           = float('NaN');
+		self.extractedelements           = float('NaN');
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   2D tria Mesh (horizontal):" 
+
+		string="%s\n%s"%(string,"\n      Elements and vertices:")
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","vertex indices of the mesh elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
+
+		string="%s%s"%(string,"\n\n      Properties:")
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
+		string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+
+		string="%s%s"%(string,"\n\n      Extracted model:")
+		string="%s\n%s"%(string,fielddisplay(self,"extractedvertices","vertices extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedelements","elements extracted from the model"))
+
+		string="%s%s"%(string,"\n\n      Projection:")
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#the connectivity is the averaged number of nodes linked to a
+		#given node through an edge. This connectivity is used to initially
+		#allocate memory to the stiffness matrix. A value of 16 seems to
+		#give a good memory/time ration. This value can be checked in
+		#trunk/test/Miscellaneous/runme.m
+		self.average_vertex_connectivity=25
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
+		md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,3])
+		if numpy.any(numpy.logical_not(m.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,'fieldname','mesh.numberofelements','>',0)
+		md = checkfield(md,'fieldname','mesh.numberofvertices','>',0)
+		md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
+		if solution==ThermalSolutionEnum():
+			md.checkmessage("thermal not supported for 2d mesh")
+
+		return md
+	# }}}
+	def domaintype(self): # {{{
+		return "2Dhorizontal"
+	#}}}
+	def dimension(self): # {{{
+		return 2
+	#}}}
+	def elementtype(self): # {{{
+		return "Tria"
+	#}}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer');
+		WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer');
+		WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer');
+		WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
+		WriteData(fid,'enum',MeshZEnum(),'data',numpy.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
+		WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2dvertical.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2dvertical.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh2dvertical.m	(revision 18231)
@@ -0,0 +1,264 @@
+%MESH2DVERTICAL class definition
+%
+%   Usage:
+%      mesh2dvertical=mesh2dvertical();
+
+classdef mesh2dvertical
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		elements                    = NaN
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonboundary            = NaN
+		vertexonbase                 = NaN
+		vertexonsurface             = NaN
+
+		edges                       = NaN
+		segments                    = NaN
+		segmentmarkers              = NaN
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+	end
+	methods
+                function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- 2d Mesh (Vertical) -->\n');
+            
+            %elements and vertices
+            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices">','       <section name="mesh" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(obj.edges),'" default="',convert2str(obj.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(obj.numberofedges),'" default="',convert2str(obj.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','       </frame>');
+     
+            % properties
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh" />','     <help> vertices on the bed of the domain flag list </help>','  </parameter>');            
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(obj.segments),'" default="',convert2str(obj.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(obj.segmentmarkers),'" default="',convert2str(obj.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+
+            %projection
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Projection">','<section name="mesh" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        
+        end % }}}
+		function obj = mesh2dvertical(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('mesh2dvertical');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements 3]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
+			md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+
+			switch(solution),
+				case ThermalSolutionEnum(),
+					md = checkmessage(md,'thermal not supported for 2d mesh');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   2D tria Mesh (vertical):')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(obj,'vertexonbase','vertices on the bed of the domain flag list');
+			fielddisplay(obj,'vertexonsurface','vertices on the surface of the domain flag list');
+			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(obj,'segmentmarkers','number associated to each segment');
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+		function t = domaintype(obj) % {{{
+			t = '2Dvertical';
+		end % }}}
+		function d = dimension(obj) % {{{
+			d = 2;
+		end % }}}
+		function s = elementtype(obj) % {{{
+			s = 'Tria';
+		end % }}}
+		function flags = vertexflags(self,value) % {{{
+			flags = zeros(self.numberofvertices,1);
+			pos   = self.segments(find(self.segmentmarkers==value),1:2);
+			flags(pos) = 1;
+		end % }}}
+		function [data datatype] = processdata(self,md,data,options) % {{{
+
+			%transpose data if necessary
+			if (size(data,2) > size(data,1)),
+				data=data';
+			end
+			datasize=size(data);
+
+			%convert to double if necessary
+			if ~isnumeric(data);
+				disp('processdata info message: data is not numeric (logical?). Converted to double');
+				data=double(data);
+			end
+
+			%check length
+			if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements
+				error('plotmodel error message: data not supported yet');
+			end
+
+			%quiver?
+			if datasize(2)>1,
+				datatype=3;
+			end
+
+			%smoothing?
+			if exist(options,'smooth')
+				data=averaging(md,data,getfieldvalue(options,'smooth'));
+				datasize(1)=md.mesh.numberofvertices;
+				%---> go to node data
+			end
+
+			%element data
+			if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+				datatype=1;
+
+				%Mask?
+				if exist(options,'mask'),
+					flags=getfieldvalue(options,'mask');
+					pos=find(~flags);
+					if length(flags)==md.mesh.numberofvertices,
+						[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+						data(pos2,:)=NaN;
+					elseif length(flags)==md.mesh.numberofelements
+						data(pos,:)=NaN;
+					else
+						disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+					end
+				end
+
+				%log?
+				if exist(options,'log'),
+					bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+					data(find(data<bounds(1)))=bounds(1);
+					if any(data<=0),
+						error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+					end
+					pos=find(~isnan(data));
+					data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+				end
+			end
+
+			%node data
+			if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+				datatype=2;
+
+				%Mask?
+				if exist(options,'mask'),
+					flags=getfieldvalue(options,'mask');
+					pos=find(~flags);
+					if length(flags)==md.mesh.numberofvertices,
+						data(pos,:)=NaN;
+					elseif length(flags)==md.mesh.numberofelements
+						data(md.mesh.elements(pos,:),:)=NaN;
+					else
+						disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+					end
+				end
+
+				%log?
+				if exist(options,'log'),
+					%if any(data<=0),
+					%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+					%end
+					data=log(data)/log(getfieldvalue(options,'log'));
+				end
+			end
+		end % }}}
+		function [x y z elements is2d isplanet] = processmesh(self,options) % {{{
+
+			isplanet = 0;
+			is2d     = 1;
+
+			elements = self.elements;
+			x        = self.x;
+			y        = self.y;
+			z        = zeros(self.numberofvertices,1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.m	(revision 18231)
@@ -0,0 +1,213 @@
+%MESH3DPRISMS class definition
+%
+%   Usage:
+%      mesh=mesh3dprisms();
+
+classdef mesh3dprisms
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN
+		elements                    = NaN
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonbase                 = NaN
+		vertexonsurface             = NaN
+		lowerelements               = NaN
+		lowervertex                 = NaN
+		upperelements               = NaN
+		uppervertex                 = NaN
+		vertexonboundary            = NaN
+
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+
+		x2d                         = NaN
+		y2d                         = NaN
+		elements2d                  = NaN
+		numberofvertices2d          = 0;
+		numberofelements2d          = 0;
+
+		extractedvertices           = NaN
+		extractedelements           = NaN
+	end
+	methods
+           function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- 3D prism Mesh -->\n');
+            
+            % Elements and verticies of the original 2d mesh
+            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(obj.numberofelements2d),'" default="',convert2str(obj.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(obj.numberofvertices2d),'" default="',convert2str(obj.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(obj.elements2d),'" default="',convert2str(obj.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(obj.x2d),'" default="',convert2str(obj.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(obj.y2d),'" default="',convert2str(obj.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','       </frame>');
+            
+            % Elements and vertices of the extruded 3d mesh
+            fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','       </frame>');
+     
+            % properties
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(obj.numberoflayers),'" default="',convert2str(obj.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(obj.elementontbase),'" default="',convert2str(obj.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(obj.vertexonsurface),'" default="',convert2str(obj.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(obj.elementontsurface),'" default="',convert2str(obj.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(obj.uppervertex),'" default="',convert2str(obj.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(obj.upperelements),'" default="',convert2str(obj.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(obj.lowervertex),'" default="',convert2str(obj.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(obj.lowerelements),'" default="',convert2str(obj.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % Extracted model
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % Projection
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh3dprisms" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        
+        end % }}}cd
+		function self = mesh3dprisms(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=mesh3dprisms();
+					object=varargin{1};
+					fields=fieldnames(object);
+					for i=1:length(fields)
+						field=fields{i};
+						if ismember(field,properties('mesh3dprisms')),
+							self.(field)=object.(field);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements 6]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0);
+			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
+			%no checks for numberofedges lat long and hemisphere
+			md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.z','>=',md.geometry.base-10^-10,'message','''mesh.z'' lower than bedrock');
+			md = checkfield(md,'fieldname','mesh.z','<=',md.geometry.surface+10^-10,'message','''mesh.z'' higher than surface elevation');
+			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   3D prism Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices of the original 2d mesh:'));
+			fielddisplay(obj,'numberofelements2d','number of elements');
+			fielddisplay(obj,'numberofvertices2d','number of vertices');
+			fielddisplay(obj,'elements2d','vertex indices of the mesh elements');
+			fielddisplay(obj,'x2d','vertices x coordinate [m]');
+			fielddisplay(obj,'y2d','vertices y coordinate [m]');
+
+			disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+			fielddisplay(obj,'vertexonbase','lower vertices flags list');
+			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
+			fielddisplay(obj,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
+			fielddisplay(obj,'upperelements','upper element list (NaN for element on the upper layer)');
+			fielddisplay(obj,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
+			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,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Extracted model:'));
+			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
+			fielddisplay(obj,'extractedelements','elements extracted from the model');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices2d','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements2d','format','Integer');
+		end % }}}
+		function type = domaintype(obj) % {{{
+			type = '3D';
+		end % }}}
+		function d = dimension(obj) % {{{
+			d = 3;
+		end % }}}
+		function s = elementtype(obj) % {{{
+			s = 'Penta';
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dprisms.py	(revision 18231)
@@ -0,0 +1,153 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+import MatlabFuncs as m
+from WriteData import WriteData
+
+class mesh3dprisms(object):
+	"""
+	MESH3DPRISMS class definition
+
+	   Usage:
+	      mesh3d=mesh3dprisms();
+	"""
+
+	def __init__(self): # {{{
+		self.x                           = float('NaN');
+		self.y                           = float('NaN');
+		self.z                           = float('NaN');
+		self.elements                    = float('NaN');
+		self.numberoflayers              = 0;
+		self.numberofelements            = 0;
+		self.numberofvertices            = 0;
+		
+		self.lat                         = float('NaN');
+		self.long                        = float('NaN');
+		self.hemisphere                  = float('NaN');
+
+		self.vertexonbase                 = float('NaN');
+		self.vertexonsurface             = float('NaN');
+		self.lowerelements               = float('NaN');
+		self.lowervertex                 = float('NaN');
+		self.upperelements               = float('NaN');
+		self.uppervertex                 = float('NaN');
+		self.vertexonboundary            = float('NaN');
+
+		self.vertexconnectivity          = float('NaN');
+		self.elementconnectivity         = float('NaN');
+		self.average_vertex_connectivity = 0;
+
+		self.x2d                         = float('NaN');
+		self.y2d                         = float('NaN');
+		self.elements2d                  = float('NaN');
+		self.numberofvertices2d          = 0;
+		self.numberofelements2d          = 0;
+
+		self.extractedvertices           = float('NaN');
+		self.extractedelements           = float('NaN');
+
+		#set defaults
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   3D prism Mesh:" 
+
+		string="%s\n%s"%(string,"\n      Elements and vertices of the original 2d mesh3dprisms:")
+		
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements2d","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices2d","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements2d","vertex indices of the mesh3dprisms elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x2d","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y2d","vertices y coordinate [m]"))
+
+		string="%s\n%s"%(string,"\n\n      Elements and vertices of the extruded 3d mesh3dprisms:")
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","vertex indices of the mesh3dprisms elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"z","vertices z coordinate [m]"))
+
+		string="%s%s"%(string,"\n\n      Properties:")
+		string="%s\n%s"%(string,fielddisplay(self,"numberoflayers","number of extrusion layers"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonbase","lower vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (-1 for vertex on the upper surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (-1 for element on the upper layer)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (-1 for vertex on the lower surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (-1 for element on the lower layer)"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+
+		string="%s%s"%(string,"\n\n      Extracted model:")
+		string="%s\n%s"%(string,fielddisplay(self,"extractedvertices","vertices extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedelements","elements extracted from the model"))
+
+		string="%s%s"%(string,"\n\n      Projection:")
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#the connectivity is the averaged number of nodes linked to a
+		#given node through an edge. This connectivity is used to initially
+		#allocate memory to the stiffness matrix. A value of 16 seems to
+		#give a good memory/time ration. This value can be checked in
+		#trunk/test/Miscellaneous/runme.m
+		self.average_vertex_connectivity=25
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.z','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
+		md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,6])
+		if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
+			md.checkmessage("orphan nodes have been found. Check the mesh3dprisms outline")
+		md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0)
+		md = checkfield(md,'fieldname','mesh.numberofelements','>',0)
+		md = checkfield(md,'fieldname','mesh.numberofvertices','>',0)
+		#no checks for numberofedges lat long and hemisphere
+		md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d")
+
+		return md
+	# }}}
+	def domaintype(self): # {{{
+		return "3D"
+	#}}}
+	def dimension(self): # {{{
+		return 3
+	#}}}
+	def elementtype(self): # {{{
+		return "Penta"
+	#}}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer');
+		WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer');
+		WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer');
+		WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1)
+		WriteData(fid,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer')
+		WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dtetras.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dtetras.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/mesh3dtetras.m	(revision 18231)
@@ -0,0 +1,213 @@
+%MESH3DTETRAS class definition
+%
+%   Usage:
+%      mesh=mesh3dtetras();
+
+classdef mesh3dtetras
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN
+		elements                    = NaN
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		vertexonbase                 = NaN
+		vertexonsurface             = NaN
+		lowerelements               = NaN
+		lowervertex                 = NaN
+		upperelements               = NaN
+		uppervertex                 = NaN
+		vertexonboundary            = NaN
+
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+
+		x2d                         = NaN
+		y2d                         = NaN
+		elements2d                  = NaN
+		numberofvertices2d          = 0;
+		numberofelements2d          = 0;
+
+		extractedvertices           = NaN
+		extractedelements           = NaN
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- 3D Tetra Mesh -->\n');
+            
+            % Elements and verticies of the original 2d mesh
+            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(obj.numberofelements2d),'" default="',convert2str(obj.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(obj.numberofvertices2d),'" default="',convert2str(obj.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(obj.elements2d),'" default="',convert2str(obj.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(obj.x2d),'" default="',convert2str(obj.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(obj.y2d),'" default="',convert2str(obj.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','       </frame>');
+            
+            % Elements and vertices of the extruded 3d mesh
+            fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','       </frame>');
+     
+            % properties
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(obj.numberoflayers),'" default="',convert2str(obj.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(obj.elementontbase),'" default="',convert2str(obj.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(obj.vertexonsurface),'" default="',convert2str(obj.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(obj.elementontsurface),'" default="',convert2str(obj.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(obj.uppervertex),'" default="',convert2str(obj.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(obj.upperelements),'" default="',convert2str(obj.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(obj.lowervertex),'" default="',convert2str(obj.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(obj.lowerelements),'" default="',convert2str(obj.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % Extracted model
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % Projection
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh3dprisms" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+        
+        end % }}}cd
+		function self = mesh3dtetras(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('mesh3dtetras');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements 4]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0);
+			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
+			%no checks for numberofedges lat long and hemisphere
+			md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','mesh.z','>=',md.geometry.base-10^-10,'message','''mesh.z'' lower than bedrock');
+			md = checkfield(md,'fieldname','mesh.z','<=',md.geometry.surface+10^-10,'message','''mesh.z'' higher than surface elevation');
+			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   3D tetra Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices of the original 2d mesh:'));
+			fielddisplay(obj,'numberofelements2d','number of elements');
+			fielddisplay(obj,'numberofvertices2d','number of vertices');
+			fielddisplay(obj,'elements2d','vertex indices of the mesh elements');
+			fielddisplay(obj,'x2d','vertices x coordinate [m]');
+			fielddisplay(obj,'y2d','vertices y coordinate [m]');
+
+			disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+			fielddisplay(obj,'vertexonbase','lower vertices flags list');
+			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
+			fielddisplay(obj,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
+			fielddisplay(obj,'upperelements','upper element list (NaN for element on the upper layer)');
+			fielddisplay(obj,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
+			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,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Extracted model:'));
+			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
+			fielddisplay(obj,'extractedelements','elements extracted from the model');
+
+			disp(sprintf('\n      Projection:'));
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices2d','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements2d','format','Integer');
+		end % }}}
+		function t = domaintype(obj) % {{{
+			t = '3D';
+		end % }}}
+		function d = dimension(obj) % {{{
+			d = 3;
+		end % }}}
+		function s = elementtype(obj) % {{{
+			s = 'Tetra';
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.m	(revision 18231)
@@ -0,0 +1,52 @@
+%MISCELLANEOUS class definition
+%
+%   Usage:
+%      miscellaneous=miscellaneous();
+
+classdef miscellaneous
+	properties (SetAccess=public) 
+		notes = '';
+		name  = '';
+		dummy = struct();
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- miscellaneous -->\n');            
+                    
+            % miscellaneous solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="miscellaneous parameters">','<section name="miscellaneous" />');                    
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="notes" type="',class(obj.notes),'" default="',convert2str(obj.notes),'">','     <section name="miscellaneous" />','     <help> notes in a cell of strings </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="name" type="',class(obj.name),'" default="',convert2str(obj.name),'">','     <section name="miscellaneous" />','     <help> model name </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dummy" type="',class(obj.dummy),'" default="',convert2str(obj.dummy),'">','     <section name="miscellaneous" />','     <help> empty field to store some data </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}        
+		function obj = miscellaneous(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','miscellaneous.name','empty',1);
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   miscellaneous parameters:'));
+
+			fielddisplay(obj,'notes','notes in a cell of strings');
+			fielddisplay(obj,'name','model name');
+			fielddisplay(obj,'dummy','empty field to store some data');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','name','format','String');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/miscellaneous.py	(revision 18231)
@@ -0,0 +1,41 @@
+from collections import OrderedDict
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class miscellaneous(object):
+	"""
+	MISCELLANEOUS class definition
+
+	   Usage:
+	      miscellaneous=miscellaneous();
+	"""
+
+	def __init__(self): # {{{
+		self.notes = ''
+		self.name  = ''
+		self.dummy = OrderedDict()
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   miscellaneous parameters:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'notes','notes in a cell of strings'))
+		string="%s\n%s"%(string,fielddisplay(self,'name','model name'))
+		string="%s\n%s"%(string,fielddisplay(self,'dummy','empty field to store some data'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','miscellaneous.name','empty',1)
+		return md
+	# }}}
+	def marshall(self,md,fid):    #  {{{
+		WriteData(fid,'object',self,'fieldname','name','format','String')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/misfit.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/misfit.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/misfit.m	(revision 18231)
@@ -0,0 +1,89 @@
+%MISFIT class definition
+%
+%   Usage:
+%      misfit=misfit();
+%      misfit=misfit('name','SurfaceAltimetry',...
+%                    'model_enum',SurfaceEnum,...
+%                    'observation_enum',SurfaceObservationsEnum,...
+%                    'observation',md.geometry.surface,...
+%                    'timeinterpolation','nearestneighbor',...
+%                    'weights',ones(md.mesh.numberofvertices,1),...
+%                    'weights_enum',WeightsSurfaceObservationsEnum);
+%
+%
+
+classdef misfit
+	properties (SetAccess=public)
+		%misfit
+		name              = '';
+		model_enum        = NaN; %enum for field that is modeled
+		observation       = NaN; %observed field that we compare the model against
+		observation_enum  = NaN; %enum for observed field.
+		timeinterpolation = '';
+		weights           = NaN; %weight coefficients for every vertex
+		weights_enum      = NaN; %enum to identify this particular set of weights
+		cumulated         = NaN; %do we cumulate misfit through time?
+	end
+	
+	methods
+		function obj = misfit(varargin) % {{{
+			if nargin==0,
+				obj=setdefaultparameters(obj);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				obj.name=getfieldvalue(options,'name','');
+				obj.model_enum=getfieldvalue(options,'model_enum');
+				obj.observation=getfieldvalue(options,'observation',NaN);
+				obj.observation_enum=getfieldvalue(options,'observation_enum');
+				obj.timeinterpolation=getfieldvalue(options,'timeinterpolation','nearestneighbor');
+				obj.weights=getfieldvalue(options,'weights',NaN);
+				obj.weights_enum=getfieldvalue(options,'weights_enum',NaN);
+
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+			obj.timeinterpolation='nearestneighbor';
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ~ischar(obj.name),
+				error('misfit error message: ''name'' field should be a string!');
+			end
+
+			if ~ischar(obj.timeinterpolation),
+				error('misfit error message: ''timeinterpolation'' field should be a string!');
+			end
+			md = checkfield(md,'fieldname','obj.observation','field',obj.observation,'forcing',1,'NaN',1);
+			md = checkfield(md,'fieldname','obj.timeinterpolation','field',obj.timeinterpolation,'values',{'nearestneighbor'});
+			md = checkfield(md,'fieldname','obj.weights','field',obj.weights,'forcing',1,'NaN',1);
+
+		end % }}}
+		function md = disp(obj) % {{{
+		
+			disp(sprintf('   Misfit:\n'));
+
+			fielddisplay(obj,'name','identifier for this misfit response');
+			fielddisplay(obj,'model_enum','enum for field that is modeled');
+			fielddisplay(obj,'observation','observed field that we compare the model against');
+			fielddisplay(obj,'observation_enum','observation enum');
+			fielddisplay(obj,'timeinterpolation','interpolation routine used to interpolate misfit between two time steps (default is ''nearestneighbor''');
+			fielddisplay(obj,'weights','weights (at vertices) to apply to the misfit');
+			fielddisplay(obj,'weights_enum','enum for weights for identification purposes');
+
+		end % }}}
+		function md = marshall(obj,md,fid) % {{{
+
+		WriteData(fid,'object',obj,'fieldname','name','format','String');
+		WriteData(fid,'object',obj,'fieldname','model_enum','format','Integer');
+		WriteData(fid,'object',obj,'fieldname','observation','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+		WriteData(fid,'object',obj,'fieldname','observation_enum','format','Integer');
+		WriteData(fid,'object',obj,'fieldname','timeinterpolation','format','String');
+		WriteData(fid,'object',obj,'fieldname','weights','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+		WriteData(fid,'object',obj,'fieldname','weights_enum','format','Integer');
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.m	(revision 18231)
@@ -0,0 +1,1378 @@
+%MODEL class definition
+%
+%   Usage:
+%      md = model(varargin)
+
+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;
+		damage           = 0;
+		friction         = 0;
+		flowequation     = 0;
+		timestepping     = 0;
+		initialization   = 0;
+		rifts            = 0;
+
+		debug            = 0;
+		verbose          = 0;
+		settings         = 0;
+		toolkits         = 0;
+		cluster          = 0;
+
+		balancethickness = 0;
+		stressbalance    = 0;
+		groundingline    = 0;
+		hydrology        = 0;
+		masstransport    = 0;
+		thermal          = 0;
+		steadystate      = 0;
+		transient        = 0;
+		gia              = 0;
+
+		autodiff         = 0;
+		flaim            = 0;
+		inversion        = 0;
+		qmu              = 0;
+
+		results          = 0;
+		outputdefinition = 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
+			%2013 April 12
+			if numel(md.stressbalance.loadingforce==1)
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+			%2013 April 17
+			if isa(md.hydrology,'hydrology'),
+				disp('Recovering old hydrology class');
+				md.hydrology=hydrologyshreve(md.materials);
+			end
+			%2013 October 9
+			if ~isa(md.damage,'damage'),
+				md.damage=damage();
+				md.damage.D=zeros(md.mesh.numberofvertices,1);
+				md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+			end
+			%2013 November 18
+			if ~isa(md.outputdefinition,'outputdefinition'),
+				md.outputdefinition=outputdefinition();
+			end
+			%2014 January 9th
+			if isa(md.surfaceforcings,'surfaceforcings'),
+				disp('Recovering old surfaceforcings class');
+				mass_balance=md.surfaceforcings.mass_balance;
+				md.surfaceforcings=SMB();
+				md.surfaceforcings.mass_balance=mass_balance;
+			end
+			%2014 March 26th
+			if isa(md.mesh,'mesh'),
+				disp('Recovering old mesh class');
+				if isprop(md.mesh,'dimension'),
+					if md.mesh.dimension==2,
+						md.mesh=mesh2d(md.mesh);
+					else
+						md.mesh=mesh3dprisms(md.mesh);
+					end
+				else
+					md.mesh=mesh2dvertical(md.mesh);
+				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 ~strcmp(md.mesh.elementtype(),'Penta'),
+				error('collapse error message: only 3d mesh can be collapsed')
+			end
+
+			%Start with changing all 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;
+
+			%gia
+			if ~isnan(md.gia.mantle_viscosity), md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1); end
+			if ~isnan(md.gia.lithosphere_thickness), md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1); end
+
+			%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.borderSSA=project2d(md,md.flowequation.borderSSA,1);
+				md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1);
+				md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1);
+			end	
+
+			%boundary conditions
+			md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers);
+			md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers);
+			md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers);
+			md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers);
+			md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
+			md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
+			if ~isnan(md.damage.spcdamage), md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers); end
+			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+			%materials
+			md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+			md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+			
+			%damage: 
+			if md.damage.isdamage,
+				md.damage.D=DepthAverage(md,md.damage.D);
+			end
+
+			%special for thermal modeling:
+			md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
+			md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_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.base=project2d(md,md.geometry.base,1);
+			md.geometry.bed=project2d(md,md.geometry.bed,1);
+
+			md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
+			md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+
+			%lat long
+			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
+			mesh=mesh2d();
+			mesh.x=md.mesh.x2d;
+			mesh.y=md.mesh.y2d;
+			mesh.numberofvertices=md.mesh.numberofvertices2d;
+			mesh.numberofelements=md.mesh.numberofelements2d;
+			mesh.elements=md.mesh.elements2d;
+			if ~isnan(md.mesh.vertexonboundary), mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1); end
+			if ~isnan(md.mesh.elementconnectivity), mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1); end
+			md.mesh=mesh;
+
+		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: '~HO.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');
+			%
+			%   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 isa(md1.mesh,'mesh3dprisms'),
+				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 isa(md1.mesh,'mesh3dprisms'),
+				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 isa(md1.mesh,'mesh3dprisms'),
+				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(dimension(md.mesh)==2),
+				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
+			end
+
+			%Penalties
+			if ~isnan(md2.stressbalance.vertex_pairing),
+				for i=1:size(md1.stressbalance.vertex_pairing,1);
+					md2.stressbalance.vertex_pairing(i,:)=Pnode(md1.stressbalance.vertex_pairing(i,:));
+				end
+				md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing(find(md2.stressbalance.vertex_pairing(:,1)),:);
+			end
+			if ~isnan(md2.masstransport.vertex_pairing),
+				for i=1:size(md1.masstransport.vertex_pairing,1);
+					md2.masstransport.vertex_pairing(i,:)=Pnode(md1.masstransport.vertex_pairing(i,:));
+				end
+				md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing(find(md2.masstransport.vertex_pairing(:,1)),:);
+			end
+
+			%recreate segments
+			if isa(md1.mesh,'mesh2d'),
+				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);
+				segments=contourenvelope(md2);
+				md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(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.stressbalance.spcvx)>1 & numel(md1.stressbalance.spcvy)>2 & numel(md1.stressbalance.spcvz)>2,
+				if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
+					md2.stressbalance.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+					md2.stressbalance.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+				else
+					md2.stressbalance.spcvx(nodestoflag2)=NaN;
+					md2.stressbalance.spcvy(nodestoflag2)=NaN;
+					disp(' ')
+					disp('!! extract warning: spc values should be checked !!')
+					disp(' ')
+				end
+				%put 0 for vz
+				md2.stressbalance.spcvz(nodestoflag2)=0;
+			end
+			if ~isnan(md1.thermal.spctemperature),
+				md2.thermal.spctemperature(nodestoflag2,1)=1;
+			end
+
+			%Results fields
+			if isstruct(md1.results),
+				md2.results=struct();
+				solutionfields=fields(md1.results);
+				for i=1:length(solutionfields),
+					if isstruct(md1.results.(solutionfields{i}))
+						%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
+					else
+						field=md1.results.(solutionfields{i});
+						if length(field)==numberofvertices1,
+							md2.results.(solutionfields{i})=field(pos_node);
+						elseif length(field)==numberofelements1,
+							md2.results.(solutionfields{i})=field(pos_elem);
+						else
+							md2.results.(solutionfields{i})=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 strcmp(md.mesh.domaintype(),'3D')
+				error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+			end
+
+			%Initialize with the 2d mesh
+			mesh2d = md.mesh;
+			md.mesh=mesh3dprisms();
+			md.mesh.x                           = mesh2d.x;
+			md.mesh.y                           = mesh2d.y;
+			md.mesh.elements                    = mesh2d.elements;
+			md.mesh.numberofelements            = mesh2d.numberofelements;
+			md.mesh.numberofvertices            = mesh2d.numberofvertices;
+
+			md.mesh.lat                         = mesh2d.lat;
+			md.mesh.long                        = mesh2d.long;
+			md.mesh.hemisphere                  = mesh2d.hemisphere;
+
+			md.mesh.vertexonboundary            = mesh2d.vertexonboundary;
+			md.mesh.vertexconnectivity          = mesh2d.vertexconnectivity;
+			md.mesh.elementconnectivity         = mesh2d.elementconnectivity;
+			md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity;
+
+			md.mesh.extractedvertices           = mesh2d.extractedvertices;
+			md.mesh.extractedelements           = mesh2d.extractedelements;
+
+			x3d=[]; 
+			y3d=[];
+			z3d=[];  %the lower node is on the bed
+			thickness3d=md.geometry.thickness; %thickness and bed for these nodes
+			bed3d=md.geometry.base;
+
+			%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
+			lowervertex=NaN*ones(number_nodes3d,1);
+			uppervertex=NaN*ones(number_nodes3d,1);
+			lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
+			uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
+			md.mesh.lowervertex=lowervertex;
+			md.mesh.uppervertex=uppervertex;
+
+			%same for lower and upper elements
+			lowerelements=NaN*ones(number_el3d,1);
+			upperelements=NaN*ones(number_el3d,1);
+			lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
+			upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
+			md.mesh.lowerelements=lowerelements;
+			md.mesh.upperelements=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;
+
+			%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.inversion.thickness_obs=project3d(md,'vector',md.inversion.thickness_obs,'type','node');
+			md.surfaceforcings = extrude(md.surfaceforcings,md);
+			md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'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;
+      if ~isnan(md.initialization.watercolumn),md.initialization.watercolumn=project3d(md,'vector',md.initialization.watercolumn,'type','node','layer',1);end;
+      if ~isnan(md.initialization.sediment_head),md.initialization.sediment_head=project3d(md,'vector',md.initialization.sediment_head,'type','node','layer',1);end;
+      if ~isnan(md.initialization.epl_head),md.initialization.epl_head=project3d(md,'vector',md.initialization.epl_head,'type','node','layer',1);end;
+      if ~isnan(md.initialization.epl_thickness),md.initialization.epl_thickness=project3d(md,'vector',md.initialization.epl_thickness,'type','node','layer',1);end;
+
+			%bedinfo and surface info
+			md.mesh.vertexonbase=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.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node');
+			md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node');
+			md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node');
+
+			%boundary conditions
+			md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node');
+			md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node');
+			md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node');
+			md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+			if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+				md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+				if isprop(md.mesh,'vertexonsurface'),
+					pos=find(md.mesh.vertexonsurface);
+					md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+				end
+			end
+			md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node');
+			md.masstransport.calvingrate=project3d(md,'vector',md.masstransport.calvingrate,'type','node');
+			md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
+			md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node');
+			md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node');
+			md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node');
+
+			% Hydrologydc variables
+			if isa(md.hydrology,'hydrologydc');
+				md.hydrology.spcsediment_head=project3d(md,'vector',md.hydrology.spcsediment_head,'type','node','layer',1);
+				md.hydrology.spcepl_head=project3d(md,'vector',md.hydrology.spcepl_head,'type','node','layer',1);
+				md.hydrology.mask_eplactive_node=project3d(md,'vector',md.hydrology.mask_eplactive_node,'type','node','layer',1);
+				md.hydrology.sediment_transmitivity=project3d(md,'vector',md.hydrology.sediment_transmitivity,'type','node','layer',1);
+				md.hydrology.basal_moulin_input=project3d(md,'vector',md.hydrology.basal_moulin_input,'type','node','layer',1);
+	    end
+
+			%connectivity
+			if ~isnan(md.mesh.elementconnectivity)
+				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;
+			end
+
+			%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');
+				
+			%damage
+			md.damage.D=project3d(md,'vector',md.damage.D,'type','node');
+
+			%parameters
+			md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
+			md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+			md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node');
+			md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node');
+			md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
+			md.geometry.base=project3d(md,'vector',md.geometry.base,'type','node');
+			md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
+			md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+			md.mask.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node');
+			md.mask.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node');
+			if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+			if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
+			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
+
+			%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.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1); 
+			md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_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.floatingice_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,'gridonbase'), md.mesh.vertexonbase=structmd.gridonbase; end
+			if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
+			if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
+			if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
+			if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.toolkits=structmd.petscoptions; end
+			if isfield(structmd,'g'), md.constants.g=structmd.g; end
+			if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
+			if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
+			if isfield(structmd,'basal_melting_rate'), md.basalforcings.floatingice_melting_rate=structmd.basal_melting_rate; 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.masstransport.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.masstransport.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'hydrostatic_adjustment'), md.masstransport.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
+			if isfield(structmd,'penalties'), md.masstransport.vertex_pairing=structmd.penalties; end
+			if isfield(structmd,'penalty_offset'), md.masstransport.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
+			if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
+			if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
+			if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
+			if isfield(structmd,'rheology_Z'), md.damage.D=(1-structmd.rheology_Z); 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,'isSIA'), md.flowequation.isSIA=structmd.isSIA; end
+			if isfield(structmd,'isFS'), md.flowequation.isFS=structmd.isFS; end
+			if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
+			if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
+			if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
+			if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
+			if isfield(structmd,'isdiagnostic'), md.transient.isstressbalance=structmd.isdiagnostic; end
+			if isfield(structmd,'isprognostic'), md.transient.ismasstransport=structmd.isprognostic; end
+			if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
+			if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
+			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.base=structmd.bed; end
+			if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
+			if isfield(structmd,'bathymetry'), md.geometry.bed=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,'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,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
+			if isfield(structmd,'nodeonbase'), md.mesh.vertexonbase=structmd.nodeonbase; 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,'diagnostic_ref'), md.stressbalance.referential=structmd.diagnostic_ref; end
+			if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
+			if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
+
+			if isnumeric(md.verbose),
+				md.verbose=verbose;
+			end
+
+			if isfield(structmd,'spcvelocity'), 
+				md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(structmd.spcvelocity(:,1)); md.stressbalance.spcvx(pos)=structmd.spcvelocity(pos,4); 
+				pos=find(structmd.spcvelocity(:,2)); md.stressbalance.spcvy(pos)=structmd.spcvelocity(pos,5); 
+				pos=find(structmd.spcvelocity(:,3)); md.stressbalance.spcvz(pos)=structmd.spcvelocity(pos,6); 
+			end
+			if isfield(structmd,'spcvx'), 
+				md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvx)); md.stressbalance.spcvx(pos)=structmd.spcvx(pos); 
+			end
+			if isfield(structmd,'spcvy'),
+				md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvy)); md.stressbalance.spcvy(pos)=structmd.spcvy(pos);     
+			end
+			if isfield(structmd,'spcvz'),
+				md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvz)); md.stressbalance.spcvz(pos)=structmd.spcvz(pos);     
+			end
+			if isfield(structmd,'pressureload'),
+				if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
+					pos=find(structmd.pressureload(:,end)==120); md.stressbalance.icefront(pos,end)=0;
+					pos=find(structmd.pressureload(:,end)==118); md.stressbalance.icefront(pos,end)=1;
+					pos=find(structmd.pressureload(:,end)==119); md.stressbalance.icefront(pos,end)=2;
+				end
+			end
+			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='AggressiveMigration';  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.masstransport.stabilization=1;
+					md.balancethickness.stabilization=1;
+			end
+			if isnumeric(md.masstransport.hydrostatic_adjustment)
+				if md.masstransport.hydrostatic_adjustment==269,
+					md.masstransport.hydrostatic_adjustment='Incremental';
+				else
+					md.masstransport.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.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+			end
+			if ~isfield(structmd,'loadingforce');
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+
+			%2013 August 9
+			if isfield(structmd,'prognostic') & isa(structmd.prognostic,'prognostic'),
+				disp('Recovering old prognostic class');
+				md.masstransport=masstransport(structmd.prognostic);
+			end
+			%2013 August 9
+			if isfield(structmd,'diagnostic') & (isa(structmd.diagnostic,'diagnostic') || isa(structmd.diagnostic,'stressbalance')),
+				disp('Recovering old diagnostic class');
+				md.stressbalance=stressbalance(structmd.diagnostic);
+			end
+		end% }}}
+		function md = setdefaultparameters(md) % {{{
+
+			%initialize subclasses
+			md.mesh             = mesh2d();
+			md.mask             = mask();
+			md.constants        = constants();
+			md.geometry         = geometry();
+			md.initialization   = initialization();
+			md.surfaceforcings  = SMB();
+			md.basalforcings    = basalforcings();
+			md.friction         = friction();
+			md.rifts            = rifts();
+			md.timestepping     = timestepping();
+			md.groundingline    = groundingline();
+			md.materials        = matice();
+			md.damage           = damage();
+			md.flowequation     = flowequation();
+			md.debug            = debug();
+			md.verbose          = verbose();
+			md.settings         = settings();
+			md.toolkits         = toolkits();
+			md.cluster          = generic();
+			md.balancethickness = balancethickness();
+			md.stressbalance    = stressbalance();
+			md.hydrology        = hydrologyshreve();
+			md.masstransport    = masstransport();
+			md.thermal          = thermal();
+			md.steadystate      = steadystate();
+			md.transient        = transient();
+			md.gia              = gia();
+			md.autodiff         = autodiff();
+			md.flaim            = flaim();
+			md.inversion        = inversion();
+			md.qmu              = qmu();
+			md.radaroverlay     = radaroverlay();
+			md.results          = struct();
+			md.outputdefinition = outputdefinition();
+			md.miscellaneous    = miscellaneous();
+			md.private          = private();
+		end
+		%}}}
+		function md = tetras(md,varargin) % {{{
+			%TETRAS - split 3d prismatic mesh into 3 tetrahedrons
+			%
+			%   Usage:
+			%      md=tetra(md)
+
+			if ~isa(md.mesh,'mesh3dprisms')
+				error('mesh is not a 3d prismatic mesh');
+			end
+
+			%Initialize tetra mesh
+			md.mesh=mesh3dtetras(md.mesh);
+
+			%Subdivision from Philipp Furnstahl (http://studierstube.icg.tugraz.at/thesis/fuernstahl_thesis.pdf)
+			steiner  = 0;
+			nbv      = md.mesh.numberofvertices;
+			nbt      = 3*md.mesh.numberofelements;
+			elements = zeros(nbt,4);
+			for i=1:md.mesh.numberofelements
+				v1=md.mesh.elements(i,1); v2=md.mesh.elements(i,2); v3=md.mesh.elements(i,3);
+				v4=md.mesh.elements(i,4); v5=md.mesh.elements(i,5); v6=md.mesh.elements(i,6);
+				if(min(v2,v4)<min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)<min(v2,v6)),
+					steiner = steiner+1; nbv = nbv+1; nbt = nbt+5; v7 = nbv;
+					md.mesh.x=[md.mesh.x; mean(md.mesh.x(md.mesh.elements(i,:)))];
+					md.mesh.y=[md.mesh.y; mean(md.mesh.y(md.mesh.elements(i,:)))];
+					md.mesh.z=[md.mesh.z; mean(md.mesh.z(md.mesh.elements(i,:)))];
+					elements(3*(i-1)+1,:) = [v1 v2 v3 v7];
+					elements(3*(i-1)+2,:) = [v1 v2 v4 v7];
+					elements(3*(i-1)+3,:) = [v2 v4 v5 v7];
+					elements(end+1,:) = [v2 v3 v5 v7];
+					elements(end+1,:) = [v3 v5 v6 v7];
+					elements(end+1,:) = [v1 v3 v6 v7];
+					elements(end+1,:) = [v1 v4 v6 v7];
+					elements(end+1,:) = [v4 v5 v6 v7];
+				elseif(min(v2,v4)<min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)>min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v2 v4 v6];
+					elements(3*(i-1)+2,:) = [v2 v4 v5 v6];
+					elements(3*(i-1)+3,:) = [v1 v2 v3 v6];
+				elseif(min(v2,v4)<min(v1,v5) & min(v1,v6)>min(v3,v4) & min(v3,v5)<min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v2 v3 v4];
+					elements(3*(i-1)+2,:) = [v2 v3 v4 v5];
+					elements(3*(i-1)+3,:) = [v3 v4 v5 v6];
+				elseif(min(v2,v4)<min(v1,v5) & min(v1,v6)>min(v3,v4) & min(v3,v5)>min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v2 v3 v4];
+					elements(3*(i-1)+2,:) = [v2 v4 v5 v6];
+					elements(3*(i-1)+3,:) = [v2 v3 v4 v6];
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)<min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v4 v5 v6];
+					elements(3*(i-1)+2,:) = [v1 v2 v3 v5];
+					elements(3*(i-1)+3,:) = [v1 v3 v5 v6];
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)>min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v4 v5 v6];
+					elements(3*(i-1)+2,:) = [v1 v2 v5 v6];
+					elements(3*(i-1)+3,:) = [v1 v2 v3 v6];
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)>min(v3,v4) & min(v3,v5)<min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v3 v4 v5];
+					elements(3*(i-1)+2,:) = [v1 v2 v3 v5];
+					elements(3*(i-1)+3,:) = [v3 v4 v5 v6];
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)<min(v2,v6)),
+					elements(3*(i-1)+1,:) = [v1 v5 v6 v4];
+					elements(3*(i-1)+2,:) = [v1 v2 v3 v5];
+					elements(3*(i-1)+3,:) = [v5 v6 v3 v1];
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)>min(v3,v4) & min(v3,v5)>min(v2,v6)),
+					steiner = steiner+1; nbv = nbv+1; nbt = nbt+5; v7 = nbv;
+					md.mesh.x=[md.mesh.x; mean(md.mesh.x(md.mesh.elements(i,:)))];
+					md.mesh.y=[md.mesh.y; mean(md.mesh.y(md.mesh.elements(i,:)))];
+					md.mesh.z=[md.mesh.z; mean(md.mesh.z(md.mesh.elements(i,:)))];
+					elements(3*(i-1)+1,:) = [v1 v2 v3 v7];
+					elements(3*(i-1)+2,:) = [v1 v4 v5 v7];
+					elements(3*(i-1)+3,:) = [v1 v2 v5 v7];
+					elements(end+1,:) = [v2 v5 v6 v7];
+					elements(end+1,:) = [v2 v3 v6 v7];
+					elements(end+1,:) = [v3 v4 v6 v7];
+					elements(end+1,:) = [v1 v3 v4 v7];
+					elements(end+1,:) = [v4 v5 v6 v7];
+				else
+					error('Case not supported'); %not supposed to happen!
+				end
+				%Reorder elements to make sure they are direct
+				for j=1:3
+					element = elements(3*(i-1)+j,:);
+					matrix = [md.mesh.x(element), md.mesh.y(element), md.mesh.z(element), ones(4,1)];
+					if det(matrix)>0,
+						elements(3*(i-1)+j,1)=element(2);
+						elements(3*(i-1)+j,2)=element(1);
+					end
+				end
+			end
+			%%Split in 3 tetras
+			%subelement1 = [1 2 3 5];
+			%subelement2 = [4 6 5 1];
+			%subelement3 = [5 6 3 1];
+			%elements=[md.mesh.elements(:,subelement1);md.mesh.elements(:,subelement2);md.mesh.elements(:,subelement3)];
+			if steiner==0,
+				disp('No Steiner point required to split prismatic mesh into tets');
+			else
+				disp([num2str(steiner) ' Steiner points had to be included'])
+				error('Steiner point not supported yet');
+			end
+
+			pos_elements = repmat([1:md.mesh.numberofelements]',3,1);
+
+			md.mesh.elements=elements;
+			md.mesh.numberofelements=size(elements,1);
+
+			%p and q (same deal, except for element that are on the bedrock: )
+			if ~isnan(md.friction.p),
+				md.friction.p=md.friction.p(pos_elements);
+				md.friction.q=md.friction.q(pos_elements);
+			end
+
+			%elementstype
+			if ~isnan(md.flowequation.element_equation)
+				oldelements_type=md.flowequation.element_equation;
+				md.flowequation.element_equation=md.flowequation.element_equation(pos_elements);
+			end
+
+			%connectivity
+			md.mesh.elementconnectivity=NaN;
+
+			%materials
+			if ~isnan(md.materials.rheology_n),
+				md.materials.rheology_n=md.materials.rheology_n(pos_elements);
+			end
+
+			%increase connectivity if less than 25:
+			if md.mesh.average_vertex_connectivity<=25,
+				md.mesh.average_vertex_connectivity=100;
+			end
+		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','damage'          ,['[1x1 ' class(obj.damage) ']'],'parameters for damage evolution solution'));
+			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','toolkits'          ,['[1x1 ' class(obj.toolkits) ']'],'PETSc options for each solution'));
+			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
+			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
+			disp(sprintf('%19s: %-22s -- %s','stressbalance'      ,['[1x1 ' class(obj.stressbalance) ']'],'parameters for stressbalance solution'));
+			disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
+			disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
+			disp(sprintf('%19s: %-22s -- %s','masstransport'      ,['[1x1 ' class(obj.masstransport) ']'],'parameters for masstransport solution'));
+			disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
+			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
+			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
+			disp(sprintf('%19s: %-22s -- %s','gia'       ,['[1x1 ' class(obj.gia) ']'],'parameters for gia solution'));
+			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
+			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
+			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','outputdefinition',['[1x1 ' class(obj.outputdefinition) ']'],'output definition'));
+			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 % }}}
+		function memory(obj) % {{{
+
+		disp(sprintf('\nMemory imprint:\n'));
+
+		fields=properties('model');
+		mem=0;
+
+		for i=1:length(fields),
+			field=obj.(fields{i});
+			s=whos('field'); 
+			mem=mem+s.bytes/1e6;
+			disp(sprintf('%19s: %6.2f Mb',fields{i},s.bytes/1e6));
+		end
+		disp(sprintf('%19s--%10s','--------------','--------------'));
+		disp(sprintf('%19s: %g Mb','Total',mem));
+		end % }}}
+		function netcdf(obj,filename) % {{{
+		%NETCDF - save model as netcdf
+		%
+		%   Usage:
+		%      netcdf(md,filename)
+		%
+		%   Example:
+		%      netcdf(md,'model.nc');
+
+		disp('Saving model as NetCDF');
+		%1. Create NetCDF file
+		ncid=netcdf.create(filename,'CLOBBER');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Conventions','CF-1.4');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['ISSM model (' obj.miscellaneous.name ')']);
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Author',getenv('USER'));
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',datestr(now));
+
+		%Preallocate variable id, needed to write variables in netcdf file
+		var_id=zeros(1000,1);%preallocate
+
+		for step=1:2,
+			counter=0;
+			[var_id,counter]=structtonc(ncid,'md',obj,0,var_id,counter,step);
+			if step==1, netcdf.endDef(ncid); end
+		end
+
+		if counter>1000,
+			warning(['preallocation of var_id need to be updated from ' num2str(1000) ' to ' num2str(counter)]);
+		end
+
+		netcdf.close(ncid)
+		end % }}}
+		function xylim(obj) % {{{
+
+			xlim([min(obj.mesh.x) max(obj.mesh.x)]);
+			ylim([min(obj.mesh.y) max(obj.mesh.y)])
+		end % }}}
+		function md=upload(md) % {{{
+		%the goal of this routine is to upload the model onto a server, and to empty it.
+		%So first, save the model with a unique name and upload the file to the server: 
+		random_part=fix(rand(1)*10000);
+		id=[md.miscellaneous.name '-' regexprep(datestr(now),'[^\w'']','') '-' num2str(random_part)  '-' getenv('USER') '-' oshostname() '.upload']; 
+		eval(['save ' id ' md']);
+
+		%Now, upload the file: 
+		issmscpout(md.settings.upload_server,md.settings.upload_path,md.settings.upload_login,md.settings.upload_port,{id},1);
+
+		%Now, empty this model of everything except settings, and record name of file we just uploaded!
+		settings_back=md.settings;
+		md=model();
+		md.settings=settings_back;
+		md.settings.upload_filename=id;
+
+		%get locally rid of file that was uploaded
+		eval(['delete ' id]);
+
+		end % }}}
+		function md=download(md) % {{{
+
+		%the goal of this routine is to download the internals of the current model from a server, because 
+		%this model is empty, except for the settings which tell us where to go and find this model!
+
+		%Download the file: 
+		issmscpin(md.settings.upload_server, md.settings.upload_login, md.settings.upload_port, md.settings.upload_path, {md.settings.upload_filename});
+
+		name=md.settings.upload_filename;
+
+		%Now, load this model: 
+		md=loadmodel(md.settings.upload_filename);
+
+		%get locally rid of file that was downloaded
+		eval(['delete ' name]);
+
+		end % }}}
+	end
+ end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/model.py	(revision 18231)
@@ -0,0 +1,816 @@
+#module imports {{{
+import numpy
+import copy
+import sys
+from mesh2d import mesh2d
+from mesh3dprisms import mesh3dprisms
+from mask import mask
+from geometry import geometry
+from constants import constants
+from SMB import SMB
+from SMBpdd import SMBpdd
+from SMBgradients import SMBgradients
+from SMBcomponents import SMBcomponents
+from SMBmeltcomponents import SMBmeltcomponents
+from basalforcings import basalforcings
+from matice import matice
+from damage import damage
+from friction import friction
+from flowequation import flowequation
+from timestepping import timestepping
+from initialization import initialization
+from rifts import rifts
+from debug import debug
+from verbose import verbose
+from settings import settings
+from toolkits import toolkits
+from generic import generic
+from balancethickness import balancethickness
+from stressbalance import stressbalance
+from groundingline import groundingline
+from hydrologyshreve import hydrologyshreve
+from masstransport import masstransport
+from thermal import thermal
+from steadystate import steadystate
+from transient import transient
+from gia import gia
+from autodiff import autodiff
+from flaim import flaim
+from inversion import inversion
+from outputdefinition import outputdefinition
+from qmu import qmu
+from results import results
+from radaroverlay import radaroverlay
+from miscellaneous import miscellaneous
+from private import private
+from mumpsoptions import mumpsoptions
+from iluasmoptions import iluasmoptions
+from project3d import project3d
+from project2d import project2d
+from FlagElements import FlagElements
+from NodeConnectivity import NodeConnectivity
+from ElementConnectivity import ElementConnectivity
+from contourenvelope import contourenvelope
+import MatlabFuncs as m
+from DepthAverage import DepthAverage
+#}}}
+
+class model(object):
+	#properties
+	def __init__(self):#{{{
+		self.mesh             = mesh2d()
+		self.mask             = mask()
+		self.geometry         = geometry()
+		self.constants        = constants()
+		self.surfaceforcings  = SMB()
+		self.basalforcings    = basalforcings()
+		self.materials        = matice()
+		self.damage           = damage()
+		self.friction         = friction()
+		self.flowequation     = flowequation()
+		self.timestepping     = timestepping()
+		self.initialization   = initialization()
+		self.rifts            = rifts()
+
+		self.debug            = debug()
+		self.verbose          = verbose()
+		self.settings         = settings()
+		self.toolkits         = toolkits()
+		self.cluster          = generic()
+
+		self.balancethickness = balancethickness()
+		self.stressbalance       = stressbalance()
+		self.groundingline    = groundingline()
+		self.hydrology        = hydrologyshreve()
+		self.masstransport       = masstransport()
+		self.thermal          = thermal()
+		self.steadystate      = steadystate()
+		self.transient        = transient()
+		self.gia              = gia()
+
+		self.autodiff         = autodiff()
+		self.flaim            = flaim()
+		self.inversion        = inversion()
+		self.qmu              = qmu()
+
+		self.results          = results()
+		self.outputdefinition = outputdefinition()
+		self.radaroverlay     = radaroverlay()
+		self.miscellaneous    = miscellaneous()
+		self.private          = private()
+		#}}}
+	def properties(self):    # {{{
+		# ordered list of properties since vars(self) is random
+		return ['mesh',\
+		        'mask',\
+		        'geometry',\
+		        'constants',\
+		        'surfaceforcings',\
+		        'basalforcings',\
+		        'materials',\
+		        'damage',\
+		        'friction',\
+		        'flowequation',\
+		        'timestepping',\
+		        'initialization',\
+		        'rifts',\
+		        'debug',\
+		        'verbose',\
+		        'settings',\
+		        'toolkits',\
+		        'cluster',\
+		        'balancethickness',\
+		        'stressbalance',\
+		        'groundingline',\
+		        'hydrology',\
+		        'masstransport',\
+		        'thermal',\
+		        'steadystate',\
+		        'transient',\
+				  'gia',\
+		        'autodiff',\
+		        'flaim',\
+		        'inversion',\
+		        'qmu',\
+		        'outputdefinition',\
+		        'results',\
+		        'radaroverlay',\
+		        'miscellaneous',\
+		        'private']
+	# }}}
+	def __repr__(obj): #{{{
+		#print "Here %s the number: %d" % ("is", 37)
+		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("surfaceforcings","[%s,%s]" % ("1x1",obj.surfaceforcings.__class__.__name__),"surface forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("damage","[%s,%s]" % ("1x1",obj.damage.__class__.__name__),"damage propagation laws"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("stressbalance","[%s,%s]" % ("1x1",obj.stressbalance.__class__.__name__),"parameters for stressbalance solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("masstransport","[%s,%s]" % ("1x1",obj.masstransport.__class__.__name__),"parameters for masstransport solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("outputdefinition","[%s,%s]" % ("1x1",obj.outputdefinition.__class__.__name__),"output definition"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
+		return string
+	# }}}
+	def checkmessage(self,string):    # {{{
+		print "model not consistent: ", 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: '~HO.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')
+
+		   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,:])-1
+		flag=numpy.ones(md1.mesh.numberofvertices)
+		flag[spc_node]=0
+		pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements-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,:])-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,int)
+		Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
+		Pnode=numpy.zeros(numberofvertices1,int)
+		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]-1]
+		elements_2[:,1]=Pnode[elements_2[:,1]-1]
+		elements_2[:,2]=Pnode[elements_2[:,2]-1]
+		if md1.mesh.__class__.__name__=='mesh3dprisms':
+			elements_2[:,3]=Pnode[elements_2[:,3]-1]
+			elements_2[:,4]=Pnode[elements_2[:,4]-1]
+			elements_2[:,5]=Pnode[elements_2[:,5]-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 m.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.__class__.__name__=='mesh3dprisms':
+			md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.uppervertex==-1))[0]
+			md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos]-1]
+
+			md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowervertex==-1))[0]
+			md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos]-1]
+
+			md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.upperelements==-1))[0]
+			md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos]-1]
+
+			md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowerelements==-1))[0]
+			md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos]-1]
+
+		#Initial 2d mesh 
+		if md1.mesh.__class__.__name__=='mesh3dprisms':
+			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]-1]
+			md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1]-1]
+			md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2]-1]
+
+			md2.mesh.x2d=md1.mesh.x[pos_node_2d]
+			md2.mesh.y2d=md1.mesh.y[pos_node_2d]
+
+		#Edges
+		if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
+			if numpy.ndim(md2.mesh.edges)>1 and numpy.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some numpy.nans...
+				#renumber first two columns
+				pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
+				md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0]-1]
+				md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1]-1]
+				md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2]-1]
+				md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-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.stressbalance.vertex_pairing))):
+			for i in xrange(numpy.size(md1.stressbalance.vertex_pairing,axis=0)):
+				md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]]
+			md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[numpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):
+			for i in xrange(numpy.size(md1.masstransport.vertex_pairing,axis=0)):
+				md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]]
+			md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
+
+		#recreate segments
+		if md1.mesh.__class__.__name__=='mesh2d':
+			[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,bool)
+			md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True
+		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)
+			segments=contourenvelope(md2)
+			md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
+			md2.mesh.vertexonboundary[segments[:,0:2]-1]=True
+			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,:])-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.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:
+			if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
+				md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
+				md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
+			else:
+				md2.stressbalance.spcvx[nodestoflag2]=numpy.nan
+				md2.stressbalance.spcvy[nodestoflag2]=numpy.nan
+				print "\n!! extract warning: spc values should be checked !!\n\n"
+			#put 0 for vz
+			md2.stressbalance.spcvz[nodestoflag2]=0
+		if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
+			md2.thermal.spctemperature[nodestoflag2,0]=1
+
+		#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+1
+		md2.mesh.extractedelements=pos_elem+1
+
+		return md2
+	# }}}
+	def extrude(md,*args):    # {{{
+		"""
+		EXTRUDE - vertically extrude a 2d mesh
+
+		   vertically extrude a 2d mesh and create corresponding 3d mesh.
+		   The vertical distribution can:
+		    - follow a polynomial law
+		    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+		    - be discribed by a list of coefficients (between 0 and 1)
+ 
+
+		   Usage:
+		      md=extrude(md,numlayers,extrusionexponent)
+		      md=extrude(md,numlayers,lowerexponent,upperexponent)
+		      md=extrude(md,listofcoefficients)
+
+		   Example:
+		      md=extrude(md,8,3)
+		      md=extrude(md,8,3,2)
+		      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1])
+
+		   See also: MODELEXTRACT, COLLAPSE
+		"""
+
+		#some checks on list of arguments
+		if len(args)>3 or len(args)<1:
+			raise RuntimeError("extrude error message")
+
+		#Extrude the mesh
+		if   len(args)==1:    #list of coefficients
+			clist=args[0]
+			if any(clist<0) or any(clist>1):
+				raise TypeError("extrusioncoefficients must be between 0 and 1")
+			clist.extend([0.,1.])
+			clist.sort()
+			extrusionlist=list(set(clist))
+			numlayers=len(extrusionlist)
+
+		elif len(args)==2:    #one polynomial law
+			if args[1]<=0:
+				raise TypeError("extrusionexponent must be >=0")
+			numlayers=args[0]
+			extrusionlist=(numpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
+
+		elif len(args)==3:    #two polynomial laws
+			numlayers=args[0]
+			lowerexp=args[1]
+			upperexp=args[2]
+
+			if args[1]<=0 or args[2]<=0:
+				raise TypeError("lower and upper extrusionexponents must be >=0")
+
+			lowerextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
+			upperextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
+			extrusionlist=numpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
+
+		if numlayers<2:
+			raise TypeError("number of layers should be at least 2")
+		if md.mesh.__class__.__name__=='mesh3dprisms':
+			raise TypeError("Cannot extrude a 3d mesh (extrude cannot be called more than once)")
+
+		#Initialize with the 2d mesh
+		mesh2d = md.mesh
+		md.mesh=mesh3dprisms()
+		md.mesh.x                           = mesh2d.x
+		md.mesh.y                           = mesh2d.y
+		md.mesh.elements                    = mesh2d.elements
+		md.mesh.numberofelements            = mesh2d.numberofelements
+		md.mesh.numberofvertices            = mesh2d.numberofvertices
+
+		md.mesh.lat                         = mesh2d.lat
+		md.mesh.long                        = mesh2d.long
+		md.mesh.hemisphere                  = mesh2d.hemisphere
+
+		md.mesh.vertexonboundary            = mesh2d.vertexonboundary
+		md.mesh.vertexconnectivity          = mesh2d.vertexconnectivity
+		md.mesh.elementconnectivity         = mesh2d.elementconnectivity
+		md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity
+
+		md.mesh.extractedvertices           = mesh2d.extractedvertices
+		md.mesh.extractedelements           = mesh2d.extractedelements
+
+		x3d=numpy.empty((0))
+		y3d=numpy.empty((0))
+		z3d=numpy.empty((0))    #the lower node is on the bed
+		thickness3d=md.geometry.thickness    #thickness and bed for these nodes
+		bed3d=md.geometry.base
+
+		#Create the new layers
+		for i in xrange(numlayers):
+			x3d=numpy.concatenate((x3d,md.mesh.x))
+			y3d=numpy.concatenate((y3d,md.mesh.y))
+			#nodes are distributed between bed and surface accordingly to the given exponent
+			z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
+		number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Extrude elements 
+		elements3d=numpy.empty((0,6),int)
+		for i in xrange(numlayers-1):
+			elements3d=numpy.vstack((elements3d,numpy.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices))))    #Create the elements of the 3d mesh for the non extruded part
+		number_el3d=numpy.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Keep a trace of lower and upper nodes
+		lowervertex=-1*numpy.ones(number_nodes3d,int)
+		uppervertex=-1*numpy.ones(number_nodes3d,int)
+		lowervertex[md.mesh.numberofvertices:]=numpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
+		uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=numpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
+		md.mesh.lowervertex=lowervertex
+		md.mesh.uppervertex=uppervertex
+
+		#same for lower and upper elements
+		lowerelements=-1*numpy.ones(number_el3d,int)
+		upperelements=-1*numpy.ones(number_el3d,int)
+		lowerelements[md.mesh.numberofelements:]=numpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
+		upperelements[:(numlayers-2)*md.mesh.numberofelements]=numpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
+		md.mesh.lowerelements=lowerelements
+		md.mesh.upperelements=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
+
+		#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.inversion.thickness_obs=project3d(md,'vector',md.inversion.thickness_obs,'type','node')
+		md.surfaceforcings.extrude(md)
+		md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node')
+
+		#results
+		if not numpy.any(numpy.isnan(md.initialization.vx)):
+			md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vy)):
+			md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vz)):
+			md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vel)):
+			md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.temperature)):
+			md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.waterfraction)):
+			md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.watercolumn)):
+			md.initialization.watercolumn=project3d(md,'vector',md.initialization.watercolumn,'type','node')
+
+
+		#bedinfo and surface info
+		md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
+		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
+
+		#elementstype
+		if not numpy.any(numpy.isnan(md.flowequation.element_equation)):
+			oldelements_type=md.flowequation.element_equation
+			md.flowequation.element_equation=numpy.zeros(number_el3d,int)
+			md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element')
+
+		#verticestype
+		if not numpy.any(numpy.isnan(md.flowequation.vertex_equation)):
+			oldvertices_type=md.flowequation.vertex_equation
+			md.flowequation.vertex_equation=numpy.zeros(number_nodes3d,int)
+			md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node')
+
+		md.flowequation.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node')
+		md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node')
+		md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node')
+
+		#boundary conditions
+		md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node')
+		md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node')
+		md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node')
+		md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',numpy.nan)
+		if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
+			md.thermal.spctemperature=numpy.nan*numpy.ones((md.mesh.numberofvertices,1))
+			if hasattr(md.mesh,'vertexonsurface'):
+				pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+				md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node')
+		md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node')
+		md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node')
+		md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node')
+		md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node')
+		md.masstransport.calvingrate=project3d(md,'vector',md.masstransport.calvingrate,'type','node')
+
+		#connectivity
+		md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
+		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxint-1
+		if not numpy.isnan(md.mesh.elementconnectivity).all():
+			for i in xrange(1,numlayers-1):
+				md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
+						=md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
+				md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=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')
+
+		#damage
+		md.damage.D=project3d(md,'vector',md.damage.D,'type','node')
+
+		#parameters
+		md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node')
+		md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node')
+		md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node')
+		md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node')
+		md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node')
+		md.geometry.base=project3d(md,'vector',md.geometry.base,'type','node')
+		md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node')
+		md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
+		md.mask.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node')
+		md.mask.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.cost_functions_coefficients)):
+			md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.min_parameters)):
+			md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.max_parameters)):
+			md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.qmu.partition)):
+			md.qmu.partition=project3d(md,'vector',numpy.transpose(md.qmu.partition),'type','node')
+
+		#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.reshape(-1,1))
+
+		#special for thermal modeling:
+		md.basalforcings.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1)
+		md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_melting_rate,'type','node','layer',1)
+		if not numpy.any(numpy.isnan(md.basalforcings.geothermalflux)):
+			md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
+
+		#increase connectivity if less than 25:
+		if md.mesh.average_vertex_connectivity<=25:
+			md.mesh.average_vertex_connectivity=100
+
+		return md
+		# }}}
+	def collapse(md): #{{{
+		'''
+		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)
+		'''	
+
+		#Check that the model is really a 3d model
+		if md.mesh.domaintype().lower() != '3d':
+			raise StandardError("only a 3D model can be collapsed")
+		
+		#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 not numpy.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers) 
+		if not numpy.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers) 
+		if not numpy.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers) 
+		if not numpy.isnan(md.inversion.cost_functions_coefficients).all(): md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers) 
+		if md.inversion.min_parameters.size>1: md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers) 
+		if md.inversion.max_parameters.size>1: md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers) 
+		if not numpy.isnan(md.surfaceforcings.mass_balance).all():
+			md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers) 
+		
+		if not numpy.isnan(md.balancethickness.thickening_rate).all(): md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers) 
+
+		#results
+		if not numpy.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx)
+		if not numpy.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy)
+		if not numpy.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz)
+		if not numpy.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
+		if not numpy.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
+
+		#gia
+		if not numpy.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1) 
+		if not numpy.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1) 
+
+		#elementstype
+		if not numpy.isnan(md.flowequation.element_equation).all():
+			md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1)
+			md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1)
+			md.flowequation.borderSSA=project2d(md,md.flowequation.borderSSA,1)
+			md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1)
+			md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1)
+
+		#boundary conditions
+		md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers)
+		md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers)
+		md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers)
+		md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers)
+		md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers)
+		md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers)
+		if not numpy.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
+		md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1)
+
+		#materials
+		md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B)
+		md.materials.rheology_n=project2d(md,md.materials.rheology_n,1)
+		
+		#damage: 
+		if md.damage.isdamage:
+			md.damage.D=DepthAverage(md,md.damage.D)
+
+		#special for thermal modeling:
+		md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1) 
+		md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_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.base=project2d(md,md.geometry.base,1)
+		md.geometry.bed=project2d(md,md.geometry.bed,1)
+		md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1)
+		md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1)
+
+		#lat long
+		if md.mesh.lat.size==md.mesh.numberofvertices:  md.mesh.lat=project2d(md,md.mesh.lat,1) 
+		if md.mesh.long.size==md.mesh.numberofvertices: md.mesh.long=project2d(md,md.mesh.long,1) 
+
+		#Initialize with the 2d mesh
+		mesh=mesh2d()
+		mesh.x=md.mesh.x2d
+		mesh.y=md.mesh.y2d
+		mesh.numberofvertices=md.mesh.numberofvertices2d
+		mesh.numberofelements=md.mesh.numberofelements2d
+		mesh.elements=md.mesh.elements2d
+		if not numpy.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
+		if not numpy.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
+		md.mesh=mesh
+
+		return md
+
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/modellist.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/modellist.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/modellist.m	(revision 18231)
@@ -0,0 +1,385 @@
+%MODELLIST class definition
+%
+%   Usage:
+%      modellist=modellist({md1 md2 md3});
+
+classdef modellist
+	properties (SetAccess=public) 
+		models  = cell(0,1);
+		cluster = generic();
+	end
+	methods
+		function md_list=modelsextract(md,flags,minel,varargin) % {{{
+			%modelsextract - extract several self contained models according to a list of element flags.
+			%
+			%   The difference between this routine and the modelextract.m routine (without an 's') is that 
+			%   as many models are extracted as there are closed contours defined in area. 
+			%   This routine is needed for example when doing data assimilation of ice shelves in Antarctica. 
+			%   Many independent ice shelves are present, and we don't want data assimilation on one ice shelf 
+			%   to be hindered by another totally independent ice shelf.
+			%
+			%   Usage:
+			%      md_list=modelsextract(md,elementfalgs,minel);
+			%
+			%   Examples:
+			%      md_list=modelsextract(md...,,1000);
+			%
+			%   See also: EXTRUDE, COLLAPSE, MODELEXTRACT
+
+			disp('selecting pools of elements');
+			%go through flags and build as many independent element flags as there are groups of connected 1s
+			%in flags.
+
+			%2D or 3D?
+			if dimension(md.mesh)==3,
+				numberofelements=md.mesh.numberofelements2d; %this will be forgotten when we get out.
+				flags=project2d(md,flags,1);
+			else
+				numberofelements=md.mesh.numberofelements;
+			end
+
+			%recover extra arguments: 
+			distance=0;
+			if nargin==4,
+				distance=varargin{1};
+			end
+
+			flag_list=cell(0,1);
+
+			for i=1:size(flags,1),
+
+				if (flags(i)),
+
+					%ok, we are sure element i is part of a new pool.
+					pool=zeros(numberofelements,1);
+					pool=PropagateFlagsFromConnectivity(md.mesh.elementconnectivity,pool,i,flags);
+					flag_list{end+1,1}=pool;
+
+					%speed up rest of computation by taking pool out of flags: 
+					pos=find(pool);flags(pos)=0;
+
+				end
+			end
+
+			%go through flag_list and discard any pool of less than minel elements: 
+			ex_pos=[];
+			for i=1:length(flag_list),
+				if length(find(flag_list{i}))<minel,
+					ex_pos=[ex_pos; i];
+				end
+			end
+			flag_list(ex_pos)=[];
+
+			%now, if distance was specified, expand the flag_list by distance km: 
+			if distance,
+				for i=1:length(flag_list),
+					flag_list{i}=PropagateFlagsUntilDistance(md,flag_list{i},distance);
+				end
+			end
+
+			%now, go use the pools of flags to extract models: 
+			disp(['extracting ' num2str(size(flag_list,1)) ' models']);
+			models=cell(0,1);
+
+			for i=1:size(flag_list,1),
+				disp(['   ' num2str(i) '/' num2str(size(flag_list,1))]);
+				if dimension(md.mesh)==3,
+					flags2d=flag_list{i};
+					realflags=project3d(md,flags2d,'element');
+				else
+					realflags=flag_list{i};
+				end
+				models{end+1,1}=modelextract(md,realflags);
+			end
+
+			%return model list
+			md_list=modellist(models);
+
+		end %end of this function }}}
+		function md_list=modelsextractfromdomains(md,directory) % {{{
+			%modelsextractfromdomains- extract several self contained models according to a list of domains
+			%
+			%   Usage:
+			%      md_list=modelsextractfromdomains(md,'Basins/');
+			%
+			%   Examples:
+			%      md_list=modelsextract(md,'Basins/');
+			%
+			%   See also: MODELSEXTRACTS, MODELEXTRACT
+
+			%go into directory and get list of files.
+			cd(directory);
+			basins=listfiles;
+			cd ..
+
+			models=cell(0,1);
+			for i=1:length(basins),
+				models{end+1,1}=modelextract(md,[directory '/' basins{i}]);
+			end
+
+			%return model list: 
+			md_list=modellist(models);
+
+		end % }}}
+		function obj = modellist(varargin) % {{{
+
+			%initialize list
+			if nargin==0,
+				%Do nothing,
+			elseif nargin==1,
+				if ~isa(varargin{1},'cell'),
+					error('not supported yet');
+				end
+
+				celllist=varargin{1};
+
+				%check on size of cell list: 
+				if (size(celllist,2)~=1),
+					error('modellist constructor error message: list of models should be a cell list of column size 1');
+				end
+
+				%check that only models are in the celllist: 
+				for i=1:size(celllist,1),
+					if ~isa(celllist{i},'model')
+						error(['modellist constructor error message: element ' num2str(i) ' of cell list is not a model!']);
+					end
+				end
+
+				obj.models  = celllist;
+				obj.cluster = obj.models{1}.cluster;
+			end
+		end % }}}
+		function val = get(obj, propName)% {{{
+		%GET - gets model propertie from a specified object ans returns the value
+		% 
+		%   Usage:
+		%      val = get(a, propName)
+
+			switch propName
+				case 'numberofelements'
+					val = obj.numberofelements;
+				case 'numberofnodes'
+					val = obj.numberofnodes;
+				case 'elements' 
+					val = obj.elements;
+				case 'x' 
+					val = obj.x;
+				case 'y' 
+					val = obj.y;
+				case 'z' 
+					val = obj.z;
+				otherwise
+					error(['get error message: ' propName,' is not a valid model property'])
+			end
+		end % }}}
+		function obj = loadmultipleresultsfromcluster(obj) % {{{
+			%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
+			%
+			%   Usage:
+			%      obj=loadresultsfromcluster(obj);
+
+			nummodels=length(obj.models);
+
+			%Get cluster settings
+			cluster=obj.cluster;
+			name=obj.name;
+			cluster_rc_location=which('cluster.rc');
+			[codepath,executionpath]=ClusterParameters(cluster,cluster_rc_location);
+
+			%Remote tar: 
+			disp('tarring results');
+			issmssh(cluster,['"cd ' executionpath '/' name ' && rm -rf file_list.txt ModelResults.tar.gz && find -iname ''*-*vs*.outbin'' > file_list.txt && tar zcvf ModelResults.tar.gz --files-from file_list.txt  && rm -rf file_list.txt "']);
+
+			%copy results from cluster to present directory
+			scpin(cluster, [executionpath '/' name], {'ModelResults.tar.gz'});
+
+			%untar:
+			!tar -zxvf ModelResults.tar.gz
+
+			%ok, go through list and load results from disk: 
+			for i=1:nummodels,
+				%load  results for this model
+				obj.models{i}=loadresultsfromdisk(obj.models{i},[name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
+
+				delete([name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
+			end
+
+			%erase files 
+			delete('ModelResults.tar.gz');
+		end % }}}
+		function obj = solve(obj,varargin)% {{{
+			%SOLVE - apply solution sequence for  a list of models. Used in batch mode.
+			%
+			%   Usage:
+			%      obj=solve(obj,varargin)
+			%      where varargin is a lit of paired arguments. 
+			%      arguments can be: 'analysis_type': 'stressbalance','thermal','masstransport','transient'
+			%
+			%   Examples:
+			%      obj=solve(obj,'analysis_type','stressbalance');
+
+			%recover options
+			options=pairoptions(varargin{:});
+
+			%add default options
+			options=process_solve_options(options);
+
+			%length of list
+			nummodels=length(obj.models);
+
+			%name of queue: to make it unique, add a time stamp
+			name=[obj.name '-' datestr(now,1) '-' datestr(now,'HH-MM-SS') ];
+
+			%name of cluster will be first name of list
+			cluster=obj.cluster;
+
+			%Figure out parameters for this particular cluster
+			cluster_rc_location=which('cluster.rc');
+			[codepath,executionpath]=ClusterParameters(cluster,cluster_rc_location);
+
+			%solve in batch mode: 
+			for i=1:nummodels,
+
+				%model
+				mdex=obj.models{i};
+
+				%recover some fields
+				mdex.analysis_type=options.analysis_type;
+
+				mdex.name=[name '-' num2str(i) 'vs' num2str(nummodels)];
+				mdex.time=obj.time;
+				mdex.queue=obj.queue;
+				mdex.cluster=obj.cluster;
+				if ~isnan(obj.np),
+					mdex.np=obj.np;
+				end
+
+				%call solve in batch mode:
+				if strcmpi(cluster,oshostname),
+					mdex=solve(mdex,varargin{:});
+				else
+					mdex=solve(mdex,varargin{:},'batch','yes','directory',name);
+				end
+
+				%feed back
+				obj.models{i}=mdex;
+			end
+
+			%locally, we are done.
+			if strcmpi(cluster,oshostname),
+				return
+			end
+
+			%now, tar all the files and then erase them.
+			eval(['!find -iname ''' name '-*'' > file_list.txt']);
+			!tar zcvf ModelList.tar.gz --files-from file_list.txt
+			!rm -rf *.bin *.queue file_list.txt
+
+			%still have to build a launching script.
+			BuildMultipleQueueingScript(cluster,name,executionpath,codepath);
+
+			%launch jobs on remote cluster
+			LaunchMultipleQueueJob(cluster,name,executionpath);
+
+			%erase files: 
+			delete([name '.queue']);
+			delete('ModelList.tar.gz');
+
+			%save name: 
+			obj.name=name;
+		end % }}}
+	end
+end
+
+function BuildMultipleQueueingScript(cluster,name,executionpath,codepath)% {{{
+%BUILDMULTIPLEQUEUEINGSCRIPT - 
+%
+%   Usage:
+%      BuildMultipleQueueingScript(executionpath,codepath)
+
+disp('building queueing script');
+
+%First try and figure out if there is a special script for this particular cluster
+function_name=['BuildMultipleQueueingScript' cluster]
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='BuildMultipleQueueingScriptgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(name,executionpath,codepath);']);
+else
+	%Call the generic BuildQueueingScript:
+	BuildMultipleQueueingScriptGeneric(name,executionpath,codepath);
+end
+end % }}}
+function BuildQueueingScriptgemini(name,executionpath,codepath)% {{{
+%BUILDQUEUEINGSCRIPTGEMINI - ...
+%
+%   Usage:
+%      BuildQueueingScriptgemini(md,executionpath,codepath)
+
+scriptname=[name '.queue'];
+
+fid=fopen(scriptname,'w');
+if fid==-1,
+	error(['BuildQueueingScriptgeminierror message: could not open ' scriptname ' file for ascii writing']);
+end
+
+fprintf(fid,'#!/bin/sh\n');
+fprintf(fid,'cd %s\n',executionpath);
+fprintf(fid,'mkdir %s\n',name);
+fprintf(fid,'cd %s\n',name);
+fprintf(fid,'mv ../ModelList.tar.gz ./\n');
+fprintf(fid,'tar -zxvf ModelList.tar.gz\n');
+fprintf(fid,'foreach i (%s-*vs*.queue)\n',name);
+fprintf(fid,'qsub $i\n');
+fprintf(fid,'end\n');
+fclose(fid);
+end% }}}
+function LaunchMultipleQueueJob(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOB - ...
+%
+%   Usage:
+%      LaunchMultipleQueueJob(executionpath)
+
+%First try and figure out if there is a special script for thie particular cluster
+function_name=['LaunchMultipleQueueJob' cluster]
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='LaunchMultipleQueueJobgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(cluster,name,executionpath);']);
+else
+	%Call the generic LaunchMultipleQueueJob:
+	LaunchMultipleQueueJobGeneric(cluster,name,executionpath);
+end
+end% }}}
+function md=LaunchMultipleQueueJobgemini(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOBGEMINI - Launch multiple queueing script on Gemini cluster
+%
+%   Usage:
+%      LaunchMultipleQueueJobgemini(cluster,name,executionpath)
+
+%first, check we have the binary file and the queueing script
+if ~exist([ name '.queue'],'file'),
+	error('LaunchMultipleQueueJobgemini error message: queueing script issing, cannot go forward');
+end
+
+if ~exist('ModelList.tar.gz','file'),
+	error('LaunchMultipleQueueJobgemini error message: inputs models file missing, cannot go forward');
+end
+
+%upload both files to cluster
+disp('uploading input file,  queueing script and variables script');
+eval(['!scp ModelList.tar.gz ' name '.queue '  cluster ':' executionpath]);
+
+disp('launching solution sequence on remote cluster');
+issmssh(cluster,login,['"cd ' executionpath ' && source ' name '.queue "']);
+end% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/README	(revision 18231)
@@ -0,0 +1,4 @@
+We put here all old classes so that matlab can still load old models
+When an object is renamed or deleted, matlab is not able to load it
+anymore. We keep it here so that matlab can load the object (just remove all
+methods)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/diagnostic.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/diagnostic.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/diagnostic.m	(revision 18231)
@@ -0,0 +1,28 @@
+%DIAGNOSTIC class definition
+%
+%   Usage:
+%      diagnostic=diagnostic();
+
+classdef diagnostic
+	properties (SetAccess=public) 
+		spcvx                    = NaN;
+		spcvy                    = NaN;
+		spcvz                    = NaN;
+		restol                   = 0;
+		reltol                   = 0;
+		abstol                   = 0;
+		isnewton                 = 0;
+		FSreconditioning     = 0;
+		viscosity_overshoot      = 0;
+		icefront                 = NaN;
+		maxiter                  = 0;
+		shelf_dampening          = 0;
+		vertex_pairing           = NaN;
+		penalty_factor           = NaN;
+		rift_penalty_lock        = NaN;
+		rift_penalty_threshold   = 0;
+		referential              = NaN;
+		loadingforce             = NaN;
+		requested_outputs        = NaN;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/hydrology.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/hydrology.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/hydrology.m	(revision 18231)
@@ -0,0 +1,16 @@
+%HYDROLOGY class definition
+%
+%   Usage:
+%      hydrology=hydrology();
+
+classdef hydrology
+	properties (SetAccess=public) 
+		spcwatercolumn = NaN;
+		n              = 0;
+		CR             = 0;
+		p              = 0;
+		q              = 0;
+		kn             = 0;
+		stabilization  = 0;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/materials.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/materials.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/materials.m	(revision 18231)
@@ -0,0 +1,21 @@
+%OLD materials class definition
+
+classdef materials
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_Z   = NaN;
+		rheology_law = '';
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/mesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/mesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/mesh.m	(revision 18231)
@@ -0,0 +1,43 @@
+classdef mesh
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN
+		elements                    = NaN
+		dimension                   = 0;
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN
+		long                        = NaN
+		hemisphere                  = NaN
+
+		elementonbed                = NaN
+		elementonsurface            = NaN
+		vertexonbed                 = NaN
+		vertexonsurface             = NaN
+		lowerelements               = NaN
+		lowervertex                 = NaN
+		upperelements               = NaN
+		uppervertex                 = NaN
+		vertexonboundary            = NaN
+
+		edges                       = NaN
+		segments                    = NaN
+		segmentmarkers              = NaN
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+
+		x2d                         = NaN
+		y2d                         = NaN
+		elements2d                  = NaN
+		numberofvertices2d          = 0;
+		numberofelements2d          = 0;
+
+		extractedvertices           = NaN
+		extractedelements           = NaN
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/prognostic.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/prognostic.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/prognostic.m	(revision 18231)
@@ -0,0 +1,16 @@
+%MASSTRANSPORT class definition
+%
+%   Usage:
+%      prognostic=prognostic();
+
+classdef prognostic
+	properties (SetAccess=public) 
+		 spcthickness           = NaN;
+		 min_thickness          = 0;
+		 hydrostatic_adjustment = 0;
+		 stabilization          = 0;
+		 vertex_pairing         = NaN;
+		 penalty_factor         = 0;
+		 requested_outputs      = NaN;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/surfaceforcings.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/surfaceforcings.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/oldclasses/surfaceforcings.m	(revision 18231)
@@ -0,0 +1,26 @@
+%SURFACEFORCING Class definition
+%
+%   Usage:
+%      surfaceforcings=surfaceforcings();
+
+classdef surfaceforcings
+	properties (SetAccess=public) 
+		precipitation             = NaN;
+		mass_balance              = NaN;
+		ispdd                     = 0;
+		issmbgradients            = 0;
+		isdelta18o                = 0;
+		href                      = NaN;
+		smbref                    = NaN;
+		b_pos                     = NaN;
+		b_neg                     = NaN;
+		monthlytemperatures       = NaN;
+		delta18o                  = NaN;
+		delta18o_surface          = NaN;
+		temperatures_presentday   = NaN;
+		temperatures_lgm          = NaN;
+		precipitations_presentday = NaN;
+		desfac                    = 0.5;
+		s0p                       = 0;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.m	(revision 18231)
@@ -0,0 +1,252 @@
+%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
+
+classdef organizer < handle
+    properties (SetAccess=private) 
+		% {{{
+		currentstep   =0;
+	end
+    properties (SetAccess=public) 
+		repository    ='./';
+		prefix        ='model.';
+		trunkprefix   ='';
+		steps         =[];
+		requestedsteps=[0];
+		upload_server='';
+		upload_path='';
+		upload_login='';
+		upload_port=0;
+		download=0;
+		%}}}
+	end
+	methods
+		function org=organizer(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 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 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
+
+			%Get upload information, if provided
+			org.upload_server=getfieldvalue(options,'upload_server','');
+			org.upload_path=getfieldvalue(options,'upload_path','');
+			org.upload_login=getfieldvalue(options,'upload_login','');
+			org.upload_port=getfieldvalue(options,'upload_port',0);
+			org.download=getfieldvalue(options,'download',0);
+
+		end
+		%}}}
+		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
+			if isempty(org.upload_server),
+				disp('   no upload info');
+			else
+				disp(sprintf('   upload_server:     ''%s''',org.upload_server));
+				disp(sprintf('   upload_login:     ''%s''',org.upload_login));
+				disp(sprintf('   upload_path:     ''%s''',org.upload_path));
+				disp(sprintf('   upload_port:     ''%i''',org.upload_port));
+			end
+		end
+		%}}}
+		function md=load(org,string),% {{{
+
+			%Get model path
+			if ~ischar(string), error('argument provided is not a string'); end
+			path=[org.repository '/' org.prefix string];
+
+			%figure out if the model is there
+			if exist(path,'file'),
+				path=path;
+			elseif exist([path '.mat'],'file'),
+				path=[path '.mat'];
+			else
+				error(['Could not find ' path ]);
+			end
+
+			struc=load(path,'-mat');
+			name=char(fieldnames(struc));
+			md=struc.(name);
+			if nargout,
+				varargout{1}=md;
+			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];
+
+			%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 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 loaddata(org,string),% {{{
+
+			%Get model path
+			if ~ischar(string), error('argument provided is not a string'); end
+			path=[org.repository '/' org.prefix string];
+
+			%figure out if the data is there, otherwise, we have to use the default path supplied by user.
+			if exist(path,'file') | exist([path '.mat'],'file'),
+				evalin('caller',['load -mat ' path]);
+				return;
+			end
+
+			%If we are here, the data 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]);
+					evalin('caller',['load -mat ' path2]);
+					return;
+				end
+			else
+				error(['Could not find ' path ]);
+			end
+		end%}}}
+		function bool=perform(org,string) % {{{
+
+			bool=false;
+
+			%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
+
+			%Add step
+			org.steps(end+1).id=length(org.steps)+1;
+			org.steps(end).string=string;
+			org.currentstep=org.currentstep+1;
+
+			%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
+
+			%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
+
+			%But if download is requested, we are downloading and skipping the step: 
+			if ismember(org.currentstep,org.requestedsteps) & org.download,
+				%load the model if it exists, and download
+				name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
+				if exist(name,'file'),
+					md=loadmodel(name); 
+					if isa(md,'model'),
+						if ~isempty(md.settings.upload_filename),
+							disp(sprintf('   downloading model'));
+							md=download(md);
+							save(name,'md','-v7.3');
+						end
+					end
+				end
+
+				%reset bool to false, so we stick with only downloading
+				bool=false;
+			end
+
+		end%}}}
+		function savemodel(org,md) % {{{
+
+			%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
+
+			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%}}}
+		function savedata(org,varargin) % {{{
+
+			%check
+			if (org.currentstep==0), error('Cannot save data because organizer (org) is empty! Make sure you did not skip any perform call'); end
+			if (org.currentstep>length(org.steps)), error('Cannot save data because organizer (org) is not up to date!'); end
+
+			name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
+			disp(['saving data in: ' name]);
+
+			%check that md is a model
+			if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
+
+			%list of variable names: 
+			variables='';
+			for i=2:nargin, 
+				variables=[variables ',' '''' inputname(i) ''''];
+				eval([inputname(i) '= varargin{' num2str(i-1) '};']);
+			end
+			eval(['save(''' name '''' variables ',''-v7.3'');']);
+		end%}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/organizer.py	(revision 18231)
@@ -0,0 +1,172 @@
+import os.path
+from collections import OrderedDict
+import pairoptions
+from loadvars import loadvars
+from loadmodel import loadmodel
+from savevars import savevars
+from model import model
+from whichdb import whichdb
+import MatlabFuncs as m
+
+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.pairoptions(*args)
+
+		#Get prefix
+		prefix=options.getfieldvalue('prefix','model.')
+		if not isinstance(prefix,(str,unicode)):
+			raise TypeError("prefix is not a string")
+		if not m.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 m.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+'.step#'+string+'.python')
+
+		#figure out if the model is there, otherwise, we have to use the default path supplied by user.
+		if whichdb(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 m.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+'.step#'+self.steps[self._currentstep-1]['string']+'.python')
+		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/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.m	(revision 18231)
@@ -0,0 +1,61 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      outputdefinition=outputdefinition();
+
+classdef outputdefinition
+	properties (SetAccess=public) 
+		definitions                 = {};
+	end
+	methods
+	   function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- outputdefinition -->\n');            
+                    
+            % outputdefinition solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="outputdefinition">','<section name="outputdefinition" />');                    
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="definitions" type="',class(obj.definitions),'" default="',convert2str(obj.definitions),'">','     <section name="outputdefinition" />','     <help> list of potential outputs that can be requested, but which need additional data to be defined </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = outputdefinition(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			obj.definitions={};
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','outputdefinition.definitions','cell',1);
+
+			for i=1:length(obj.definitions),
+				md=checkconsistency(obj.definitions{i},md,solution,analyses);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   outputdefinition:'));
+			fielddisplay(obj,'definitions','list of potential outputs that can be requested, but which need additional data to be defined');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+		enums=zeros(length(obj.definitions),1);
+		for i=1:length(obj.definitions),
+			obj.definitions{i}.marshall(md,fid);
+			classdefinition=class(obj.definitions{i});
+			classdefinition(1)=upper(classdefinition(1)); %so it matches our enums definitions.
+			enums(i)=StringToEnum(classdefinition);
+		end
+		enums=unique(enums);
+		
+		WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/outputdefinition.py	(revision 18231)
@@ -0,0 +1,49 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+import numpy as npy
+
+class outputdefinition(object):
+	"""
+	OUTPUTDEFINITION class definition
+
+	   Usage:
+	      outputdefinition=outputdefinition();
+	"""
+
+	def __init__(self): # {{{
+		self.definitions                   = []
+		#}}}
+	def __repr__(self): # {{{
+		string="   Outputdefinitions:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"definitions","list of potential outputs that can be requested, but which need additional data to be defined"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		md = checkfield(md,'fieldname','outputdefinition.definitions','cell',1)
+		for definition in self.definitions:
+			definition.checkconsistency(md,solution,analyses);
+
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		
+		enums=npy.zeros(len(self.definitions),)
+		
+		for i in range(len(self.definitions)):
+			self.definitions[i].marshall(md,fid);
+			classdefinition=self.definitions[i].__class__.__name__
+			classdefinition=classdefinition[0].upper()+classdefinition[1:]
+			enums[i]=StringToEnum(classdefinition)[0]
+		
+		enums=npy.unique(enums);
+		
+		WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1);
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.m	(revision 18231)
@@ -0,0 +1,265 @@
+%PAIROPTIONS class definition
+%
+%   Usage:
+%      pairoptions=pairoptions();
+%      pairoptions=pairoptions('module',true,'solver',false);
+
+classdef pairoptions < handle
+	properties (SetAccess = private,GetAccess = private) 
+		functionname = '';
+		list         = cell(0,3);
+	end
+	methods
+		function obj = pairoptions(varargin) % {{{
+
+			%get calling function name
+			a=dbstack;
+			if length(a)>1,
+				obj.functionname=a(2).file(1:end-2);
+			else
+				obj.functionname='';
+			end
+
+			%initialize list
+			if nargin==0,
+				%Do nothing,
+			else
+				obj=buildlist(obj,varargin{:});
+			end
+		end % }}}
+		function obj = buildlist(obj,varargin) % {{{
+		%BUILDLIST - build list of obj from input
+
+			%check length of input
+			if mod((nargin-1),2),
+				error('Invalid parameter/value pair arguments') 
+			end
+			numoptions = (nargin-1)/2;
+
+			%Allocate memory
+			obj.list=cell(numoptions,3);
+
+			%go through varargin and build list of obj
+			for i=1:numoptions,
+				if ischar(varargin{2*i-1}),
+					obj.list{i,1}=varargin{2*i-1};
+					obj.list{i,2}=varargin{2*i};
+					obj.list{i,3}=false; %used?
+				else
+					%option is not a string, ignore it
+					disp(['WARNING: option number ' num2str(i) ' is not a string, it will be ignored']);
+					obj.list(i,:)=[];
+					continue
+				end
+			end
+		end % }}}
+		function obj = addfield(obj,field,value) % {{{
+			if ischar(field),
+				obj.list{end+1,1} = field;
+				obj.list{end,2}   = value;
+				obj.list{end,3}   = false;
+			end
+		end % }}}
+		function obj = addfielddefault(obj,field,value) % {{{
+		%ADDFIELDDEFAULT - add a field to an options list if it does not exist
+			if ischar(field),
+				if ~exist(obj,field),
+					obj.list{end+1,1} = field;
+					obj.list{end,2}   = value;
+					obj.list{end,3}   = true;  %It is a default so user will not be notified if not used
+				end
+			end
+		end % }}}
+		function obj2 = AssignObjectFields(options,obj2) % {{{
+		%ASSIGNOBJECTFIELDS - assign object fields from options
+			listproperties=properties(obj2);
+			for i=1:size(options.list,1),
+				fieldname=options.list{i,1};
+				fieldvalue=options.list{i,2};
+				if ismember(fieldname,listproperties),
+					obj2.(fieldname)=fieldvalue;
+				else
+					disp(['WARNING: ''' fieldname ''' is not a property of ''' class(obj2) '''']);
+				end
+			end
+		end % }}}
+		function obj = changefieldvalue(obj,field,newvalue) % {{{
+		%CHANGEOPTIONVALUE - change the value of an option in an option list
+
+			%track occurrence of field
+			lines=find(strcmpi(obj.list(:,1),field));
+
+			%replace value
+			if isempty(lines),
+				%add new field if not found
+				obj=addfield(obj,field,newvalue);
+				obj.list{end,3}=true; % do not notify user if unused
+			else
+				for i=1:length(lines),
+					obj.list{lines(i),2}=newvalue;
+				end
+			end
+		end % }}}
+		function obj = deleteduplicates(obj,warn) % {{{
+		%DELETEDUPLICATES - delete duplicates in an option list
+
+			%track the first occurrence of each option
+			[dummy lines]=unique(obj.list(:,1),'first');
+			clear dummy
+
+			%warn user if requested
+			if warn,
+				numoptions=size(obj.list,1);
+				for i=1:numoptions,
+					if ~ismember(i,lines),
+						disp(['WARNING: option ' obj.list{i,1} ' appeared more than once. Only its first occurrence will be kept'])
+					end
+				end
+			end
+
+			%remove duplicates from the options list
+			obj.list=obj.list(lines,:);
+		end % }}}
+		function displayunused(obj) % {{{
+			%DISPLAYUNUSED - display unused options
+
+			numoptions=size(obj.list,1);
+			for i=1:numoptions,
+				if ~obj.list{i,3},
+					disp(['WARNING: option ' obj.list{i,1} ' was not used'])
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   functionname: %s',obj.functionname));
+			if ~isempty(obj.list),
+				disp(sprintf('   list: (%ix%i)\n',size(obj.list,1),size(obj.list,2)));
+				for i=1:size(obj.list,1),
+					if ischar(obj.list{i,2}),
+						disp(sprintf('     field: %-10s value: ''%s''',obj.list{i,1},obj.list{i,2}));
+					elseif isnumeric(obj.list{i,2}) & length(obj.list{i,2})==1,
+						disp(sprintf('     field: %-10s value: %g',obj.list{i,1},obj.list{i,2}));
+					elseif isnumeric(obj.list{i,2}) & length(obj.list{i,2})==2,
+						disp(sprintf('     field: %-10s value: [%g %g]',obj.list{i,1},obj.list{i,2}));
+					else
+						disp(sprintf('     field: %-10s value: (%ix%i)',obj.list{i,1},size(obj.list{i,2},1),size(obj.list{i,2},2)));
+					end
+				end
+			else
+				disp(sprintf('   list: empty'));
+			end
+		end % }}}
+		function bool = exist(obj,field) % {{{
+		%EXIST - check if the option exists
+
+			%some argument checking: 
+			if ((nargin~=2) | (nargout~=1)),
+				error('exist error message: bad usage');
+			end
+			if ~ischar(field),
+				error('exist error message: field should be a string');
+			end
+
+			%Recover option
+			pos=find(strcmpi(field,obj.list(:,1)));
+			if ~isempty(pos),
+				bool=true;
+				obj.list{pos,3}   = true;  %It is a default so user will not be notified if not used
+			else
+				bool=false;
+			end
+		end % }}}
+		function num = fieldoccurrences(obj,field), % {{{
+		%FIELDOCCURRENCES - get number of occurrence of a field
+
+			%check input 
+			if ~ischar(field),
+				error('fieldoccurrences error message: field should be a string');
+			end
+
+			%get number of occurrence
+			num=sum(strcmpi(field,obj.list(:,1)));
+		end % }}}
+		function value = getfieldvalue(obj,field,varargin), % {{{
+		%GETOPTION - get the value of an option
+		%
+		%   Usage:
+		%      value=getfieldvalue(obj,field,varargin)
+		%
+		%   Find an option value from a field. A default option
+		%   can be given in input if the field does not exist
+		%
+		%   Examples:
+		%      value=getfieldvalue(options,'caxis');
+		%      value=getfieldvalue(options,'caxis',[0 2]);
+
+			%some argument checking: 
+			if nargin~=2 && nargin~=3,
+				help getfieldvalue
+				error('getfieldvalue error message: bad usage');
+			end
+
+			if ~ischar(field),
+				error('getfieldvalue error message: field should be a string');
+			end
+
+			%Recover option
+			pos=find(strcmpi(obj.list(:,1),field));
+			if ~isempty(pos),
+				value=obj.list{pos(1),2}; % ignore extra entry
+				obj.list{pos(1),3}=true;  % option used
+				return;
+			end
+
+			%The option has not been found, output default if provided
+			if nargin==3,
+				value=varargin{1};
+			else
+				error(['error message: field ' field ' has not been provided by user (and no default value has been specified)'])
+			end
+		end % }}}
+		function obj = removefield(obj,field,warn)% {{{
+		%REMOVEFIELD - delete a field in an option list
+		%
+		%   Usage:
+		%      obj=removefield(obj,field,warn)
+		%
+		%   if warn==1 display an info message to warn user that
+		%   some of his options have been removed.
+
+			%check is field exist
+			if exist(obj,field),
+
+				%find where the field is located
+				lines=find(~strcmpi(obj.list(:,1),field));
+
+				%remove duplicates from the options list
+				obj.list=obj.list(lines,:);
+
+				%warn user if requested
+				if warn
+					disp(['removefield info: option ' field ' has been removed from the list of options.'])
+				end
+			end
+		end % }}}
+		function marshall(obj,fid,firstindex)% {{{
+
+			for i=1:size(obj.list,1),
+				name  = obj.list{i,1};
+				value = obj.list{i,2};
+
+				%Write option name
+				WriteData(fid,'enum',(firstindex-1)+2*i-1,'data',name,'format','String');
+
+				%Write option value
+				if (isnumeric(value) & numel(value)==1),
+					WriteData(fid,'enum',(firstindex-1)+2*i,'data',value,'format','Double');
+				elseif ischar(value),
+					WriteData(fid,'enum',(firstindex-1)+2*i,'data',value,'format','String');
+				else
+					error(['Cannot marshall option ' name ': format not supported yet']);
+				end
+			end
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/pairoptions.py	(revision 18231)
@@ -0,0 +1,170 @@
+from collections import OrderedDict
+from WriteData import WriteData
+
+class pairoptions(object):
+	"""
+	PAIROPTIONS class definition
+ 
+	   Usage:
+	      pairoptions=pairoptions();
+	      pairoptions=pairoptions('module',true,'solver',false);
+	"""
+
+	def __init__(self,*arg): # {{{
+		self.functionname = ''
+		self.list         = OrderedDict()
+
+		#get calling function name
+		import inspect
+		if len(inspect.stack()) > 1:
+			self.functionname=inspect.stack()[1][3]
+
+		#initialize list
+		if not len(arg):
+			pass    #Do nothing,
+		else:
+			self.buildlist(*arg)
+	# }}}
+	def __repr__(self):    # {{{
+		s="   functionname: '%s'\n" % self.functionname
+		if self.list:
+			s+="   list: (%ix%i)\n\n" % (len(self.list),2)
+			for item in self.list.iteritems():
+				if   isinstance(item[1],(str,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],type(item[1]))
+		else:
+			s+="   list: empty\n"
+		return s
+	# }}}
+	def buildlist(self,*arg):    # {{{
+		"""BUILDLIST - build list of objects from input"""
+
+		#check length of input
+		if len(arg) % 2:
+			raise TypeError('Invalid parameter/value pair arguments') 
+		numoptions = len(arg)/2
+
+		#go through arg and build list of objects
+		for i in xrange(numoptions):
+			if isinstance(arg[2*i],(str,unicode)):
+				self.list[arg[2*i]] = arg[2*i+1];
+			else:
+				#option is not a string, ignore it
+				print "WARNING: option number %d is not a string and will be ignored." % (i+1)
+	# }}}
+	def addfield(self,field,value):    # {{{
+		"""ADDFIELD - add a field to an options list"""
+		if isinstance(field,(str,unicode)):
+			if field in self.list:
+				print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
+			self.list[field] = value
+	# }}}
+	def addfielddefault(self,field,value):    # {{{
+		"""ADDFIELDDEFAULT - add a field to an options list if it does not already exist"""
+		if isinstance(field,(str,unicode)):
+			if field not in self.list:
+				self.list[field] = value
+	# }}}
+	def AssignObjectFields(self,obj2):    # {{{
+		"""ASSIGNOBJECTFIELDS - assign object fields from options"""
+		for item in self.list.iteritems():
+			if item[0] in dir(obj2):
+				setattr(obj2,item[0],item[1])
+			else:
+				print "WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))
+		return obj2
+	# }}}
+	def changefieldvalue(self,field,newvalue):    # {{{
+		"""CHANGEOPTIONVALUE - change the value of an option in an option list"""
+
+		self.list[field]=newvalue;
+	# }}}
+	def exist(self,field):    # {{{
+		"""EXIST - check if the option exist"""
+
+		#some argument checking: 
+		if field == None or field == '':
+			raise ValueError('exist error message: bad usage');
+		if not isinstance(field,(str,unicode)):
+			raise TypeError("exist error message: field '%s' should be a string." % str(field));
+
+		#Recover option
+		if field in self.list:
+			return True
+		else:
+			return False
+	# }}}
+	def getfieldvalue(self,field,default=None):    # {{{
+		"""
+		GETOPTION - get the value of an option
+	
+		Usage:
+		   value=options.getfieldvalue(field,default)
+	 
+		Find an option value from a field. A default option
+		can be given in input if the field does not exist
+	 
+		Examples:
+		   value=options.getfieldvalue(options,'caxis')
+		   value=options.getfieldvalue(options,'caxis',[0 2])
+		"""
+
+		#some argument checking: 
+		if field == None or field == '':
+			raise ValueError('getfieldvalue error message: bad usage');
+		if not isinstance(field,(str,unicode)):
+			raise TypeError("getfieldvalue error message: field '%s' should be a string." % str(field));
+
+		#Recover option
+		if field in self.list:
+			value=self.list[field]
+		else:
+			if not default == None:
+				value=default
+			else:
+				raise KeyError("error message: field '%s' has not been provided by user (and no default value has been specified)." % field)
+
+		return value
+	# }}}
+	def removefield(self,field,warn):    # {{{
+		"""
+		REMOVEFIELD - delete a field in an option list
+	 
+		Usage:
+		   obj=removefield(self,field,warn)
+	 
+		if warn==1 display an info message to warn user that
+		some of his options have been removed.
+		"""
+
+		#check if field exist
+		if field in self.list:
+
+			#remove duplicates from the options list
+			del self.list[field]
+
+			#warn user if requested
+			if warn:
+				print "removefield info: option '%s' has been removed from the list of options." % field
+	# }}}
+	def marshall(self,md,fid,firstindex):    # {{{
+
+		for i,item in enumerate(self.list.iteritems()):
+			name  = item[0]
+			value = item[1]
+
+			#Write option name
+			WriteData(fid,'enum',(firstindex-1)+2*i+1,'data',name,'format','String')
+
+			#Write option value
+			if   isinstance(value,(str,unicode)):
+				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
+			elif isinstance(value,(bool,int,long,float)):
+				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double')
+			else:
+				raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.m	(revision 18231)
@@ -0,0 +1,179 @@
+%PLOTOPTIONS class definition
+%
+%   Usage:
+%      plotoptions = plotoptions(varargin)
+
+classdef plotoptions
+    properties (SetAccess=public) 
+		 % {{{
+		 numberofplots = 0;
+		 figurenumber  = 1;
+		 list          = cell(0,0);
+		 %}}}
+	 end
+	 methods
+		 function opt=plotoptions(varargin) % {{{
+			 opt=buildlist(opt,varargin{:});
+		 end
+		 %}}}
+		 function disp(opt) % {{{
+			 disp(sprintf('\n%s = \n',inputname(1)));
+			 disp(sprintf('   numberofplots: %i',opt.numberofplots));
+			 disp(sprintf('   figurenumber: %i',opt.figurenumber));
+			 if ~isempty(opt.list),
+				 disp(sprintf('   list: (%ix%i)',size(opt.list,1),size(opt.list,2)));
+				 for i=1:size(opt.list,1),
+					 unit=opt.list{i};
+					 disp(sprintf('\n   options of plot number %i',i));
+					 for j=1:size(unit.list,1)
+						 if ischar(unit.list{j,2}),
+							 disp(sprintf('     field: %-10s value: ''%s''',unit.list{j,1},unit.list{j,2}));
+						 elseif isnumeric(unit.list{j,2}) & length(unit.list{j,2})==1,
+							 disp(sprintf('     field: %-10s value: %g',unit.list{j,1},unit.list{j,2}));
+						 else
+							 disp(sprintf('     field: %-10s value: (%ix%i)',unit.list{j,1},size(unit.list{j,2},1),size(unit.list{j,2},2)));
+						 end
+					 end
+				 end
+			 else
+				 disp(sprintf('   list: empty'));
+			 end
+		 end
+		 %}}}
+		 function opt=buildlist(opt,varargin) % {{{
+
+			 %check length of input
+			 if mod((nargin-1),2),
+				 for i=1:2:(nargin-1)
+					 if ~ischar(varargin{i}),
+						 disp(['Last valid option: ' varargin{i-2} ]);
+						 break;
+					 end
+				 end
+				 error('Invalid parameter/value pair arguments')
+			 end
+
+			 %go through varargin and build list (like pairoptions)
+			 rawoptions=pairoptions(varargin{:});
+			 numoptions = (nargin-1)/2;
+			 rawlist=cell(numoptions,2);
+			 counter=1;
+			 for i=1:numoptions,
+				 optionname = varargin{2*i-1};
+				 optionval  = varargin{2*i};
+				 if ischar(optionname),
+					 rawlist{counter,1}=optionname;
+					 rawlist{counter,2}=optionval;
+					 counter=counter+1;
+				 else
+					 %option is not a string, ignore it
+					 disp(['WARNING: option number ' num2str(i) ' is not a string, it will be ignored']);
+					 rawlist(counter,:)=[];
+					 continue
+				 end
+			 end
+
+			 %get number of data to be plotted
+			 numberofplots=fieldoccurrences(rawoptions,'data');
+			 opt.numberofplots=numberofplots;
+
+			 %figure out wether alloptions flog is on
+			 if strcmpi(getfieldvalue(rawoptions,'alloptions','off'),'on'),
+				 allflag=1;
+			 else
+				 allflag=0;
+			 end
+
+			 %initialize opt.list
+			 opt.list=cell(numberofplots,1);
+			 for i=1:numberofplots,
+				 opt.list{i}=pairoptions;
+			 end
+
+			 %process plot options
+			 for i=1:size(rawlist,1),
+
+				 %If alloptions flag has is on, apply to all plots
+				 if (allflag & ~strcmpi(rawlist{i,1},'data') & ~ismember('#',rawlist{i,1})),
+					 for j=1:numberofplots,
+						 opt.list{j}=addfield(opt.list{j},rawlist{i,1},rawlist{i,2});
+					 end
+
+					 %option contains '#'
+				 elseif ismember('#',rawlist{i,1}),
+
+					 %get suplot(s) associated
+					 string=strsplit(rawlist{i,1},'#');
+					 plotnums=string{end};
+					 field=string{1};
+
+					 %divide plotnums if there is a comma ','
+					 plotnums=strsplit_strict(plotnums,',');
+
+					 %loop over plotnums
+					 for k=1:length(plotnums);
+						 plotnum=plotnums{k};
+
+						 %Empty
+						 if isempty(plotnum),
+							 continue;
+
+							 %pound all
+						 elseif strcmpi(plotnum,'all');
+							 for j=1:numberofplots,
+								 opt.list{j}=addfield(opt.list{j},field,rawlist{i,2});
+							 end
+
+							 %pound i-j
+						 elseif ismember('-',plotnum)
+							 nums=strsplit(plotnum,'-');
+							 if length(nums)~=2, continue; end
+							 if ~isnumeric(nums)
+								 error(['the option #i-j is not set properly for ' field]);
+							 end
+							 for j=nums(1):nums(2),
+								 opt.list{j}=addfield(opt.list{j},field,rawlist{i,2});
+							 end
+
+							 %pound i
+						 else
+							 %assign to subplot
+							 if str2num(plotnum)>numberofplots,
+								 error(['opt error message: ' field ' cannot be assigned (' plotnum ' exceed maximum number of plot)']);
+							 end
+							 opt.list{str2num(plotnum)}=addfield(opt.list{str2num(plotnum)},field,rawlist{i,2});
+						 end
+					 end
+
+					 %assign option field to corresponding subplot
+				 else
+
+					 %go through all subplot and assign to the first one free
+					 j=1;
+					 while (j<=numberofplots),
+						 if ~exist(opt.list{j},rawlist{i,1});
+							 opt.list{j}=addfield(opt.list{j},rawlist{i,1},rawlist{i,2});
+							 break
+						 else
+							 j=j+1;
+						 end
+					 end
+					 if j>numberofplots,
+						 disp(['plot info message: too many ''' rawlist{i,1} ''' options']);
+					 end
+				 end
+			 end
+
+			 %check that there is no duplicates
+			 for i=1:numberofplots,
+				 opt.list{i}=deleteduplicates(opt.list{i},1);
+			 end
+
+			 %Get figure number (should be in options for subplot 1)
+			 opt.figurenumber=getfieldvalue(opt.list{1},'figure',1);
+			 removefield(opt.list{1},'figure',0);
+
+		 end
+		 %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/plotoptions.py	(revision 18231)
@@ -0,0 +1,128 @@
+from collections import OrderedDict, Counter, defaultdict
+import pairoptions
+
+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('Invalid parameter/value pair arguments')
+
+		#go through args and build list (like pairoptions)
+		rawoptions=pairoptions.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)
+		rawoptions.removefield('figure',0)
+
+		#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.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/branches/trunk-jpl-ad2-integrated/src/m/classes/private.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/private.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/private.m	(revision 18231)
@@ -0,0 +1,38 @@
+%PRIVATE class definition
+%
+%   Usage:
+%      private=private();
+
+classdef private
+	properties (SetAccess=public) 
+		isconsistent = true;
+		runtimename  = '';
+		bamg         = struct();
+		solution     = '';
+	end
+	methods
+		function obj = private(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   private parameters: do not change'));
+
+			fielddisplay(obj,'isconsistent','is model self consistent');
+			fielddisplay(obj,'runtimename','name of the run launched');
+			fielddisplay(obj,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain');
+			fielddisplay(obj,'solution','type of solution launched');
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/private.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/private.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/private.py	(revision 18231)
@@ -0,0 +1,38 @@
+from collections import OrderedDict
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+
+class private(object):
+	"""
+	PRIVATE class definition
+
+	   Usage:
+	      private=private();
+	"""
+
+	def __init__(self): # {{{
+		self.isconsistent = True
+		self.runtimename  = ''
+		self.bamg         = OrderedDict()
+		self.solution     = ''
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   private parameters: do not change'
+
+		string="%s\n%s"%(string,fielddisplay(self,'isconsistent','is model self consistent'))
+		string="%s\n%s"%(string,fielddisplay(self,'runtimename','name of the run launched'))
+		string="%s\n%s"%(string,fielddisplay(self,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain'))
+		string="%s\n%s"%(string,fielddisplay(self,'solution','type of solution launched'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.m	(revision 18231)
@@ -0,0 +1,191 @@
+%QMU class definition
+%
+%   Usage:
+%      qmu=qmu();
+
+classdef qmu
+	properties (SetAccess=public) 
+		isdakota                    = 0;
+		variables                   = struct();
+		responses                   = struct();
+		method                      = struct();
+		params                      = struct();
+		results                     = struct();
+		partition                   = NaN;
+		numberofpartitions          = 0;
+		numberofresponses           = 0;
+		variabledescriptors         = {};
+		responsedescriptors         = {};
+		mass_flux_profile_directory = NaN;
+		mass_flux_profiles          = NaN;
+		mass_flux_segments          = {};
+		adjacency                   = NaN;
+		vertex_weight               = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- qmu -->\n');            
+                    
+            % qmu solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="qmu parameters">','<section name="qmu" />');                    
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdakota" type="',class(obj.isdakota),'" default="',convert2str(obj.isdakota),'">','     <section name="qmu" />','     <help> is qmu analysis activated? </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variables" type="',class(obj.variables),'" default="',convert2str(obj.variables),'">','     <section name="qmu" />','     <help> (arrays of each variable class) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responses" type="',class(obj.responses),'" default="',convert2str(obj.responses),'">','     <section name="qmu" />','     <help> (arrays of each response class) </help>','  </parameter>');
+                
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofresponses" type="',class(obj.numberofresponses),'" default="',convert2str(obj.numberofresponses),'">','     <section name="qmu" />','     <help> number of responses </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="params" type="',class(obj.params),'" default="',convert2str(obj.params),'">','     <section name="qmu" />','     <help> (array of method-independent parameters)  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="results" type="',class(obj.results),'" default="',convert2str(obj.results),'">','     <section name="qmu" />','     <help> (information from dakota files) </help>','  </parameter>');
+                
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="partition" type="',class(obj.partition),'" default="',convert2str(obj.partition),'">','     <section name="qmu" />','     <help> user provided mesh partitioning, defaults to metis if not specified </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofpartitions" type="',class(obj.numberofpartitions),'" default="',convert2str(obj.numberofpartitions),'">','     <section name="qmu" />','     <help> number of partitions for semi-discrete qmu  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variabledescriptors" type="',class(obj.variabledescriptors),'" default="',convert2str(obj.variabledescriptors),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+            
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responsedescriptors" type="',class(obj.responsedescriptors),'" default="',convert2str(obj.responsedescriptors),'">','     <section name="qmu" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="method" type="',class(obj.method),'" default="',convert2str(obj.method),'">','     <section name="qmu" />','     <help> array of dakota_method class </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profile_directory" type="',class(obj.mass_flux_profile_directory),'" default="',convert2str(obj.mass_flux_profile_directory),'">','     <section name="qmu" />','     <help> directory for mass flux profiles </help>','  </parameter>');
+                
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profiles" type="',class(obj.mass_flux_profiles),'" default="',convert2str(obj.mass_flux_profiles),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_segments" type="',class(obj.mass_flux_segments),'" default="',convert2str(obj.mass_flux_segments),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="adjacency" type="',class(obj.adjacency),'" default="',convert2str(obj.adjacency),'">','     <section name="qmu" />','     <help> additional outputs requested </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertex_weight" type="',class(obj.vertex_weight),'" default="',convert2str(obj.vertex_weight),'">','     <section name="qmu" />','     <help> weight applied to each mesh vertex </help>','  </parameter>');
+            
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}        
+		function obj = qmu(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~md.qmu.isdakota, return; end
+
+			if md.qmu.params.evaluation_concurrency~=1,
+				md = checkmessage(md,['concurrency should be set to 1 when running dakota in library mode']);
+			end
+			if ~isempty(md.qmu.partition),
+				if numel(md.qmu.partition)~=md.mesh.numberofvertices,
+					md = checkmessage(md,['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
+				end
+				if min(md.qmu.partition)~=0,
+					md = checkmessage(md,['partition vector not indexed from 0 on']);
+				end
+				if max(md.qmu.partition)>=md.qmu.numberofpartitions,
+					md = checkmessage(md,['for qmu analysis, partitioning vector cannot go over npart, number of partition areas']);
+				end
+			end
+
+			if ~strcmpi(md.cluster.name,'none'),
+				if md.settings.waitonlock==0,
+					md = checkmessage(md,['waitonlock should be activated when running qmu in parallel mode!']);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   qmu parameters:'));
+
+			fielddisplay(obj,'isdakota','is qmu analysis activated?');
+			for i=1:numel(obj.variables)
+				disp(sprintf('         variables%s:  (arrays of each variable class)',...
+					string_dim(obj.variables,i)));
+				fnames=fieldnames(obj.variables(i));
+				maxlen=0;
+				for j=1:numel(fnames)
+					maxlen=max(maxlen,length(fnames{j}));
+				end
+
+				for j=1:numel(fnames)
+					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
+						fnames{j},size(obj.variables.(fnames{j})),class(obj.variables.(fnames{j}))));
+				end
+			end
+			for i=1:numel(obj.responses)
+				disp(sprintf('         responses%s:  (arrays of each response class)',...
+					string_dim(obj.responses,i)));
+				fnames=fieldnames(obj.responses(i));
+				maxlen=0;
+				for j=1:numel(fnames)
+					maxlen=max(maxlen,length(fnames{j}));
+				end
+
+				for j=1:numel(fnames)
+					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
+						fnames{j},size(obj.responses.(fnames{j})),class(obj.responses.(fnames{j}))));
+				end
+			end
+			fielddisplay(obj,'numberofresponses','number of responses') 
+			for i=1:numel(obj.method);
+				if strcmp(class(obj.method(i)),'dakota_method')
+					disp(sprintf('            method%s :    ''%s''',...
+						string_dim(obj.method,i),obj.method(i).method));
+				end
+			end
+			for i=1:numel(obj.params)
+				disp(sprintf('         params%s:  (array of method-independent parameters)',...
+					string_dim(obj.params,i)));
+				fnames=fieldnames(obj.params(i));
+				maxlen=0;
+				for j=1:numel(fnames)
+					maxlen=max(maxlen,length(fnames{j}));
+				end
+
+				for j=1:numel(fnames)
+					disp(sprintf(['            %-' num2str(maxlen+1) 's: %s'],...
+						fnames{j},any2str(obj.params(i).(fnames{j}))));
+				end
+			end
+			for i=1:numel(obj.results)
+				disp(sprintf('         results%s:  (information from dakota files)',...
+					string_dim(obj.results,i)));
+				fnames=fieldnames(obj.results(i));
+				maxlen=0;
+				for j=1:numel(fnames)
+					maxlen=max(maxlen,length(fnames{j}));
+				end
+
+				for j=1:numel(fnames)
+					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
+						fnames{j},size(obj.results.(fnames{j})),class(obj.results.(fnames{j}))));
+				end
+			end
+			fielddisplay(obj,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+			fielddisplay(obj,'numberofpartitions','number of partitions for semi-discrete qmu') 
+			fielddisplay(obj,'variabledescriptors','');
+			fielddisplay(obj,'responsedescriptors','');
+			fielddisplay(obj,'method','array of dakota_method class');
+			fielddisplay(obj,'mass_flux_profile_directory','directory for mass flux profiles');
+			fielddisplay(obj,'mass_flux_profiles','list of mass_flux profiles');
+			fielddisplay(obj,'mass_flux_segments','');
+			fielddisplay(obj,'adjacency','');
+			fielddisplay(obj,'vertex_weight','weight applied to each mesh vertex');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
+			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');
+			WriteData(fid,'object',obj,'fieldname','numberofresponses','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','variabledescriptors','format','StringArray');
+			WriteData(fid,'object',obj,'fieldname','responsedescriptors','format','StringArray');
+			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
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu.py	(revision 18231)
@@ -0,0 +1,152 @@
+import numpy
+from collections import OrderedDict
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class qmu(object):
+	"""
+	QMU class definition
+
+	   Usage:
+	      qmu=qmu();
+	"""
+
+	def __init__(self): # {{{
+		self.isdakota                    = 0
+		self.variables                   = OrderedDict()
+		self.responses                   = OrderedDict()
+		self.method                      = OrderedDict()
+		self.params                      = OrderedDict()
+		self.results                     = OrderedDict()
+		self.partition                   = float('NaN')
+		self.numberofpartitions          = 0
+		self.numberofresponses           = 0
+		self.variabledescriptors         = []
+		self.responsedescriptors         = []
+		self.mass_flux_profile_directory = float('NaN')
+		self.mass_flux_profiles          = float('NaN')
+		self.mass_flux_segments          = []
+		self.adjacency                   = float('NaN')
+		self.vertex_weight               = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not md.qmu.isdakota:
+			return
+
+		if not md.qmu.params.evaluation_concurrency==1:
+			md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
+		if md.qmu.partition:
+			if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices:
+				md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1")
+			if not min(md.qmu.partition)==0:
+				md.checkmessage("partition vector not indexed from 0 on")
+			if max(md.qmu.partition)>=md.qmu.numberofpartitions:
+				md.checkmessage("for qmu analysis, partitioning vector cannot go over npart, number of partition areas")
+
+		if not m.strcmpi(md.cluster.name,'none'):
+			if not md.settings.waitonlock:
+				md.checkmessage("waitonlock should be activated when running qmu in parallel mode!")
+
+		return md
+	# }}}
+	def __repr__(self):    # {{{
+		s ='   qmu parameters:\n'
+
+		s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
+		for i,variable in enumerate(self.variables.iteritems()):
+			s+="         variables%s:  (arrays of each variable class)\n" % \
+				string_dim(self.variables,i)
+			fnames=vars(variable)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="'            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
+
+		for i,response in enumerate(self.responses.iteritems()):
+			s+="         responses%s:  (arrays of each response class)\n" % \
+				string_dim(self.responses,i)
+			fnames=vars(response)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
+
+		s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 
+
+		for i,method in enumerate(self.method.iteritems()):
+			if isinstance(method,'dakota_method'):
+				s+="            method%s :    '%s'\n" % \
+					(string_dim(method,i),method.method)
+
+		for i,param in enumerate(self.params.iteritems()):
+			s+="         params%s:  (array of method-independent parameters)\n" % \
+				string_dim(self.params,i)
+			fnames=vars(param)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s: %s\n" % \
+					(maxlen+1,fname,any2str(getattr(param,fname)))
+
+		for i,result in enumerate(self.results.iteritems()):
+			s+="         results%s:  (information from dakota files)\n" % \
+				string_dim(self.results,i)
+			fnames=vars(result)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
+
+		s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+		s+="%s\n" % fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
+		s+="%s\n" % fielddisplay(self,'variabledescriptors','')
+		s+="%s\n" % fielddisplay(self,'responsedescriptors','')
+		s+="%s\n" % fielddisplay(self,'method','array of dakota_method class')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_segments','')
+		s+="%s\n" % fielddisplay(self,'adjacency','')
+		s+="%s\n" % fielddisplay(self,'vertex_weight','weight applied to each mesh vertex')
+
+		return s
+	# }}}
+	def marshall(self,md,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)
+		WriteData(fid,'object',self,'fieldname','numberofpartitions','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofresponses','format','Integer')
+		WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray')
+		WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray')
+		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/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dakota_method.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 18231)
@@ -0,0 +1,872 @@
+%
+%  definition for the dakota_method class.
+%
+%  [dm]=dakota_method(method)
+%
+%  where the required input is:
+%    method       (char, beginning of method name)
+%
+%  and the output properties and defaults are:
+%    method       (char, full method name, '')
+%    type         (char, type of method, '')
+%    variables    (cell array, applicable variable types, {})
+%    lcspec       (cell array, linear constraint specs, {})
+%    responses    (cell array, applicable response types, {})
+%    ghspec       (cell array, gradient and hessian specs, {})
+%    params       (structure, method-dependent parameters, [])
+%
+%  this class is used to guide the writing of a dakota input
+%  file for the specified dakota_method.
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and one argument
+%  with enough characters to match a unique method constructs
+%  a new instance of that method.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef dakota_method
+    properties (SetAccess=private)
+        method   ='';
+        type     ='';
+        variables={};
+        lcspec   ={};
+        responses={};
+        ghspec   ={};
+    end
+    properties
+        params   =struct();
+    end
+
+    methods
+        function [dm]=dakota_method(method)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                case 1
+                    if  (nargin == 1) && isa(method,'dakota_method')
+                        dm=method;
+                    else
+                        mlist={...
+                            'dot_bfgs',...
+                            'dot_frcg',...
+                            'dot_mmfd',...
+                            'dot_slp',...
+                            'dot_sqp',...
+                            'npsol_sqp',...
+                            'conmin_frcg',...
+                            'conmin_mfd',...
+                            'optpp_cg',...
+                            'optpp_q_newton',...
+                            'optpp_fd_newton',...
+                            'optpp_newton',...
+                            'optpp_pds',...
+                            'asynch_pattern_search',...
+                            'coliny_cobyla',...
+                            'coliny_direct',...
+                            'coliny_ea',...
+                            'coliny_pattern_search',...
+                            'coliny_solis_wets',...
+                            'ncsu_direct',...
+                            'surrogate_based_local',...
+                            'surrogate_based_global',...
+                            'moga',...
+                            'soga',...
+                            'nl2sol',...
+                            'nlssol_sqp',...
+                            'optpp_g_newton',...
+                            'nond_sampling',...
+                            'nond_local_reliability',...
+                            'nond_global_reliability',...
+                            'nond_polynomial_chaos',...
+                            'nond_stoch_collocation',...
+                            'nond_evidence',...
+                            'dace',...
+                            'fsu_quasi_mc',...
+                            'fsu_cvt',...
+                            'vector_parameter_study',...
+                            'list_parameter_study',...
+                            'centered_parameter_study',...
+                            'multidim_parameter_study',...
+                            };
+
+                        mlist2={};
+                        for i=1:length(mlist)
+                            if strncmpi(method,mlist{i},length(method))
+                                mlist2(end+1)=mlist(i);
+                            end
+                        end
+
+%  check for a unique match in the list of methods
+
+                        switch length(mlist2)
+                            case 0
+                                error('Unrecognized method: ''%s''.',...
+                                    method);
+                            case 1
+                                dm.method=mlist2{1};
+                            otherwise
+                                error('Non-unique method: ''%s'' matches %s.',...
+                                    method,string_cell(mlist2));
+                        end
+
+%  assign the default values for the method
+
+                        switch dm.method
+                            case {'dot_bfgs',...
+                                  'dot_frcg'}
+                                dm.type     ='dot';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.optimization_type='minimize';
+                            case {'dot_mmfd',...
+                                  'dot_slp',...
+                                  'dot_sqp'}
+                                dm.type     ='dot';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.optimization_type='minimize';
+
+                            case {'npsol_sqp'}
+                                dm.type     ='npsol';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.verify_level=-1;
+                                dm.params.function_precision=1.e-10;
+                                dm.params.linesearch_tolerance=0.9;
+
+                            case {'conmin_frcg'}
+                                dm.type     ='conmin';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                            case {'conmin_mfd'}
+                                dm.type     ='conmin';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+
+                            case {'optpp_cg'}
+                                dm.type     ='optpp';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.max_step=1000.;
+                                dm.params.gradient_tolerance=1.e-4;
+                            case {'optpp_q_newton',...
+                                  'optpp_fd_newton',...
+                                  'optpp_newton'}
+                                dm.type     ='optpp';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.value_based_line_search=false;
+                                dm.params.gradient_based_line_search=false;
+                                dm.params.trust_region=false;
+                                dm.params.tr_pds=false;
+                                dm.params.max_step=1000.;
+                                dm.params.gradient_tolerance=1.e-4;
+                                dm.params.merit_function='argaez_tapia';
+                                dm.params.central_path=dm.params.merit_function;
+                                dm.params.steplength_to_boundary=0.99995;
+                                dm.params.centering_parameter=0.2;
+                            case {'optpp_pds'}
+                                dm.type     ='optpp';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.search_scheme_size=32;
+
+                            case {'asynch_pattern_search'}
+                                dm.type     ='apps';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_function_evaluations=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.initial_delta=1.0;
+                                dm.params.threshold_delta=0.01;
+                                dm.params.contraction_factor=0.5;
+                                dm.params.solution_target=false;
+                                dm.params.synchronization='nonblocking';
+                                dm.params.merit_function='merit2_smooth';
+                                dm.params.constraint_penalty=1.0;
+                                dm.params.smoothing_factor=1.0;
+
+                            case {'coliny_cobyla'}
+                                dm.type     ='coliny';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.show_misc_options=false;
+                                dm.params.misc_options={};
+                                dm.params.solution_accuracy=-Inf;
+                                dm.params.initial_delta=[];
+                                dm.params.threshold_delta=[];
+                            case {'coliny_direct'}
+                                dm.type     ='coliny';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.show_misc_options=false;
+                                dm.params.misc_options={};
+                                dm.params.solution_accuracy=-Inf;
+                                dm.params.division='major_dimension';
+                                dm.params.global_balance_parameter=0.0;
+                                dm.params.local_balance_parameter=1.e-8;
+                                dm.params.max_boxsize_limit=0.0;
+                                dm.params.min_boxsize_limit=0.0001;
+                                dm.params.constraint_penalty=1000.0;
+                            case {'coliny_ea'}
+                                dm.type     ='coliny';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.show_misc_options=false;
+                                dm.params.misc_options={};
+                                dm.params.solution_accuracy=-Inf;
+                                dm.params.seed=false;
+                                dm.params.population_size=50;
+                                dm.params.initialization_type='unique_random';
+                                dm.params.fitness_type='linear_rank';
+                                dm.params.replacement_type='elitist';
+                                dm.params.random=[];
+                                dm.params.chc=[];
+                                dm.params.elitist=[];
+                                dm.params.new_solutions_generated='population_size - replacement_size';
+                                dm.params.crossover_type='two_point';
+                                dm.params.crossover_rate=0.8;
+                                dm.params.mutation_type='offset_normal';
+                                dm.params.mutation_scale=0.1;
+                                dm.params.mutation_range=1;
+                                dm.params.dimension_ratio=1.0;
+                                dm.params.mutation_rate=1.0;
+                                dm.params.non_adaptive=false;
+                            case {'coliny_pattern_search'}
+                                dm.type     ='coliny';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.show_misc_options=false;
+                                dm.params.misc_options={};
+                                dm.params.solution_accuracy=-Inf;
+                                dm.params.stochastic=false;
+                                dm.params.seed=false;
+                                dm.params.initial_delta=[];
+                                dm.params.threshold_delta=[];
+                                dm.params.constraint_penalty=1.0;
+                                dm.params.constant_penalty=false;
+                                dm.params.pattern_basis='coordinate';
+                                dm.params.total_pattern_size=false;
+                                dm.params.no_expansion=false;
+                                dm.params.expand_after_success=1;
+                                dm.params.contraction_factor=0.5;
+                                dm.params.synchronization='nonblocking';
+                                dm.params.exploratory_moves='basic_pattern';
+                            case {'coliny_solis_wets'}
+                                dm.type     ='coliny';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.show_misc_options=false;
+                                dm.params.misc_options={};
+                                dm.params.solution_accuracy=-Inf;
+                                dm.params.seed=false;
+                                dm.params.initial_delta=[];
+                                dm.params.threshold_delta=[];
+                                dm.params.no_expansion=false;
+                                dm.params.expand_after_success=5;
+                                dm.params.contract_after_failure=3;
+                                dm.params.contraction_factor=0.5;
+                                dm.params.constraint_penalty=1.0;
+                                dm.params.constant_penalty=false;
+
+                            case {'ncsu_direct'}
+                                dm.type     ='ncsu';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};  %  ?
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};  %  ?
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.scaling=false;
+                                dm.params.solution_accuracy=0.;
+                                dm.params.min_boxsize_limit=1.e-8;
+                                dm.params.vol_boxsize_limit=1.e-8;
+
+%                             case {'surrogate_based_local',...
+%                                   'surrogate_based_global'}
+
+                            case {'moga'}
+                                dm.type     ='jega';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.seed=false;
+                                dm.params.log_file='JEGAGlobal.log';
+                                dm.params.population_size=50;
+                                dm.params.print_each_pop=false;
+%                               according to documentation, uses method-independent control
+%                               dm.params.output='normal';
+                                dm.params.initialization_type='unique_random';
+                                dm.params.mutation_type='replace_uniform';
+                                dm.params.mutation_scale=0.15;
+                                dm.params.mutation_rate=0.08;
+                                dm.params.replacement_type='';
+                                dm.params.below_limit=6;
+                                dm.params.shrinkage_percentage=0.9;
+                                dm.params.crossover_type='shuffle_random';
+                                dm.params.multi_point_binary=[];
+                                dm.params.multi_point_parameterized_binary=[];
+                                dm.params.multi_point_real=[];
+                                dm.params.shuffle_random=[];
+                                dm.params.num_parents=2;
+                                dm.params.num_offspring=2;
+                                dm.params.crossover_rate=0.8;
+                                dm.params.fitness_type='';
+                                dm.params.niching_type=false;
+                                dm.params.radial=[0.01];
+                                dm.params.distance=[0.01];
+                                dm.params.metric_tracker=false;
+                                dm.params.percent_change=0.1;
+                                dm.params.num_generations=10;
+                                dm.params.postprocessor_type=false;
+                                dm.params.orthogonal_distance=[0.01];
+                            case {'soga'}
+                                dm.type     ='jega';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'objective_function',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.seed=false;
+                                dm.params.log_file='JEGAGlobal.log';
+                                dm.params.population_size=50;
+                                dm.params.print_each_pop=false;
+                                dm.params.output='normal';
+                                dm.params.initialization_type='unique_random';
+                                dm.params.mutation_type='replace_uniform';
+                                dm.params.mutation_scale=0.15;
+                                dm.params.mutation_rate=0.08;
+                                dm.params.replacement_type='';
+                                dm.params.below_limit=6;
+                                dm.params.shrinkage_percentage=0.9;
+                                dm.params.crossover_type='shuffle_random';
+                                dm.params.multi_point_binary=[];
+                                dm.params.multi_point_parameterized_binary=[];
+                                dm.params.multi_point_real=[];
+                                dm.params.shuffle_random=[];
+                                dm.params.num_parents=2;
+                                dm.params.num_offspring=2;
+                                dm.params.crossover_rate=0.8;
+                                dm.params.fitness_type='merit_function';
+                                dm.params.constraint_penalty=1.0;
+                                dm.params.replacement_type='';
+                                dm.params.convergence_type=false;
+                                dm.params.num_generations=10;
+                                dm.params.percent_change=0.1;
+
+                            case {'nl2sol'}
+                                dm.type     ='lsq';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'least_squares_term'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.scaling=false;
+                                dm.params.function_precision=1.e-10;
+                                dm.params.absolute_conv_tol=-1.;
+                                dm.params.x_conv_tol=-1.;
+                                dm.params.singular_conv_tol=-1.;
+                                dm.params.singular_radius=-1.;
+                                dm.params.false_conv_tol=-1.;
+                                dm.params.initial_trust_radius=-1.;
+                                dm.params.covariance=0;
+                                dm.params.regression_stressbalances=false;
+                            case {'nlssol_sqp'}
+                                dm.type     ='lsq';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'least_squares_term',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.constraint_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.verify_level=-1;
+                                dm.params.function_precision=1.e-10;
+                                dm.params.linesearch_tolerance=0.9;
+                            case {'optpp_g_newton'}
+                                dm.type     ='lsq';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={'linear_inequality_constraint',...
+                                              'linear_equality_constraint'};
+                                dm.responses={'least_squares_term',...
+                                              'nonlinear_inequality_constraint',...
+                                              'nonlinear_equality_constraint'};
+                                dm.ghspec   ={'grad'};
+                                dm.params.max_iterations=false;
+                                dm.params.max_function_evaluations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.output=false;
+                                dm.params.speculative=false;
+                                dm.params.scaling=false;
+                                dm.params.value_based_line_search=false;
+                                dm.params.gradient_based_line_search=false;
+                                dm.params.trust_region=false;
+                                dm.params.tr_pds=false;
+                                dm.params.max_step=1000.;
+                                dm.params.gradient_tolerance=1.e-4;
+                                dm.params.merit_function='argaez_tapia';
+                                dm.params.central_path=dm.params.merit_function;
+                                dm.params.steplength_to_boundary=0.99995;
+                                dm.params.centering_parameter=0.2;
+
+                            case {'nond_sampling'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={};
+%                               not documented, but apparently works
+                                dm.params.output=false;
+                                dm.params.seed=false;
+                                dm.params.fixed_seed=false;
+                                dm.params.rng=false;
+                                dm.params.samples=false;
+                                dm.params.sample_type='lhs';
+                                dm.params.all_variables=false;
+                                dm.params.variance_based_decomp=false;
+                                dm.params.previous_samples=0;
+                            case {'nond_local_reliability'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={'grad'};
+%                               not documented, but may work
+                                dm.params.output=false;
+                                dm.params.max_iterations=false;
+                                dm.params.convergence_tolerance=false;
+                                dm.params.mpp_search=false;
+                                dm.params.sqp=false;
+                                dm.params.nip=false;
+                                dm.params.integration='first_order';
+                                dm.params.refinement=false;
+                                dm.params.samples=0;
+                                dm.params.seed=false;
+                            case {'nond_global_reliability'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={'grad'};
+%                               not documented, but may work
+                                dm.params.output=false;
+                                dm.params.x_gaussian_process=false;
+                                dm.params.u_gaussian_process=false;
+                                dm.params.all_variables=false;
+                                dm.params.seed=false;
+                            case {'nond_polynomial_chaos'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={'grad'};
+%                               not documented, but may work
+                                dm.params.output=false;
+                                dm.params.expansion_order=[];
+                                dm.params.expansion_terms=[];
+                                dm.params.quadrature_order=[];
+                                dm.params.sparse_grid_level=[];
+                                dm.params.expansion_samples=[];
+                                dm.params.incremental_lhs=false;
+                                dm.params.collocation_points=[];
+                                dm.params.collocation_ratio=[];
+                                dm.params.reuse_samples=false;
+                                dm.params.expansion_import_file='';
+                                dm.params.seed=false;
+                                dm.params.fixed_seed=false;
+                                dm.params.samples=0;
+                                dm.params.sample_type='lhs';
+                                dm.params.all_variables=false;
+                            case {'nond_stoch_collocation'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={'grad'};
+%                               not documented, but may work
+                                dm.params.output=false;
+                                dm.params.quadrature_order=[];
+                                dm.params.sparse_grid_level=[];
+                                dm.params.seed=false;
+                                dm.params.fixed_seed=false;
+                                dm.params.samples=0;
+                                dm.params.sample_type='lhs';
+                                dm.params.all_variables=false;
+                            case {'nond_evidence'}
+                                dm.type     ='nond';
+                                dm.variables={'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'response_function'};
+                                dm.ghspec   ={'grad'};
+%                               not documented, but may work
+                                dm.params.output=false;
+                                dm.params.seed=false;
+                                dm.params.samples=10000;
+
+                            case {'dace'}
+                                dm.type     ='dace';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.grid=false;
+                                dm.params.random=false;
+                                dm.params.oas=false;
+                                dm.params.lhs=false;
+                                dm.params.oa_lhs=false;
+                                dm.params.box_behnken=false;
+                                dm.params.central_composite=false;
+                                dm.params.seed=false;
+                                dm.params.fixed_seed=false;
+                                dm.params.samples=false;
+                                dm.params.symbols=false;
+                                dm.params.quality_metrics=false;
+                                dm.params.variance_based_decomp=false;
+                            case {'fsu_quasi_mc'}
+                                dm.type     ='dace';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.halton=false;
+                                dm.params.hammersley=false;
+                                dm.params.samples=0;
+                                dm.params.sequence_start=[0];
+                                dm.params.sequence_leap=[1];
+                                dm.params.prime_base=false;
+                                dm.params.fixed_sequence=false;
+                                dm.params.latinize=false;
+                                dm.params.variance_based_decomp=false;
+                                dm.params.quality_metrics=false;
+                            case {'fsu_cvt'}
+                                dm.type     ='dace';
+                                dm.variables={'continuous_design',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.seed=false;
+                                dm.params.fixed_seed=false;
+                                dm.params.samples=0;
+                                dm.params.num_trials=10000;
+                                dm.params.trial_type='random';
+                                dm.params.latinize=false;
+                                dm.params.variance_based_decomp=false;
+                                dm.params.quality_metrics=false;
+
+                            case {'vector_parameter_study'}
+                                dm.type     ='param';
+                                dm.variables={'continuous_design',...
+                                              'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.output=false;
+                                dm.params.final_point=[];
+                                dm.params.step_length=[];
+                                dm.params.num_steps=[];
+                                dm.params.step_vector=[];
+                                dm.params.num_steps=[];
+                            case {'list_parameter_study'}
+                                dm.type     ='param';
+                                dm.variables={'continuous_design',...
+                                              'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.output=false;
+                                dm.params.list_of_points=[];
+                            case {'centered_parameter_study'}
+                                dm.type     ='param';
+                                dm.variables={'continuous_design',...
+                                              'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.output=false;
+                                dm.params.percent_delta=[];
+                                dm.params.deltas_per_variable=[];
+                            case {'multidim_parameter_study'}
+                                dm.type     ='param';
+                                dm.variables={'continuous_design',...
+                                              'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function'};
+                                dm.ghspec   ={};
+                                dm.params.output=false;
+                                dm.params.partitions=[];
+
+                            otherwise
+                                error('Unimplemented method: ''%s''.',dm.method);
+                        end
+
+                    end
+
+%  if more than one argument, issue warning
+
+                otherwise
+                    warning('dakota_method:extra_arg',...
+                        'Extra arguments for object of class ''%s''.',...
+                        class(dm));
+            end
+
+        end
+
+        function []=disp(dm)
+
+%  display the object
+
+            for i=1:numel(dm)
+                disp(sprintf('\nclass ''%s'' object ''%s%s'' = \n',...
+                    class(dm),inputname(1),string_dim(dm,i)));
+                disp(sprintf('       method: ''%s'''  ,dm(i).method));
+                disp(sprintf('         type: ''%s'''  ,dm(i).type));
+                disp(sprintf('    variables: %s'      ,string_cell(dm(i).variables)));
+                disp(sprintf('       lcspec: %s'      ,string_cell(dm(i).lcspec)));
+                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
+
+                fnames=fieldnames(dm(i).params);
+                maxlen=0;
+                for j=1:numel(fnames)
+                    maxlen=max(maxlen,length(fnames{j}));
+                end
+
+                for j=1:numel(fnames)
+                    disp(sprintf(['       params.%-' num2str(maxlen+1) 's: %s'],...
+                        fnames{j},any2str(dm(i).params.(fnames{j}))));
+                end
+            end
+
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m	(revision 18231)
@@ -0,0 +1,27 @@
+%
+%  merge a structure of parameters into a dakota_method object.
+%
+%  [dm]=dmeth_params_merge(dm,params)
+%
+function [dm]=dmeth_params_merge(dm,params)
+
+if ~isa(dm,'dakota_method')
+    error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+        inputname(1),class(dm),'dakota_method');
+end
+
+%  loop through each parameter field in the structure
+
+fnames=fieldnames(params);
+
+for i=1:numel(fnames)
+    if isfield(dm.params,fnames{i})
+        dm.params.(fnames{i})=params.(fnames{i});
+    else
+        warning('dmeth_params_merge:unknown_param',...
+            'No parameter ''%s'' for dakota_method ''%s''.',...
+            fnames{i},dm.method);
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_set.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_set.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_set.m	(revision 18231)
@@ -0,0 +1,25 @@
+%
+%  set parameters of a dakota_method object.
+%
+%  [dm]=dmeth_params_set(dm,varargin)
+%
+function [dm]=dmeth_params_set(dm,varargin)
+
+if ~isa(dm,'dakota_method')
+    error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+        inputname(1),class(dm),'dakota_method');
+end
+
+%  loop through each parameter field in the input list
+
+for i=1:2:length(varargin)
+    if isfield(dm.params,varargin{i})
+        dm.params.(varargin{i})=varargin{i+1};
+    else
+        warning('dmeth_params_set:unknown_param',...
+            'No parameter ''%s'' for dakota_method ''%s''.',...
+            varargin{i},dm.method);
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 18231)
@@ -0,0 +1,582 @@
+%
+%  write the parameters from a dakota_method object.
+%
+%  []=dmeth_params_write(dm,fid,sbeg)
+%
+function []=dmeth_params_write(dm,fid,sbeg)
+
+if ~isa(dm,'dakota_method')
+    error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+        inputname(1),class(dm),'dakota_method');
+end
+
+if ~exist('sbeg','var')
+    sbeg='\t  ';
+end
+
+%  perform some error checking, but leave the rest to dakota.
+%  unfortunately this prevents merely looping through the fields
+%  of the parameters structure.
+
+%  write method-independent controls
+
+% param_write(fid,sbeg,'id_method','                = ','\n',dm.params);
+% param_write(fid,sbeg,'model_pointer','            = ','\n',dm.params);
+
+%  write method-dependent controls
+
+switch dm.type
+    case {'dot'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+        param_write(fid,sbeg,'constraint_tolerance','     = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'speculative','','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case{'dot_bfgs',...
+                 'dot_frcg',...
+                 'dot_mmfd',...
+                 'dot_slp',...
+                 'dot_sqp'}
+                param_write(fid,sbeg,'optimization_type',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'npsol'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+        param_write(fid,sbeg,'constraint_tolerance','     = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'speculative','','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case {'npsol_sqp'}
+                param_write(fid,sbeg,'verify_level','         = ','\n',dm.params);
+                param_write(fid,sbeg,'function_precision','   = ','\n',dm.params);
+                param_write(fid,sbeg,'linesearch_tolerance',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'conmin'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+        param_write(fid,sbeg,'constraint_tolerance','     = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'speculative','','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case {'conmin_frcg',...
+                  'conmin_mfd'}
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'optpp'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'speculative','','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case {'optpp_cg'}
+                param_write(fid,sbeg,'max_step','           = ','\n',dm.params);
+                param_write(fid,sbeg,'gradient_tolerance',' = ','\n',dm.params);
+
+            case {'optpp_q_newton',...
+                  'optpp_fd_newton',...
+                  'optpp_newton'}
+                if (dm.params.value_based_line_search + ...
+                    dm.params.gradient_based_line_search + ...
+                    dm.params.trust_region + ...
+                    dm.params.tr_pds > 1)
+                    error('''%s'' method must have only one algorithm.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'value_based_line_search','','\n',dm.params);
+                param_write(fid,sbeg,'gradient_based_line_search','','\n',dm.params);
+                param_write(fid,sbeg,'trust_region','','\n',dm.params);
+                param_write(fid,sbeg,'tr_pds','','\n',dm.params);
+                param_write(fid,sbeg,'max_step','               = ','\n',dm.params);
+                param_write(fid,sbeg,'gradient_tolerance','     = ','\n',dm.params);
+                param_write(fid,sbeg,'merit_function','         = ','\n',dm.params);
+                param_write(fid,sbeg,'central_path','           = ','\n',dm.params);
+                param_write(fid,sbeg,'steplength_to_boundary',' = ','\n',dm.params);
+                param_write(fid,sbeg,'centering_parameter','    = ','\n',dm.params);
+
+            case {'optpp_pds'}
+                param_write(fid,sbeg,'search_scheme_size',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'apps'}
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'constraint_tolerance','     = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case {'asynch_pattern_search'}
+                param_write(fid,sbeg,'initial_delta','      = ','\n',dm.params);
+                param_write(fid,sbeg,'threshold_delta','    = ','\n',dm.params);
+                param_write(fid,sbeg,'contraction_factor',' = ','\n',dm.params);
+                param_write(fid,sbeg,'solution_target','    = ','\n',dm.params);
+                param_write(fid,sbeg,'synchronization','    = ','\n',dm.params);
+                param_write(fid,sbeg,'merit_function','     = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_penalty',' = ','\n',dm.params);
+                param_write(fid,sbeg,'smoothing_factor','   = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'coliny'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+
+        param_write(fid,sbeg,'show_misc_options','','\n',dm.params);
+        param_write(fid,sbeg,'misc_options','      = ','\n',dm.params);
+        param_write(fid,sbeg,'solution_accuracy',' = ','\n',dm.params);
+        switch dm.method
+            case {'coliny_cobyla'}
+                param_write(fid,sbeg,'initial_delta','   = ','\n',dm.params);
+                param_write(fid,sbeg,'threshold_delta',' = ','\n',dm.params);
+
+            case {'coliny_direct'}
+                param_write(fid,sbeg,'division','                 = ','\n',dm.params);
+                param_write(fid,sbeg,'global_balance_parameter',' = ','\n',dm.params);
+                param_write(fid,sbeg,'local_balance_parameter','  = ','\n',dm.params);
+                param_write(fid,sbeg,'max_boxsize_limit','        = ','\n',dm.params);
+                param_write(fid,sbeg,'min_boxsize_limit','        = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_penalty','       = ','\n',dm.params);
+
+            case {'coliny_ea'}
+                param_write(fid,sbeg,'seed','                    = ','\n',dm.params);
+                param_write(fid,sbeg,'population_size','         = ','\n',dm.params);
+                param_write(fid,sbeg,'initialization_type','     = ','\n',dm.params);
+                param_write(fid,sbeg,'fitness_type','            = ','\n',dm.params);
+                param_write(fid,sbeg,'replacement_type','        = ','\n',dm.params);
+                param_write(fid,sbeg,'random','                  = ','\n',dm.params);
+                param_write(fid,sbeg,'chc','                     = ','\n',dm.params);
+                param_write(fid,sbeg,'elitist','                 = ','\n',dm.params);
+                param_write(fid,sbeg,'new_solutions_generated',' = ','\n',dm.params);
+                param_write(fid,sbeg,'crossover_type','          = ','\n',dm.params);
+                param_write(fid,sbeg,'crossover_rate','          = ','\n',dm.params);
+                param_write(fid,sbeg,'mutation_type','           = ','\n',dm.params);
+                param_write(fid,sbeg,'mutation_scale','          = ','\n',dm.params);
+                param_write(fid,sbeg,'mutation_range','          = ','\n',dm.params);
+                param_write(fid,sbeg,'dimension_ratio','         = ','\n',dm.params);
+                param_write(fid,sbeg,'mutation_rate','           = ','\n',dm.params);
+                param_write(fid,sbeg,'non_adaptive','','\n',dm.params);
+
+            case {'coliny_pattern_search'}
+                param_write(fid,sbeg,'stochastic','','\n',dm.params);
+                param_write(fid,sbeg,'seed','                 = ','\n',dm.params);
+                param_write(fid,sbeg,'initial_delta','        = ','\n',dm.params);
+                param_write(fid,sbeg,'threshold_delta','      = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_penalty','   = ','\n',dm.params);
+                param_write(fid,sbeg,'constant_penalty','','\n',dm.params);
+                param_write(fid,sbeg,'pattern_basis','        = ','\n',dm.params);
+                param_write(fid,sbeg,'total_pattern_size','   = ','\n',dm.params);
+                param_write(fid,sbeg,'no_expansion','','\n',dm.params);
+                param_write(fid,sbeg,'expand_after_success',' = ','\n',dm.params);
+                param_write(fid,sbeg,'contraction_factor','   = ','\n',dm.params);
+                param_write(fid,sbeg,'synchronization','      = ','\n',dm.params);
+                param_write(fid,sbeg,'exploratory_moves','    = ','\n',dm.params);
+
+            case {'coliny_solis_wets'}
+                param_write(fid,sbeg,'seed','                   = ','\n',dm.params);
+                param_write(fid,sbeg,'initial_delta','          = ','\n',dm.params);
+                param_write(fid,sbeg,'threshold_delta','        = ','\n',dm.params);
+                param_write(fid,sbeg,'no_expansion','','\n',dm.params);
+                param_write(fid,sbeg,'expand_after_success','   = ','\n',dm.params);
+                param_write(fid,sbeg,'contract_after_failure',' = ','\n',dm.params);
+                param_write(fid,sbeg,'contraction_factor','     = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_penalty','     = ','\n',dm.params);
+                param_write(fid,sbeg,'constant_penalty','','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'ncsu'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+        switch dm.method
+            case {'ncsu_direct'}
+                param_write(fid,sbeg,'solution_accuracy',' = ','\n',dm.params);
+                param_write(fid,sbeg,'min_boxsize_limit',' = ','\n',dm.params);
+                param_write(fid,sbeg,'vol_boxsize_limit',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'jega'}
+        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        param_write(fid,sbeg,'scaling','','\n',dm.params);
+
+        param_write(fid,sbeg,'seed','                             = ','\n',dm.params);
+        param_write(fid,sbeg,'log_file','                         = ','\n',dm.params);
+        param_write(fid,sbeg,'population_size','                  = ','\n',dm.params);
+        param_write(fid,sbeg,'print_each_pop','','\n',dm.params);
+        param_write(fid,sbeg,'output','                           = ','\n',dm.params);
+        param_write(fid,sbeg,'initialization_type','              = ','\n',dm.params);
+        param_write(fid,sbeg,'mutation_type','                    = ','\n',dm.params);
+        param_write(fid,sbeg,'mutation_scale','                   = ','\n',dm.params);
+        param_write(fid,sbeg,'mutation_rate','                    = ','\n',dm.params);
+        param_write(fid,sbeg,'replacement_type','                 = ','\n',dm.params);
+        param_write(fid,sbeg,'below_limit','                      = ','\n',dm.params);
+        param_write(fid,sbeg,'shrinkage_percentage','             = ','\n',dm.params);
+        param_write(fid,sbeg,'crossover_type','                   = ','\n',dm.params);
+        param_write(fid,sbeg,'multi_point_binary','               = ','\n',dm.params);
+        param_write(fid,sbeg,'multi_point_parameterized_binary',' = ','\n',dm.params);
+        param_write(fid,sbeg,'multi_point_real','                 = ','\n',dm.params);
+        param_write(fid,sbeg,'shuffle_random','                   = ','\n',dm.params);
+        param_write(fid,sbeg,'num_parents','                      = ','\n',dm.params);
+        param_write(fid,sbeg,'num_offspring','                    = ','\n',dm.params);
+        param_write(fid,sbeg,'crossover_rate','                   = ','\n',dm.params);
+
+        switch dm.method
+            case {'moga'}
+                param_write(fid,sbeg,'fitness_type','        = ','\n',dm.params);
+                param_write(fid,sbeg,'niching_type','        = ','\n',dm.params);
+                if ~isempty(dm.params.radial) && ...
+                   ~isempty(dm.params.distance)
+                    error('''%s'' method must have only one niching distance.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'radial','              = ','\n',dm.params);
+                param_write(fid,sbeg,'distance','            = ','\n',dm.params);
+                param_write(fid,sbeg,'metric_tracker','','\n',dm.params);
+                param_write(fid,sbeg,'percent_change','      = ','\n',dm.params);
+                param_write(fid,sbeg,'num_generations','     = ','\n',dm.params);
+                param_write(fid,sbeg,'postprocessor_type','  = ','\n',dm.params);
+                param_write(fid,sbeg,'orthogonal_distance',' = ','\n',dm.params);
+
+            case {'soga'}
+                param_write(fid,sbeg,'fitness_type','       = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_penalty',' = ','\n',dm.params);
+                param_write(fid,sbeg,'replacement_type','   = ','\n',dm.params);
+                param_write(fid,sbeg,'convergence_type','   = ','\n',dm.params);
+                param_write(fid,sbeg,'num_generations','    = ','\n',dm.params);
+                param_write(fid,sbeg,'percent_change','     = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'lsq'}
+        switch dm.method
+            case {'nl2sol'}
+                param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+                param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+                param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+                param_write(fid,sbeg,'output',' ','\n',dm.params);
+                param_write(fid,sbeg,'scaling','','\n',dm.params);
+
+                param_write(fid,sbeg,'function_precision','   = ','\n',dm.params);
+                param_write(fid,sbeg,'absolute_conv_tol','    = ','\n',dm.params);
+                param_write(fid,sbeg,'x_conv_tol','           = ','\n',dm.params);
+                param_write(fid,sbeg,'singular_conv_tol','    = ','\n',dm.params);
+                param_write(fid,sbeg,'singular_radius','      = ','\n',dm.params);
+                param_write(fid,sbeg,'false_conv_tol','       = ','\n',dm.params);
+                param_write(fid,sbeg,'initial_trust_radius',' = ','\n',dm.params);
+                param_write(fid,sbeg,'covariance','           = ','\n',dm.params);
+                param_write(fid,sbeg,'regression_stressbalances','','\n',dm.params);
+
+            case {'nlssol_sqp'}
+                param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+                param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+                param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+                param_write(fid,sbeg,'constraint_tolerance','     = ','\n',dm.params);
+                param_write(fid,sbeg,'output',' ','\n',dm.params);
+                param_write(fid,sbeg,'speculative','','\n',dm.params);
+                param_write(fid,sbeg,'scaling','','\n',dm.params);
+
+                param_write(fid,sbeg,'verify_level','         = ','\n',dm.params);
+                param_write(fid,sbeg,'function_precision','   = ','\n',dm.params);
+                param_write(fid,sbeg,'linesearch_tolerance',' = ','\n',dm.params);
+
+            case {'optpp_g_newton'}
+                param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+                param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
+                param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+                param_write(fid,sbeg,'output',' ','\n',dm.params);
+                param_write(fid,sbeg,'speculative','','\n',dm.params);
+                param_write(fid,sbeg,'scaling','','\n',dm.params);
+
+                if (dm.params.value_based_line_search + ...
+                    dm.params.gradient_based_line_search + ...
+                    dm.params.trust_region + ...
+                    dm.params.tr_pds > 1)
+                    error('''%s'' method must have only one algorithm.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'value_based_line_search','','\n',dm.params);
+                param_write(fid,sbeg,'gradient_based_line_search','','\n',dm.params);
+                param_write(fid,sbeg,'trust_region','','\n',dm.params);
+                param_write(fid,sbeg,'tr_pds','','\n',dm.params);
+                param_write(fid,sbeg,'max_step','               = ','\n',dm.params);
+                param_write(fid,sbeg,'gradient_tolerance','     = ','\n',dm.params);
+                param_write(fid,sbeg,'merit_function','         = ','\n',dm.params);
+                param_write(fid,sbeg,'central_path','           = ','\n',dm.params);
+                param_write(fid,sbeg,'steplength_to_boundary',' = ','\n',dm.params);
+                param_write(fid,sbeg,'centering_parameter','    = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'nond'}
+        switch dm.method
+            case {'nond_sampling'}
+                param_write(fid,sbeg,'seed','             = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
+                dver=textscan(IssmConfig('_DAKOTA_VERSION_'),'%[0123456789].%[0123456789].%[0123456789]');
+                if ((str2num(dver{1}{1})==4 && str2num(dver{2}{1})>2) || str2num(dver{1}{1})>4)
+                    param_write(fid,sbeg,'rng','                ','\n',dm.params);
+                end
+                param_write(fid,sbeg,'samples','          = ','\n',dm.params);
+                param_write(fid,sbeg,'sample_type','        ','\n',dm.params);
+                param_write(fid,sbeg,'all_variables','','\n',dm.params);
+                param_write(fid,sbeg,'variance_based_decomp','','\n',dm.params);
+                if strcmp(dm.params.sample_type,'incremental_random') || ...
+                   strcmp(dm.params.sample_type,'incremental_lhs'   )
+                    param_write(fid,sbeg,'previous_samples',' = ','\n',dm.params);
+                end
+                param_write(fid,sbeg,'output',' ','\n',dm.params);
+
+            case {'nond_local_reliability'}
+                param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
+                param_write(fid,sbeg,'convergence_tolerance','    = ','\n',dm.params);
+
+                param_write(fid,sbeg,'mpp_search','  = ','\n',dm.params);
+                if ischar(dm.params.mpp_search)
+                    if (dm.params.sqp + ...
+                        dm.params.nip > 1)
+                        error('''%s'' method must have only one algorithm.',...
+                            dm.method);
+                    end
+                    param_write(fid,sbeg,'sqp','','\n',dm.params);
+                    param_write(fid,sbeg,'nip','','\n',dm.params);
+                    param_write(fid,sbeg,'integration','   ','\n',dm.params);
+                    param_write(fid,sbeg,'refinement','  = ','\n',dm.params);
+                    if ischar(dm.params.refinement)
+                        param_write(fid,sbeg,'samples','     = ','\n',dm.params);
+                        param_write(fid,sbeg,'seed','        = ','\n',dm.params);
+                    end
+                end
+                param_write(fid,sbeg,'output',' ','\n',dm.params);
+
+            case {'nond_global_reliability'}
+                if (dm.params.x_gaussian_process + ...
+                    dm.params.u_gaussian_process ~= 1)
+                    error('''%s'' method must have one and only one algorithm.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'x_gaussian_process','','\n',dm.params);
+                param_write(fid,sbeg,'u_gaussian_process','','\n',dm.params);
+                param_write(fid,sbeg,'all_variables','','\n',dm.params);
+                param_write(fid,sbeg,'seed',' = ','\n',dm.params);
+
+            case {'nond_polynomial_chaos'}
+                param_write(fid,sbeg,'expansion_order','       = ','\n',dm.params);
+                param_write(fid,sbeg,'expansion_terms','       = ','\n',dm.params);
+                param_write(fid,sbeg,'quadrature_order','      = ','\n',dm.params);
+                param_write(fid,sbeg,'sparse_grid_level','     = ','\n',dm.params);
+                param_write(fid,sbeg,'expansion_samples','     = ','\n',dm.params);
+                param_write(fid,sbeg,'incremental_lhs','','\n',dm.params);
+                param_write(fid,sbeg,'collocation_points','    = ','\n',dm.params);
+                param_write(fid,sbeg,'collocation_ratio','     = ','\n',dm.params);
+                param_write(fid,sbeg,'reuse_samples','','\n',dm.params);
+                param_write(fid,sbeg,'expansion_import_file',' = ','\n',dm.params);
+                param_write(fid,sbeg,'seed','                  = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
+                param_write(fid,sbeg,'samples','               = ','\n',dm.params);
+                param_write(fid,sbeg,'sample_type','           = ','\n',dm.params);
+                param_write(fid,sbeg,'all_variables','','\n',dm.params);
+
+            case {'nond_stoch_collocation'}
+                param_write(fid,sbeg,'quadrature_order','  = ','\n',dm.params);
+                param_write(fid,sbeg,'sparse_grid_level',' = ','\n',dm.params);
+                param_write(fid,sbeg,'seed','              = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
+                param_write(fid,sbeg,'samples','           = ','\n',dm.params);
+                param_write(fid,sbeg,'sample_type','       = ','\n',dm.params);
+                param_write(fid,sbeg,'all_variables','','\n',dm.params);
+
+            case {'nond_evidence'}
+                param_write(fid,sbeg,'seed','    = ','\n',dm.params);
+                param_write(fid,sbeg,'samples',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'dace'}
+        switch dm.method
+            case {'dace'}
+                if (dm.params.grid + ...
+                    dm.params.random + ...
+                    dm.params.oas + ...
+                    dm.params.lhs + ...
+                    dm.params.oa_lhs + ...
+                    dm.params.box_behnken + ...
+                    dm.params.central_composite ~= 1)
+                    error('''%s'' method must have one and only one algorithm.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'grid','','\n',dm.params);
+                param_write(fid,sbeg,'random','','\n',dm.params);
+                param_write(fid,sbeg,'oas','','\n',dm.params);
+                param_write(fid,sbeg,'lhs','','\n',dm.params);
+                param_write(fid,sbeg,'oa_lhs','','\n',dm.params);
+                param_write(fid,sbeg,'box_behnken','','\n',dm.params);
+                param_write(fid,sbeg,'central_composite','','\n',dm.params);
+                param_write(fid,sbeg,'seed','    = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
+                param_write(fid,sbeg,'samples',' = ','\n',dm.params);
+                param_write(fid,sbeg,'symbols',' = ','\n',dm.params);
+                param_write(fid,sbeg,'quality_metrics','','\n',dm.params);
+                param_write(fid,sbeg,'variance_based_decomp','','\n',dm.params);
+
+            case {'fsu_quasi_mc'}
+                if (dm.params.halton + ...
+                    dm.params.hammersley ~= 1)
+                    error('''%s'' method must have one and only one sequence type.',...
+                        dm.method);
+                end
+                param_write(fid,sbeg,'halton','','\n',dm.params);
+                param_write(fid,sbeg,'hammersley','','\n',dm.params);
+                param_write(fid,sbeg,'samples','        = ','\n',dm.params);
+                param_write(fid,sbeg,'sequence_start',' = ','\n',dm.params);
+                param_write(fid,sbeg,'sequence_leap','  = ','\n',dm.params);
+                param_write(fid,sbeg,'prime_base','     = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_sequence','','\n',dm.params);
+                param_write(fid,sbeg,'latinize','','\n',dm.params);
+                param_write(fid,sbeg,'variance_based_decomp','','\n',dm.params);
+                param_write(fid,sbeg,'quality_metrics','','\n',dm.params);
+
+            case {'fsu_cvt'}
+                param_write(fid,sbeg,'seed','       = ','\n',dm.params);
+                param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
+                param_write(fid,sbeg,'samples','    = ','\n',dm.params);
+                param_write(fid,sbeg,'num_trials',' = ','\n',dm.params);
+                param_write(fid,sbeg,'trial_type',' = ','\n',dm.params);
+                param_write(fid,sbeg,'latinize','','\n',dm.params);
+                param_write(fid,sbeg,'variance_based_decomp','','\n',dm.params);
+                param_write(fid,sbeg,'quality_metrics','','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    case {'param'}
+        param_write(fid,sbeg,'output',' ','\n',dm.params);
+        switch dm.method
+            case {'vector_parameter_study'}
+                if ~xor(isempty(dm.params.final_point), ...
+                        isempty(dm.params.step_vector))
+                    error('''%s'' method must have one and only one specification.',...
+                        dm.method);
+                end
+                if     ~isempty(dm.params.final_point)
+                    param_write(fid,sbeg,'final_point',' = ','\n',dm.params);
+                    param_write(fid,sbeg,'step_length',' = ','\n',dm.params);
+                    param_write(fid,sbeg,'num_steps','   = ','\n',dm.params);
+                elseif ~isempty(dm.params.step_vector)
+                    param_write(fid,sbeg,'step_vector',' = ','\n',dm.params);
+                    param_write(fid,sbeg,'num_steps','   = ','\n',dm.params);
+                end
+
+            case {'list_parameter_study'}
+                param_write(fid,sbeg,'list_of_points',' = ','\n',dm.params);
+
+            case {'centered_parameter_study'}
+                param_write(fid,sbeg,'percent_delta','       = ','\n',dm.params);
+                param_write(fid,sbeg,'deltas_per_variable',' = ','\n',dm.params);
+
+            case {'multidim_parameter_study'}
+                param_write(fid,sbeg,'partitions',' = ','\n',dm.params);
+
+            otherwise
+                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
+        end
+
+    otherwise
+        error('Unrecognized method type: ''%s''.',dm.type);
+end
+
+end
+
+%%  function to write a structure of parameters
+
+function []=param_struc_write(fidi,sbeg,smid,send,params)
+
+%  loop through each parameter field in the structure
+
+fnames=fieldnames(params);
+
+for i=1:numel(fnames)
+    param_write(fidi,sbeg,fnames{i},smid,send,params);
+end
+
+end
+
+%%  function to write a parameter
+
+function []=param_write(fidi,sbeg,pname,smid,send,params)
+
+%  check for errors
+
+if ~isfield(params,pname)
+    warning('param_write:param_not_found',...
+        'Parameter ''%s'' not found in ''%s''.',...
+        pname,inputname(6));
+    return
+elseif islogical(params.(pname)) && ~params.(pname)
+    return
+elseif isempty(params.(pname))
+    warning('param_write:param_empty',...
+        'Parameter ''%s'' requires input of type ''%s''.',...
+        pname,class(params.(pname)));
+    return
+end
+
+%  construct the parameter string based on type
+
+if     islogical(params.(pname))
+    fprintf(fidi,[sbeg '%s' send],pname);
+elseif isnumeric(params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%g'],pname,params.(pname)(1));
+    for i=2:numel(params.(pname))
+        fprintf(fidi,[' %g'],params.(pname)(i));
+    end
+    fprintf(fidi,[send]);
+elseif ischar   (params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%s' send],pname,params.(pname));
+else
+    warning('param_write:param_unrecog',...
+        'Parameter ''%s'' is of unrecognized type ''%s''.',...
+        pname,class(params.(pname)));
+    return
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_design.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_design.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_design.m	(revision 18231)
@@ -0,0 +1,227 @@
+%
+%  definition for the continuous_design class.
+%
+%  [cdv]=continuous_design(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    initpt        (double, initial point, 0.)
+%  and the optional varargin and defaults are:
+%    lower         (double, lower bound, -Inf)
+%    upper         (double, upper bound,  Inf)
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef continuous_design
+    properties
+        descriptor='';
+        initpt    = 0.;
+        lower     =-Inf;
+        upper     = Inf;
+        scale_type='none';
+        scale     = 1.;
+    end
+
+    methods
+        function [cdv]=continuous_design(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'continuous_design')
+                        cdv=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'continuous_design');
+                    end
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,6)}));
+                    cdv(asizec{:})=continuous_design;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(cdv)
+                        if (numel(varargin{1}) > 1)
+                            cdv(i).descriptor=varargin{1}{i};
+                        else
+                            cdv(i).descriptor=[char(varargin{1}) string_dim(cdv,i,'vector')];
+                        end
+                    end
+
+                    if (nargin >= 2)
+                        for i=1:numel(cdv)
+                            if (numel(varargin{2}) > 1)
+                                cdv(i).initpt    =varargin{2}(i);
+                            else
+                                cdv(i).initpt    =varargin{2};
+                            end
+                        end
+                        if (nargin >= 3)
+                            for i=1:numel(cdv)
+                                if (numel(varargin{3}) > 1)
+                                    cdv(i).lower     =varargin{3}(i);
+                                else
+                                    cdv(i).lower     =varargin{3};
+                                end
+                            end
+                            if (nargin >= 4)
+                                for i=1:numel(cdv)
+                                    if (numel(varargin{4}) > 1)
+                                        cdv(i).upper     =varargin{4}(i);
+                                    else
+                                        cdv(i).upper     =varargin{4};
+                                    end
+                                end
+                                if (nargin >= 5)
+                                    if ischar(varargin{5})
+                                        varargin{5}=cellstr(varargin{5});
+                                    end
+                                    for i=1:numel(cdv)
+                                        if (numel(varargin{5}) > 1)
+                                            cdv(i).scale_type=varargin{5}{i};
+                                        else
+                                            cdv(i).scale_type=char(varargin{5});
+                                        end
+                                    end
+                                    if (nargin >= 6)
+                                        for i=1:numel(cdv)
+                                            if (numel(varargin{6}) > 1)
+                                                cdv(i).scale     =varargin{6}(i);
+                                            else
+                                                cdv(i).scale     =varargin{6};
+                                            end
+                                        end
+                                        if (nargin > 6)
+                                            warning('continuous_design:extra_arg',...
+                                                'Extra arguments for object of class ''%s''.',...
+                                                class(cdv));
+                                        end
+                                    end
+                                end
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(cdv)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(cdv)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(cdv),inputname(1),string_dim(cdv,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,cdv(i).descriptor));
+                disp(sprintf('        initpt: %g'      ,cdv(i).initpt));
+                disp(sprintf('         lower: %g'      ,cdv(i).lower));
+                disp(sprintf('         upper: %g'      ,cdv(i).upper));
+                disp(sprintf('    scale_type: ''%s'''  ,cdv(i).scale_type));
+                disp(sprintf('         scale: %g\n'    ,cdv(i).scale));
+            end
+
+        end
+
+        function [desc]  =prop_desc(cdv,dstr)
+            desc=cell(1,numel(cdv));
+            for i=1:numel(cdv)
+                if ~isempty(cdv(i).descriptor)
+                    desc(i)=cellstr(cdv(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(cdv,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(cdv,i,'vector')]);
+                else
+                    desc(i)=cellstr(['cdv'        string_dim(cdv,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [initpt]=prop_initpt(cdv)
+            initpt=zeros(1,numel(cdv));
+            for i=1:numel(cdv)
+                initpt(i)=cdv(i).initpt;
+            end
+            initpt=allequal(initpt,0.);
+        end
+        function [lower] =prop_lower(cdv)
+            lower=zeros(1,numel(cdv));
+            for i=1:numel(cdv)
+                lower(i)=cdv(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(cdv)
+            upper=zeros(1,numel(cdv));
+            for i=1:numel(cdv)
+                upper(i)=cdv(i).upper;
+            end
+            upper=allequal(upper, Inf);
+        end
+        function [mean]  =prop_mean(cdv)
+            mean=[];
+        end
+        function [stddev]=prop_stddev(cdv)
+            stddev=[];
+        end
+        function [initst]=prop_initst(cdv)
+            initst=[];
+        end
+        function [stype] =prop_stype(cdv)
+            stype=cell(1,numel(cdv));
+            for i=1:numel(cdv)
+                stype(i)=cellstr(cdv(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(cdv)
+            scale=zeros(1,numel(cdv));
+            for i=1:numel(cdv)
+                scale(i)=cdv(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            cdv=struc_class(dvar,'continuous_design');
+
+%  write variables
+
+            vlist_write(fidi,'continuous_design','cdv',cdv);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_state.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_state.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/continuous_state.m	(revision 18231)
@@ -0,0 +1,192 @@
+%
+%  definition for the continuous_state class.
+%
+%  [csv]=continuous_state(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    initst        (double, initial state, 0.)
+%  and the optional varargin and defaults are:
+%    lower         (double, lower bound, -Inf)
+%    upper         (double, upper bound,  Inf)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef continuous_state
+    properties
+        descriptor='';
+        initst    = 0.;
+        lower     =-Inf;
+        upper     = Inf;
+    end
+
+    methods
+        function [csv]=continuous_state(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'continuous_state')
+                        csv=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'continuous_state');
+                    end
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,4)}));
+                    csv(asizec{:})=continuous_state;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(csv)
+                        if (numel(varargin{1}) > 1)
+                            csv(i).descriptor=varargin{1}{i};
+                        else
+                            csv(i).descriptor=[char(varargin{1}) string_dim(csv,i,'vector')];
+                        end
+                    end
+
+                    if (nargin >= 2)
+                        for i=1:numel(csv)
+                            if (numel(varargin{2}) > 1)
+                                csv(i).initst    =varargin{2}(i);
+                            else
+                                csv(i).initst    =varargin{2};
+                            end
+                        end
+                        if (nargin >= 3)
+                            for i=1:numel(csv)
+                                if (numel(varargin{3}) > 1)
+                                    csv(i).lower     =varargin{3}(i);
+                                else
+                                    csv(i).lower     =varargin{3};
+                                end
+                            end
+                            if (nargin >= 4)
+                                for i=1:numel(csv)
+                                    if (numel(varargin{4}) > 1)
+                                        csv(i).upper     =varargin{4}(i);
+                                    else
+                                        csv(i).upper     =varargin{4};
+                                    end
+                                end
+                                if (nargin > 4)
+                                    warning('continuous_state:extra_arg',...
+                                        'Extra arguments for object of class ''%s''.',...
+                                        class(csv));
+                                end
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(csv)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(csv)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(csv),inputname(1),string_dim(csv,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,csv(i).descriptor));
+                disp(sprintf('        initst: %g'      ,csv(i).initst));
+                disp(sprintf('         lower: %g'      ,csv(i).lower));
+                disp(sprintf('         upper: %g\n'    ,csv(i).upper));
+            end
+
+        end
+
+        function [desc]  =prop_desc(csv,dstr)
+            desc=cell(1,numel(csv));
+            for i=1:numel(csv)
+                if ~isempty(csv(i).descriptor)
+                    desc(i)=cellstr(csv(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(csv,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(csv,i,'vector')]);
+                else
+                    desc(i)=cellstr(['csv'        string_dim(csv,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [initpt]=prop_initpt(csv)
+            initpt=[];
+        end
+        function [lower] =prop_lower(csv)
+            lower=zeros(1,numel(csv));
+            for i=1:numel(csv)
+                lower(i)=csv(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(csv)
+            upper=zeros(1,numel(csv));
+            for i=1:numel(csv)
+                upper(i)=csv(i).upper;
+            end
+            upper=allequal(upper, Inf);
+        end
+        function [mean]  =prop_mean(csv)
+            mean=[];
+        end
+        function [stddev]=prop_stddev(csv)
+            stddev=[];
+        end
+        function [initst]=prop_initst(csv)
+            initst=zeros(1,numel(csv));
+            for i=1:numel(csv)
+                initst(i)=csv(i).initst;
+            end
+            initst=allequal(initst,0.);
+        end
+        function [stype] =prop_stype(csv)
+            stype={};
+        end
+        function [scale] =prop_scale(csv)
+            scale=[];
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            csv=struc_class(dvar,'continuous_state');
+
+%  write variables
+
+            vlist_write(fidi,'continuous_state','csv',csv);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/least_squares_term.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/least_squares_term.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/least_squares_term.m	(revision 18231)
@@ -0,0 +1,187 @@
+%
+%  definition for the least_squares_term class.
+%
+%  [lst]=least_squares_term(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%    weight        (double, weighting factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and one or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef least_squares_term
+    properties
+        descriptor='';
+        scale_type='none';
+        scale     = 1.;
+        weight    = 1.;
+    end
+
+    methods
+        function [lst]=least_squares_term(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if  (nargin == 1) && isa(varargin{1},'least_squares_term')
+                        lst=varargin{1};
+                    else
+                        asizec=num2cell(array_size(varargin{1:min(nargin,4)}));
+                        lst(asizec{:})=least_squares_term;
+                        clear asizec
+
+                        if ischar(varargin{1})
+                            varargin{1}=cellstr(varargin{1});
+                        end
+                        for i=1:numel(lst)
+                            if (numel(varargin{1}) > 1)
+                                lst(i).descriptor=varargin{1}{i};
+                            else
+                                lst(i).descriptor=[char(varargin{1}) string_dim(lst,i,'vector')];
+                            end
+                        end
+
+                        if (nargin >= 2)
+                            if ischar(varargin{2})
+                                varargin{2}=cellstr(varargin{2});
+                            end
+                            for i=1:numel(lst)
+                                if (numel(varargin{2}) > 1)
+                                    lst(i).scale_type=varargin{2}{i};
+                                else
+                                    lst(i).scale_type=char(varargin{2});
+                                end
+                            end
+                            if (nargin >= 3)
+                                for i=1:numel(lst)
+                                    if (numel(varargin{3}) > 1)
+                                        lst(i).scale     =varargin{3}(i);
+                                    else
+                                        lst(i).scale     =varargin{3};
+                                    end
+                                end
+                                if (nargin >= 4)
+                                    for i=1:numel(lst)
+                                        if (numel(varargin{4}) > 1)
+                                            lst(i).weight    =varargin{4}(i);
+                                        else
+                                            lst(i).weight    =varargin{4};
+                                        end
+                                    end
+
+                                    if (nargin > 4)
+                                        warning('least_squares_term:extra_arg',...
+                                            'Extra arguments for object of class ''%s''.',...
+                                            class(lst));
+                                    end
+                                end
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(lst)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(lst)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(lst),inputname(1),string_dim(lst,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,lst(i).descriptor));
+                disp(sprintf('    scale_type: ''%s'''  ,lst(i).scale_type));
+                disp(sprintf('         scale: %g'      ,lst(i).scale));
+                disp(sprintf('        weight: %g\n'    ,lst(i).weight));
+            end
+
+        end
+
+        function [desc]  =prop_desc(lst,dstr)
+            desc=cell(1,numel(lst));
+            for i=1:numel(lst)
+                if ~isempty(lst(i).descriptor)
+                    desc(i)=cellstr(lst(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(lst,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(lst,i,'vector')]);
+                else
+                    desc(i)=cellstr(['lst'        string_dim(lst,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [stype] =prop_stype(lst)
+            stype=cell(1,numel(lst));
+            for i=1:numel(lst)
+                stype(i)=cellstr(lst(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(lst)
+            scale=zeros(1,numel(lst));
+            for i=1:numel(lst)
+                scale(i)=lst(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+        function [weight]=prop_weight(lst)
+            weight=zeros(1,numel(lst));
+            for i=1:numel(lst)
+                weight(i)=lst(i).weight;
+            end
+            weight=allequal(weight,1.);
+        end
+        function [lower] =prop_lower(lst)
+            lower=[];
+        end
+        function [upper] =prop_upper(lst)
+            upper=[];
+        end
+        function [target]=prop_target(lst)
+            target=[];
+        end
+    end
+
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            lst=struc_class(dresp,'least_squares_term');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'least_squares_terms','least_squares_term',lst,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_equality_constraint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_equality_constraint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_equality_constraint.m	(revision 18231)
@@ -0,0 +1,182 @@
+%
+%  constructor for the linear_equality_constraint class.
+%
+%  [lec]=linear_equality_constraint(varargin)
+%
+%  where the required varargin are:
+%    matrix        (double row, variable coefficients, NaN)
+%    target        (double vector, target values, 0.)
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef linear_equality_constraint
+    properties
+        matrix    = NaN;
+        target    = 0.;
+        scale_type='none';
+        scale     = 1.;
+    end
+
+    methods
+        function [lec]=linear_equality_constraint(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'linear_equality_constraint')
+                        lec=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'linear_equality_constraint');
+                    end
+
+%  create the object from the input
+
+                otherwise
+                    if     (size(varargin{1},1) == array_numel(varargin{2:min(nargin,4)}) || ...
+                            size(varargin{1},1) == 1)
+                        asizec=num2cell(array_size(varargin{2:min(nargin,4)}));
+                    elseif (array_numel(varargin{2:min(nargin,4)}) == 1)
+                        asizec=num2cell([size(varargin{1},1) 1]);
+                    else
+                        error('Matrix for object of class ''%s'' has inconsistent number of rows.',...
+                              class(lec));
+                    end
+                    lec(asizec{:})=linear_equality_constraint;
+                    clear asizec
+
+                    for i=1:numel(lec)
+                        if (size(varargin{1},1) > 1)
+                            lec(i).matrix    =varargin{1}(i,:);
+                        else
+                            lec(i).matrix    =varargin{1};
+                        end
+                    end
+
+                    if (nargin >= 2)
+                        for i=1:numel(lec)
+                            if (numel(varargin{2}) > 1)
+                                lec(i).target    =varargin{2}(i);
+                            else
+                                lec(i).target    =varargin{2};
+                            end
+                        end
+                        if (nargin >= 3)
+                            if ischar(varargin{3})
+                                varargin{3}=cellstr(varargin{3});
+                            end
+                            for i=1:numel(lec)
+                                if (numel(varargin{3}) > 1)
+                                    lec(i).scale_type=varargin{3}{i};
+                                else
+                                    lec(i).scale_type=char(varargin{3});
+                                end
+                            end
+                            if (nargin >= 4)
+                                for i=1:numel(lec)
+                                    if (numel(varargin{4}) > 1)
+                                        lec(i).scale     =varargin{4}(i);
+                                    else
+                                        lec(i).scale     =varargin{4};
+                                    end
+                                end
+
+                                if (nargin > 4)
+                                    warning('linear_equality_constraint:extra_arg',...
+                                        'Extra arguments for object of class ''%s''.',...
+                                        class(lec));
+                                end
+                            end
+                        end
+                    end
+            end
+        end
+
+        function []=disp(lec)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(lec)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(lec),inputname(1),string_dim(lec,i)));
+                disp(sprintf('        matrix: %s'      ,string_vec(lec(i).matrix)));
+                disp(sprintf('        target: %g'      ,lec(i).target));
+                disp(sprintf('    scale_type: ''%s'''  ,lec(i).scale_type));
+                disp(sprintf('         scale: %g\n'    ,lec(i).scale));
+            end
+
+        end
+
+        function [matrix]=prop_matrix(lec)
+            matrix=zeros(numel(lec),0);
+            for i=1:numel(lec)
+                matrix(i,1:size(lec(i).matrix,2))=lec(i).matrix(1,:);
+            end
+        end
+        function [lower] =prop_lower(lec)
+            lower=[];
+        end
+        function [upper] =prop_upper(lec)
+            upper=[];
+        end
+        function [target]=prop_target(lec)
+            target=zeros(size(lec));
+            for i=1:numel(lec)
+                target(i)=lec(i).target;
+            end
+            target=allequal(target,0.);
+        end
+        function [stype] =prop_stype(lec)
+            stype=cell(size(lec));
+            for i=1:numel(lec)
+                stype(i)=cellstr(lec(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(lec)
+            scale=zeros(size(lec));
+            for i=1:numel(lec)
+                scale(i)=lec(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            lec=struc_class(dvar,'linear_equality_constraint');
+
+%  write constraints
+
+            lclist_write(fidi,'linear_equality_constraints','linear_equality',lec);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_inequality_constraint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_inequality_constraint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/linear_inequality_constraint.m	(revision 18231)
@@ -0,0 +1,204 @@
+%
+%  constructor for the linear_inequality_constraint class.
+%
+%  [lic]=linear_inequality_constraint(varargin)
+%
+%  where the required varargin are:
+%    matrix        (double row, variable coefficients, NaN)
+%    lower         (double vector, lower bounds, -Inf)
+%    upper         (double vector, upper bounds, 0.)
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and three or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef linear_inequality_constraint
+    properties
+        matrix    = NaN;
+        lower     =-Inf;
+        upper     = 0.;
+        scale_type='none';
+        scale     = 1.;
+    end
+
+    methods
+        function [lic]=linear_inequality_constraint(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'linear_inequality_constraint')
+                        lic=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'linear_inequality_constraint');
+                    end
+
+%  not enough arguments
+
+                case 2
+                    error('Construction of ''%s'' class object requires at least %d inputs.',...
+                        'linear_inequality_constraint',3)
+
+%  create the object from the input
+
+                otherwise
+                    if     (size(varargin{1},1) == array_numel(varargin{2:min(nargin,5)}) || ...
+                            size(varargin{1},1) == 1)
+                        asizec=num2cell(array_size(varargin{2:min(nargin,5)}));
+                    elseif (array_numel(varargin{2:min(nargin,5)}) == 1)
+                        asizec=num2cell([size(varargin{1},1) 1]);
+                    else
+                        error('Matrix for object of class ''%s'' has inconsistent number of rows.',...
+                              class(lic));
+                    end
+                    lic(asizec{:})=linear_inequality_constraint;
+                    clear asizec
+
+                    for i=1:numel(lic)
+                        if (size(varargin{1},1) > 1)
+                            lic(i).matrix    =varargin{1}(i,:);
+                        else
+                            lic(i).matrix    =varargin{1};
+                        end
+                    end
+
+                    if (nargin >= 2)
+                        for i=1:numel(lic)
+                            if (numel(varargin{2}) > 1)
+                                lic(i).lower     =varargin{2}(i);
+                            else
+                                lic(i).lower     =varargin{2};
+                            end
+                        end
+                        if (nargin >= 3)
+                            for i=1:numel(lic)
+                                if (numel(varargin{3}) > 1)
+                                    lic(i).upper     =varargin{3}(i);
+                                else
+                                    lic(i).upper     =varargin{3};
+                                end
+                            end
+                            if (nargin >= 4)
+                                if ischar(varargin{4})
+                                    varargin{4}=cellstr(varargin{4});
+                                end
+                                for i=1:numel(lic)
+                                    if (numel(varargin{4}) > 1)
+                                        lic(i).scale_type=varargin{4}{i};
+                                    else
+                                        lic(i).scale_type=char(varargin{4});
+                                    end
+                                end
+                                if (nargin >= 5)
+                                    for i=1:numel(lic)
+                                        if (numel(varargin{5}) > 1)
+                                            lic(i).scale     =varargin{5}(i);
+                                        else
+                                            lic(i).scale     =varargin{5};
+                                        end
+                                    end
+
+                                    if (nargin > 5)
+                                        warning('linear_inequality_constraint:extra_arg',...
+                                            'Extra arguments for object of class ''%s''.',...
+                                            class(lic));
+                                    end
+                                end
+                            end
+                        end
+                    end
+            end
+        end
+
+        function []=disp(lic)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(lic)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(lic),inputname(1),string_dim(lic,i)));
+                disp(sprintf('        matrix: %s'      ,string_vec(lic(i).matrix)));
+                disp(sprintf('         lower: %g'      ,lic(i).lower));
+                disp(sprintf('         upper: %g'      ,lic(i).upper));
+                disp(sprintf('    scale_type: ''%s'''  ,lic(i).scale_type));
+                disp(sprintf('         scale: %g\n'    ,lic(i).scale));
+            end
+
+        end
+
+        function [matrix]=prop_matrix(lic)
+            matrix=zeros(numel(lic),0);
+            for i=1:numel(lic)
+                matrix(i,1:size(lic(i).matrix,2))=lic(i).matrix(1,:);
+            end
+        end
+        function [lower] =prop_lower(lic)
+            lower=zeros(size(lic));
+            for i=1:numel(lic)
+                lower(i)=lic(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(lic)
+            upper=zeros(size(lic));
+            for i=1:numel(lic)
+                upper(i)=lic(i).upper;
+            end
+            upper=allequal(upper,0.);
+        end
+        function [target]=prop_target(lic)
+            target=[];
+        end
+        function [stype] =prop_stype(lic)
+            stype=cell(size(lic));
+            for i=1:numel(lic)
+                stype(i)=cellstr(lic(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(lic)
+            scale=zeros(size(lic));
+            for i=1:numel(lic)
+                scale(i)=lic(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            lic=struc_class(dvar,'linear_inequality_constraint');
+
+%  write constraints
+
+            lclist_write(fidi,'linear_inequality_constraints','linear_inequality',lic);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_equality_constraint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 18231)
@@ -0,0 +1,189 @@
+%
+%  constructor for the nonlinear_equality_constraint class.
+%
+%  [nec]=nonlinear_equality_constraint(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    target        (double, target value, 0.)
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef nonlinear_equality_constraint
+    properties
+        descriptor='';
+        target    = 0.;
+        scale_type='none';
+        scale     = 1.;
+    end
+
+    methods
+        function [nec]=nonlinear_equality_constraint(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'nonlinear_equality_constraint')
+                        nec=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'nonlinear_equality_constraint');
+                    end
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,4)}));
+                    nec(asizec{:})=nonlinear_equality_constraint;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(nec)
+                        if (numel(varargin{1}) > 1)
+                            nec(i).descriptor=varargin{1}{i};
+                        else
+                            nec(i).descriptor=[char(varargin{1}) string_dim(nec,i,'vector')];
+                        end
+                        if (numel(varargin{2}) > 1)
+                            nec(i).target    =varargin{2}(i);
+                        else
+                            nec(i).target    =varargin{2};
+                        end
+                    end
+
+                    if (nargin >= 3)
+                        if ischar(varargin{3})
+                            varargin{3}=cellstr(varargin{3});
+                        end
+                        for i=1:numel(nec)
+                            if (numel(varargin{3}) > 1)
+                                nec(i).scale_type=varargin{3}{i};
+                            else
+                                nec(i).scale_type=char(varargin{3});
+                            end
+                        end
+                        if (nargin >= 4)
+                            for i=1:numel(nec)
+                                if (numel(varargin{4}) > 1)
+                                    nec(i).scale     =varargin{4}(i);
+                                else
+                                    nec(i).scale     =varargin{4};
+                                end
+                            end
+
+                            if (nargin > 4)
+                                warning('objective_function:extra_arg',...
+                                    'Extra arguments for object of class ''%s''.',...
+                                    class(nec));
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(nec)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(nec)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(nec),inputname(1),string_dim(nec,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,nec(i).descriptor));
+                disp(sprintf('        target: %g'      ,nec(i).target));
+                disp(sprintf('    scale_type: ''%s'''  ,nec(i).scale_type));
+                disp(sprintf('         scale: %g\n'    ,nec(i).scale));
+            end
+
+        end
+
+        function [desc]  =prop_desc(nec,dstr)
+            desc=cell(1,numel(nec));
+            for i=1:numel(nec)
+                if ~isempty(nec(i).descriptor)
+                    desc(i)=cellstr(nec(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(nec,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(nec,i,'vector')]);
+                else
+                    desc(i)=cellstr(['nec'        string_dim(nec,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [stype] =prop_stype(nec)
+            stype=cell(size(nec));
+            for i=1:numel(nec)
+                stype(i)=cellstr(nec(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(nec)
+            scale=zeros(size(nec));
+            for i=1:numel(nec)
+                scale(i)=nec(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+        function [weight]=prop_weight(nec)
+            weight=[];
+        end
+        function [lower] =prop_lower(nec)
+            lower=[];
+        end
+        function [upper] =prop_upper(nec)
+            upper=[];
+        end
+        function [target]=prop_target(nec)
+            target=zeros(size(nec));
+            for i=1:numel(nec)
+                target(i)=nec(i).target;
+            end
+            target=allequal(target,0.);
+        end
+    end
+
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            nec=struc_class(dresp,'nonlinear_equality_constraint');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'nonlinear_equality_constraints','nonlinear_equality',nec,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_inequality_constraint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 18231)
@@ -0,0 +1,207 @@
+%
+%  constructor for the nonlinear_inequality_constraint class.
+%
+%  [nic]=nonlinear_inequality_constraint(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    lower         (double, lower bound, -Inf)
+%    upper         (double, upper bound, 0.)
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and three or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef nonlinear_inequality_constraint
+    properties
+        descriptor='';
+        lower     =-Inf;
+        upper     = 0.;
+        scale_type='none';
+        scale     = 1.;
+    end
+
+    methods
+        function [nic]=nonlinear_inequality_constraint(varargin)
+
+            switch nargin
+
+ %  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'nonlinear_inequality_constraint')
+                        nic=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'nonlinear_inequality_constraint');
+                    end
+
+%  not enough arguments
+
+                case 2
+                    error('Construction of ''%s'' class object requires at least %d inputs.',...
+                        'nonlinear_inequality_constraint',3)
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,5)}));
+                    nic(asizec{:})=nonlinear_inequality_constraint;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(nic)
+                        if (numel(varargin{1}) > 1)
+                            nic(i).descriptor=varargin{1}{i};
+                        else
+                            nic(i).descriptor=[char(varargin{1}) string_dim(nic,i,'vector')];
+                        end
+                        if (numel(varargin{2}) > 1)
+                            nic(i).lower     =varargin{2}(i);
+                        else
+                            nic(i).lower     =varargin{2};
+                        end
+                        if (numel(varargin{3}) > 1)
+                            nic(i).upper     =varargin{3}(i);
+                        else
+                            nic(i).upper     =varargin{3};
+                        end
+                    end
+
+                    if (nargin >= 4)
+                        if ischar(varargin{4})
+                            varargin{4}=cellstr(varargin{4});
+                        end
+                        for i=1:numel(nic)
+                            if (numel(varargin{4}) > 1)
+                                nic(i).scale_type=varargin{4}{i};
+                            else
+                                nic(i).scale_type=char(varargin{4});
+                            end
+                        end
+                        if (nargin >= 5)
+                            for i=1:numel(nic)
+                                if (numel(varargin{5}) > 1)
+                                    nic(i).scale     =varargin{5}(i);
+                                else
+                                    nic(i).scale     =varargin{5};
+                                end
+                            end
+
+                            if (nargin > 5)
+                                warning('objective_function:extra_arg',...
+                                    'Extra arguments for object of class ''%s''.',...
+                                    class(nic));
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(nic)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(nic)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(nic),inputname(1),string_dim(nic,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,nic(i).descriptor));
+                disp(sprintf('         lower: %g'      ,nic(i).lower));
+                disp(sprintf('         upper: %g'      ,nic(i).upper));
+                disp(sprintf('    scale_type: ''%s'''  ,nic(i).scale_type));
+                disp(sprintf('         scale: %g\n'    ,nic(i).scale));
+            end
+
+        end
+
+        function [desc]  =prop_desc(nic,dstr)
+            desc=cell(1,numel(nic));
+            for i=1:numel(nic)
+                if ~isempty(nic(i).descriptor)
+                    desc(i)=cellstr(nic(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(nic,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(nic,i,'vector')]);
+                else
+                    desc(i)=cellstr(['nic'        string_dim(nic,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [stype] =prop_stype(nic)
+            stype=cell(size(nic));
+            for i=1:numel(nic)
+                stype(i)=cellstr(nic(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(nic)
+            scale=zeros(size(nic));
+            for i=1:numel(nic)
+                scale(i)=nic(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+        function [weight]=prop_weight(nic)
+            weight=[];
+        end
+        function [lower] =prop_lower(nic)
+            lower=zeros(size(nic));
+            for i=1:numel(nic)
+                lower(i)=nic(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(nic)
+            upper=zeros(size(nic));
+            for i=1:numel(nic)
+                upper(i)=nic(i).upper;
+            end
+            upper=allequal(upper,0.);
+        end
+        function [target]=prop_target(nic)
+            target=[];
+        end
+    end
+
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            nic=struc_class(dresp,'nonlinear_inequality_constraint');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'nonlinear_inequality_constraints','nonlinear_inequality',nic,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/normal_uncertain.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/normal_uncertain.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/normal_uncertain.m	(revision 18231)
@@ -0,0 +1,208 @@
+%
+%  definition for the normal_uncertain class.
+%
+%  [nuv]=normal_uncertain(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    mean          (double, mean, NaN)
+%    stddev        (double, standard deviation, NaN)
+%  and the optional varargin and defaults are:
+%    lower         (double, lower bound, -Inf)
+%    upper         (double, upper bound,  Inf)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and three or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef normal_uncertain
+    properties
+        descriptor='';
+        mean      = NaN;
+        stddev    = NaN;
+        lower     =-Inf;
+        upper     = Inf;
+    end
+
+    methods
+        function [nuv]=normal_uncertain(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'normal_uncertain')
+                        nuv=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'normal_uncertain');
+                    end
+
+%  not enough arguments
+
+                case 2
+                    error('Construction of ''%s'' class object requires at least %d inputs.',...
+                        'normal_uncertain',3)
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,5)}));
+                    nuv(asizec{:})=normal_uncertain;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(nuv)
+                        if (numel(varargin{1}) > 1)
+                            nuv(i).descriptor=varargin{1}{i};
+                        else
+                            if numel(nuv)==1,
+								nuv(i).descriptor=char(varargin{1});
+							else
+								nuv(i).descriptor=[char(varargin{1}) num2str(i)];
+							end
+                        end
+                        if (numel(varargin{2}) > 1)
+                            nuv(i).mean      =varargin{2}(i);
+                        else
+                            nuv(i).mean      =varargin{2};
+                        end
+                        if (numel(varargin{3}) > 1)
+                            nuv(i).stddev    =varargin{3}(i);
+                        else
+                            nuv(i).stddev    =varargin{3};
+                        end
+                    end
+
+                    if (nargin >= 4)
+                        for i=1:numel(nuv)
+                            if (numel(varargin{4}) > 1)
+                                nuv(i).lower     =varargin{4}(i);
+                            else
+                                nuv(i).lower     =varargin{4};
+                            end
+                        end
+                        if (nargin >= 5)
+                            for i=1:numel(nuv)
+                                if (numel(varargin{5}) > 1)
+                                    nuv(i).upper     =varargin{5}(i);
+                                else
+                                    nuv(i).upper     =varargin{5};
+                                end
+                            end
+                            if (nargin > 5)
+                                warning('normal_uncertain:extra_arg',...
+                                    'Extra arguments for object of class ''%s''.',...
+                                    class(nuv));
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(nuv)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(nuv)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(nuv),inputname(1),string_dim(nuv,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,nuv(i).descriptor));
+                disp(sprintf('          mean: %g'      ,nuv(i).mean));
+                disp(sprintf('        stddev: %g'      ,nuv(i).stddev));
+                disp(sprintf('         lower: %g'      ,nuv(i).lower));
+                disp(sprintf('         upper: %g\n'    ,nuv(i).upper));
+            end
+
+        end
+
+        function [desc]  =prop_desc(nuv,dstr)
+            desc=cell(1,numel(nuv));
+            for i=1:numel(nuv)
+                if ~isempty(nuv(i).descriptor)
+                    desc(i)=cellstr(nuv(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(nuv,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(nuv,i,'vector')]);
+                else
+                    desc(i)=cellstr(['nuv'        string_dim(nuv,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [initpt]=prop_initpt(nuv)
+            initpt=[];
+        end
+        function [lower] =prop_lower(nuv)
+            lower=zeros(1,numel(nuv));
+            for i=1:numel(nuv)
+                lower(i)=nuv(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(nuv)
+            upper=zeros(1,numel(nuv));
+            for i=1:numel(nuv)
+                upper(i)=nuv(i).upper;
+            end
+            upper=allequal(upper, Inf);
+        end
+        function [mean]  =prop_mean(nuv)
+            mean=zeros(1,numel(nuv));
+            for i=1:numel(nuv)
+                mean(i)=nuv(i).mean;
+            end
+        end
+        function [stddev]=prop_stddev(nuv)
+            stddev=zeros(1,numel(nuv));
+            for i=1:numel(nuv)
+                stddev(i)=nuv(i).stddev;
+            end
+        end
+        function [initst]=prop_initst(nuv)
+            initst=[];
+        end
+        function [stype] =prop_stype(nuv)
+            stype={};
+        end
+        function [scale] =prop_scale(nuv)
+            scale=[];
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            nuv=struc_class(dvar,'normal_uncertain');
+
+%  write variables
+
+            vlist_write(fidi,'normal_uncertain','nuv',nuv);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/objective_function.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/objective_function.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/objective_function.m	(revision 18231)
@@ -0,0 +1,187 @@
+%
+%  definition for the objective_function class.
+%
+%  [of]=objective_function(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%    weight        (double, weighting factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and one or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef objective_function
+    properties
+        descriptor='';
+        scale_type='none';
+        scale     = 1.;
+        weight    = 1.;
+    end
+
+    methods
+        function [of]=objective_function(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if  (nargin == 1) && isa(varargin{1},'objective_function')
+                        of=varargin{1};
+                    else
+                        asizec=num2cell(array_size(varargin{1:min(nargin,4)}));
+                        of(asizec{:})=objective_function;
+                        clear asizec
+
+                        if ischar(varargin{1})
+                            varargin{1}=cellstr(varargin{1});
+                        end
+                        for i=1:numel(of)
+                            if (numel(varargin{1}) > 1)
+                                of(i).descriptor=varargin{1}{i};
+                            else
+                                of(i).descriptor=[char(varargin{1}) string_dim(of,i,'vector')];
+                            end
+                        end
+
+                        if (nargin >= 2)
+                            if ischar(varargin{2})
+                                varargin{2}=cellstr(varargin{2});
+                            end
+                            for i=1:numel(of)
+                                if (numel(varargin{2}) > 1)
+                                    of(i).scale_type=varargin{2}{i};
+                                else
+                                    of(i).scale_type=char(varargin{2});
+                                end
+                            end
+                            if (nargin >= 3)
+                                for i=1:numel(of)
+                                    if (numel(varargin{3}) > 1)
+                                        of(i).scale     =varargin{3}(i);
+                                    else
+                                        of(i).scale     =varargin{3};
+                                    end
+                                end
+                                if (nargin >= 4)
+                                    for i=1:numel(of)
+                                        if (numel(varargin{4}) > 1)
+                                            of(i).weight    =varargin{4}(i);
+                                        else
+                                            of(i).weight    =varargin{4};
+                                        end
+                                    end
+
+                                    if (nargin > 4)
+                                        warning('objective_function:extra_arg',...
+                                            'Extra arguments for object of class ''%s''.',...
+                                            class(of));
+                                    end
+                                end
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(of)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(of)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(of),inputname(1),string_dim(of,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,of(i).descriptor));
+                disp(sprintf('    scale_type: ''%s'''  ,of(i).scale_type));
+                disp(sprintf('         scale: %g'      ,of(i).scale));
+                disp(sprintf('        weight: %g\n'    ,of(i).weight));
+            end
+
+        end
+
+        function [desc]  =prop_desc(of,dstr)
+            desc=cell(1,numel(of));
+            for i=1:numel(of)
+                if ~isempty(of(i).descriptor)
+                    desc(i)=cellstr(of(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(of,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(of,i,'vector')]);
+                else
+                    desc(i)=cellstr(['of'         string_dim(of,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [stype] =prop_stype(of)
+            stype=cell(1,numel(of));
+            for i=1:numel(of)
+                stype(i)=cellstr(of(i).scale_type);
+            end
+            stype=allequal(stype,'none');
+        end
+        function [scale] =prop_scale(of)
+            scale=zeros(1,numel(of));
+            for i=1:numel(of)
+                scale(i)=of(i).scale;
+            end
+            scale=allequal(scale,1.);
+        end
+        function [weight]=prop_weight(of)
+            weight=zeros(1,numel(of));
+            for i=1:numel(of)
+                weight(i)=of(i).weight;
+            end
+            weight=allequal(weight,1.);
+        end
+        function [lower] =prop_lower(of)
+            lower=[];
+        end
+        function [upper] =prop_upper(of)
+            upper=[];
+        end
+        function [target]=prop_target(of)
+            target=[];
+        end
+    end
+
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            of=struc_class(dresp,'objective_function');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'objective_functions','objective_function',of,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/response_function.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/response_function.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/response_function.m	(revision 18231)
@@ -0,0 +1,192 @@
+%
+%  definition for the response_function class.
+%
+%  [rf]=response_function(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%  and the optional varargin and defaults are:
+%    respl         (double vector, response levels, [])
+%    probl         (double vector, probability levels, [])
+%    rell          (double vector, reliability levels, [])
+%    grell         (double vector, gen. reliability levels, [])
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and one or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef response_function
+    properties
+        descriptor='';
+        respl     =[];
+        probl     =[];
+        rell      =[];
+        grell     =[];
+    end
+
+    methods
+        function [rf]=response_function(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if  (nargin == 1) && isa(varargin{1},'response_function')
+                        rf=varargin{1};
+                    else
+                        asizec=num2cell(array_size(varargin{1:min(nargin,1)}));
+                        rf(asizec{:})=response_function;
+                        clear asizec
+
+                        if ischar(varargin{1})
+                            varargin{1}=cellstr(varargin{1});
+                        end
+                        for i=1:numel(rf)
+                            if (numel(varargin{1}) > 1)
+                                rf(i).descriptor=varargin{1}{i};
+                            else
+                                rf(i).descriptor=[char(varargin{1}) string_dim(rf,i,'vector')];
+                            end
+                        end
+
+                        if (nargin >= 2)
+                            for i=1:numel(rf)
+                                rf(i).respl     =varargin{2};
+                            end
+                            if (nargin >= 3)
+                                for i=1:numel(rf)
+                                    rf(i).probl     =varargin{3};
+                                end
+                                if (nargin >= 4)
+                                    for i=1:numel(rf)
+                                        rf(i).rell      =varargin{4};
+                                    end
+                                    if (nargin >= 5)
+                                        for i=1:numel(rf)
+                                            rf(i).grell     =varargin{5};
+                                        end
+
+                                        if (nargin > 5)
+                                            warning('response_function:extra_arg',...
+                                                'Extra arguments for object of class ''%s''.',...
+                                                class(rf));
+                                        end
+                                    end
+                                end
+                            end
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(rf)
+
+        %  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(rf)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(rf),inputname(1),string_dim(rf,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,rf(i).descriptor));
+                disp(sprintf('         respl: %s'      ,string_vec(rf(i).respl)));
+                disp(sprintf('         probl: %s'      ,string_vec(rf(i).probl)));
+                disp(sprintf('          rell: %s'      ,string_vec(rf(i).rell)));
+                disp(sprintf('         grell: %s\n'    ,string_vec(rf(i).grell)));
+            end
+
+        end
+
+        function [desc]  =prop_desc(rf,dstr)
+            desc=cell(1,numel(rf));
+            for i=1:numel(rf)
+                if ~isempty(rf(i).descriptor)
+                    desc(i)=cellstr(rf(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(rf,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(rf,i,'vector')]);
+                else
+                    desc(i)=cellstr(['rf'         string_dim(rf,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [stype] =prop_stype(rf)
+            stype={};
+        end
+        function [scale] =prop_scale(rf)
+            scale=[];
+        end
+        function [weight]=prop_weight(rf)
+            weight=[];
+        end
+        function [lower] =prop_lower(rf)
+            lower=[];
+        end
+        function [upper] =prop_upper(rf)
+            upper=[];
+        end
+        function [target]=prop_target(rf)
+            target=[];
+        end
+        function [respl,probl,rell,grell]=prop_levels(rf)
+            respl=cell(1,numel(rf));
+            probl=cell(1,numel(rf));
+            rell =cell(1,numel(rf));
+            grell=cell(1,numel(rf));
+            for i=1:numel(rf)
+                respl(i)={rf(i).respl};
+                probl(i)={rf(i).probl};
+                rell (i)={rf(i).rell};
+                grell(i)={rf(i).grell};
+            end
+            respl=allempty(respl);
+            probl=allempty(probl);
+            rell =allempty(rell);
+            grell=allempty(grell);
+        end
+    end
+
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            rf=struc_class(dresp,'response_function');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'response_functions','response_function',rf,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+
+%  collect only the responses of the appropriate class
+
+            rf=struc_class(dresp,'response_function');
+
+%  write response levels
+
+            rlev_write(fidi,rf,params);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/uniform_uncertain.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/uniform_uncertain.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/qmu/uniform_uncertain.m	(revision 18231)
@@ -0,0 +1,167 @@
+%
+%  definition for the uniform_uncertain class.
+%
+%  [uuv]=uniform_uncertain(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%    lower         (double, lower bound, -Inf)
+%    upper         (double, upper bound,  Inf)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and three or more
+%  arguments constructs a new instance from the arguments.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+classdef uniform_uncertain
+    properties
+        descriptor='';
+        lower     =-Inf;
+        upper     = Inf;
+    end
+
+    methods
+        function [uuv]=uniform_uncertain(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object
+
+                case 1
+                    if isa(varargin{1},'uniform_uncertain')
+                        uuv=varargin{1};
+                    else
+                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+                            inputname(1),class(varargin{1}),'uniform_uncertain');
+                    end
+
+%  not enough arguments
+
+                case 2
+                    error('Construction of ''%s'' class object requires at least %d inputs.',...
+                        'uniform_uncertain',3)
+
+%  create the object from the input
+
+                otherwise
+                    asizec=num2cell(array_size(varargin{1:min(nargin,3)}));
+                    uuv(asizec{:})=uniform_uncertain;
+                    clear asizec
+
+                    if ischar(varargin{1})
+                        varargin{1}=cellstr(varargin{1});
+                    end
+                    for i=1:numel(uuv)
+                        if (numel(varargin{1}) > 1)
+                            uuv(i).descriptor=varargin{1}{i};
+                        else
+                            uuv(i).descriptor=[char(varargin{1}) string_dim(uuv,i,'vector')];
+                        end
+                        if (numel(varargin{2}) > 1)
+                            uuv(i).lower     =varargin{2}(i);
+                        else
+                            uuv(i).lower     =varargin{2};
+                        end
+                        if (numel(varargin{3}) > 1)
+                            uuv(i).upper     =varargin{3}(i);
+                        else
+                            uuv(i).upper     =varargin{3};
+                        end
+                    end
+            end
+
+        end
+
+        function []=disp(uuv)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(uuv)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(uuv),inputname(1),string_dim(uuv,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,uuv(i).descriptor));
+                disp(sprintf('         lower: %g'      ,uuv(i).lower));
+                disp(sprintf('         upper: %g\n'    ,uuv(i).upper));
+            end
+
+        end
+
+        function [desc]  =prop_desc(uuv,dstr)
+            desc=cell(1,numel(uuv));
+            for i=1:numel(uuv)
+                if ~isempty(uuv(i).descriptor)
+                    desc(i)=cellstr(uuv(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(uuv,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(uuv,i,'vector')]);
+                else
+                    desc(i)=cellstr(['uuv'        string_dim(uuv,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+        end
+        function [initpt]=prop_initpt(uuv)
+            initpt=[];
+        end
+        function [lower] =prop_lower(uuv)
+            lower=zeros(1,numel(uuv));
+            for i=1:numel(uuv)
+                lower(i)=uuv(i).lower;
+            end
+            lower=allequal(lower,-Inf);
+        end
+        function [upper] =prop_upper(uuv)
+            upper=zeros(1,numel(uuv));
+            for i=1:numel(uuv)
+                upper(i)=uuv(i).upper;
+            end
+            upper=allequal(upper, Inf);
+        end
+        function [mean]  =prop_mean(uuv)
+            mean=[];
+        end
+        function [stddev]=prop_stddev(uuv)
+            stddev=[];
+        end
+        function [initst]=prop_initst(uuv)
+            initst=[];
+        end
+        function [stype] =prop_stype(uuv)
+            stype={};
+        end
+        function [scale] =prop_scale(uuv)
+            scale=[];
+        end
+    end
+
+    methods (Static)
+        function []=dakota_write(fidi,dvar)
+
+%  collect only the variables of the appropriate class
+
+            uuv=struc_class(dvar,'uniform_uncertain');
+
+%  write variables
+
+            vlist_write(fidi,'uniform_uncertain','uuv',uuv);
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.m	(revision 18231)
@@ -0,0 +1,33 @@
+%RADAROVERLAY class definition
+%
+%   Usage:
+%      radaroverlay=radaroverlay();
+
+classdef radaroverlay
+	properties (SetAccess=public) 
+		pwr = NaN;
+		x   = NaN;
+		y   = NaN;
+	end
+	methods
+		function obj = radaroverlay(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   radaroverlay parameters:'));
+
+			fielddisplay(obj,'pwr','radar power image (matrix)');
+			fielddisplay(obj,'x','corresponding x coordinates [m]');
+			fielddisplay(obj,'y','corresponding y coordinates [m]');
+
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/radaroverlay.py	(revision 18231)
@@ -0,0 +1,29 @@
+from fielddisplay import fielddisplay
+
+class radaroverlay(object):
+	"""
+	RADAROVERLAY class definition
+
+	   Usage:
+	      radaroverlay=radaroverlay();
+	"""
+
+	def __init__(self): # {{{
+		self.pwr = float('NaN')
+		self.x   = float('NaN')
+		self.y   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   radaroverlay parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'pwr','radar power image (matrix)'))
+		string="%s\n%s"%(string,fielddisplay(self,'x','corresponding x coordinates [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'y','corresponding y coordinates [m]'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/results.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/results.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/results.py	(revision 18231)
@@ -0,0 +1,53 @@
+import numpy
+from pairoptions import pairoptions
+from fielddisplay import fielddisplay
+import MatlabFuncs as m
+from EnumDefinitions 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,md,fid):    # {{{
+		pass
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.m	(revision 18231)
@@ -0,0 +1,94 @@
+%RIFTS class definition
+%
+%   Usage:
+%      rifts=rifts();
+
+classdef rifts
+	properties (SetAccess=public) 
+		riftstruct     = NaN;
+		riftproperties = NaN;
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- rifts -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftstruct" type="',              class(obj.riftstruct),'" default="',                  obj.riftstruct,'">',              '     <section name="rifts" />','     <help> structure containing all rift information (vertices coordinates, segments, type of melange, ...) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftproperties" type="',            class(obj.riftproperties),'" default="',                obj.riftproperties,'">',   '     <section name="rifts" />','     <help> N/A </help>','</parameter>');
+    
+        end % }}}
+		function obj = rifts(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
+				numrifts=0;
+			else
+				numrifts=numel(obj.riftstruct);
+			end
+			if numrifts,
+				if ~(strcmp(domaintype(md.mesh),'2Dhorizontal')),
+					md = checkmessage(md,['models with rifts are only supported in 2d for now!']);
+				end
+				if ~isstruct(obj.riftstruct),
+					md = checkmessage(md,['rifts.riftstruct should be a structure!']);
+				end
+				if ~isempty(find(md.mesh.segmentmarkers>=2)),
+					%We have segments with rift markers, but no rift structure!
+					md = checkmessage(md,['model should be processed for rifts (run meshprocessrifts)!']);
+				end
+				for i=1:numrifts,
+					md = checkfield(md,'fieldname',sprintf('rifts.riftstruct(%d).fill',i),'values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
+				end
+			else
+				if ~isnans(obj.riftstruct),
+					md = checkmessage(md,['riftstruct should be NaN since numrifts is 0!']);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   rifts parameters:'));
+
+			fielddisplay(obj,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)');
+			fielddisplay(obj,'riftproperties','');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			%Process rift info
+			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
+				numrifts=0;
+			else
+				numrifts=numel(obj.riftstruct);
+			end
+			numpairs=0;
+			for i=1:numrifts,
+				numpairs=numpairs+size(obj.riftstruct(i).penaltypairs,1);
+			end
+
+			% 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=zeros(numpairs,12);
+			count=1;
+			for i=1:numrifts,
+				numpairsforthisrift=size(obj.riftstruct(i).penaltypairs,1);
+				data(count:count+numpairsforthisrift-1,1:7)=obj.riftstruct(i).penaltypairs;
+				data(count:count+numpairsforthisrift-1,8)=obj.riftstruct(i).fill;
+				data(count:count+numpairsforthisrift-1,9)=obj.riftstruct(i).friction;
+				data(count:count+numpairsforthisrift-1,10)=obj.riftstruct(i).fraction;
+				data(count:count+numpairsforthisrift-1,11)=obj.riftstruct(i).fractionincrement;
+				data(count:count+numpairsforthisrift-1,12)=obj.riftstruct(i).state;
+				count=count+numpairsforthisrift;
+			end
+
+			WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer');
+			WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/rifts.py	(revision 18231)
@@ -0,0 +1,84 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+from isnans import isnans
+import MatlabFuncs as m
+
+class rifts(object):
+	"""
+	RIFTS class definition
+
+	   Usage:
+	      rifts=rifts();
+	"""
+
+	def __init__(self): # {{{
+		self.riftstruct     = []
+		self.riftproperties = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   rifts parameters:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)'))
+		string="%s\n%s"%(string,fielddisplay(self,'riftproperties',''))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		if numrifts:
+			if not m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
+				md.checkmessage("models with rifts are only supported in 2d for now!")
+			if not isinstance(self.riftstruct,list):
+				md.checkmessage("rifts.riftstruct should be a structure!")
+			if numpy.any(md.mesh.segmentmarkers>=2):
+				#We have segments with rift markers, but no rift structure!
+				md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
+			for i,rift in enumerate(self.riftstruct):
+				md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
+		else:
+			if self.riftstruct and numpy.any(numpy.logical_not(isnans(self.riftstruct))):
+				md.checkmessage("riftstruct should be NaN since numrifts is 0!")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		#Process rift info
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		numpairs=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 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
+
+		WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer')
+		WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.m	(revision 18231)
@@ -0,0 +1,106 @@
+%SETTINGS class definition
+%
+%   Usage:
+%      settings=settings();
+
+classdef settings
+	properties (SetAccess=public) 
+		results_on_nodes    = 0;
+		io_gather           = 0;
+		lowmem              = 0;
+		output_frequency    = 0;
+		waitonlock          = 0;
+		upload_server       = '';
+		upload_path         = '';
+		upload_login        = '';
+		upload_port         = 0;
+		upload_filename     = '';
+
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- settings -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="results_on_nodes" type="',      class(obj.results_on_nodes),'" default="',        convert2str(obj.results_on_nodes),'">',	'     <section name="settings" />','     <help> results are output for all the nodes of each element </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="io_gather" type="',          class(obj.io_gather),'" default="',           convert2str(obj.io_gather),'">',     '     <section name="settings" />','     <help> I/O gathering strategy for result outputs (default 1) </help>','</parameter>');
+            
+            % lowmen drop-down (0 or 1)
+            fprintf(fid,'%s\n%s\n%s\n%s\n',	'<parameter key ="lowmem" type="alternative" optional="true">',	'     <section name="settings" />','     <help> is the memory limited ? (0 or 1) </help>');
+            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
+
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="output_frequency" type="',          class(obj.output_frequency),'" default="',           convert2str(obj.output_frequency),'">',	'     <section name="settings" />','     <help> frequency at which results are saved in all solutions with multiple time_steps </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="waitonlock" type="',  	class(obj.waitonlock),'" default="',      convert2str(obj.waitonlock),'">',     '     <section name="settings" />','     <help> maximum number of minutes to wait for batch results (NaN to deactivate) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_server" type="',         class(obj.upload_server),'" default="',          convert2str(obj.upload_server),'">',	'     <section name="settings" />','     <help> server hostname where model should be uploaded </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_path" type="',             class(obj.upload_path),'" default="',              convert2str(obj.upload_path),'">',     '     <section name="settings" />','     <help> path on server where model should be uploaded </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_login" type="',        class(obj.upload_login),'" default="',         convert2str(obj.upload_login),'">',	'     <section name="settings" />','     <help> server login </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_port" type="',    	class(obj.upload_port),'" default="',      convert2str(obj.upload_port),'">',     '     <section name="settings" />','     <help> port login (default is 0) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="upload_filename" type="',         class(obj.upload_filename),'" default="',          convert2str(obj.upload_filename),'">',	'     <section name="settings" />','     <help> unique id generated when uploading the file to server </help>','</parameter>');
+             
+        end % }}}
+		function obj = settings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%are we short in memory ? (0 faster but requires more memory)
+			obj.lowmem=0;
+
+			%i/o:
+			obj.io_gather=1;
+
+			%results frequency by default every step
+			obj.output_frequency=1;
+
+			%this option can be activated to load automatically the results
+			%onto the model after a parallel run by waiting for the lock file
+			%N minutes that is generated once the solution has converged
+			%0 to deactivate
+			obj.waitonlock=Inf;
+
+			%upload options: 
+			upload_port         = 0;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1);
+			md = checkfield(md,'fieldname','settings.waitonlock','numel',[1]);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   general settings parameters:'));
+
+			fielddisplay(obj,'results_on_nodes','results are output for all the nodes of each element');
+			fielddisplay(obj,'io_gather','I/O gathering strategy for result outputs (default 1)');
+			fielddisplay(obj,'lowmem','is the memory limited ? (0 or 1)');
+			fielddisplay(obj,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
+			fielddisplay(obj,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
+			fielddisplay(obj,'upload_server','server hostname where model should be uploaded');
+			fielddisplay(obj,'upload_path','path on server where model should be uploaded');
+			fielddisplay(obj,'upload_login','server login');
+			fielddisplay(obj,'upload_port','port login (default is 0)');
+			fielddisplay(obj,'upload_filename','unique id generated when uploading the file to server');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','results_on_nodes','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','io_gather','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','lowmem','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','output_frequency','format','Integer');
+			if obj.waitonlock>0,
+				WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',true,'format','Boolean');
+			else
+				WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',false,'format','Boolean');
+			end
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/settings.py	(revision 18231)
@@ -0,0 +1,72 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class settings(object):
+	"""
+	SETTINGS class definition
+
+	   Usage:
+	      settings=settings();
+	"""
+
+	def __init__(self): # {{{
+		self.results_on_nodes    = 0
+		self.io_gather           = 0
+		self.lowmem              = 0
+		self.output_frequency    = 0
+		self.waitonlock          = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   general settings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"results_on_nodes","results are output for all the nodes of each element"))
+		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
+		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#are we short in memory ? (0 faster but requires more memory)
+		self.lowmem=0
+
+		#i/o:
+		self.io_gather=1
+
+		#results frequency by default every step
+		self.output_frequency=1
+
+		#this option can be activated to load automatically the results
+		#onto the model after a parallel run by waiting for the lock file
+		#N minutes that is generated once the solution has converged
+		#0 to deactivate
+		self.waitonlock=2**31-1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1)
+		md = checkfield(md,'fieldname','settings.waitonlock','numel',[1])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','results_on_nodes','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','output_frequency','format','Integer')
+		if self.waitonlock>0:
+			WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',True,'format','Boolean');
+		else:
+			WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',False,'format','Boolean');
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/snowpack.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/snowpack.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/snowpack.m	(revision 18231)
@@ -0,0 +1,479 @@
+%SNOWPACK class definition
+%
+%   Usage:
+%      snowpack=snowpack();
+
+classdef snowpack
+	properties (SetAccess=public) 
+
+		%first, the configuration fields, by category: 
+		%snowpack:  %{{{
+		snowpack_meas_tss = 0;
+		snowpack_enforce_measured_snow_heights = 0;
+		snowpack_sw_mode = 0;
+		snowpack_incoming_longwave = 0;
+		snowpack_height_of_wind_value = 0;
+		snowpack_height_of_meteo_values = 0;
+		snowpack_neutral = 0;
+		snowpack_roughness_length = 0;
+		snowpack_number_slopes = 0;
+		snowpack_snow_redistribution = 0;
+		snowpack_calculation_step_length = 0;
+		snowpack_change_bc = 0;
+		snowpack_thresh_change_bc = 0;
+		snowpack_snp_soil = 0;
+		snowpack_soil_flux = 0;
+		snowpack_geo_heat = 0;
+		snowpack_canopy = 0;
+		%}}}
+		%snowpackadvanced:  %{{{
+		snowpackadvanced_variant = ''; % use 320 kg m-3 for fixed density
+		snowpackadvanced_hn_density = '';
+		%}}}
+		%general:  %{{{
+		general_pluginpath = '';
+		general_buff_chunk_size = 0;
+		general_buff_before = 0;
+		%}}}
+		%input {{{
+		input_coordsys = '';
+		input_coordparam = '';
+		input_time_zone = 0;
+		input_meteo = '';
+		input_meteopath = '';
+		input_station1 = '';
+		input_snowfile1 = '';
+		%}}}
+		%output {{{
+		output_coordsys = '';
+		output_coordparam = '';
+		output_time_zone = 0;
+		output_meteopath = '';
+		output_experiment = '';
+		output_ts_write = 0;
+		output_ts_start = 0;
+		output_ts_days_between = 0;
+		output_profile = '';
+		output_prof_write = 0;
+		output_prof_start = 0;
+		output_prof_days_between = 0;
+		%}}}
+		%interpolations1d %{{{
+		interpolations1d_window_size = 0; %that is 5 d and 2 h; 1 d = 86400
+		interpolations1d_hnw_resample = '';
+		interpolations1d_hs_resample = '';
+		interpolations1d_tsg_resample = '';
+		interpolations1d_rho_hn_resample = '';
+		interpolations1d_vw_resample = '';
+		interpolations1d_vw_args = '';
+		%}}}
+		%filters {{{
+		filters={'TA::filter1',{'soft',[-20 10]}};
+		filters=NaN;
+		filter_values=NaN;
+
+		filters_ta_filter1 = '';
+		filters_ta_arg1 = NaN;
+		filters_rh_filter1 = '';
+		filters_rh_arg1 = NaN;
+		filters_rh_filter2 = '';
+		filters_rh_arg2 = NaN;
+		filters_iswr_filter1 = '';
+		filters_iswr_arg1 = NaN;
+		filters_iswr_filter2 = '';
+		filters_iswr_arg2 = NaN;
+		filters_rswr_filter1 = '';
+		filters_rswr_arg1 = NaN;
+		filters_rswr_filter2 = '';
+		filters_rswr_arg2 = NaN;
+
+		%for ta between 190 and 280 k;
+		filters_ilwr_filter1 = '';
+		filters_ilwr_arg1 = NaN;
+		filters_ilwr_filter2 = '';
+		filters_ilwr_arg2 = NaN;
+		filters_tss_filter1 = '';
+		filters_tss_arg1 = NaN;
+		filters_tsg_filter1 = '';
+		filters_tsg_arg1 = NaN;
+		filters_vw_filter1 = '';
+		filters_vw_arg1 = NaN;
+		filters_vw_filter2 = '';
+		filters_vw_arg2 = NaN;
+		%}}}
+
+	end
+	methods
+		function obj = snowpack(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('snowpack');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		%snowpack:  %{{{
+		obj.snowpack_meas_tss = 1;
+		obj.snowpack_enforce_measured_snow_heights = 0;
+		obj.snowpack_sw_mode = 0;
+		obj.snowpack_incoming_longwave = 1;
+		obj.snowpack_height_of_wind_value = 12.;
+		obj.snowpack_height_of_meteo_values = 12.;
+		obj.snowpack_neutral = 0;
+		obj.snowpack_roughness_length = 0.002;
+		obj.snowpack_number_slopes = 1;
+		obj.snowpack_snow_redistribution = 1;
+		obj.snowpack_calculation_step_length = 15.0;
+		obj.snowpack_change_bc = 0;
+		obj.snowpack_thresh_change_bc = -1.0;
+		obj.snowpack_snp_soil = 0;
+		obj.snowpack_soil_flux = 0;
+		obj.snowpack_geo_heat = 0.06;
+		obj.snowpack_canopy = 0;
+		%}}}
+		%snowpackadvanced:  %{{{
+		obj.snowpackadvanced_variant = 'ANTARCTICA'; % use 320 kg m-3 for fixed density
+		obj.snowpackadvanced_hn_density = 'EVENT';
+		%}}}
+		%general:  %{{{
+		obj.general_pluginpath = '/usr/local/lib/meteoio/plugins/';
+		obj.general_buff_chunk_size = 90;
+		obj.general_buff_before = 1.5;
+		%}}}
+		%input {{{
+		obj.input_coordsys = 'ch1903';
+		obj.input_coordparam = 'null';
+		obj.input_time_zone = 8;
+		obj.input_meteo = 'smet';
+		obj.input_meteopath = './input';
+		obj.input_station1 = 'domec.smet';
+		obj.input_snowfile1 = 'domec.sno';
+		%}}}
+		%output {{{
+		obj.output_coordsys = 'ch1903';
+		obj.output_coordparam = 'null';
+		obj.output_time_zone = 8;
+		obj.output_meteopath = './output';
+		obj.output_experiment = 'smet';
+		obj.output_ts_write = 1;
+		obj.output_ts_start = 0.0;
+		obj.output_ts_days_between = 0.04166667;
+		obj.output_profile = 'ascii';
+		obj.output_prof_write = 1;
+		obj.output_prof_start = 0.0;
+		obj.output_prof_days_between = 0.04166667;
+		%}}}
+		%interpolations1d %{{{
+		obj.interpolations1d_window_size = 439200; %that is 5 d and 2 h; 1 d = 86400
+		obj.interpolations1d_hnw_resample = 'none';
+		obj.interpolations1d_hs_resample = 'linear';
+		obj.interpolations1d_tsg_resample = 'linear';
+		obj.interpolations1d_rho_hn_resample = 'none';
+		obj.interpolations1d_vw_resample = 'nearest_neighbour';
+		obj.interpolations1d_vw_args = 'extrapolate';
+		%}}}
+		%filters {{{
+		obj.filters_ta_filter1 = 'min_max';
+		obj.filters_ta_arg1 = [190 280];
+		obj.filters_rh_filter1 = 'min_max';
+		obj.filters_rh_arg1 = [0.01 1.2];
+		obj.filters_rh_filter2 = 'min_max';
+		obj.filters_rh_arg2 = {'soft' 0.01 1.0};
+		obj.filters_iswr_filter1 = 'min_max';
+		obj.filters_iswr_arg1 = [-10 1500];
+		obj.filters_iswr_filter2 = 'min_max';
+		obj.filters_iswr_arg2 = {'soft' 0 1500};
+		obj.filters_rswr_filter1 = 'min_max';
+		obj.filters_rswr_arg1 = [-10 1500];
+		obj.filters_rswr_filter2 = 'min_max';
+		obj.filters_rswr_arg2 = {'soft' 0 1500};
+
+		%for ta between 190 and 280 k;
+		obj.filters_ilwr_filter1 = 'min_max';
+		obj.filters_ilwr_arg1 = [30 355];
+		obj.filters_ilwr_filter2 = 'min_max';
+		obj.filters_ilwr_arg2 = {'soft' 35 350};
+		obj.filters_tss_filter1 = 'min_max';
+		obj.filters_tss_arg1 = [180 275];
+		obj.filters_tsg_filter1 = 'min_max';
+		obj.filters_tsg_arg1 = [200 275];
+		obj.filters_vw_filter1 = 'min_max';
+		obj.filters_vw_arg1 = [-2 70];
+		obj.filters_vw_filter2 = 'min_max';
+		obj.filters_vw_arg2 = {'soft' 0 50};
+		%}}}
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			%snowpack:  %{{{
+			md=checkfield(md,'fieldname','snowpack.snowpack_meas_tss','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_enforce_measured_snow_heights','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_sw_mode','values',[0 1 2]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_incoming_longwave','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_height_of_wind_value','>=',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_height_of_meteo_values','>=',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_neutral','values',[-1 0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_roughness_length','>=',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_number_slopes','values',[1 3 5 9]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_snow_redistribution','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_calculation_step_length','>',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_change_bc','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_thresh_change_bc','<=',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_snp_soil','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_soil_flux','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.snowpack_geo_heat','>=',0);
+			md=checkfield(md,'fieldname','snowpack.snowpack_canopy','values',[0 1]);
+			%}}}
+			%snowpackadvanced:  %{{{
+			md=checkfield(md,'fieldname','snowpack.snowpackadvanced_variant','values',{'JAPAN','DEFAULT','ANTARCTICA'});
+			md=checkfield(md,'fieldname','snowpack.snowpackadvanced_hn_density','values',{'PARAMETERIZED','EVENT','MEASURED'});
+			%}}}
+			%general:  %{{{
+			md=checkfield(md,'fieldname','snowpack.general_buff_chunk_size','>',0);
+			md=checkfield(md,'fieldname','snowpack.general_buff_before','>',0);
+			%}}}
+			%input {{{
+			md=checkfield(md,'fieldname','snowpack.input_coordsys','values',{'CH1903','UTM','UPS','PROJ4','LOCAL'});
+			md=checkfield(md,'fieldname','snowpack.input_coordparam','values','null');
+			md=checkfield(md,'fieldname','snowpack.input_time_zone','>',-12,'<',12);
+			md=checkfield(md,'fieldname','snowpack.input_meteo','values',{'BORMA','COSMO','GEOTOP','GRIB','GSN','IMIS','SMET','SNOWPACK'});
+			md=checkfield(md,'fieldname','snowpack.input_meteopath','empty',1);
+			md=checkfield(md,'fieldname','snowpack.input_station1 ','empty',1);
+			md=checkfield(md,'fieldname','snowpack.input_snowfile1','empty',1);
+			%}}}
+			%output {{{
+			md=checkfield(md,'fieldname','snowpack.output_coordsys','values',{'CH1903','UTM','UPS','PROJ4','LOCAL'});
+			md=checkfield(md,'fieldname','snowpack.output_coordparam','values','null');
+			md=checkfield(md,'fieldname','snowpack.output_time_zone','>',-12,'<',12);
+			md=checkfield(md,'fieldname','snowpack.output_meteopath','empty',1);
+			md=checkfield(md,'fieldname','snowpack.output_experiment','empty',1);
+			md=checkfield(md,'fieldname','snowpack.output_ts_write','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.output_ts_start','>=',0);
+			md=checkfield(md,'fieldname','snowpack.output_ts_days_between','>=',0);
+			md=checkfield(md,'fieldname','snowpack.output_profile','values',{'ASCII','IMIS','ASCII IMIS'});
+			md=checkfield(md,'fieldname','snowpack.output_prof_write','values',[0 1]);
+			md=checkfield(md,'fieldname','snowpack.output_prof_start','>=',0);
+			md=checkfield(md,'fieldname','snowpack.output_prof_days_between','>=',0);
+			%}}}
+			%interpolations1d %{{{
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_window_size','>',0);
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_hnw_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_hs_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_tsg_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_rho_hn_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_vw_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'fieldname','snowpack.interpolations1d_vw_args','values',{'EXTRAPOLATE'});
+			%}}}
+			%filters {{{
+			filter_values={'MIN_MAX','RATE_FILTER1','RATE_FILTER2','UNHEATED_RAIN_GAUGE_FILTER','WMO_UNDERCATCH_FILTER','WMO_UNDERCATCH_FILTER-SIMPLIFIED','UNVENTILLATED_TEMPERATURE_SENSOR','ADD_AN_OFFSET'};
+
+			md=checkfield(md,'fieldname','snowpack.filters_ta_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ta_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ta_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_ta_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ta_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ta_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rh_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rh_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rh_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rh_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rh_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_filter2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rh_filter2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rh_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_arg2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rh_arg2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_iswr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_iswr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_iswr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_iswr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_iswr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_filter2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_iswr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_iswr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_arg2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_iswr_arg2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rswr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rswr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rswr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rswr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rswr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_filter2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rswr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_rswr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_arg2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_rswr_arg2','size',[1 NaN]); end
+
+			%for ta between 190 and 280 k;
+			md=checkfield(md,'fieldname','snowpack.filters_ilwr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ilwr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_ilwr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ilwr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_ilwr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_filter2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ilwr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_ilwr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_arg2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_ilwr_arg2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_tss_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tss_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_tss_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_tss_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tss_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_tss_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_tsg_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tsg_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_tsg_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_tsg_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tsg_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_tsg_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_vw_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_filter1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_vw_filter1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_vw_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_arg1,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_vw_arg1','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_vw_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_filter2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_vw_filter2','size',[1 NaN]); end
+			md=checkfield(md,'fieldname','snowpack.filters_vw_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_arg2,'MIN_MAX'), md=checkfield(md,'fieldname','snowpack.filters_vw_arg2','size',[1 NaN]); end
+
+			%}}}
+		end % }}}
+		function disp(obj) % {{{
+
+			disp(sprintf('   Snowpack solution parameters:'));
+			disp(sprintf('\n	%s','Snowpack parameters:')); % {{{
+			fielddisplay(obj,'snowpack_meas_tss',{'A measured surface temperature is available and can be reliably ','used for various consistency tests (it needs to be set to true if enabling CHANGE_BC) (0 or 1)'});
+			fielddisplay(obj,'snowpack_enforce_measured_snow_heights','Input mode by which a measurement of snow depth is used to drive the snow cover mass balance (0 or 1)');
+			fielddisplay(obj,'snowpack_sw_mode',{'Define the shortwave radiation input:',...
+				'0 Incoming shortwave radiation is measured and albedo estimated by the model',...
+				'1 Reflected shortwave radiation is available as input and albedo is estimated by the model (IMIS standard)',...
+				'2 Incoming and reflected shortwave radiation are both measured and the albedo is estimated from both measurements subject to plausibility checks.'});
+			fielddisplay(obj,'snowpack_incoming_longwave','Use the provided incoming long wave on the virtual slopes? (0 or 1)');
+			fielddisplay(obj,'snowpack_height_of_wind_value',{'The instrument height (or model layer height) for wind input data; note that height ',...
+				'is above ground for a standard SNOWPACK application but above surface (snow or ground) for Alpine3D applications '});
+			fielddisplay(obj,'snowpack_height_of_meteo_values',{'The instrument height (or model layer height) for meteorological input data except for wind,',...
+				'which may be at a different height; note that height is above ground for a standard SNOWPACK ',...
+				'application but above surface (snow or ground) for Alpine3D applications. '});
+			fielddisplay(obj,'snowpack_neutral',{'Select the atmospheric stability correction model:',...
+				'-1 use a simplified Richardson number stability correction',...
+				'0 assume standard Monin-Obukhov bulk formulation for surface exchange iteration with Paulson, Stearns and Weidner (can be used with BC_CHANGE=0)',...
+				'1 force Monin-Obukhov formulation to assume neutral conditions regardless of the actual stratification; it has been shown to work well in ',...
+				'complex terrain settings. It should be used with BC_CHANGE=1, i.e., Dirichlet /* but also is recommended with Neumann b.c., i.e., BC_CHANGE=0.'});
+			fielddisplay(obj,'snowpack_roughness_length',{'Aerodynamic roughness length as a parameter for the Monin-Obukhov bulk formulation;',...
+				'A typical value for complex terrain is 0.01 m and for snow covered flat sites 0.001 m. '});
+			fielddisplay(obj,'snowpack_number_slopes',{'Based on meteorological input from a (flat field) automatic station or numerical weather model,',...
+				'up to 8 expositions can be calculated in addition to the flat field if the corresponding *.sno files are provided. For example,',...
+				'if you provide a flat field *.snow file (mandatory), which is named KLO3.sno and you want 4 slopes to be calculated the corresponding',...
+				'slope files should be named KLO21.sno, ...,KLO24.sno '});
+			fielddisplay(obj,'snowpack_snow_redistribution',{'Specifies if redistribution of snow is allowed from (upwind) expositions to lee slopes.',...
+				'In case just the flat field is calculated, snow erosion is enabled but only for "ENFORCE_MEASURED_SNOW_HEIGHTS".'});
+				fielddisplay(obj,'snowpack_calculation_step_length',{'Internal time step (in minutes) used for model simulation. Please note that this MUST ',...
+				'be the same as HNW::accumulate (the latter being in seconds) if re-acumulating precipitation, otherwise it would lead to wrong results.'});
+			fielddisplay(obj,'snowpack_change_bc',{'Use measured surface temperature as Dirichlet temperature BC for sub-freezing snowpacks and switch to ',...
+			'Neumann only for melting snowpacks. If set to false, assumes Neumann boundary conditions.'});
+			fielddisplay(obj,'snowpack_thresh_change_bc','Threshold value (small number below freezing), which switches from Dirichlet to Neumann BCs if CHANGE_BC is selected');
+			fielddisplay(obj,'snowpack_snp_soil','Soil layers as defined by the *.sno files are included in the simulation');
+			fielddisplay(obj,'snowpack_soil_flux','Assume that the lower temperature boundary condition is given by GEO_HEAT (Neumann) and not by a measured temperature');
+			fielddisplay(obj,'snowpack_geo_heat','Constant geothermal heat flux at great) depth W m-2): Lower flux boundary condition for temperature equation if BC is Neumann');
+			fielddisplay(obj,'snowpack_canopy','Switch to tell the model that canopy is present (note that Canopy parameters should then be provided in the *.sno file)');
+			% }}}
+			disp(sprintf('\n	%s','Snowpackadvanced parameters:')); % {{{
+			fielddisplay(obj,'snowpackadvanced_variant','variant selection (includes a choice of specific models, DEFAULT, ANTARCTICA and JAPAN )'); % use 320 kg m-3 for fixed density
+			fielddisplay(obj,'snowpackadvanced_hn_density',{'Fixed value to be used as new snow density if a constant density model is chosen, otherwise the choices are "PARAMETERIZED" "EVENT" "MEASURED"'});
+			% }}}
+			disp(sprintf('\n	%s','General parameters:')); % {{{
+			fielddisplay(obj,'general_pluginpath','');
+			fielddisplay(obj,'general_buff_chunk_size','Size in days of a chunk of data to read at once.');
+			fielddisplay(obj,'general_buff_before','Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the beginning of the buffer (therefore, it takes a value in days). ');
+			% }}}
+			disp(sprintf('\n	%s','Input  parameter:')); % {{{
+			fielddisplay(obj,'input_coordsys','coordinates in the Swiss Grid (http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf). One of CH1903,UTM,UPS,PROJ4 or LOCAL');
+			fielddisplay(obj,'input_coordparam',' ');
+			fielddisplay(obj,'input_time_zone',' ');
+			fielddisplay(obj,'input_meteo','plugin for METEO data (one of BORMA,COSMO,GEOTOP,GRIB,GS,IMIS,SMET,SNOWPACK');
+			fielddisplay(obj,'input_meteopath','string containing the path to the xml files.');
+			fielddisplay(obj,'input_station1','Meteorology file for station number #');
+			fielddisplay(obj,'input_snowfile1','File name for the initial snow profile for station number #');
+			% }}}
+			disp(sprintf('\n	%s','Output parameters:')); % {{{
+			fielddisplay(obj,'output_coordsys','Coordinates in the Swiss Grid http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf. One of CH1903,UTM,UPS,PROJ4 or LOCAL ');
+			fielddisplay(obj,'output_coordparam','');
+			fielddisplay(obj,'output_time_zone','');
+			fielddisplay(obj,'output_meteopath','Path to the outputs (this path MUST exist, it won''t be created)');
+			fielddisplay(obj,'output_experiment','Option to give an additional simulation specific output name to the run in addition to "STATION_NAME"');
+			fielddisplay(obj,'output_ts_write','Write meteo data out? (0 or 1)');
+			fielddisplay(obj,'output_ts_start','When to start writing meteo data out (offset, in days)');
+			fielddisplay(obj,'output_ts_days_between','How often to write meteo data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
+			fielddisplay(obj,'output_profile','How to write the profiles (default: ASCII, choice is ASCII,IMIS or ASCII IMIS)');
+)');
+			fielddisplay(obj,'output_prof_write','Write profile data out? (0 or 1) ');
+			fielddisplay(obj,'output_prof_start','When to start writing profile data out (offset, in days)');
+			fielddisplay(obj,'output_prof_days_between','How often to write profile data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
+			% }}}
+			disp(sprintf('\n	%s','Interpolations1d parameters:')); % {{{
+			fielddisplay(obj,'interpolations1d_window_size','Affects resampling: expresses (in seconds) how far a valid point can be searched for when re-interpolating a missing value'); 
+			fielddisplay(obj,'interpolations1d_hnw_resample','NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR');
+ ');
+			fielddisplay(obj,'interpolations1d_hs_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window. (NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(obj,'interpolations1d_tsg_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window.(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(obj,'interpolations1d_rho_hn_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(obj,'interpolations1d_vw_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(obj,'interpolations1d_vw_args','default nothing, otherwise, ''extrapolcate''');
+			% }}}
+			disp(sprintf('\n	%s','Filters parameters:')); % {{{
+			fielddisplay(obj,'filters_ta_filter1',' ');
+			fielddisplay(obj,'filters_ta_arg1','');
+			fielddisplay(obj,'filters_rh_filter1',' ');
+			fielddisplay(obj,'filters_rh_arg1','');
+			fielddisplay(obj,'filters_rh_filter2',' ');
+			fielddisplay(obj,'filters_rh_arg2','');
+			fielddisplay(obj,'filters_iswr_filter1',' ');
+			fielddisplay(obj,'filters_iswr_arg1','');
+			fielddisplay(obj,'filters_iswr_filter2',' ');
+			fielddisplay(obj,'filters_iswr_arg2','');
+			fielddisplay(obj,'filters_rswr_filter1',' ');
+			fielddisplay(obj,'filters_rswr_arg1','');
+			fielddisplay(obj,'filters_rswr_filter2',' ');
+			fielddisplay(obj,'filters_rswr_arg2','');
+
+			%for ta between 190 and 280 k;
+			fielddisplay(obj,'filters_ilwr_filter1',' ');
+			fielddisplay(obj,'filters_ilwr_arg1','');
+			fielddisplay(obj,'filters_ilwr_filter2',' ');
+			fielddisplay(obj,'filters_ilwr_arg2','');
+			fielddisplay(obj,'filters_tss_filter1',' ');
+			fielddisplay(obj,'filters_tss_arg1','');
+			fielddisplay(obj,'filters_tsg_filter1',' ');
+			fielddisplay(obj,'filters_tsg_arg1','');
+			fielddisplay(obj,'filters_vw_filter1',' ');
+			fielddisplay(obj,'filters_vw_arg1','');
+			fielddisplay(obj,'filters_vw_filter2',' ');
+			fielddisplay(obj,'filters_vw_arg2','');
+			% }}}
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','restol','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','abstol','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','isnewton','format','Integer');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','FSreconditioning','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','shelf_dampening','format','Integer');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','referential','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','snowpack','fieldname','requested_outputs','format','StringArray');
+			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
+			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
+			WriteData(fid,'data',obj.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/spheremesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/spheremesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/spheremesh.m	(revision 18231)
@@ -0,0 +1,96 @@
+%SPHEREMESH class definition
+%
+%   Usage:
+%      spheremesh=spheremesh();
+
+classdef spheremesh
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN;
+		r                           = NaN;
+		theta                       = NaN;
+		phi                         = NaN
+		elements                    = NaN
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+	end
+	methods
+		function obj = spheremesh(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the avergaded number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','spheremesh.x','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.y','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.z','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.r','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.theta','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.phi','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','spheremesh.elements','NaN',1,'>',0,'values',1:md.spheremesh.numberofvertices);
+			md = checkfield(md,'fieldname','spheremesh.elements','size',[md.spheremesh.numberofelements 3]);
+			if any(~ismember(1:md.spheremesh.numberofvertices,sort(unique(md.spheremesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the spheremesh outline');
+			end
+			md = checkfield(md,'fieldname','spheremesh.numberoflayers','>=',0);
+			md = checkfield(md,'fieldname','spheremesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','spheremesh.numberofvertices','>',0);
+			md = checkfield(md,'fieldname','spheremesh.elementconnectivity','size',[md.spheremesh.numberofelements 3],'NaN',1);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(obj,'r','vertices r coordinate [m]');
+			fielddisplay(obj,'theta','vertices theta coordinate [degrees]');
+			fielddisplay(obj,'phi','vertices phi coordinate [degrees]');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','phi','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.m	(revision 18231)
@@ -0,0 +1,83 @@
+%STEADYSTATE class definition
+%
+%   Usage:
+%      steadystate=steadystate();
+
+classdef steadystate
+	properties (SetAccess=public) 
+		reltol            = 0;
+		maxiter           = 0;
+		requested_outputs = {};
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- steadystate -->\n');            
+                    
+            % steadystate solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="steadystate solution parameters">','<section name="steadystate" />');                    
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="reltol" type="',class(obj.reltol),'" default="',convert2str(obj.reltol),'">','     <section name="steadystate" />','     <help> relative tolerance criterion [K] </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(obj.maxiter),'" default="',convert2str(obj.maxiter),'">','     <section name="steadystate" />','     <help> maximum number of iterations </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="steadystate" />','     <help> additional requested outputs </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = steadystate(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+			%maximum of steady state iterations
+			obj.maxiter=100;
+
+			%Relative tolerance for the steadystate convertgence
+			obj.reltol=0.01;
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function list=defaultoutputs(self,md) % {{{
+
+			list =  [md.stressbalance.defaultoutputs(md) md.thermal.defaultoutputs(md)];
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=SteadystateSolutionEnum(), return; end;
+
+			if md.timestepping.time_step~=0,
+				md = checkmessage(md,['for a steadystate computation, timestepping.time_step must be zero.']);
+			end
+			md = checkfield(md,'fieldname','steadystate.requested_outputs','stringrow',1);
+
+			if isnan(md.stressbalance.reltol),
+				md = checkmessage(md,['for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!']);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   steadystate solution parameters:'));
+
+			fielddisplay(obj,'reltol','relative tolerance criterion');
+			fielddisplay(obj,'maxiter','maximum number of iterations');
+			fielddisplay(obj,'requested_outputs','additional requested outputs');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum,'format','StringArray');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/steadystate.py	(revision 18231)
@@ -0,0 +1,75 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class steadystate(object):
+	"""
+	STEADYSTATE class definition
+
+	   Usage:
+	      steadystate=steadystate();
+	"""
+
+	def __init__(self): # {{{
+		self.reltol            = 0
+		self.maxiter           = 0
+		self.requested_outputs = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   steadystate solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','relative tolerance criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional requested outputs'))
+		return string
+		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		return md.stressbalance.defaultoutputs(md)+md.thermal.defaultoutputs(md)
+
+	#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#maximum of steady state iterations
+		self.maxiter=100
+
+		#Relative tolerance for the steadystate convertgence
+		self.reltol=0.01
+
+		#default output
+		self.requested_outputs=['default']
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==SteadystateSolutionEnum():
+			return md
+
+		if not md.timestepping.time_step==0:
+			md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
+
+		if numpy.isnan(md.stressbalance.reltol):
+			md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!")
+
+		md = checkfield(md,'fieldname','steadystate.requested_outputs','stringrow',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.m	(revision 18231)
@@ -0,0 +1,245 @@
+%STRESSBALANC Eclass definition
+%
+%   Usage:
+%      stressbalance=stressbalance();
+
+classdef stressbalance
+	properties (SetAccess=public) 
+		spcvx                  = NaN;
+		spcvy                  = NaN;
+		spcvz                  = NaN;
+		restol                 = 0;
+		reltol                 = 0;
+		abstol                 = 0;
+		isnewton               = 0;
+		FSreconditioning       = 0;
+		viscosity_overshoot    = 0;
+		maxiter                = 0;
+		shelf_dampening        = 0;
+		vertex_pairing         = NaN;
+		penalty_factor         = NaN;
+		rift_penalty_lock      = NaN;
+		rift_penalty_threshold = 0;
+		referential            = NaN;
+		loadingforce           = NaN;
+		requested_outputs      = {};
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- StressBalance solution parameters: -->');
+            
+            % Convergence criteria            
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Convergence criteria">','<section name="stressbalance" />'); 
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="restol" type="',      class(obj.restol),'" default="',        convert2str(obj.restol),'">',	'     <section name="stressbalance" />','     <help> mechanical equilibrium residual convergence criterion </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="reltol" type="',          class(obj.reltol),'" default="',            convert2str(obj.reltol),'">',     '     <section name="stressbalance" />','     <help> velocity relative convergence criterion, NaN: not applied </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="abstol" type="',        class(obj.abstol),'" default="',          convert2str(obj.abstol),'">',	'     <section name="stressbalance" />','     <help> velocity absolute convergence criterion, NaN: not applied </help>','</parameter>');
+             
+             %is newton drop-down (0,1,or 2)
+             fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="isnewton" type="alternative" optional="false">',	'     <section name="stressbalance" />','     <help> 0: Picards fixed point, 1: Newtons method, 2: hybrid </help>');
+             fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+             fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
+             fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+    
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',  	class(obj.maxiter),'" default="',       convert2str(obj.maxiter),'">',     '     <section name="stressbalance" />','     <help> maximum number of nonlinear iterations </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="viscosity_overshoot" type="',         class(obj.viscosity_overshoot),'" default="',           convert2str(obj.viscosity_overshoot),'">',	'     <section name="stressbalance" />','     <help> over-shooting constant new=new+C*(new-old) </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % boundary conditions    
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Boundary conditions">','<section name="stressbalance" />'); 			 
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvx" type="',     	class(obj.spcvx),'" default="',    	convert2str(obj.spcvx),'">',     '     <section name="stressbalance" />','     <help> x-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvy" type="',     	class(obj.spcvy),'" default="',    	convert2str(obj.spcvy),'">',	'     <section name="stressbalance" />','     <help> y-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvz" type="',    	class(obj.spcvz),'" default="',    	convert2str(obj.spcvz),'">',     '     <section name="stressbalance" />','     <help> z-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');
+            
+            % Rift options   
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Rift options">','<section name="stressbalance" />'); 	
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="rift_penalty_threshold" type="',    	class(obj.rift_penalty_threshold),'" default="',       convert2str(obj.rift_penalty_threshold),'">',     '     <section name="stressbalance" />','     <help> threshold for instability of mechanical constraints </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    	'<parameter key ="rift_penalty_lock" type="',         class(obj.rift_penalty_lock),'" default="',           convert2str(obj.rift_penalty_lock),'">',	'     <section name="stressbalance" />','     <help> number of iterations before rift penalties are locked </help>','</parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>'); 
+            
+            %others
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Other">','<section name="stressbalance" />'); 	
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="shelf_dampening" type="',  	class(obj.shelf_dampening),'" default="',       convert2str(obj.shelf_dampening),'">',     '     <section name="stressbalance" />','     <help> use dampening for floating ice ? Only for FS model </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="FSreconditioning" type="', 	class(obj.FSreconditioning),'" default="',           convert2str(obj.FSreconditioning),'">',	'     <section name="stressbalance" />','     <help> multiplier for incompressibility equation. Only for FS model </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="referential" type="',  	class(obj.referential),'" default="',       convert2str(obj.referential),'">',     '     <section name="stressbalance" />','     <help> local referential </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="loadingforce" type="', 	class(obj.loadingforce),'" default="',           convert2str(obj.loadingforce),'">',	'     <section name="stressbalance" />','     <help> loading force applied on each point [N/m^3] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="requested_outputs" type="',  	class(obj.requested_outputs),'" default="',       convert2str(obj.requested_outputs),'">',     '     <section name="stressbalance" />','     <help> additional outputs requested </help>','</parameter>');
+             
+            
+            fprintf(fid,'%s\n%s\n','</frame>'); 
+        end % }}}
+		function obj = stressbalance(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('stressbalance');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			 %maximum of non-linear iterations.
+			 obj.maxiter=100;
+
+			 %Convergence criterion: absolute, relative and residual
+			 obj.restol=10^-4; 
+			 obj.reltol=0.01;
+			 obj.abstol=10;
+
+			 obj.FSreconditioning=10^13;
+			 obj.shelf_dampening=0;
+
+			 %Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
+			 obj.penalty_factor=3;
+
+			 %coefficient to update the viscosity between each iteration of
+			 %a stressbalance according to the following formula
+			 %viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
+			 obj.viscosity_overshoot=0;
+
+			 %Stop the iterations of rift if below a threshold
+			 obj.rift_penalty_threshold=0;
+
+			 %in some solutions, it might be needed to stop a run when only
+			 %a few constraints remain unstable. For thermal computation, this
+			 %parameter is often used.
+			 obj.rift_penalty_lock=10;
+
+			 %output default:
+			 obj.requested_outputs={'default'};
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses), return; end
+
+			md = checkfield(md,'fieldname','stressbalance.spcvx','forcing',1);
+			md = checkfield(md,'fieldname','stressbalance.spcvy','forcing',1);
+			md = checkfield(md,'fieldname','stressbalance.spcvz','forcing',1);
+			md = checkfield(md,'fieldname','stressbalance.restol','size',[1 1],'>',0,'NaN',1);
+			md = checkfield(md,'fieldname','stressbalance.reltol','size',[1 1]);
+			md = checkfield(md,'fieldname','stressbalance.abstol','size',[1 1]);
+			md = checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0 1 2]);
+			md = checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1 1],'NaN',1);
+			md = checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1 1],'NaN',1);
+			md = checkfield(md,'fieldname','stressbalance.maxiter','size',[1 1],'>=',1);
+			md = checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices 6]);
+			md = checkfield(md,'fieldname','stressbalance.loadingforce','size',[md.mesh.numberofvertices 3]);
+			md = checkfield(md,'fieldname','stressbalance.requested_outputs','stringrow',1);
+
+			%singular solution
+			if ~(any(~isnan(md.stressbalance.spcvx)) | any(~isnan(md.stressbalance.spcvy))),
+				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
+			end
+			%CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+			if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
+				md = checkmessage(md,['Each line of stressbalance.referential should contain either only NaN values or no NaN values']);
+			end
+			%CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+			if any(sum(isnan(md.stressbalance.referential),2)==0),
+				pos=find(sum(isnan(md.stressbalance.referential),2)==0);
+				if any(abs(dot(md.stressbalance.referential(pos,1:3),md.stressbalance.referential(pos,4:6),2))>eps),
+					md = checkmessage(md,['Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal']);
+				end
+			end
+			%CHECK THAT NO rotation specified for FS Grounded ice at base
+			if strcmp(domaintype(md.mesh),'3D') & md.flowequation.isFS,
+				pos=find(md.mask.groundedice_levelset>0. & md.mesh.vertexonbase);
+				if any(~isnan(md.stressbalance.referential(pos,:))),
+					md = checkmessage(md,['no referential should be specified for basal vertices of grounded ice']);
+				end
+				md = checkfield(md,'fieldname','stressbalance.FSreconditioning','>',0);
+			end
+		end % }}}
+		function list=defaultoutputs(self,md) % {{{
+
+			if dimension(md.mesh)==3,
+				list = {'Vx','Vy','Vz','Vel','Pressure'};
+			elseif dimension(md.mesh)==2,
+				list = {'Vx','Vy','Vel','Pressure'};
+			else
+				error('mesh type not supported yet');
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+
+			disp(sprintf('   StressBalance solution parameters:'));
+
+			disp(sprintf('\n      %s','Convergence criteria:'));
+			fielddisplay(obj,'restol','mechanical equilibrium residual convergence criterion');
+			fielddisplay(obj,'reltol','velocity relative convergence criterion, NaN: not applied');
+			fielddisplay(obj,'abstol','velocity absolute convergence criterion, NaN: not applied');
+			fielddisplay(obj,'isnewton','0: Picard''s fixed point, 1: Newton''s method, 2: hybrid');
+			fielddisplay(obj,'maxiter','maximum number of nonlinear iterations');
+			fielddisplay(obj,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
+
+			disp(sprintf('\n      %s','boundary conditions:'));
+			fielddisplay(obj,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]');
+			fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]');
+			fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]');
+
+			disp(sprintf('\n      %s','Rift options:'));
+			fielddisplay(obj,'rift_penalty_threshold','threshold for instability of mechanical constraints');
+			fielddisplay(obj,'rift_penalty_lock','number of iterations before rift penalties are locked');
+
+			disp(sprintf('\n      %s','Penalty options:'));
+			fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
+			fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
+
+			disp(sprintf('\n      %s','Other:'));
+			fielddisplay(obj,'shelf_dampening','use dampening for floating ice ? Only for FS model');
+			fielddisplay(obj,'FSreconditioning','multiplier for incompressibility equation. Only for FS model');
+			fielddisplay(obj,'referential','local referential');
+			fielddisplay(obj,'loadingforce','loading force applied on each point [N/m^3]');
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','restol','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','abstol','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','isnewton','format','Integer');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','FSreconditioning','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','shelf_dampening','format','Integer');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',obj,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1);
+
+			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
+			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
+			WriteData(fid,'data',obj.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum,'format','StringArray');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/stressbalance.py	(revision 18231)
@@ -0,0 +1,198 @@
+import numpy
+import sys
+import copy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class stressbalance(object):
+	"""
+	STRESSBALANCE class definition
+
+	   Usage:
+	      stressbalance=stressbalance();
+	"""
+
+	def __init__(self): # {{{
+		self.spcvx                    = float('NaN')
+		self.spcvy                    = float('NaN')
+		self.spcvz                    = float('NaN')
+		self.restol                   = 0
+		self.reltol                   = 0
+		self.abstol                   = 0
+		self.isnewton                 = 0
+		self.FSreconditioning     = 0
+		self.viscosity_overshoot      = 0
+		self.icefront                 = float('NaN')
+		self.maxiter                  = 0
+		self.shelf_dampening          = 0
+		self.vertex_pairing           = float('NaN')
+		self.penalty_factor           = float('NaN')
+		self.rift_penalty_lock        = float('NaN')
+		self.rift_penalty_threshold   = 0
+		self.referential              = float('NaN')
+		self.loadingforce             = float('NaN')
+		self.requested_outputs        = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   StressBalance solution parameters:'
+		string="%s\n%s"%(string,'      Convergence criteria:')
+		string="%s\n%s"%(string,fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','velocity relative convergence criterion, NaN: not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN: not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid"))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
+
+		string="%s\n%s"%(string,'\n      boundary conditions:')
+		string="%s\n%s"%(string,fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'icefront','segments on ice front list (last column 0: Air, 1: Water, 2: Ice'))
+
+		string="%s\n%s"%(string,'\n      Rift options:')
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked'))
+
+		string="%s\n%s"%(string,'\n      Penalty options:')
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized'))
+
+		string="%s\n%s"%(string,'\n      Other:')
+		string="%s\n%s"%(string,fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for FS model'))
+		string="%s\n%s"%(string,fielddisplay(self,'FSreconditioning','multiplier for incompressibility equation. Only for FS model'))
+		string="%s\n%s"%(string,fielddisplay(self,'referential','local referential'))
+		string="%s\n%s"%(string,fielddisplay(self,'loadingforce','loading force applied on each point [N/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		#maximum of non-linear iterations.
+		self.maxiter=100
+
+		#Convergence criterion: absolute, relative and residual
+		self.restol=10**-4
+		self.reltol=0.01
+		self.abstol=10
+
+		self.FSreconditioning=10**13
+		self.shelf_dampening=0
+
+		#Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+
+		#coefficient to update the viscosity between each iteration of
+		#a stressbalance according to the following formula
+		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
+		self.viscosity_overshoot=0
+
+		#Stop the iterations of rift if below a threshold
+		self.rift_penalty_threshold=0
+
+		#in some solutions, it might be needed to stop a run when only
+		#a few constraints remain unstable. For thermal computation, this
+		#parameter is often used.
+		self.rift_penalty_lock=10
+
+		#output default:
+		self.requested_outputs=['default']
+
+		return self
+	#}}}
+	def defaultoutputs(self,md): # {{{
+
+		if md.mesh.dimension()==3:
+			list = ['Vx','Vy','Vz','Vel','Pressure']
+		else:
+			list = ['Vx','Vy','Vel','Pressure']
+		return list
+
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if StressbalanceAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','stressbalance.spcvx','forcing',1)
+		md = checkfield(md,'fieldname','stressbalance.spcvy','forcing',1)
+		if m.strcmp(md.mesh.domaintype(),'3D'):
+			md = checkfield(md,'fieldname','stressbalance.spcvz','forcing',1)
+		md = checkfield(md,'fieldname','stressbalance.restol','size',[1],'>',0)
+		md = checkfield(md,'fieldname','stressbalance.reltol','size',[1])
+		md = checkfield(md,'fieldname','stressbalance.abstol','size',[1])
+		md = checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1],'NaN',1)
+		md = checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1],'NaN',1)
+		md = checkfield(md,'fieldname','stressbalance.maxiter','size',[1],'>=',1)
+		md = checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices,6])
+		md = checkfield(md,'fieldname','stressbalance.loadingforce','size',[md.mesh.numberofvertices,3])
+		md = checkfield(md,'fieldname','stressbalance.requested_outputs','stringrow',1);
+
+		#singular solution
+#		if ~any((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy))==2),
+		if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)),numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)))):
+			md.checkmessage("model is not well posed (singular). You need at least one node with fixed velocity!")
+		#CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+#		if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
+		if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=6)):
+			md.checkmessage("Each line of stressbalance.referential should contain either only NaN values or no NaN values")
+		#CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+#		if any(sum(isnan(md.stressbalance.referential),2)==0),
+		if numpy.any(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)==0):
+			pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)) if item==0]
+#			numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
+#			if numpy.any(numpy.abs(numpy.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
+#				md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+			for item in md.stressbalance.referential[pos,:]:
+				if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
+					md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+		#CHECK THAT NO rotation specified for FS Grounded ice at base
+		if m.strcmp(md.mesh.domaintype(),'3D') and md.flowequation.isFS:
+			pos=numpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))
+			if numpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):
+				md.checkmessage("no referential should be specified for basal vertices of grounded ice")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','restol','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','viscosity_overshoot','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1)
+
+		WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum())
+		WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum())
+		WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum())
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/taoinversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/taoinversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/taoinversion.m	(revision 18231)
@@ -0,0 +1,190 @@
+%TAOINVERSION class definition
+%
+%   Usage:
+%      taoinversion=taoinversion();
+
+classdef taoinversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		incomplete_adjoint          = 0
+		control_parameters          = NaN
+		maxsteps                    = 0
+		maxiter                     = 0
+		fatol                       = 0
+		frtol                       = 0
+		gatol                       = 0
+		grtol                       = 0
+		gttol                       = 0
+		algorithm                   = ''
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		min_parameters              = NaN
+		max_parameters              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+	end
+	methods
+		function obj = taoinversion(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(taoinversion(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%default is incomplete adjoint for now
+			obj.incomplete_adjoint=1;
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			obj.control_parameters={'FrictionCoefficient'};
+
+			%number of iterations and steps
+			obj.maxsteps=20;
+			obj.maxiter =30;
+
+			%default tolerances
+			obj.fatol = 0;
+			obj.frtol = 0;
+			obj.gatol = 0;
+			obj.grtol = 0;
+			obj.gttol = 1e-4;
+
+			%minimization algorithm
+			obj.algorithm = 'tao_blmvm';
+
+			%several responses can be used:
+			obj.cost_functions=101;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~obj.iscontrol, return; end
+
+			if ~IssmConfig('_HAVE_TAO_'),
+				md = checkmessage(md,['TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO']);
+			end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness'});
+			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.fatol','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.frtol','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.gatol','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.grtol','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.algorithm','values',{'tao_blmvm','tao_cg','tao_lmvm'});
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   taoinversion parameters:'));
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(obj,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(obj,'fatol','convergence criterion: f(X)-f(X*) (X: current iteration, X*: "true" solution, f: cost function)');
+			fielddisplay(obj,'frtol','convergence criterion: |f(X)-f(X*)|/|f(X*)|');
+			fielddisplay(obj,'gatol','convergence criterion: ||g(X)|| (g: gradient of the cost function)');
+			fielddisplay(obj,'grtol','convergence criterion: ||g(X)||/|f(X)|');
+			fielddisplay(obj,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+			fielddisplay(obj,'algorithm','minimization algorithm: ''tao_blmvm'', ''tao_cg'', ''tao_lmvm''');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'enum',InversionTypeEnum(),'data',1,'format','Integer');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','fatol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','frtol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','gatol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','grtol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','gttol','format','Double');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','algorithm','format','String');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1);
+
+			%process control parameters
+			num_control_parameters=numel(obj.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(obj.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(obj.cost_functions,2);
+			data=obj.cost_functions;
+			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.m	(revision 18231)
@@ -0,0 +1,136 @@
+%THERMAL class definition
+%
+%   Usage:
+%      thermal=thermal();
+
+classdef thermal
+	properties (SetAccess=public) 
+		spctemperature    = NaN;
+		penalty_threshold = 0;
+		stabilization     = 0;
+		maxiter           = 0;
+		penalty_lock      = 0;
+		penalty_factor    = 0;
+		isenthalpy        = 0;
+		isdynamicbasalspc = 0;
+		requested_outputs = {};
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- thermal -->\n');            
+                    
+            % thermal solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Thermal solution parameters">','<section name="thermal" />');                    
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="spctemperature" type="',class(obj.spctemperature),'" default="',convert2str(obj.spctemperature),'">','     <section name="thermal" />','     <help> temperature constraints (NaN means no constraint) [K] </help>','  </parameter>');
+                
+            % penalty_threshold drop-down (0, 1, or 2)
+            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="penalty_threshold" type="alternative"  optional="false">','     <section name="thermal" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
+            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+            fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
+            fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="stabilization" type="',class(obj.stabilization),'" default="',convert2str(obj.stabilization),'">','     <section name="thermal" />','     <help> maximum number of non linear iterations </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(obj.maxiter),'" default="',convert2str(obj.maxiter),'">','     <section name="thermal" />','     <help> stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_lock" type="',class(obj.penalty_lock),'" default="',convert2str(obj.penalty_lock),'">','     <section name="thermal" />','     <help> threshold to declare convergence of thermal solution (default is 0)  </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_factor" type="',class(obj.penalty_factor),'" default="',convert2str(obj.penalty_factor),'">','     <section name="thermal" />','     <help> scaling exponent (default is 3) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isenthalpy" type="',class(obj.isenthalpy),'" default="',convert2str(obj.isenthalpy),'">','     <section name="thermal" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdynamicbasalspc" type="',class(obj.isdynamicbasalspc),'" default="',convert2str(obj.isdynamicbasalspc),'">','     <section name="thermal" />','     <help> enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)  </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="thermal" />','     <help> additional outputs requested </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = thermal(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+
+			if self.isenthalpy,
+				list = {'Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsGroundediceMeltingRate'};
+			else
+				list = {'Temperature','BasalforcingsGroundediceMeltingRate'};
+			end
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Number of unstable constraints acceptable
+			obj.penalty_threshold=0;
+
+			%Type of stabilization used
+			obj.stabilization=1;
+
+			%Maximum number of iterations
+			obj.maxiter=100;
+
+			%factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+
+			%Should we use cold ice (default) or enthalpy formulation
+			obj.isenthalpy=0;
+
+			%will basal boundary conditions be set dynamically
+			obj.isdynamicbasalspc=0;
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if (~ismember(ThermalAnalysisEnum(),analyses) & ~ismember(EnthalpyAnalysisEnum(),analyses)) | (solution==TransientSolutionEnum() & md.transient.isthermal==0), return; end
+
+			md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0 1 2]);
+			md = checkfield(md,'fieldname','thermal.spctemperature','forcing',1);
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy & dimension(md.mesh)==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,'fieldname','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,'fieldname','thermal.isenthalpy','numel',[1],'values',[0 1]);
+				md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[0 1]);
+				if(md.thermal.isenthalpy)
+					md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[1], 'message',['for enthalpy run thermal.isdynamicbasalspc should be 1']);
+				end
+	    end
+
+		 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1);
+    end % }}} 
+		function disp(obj) % {{{
+			disp(sprintf('   Thermal solution parameters:'));
+
+			fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint) [K]');
+			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
+			fielddisplay(obj,'maxiter','maximum number of non linear iterations');
+			fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+			fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)');
+			fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
+			fielddisplay(obj,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)');
+			fielddisplay(obj,'isdynamicbasalspc',['enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)']);
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'fieldname','isenthalpy','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isdynamicbasalspc','format','Boolean');
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray');
+        	end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/thermal.py	(revision 18231)
@@ -0,0 +1,113 @@
+import numpy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import MatlabFuncs as m
+
+class thermal(object):
+	"""
+	THERMAL class definition
+
+	   Usage:
+	      thermal=thermal();
+	"""
+
+	def __init__(self): # {{{
+		self.spctemperature    = float('NaN')
+		self.penalty_threshold = 0
+		self.stabilization     = 0
+		self.maxiter           = 0
+		self.penalty_lock      = 0
+		self.penalty_factor    = 0
+		self.isenthalpy        = 0
+		self.isdynamicbasalspc = 0;
+		self.requested_outputs = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   Thermal solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint) [K]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of non linear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdynamicbasalspc','enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+		return string
+		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		if self.isenthalpy:
+			return ['Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsGroundediceMeltingRate']
+		else:
+			return ['Temperature','BasalforcingsGroundediceMeltingRate']
+
+	#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Number of unstable constraints acceptable
+		self.penalty_threshold=0
+
+		#Type of stabilization used
+		self.stabilization=1
+
+		#Maximum number of iterations
+		self.maxiter=100
+
+		#factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+
+		#Should we use cold ice (default) or enthalpy formulation
+		self.isenthalpy=0
+
+		#will basal boundary conditions be set dynamically
+		self.isdynamicbasalspc=0;
+
+		#default output
+		self.requested_outputs=['default']
+		return self
+
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (ThermalAnalysisEnum() not in analyses and EnthalpyAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			return md
+
+		md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'fieldname','thermal.spctemperature','forcing',1)
+		if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy 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,'fieldname','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,'fieldname','thermal.isenthalpy','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
+			if(md.thermal.isenthalpy):
+				md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[1], 'message',"for enthalpy run thermal.isdynamicbasalspc should be true")
+		md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdynamicbasalspc','format','Boolean');
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.m	(revision 18231)
@@ -0,0 +1,88 @@
+%TIMESTEPPING Class definition
+%
+%   Usage:
+%      timestepping=timestepping();
+
+classdef timestepping
+	properties (SetAccess=public) 
+		start_time      = 0.;
+		final_time      = 0.;
+		time_step       = 0.;
+		time_adapt      = 0;
+		cfl_coefficient = 0.;
+		interp_forcings = 1;
+	end
+	methods
+       function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- Timestepping -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="start_time" type="',              class(obj.start_time),'" default="',                  convert2str(obj.start_time),'">',              '     <section name="timestepping" />','     <help> simulation starting time [yr] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="final_time" type="',            class(obj.final_time),'" default="',                convert2str(obj.final_time),'">',   '     <section name="timestepping" />','     <help> final time to stop the simulation [yr] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="time_step" type="',      class(obj.time_step),'" default="',          convert2str(obj.time_step),'">',            '     <section name="timestepping" />','     <help> length of time steps [yr] </help>','</parameter>');
+            % time_adapt 0 or 1 drop down
+            fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="time_adapt" type="alternative" optional="false">','     <section name="timestepping" />','     <help> use cfl condition to define time step ? (0 or 1)  </help>');
+            fprintf(fid, '%s\n',   '       <option value="0" type="string" default="true"></option>');
+            fprintf(fid, '%s\n%s\n',   '       <option value="1" type="string" default="false"></option>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="cfl_coefficient" type="',       class(obj.cfl_coefficient),'" default="',              convert2str(obj.cfl_coefficient),'">',              '     <section name="timestepping" />','     <help> coefficient applied to cfl condition </help>','</parameter>');
+            
+        end % }}}
+        
+		function obj = timestepping(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%time between 2 time steps
+			obj.time_step=1./2.;
+
+			%final time
+			obj.final_time=10.*obj.time_step;
+
+			%time adaptation? 
+			obj.time_adapt=0;
+			obj.cfl_coefficient=0.5;
+
+			%should we interpolate forcings between timesteps?
+			obj.interp_forcings=1;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1);
+			md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1);
+			md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1);
+			md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
+			md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0 1]);
+			if obj.final_time-obj.start_time<0,
+				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
+			end 
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   timestepping parameters:'));
+
+			fielddisplay(obj,'start_time','simulation starting time [yr]');
+			fielddisplay(obj,'final_time','final time to stop the simulation [yr]');
+			fielddisplay(obj,'time_step','length of time steps [yr]');
+			fielddisplay(obj,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
+			fielddisplay(obj,'cfl_coefficient','coefficient applied to cfl condition');
+			fielddisplay(obj,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'fieldname','start_time','format','Double','scale',yts);
+			WriteData(fid,'object',obj,'fieldname','final_time','format','Double','scale',yts);
+			WriteData(fid,'object',obj,'fieldname','time_step','format','Double','scale',yts);
+			WriteData(fid,'object',obj,'fieldname','time_adapt','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','cfl_coefficient','format','Double');
+			WriteData(fid,'object',obj,'fieldname','interp_forcings','format','Boolean');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/timestepping.py	(revision 18231)
@@ -0,0 +1,76 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class timestepping(object):
+	"""
+	TIMESTEPPING Class definition
+
+	   Usage:
+	      timestepping=timestepping();
+	"""
+
+	def __init__(self): # {{{
+		self.start_time      = 0.
+		self.final_time      = 0.
+		self.time_step       = 0.
+		self.time_adapt      = 0
+		self.cfl_coefficient = 0.
+		self.interp_forcings = 1
+		
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   timestepping parameters:"
+		string="%s\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
+		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
+		string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#time between 2 time steps
+		self.time_step=1./2.
+
+		#final time
+		self.final_time=10.*self.time_step
+
+		#time adaptation? 
+		self.time_adapt=0
+		self.cfl_coefficient=0.5
+		
+		#should we interpolate forcings between timesteps?
+		self.interp_forcings=1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1)
+		md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1)
+		md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1)
+		md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)
+		if self.final_time-self.start_time<0:
+			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+		md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'fieldname','start_time','format','Double','scale',yts)
+		WriteData(fid,'object',self,'fieldname','final_time','format','Double','scale',yts)
+		WriteData(fid,'object',self,'fieldname','time_step','format','Double','scale',yts)
+		WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
+		WriteData(fid,'object',self,'fieldname','interp_forcings','format','Boolean')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.m	(revision 18231)
@@ -0,0 +1,128 @@
+%TOOLKITS class definition
+%
+%   Usage:
+%      obj=toolkits();
+
+classdef toolkits < dynamicprops
+    properties (SetAccess=public) 
+		 DefaultAnalysis           = struct();
+		 %The other properties are dynamic
+	 end
+	 methods
+		 function obj = toolkits(varargin) % {{{
+			 switch nargin
+				 case 0
+					 obj=setdefaultparameters(obj);
+				 case 1
+					 obj=structtoobj(obj,varargin{1});
+				 otherwise
+					 error('constructor not supported');
+				 end
+			 end % }}}
+		 function obj = addoptions(obj,analysis,varargin) % {{{
+		 % Usage example:
+		 %    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
+		 %    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum());
+
+			 %Convert analysis from enum to string
+			 analysis=EnumToString(analysis);
+
+			 %Create dynamic property if property does not exist yet
+			 if ~ismember(analysis,properties(obj)),
+				 obj.addprop(analysis);
+			 end
+
+			 %Add toolkits options to analysis
+			 if nargin==3, obj.(analysis) = varargin{1}; end
+		 end
+		 %}}}
+		 function obj = setdefaultparameters(obj) % {{{
+
+			 %default toolkits: 
+			 if IssmConfig('_HAVE_PETSC_'),
+				 %MUMPS is the default toolkits
+				 if IssmConfig('_HAVE_MUMPS_'),
+					 obj.DefaultAnalysis           = mumpsoptions();
+				 else
+					 obj.DefaultAnalysis           = iluasmoptions(); 
+				 end
+			 else
+				 if IssmConfig('_HAVE_MUMPS_'),
+					 obj.DefaultAnalysis           = issmmumpssolver(); 
+				 elseif IssmConfig('_HAVE_GSL_'),
+					 obj.DefaultAnalysis           = issmgslsolver(); 
+				 else 
+					 error('Need at least Mumps or Gsl to define an issm solver type');
+				 end
+			 end
+
+		 end % }}}
+		 function disp(obj) % {{{
+			 analyses=properties(obj);
+			 disp(sprintf('List of toolkits options per analysis:\n'));
+			 for i=1:numel(analyses),
+				 analysis=analyses{i};
+				 disp([analysis ':']);
+				 disp(obj.(analysis));
+			 end
+		 end % }}}
+		 function md = checkconsistency(obj,md,solution,analyses) % {{{
+			 analyses=properties(obj);
+			 for i=1:numel(analyses),
+				 if isempty(fieldnames(obj.(analyses{i})))
+					 md = checkmessage(md,['md.toolkits.' analyses{i} ' is empty']);
+				 end
+			 end
+		 end % }}}
+		 function ToolkitsFile(toolkits,filename) % {{{
+		 %TOOLKITSFILE - build toolkits file
+		 %
+		 %   Build a Petsc compatible options file, from the toolkits model field  + return options string. 
+		 %   This file will also be used when the toolkit used is 'issm' instead of 'petsc'
+		 %
+		 %   Usage:     ToolkitsFile(toolkits,filename);
+
+			 %open file for writing
+			 fid=fopen(filename,'w');
+			 if fid==-1,
+				 error(['ToolkitsFile error: could not open ' filename ' for writing']);
+			 end
+
+			 %write header
+			 fprintf(fid,'%s%s%s\n','%Toolkits options file: ',filename,' written from Matlab toolkits array');
+
+			 %start writing options
+			 analyses=properties(toolkits);
+			 for i=1:numel(analyses),
+				 analysis=analyses{i};
+				 options=toolkits.(analysis);
+
+				 %first write analysis:
+				 fprintf(fid,'\n+%s\n',analysis); %append a + to recognize it's an analysis enum
+
+				 %now, write options
+				 optionslist=fieldnames(options);
+				 for j=1:numel(optionslist),
+					 optionname=optionslist{j};
+					 optionvalue=options.(optionname);
+
+					 if isempty(optionvalue),
+						 %this option has only one argument
+						 fprintf(fid,'-%s\n',optionname);
+					 else
+						 %option with value. value can be string or scalar
+						 if isnumeric(optionvalue),
+							 fprintf(fid,'-%s %g\n',optionname,optionvalue);
+						 elseif ischar(optionvalue),
+							 fprintf(fid,'-%s %s\n',optionname,optionvalue);
+						 else
+							 error(['ToolkitsFile error: option ' optionname ' is not well formatted']);
+						 end
+					 end
+				 end
+			 end
+
+			 fclose(fid);
+		 end %}}}
+	 end
+ end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/toolkits.py	(revision 18231)
@@ -0,0 +1,111 @@
+from IssmConfig import IssmConfig
+from mumpsoptions import mumpsoptions
+from iluasmoptions import iluasmoptions
+from EnumToString import EnumToString
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+
+class toolkits(object):
+	"""
+	TOOLKITS class definition
+
+	   Usage:
+	      obj=toolkits();
+	"""
+
+	def __init__(self):    # {{{
+		#default toolkits
+		if IssmConfig('_HAVE_PETSC_')[0]:
+			#MUMPS is the default toolkits
+			if IssmConfig('_HAVE_MUMPS_')[0]:
+				self.DefaultAnalysis           = mumpsoptions()
+			else:
+				self.DefaultAnalysis           = iluasmoptions()
+		else:
+			if IssmConfig('_HAVE_MUMPS_')[0]:
+				self.DefaultAnalysis           = issmmumpssolver()
+			elif IssmConfig('_HAVE_GSL_')[0]:
+				self.DefaultAnalysis           = issmgslsolver()
+			else:
+				raise IOError("ToolkitsFile error: need at least Mumps or Gsl to define issm solver type")
+
+		#The other properties are dynamic
+	# }}}
+	def __repr__(self):    # {{{
+		s ="List of toolkits options per analysis:\n\n"
+		for analysis in vars(self).iterkeys():
+			s+="%s\n" % fielddisplay(self,analysis,'')
+
+		return s
+	# }}}
+	def addoptions(self,analysis,*args):    # {{{
+		# Usage example:
+		#    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
+		#    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum());
+
+		#Convert analysis from enum to string
+		[analysis]=EnumToString(analysis)
+
+		#Create dynamic property if property does not exist yet
+		if not hasattr(self,analysis):
+#			exec("self.%s = None" % analysis)
+			setattr(self,analysis,None)
+
+		#Add toolkits options to analysis
+		if len(args)==1:
+			setattr(self,analysis,args[0])
+
+		return self
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		for analysis in vars(self).iterkeys():
+			if not getattr(self,analysis):
+				md.checkmessage("md.toolkits.%s is empty" % analysis)
+
+		return md
+	# }}}
+	def ToolkitsFile(self,filename):    # {{{
+		"""
+		TOOLKITSFILE- build toolkits file
+
+		   Build a Petsc compatible options file, from the toolkits model field  + return options string
+		   This file will also be used when the toolkit used is 'issm' instead of 'petsc'
+
+
+		   Usage:     ToolkitsFile(toolkits,filename);
+		"""
+
+		#open file for writing
+		try:
+			fid=open(filename,'w')
+		except IOError as e:
+			raise IOError("ToolkitsFile error: could not open '%s' for writing." % filename)
+
+		#write header
+		fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab toolkits array'))
+
+		#start writing options
+		for analysis in vars(self).iterkeys():
+			options=getattr(self,analysis)
+
+			#first write analysis:
+			fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
+
+			#now, write options
+			for optionname,optionvalue in options.iteritems():
+
+				if not optionvalue:
+					#this option has only one argument
+					fid.write("-%s\n" % optionname)
+				else:
+					#option with value. value can be string or scalar
+					if   isinstance(optionvalue,(bool,int,long,float)):
+						fid.write("-%s %g\n" % (optionname,optionvalue))
+					elif isinstance(optionvalue,(str,unicode)):
+						fid.write("-%s %s\n" % (optionname,optionvalue))
+					else:
+						raise TypeError("ToolkitsFile error: option '%s' is not well formatted." % optionname)
+
+		fid.close()
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.m	(revision 18231)
@@ -0,0 +1,130 @@
+%TRANSIENT class definition
+%
+%   Usage:
+%      transient=transient();
+
+classdef transient
+	properties (SetAccess=public) 
+		ismasstransport   = 0;
+		isstressbalance   = 0;
+		isthermal         = 0;
+		isgroundingline   = 0;
+		isgia             = 0;
+		isdamageevolution = 0;
+		islevelset        = 0;
+		ishydrology       = 0;
+		requested_outputs = {};
+	end
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '<!-- transient -->\n');            
+                    
+            % transient solution parameters
+            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="transient solution parameters">','<section name="transient" />');                    
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ismasstransport" type="',class(obj.ismasstransport),'" default="',convert2str(obj.ismasstransport),'">','     <section name="transient" />','     <help> indicates whether a masstransport solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isstressbalance" type="',class(obj.isstressbalance),'" default="',convert2str(obj.isstressbalance),'">','     <section name="transient" />','     <help> indicates whether a stressbalance solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isthermal" type="',class(obj.isthermal),'" default="',convert2str(obj.isthermal),'">','     <section name="transient" />','     <help> indicates whether a thermal solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgroundingline" type="',class(obj.isgroundingline),'" default="',convert2str(obj.isgroundingline),'">','     <section name="transient" />','     <help> indicates whether a groundingline migration is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgia" type="',class(obj.isgia),'" default="',convert2str(obj.isgia),'">','     <section name="transient" />','     <help> indicates whether a postglacial rebound model is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdamageevolution" type="',class(obj.isdamageevolution),'" default="',convert2str(obj.isdamageevolution),'">','     <section name="transient" />','     <help> indicates whether damage evolution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="islevelset" type="',class(obj.islevelset),'" default="',convert2str(obj.islevelset),'">','     <section name="transient" />','     <help> LEVEL SET DESCRIPTION...  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="transient" />','     <help> list of additional outputs requested </help>','  </parameter>');
+            fprintf(fid,'%s\n%s\n','</frame>');    
+        
+        end % }}}
+		function obj = transient(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = deactivateall(obj) % {{{
+
+			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+			obj.ismasstransport = 0;
+			obj.isstressbalance = 0;
+			obj.isthermal       = 0;
+			obj.isgroundingline = 0;
+			obj.isgia           = 0;
+			obj.isdamageevolution = 0;
+			obj.islevelset      = 0;
+			obj.ishydrology     = 0;
+
+			%default output
+			obj.requested_outputs={};
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+			obj.ismasstransport = 1;
+			obj.isstressbalance = 1;
+			obj.isthermal       = 1;
+			obj.isgroundingline = 0;
+			obj.isgia           = 0;
+			obj.isdamageevolution = 0;
+			obj.islevelset      = 0;
+			obj.ishydrology     = 0;
+
+			%default output
+			obj.requested_outputs={'default'};
+		end % }}}
+		function list = defaultoutputs(self,md) % {{{
+			if(self.ismasstransport)
+				list = {'SurfaceforcingsMassBalance'};
+			else
+				list = {};
+			end
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=TransientSolutionEnum(), return; end
+
+			md = checkfield(md,'fieldname','transient.ismasstransport','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.isstressbalance','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.isthermal','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.isgroundingline','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.isgia','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.isdamageevolution','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   transient solution parameters:'));
+
+			fielddisplay(obj,'ismasstransport','indicates whether a masstransport solution is used in the transient');
+			fielddisplay(obj,'isstressbalance','indicates whether a stressbalance solution is used in the transient');
+			fielddisplay(obj,'isthermal','indicates whether a thermal solution is used in the transient');
+			fielddisplay(obj,'isgroundingline','indicates whether a groundingline migration is used in the transient');
+			fielddisplay(obj,'isgia','indicates whether a postglacial rebound model is used in the transient');
+			fielddisplay(obj,'isdamageevolution','indicates whether damage evolution is used in the transient');
+			fielddisplay(obj,'islevelset','LEVEL SET DESCRIPTION...');
+			fielddisplay(obj,'ishydrology','indicates whether an hydrology model is used');
+			fielddisplay(obj,'requested_outputs','list of additional outputs requested');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','ismasstransport','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isstressbalance','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isthermal','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isgroundingline','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isgia','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isdamageevolution','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','ishydrology','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','islevelset','format','Boolean');
+
+			%process requested outputs
+			outputs = obj.requested_outputs;
+			pos  = find(ismember(outputs,'default'));
+			if ~isempty(pos),
+				outputs(pos) = [];                         %remove 'default' from outputs
+				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+			end
+			WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum,'format','StringArray');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/transient.py	(revision 18231)
@@ -0,0 +1,117 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+
+class transient(object):
+	"""
+	TRANSIENT class definition
+
+	   Usage:
+	      transient=transient();
+	"""
+
+	def __init__(self): # {{{
+		self.ismasstransport   = False
+		self.isstressbalance   = False
+		self.isthermal         = False
+		self.isgroundingline   = False
+		self.isgia             = False
+		self.isdamageevolution = False
+		self.islevelset        = False
+		self.ishydrology       = False
+		self.requested_outputs = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   transient solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'ismasstransport','indicates if a masstransport solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isstressbalance','indicates if a stressbalance solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isthermal','indicates if a thermal solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isgia','indicates if a postglacial rebound is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdamageevolution','indicates whether damage evolution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'islevelset','LEVELSET METHOD DESCRIPTION'))
+		string="%s\n%s"%(string,fielddisplay(self,'ishydrology','indicates whether an hydrology model is used'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
+		return string
+		#}}}
+	def defaultoutputs(self,md): # {{{
+
+		if self.ismasstransport:
+			return ['SurfaceforcingsMassBalance']
+		else:
+			return []
+
+	#}}}
+	def setallnullparameters(self): # {{{
+		
+		#Nothing done
+		self.ismasstransport = False
+		self.isstressbalance = False
+		self.isthermal       = False
+		self.isgroundingline = False
+		self.isgia           = False
+		self.isdamageevolution = False
+		self.islevelset      = False
+                self.ishydrology     = False
+
+		#default output
+		self.requested_outputs=[]
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+		self.ismasstransport = True
+		self.isstressbalance = True
+		self.isthermal       = True
+		self.isgroundingline = False
+		self.isgia           = False
+		self.isdamageevolution = False
+		self.islevelset      = False
+                self.ishydrology     = False
+
+		#default output
+		self.requested_outputs=['default']
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==TransientSolutionEnum():
+			return md
+
+		md = checkfield(md,'fieldname','transient.ismasstransport','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.isstressbalance','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.isthermal','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.isgroundingline','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.isgia','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.isdamageevolution','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','ismasstransport','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isstressbalance','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isgia','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdamageevolution','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','islevelset','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','ishydrology','format','Boolean')
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum(),'format','StringArray')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.m	(revision 18231)
@@ -0,0 +1,148 @@
+%VERBOSE class definition
+%
+%   Available verbosity levels:
+%      mprocessor  : model processing 
+%      module      : modules
+%      solution    : solution sequence
+%      solver      : solver info (extensive)
+%      convergence : convergence criteria
+%      control     : control method
+%      qmu         : sensitivity analysis
+%      autodiff    : AD analysis
+%
+%   Usage:
+%      verbose=verbose();
+%      verbose=verbose(3);
+%      verbose=verbose('all');
+%      verbose=verbose('001100');
+%      verbose=verbose('module',true,'solver',false);
+
+%WARNING: some parts of this file are Synchronized with src/c/shared/Numerics/Verbosity.h
+%         Do not modify these sections. See src/c/shared/Numerics/README for more info
+
+classdef verbose
+	properties (SetAccess=public) 
+		% {{{
+		%BEGINFIELDS
+		mprocessor=false;
+		module=false;
+		solution=false;
+		solver=false;
+		convergence=false;
+		control=false;
+		qmu=false;
+		autodiff=false;
+		%ENDFIELDS
+		% }}}
+	end
+	%}}}
+	methods
+        function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- verbose -->');
+             
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="mprocessor" type="',              class(obj.mprocessor),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.mprocessor),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="module" type="',              class(obj.module),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.module),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solution" type="',              class(obj.solution),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.solution),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solver" type="',              class(obj.solver),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.solver),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="convergence" type="',              class(obj.convergence),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.convergence),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="control" type="',              class(obj.control),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.control),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="qmu" type="',              class(obj.qmu),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.qmu),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="autodiff" type="',              class(obj.autodiff),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.autodiff),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+             
+             
+        end % }}}
+		function verbose=verbose(varargin) % {{{
+
+			switch(nargin),
+				case 0,
+					verbose.solution=true;
+					verbose.qmu=true;
+					verbose.control=true;
+				case 1,
+					binary=varargin{1};
+					if     ischar(binary),
+						if strcmpi(binary,'all'),
+							binary=2^11-1; %all ones
+							verbose=BinaryToVerbose(verbose,binary);
+							verbose.solver=false; %Do not use by default
+						else
+							binary=bin2dec(binary);
+							verbose=BinaryToVerbose(verbose,binary);
+						end
+					elseif isnumeric(binary),
+						verbose=BinaryToVerbose(verbose,binary);
+					end 
+				otherwise,
+					%Use options to initialize object
+					verbose=AssignObjectFields(pairoptions(varargin{:}),verbose);
+
+					%Cast to logicals
+					listproperties=properties('verbose');
+					for i=1:numel(listproperties),
+						fieldname=listproperties{i};
+						fieldvalue=verbose.(fieldname);
+						if (islogical(fieldvalue) | isnumeric(fieldvalue)) & numel(fieldvalue)==1,
+							verbose.(fieldname)=logical(fieldvalue);
+						else
+							error('verbose supported field values are logicals only (true or false)');
+						end
+					end
+			end
+		end
+		%}}}
+		function binary=VerboseToBinary(verbose) % {{{
+
+		%BEGINVERB2BIN
+		binary=0;
+		if (verbose.mprocessor), binary=bitor(binary,1); end
+		if (verbose.module), binary=bitor(binary,2); end
+		if (verbose.solution), binary=bitor(binary,4); end
+		if (verbose.solver), binary=bitor(binary,8); end
+		if (verbose.convergence), binary=bitor(binary,16); end
+		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
+
+		end
+		%}}}
+		function verbose=BinaryToVerbose(verbose,binary) % {{{
+
+		%BEGINBIN2VERB
+		if bitand(binary,1), verbose.mprocessor=true; else verbose.mprocessor=false; end
+		if bitand(binary,2), verbose.module=true; else verbose.module=false; end
+		if bitand(binary,4), verbose.solution=true; else verbose.solution=false; end
+		if bitand(binary,8), verbose.solver=true; else verbose.solver=false; end
+		if bitand(binary,16), verbose.convergence=true; else verbose.convergence=false; end
+		if bitand(binary,32), verbose.control=true; else verbose.control=false; end
+		if bitand(binary,64), verbose.qmu=true; else verbose.qmu=false; end
+		if bitand(binary,128), verbose.autodiff=true; else verbose.autodiff=false; end
+		%ENDBIN2VERB
+
+		end
+		%}}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+		end % }}}
+		function disp(verbose) % {{{
+
+		%BEGINDISP
+		disp(sprintf('class ''%s''  = ',class(verbose)));
+		disp(sprintf('   %15s : %s','mprocessor',mat2str(verbose.mprocessor)));
+		disp(sprintf('   %15s : %s','module',mat2str(verbose.module)));
+		disp(sprintf('   %15s : %s','solution',mat2str(verbose.solution)));
+		disp(sprintf('   %15s : %s','solver',mat2str(verbose.solver)));
+		disp(sprintf('   %15s : %s','convergence',mat2str(verbose.convergence)));
+		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
+
+		end
+		%}}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/classes/verbose.py	(revision 18231)
@@ -0,0 +1,132 @@
+from pairoptions import pairoptions
+import MatlabFuncs as m
+from EnumDefinitions import *
+from WriteData import WriteData
+
+class verbose(object):
+	"""
+	VERBOSE class definition
+
+	   Available verbosity levels:
+	      mprocessor  : model processing 
+	      module      : modules
+	      solution    : solution sequence
+	      solver      : solver info (extensive)
+	      convergence : convergence criteria
+	      control     : control method
+	      qmu         : sensitivity analysis
+	      autodiff    : AD analysis
+
+	   Usage:
+	      verbose=verbose();
+	      verbose=verbose(3);
+	      verbose=verbose('001100');
+	      verbose=verbose('module',True,'solver',False);
+
+	WARNING: some parts of this file are Synchronized with src/c/shared/Numerics/Verbosity.h
+	         Do not modify these sections. See src/c/shared/Numerics/README for more info
+	"""
+
+	def __init__(self,*args):    # {{{
+		#BEGINFIELDS
+		self.mprocessor  = False
+		self.module      = False
+		self.solution    = False
+		self.solver      = False
+		self.convergence = False
+		self.control     = False
+		self.qmu         = False
+		self.autodiff    = False
+		#ENDFIELDS
+
+		if not len(args):
+			#Don't do anything
+			self.solution=True;
+			self.qmu=True;
+			self.control=True;
+			pass
+
+		elif len(args) == 1:
+			binary=args[0]
+			if   isinstance(binary,(str,unicode)):
+				if binary.lower()=='all':
+					binary=2**11-1    #all ones
+					self.BinaryToVerbose(binary)
+					self.solver=False    #Do not use by default
+				else:
+					binary=int(binary,2)
+					self.BinaryToVerbose(binary)
+			elif isinstance(binary,(int,long,float)):
+				self.BinaryToVerbose(int(binary))
+
+		else:
+			#Use options to initialize object
+			self=pairoptions(*args).AssignObjectFields(self)
+
+			#Cast to logicals
+			listproperties=vars(self)
+			for fieldname,fieldvalue in listproperties.iteritems():
+				if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,long,float)):
+					setattr(self,fieldname,bool(fieldvalue))
+				else:
+					raise TypeError("verbose supported field values are logicals only (True or False)")
+	# }}}
+	def __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
+	# }}}
+	def VerboseToBinary(self):    # {{{
+
+		#BEGINVERB2BIN
+		binary=0
+		if self.mprocessor:
+			binary=binary |  1
+		if self.module:
+			binary=binary |  2
+		if self.solution:
+			binary=binary |  4
+		if self.solver:
+			binary=binary |  8
+		if self.convergence:
+			binary=binary | 16
+		if self.control:
+			binary=binary | 32
+		if self.qmu:
+			binary=binary | 64
+		if self.autodiff:
+			binary=binary | 128
+		#ENDVERB2BIN
+
+		return binary
+	# }}}
+	def BinaryToVerbose(self,binary):    # {{{
+
+		#BEGINBIN2VERB
+		self.mprocessor =bool(binary &   1)
+		self.module     =bool(binary &   2)
+		self.solution   =bool(binary &   4)
+		self.solver     =bool(binary &   8)
+		self.convergence=bool(binary &  16)
+		self.control    =bool(binary &  32)
+		self.qmu        =bool(binary &  64)
+		self.autodiff   =bool(binary & 128)
+		#ENDBIN2VERB
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/QueueRequirements.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/QueueRequirements.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/QueueRequirements.m	(revision 18231)
@@ -0,0 +1,35 @@
+function QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,queue,np,time)
+%QUEUEREQUIREMENTS - queue requirements in time, number of cpus, by name of queue.
+%
+%   Usage: 
+%      QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,np,time)
+
+%Ok, go through requirements for current queue:
+index=ismemberi(queue,available_queues);
+if  ~index,
+	%ok, either we a generic cluster, with 'none' queue, or we could not find the queue reqruirements
+	if strcmpi(available_queues{1},'none'),
+		%reset index to 1, so we can fish the requirements
+		index=1;
+	else
+		string=available_queues{1};
+		for i=2:length(available_queues),
+			string=[string ' ' available_queues{i}];
+		end
+		error(['QueueRequirements error message: availables queues are ' string]);
+	end
+end
+
+%check on time requirements
+rtime=queue_requirements_time(index);
+if time<=0,
+	error('QueueRequirements: time should be a positive number');
+end
+if time>rtime,
+	error(['QueueRequirements: time should be < ' num2str(rtime) ' for queue: ' queue]);
+end
+
+%check on np requirements
+if np<=0,
+	error('QueueRequirements: np should be a positive number');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.m	(revision 18231)
@@ -0,0 +1,219 @@
+function md = checkfield(md,varargin)
+%CHECKFIELD - check field consistency
+%
+%   Used to check model consistency.
+%   Requires: 
+%     'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname)) 
+%             If 'field' is provided, it will assume the argument following 'field' is a numeric array.
+%   Available options:
+%      - NaN: 1 if check that there is no NaN
+%      - size: [lines cols], NaN for non checked dimensions
+%      - >:  greater than provided value
+%      - >=: greater or equal to provided value
+%      - <:  smallerthan provided value
+%      - <=: smaller or equal to provided value
+%      - < vec:  smallerthan provided values on each vertex
+%      - forcing: 1 if check forcing consistency (size and time)
+%      - values: cell of strings or vector of acceptable values
+%      - numel: list of acceptable number of elements
+%      - cell: 1 if check that is cell
+%      - empty: 1 if check that non empty
+%      - message: overloaded error message
+%
+%   Usage:
+%      md = checkfield(md,fieldname,options);
+
+%get options
+options=pairoptions(varargin{:});
+
+%get field: 
+if exist(options,'field'), 
+	field=getfieldvalue(options,'field'); 
+	fieldname=getfieldvalue(options,'fieldname','no fieldname'); 
+else
+	fieldname=getfieldvalue(options,'fieldname'); 
+	eval(['field=md.' fieldname ';']);
+end
+
+
+%check empty
+if exist(options,'empty')
+	if isempty(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' is empty']));
+	end
+end
+
+%Check size
+if exist(options,'size')
+	fieldsize=getfieldvalue(options,'size');
+	if isnan(fieldsize(1)),
+		if (size(field,2)~=fieldsize(2)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(2)) ' columns']));
+		end
+	elseif isnan(fieldsize(2)),
+		if (size(field,1)~=fieldsize(1)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(1)) ' lines']));
+		end
+	else
+		if ((size(field,1)~=fieldsize(1)) |  (size(field,2)~=fieldsize(2)))
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldsize(1)) ' x ' num2str(fieldsize(2))]));
+		end
+	end
+end
+
+%Check numel
+if exist(options,'numel')
+	fieldnumel=getfieldvalue(options,'numel');
+	if ~ismember(numel(field),fieldnumel),
+		if length(fieldnumel)==1
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g ',fieldnumel) ]));
+		elseif length(fieldnumel)==2
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldnumel(1)) ' or ' num2str(fieldnumel(2)) ]));
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g, ',fieldnumel(1:end-1)) ' or ' num2str(fieldnumel(end)) ]));
+		end
+	end
+end
+
+%check NaN
+if getfieldvalue(options,'NaN',0);
+	field2=reshape(field,prod(size(field)),1);
+	if any(isnan(field2)),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['NaN values found in field ''' fieldname '''']));
+	end
+end
+
+%check cell
+if getfieldvalue(options,'cell',0);
+	if ~iscell(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should be a cell']));
+	end
+end
+
+%check values
+if exist(options,'values')
+	fieldvalues=getfieldvalue(options,'values');
+	if iscell(fieldvalues), %strings
+		if ischar(field) | iscell(fieldvalues),
+			if any(~ismember(field,fieldvalues)),
+				if length(fieldvalues)==1
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' value should be ''' fieldvalues{1} '''']));
+				elseif length(fieldvalues)==2
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' values should be ''' fieldvalues{1} ''' or ''' fieldvalues{2} '''']));
+				else
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' should have values in ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+				end
+			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be one of the following strings: ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+		end
+	else
+		field2=reshape(field,prod(size(field)),1);
+		if isnumeric(field),
+			if any(~ismember(field2,fieldvalues)),
+				md = checkmessage(md,getfieldvalue(options,'message',...
+					['field ''' fieldname ''' should have values in [' num2str(fieldvalues) ']']));
+			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be a number in [' num2str(fieldvalues) ']']));
+		end
+	end
+end
+
+%check greater
+if exist(options,'>=')
+	lowerbound=getfieldvalue(options,'>=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+if exist(options,'>')
+	lowerbound=getfieldvalue(options,'>');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<=lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+
+%check smaller
+if exist(options,'<=')
+	upperbound=getfieldvalue(options,'<=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+if exist(options,'<')
+	upperbound=getfieldvalue(options,'<');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>=upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+
+%Check row of stringrow
+if getfieldvalue(options,'stringrow',0),
+	if(size(field,1)~=1 & size(field,1)~=0),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have only one row']));
+	end
+	if ~iscell(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should be a cell of strings']));
+	else
+		for i=1:size(field,2),
+			if ~ischar(field{i}),
+				md = checkmessage(md,getfieldvalue(options,'message',...
+					['field ''' fieldname ''' values should a cell of chars']));
+			end
+		end
+	end
+end
+
+%check file
+if getfieldvalue(options,'file',0),
+	if ~exist(field,'file')
+		md = checkmessage(md,['file provided in ''' fieldname ''': ''' field ''' does not exist']);
+	end
+end
+
+%Check forcings (size and times)
+if getfieldvalue(options,'forcing',0),
+	if size(field,1)==md.mesh.numberofvertices,
+		if ~size(field,2)==1,
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have only one column as there are md.mesh.numberofvertices lines']));
+		end
+	elseif size(field,1)==md.mesh.numberofvertices+1
+		if any(field(end,:)~=sort(field(end,:))),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns should be sorted chronologically']));
+		end
+		if any(field(end,1:end-1)==field(end,2:end)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
+		end
+	else
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines']));
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/checkfield.py	(revision 18231)
@@ -0,0 +1,170 @@
+import numpy
+import os
+from pairoptions import pairoptions
+import MatlabFuncs as m
+
+def checkfield(md,*args):
+	"""
+	CHECKFIELD - check field consistency
+
+	   Used to check model consistency.,
+	   Requires: 
+	   'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname)) 
+             If 'field' is provided, it will assume the argument following 'field' is a numeric array.
+
+	   Available options:
+	      - NaN: 1 if check that there is no NaN
+	      - size: [lines cols], NaN for non checked dimensions
+	      - >:  greater than provided value
+	      - >=: greater or equal to provided value
+	      - <:  smallerthan provided value
+	      - <=: smaller or equal to provided value
+	      - < vec:  smallerthan provided values on each vertex
+	      - forcing: 1 if check forcing consistency (size and time)
+	      - values: cell of strings or vector of acceptable values
+	      - numel: list of acceptable number of elements
+	      - cell: 1 if check that is cell
+	      - empty: 1 if check that non empty
+	      - message: overloaded error message
+
+	   Usage:
+	      md = checkfield(md,fieldname,options);
+	"""
+
+	#get options
+	options=pairoptions(*args)
+
+	#get field from model
+	if options.exist('field'):
+		field=options.getfieldvalue('field')
+		fieldname=options.getfieldvalue('fieldname','no fieldname')
+	else:
+		fieldname=options.getfieldvalue('fieldname') 
+		exec("field=md.%s" % fieldname)
+
+	if isinstance(field,(bool,int,long,float)):
+		field=numpy.array([field])
+
+	#check empty
+	if options.exist('empty'):
+		if not field:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' is empty" % fieldname))
+
+	#Check size
+	if options.exist('size'):
+		fieldsize=options.getfieldvalue('size')
+		if   len(fieldsize) == 1:
+			if   numpy.isnan(fieldsize[0]):
+				pass
+			elif not numpy.size(field,0)==fieldsize[0]:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldsize[0])))
+		elif len(fieldsize) == 2:
+			if   numpy.isnan(fieldsize[0]):
+				if not numpy.size(field,1)==fieldsize[1]:
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' should have %d columns" % (fieldname,fieldsize[1])))
+			elif numpy.isnan(fieldsize[1]):
+				if not numpy.size(field,0)==fieldsize[0]:
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' should have %d lines" % (fieldname,fieldsize[0])))
+			else:
+				if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
+					md = md.checkmessage(options.getfieldvalue('message',\
+						"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
+	
+	#Check numel
+	if options.exist('numel'):
+		fieldnumel=options.getfieldvalue('numel')
+		if numpy.size(field) not in fieldnumel:
+			if   len(fieldnumel)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldnumel)))
+			elif len(fieldnumel)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d or %d" % (fieldname,fieldnumel[0],fieldnumel[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %s" % (fieldname,fieldnumel)))
+
+	#check NaN
+	if options.getfieldvalue('NaN',0):
+		if numpy.any(numpy.isnan(field)):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"NaN values found in field '%s'" % fieldname))
+
+	#check cell
+	if options.getfieldvalue('cell',0):
+		if not isinstance(field,(tuple,list,dict)):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should be a cell" % fieldname))
+
+	#check values
+	if options.exist('values'):
+		fieldvalues=options.getfieldvalue('values')
+		if False in m.ismember(field,fieldvalues):
+			if   len(fieldvalues)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' value should be '%s'"  % (fieldname,fieldvalues[0])))
+			elif len(fieldvalues)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' values should be '%s' or '%s'"  % (fieldname,fieldvalues[0],fieldvalues[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have values in %s" % (fieldname,fieldvalues)))
+
+	#check greater
+	if options.exist('>='):
+		lowerbound=options.getfieldvalue('>=')
+		if numpy.any(field<lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+	if options.exist('>'):
+		lowerbound=options.getfieldvalue('>')
+		if numpy.any(field<=lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+
+	#check smaller
+	if options.exist('<='):
+		upperbound=options.getfieldvalue('<=')
+		if numpy.any(field>upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+	if options.exist('<'):
+		upperbound=options.getfieldvalue('<')
+		if numpy.any(field>=upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+
+	#check file
+	if options.getfieldvalue('file',0):
+		if not os.path.exists(field):
+			md = md.checkmessage("file provided in '%s': '%s' does not exist" % (fieldname,field))
+
+	#Check row of strings
+	if options.exist('stringrow'):
+		if not isinstance(field,list):
+			md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should be a list" %fieldname))
+
+	#Check forcings (size and times)
+	if options.getfieldvalue('forcing',0):
+		if   numpy.size(field,0)==md.mesh.numberofvertices:
+			if numpy.ndim(field)>1 and not numpy.size(field,1)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname))
+		elif numpy.size(field,0)==md.mesh.numberofvertices+1:
+			if not all(field[-1,:]==numpy.sort(field[-1,:])):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns should be sorted chronologically" % fieldname))
+			if any(field[-1,0:-1]==field[-1,1:]):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns must not contain duplicate timesteps" % fieldname))
+		else:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines" % fieldname))
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/comparemodels.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/comparemodels.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/comparemodels.m	(revision 18231)
@@ -0,0 +1,33 @@
+function comparemodels(md1,md2);
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+		field1=md1.(model_fields{i});
+		field2=md2.(model_fields{i});
+		if isobject(field1), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			for j=1:length(object_fields),
+				field1=md1.(model_fields{i}).(object_fields{j});
+				field2=md2.(model_fields{i}).(object_fields{j});
+				compare([model_fields{i} '.' object_fields{j}],field1,field2);
+			end
+		else
+			compare(model_fields{i},field1,field2);
+		end
+	end
+
+end
+
+function compare(fieldname,field1,field2),
+	if any(size(field1)~=size(field2)),
+		disp([fieldname ' do not have the same size']);
+	elseif isnumeric(field1),
+		if numel(field1)==1 & isnan(field1) & isnan(field2),
+			%Do not do anything
+		elseif any(field1~=field2),
+			disp([fieldname ' differs']);
+		end
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.m	(revision 18231)
@@ -0,0 +1,97 @@
+function ismodelselfconsistent(md),
+%ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+%
+%   Usage:
+%      ismodelselfconsistent(md),
+
+%initialize consistency as true
+md.private.isconsistent=true;
+
+%Get solution and associated analyses
+solution=md.private.solution;
+[analyses]=AnalysisConfiguration(solution);
+
+%Go through a model field, check that it is a class, and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be checked
+	if ismember(field,{'results' 'debug' 'radaroverlay'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		md=checkmessage(md,['field ''' char(field) ''' is not an object']);
+		continue;
+	end
+
+	%Check consistency of the object
+	md=checkconsistency(md.(field),md,solution,analyses);
+end
+
+%error message if mode is not consistent
+if md.private.isconsistent==false,
+	error('Model not consistent, see messages above');
+end
+end
+
+function [analyses]=AnalysisConfiguration(solutiontype), % {{{
+%ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+%
+%   Usage:
+%      [analyses]=AnalysisConfiguration(solutiontype);
+
+switch solutiontype,
+
+	case StressbalanceSolutionEnum(),
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum()];
+
+	case SteadystateSolutionEnum(),
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case ThermalSolutionEnum(),
+		analyses=[EnthalpyAnalysisEnum;ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case MasstransportSolutionEnum(),
+		analyses=[MasstransportAnalysisEnum()];
+
+	case BalancethicknessSolutionEnum(),
+		analyses=[BalancethicknessAnalysisEnum()];
+
+	case Balancethickness2SolutionEnum(),
+		analyses=[Balancethickness2AnalysisEnum()];
+
+	case BalancethicknessSoftSolutionEnum(),
+		analyses=[BalancethicknessAnalysisEnum()];
+
+	case BalancevelocitySolutionEnum(),
+		analyses=[BalancevelocityAnalysisEnum()];
+
+	case SurfaceSlopeSolutionEnum(),
+		analyses=[L2ProjectionBaseAnalysisEnum()];
+
+	case BedSlopeSolutionEnum(),
+		analyses=[L2ProjectionBaseAnalysisEnum()];
+
+	case GiaSolutionEnum(),
+		analyses=[GiaAnalysisEnum()];
+
+	case TransientSolutionEnum(),
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();L2ProjectionBaseAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();MasstransportAnalysisEnum()];
+
+	case FlaimSolutionEnum(),
+		analyses=[FlaimAnalysisEnum()];
+
+	case HydrologySolutionEnum(),
+		analyses=[L2ProjectionBaseAnalysisEnum();HydrologyShreveAnalysisEnum();HydrologyDCInefficientAnalysisEnum();HydrologyDCEfficientAnalysisEnum()];
+	
+	case DamageEvolutionSolutionEnum(),
+		analyses=[DamageEvolutionAnalysisEnum()];
+
+	otherwise
+		error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+	end
+end % }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/consistency/ismodelselfconsistent.py	(revision 18231)
@@ -0,0 +1,91 @@
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def AnalysisConfiguration(solutiontype): #{{{
+	"""
+	ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+
+		Usage:
+			[analyses]=AnalysisConfiguration(solutiontype);
+	"""
+
+	if   solutiontype == StressbalanceSolutionEnum():
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum()]
+
+	elif solutiontype == SteadystateSolutionEnum():
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == ThermalSolutionEnum():
+		analyses=[EnthalpyAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == MasstransportSolutionEnum():
+		analyses=[MasstransportAnalysisEnum()]
+
+	elif solutiontype == BalancethicknessSolutionEnum():
+		analyses=[BalancethicknessAnalysisEnum()]
+
+	elif solutiontype == SurfaceSlopeSolutionEnum():
+		analyses=[L2ProjectionBaseAnalysisEnum()]
+
+	elif solutiontype == BalancevelocitySolutionEnum():
+		analyses=[BalancevelocityAnalysisEnum()]
+
+	elif solutiontype == BedSlopeSolutionEnum():
+		analyses=[L2ProjectionBaseAnalysisEnum()]
+
+	elif solutiontype == GiaSolutionEnum():
+		analyses=[GiaAnalysisEnum()]
+
+	elif solutiontype == TransientSolutionEnum():
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]
+
+	elif solutiontype == FlaimSolutionEnum():
+		analyses=[FlaimAnalysisEnum()]
+
+	elif solutiontype == HydrologySolutionEnum():
+		analyses=[L2ProjectionBaseAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]
+
+	elif DamageEvolutionSolutionEnum():
+		analyses=[DamageEvolutionAnalysisEnum()]
+
+	else:
+		raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])
+
+	return analyses
+#}}}
+
+def ismodelselfconsistent(md):
+	"""
+	ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+
+	   Usage:
+	      ismodelselfconsistent(md),
+	"""
+
+	#initialize consistency as true
+	md.private.isconsistent=True
+
+	#Get solution and associated analyses
+	solution=md.private.solution
+	analyses=AnalysisConfiguration(solution)
+
+	#Go through a model fields, check that it is a class, and call checkconsistency
+	fields=vars(md)
+#	for field in fields.iterkeys():
+	for field in md.properties():
+
+		#Some properties do not need to be checked
+		if field in ['results','debug','radaroverlay']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'checkconsistency'):
+			md.checkmessage("field '%s' is not an object." % field)
+
+		#Check consistency of the object
+		exec("md.%s.checkconsistency(md,solution,analyses)" % field)
+
+	#error message if mode is not consistent
+	if not md.private.isconsistent:
+		raise RuntimeError('Model not consistent, see messages above.')
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCall.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCall.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCall.m	(revision 18231)
@@ -0,0 +1,79 @@
+function md=BamgCall(md,field,hmin,hmax,gradation,epsilon),
+%BAMGCALL - call bam
+%
+%   build a metric using the Hessian of the given field
+%   call Bamg and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=BamgCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=BamgCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCallFromMetric.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 18231)
@@ -0,0 +1,65 @@
+function md=BamgCallFromMetric(md,metric,gradation),
+%BAMGCALL - call bam
+%
+%   call Bamg and the output mesh is plugged onto the model
+%   -gradation = maximum edge length gradation between 2 elements
+%
+%   Usage:
+%      md=BamgCallFromMetric(md,metric,gradation);
+%
+%   Example:
+%      md=BamgCall(md,metric,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.m	(revision 18231)
@@ -0,0 +1,98 @@
+function md=YamsCall(md,field,hmin,hmax,gradation,epsilon),
+%YAMSCALL - call yams
+%
+%   build a metric using the Hessian of the given field
+%   call Yams and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=YamsCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=YamsCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2./9.;
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+save -ascii carre0.met  metric
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'\n%s\n%i\n','MeshVersionFormatted',1);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y zeros(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements zeros(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%Deal with rifts
+if ~isnan(md.rifts.riftstruct),
+
+	%we have the list of triangles that make up the rift. keep those triangles around during refinement.
+	triangles=[];
+	for i=1:size(md.rifts.riftstruct,1),
+		triangles=[triangles md.rifts(i).riftstruct.segments(:,3)'];
+	end
+
+	fprintf(fid,'\n\n%s\n%i\n\n','RequiredTriangles',length(triangles));
+	fprintf(fid,'%i\n',triangles);
+end
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call yams
+fprintf('%s\n','      call Yams...');
+if ispc()
+	%windows
+	system(['yams2-win -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+elseif ismac()
+	%Macosx
+	system(['yams2-osx -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+else
+	%Linux
+	system(['yams2-linux -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+end
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+Tria=load('carre1.tria');
+Coor=load('carre1.coor');
+md.mesh.x=Coor(:,1);
+md.mesh.y=Coor(:,2);
+md.mesh.elements=Tria;
+md.mesh.numberofvertices=size(Coor,1);
+md.mesh.numberofelements=size(Tria,1);
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.tria carre1.coor carre1.meshb');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/YamsCall.py	(revision 18231)
@@ -0,0 +1,123 @@
+import numpy
+import time
+import subprocess
+import os
+from ComputeHessian import ComputeHessian
+from ComputeMetric import ComputeMetric
+
+def YamsCall(md,field,hmin,hmax,gradation,epsilon):
+	"""
+	YAMSCALL - call yams
+
+	   build a metric using the Hessian of the given field
+	   call Yams and the output mesh is plugged onto the model
+	   -hmin = minimum edge length (m)
+	   -hmax = maximum edge length (m)
+	   -gradation = maximum edge length gradation between 2 elements
+	   -epsilon = average error on each element (m/yr)
+
+	   Usage:
+	      md=YamsCall(md,field,hmin,hmax,gradation,epsilon);
+
+	   Example:
+	      md=YamsCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+	"""
+
+	#2d geometric parameter (do not change)
+	scale=2./9.
+
+	#Compute Hessian
+	t1=time.time()
+	print "%s" % '      computing Hessian...'
+	hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node')
+	t2=time.time()
+	print "%s%d%s\n" % (' done (',t2-t1,' seconds)')
+
+	#Compute metric
+	t1=time.time()
+	print "%s" % '      computing metric...'
+	metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,numpy.empty(0,int))
+	t2=time.time()
+	print "%s%d%s\n" % (' done (',t2-t1,' seconds)')
+
+	#write files
+	t1=time.time()
+	print "%s" % '      writing initial mesh files...'
+	numpy.savetxt('carre0.met',metric)
+
+	f=open('carre0.mesh','w')
+
+	#initialiation
+	f.write("\n%s\n%i\n" % ('MeshVersionFormatted',1))
+
+	#dimension
+	f.write("\n%s\n%i\n" % ('Dimension',2))
+
+	#Vertices
+	f.write("\n%s\n%i\n\n" % ('Vertices',md.mesh.numberofvertices))
+	for i in xrange(0,md.mesh.numberofvertices):
+		f.write("%8g %8g %i\n" % (md.mesh.x[i],md.mesh.y[i],0))
+
+	#Triangles
+	f.write("\n\n%s\n%i\n\n" % ('Triangles',md.mesh.numberofelements))
+	for i in xrange(0,md.mesh.numberofelements):
+		f.write("%i %i %i %i\n" % (md.mesh.elements[i,0],md.mesh.elements[i,1],md.mesh.elements[i,2],0))
+	numberofelements1=md.mesh.numberofelements
+
+	#Deal with rifts
+	if numpy.any(not numpy.isnan(md.rifts.riftstruct)):
+
+		#we have the list of triangles that make up the rift. keep those triangles around during refinement.
+		triangles=numpy.empty(0,int)
+		for riftstruct in md.rifts.riftstruct:
+			triangles=numpy.concatenate((triangles,riftstruct.segments[:,2]))
+
+		f.write("\n\n%s\n%i\n\n" % ('RequiredTriangles',numpy.size(triangles)))
+		for triangle in triangles:
+			f.write("%i\n" % triangle)
+
+	#close
+	f.close()
+	t2=time.time()
+	print "%s%d%s\n" % (' done (',t2-t1,' seconds)')
+
+	#call yams
+	print "%s\n" % '      call Yams...'
+	if   m.ispc():
+		#windows
+		subprocess.call('yams2-win -O 1 -v -0 -ecp -hgrad %g carre0 carre1' % gradation,shell=True)
+	elif ismac():
+		#Macosx
+		subprocess.call('yams2-osx -O 1 -v -0 -ecp -hgrad %g carre0 carre1' % gradation,shell=True)
+	else:
+		#Linux
+		subprocess.call('yams2-linux -O 1 -v -0 -ecp -hgrad %g carre0 carre1' % gradation,shell=True)
+
+	#plug new mesh
+	t1=time.time()
+	print "\n%s" % '      reading final mesh files...'
+	Tria=numpy.loadtxt('carre1.tria',int)
+	Coor=numpy.loadtxt('carre1.coor',float)
+	md.mesh.x=Coor[:,0]
+	md.mesh.y=Coor[:,1]
+	md.mesh.z=numpy.zeros((numpy.size(Coor,axis=0),1))
+	md.mesh.elements=Tria
+	md.mesh.numberofvertices=numpy.size(Coor,axis=0)
+	md.mesh.numberofelements=numpy.size(Tria,axis=0)
+	numberofelements2=md.mesh.numberofelements
+	t2=time.time()
+	print "%s%d%s\n\n" % (' done (',t2-t1,' seconds)')
+
+	#display number of elements
+	print "\n%s %i" % ('      inital number of elements:',numberofelements1)
+	print "\n%s %i\n\n" % ('      new    number of elements:',numberofelements2)
+
+	#clean up:
+	os.remove('carre0.mesh')
+	os.remove('carre0.met')
+	os.remove('carre1.tria')
+	os.remove('carre1.coor')
+	os.remove('carre1.meshb')
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh.m	(revision 18231)
@@ -0,0 +1,48 @@
+function md=gmsh(md,domainfile,h),
+
+%Read domain
+domain=expread(domainfile);
+x   = domain.x(1:end-1);
+y   = domain.y(1:end-1);
+nbv = numel(x);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('model.geo','w');
+fprintf(fid,['// Gmsh input file, created by ISSM on ' date '\n']);
+for i=1:nbv,
+	fprintf(fid,'Point(%i) = {%8g, %8g, %8g};\n',i,x(i),y(i),0.);
+end
+for i=1:nbv-1
+	fprintf(fid,'Line(%i) = {%i, %i};\n',i,i,i+1);
+end
+fprintf(fid,'Line(%i) = {%i, %i};\n',nbv,nbv,1);
+fprintf(fid,'Line Loop(5) = {');
+for i=1:nbv-1
+	fprintf(fid,'%i,',i);
+end
+fprintf(fid,'%i};\n',nbv);
+fprintf(fid,'Plane Surface(6) = {5};\n');
+
+%Physical lines and surfaces
+fprintf(fid,'Physical Line(2) = {1};\n');
+fprintf(fid,'Physical Line(4) = {2};\n');
+fprintf(fid,'Physical Line(5) = {3};\n');
+fprintf(fid,'Physical Line(1) = {4};\n');
+fprintf(fid,'Physical Surface(7) = {6};\n');
+
+%resolution
+fprintf(fid,'Mesh.CharacteristicLengthMax = %g;',h);
+
+%fprintf(fid,'Plane Surface(7) = {6, 2};\n');
+fclose(fid);
+
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call gmsh
+fprintf('%s\n','      call gmsh...');
+system([issmdir() '/externalpackages/gmsh/install/gmsh -2 model.geo']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+md=importgmsh('model.msh',2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh3d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh3d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/gmsh3d.m	(revision 18231)
@@ -0,0 +1,103 @@
+function md=gmsh3d(md,domainfile,h),
+
+%Read domain
+domain=expread(domainfile);
+x   = domain.x(1:end-1);
+y   = domain.y(1:end-1);
+nbv = numel(x);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('model.geo','w');
+fprintf(fid,['// Gmsh input file, created by ISSM on ' date '\n']);
+
+%Lower points
+for i=1:nbv,
+	fprintf(fid,'Point(%i) = {%8g, %8g, %8g};\n',i,x(i),y(i),0.);
+end
+%Upper points
+for i=1:nbv,
+	fprintf(fid,'Point(%i) = {%8g, %8g, %8g};\n',nbv+i,x(i),y(i),1.);
+end
+
+%Lower lines
+for i=1:nbv-1
+	fprintf(fid,'Line(%i) = {%i, %i};\n',i,i,i+1);
+end
+fprintf(fid,'Line(%i) = {%i, %i};\n',nbv,nbv,1);
+%Upper lines
+for i=nbv+1:2*nbv-1
+	fprintf(fid,'Line(%i) = {%i, %i};\n',i,i,i+1);
+end
+fprintf(fid,'Line(%i) = {%i, %i};\n',2*nbv,2*nbv,nbv+1);
+%Side lines
+for i=1:nbv
+	fprintf(fid,'Line(%i) = {%i, %i};\n',2*nbv+i,i,nbv+i);
+end
+
+counter = 3*nbv;
+ps = zeros(nbv+2,1);
+%Lower surface Loop and surface
+counter = counter+1;
+fprintf(fid,['Line Loop(' num2str(counter) ') = {']);
+for i=1:nbv-1
+	fprintf(fid,'%i,',i);
+end
+fprintf(fid,'%i};\n',nbv);
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+ps(1)=counter+1;
+counter = counter+1;
+%Upper surface Loop and surface
+counter = counter+1;
+fprintf(fid,['Line Loop(' num2str(counter) ') = {']);
+for i=nbv+1:2*nbv-1
+	fprintf(fid,'%i,',i);
+end
+fprintf(fid,'%i};\n',2*nbv);
+ps(2)=counter+1;
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+counter = counter+2;
+%Sides surfaces
+for i=1:nbv-1,
+	fprintf(fid,['Line Loop(' num2str(counter) ') = {' num2str(i) ',' num2str(2*nbv+i+1) ',-' num2str(nbv+i) ',-' num2str(2*nbv+i) '};\n']);
+	fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+	ps(2+i)=counter+1;
+	counter=counter+2;
+end
+fprintf(fid,['Line Loop(' num2str(counter) ') = {' num2str(nbv) ',' num2str(2*nbv+1) ',-' num2str(2*nbv) ',-' num2str(3*nbv) '};\n']);
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+ps(2+nbv)=counter+1;
+counter=counter+2;
+
+%Physical surfaces
+counter = counter+1;
+fprintf(fid,['Surface Loop(' num2str(counter) ') = {']);
+for i=1:numel(ps)-1
+	fprintf(fid,'%i,',ps(i));
+end
+fprintf(fid,'%i};\n',ps(end));
+fprintf(fid,['Physical Surface(1) = {' num2str(ps(2)) '};\n']);
+fprintf(fid,['Physical Surface(2) = {' num2str(ps(1)) '};\n']);
+fprintf(fid,['Physical Surface(3) = {']);
+for i=3:numel(ps)-1
+	fprintf(fid,'%i,',ps(i));
+end
+fprintf(fid,'%i};\n',ps(end));
+
+%Volume
+fprintf(fid,['Volume(1) = {' num2str(counter) '};\n']);
+fprintf(fid,['Physical Volume(2) = {1};\n']);
+
+%resolution
+fprintf(fid,'Mesh.CharacteristicLengthMax = %g;',h);
+fclose(fid);
+
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call gmsh
+fprintf('%s\n','      call gmsh...');
+system([issmdir() '/externalpackages/gmsh/install/gmsh -3 model.geo']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+md=importgmsh('model.msh',3);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/meshread.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/meshread.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/meshread.m	(revision 18231)
@@ -0,0 +1,41 @@
+function Struct=meshread(filename)
+
+%some checks
+if ~exist(filename),
+	error(['meshread error message: file ' filename ' not found!']);
+end
+
+fid=fopen(filename,'r');
+
+while (~feof(fid)),
+
+	A=fscanf(fid,'%s',1);
+
+	if strcmp(A,'MeshVersionFormatted');
+		Struct.Version=fscanf(fid,'%s',1);
+
+	elseif strcmp(A,'Dimension'),
+		Struct.Dimension=fscanf(fid,'%i',1);
+
+	elseif strcmp(A,'Vertices'),
+		Struct.nods=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%f %f %f',[3 Struct.nods]);
+		Struct.x=A(1,:)';
+		Struct.y=A(2,:)';
+
+	elseif strcmp(A,'Triangles'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i',[4 Struct.nels]);
+		Struct.index=A(1:3,:)';
+
+	elseif strcmp(A,'Quadrilaterals'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i %i',[5 Struct.nels]);
+		Struct.index=A(1:4,:)';
+	else
+		%do nothing
+
+	end
+end
+
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/yams.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/yams.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/bamg/yams.m	(revision 18231)
@@ -0,0 +1,153 @@
+function md=yams(md,varargin)
+%MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
+%
+%   Usage:
+%      md=yams(md,varargin);
+%      where varargin is a lit of paired arguments. 
+%      arguments can be: 'domainoutline': Argus file containing the outline of the domain to be meshed
+%      arguments can be: 'velocities': matlab file containing the velocities [m/yr]
+%      optional arguments: 'groundeddomain': Argus file containing the outline of the grounded ice
+%                          this option is used to minimize the metric on water (no refinement)
+%      optional arguments: 'resolution': initial mesh resolution [m]
+%      optional arguments: 'nsteps': number of steps of mesh adaptation
+%      optional arguments: 'epsilon': average interpolation error wished [m/yr]
+%      optional arguments: 'hmin': minimum edge length
+%      optional arguments: 'hmanx': maximum edge
+%      optional arguments: 'riftoutline': if rifts are present, specifies rift outline file.
+%      
+%
+%   Examples:
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp','nsteps',6,'epsilon',2,'hmin',500,'hmax',30000);
+
+%recover options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%recover some fields
+disp('MeshYams Options:')
+domainoutline=getfieldvalue(options,'domainoutline');
+disp(sprintf('   %-15s: ''%s''','DomainOutline',domainoutline));
+riftoutline=getfieldvalue(options,'riftoutline','N/A');
+disp(sprintf('   %-15s: ''%s''','riftoutline',riftoutline));
+groundeddomain=getfieldvalue(options,'groundeddomain','N/A');
+disp(sprintf('   %-15s: ''%s''','GroundedDomain',groundeddomain));
+velocities=getfieldvalue(options,'velocities');
+disp(sprintf('   %-15s: ''%s''','Velocities',velocities));
+resolution=getfieldvalue(options,'resolution',5000);
+disp(sprintf('   %-15s: %f','Resolution',resolution));
+nsteps=getfieldvalue(options,'nsteps',6);
+disp(sprintf('   %-15s: %i','nsteps',nsteps));
+gradation=getfieldvalue(options,'gradation',2*ones(nsteps,1));
+disp(sprintf('   %-15s: %g','gradation',gradation(1)));
+epsilon=getfieldvalue(options,'epsilon',3);
+disp(sprintf('   %-15s: %f','epsilon',epsilon));
+hmin=getfieldvalue(options,'hmin',500);
+disp(sprintf('   %-15s: %f','hmin',hmin));
+hmax=getfieldvalue(options,'hmax',150*10^3);
+disp(sprintf('   %-15s: %f\n','hmax',hmax));
+
+%mesh with initial resolution
+disp('Initial mesh generation...');
+if strcmpi(riftoutline,'N/A');
+	md=setmesh(md,domainoutline,resolution);
+else
+	md=setmesh(md,domainoutline,riftoutline,resolution);
+	md=meshprocessrifts(md,domainoutline);
+end
+disp(['Initial mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%load velocities 
+disp('loading velocities...');
+Names=VelFindVarNames(velocities);
+Vel=load(velocities);
+
+%start mesh adaptation
+for i=1:nsteps,
+	disp(['Iteration #' num2str(i) '/' num2str(nsteps)]);
+
+	%interpolate velocities onto mesh
+	disp('   interpolating velocities...');
+	if strcmpi(Names.interp,'node'),
+		vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	else
+		vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	end
+	field=sqrt(vx_obs.^2+vy_obs.^2);
+
+	%adapt according to velocities
+	disp('   adapting...');
+	md=YamsCall(md,field,hmin,hmax,gradation(i),epsilon);
+
+	%if we have rifts, we just messed them up, we need to recreate the segments that constitute those 
+	%rifts, because the segments are used in YamsCall to freeze the rifts elements during refinement.
+	if md.rifts.numrifts, 
+		md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+		md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+		md.mesh.segments=findsegments(md);
+		md=yamsrecreateriftsegments(md);
+	end
+
+end
+
+disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%recreate segments
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Fill in rest of fields:
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbase=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+end
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+
+%deal with rifts 
+if md.rifts.numrifts,
+	%first, recreate rift segments
+	md=meshyamsrecreateriftsegments(md);
+
+	%using the segments, recreate the penaltypairs
+	for j=1:md.rifts.numrifts,
+		rift=md.rifts.riftstruct(j);
+
+		%build normals and lengths of segments:
+		lengths=sqrt((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))).^2 + (md.mesh.y(rift.segments(:,1))-md.mesh.y(rift.segments(:,2))).^2 );
+		normalsx=cos(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+		normalsy=sin(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+
+		%ok, build penaltypairs: 
+		numpenaltypairs=length(rift.segments)/2-1;
+		rift.penaltypairs=zeros(numpenaltypairs,7);
+
+		for i=1:numpenaltypairs,
+			rift.penaltypairs(i,1)=rift.segments(i,2);
+			rift.penaltypairs(i,2)=rift.segments(end-i,2);
+			rift.penaltypairs(i,3)=rift.segments(i,3);
+			rift.penaltypairs(i,4)=rift.segments(end-i,3);
+			rift.penaltypairs(i,5)=normalsx(i)+normalsx(i+1);
+			rift.penaltypairs(i,6)=normalsy(i)+normalsy(i+1);
+			rift.penaltypairs(i,7)=(lengths(i)+lengths(i+1))/2;
+		end
+		%renormalize norms: 
+		norms=sqrt(rift.penaltypairs(:,5).^2+rift.penaltypairs(:,6).^2);
+		rift.penaltypairs(:,5)=rift.penaltypairs(:,5)./norms;
+		rift.penaltypairs(:,6)=rift.penaltypairs(:,6)./norms;
+
+		md.rifts.riftstruct(j)=rift;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/exportgmsh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/exportgmsh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/exportgmsh.m	(revision 18231)
@@ -0,0 +1,52 @@
+function exportgmsh(mesh,groundedice_levelset,filename),
+%EXPORTGMSH - export mesh to gmsh format
+%
+%   http://www.geuz.org/gmsh/doc/texinfo/#MSH-ASCII-file-format
+%
+%   Usage:
+%      exportgmsh(mesh,groundedice_levelset,filename)
+%
+%   Example:
+%      exportgmsh(md.mesh,md.mask.groundedice_levelset,'temp.msh')
+
+fid=fopen(filename,'w');
+
+%Header
+fprintf(fid,'$MeshFormat\n');
+fprintf(fid,'2.2 0 8\n');
+fprintf(fid,'$EndMeshFormat\n');
+
+%Vertices
+nbv = mesh.numberofvertices;
+fprintf(fid,'$Nodes\n');
+fprintf(fid,'%i\n',nbv);
+fprintf(fid,'%i %8g %8g %8g\n',[[1:nbv]' mesh.x mesh.y zeros(nbv,1)]');
+fprintf(fid,'$EndNodes\n');
+
+%Boundary Elements first
+nbe     = mesh.numberofelements;
+nbs     = size(mesh.segments,1);
+segment = 1;
+tria    = 2;
+
+%Create flags
+grounded = sum(groundedice_levelset(mesh.segments(:,1:2))>0,2);
+A = zeros(nbs,2);
+pos = find(mesh.segmentmarkers==4);
+A(pos,:)=repmat([1,4],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==1 &  grounded);
+A(pos,:)=repmat([2,1],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==1 & ~grounded);
+A(pos,:)=repmat([3,5],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==2);
+A(pos,:)=repmat([4,2],[numel(pos) 1]);
+pos = find(mesh.segmentmarkers==3);
+A(pos,:)=repmat([5,3],[numel(pos) 1]);
+
+fprintf(fid,'$Elements\n');
+fprintf(fid,'%i\n',nbe+nbs);
+fprintf(fid,'%i %i %i %i %i %i %i\n',[[1    :nbs    ]' segment*ones(nbs,1) 2*ones(nbs,1) A mesh.segments(:,1:2)]');
+fprintf(fid,'%i %i %i %i %i %i %i %i\n',[[nbs+1:nbs+nbe]' tria*ones(nbe,1) 2*ones(nbe,1) 7*ones(nbe,1) 6*ones(nbe,1) mesh.elements]');
+fprintf(fid,'$EndElements\n');
+
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/importgmsh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/importgmsh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/dassflow/importgmsh.m	(revision 18231)
@@ -0,0 +1,155 @@
+function md = importgmsh(filename,dim)
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+
+%open file
+fid=fopen(filename,'r');
+
+%Get Mesh format
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$MeshFormat'), 
+	error(['Expecting $MeshFormat (' A ')']);
+end
+A=fscanf(fid,'%f %i %i',[1 3]);
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$EndMeshFormat'), 
+	error(['Expecting $EndMeshFormat (' A ')']);
+end
+
+%Nodes
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$Nodes'), 
+	error(['Expecting $Nodes (' A ')']);
+end
+nbv=fscanf(fid,'%i',1);
+disp(['Number of nodes: ' num2str(nbv) ]);
+A=fscanf(fid,'%i %f %f %f',[4 nbv]);
+x = A(2,:)';
+y = A(3,:)';
+z = A(4,:)';
+
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$EndNodes'), 
+	error(['Expecting $EndNodes (' A ')']);
+end
+
+%Elements
+A=fscanf(fid,'%s',1);
+if ~strcmp(A,'$Elements'), 
+	error(['Expecting $Elements (' A ')']);
+end
+nbt=fscanf(fid,'%i',1);
+disp(['Number of elements: ' num2str(nbt) ]);
+counter = 0;
+if (dim==2),
+	index   = zeros(0,3);
+	segments       = zeros(0,2);
+	segmentmarkers = zeros(0,1);
+elseif (dim==3),
+	index   = zeros(0,4);
+	segments       = zeros(0,3);
+	segmentmarkers = zeros(0,1);
+else
+	error('not supported');
+end
+
+while(counter<nbt);
+	id = fscanf(fid,'%i',1);
+	ty = fscanf(fid,'%i',1);
+	nbf = fscanf(fid,'%i',1);
+	flags = fscanf(fid,'%i',nbf);
+
+	switch(ty)
+		case 1, %segments
+			A=fscanf(fid,'%i %i',2);
+			if (dim==2),  %Actual element
+				segments(end+1,:)=A;
+				if    (flags(1)==5 & flags(2)==3), segmentmarkers(end+1)=3; 
+				elseif(flags(1)==1 & flags(2)==4), segmentmarkers(end+1)=4;
+				elseif(flags(1)==2 & flags(2)==1), segmentmarkers(end+1)=1;
+				elseif(flags(1)==4 & flags(2)==2), segmentmarkers(end+1)=2;
+				else error(['flags ' num2str(flags') ' not supported']);
+				end
+			else
+				error('not supported');
+			end
+		case 2, %tria
+			A=fscanf(fid,'%i %i %i',3);
+			if (dim==2), %Actual element
+				index(end+1,:)=A;
+			else         %Boundary element
+				segments(end+1,:)=A;
+				if    (flags(1)==1), segmentmarkers(end+1)=1; 
+				elseif(flags(1)==2), segmentmarkers(end+1)=2;
+				elseif(flags(1)==3), segmentmarkers(end+1)=3;
+				elseif(flags(1)==4), segmentmarkers(end+1)=4;
+				else error(['flags ' num2str(flags') ' not supported']);
+				end
+			end
+		case 4, %tetra
+			A=fscanf(fid,'%i %i %i %i',4);
+			if (dim==3), %Actual element
+				index(end+1,:)=A;
+			else
+				error('not supported');
+			end
+		case 15, %point
+			A=fscanf(fid,'%i',1);
+			continue;
+		otherwise,
+			error(['Type ' num2str(ty) ' not supported']);
+	end
+	counter = counter + 1;
+end
+
+%recreate segments
+if dim==2,
+	nbs = size(segments,1);
+	segments = [segments zeros(nbs,1)];
+	for i=1:nbs,
+		E = find(sum(ismember(index,segments(i,:)),2)>1);
+		segments(i,3)=E;
+	end
+else
+	nbs = size(segments,1);
+	segments = [segments zeros(nbs,1)];
+	for i=1:nbs,
+		E = find(sum(ismember(index,segments(i,:)),2)>2);
+		segments(i,4)=E;
+	end
+end
+
+%close file
+fclose(fid);
+
+%Create model
+if dim==2, %2d triangles
+	md=meshconvert(model,index,x,y);
+	md.mesh=mesh2dvertical(md.mesh);
+	md.mesh.segmentmarkers=segmentmarkers;
+	md.mesh.segments=segments;
+	md.mesh.vertexonbase=zeros(md.mesh.numberofvertices,1);
+	md.mesh.vertexonbase(find(vertexflags(md.mesh,1)))=1;
+	md.mesh.vertexonsurface=zeros(md.mesh.numberofvertices,1);
+	md.mesh.vertexonsurface(find(vertexflags(md.mesh,3)))=1;
+else
+	md=model();
+	md.mesh=mesh3dtetras();
+	md.mesh.x = x;
+	md.mesh.y = y;
+	md.mesh.z = z;
+	md.mesh.elements = index;
+	md.mesh.numberofelements=size(md.mesh.elements,1);
+	md.mesh.numberofvertices=length(md.mesh.x);
+
+	%base 2, surface 1, inflow 3, outflow 4
+	md.mesh.vertexonbase=zeros(md.mesh.numberofvertices,1);
+	md.mesh.vertexonbase(segments(find(segmentmarkers==2),1:3))=1;
+	md.mesh.vertexonsurface=zeros(md.mesh.numberofvertices,1);
+	md.mesh.vertexonsurface(segments(find(segmentmarkers==1),1:3))=1;
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1);
+	md.mesh.vertexonboundary(segments(:,1:3))=1;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/MeltingGroundingLines.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 18231)
@@ -0,0 +1,26 @@
+function md=MeltingGroundingLines(md,distance,value)
+%MELTINGGROUNDINGLINES - set melting near grounding lines to a constant value
+%
+%   Usage:
+%      md=MeltingGroundingLines(md,distance,value)
+%
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(md.mask.groundedice_levelset<0.);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+
+for i=1:length(pos_shelf)
+
+	if (mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d<distance,
+
+		md.melting(pos_shelf(i))=value;
+
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/PropagateFlagsUntilDistance.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 18231)
@@ -0,0 +1,60 @@
+function new_flags=PropagateFlagsUntilDistance(md,flags,distance)
+%PROPAGATEFLAGSUNTILDISTANCE
+%
+% Usage: 
+%              flags=PropagateFlagsUntilDistance(md,flags,distance)
+%
+%
+
+new_flags=flags;
+
+%make 3d work in 2d: 
+if dimension(md.mesh)==3,
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.elements=md.mesh.elements2d;
+end
+
+%find elements that are at the border of flags: 
+flag_elements=find(flags);
+conn=md.mesh.elementconnectivity(flag_elements,:);
+pos=find(conn);conn(pos)=~flags(conn(pos));
+sum_conn=sum(conn,2);
+border_elements=flag_elements(find(sum_conn>=1));
+
+%average x and y over elements: 
+x_elem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+y_elem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+
+while 1,
+
+	%keep copy of new_flags for this loop: 
+	new_flags_bak=new_flags;
+
+	%extend new flags by connectivity
+	pos=find(new_flags);
+
+	connected_elements=md.mesh.elementconnectivity(pos,:);
+	connected_elements=connected_elements(find(connected_elements));
+	new_flags(connected_elements)=1;
+
+	%get new elements: 
+	new_elements=find(new_flags & ~new_flags_bak);
+	if ~length(new_elements),
+		%we are done!
+		break;
+	end
+
+	%check which of these new elements are more than distance away from the border elements
+	for i=1:length(new_elements),
+		dist=sqrt(     (x_elem(border_elements)-x_elem(new_elements(i))).^2 + (y_elem(border_elements)-y_elem(new_elements(i))).^2)-distance;
+		if ~any(dist<0)
+			%none of the border elements are within distance, this element is outside out area of interest.
+			%ensure this element never gets found again in the connectivity.
+			pos=find(md.mesh.elementconnectivity==new_elements(i));
+			md.mesh.elementconnectivity(pos)=0;
+			%exclude this new element from the new_flags!
+			new_flags(new_elements(i))=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/ecco32issm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/ecco32issm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/ecco32issm.m	(revision 18231)
@@ -0,0 +1,8 @@
+function nodefield=ecco32issm(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/issm2ecco3.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/issm2ecco3.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/ecco/issm2ecco3.m	(revision 18231)
@@ -0,0 +1,8 @@
+function nodefield=issm2ecco3(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gamv.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gamv.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gamv.m	(revision 18231)
@@ -0,0 +1,70 @@
+function output = gamv(x,y,data,varargin)
+%GAMV - use gslib for Kriging
+%
+%   Usage:
+%      output = gamv(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nlag = getfieldvalue(options,'nlag', 20);
+dlag = getfieldvalue(options,'dlag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('gamv.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str(nlag,'%i')           ,'\number of lags');
+fprintf(fid,'%-30s %s\n',num2str(dlag,'%g')           ,'\lag separation distance');
+fprintf(fid,'%-30s %s\n',num2str(dlag/2,'%g')         ,'\lag tolerance');
+fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+fclose(fid);
+
+%Call gamv
+system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+delete('gamv.par');
+
+%Read output
+output   = struct('Semivariogram',[],'Covariance',[]);
+counter1 = 1;
+counter2 = 1;
+fid=fopen('gamv.out','r');
+while (~feof(fid)),
+	A=fscanf(fid,'%s',1);
+	if strcmp(A,'Covariance');
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter1).Covariance=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter1=counter1+1;
+	elseif strcmp(A,'Semivariogram'),
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter2).Semivariogram=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter2=counter2+1;
+	else
+		%do nothing
+	end
+end
+fclose(fid);
+delete('gamv.out')
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gslib.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gslib.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/gslib.m	(revision 18231)
@@ -0,0 +1,104 @@
+function [B E] = gslib(x,y,data,xmin,ymin,nx,ny,deltax,deltay)
+%GSLIB - use gslib for Kriging
+%
+%   Usage:
+%      output = gslib(x,y,data,varargin)
+
+%Variogram
+nugget=10;
+sill  =164;
+range =25763;
+
+%Kriging options
+mindata = 1;
+maxdata = 50;
+maxsearchradius = 50000;
+
+%Some intermediaries (Convert to gslib's parameters);
+c = (sill-nugget);
+a = sqrt(3)*range;
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+if 0, %GAMV
+	%Write parameter file
+	fid=fopen('gamv.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+	fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+	fprintf(fid,'%-30s %s\n','20'                         ,'\number of lags');
+	fprintf(fid,'%-30s %s\n','5.0'                        ,'\lag separation distance');
+	fprintf(fid,'%-30s %s\n','3.0'                        ,'\lag tolerance');
+	fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+	fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+	fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+	fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+	fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+	fclose(fid);
+
+	%Call gamv
+	system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+
+else, %Kriging KB2D
+	%Write parameter file
+	fid=fopen('kb2d.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for KB2D');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'                  ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 3'                          ,'\columns for X, Y and variable');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'                 ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','0'                              ,'\debugging level: 0,1,2,3');
+	fprintf(fid,'%-30s %s\n','kb2d.dbg'                       ,'\file for debuggging output');
+	fprintf(fid,'%-30s %s\n','kb2d.out'                       ,'\file for kriged output');
+	fprintf(fid,'%-30s %s\n',num2str([nx xmin deltax],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n',num2str([ny ymin deltay],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n','1 1'                            ,'\x and y block discretization');
+	fprintf(fid,'%-30s %s\n',num2str([mindata maxdata],'%6g') ,'\min and max data for kriging');
+	fprintf(fid,'%-30s %s\n',num2str(maxsearchradius,'%6g')   ,'\max search radius');
+	fprintf(fid,'%-30s %s\n','1 2.302'                        ,'\0=SK, 1=OK, (mean if SK)');
+	fprintf(fid,'%-30s %s\n',['1 ' num2str(nugget)]           ,'\nst, nugget effect');
+	fprintf(fid,'%-30s %s\n',['3 ' num2str([c 0.0 a a],'%10g')],'\it, c, azm, a_max, a_min');
+	fclose(fid);
+
+	tic;system([issmdir() '/externalpackages/gslib/install/kb2d kb2d.par']);toc;
+	delete('kb2d.par');
+
+	%Read output
+	fid=fopen('kb2d.out','r');
+	while (~feof(fid)),
+		A=fscanf(fid,'%s',1);
+		if strcmp(A,'KB2D');
+			A=fscanf(fid,'%s',1); %Read output
+			params=fscanf(fid,'%i %i %i %i %g %g %g %g %g %g %1',[11 1]);
+		elseif strcmp(A,' Estimate'),
+			continue;
+		elseif strcmp(A,'Estimation'),
+			A=fscanf(fid,'%s',1); %Read Variance
+			A=fscanf(fid,'%g %g',[params(1) params(2)*params(3)]);
+			B=A(1,:); B=reshape(B,[params(3),params(2)])';
+			E=A(2,:); E=reshape(E,[params(3),params(2)])';
+		else
+			%do nothing
+		end
+	end
+	fclose(fid);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/pkriging.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/pkriging.m	(revision 18231)
@@ -0,0 +1,63 @@
+function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin)
+%PKRIGING - parallel Kriging
+%
+%   Usage:
+%      [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+
+options=pairoptions(varargin{:});
+cluster=getfieldvalue(options,'cluster',generic('np',1));
+options=removefield(options,'cluster',0);
+name   = ['krig' num2str(feature('GetPid'))];
+
+% =========================================   MARSHALL.m =================================================
+disp(['marshalling file ' name '.bin']);
+fid=fopen([name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' name '.bin file for binary writing']);
+end
+
+%First, write MaximumNumberOfDefinitionsEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',true,'format','Boolean');
+
+%Write all data
+WriteData(fid,'enum',0,'data',x,'format','DoubleMat');
+WriteData(fid,'enum',1,'data',y,'format','DoubleMat');
+WriteData(fid,'enum',2,'data',observations,'format','DoubleMat');
+WriteData(fid,'enum',3,'data',x_interp,'format','DoubleMat');
+WriteData(fid,'enum',4,'data',y_interp,'format','DoubleMat');
+
+%Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',true,'format','Boolean');
+
+%Now, write number of options
+options.marshall(fid,5);
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' name '.bin']);
+end
+% =========================================   MARSHALL.m =================================================
+
+%Launch job on remote cluster
+BuildKrigingQueueScript(cluster,name,'',1,0,0); %gather, valgrind, gprof
+LaunchQueueJob(cluster,name,name,{[name '.bin'] [name '.queue']});
+
+%Call waitonlock
+md=model; md.cluster=cluster; md.settings.waitonlock=Inf; md.private.runtimename=name;md.miscellaneous.name=name;
+waitonlock(md);
+
+%Download
+Download(cluster,name,{[name '.outbin']});
+structure=parseresultsfromdisk([name '.outbin'],0);
+delete([name '.outlog']);
+delete([name '.errlog']);
+delete([name '.outbin']);
+delete([name '.bin']);
+if ~ispc(),
+	delete([name '.tar.gz']);
+end
+
+%Process results
+B=structure.(EnumToString(0));
+B=reshape(B,size(x_interp,2),size(x_interp,1))';
+E=structure.(EnumToString(1));
+E=reshape(E,size(x_interp,2),size(x_interp,1))';
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/varmap.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/varmap.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/gslib/varmap.m	(revision 18231)
@@ -0,0 +1,55 @@
+function output = varmap(x,y,data,varargin)
+%VARMAP - use gslib for Kriging
+%
+%   Usage:
+%      output = varmap(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nxlag = getfieldvalue(options,'nxlag', 20);
+nylag = getfieldvalue(options,'nylag', 20);
+dxlag = getfieldvalue(options,'dxlag', 1000);
+dylag = getfieldvalue(options,'dylag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('varmap.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','0    '                      ,'\1=regular grid, 0=scattered values');
+fprintf(fid,'%-30s %s\n','50 50 1'                    ,'\if =1: nx, ny, nz');
+fprintf(fid,'%-30s %s\n','1.0 1.0 1.0'                ,'\       xsiz, ysiz, zsiz if igrid=1');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\if =0: columns for x, y and z coordinates');
+fprintf(fid,'%-30s %s\n','varmap.out'                 ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str([nxlag nylag 0],'%i '),'\nxlag, nylag, nzlag');
+fprintf(fid,'%-30s %s\n',num2str([dxlag dylag 1],'%g %g %i'),'\dxlag, dylag, dzlag');
+fprintf(fid,'%-30s %s\n','5'                          ,'\minimum number of pairs');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','1'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail, head, variogram type');
+fclose(fid);
+
+%Call varmap
+system([issmdir() '/externalpackages/gslib/install/varmap varmap.par']);
+delete('varmap.par');
+
+%Read output
+fid=fopen('varmap.out','r');
+A = textscan(fid,'%f %f %f %f %f %f','headerlines',8);
+fclose(fid);
+delete('varmap.out')
+output = reshape(A{1},[2*nxlag+1 2*nylag+1]);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/sia.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/sia.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/sia.m	(revision 18231)
@@ -0,0 +1,26 @@
+function [velx,vely,vel]=sia(md)
+%BALVEL - computation of Shallow Ice velocities
+%
+%   This routine uses the model of SIA to compute the velocities
+%   of a 2d model using the surface slope
+%
+%   Usage:
+%      [velx,vely,vel]=sia(md)
+
+if md.mesh.dimension~=2,
+	error('Only 2d meshes are allowed to compute velocity balances');
+end
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness and B over all elements.
+summer=[1;1;1];
+hel=md.geometry.thickness(md.mesh.elements)*summer/3;
+Bel=md.B(md.mesh.elements)*summer/3;
+
+Ael=Bel.^(-3);
+
+velx=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sx.*Ael/4.*hel.^4;
+vely=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sy.*Ael/4.*hel.^4;
+vel=sqrt(velx.^2+vely.^2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/thicknessevolution.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/thicknessevolution.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/thicknessevolution.m	(revision 18231)
@@ -0,0 +1,28 @@
+function dhdt=thicknessevolution(md)
+%THICKNESSEVOLUTION - compute the new thickness of a model after ∆t
+%
+%   This routine compute the new thickness of a model after a time step
+%   according to the following formula:
+%   dh/dt=-div(Hu)
+%
+%   Usage:
+%      dhdt=thicknessevolution(md)
+
+if (length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices)
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%load some variables 
+H=md.geometry.thickness;
+vx=md.initialization.vx;
+vy=md.initialization.vy;
+index=md.mesh.elements;
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+%compute dhdt=div(Hu)
+summation=1/3*ones(3,1);
+dhdt=(vx(index)*summation).*sum( H(index).*alpha,2) + (vy(index)*summation).*sum(H(index).*beta,2) ...
+	+ ( H(index)*summation).*sum(vx(index).*alpha,2) + ( H(index)*summation).*sum(vy(index).*beta,2);
+dhdt=-dhdt;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/tres.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/tres.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hack/tres.m	(revision 18231)
@@ -0,0 +1,115 @@
+function md=tres(md,string)
+%TRES - transfer results results to corresponding model fields. 
+%
+%    Usage: md=tres(md,string)
+%
+%    Example: md=tres(md,'stressbalance');
+
+%check number of arguments
+
+if strcmpi(string,'stressbalance'),
+	if strcmp(domaintype(md.mesh),'2Dhorizontal'),
+		md.initialization.vx=md.results.StressbalanceSolution.Vx;
+		md.initialization.vy=md.results.StressbalanceSolution.Vy;
+	else 
+		md.initialization.vx=md.results.StressbalanceSolution.Vx;
+		md.initialization.vy=md.results.StressbalanceSolution.Vy;
+		md.initialization.vz=md.results.StressbalanceSolution.Vz;
+	end
+	md.initialization.vel=md.results.StressbalanceSolution.Vel;
+
+	if isfield(md.results.StressbalanceSolution,'Pressure'),
+		md.initialization.pressure=md.results.StressbalanceSolution.Pressure;
+	end
+	if ~isempty(md.rifts.riftstruct),
+		if isfield(md.results.StressbalanceSolution,'riftproperties'),
+			md.rifts.riftproperties=md.results.StressbalanceSolution.riftproperties;
+		end
+	end
+
+elseif strcmpi(string,'dakota'),
+	md.qmu.results=md.results.dakota;
+
+elseif strcmpi(string,'flaim'),
+	md.flaim.solution=md.results.FlaimSolution.solution;
+	md.flaim.quality =md.results.FlaimSolution.quality;
+
+elseif strcmpi(string,'transient'),
+	results=md.results.TransientSolution;
+	results2.Vel=NaN;
+	count=1;
+	for i=1:length(results),
+		if ~isempty(md.results.TransientSolution(i).Vel),
+			results2(count).Vel=md.results.TransientSolution(i).Vel;
+			results2(count).Surface=md.results.TransientSolution(i).Surface;
+			results2(count).Thickness=md.results.TransientSolution(i).Thickness;
+			results2(count).Bed=md.results.TransientSolution(i).Bed;
+			results2(count).Vx=md.results.TransientSolution(i).Vx;
+			results2(count).Vy=md.results.TransientSolution(i).Vy;
+			results2(count).time=md.results.TransientSolution(i).time;
+			results2(count).step=md.results.TransientSolution(i).step;
+			if ~strcmpi(md.groundingline.migration,'None'),
+				results2(count).ElementOnIceShelf=md.results.TransientSolution(i).ElementOnIceShelf;
+			end
+			count=count+1;
+		end
+	end
+	md.results.TransientSolution=results2;
+	clear results,results2;
+elseif strcmpi(string,'steadystate'),
+	md.initialization.vx=md.results.SteadystateSolution.Vx;
+	md.initialization.vy=md.results.SteadystateSolution.Vy;
+	if isfield(md.results.SteadystateSolution,'Vz'),
+		md.initialization.vz=md.results.SteadystateSolution.Vz;
+	end
+
+	md.initialization.vel=md.results.SteadystateSolution.Vel;
+	md.initialization.pressure=md.results.SteadystateSolution.Pressure;
+	md.initialization.temperature=md.results.SteadystateSolution.Temperature;
+	md.basalforcings.groundedice_melting_rate=md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate;
+
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			md.(EnumToModelField(control_parameters))=md.results.SteadystateSolution.(EnumToString(control_parameters));
+		end
+	end
+
+elseif strcmpi(string,'thermal'),
+	md.initialization.temperature=md.results.ThermalSolution.Temperature;
+	md.basalforcings.groundedice_melting_rate=md.results.ThermalSolution.BasalGroundediceMeltingRate;
+elseif strcmpi(string,'hydrology'),
+	md.initialization.watercolumn=md.results.HydrologySolution.Watercolumn;
+
+else 
+	error(['tres error message: analysis ' string ' not supported yet!']);
+end
+end 
+function string=EnumToModelField(enum) % {{{
+	%ENUMTOMODELFIELD - output string of model field associated to enum
+	%
+	%   Usage:
+	%      string=EnumToModelField(enum)
+
+	disp('Warning: EnumToModelField is deprecated, it cannot work with new model definition. This function will be removed in the future');
+
+	switch enum,
+
+		case ThicknessEnum(), string='thickness'; return
+		case FrictionCoefficientEnum(), string='drag_coefficient'; return
+		case MaterialsRheologyBEnum(), string='rheology_B'; return
+		case MaterialsRheologyBbarEnum(), string='rheology_B'; return
+		case MaterialsRheologyZEnum(), string='rheology_Z'; return
+		case MaterialsRheologyZbarEnum(), string='rheology_Z'; return
+		case BalancethicknessThickeningRateEnum(), string='dhdt'; return
+		case VxEnum(), string='vx'; return
+		case InversionVxObsEnum(), string='vx_obs'; return
+		case VyEnum(), string='vy'; return
+		case InversionVyObsEnum(), string='vy_obs'; return
+		case BasalforcingsMeltingRateEnum(), string='basal_melting_rate'; return
+		case SurfaceforcingsAccumulationRateEnum(), string='surface_accumulation_rate'; return
+		case SurfaceforcingsAblationRateEnum(), string='surface_ablation_rate'; return
+		case SurfaceforcingsMassBalanceEnum(), string='surface_mass_balance'; return
+		otherwise, error(['Enum ' num2str(enum)  ' not found associated to any model field']);
+
+		end
+	end % }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hydrology/effectivepressure.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hydrology/effectivepressure.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/hydrology/effectivepressure.m	(revision 18231)
@@ -0,0 +1,12 @@
+function Neff=effectivepressure(md)
+%EFFECTIVEPRESSURE - compute effective pressure
+%
+%   Usage:
+%      Neff=effectivepressure(md)
+%
+%   Example:
+%      Neff=effectivepressure(md)
+
+Neff=md.materials.rho_ice*md.constants.g*md.geometry.thickness+md.materials.rho_ice*md.constants.g*md.geometry.base;
+pos=find(Neff<0);
+Neff(pos)=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/contourmassbalance.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/contourmassbalance.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/contourmassbalance.m	(revision 18231)
@@ -0,0 +1,45 @@
+function dhdt=contourmassbalance(md,file)
+%CONTOURMASSBALANCE - compute the mass balance on a contour
+%
+%   Usage:
+%      dhdt=contourmassbalance(md,file)
+
+%some checks
+if nargin~=2,
+	help contourmassbalance
+	error('contourmassbalance error message: bad usage');
+end
+if ((length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices))
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+if ~exist(file),
+	error(['thicknessevolution error message: file ' file ' not found']);
+end
+
+%Get segments enveloping contour
+segments=contourenvelope(md,file);
+%md.stressbalance.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
+
+%get flag list of elements and nodes inside the contour
+nodein=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,file,'node',1);
+elemin=(sum(nodein(md.mesh.elements),2)==size(md.mesh.elements,2));
+
+%conputing Mass flux
+x=md.mesh.x;
+y=md.mesh.y;
+vx=mean(md.initialization.vx(segments(:,1:end-1)),2);
+vy=mean(md.initialization.vy(segments(:,1:end-1)),2);
+H=mean(md.geometry.thickness(segments(:,1:end-1)),2);
+nx=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+ny=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+L=sqrt((x(segments(:,1))-x(segments(:,2))).^2+(y(segments(:,2))-y(segments(:,1))).^2);
+flux = - md.materials.rho_ice*sum(L.*H.*(vx.*nx+vy.*ny)); %outflux is negative!
+disp(['mass outflux on ' file ' = ' num2str(-flux/10^9) ' Gt/yr']);
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+dhdt=flux/(sum(areas(find(elemin)))*md.materials.rho_ice);
+disp(['dhdt on ' file ' (Flux  method) = ' num2str(dhdt) ' m/yr']);
+
+dhdt=thicknessevolution(md);
+in=find(elemin);
+dhdt=sum(dhdt(in).*areas(in))/sum(areas(in));
+disp(['dhdt on ' file ' (divHV method) = ' num2str(dhdt) ' m/yr']);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/divergence.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/divergence.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/divergence.m	(revision 18231)
@@ -0,0 +1,27 @@
+function div=divergence(md,a,b)
+%DIVERGENCE - divergence of [a;b] vector, using model's triangulation.
+%
+%   Usage:
+%      div=divergence(md,a,b)
+
+if (dimension(md.mesh)==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y; z=md.mesh.z;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+dx=(a(index).*alpha)*summation;
+dy=(b(index).*beta)*summation;
+
+div=dx+dy;
+div=averaging(md,div,1);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflow.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflow.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflow.m	(revision 18231)
@@ -0,0 +1,18 @@
+function flag=outflow(md)
+%OUTFLOW - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+Nx=-(md.mesh.y(A)-md.mesh.y(B));
+Ny=  md.mesh.x(A)-md.mesh.x(B);
+Vx=(md.initialization.vx(A)+md.initialization.vx(B))/2;
+Vy=(md.initialization.vy(A)+md.initialization.vy(B))/2;
+
+%dot product
+VdotN=Vx.*Nx+Vy.*Ny;
+
+flag=zeros(md.mesh.numberofvertices,1);
+flag(A(find(VdotN>0)))=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflux.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflux.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/massbalance/outflux.m	(revision 18231)
@@ -0,0 +1,48 @@
+function flux=outflux(md,varargin)
+%OUTFLUX - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+%      flag=outflow(md,step);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+
+lx=-(md.mesh.y(A)-md.mesh.y(B));
+ly=  md.mesh.x(A)-md.mesh.x(B);
+L=sqrt(lx.^2+ly.^2);
+Nx=lx./L;
+Ny=ly./L;
+
+if nargin==1,
+	if dimension(md.mesh)==3,
+		vxa=DepthAverage(md,md.initialization.vx);
+		vya=DepthAverage(md,md.initialization.vy);
+	else
+		vxa=md.initialization.vx;
+		vya=md.initialization.vy;
+	end
+	Vx=(vxa(A)+vxa(B))/2;
+	Vy=(vya(A)+vya(B))/2;
+	H=(md.geometry.thickness(A)+md.geometry.thickness(B))/2;
+else
+	step=varargin{1};
+	if dimension(md.mesh)==3,
+		vxa=DepthAverage(md,md.results.TransientSolution(step).Vx);
+		vya=DepthAverage(md,md.results.TransientSolution(step).Vy);
+	else
+		vxa=md.results.TransientSolution(step).Vx;
+		vya=md.results.TransientSolution(step).Vy;
+	end
+	Vx=(vxa(A)+vxa(B))/2;
+	Vy=(vya(A)+vya(B))/2;
+	H=(md.results.TransientSolution(step).Thickness(A)+md.results.TransientSolution(step).Thickness(B))/2;
+end
+
+%dot product
+HVdotN=H.*(Vx.*Nx+Vy.*Ny).*L;
+
+%plot_scatter(md.mesh.x(A),md.mesh.y(A),md.materials.rho_ice*HVdotN,'MarkerSize',4);
+flux=md.materials.rho_ice*sum(HVdotN)/10^12;
+
+disp(['Out flux is ' num2str(flux) ' Gt/yr'])
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/oasis/carter.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/oasis/carter.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/oasis/carter.m	(revision 18231)
@@ -0,0 +1,28 @@
+function attenuation=carter(temperature)
+%CARTER - attenuation as a function of temperature
+%
+%   TWO WAY - Attenuation (in dB/m) as a function of temperature (K)
+%   From Carter at al. 2007 (Radar-based subglacial lake classification in Antarctica)
+%   Figure 4
+%
+%   Usage:
+%      attenuation=carter(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+Temp=[-50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0]';
+A=[0.0015 0.002 0.003 0.0042 0.0055 0.0083 0.012 0.0175 0.026 0.038 0.055]';
+
+%Now, do a cubic fit between Temp and B: 
+[cfun,gof,output]=fit(Temp,A,'cubicspline');
+%breaks=cfun.p.breaks;
+%coeff=cfun.p.coefs;
+
+%Calculate attenuation
+attenuation=cfun(T);
+
+%Make it a 2 way attenuation
+attenuation=2*attenuation;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/paraview/exportVTK.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/paraview/exportVTK.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/paraview/exportVTK.m	(revision 18231)
@@ -0,0 +1,149 @@
+function exportVTK(filename,model,varargin)
+% vtk export
+% function exportVTK(filename,model)
+% creates a directory with the vtk files for displays in paraview
+% (only work for triangle and wedges based on their number of nodes)
+%
+%Give only the results for nw but could be extended to geometry, mask... 
+%
+% input: filename   destination 
+%                   (string)
+%------------------------------------------------------------------
+%        model      this is md 
+%------------------------------------------------------------------
+% By default only the results are exported, you can add whichever
+% field you need as a string:
+% add 'geometry' to export md.geometry
+%
+% Basile de Fleurian:
+
+[path,name,ext]=fileparts(filename);
+separator=filesep;
+mkdir(filename);
+
+%get the element related variables
+if dimension(model.mesh)==2,
+	points=[model.mesh.x model.mesh.y zeros(model.mesh.numberofvertices,1)];
+else
+	points=[model.mesh.x model.mesh.y model.mesh.z];
+end
+
+[num_of_points,dim]=size(points);
+[num_of_elt]=size(model.mesh.elements,1);
+[point_per_elt]=size(model.mesh.elements,2);
+
+%Select the type of element function of the number of nodes per elements
+if point_per_elt==3;
+	celltype=5; %triangles
+elseif point_per_elt==6;
+	celltype=13; %wedges
+else
+	error('Your Element definition is not taken into account \n');
+end
+
+%this is the result structure
+res_struct=model.results;
+%checking for results
+if (length(fields(res_struct))>0);
+	%Getting all the solutions of the model
+	solnames=fields(res_struct);
+	num_of_sols=length(solnames);
+	num_of_timesteps=1;
+	%building solution structure 
+	for i=1:num_of_sols
+		sol_struct{i}=res_struct.(solnames{i});
+		%looking for multiple time steps
+		if(size(sol_struct{i},2)>num_of_timesteps);
+			num_of_timesteps=size(sol_struct{i},2);
+  end
+ end
+else
+	num_of_timesteps=1;
+end
+for step=1:num_of_timesteps;
+	
+	timestep=step;
+
+	fid = fopen(strcat(path,filesep,name,filesep,name,'.vtk',int2str(timestep),'.vtk'),'w+');
+	fprintf(fid,'# vtk DataFile Version 2.0 \n');
+	fprintf(fid,'Data for run %s \n',model.miscellaneous.name);
+	fprintf(fid,'ASCII \n');
+	fprintf(fid,'DATASET UNSTRUCTURED_GRID \n');
+	
+	fprintf(fid,'POINTS %d float\n',num_of_points);
+	if(dim==3);
+		s='%f %f %f \n';
+	elseif(dim==2);
+		s='%f %f \n';
+  end
+	P=[points zeros(num_of_points,3-dim)];
+	fprintf(fid,s,P');
+	
+	fprintf(fid,'CELLS %d %d\n',num_of_elt,num_of_elt*(point_per_elt+1));
+	s='%d';
+	for j=1:point_per_elt
+		s=horzcat(s,{' %d'});
+  end
+	s=cell2mat(horzcat(s,{'\n'}));
+	fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
+	
+	fprintf(fid,'CELL_TYPES %d\n',num_of_elt);
+	s='%d\n';
+	fprintf(fid,s,celltype*ones(num_of_elt,1));
+	fprintf(fid,'POINT_DATA %s \n',num2str(num_of_points));
+
+	%loop over the different solution structures
+	if (exist('num_of_sols'));
+		for j=1:num_of_sols
+			%dealing with results on different timesteps
+			if(size(sol_struct{j},2)>timestep);
+				timestep = step;
+			else
+				timestep = size(sol_struct{j},2);
+	    end
+			
+			%getting the number of fields in the solution
+			fieldnames=fields(sol_struct{j}(timestep));
+			num_of_fields=length(fieldnames);
+			
+			%check which field is a real result and print
+			for k=1:num_of_fields
+				if ((numel(sol_struct{j}(timestep).(fieldnames{k})))== ...
+						num_of_points);
+					%paraview does not like NaN, replacing
+					nanval=find(isnan(sol_struct{j}(timestep).(fieldnames{k})));
+					sol_struct{j}(timestep).(fieldnames{k})(nanval)=-9999;
+					%also checking for verry small value that mess up
+					smallval=(abs(sol_struct{j}(timestep).(fieldnames{k}))<1.0e-20);
+					sol_struct{j}(timestep).(fieldnames{k})(smallval)=0.0;
+					fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
+					fprintf(fid,'LOOKUP_TABLE default\n');
+					s='%e\n';
+					fprintf(fid,s,sol_struct{j}(timestep).(fieldnames{k}));
+		    end		
+	    end 
+	  end
+  end
+	%loop on arguments, if something other than result is asked, do
+	%it now
+	for j= 1:nargin-2
+		res_struct=model.(varargin{j});
+		fieldnames=fields(res_struct);
+		num_of_fields=length(fieldnames);
+		for k=1:num_of_fields
+			if ((numel(res_struct.(fieldnames{k})))==num_of_points);
+				%paraview does not like NaN, replacing
+				nanval=find(isnan(res_struct.(fieldnames{k})));
+				res_struct.(fieldnames{k})(nanval)=-9999;
+				%also checking for verry small value that mess up
+				smallval=(abs(res_struct.(fieldnames{k}))<1.0e-20);
+				res_struct.(fieldnames{k})(smallval)=0.0;
+				fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
+				fprintf(fid,'LOOKUP_TABLE default\n');
+				s='%e\n';
+				fprintf(fid,s,res_struct.(fieldnames{k}));
+	    end		
+		end 
+	end
+	fclose(fid);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expremovestraightsegments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expremovestraightsegments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expremovestraightsegments.m	(revision 18231)
@@ -0,0 +1,31 @@
+function expremovestraightsegments(newfilename,filename,cutoff)
+%EXPREMOVESTRAIGHTSEGMENTS:  remove straight segments connecting contours.
+%
+% Usage: expremovestraightsegments('argus.exp',100); 
+%
+%
+
+a=expread(filename,1);
+newcontours=a(1);
+
+for i=1:length(a),
+	contour=a(i);
+
+	s=sqrt(contour.x.^2+contour.y.^2);
+	d=diff(s);
+
+	pos=find(abs(d)>cutoff);
+	pos=[0;pos;length(contour.x)];
+
+	for j=1:length(pos)-1,
+
+		newcontour=contour;
+		newcontour.x=contour.x(pos(j)+1:pos(j+1));
+		newcontour.y=contour.y(pos(j)+1:pos(j+1));
+		newcontour.nods=length(newcontour.x);
+		newcontours(end+1)=newcontour;
+	end
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,newfilename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expsplit.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expsplit.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/expsplit.m	(revision 18231)
@@ -0,0 +1,31 @@
+function expsplit(domainoutline)
+%EXPSPLIT - split exp file into sub-contours
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%   This will create as many files there are contours in the domain, each file will be postfix with _i
+%   where i is the contour name. 
+%
+%   Usage:
+%      expsplit(domainoutline)
+%
+%   Example:
+%      expsplit('Domain.exp');
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>1
+	help expsplit
+	error('expsplit error message: bad usage');
+end
+
+[path,root,ext]=fileparts(domainoutline);
+
+%Read file: 
+domains=expread(domainoutline,1);
+
+%split and write contours: 
+for i=1:length(domains),
+	subdomain=domains(i);
+	expwrite(subdomain,[root '_' num2str(i)  ext]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/pargenerate.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/pargenerate.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/contrib/uci/pargenerate.m	(revision 18231)
@@ -0,0 +1,45 @@
+function pargenerate(filename,xm,ym,data,varargin)
+%PARGENERATE - generate parameter file for images ala Rignot
+%
+%   Usage: 
+%      pargenerate(filename,data,xm,ym,options);
+%
+%   Supported options:
+%      - title: dataset title
+%      - latitude: standard latitude (degree)
+%      - meridian: meridian (degree)
+%      - format: binary format
+
+%process options
+options=pairoptions(varargin{:});
+Title=getfieldvalue(options,'title','N/A');
+latitude=getfieldvalue(options,'latitude','N/A');
+meridian=getfieldvalue(options,'meridian','N/A');
+format=getfieldvalue(options,'format','single');
+
+%Get data info
+[nlines ncols]=size(data);
+xmin=min(xm);
+ymax=max(ym);
+postx=abs(xm(2)-xm(1));
+posty=abs(ym(2)-ym(1));
+
+%Open header file and get machine type
+fid=fopen(filename,'wt');
+[filename, permission, machineformat, encoding] = fopen(fid);
+
+%write header file
+fprintf(fid,'%s\n','ISSM gridded dataset parameter file');
+fprintf(fid,'%s%s\n','title: ',Title);
+fprintf(fid,'%s  \n','DEM_projection: PS');
+fprintf(fid,'%s%s\n','data_format: ',format);
+fprintf(fid,'%s%s\n','endian:      ',machineformat);
+fprintf(fid,'%s%d\n','width:  ',ncols);
+fprintf(fid,'%s%d\n','nlines: ',nlines);
+fprintf(fid,'%s%g%s\n','PS_secant_lat:    ',latitude,'   decimal degrees');
+fprintf(fid,'%s%g%s\n','PS_meridian_long: ',meridian,'   decimal degrees');
+fprintf(fid,'%s%-15.10g\n','PS_corner_north:  ',ymax);
+fprintf(fid,'%s%-15.10g\n','PS_corner_east:   ',xmin);
+fprintf(fid,'%s%g%s\n','PS_post_north:    ',postx,' m');
+fprintf(fid,'%s%g%s\n','PS_post_east:     ',posty,' m');
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/gdaltransform.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/gdaltransform.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/gdaltransform.m	(revision 18231)
@@ -0,0 +1,19 @@
+function [xout,yout] = gdaltransform(x,y,proj_in,proj_out)
+%GDALTRANSFORM - switch from one projection system to another 
+%
+%   Usage:
+%      [x,y] = gdaltransform(x1,y1,'EPSG:3184','EPSG:3411')
+%
+%
+
+	fid=fopen('.rand1234.txt','w');
+	for i=1:length(x),
+		fprintf(fid,'%g %g\n',x(i),y(i));
+	end
+	fclose(fid);
+
+	[s,r]=system(['gdaltransform -s_srs ',proj_in,' -t_srs ',proj_out,'  < .rand1234.txt > .rand1235.txt']);
+
+	A=textread('.rand1235.txt');
+	xout=A(:,1);
+	yout=A(:,2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/lambert2xy.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/lambert2xy.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/lambert2xy.m	(revision 18231)
@@ -0,0 +1,68 @@
+function [x,y] = lambert2xy(lat,lon,sgn,projection_center_lat,projection_center_lon)  
+%LAMBERT2XY - converts lat long from Lambert Azimuthal to Polar Stereographic
+%
+%   Converts from geodetic latitude and longitude that are 
+%   in Lambert Azimuthal (equal area) projections to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%
+%   Usage:
+%      [x,y] = lambert2xy(lat,lon,sgn)
+%      [x,y] = lambert2xy(lat,lon,sgn,projection_center_lat,projection_center_lon)
+%
+%      - provide lat in [-90,90] and lon in [-180,180].
+
+%      - sgn = +1 N hemisphere [default projection center lat = 90 lon=0]
+%              -1 S hemisphere [default projection center lat = -90 lon=0]
+
+%Get projection_center_lat and projection_center_lon 
+if nargin==5,
+	latitude0  = projection_center_lat;
+	longitude0 = projection_center_lon;
+elseif nargin==3,
+	if sgn==1,
+		latitude0 = 90; longitude0 = 0;
+		disp('Info: creating coordinates in polar stereographic (Projection center lat: 90N lon: 0)');
+	elseif sgn==-1,
+		latitude0 = -90; longitude0 = 0;
+		disp('Info: creating coordinates in polar stereographic (Projection center lat: 90S lon: 0)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help lambert2xy
+	error('bad usage');
+end
+
+% Radius of the earth in meters 
+a = 6378137.0;
+% Eccentricity of the Hughes ellipsoid squared
+e = 0.081819191;
+
+% Projection center latitude and longitude in radians 
+phi0 = latitude0 * pi/180; 
+lam0 = longitude0 * pi/180; 
+
+% Some constant based on phi0 and lam0
+qp= (1-e^2)*((1/(1-e^2))-((1/(2*e))*log((1-e)/(1+e))));
+q0=(1-e^2)*((sin(phi0)/(1-e^2*sin(phi0)*sin(phi0)))-((1/(2*e))*log((1-e*sin(phi0))/(1+e*sin(phi0)))));
+Rq=a*sqrt(qp/2);
+b0=asin(q0/qp);
+D =a*(cos(phi0)/sqrt(1-e^2*sin(phi0)*sin(phi0)))/(Rq*cos(b0));
+
+% Latitude and longitude in radians 
+phi = lat*pi/180;
+lam = lon*pi/180;
+
+% Some other phi,lam dependent parameters 
+q=(1-e^2)*((sin(phi)/(1-e^2*sin(phi)*sin(phi)))-((1/(2*e))*log((1-e*sin(phi))/(1+e*sin(phi)))));
+b =asin(q/qp);
+B =Rq*sqrt(2/(1+sin(b0)*sin(b)+(cos(b0)*cos(b)*cos(lam-lam0))));
+
+% Calculation of x and y
+if(abs(lat)==90)
+	x=0.0; 
+	y=0.0; 
+else
+	x=(B*D)*(cos(b)*sin(lam-lam0));
+	y=(B/D)*((cos(b0)*sin(b))-(sin(b0)*cos(b)*cos(lam-lam0)));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2mercator.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2mercator.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2mercator.m	(revision 18231)
@@ -0,0 +1,13 @@
+function [mx my]=ll2mercator(lat, lon),
+%LL2MERCATOR - transform lat long to mercator projection
+%
+%   Usage:
+%      [mx my]=ll2mercator(lat, lon)
+
+EARTH_RADIUS = 6378137;
+EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+mx = (lon * ORIGIN_SHIFT) / 180.0;
+my = log(tan((90 + lat) * pi/360.0))/(pi/180.0);
+my = (my * ORIGIN_SHIFT) /180.0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.m	(revision 18231)
@@ -0,0 +1,66 @@
+function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help ll2xy
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+latitude  = abs(lat) * pi/180.;
+longitude = (lon + delta) * pi/180.;
+
+% compute X and Y in grid coordinates.
+T = tan(pi/4-latitude/2) ./ ((1-ex*sin(latitude))./(1+ex*sin(latitude))).^(ex/2);
+
+if (90 - slat) <  1.e-5 
+	rho = 2.*re*T/sqrt((1.+ex)^(1.+ex)*(1.-ex)^(1.-ex));
+else
+	sl  = slat*pi/180.;
+	tc  = tan(pi/4.-sl/2.)/((1.-ex*sin(sl))/(1.+ex*sin(sl)))^(ex/2.);
+	mc  = cos(sl)/sqrt(1.0-ex2*(sin(sl)^2));
+	rho = re*mc*T/tc;
+end
+
+y = -rho .* sgn .* cos(sgn.*longitude);
+x =  rho .* sgn .* sin(sgn.*longitude);
+
+[cnt1,cnt2] = find(latitude >= pi / 2.);
+
+if cnt1
+	x(cnt1,1) = 0.0;
+	y(cnt1,1) = 0.0;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/ll2xy.py	(revision 18231)
@@ -0,0 +1,62 @@
+import numpy as npy 
+
+def ll2xy(lat,lon,sgn=-1,central_meridian=0,standard_parallel=71):
+	'''
+	LL2XY - converts lat lon to polar stereographic
+
+   Converts from geodetic latitude and longitude to Polar 
+   Stereographic (X,Y) coordinates for the polar regions.
+   Author: Michael P. Schodlok, December 2003 (map2ll)
+
+   Usage:
+      x,y = ll2xy(lat,lon,sgn)
+      x,y = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+
+      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+                               -1 : south latitude (default is mer=0  lat=71)
+	'''
+
+	assert sgn==1 or sgn==-1, 'error: sgn should be either +1 or -1'
+
+	#Get central_meridian and standard_parallel depending on hemisphere
+	if sgn == 1:
+		delta = 45
+		slat = 70
+		print '		ll2xy: creating coordinates in north polar stereographic (Std Latitude: 70N Meridian: 45)'
+	else: 
+		delta = central_meridian
+		slat = standard_parallel
+		print '		ll2xy: creating coordinates in south polar stereographic (Std Latitude: 71S Meridian: 0)'
+	
+	# Conversion constant from degrees to radians
+	cde = 57.29577951
+	# Radius of the earth in meters
+	re = 6378.273*10**3
+	# Eccentricity of the Hughes ellipsoid squared
+	ex2 = .006693883
+	# Eccentricity of the Hughes ellipsoid
+	ex = npy.sqrt(ex2)
+	
+	latitude = npy.abs(lat) * npy.pi/180.
+	longitude = (lon + delta) * npy.pi/180.
+	
+	# compute X and Y in grid coordinates.
+	T = npy.tan(npy.pi/4-latitude/2) / ((1-ex*npy.sin(latitude))/(1+ex*npy.sin(latitude)))**(ex/2)
+	
+	if (90 - slat) <  1.e-5:
+		rho = 2.*re*T/npy.sqrt((1.+ex)**(1.+ex)*(1.-ex)**(1.-ex))
+	else:
+		sl  = slat*npy.pi/180.
+		tc  = npy.tan(npy.pi/4.-sl/2.)/((1.-ex*npy.sin(sl))/(1.+ex*npy.sin(sl)))**(ex/2.)
+		mc  = npy.cos(sl)/npy.sqrt(1.0-ex2*(npy.sin(sl)**2))
+		rho = re*mc*T/tc
+	
+	y = -rho * sgn * npy.cos(sgn*longitude)
+	x =  rho * sgn * npy.sin(sgn*longitude)
+
+	cnt1=npy.nonzero(latitude>= npy.pi/2.)[0]
+	
+	if cnt1:
+		x[cnt1,0] = 0.0
+		y[cnt1,0] = 0.0
+	return x,y
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/mercator2ll.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/mercator2ll.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/mercator2ll.m	(revision 18231)
@@ -0,0 +1,13 @@
+function [lat lon]=mercator2ll(mx,my),
+%LL2MERCATOR - transform mercator projection to lat/lon
+%
+%   Usage:
+%      [lat lon]=mercator2ll(mx,my)
+
+EARTH_RADIUS = 6378137;
+EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+lon = mx * 180.0 / ORIGIN_SHIFT;
+lat = my * 180.0 /ORIGIN_SHIFT;
+lat = 180.0/pi*(2.0*atan(exp(lat*pi/180.0))-pi/2.0);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/utm2ll.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/utm2ll.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/utm2ll.m	(revision 18231)
@@ -0,0 +1,117 @@
+function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
+% -------------------------------------------------------------------------
+% [Lat,Lon] = utm2ll(x,y,utmzone)
+%
+% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
+% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%
+% Inputs:on)
+%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%
+% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
+% [Lat, Lon]=utm2ll(x,y,utmzone);
+% LatDMS=dms2mat(deg2dms(Lat))
+%LatDMS =
+%    40.00         18.00         55.55
+%    46.00         17.00          2.01
+%    37.00         34.00         40.17
+%    28.00         38.00         44.33
+%    38.00         51.00         19.96
+%    25.00          3.00         42.41
+% LonDMS=dms2mat(deg2dms(Lon))
+%LonDMS =
+%    -3.00         29.00          8.61
+%     7.00         48.00          4.40
+%  -119.00         57.00         18.93
+%   -17.00         45.00         34.33
+%   -94.00         47.00         56.47
+%   121.00         38.00         24.96
+%
+% Author:
+%   Rafael Palacios
+%   Universidad Pontificia Comillas
+%   Madrid, Spain
+% Version: Apr/06, Jun/06, Aug/06
+% Aug/06: corrected m-Lint warnings
+%-------------------------------------------------------------------------
+
+% Argument checking
+%
+error(nargchk(3, 3, nargin)); %3 arguments required
+n1=length(xx);
+n2=length(yy);
+n3=size(utmzone,1);
+if (n1~=n2 || n1~=n3)
+	error('x,y and utmzone vectors should have the same number or rows');
+end
+c=size(utmzone,2);
+if (c~=4)
+	error('utmzone should be a vector of strings like "30 T"');
+end
+
+% Memory pre-allocation
+%
+Lat=zeros(n1,1);
+Lon=zeros(n1,1);
+
+% Main Loop
+%
+for i=1:n1
+	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
+		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+	end
+	if (utmzone(i,4)>'M')
+		hemis='N';   % Northern hemisphere
+	else
+		hemis='S';
+	end
+
+	x=xx(i);
+	y=yy(i);
+	zone=str2double(utmzone(i,1:2));
+
+	sa = 6378137.000000 ; sb = 6356752.314245;
+
+	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
+	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
+	e2cuadrada = e2 ^ 2;
+	c = ( sa ^ 2 ) / sb;
+	%   alpha = ( sa - sb ) / sa;             %f
+	%   ablandamiento = 1 / alpha;   % 1/f
+
+	X = x - 500000;
+
+	if hemis == 'S' || hemis == 's'
+		Y = y - 10000000;
+	else
+		Y = y;
+	end
+
+	S = ( ( zone * 6 ) - 183 );
+	lat =  Y / ( 6366197.724 * 0.9996 );
+	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
+	a = X / v;
+	a1 = sin( 2 * lat );
+	a2 = a1 * ( cos(lat) ) ^ 2;
+	j2 = lat + ( a1 / 2 );
+	j4 = ( ( 3 * j2 ) + a2 ) / 4;
+	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
+	alfa = ( 3 / 4 ) * e2cuadrada;
+	beta = ( 5 / 3 ) * alfa ^ 2;
+	gama = ( 35 / 27 ) * alfa ^ 3;
+	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
+	b = ( Y - Bm ) / v;
+	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
+	Eps = a * ( 1 - ( Epsi / 3 ) );
+	nab = ( b * ( 1 - Epsi ) ) + lat;
+	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
+	Delt = atan(senoheps / (cos(nab) ) );
+	TaO = atan(cos(Delt) * tan(nab));
+	longitude = (Delt *(180 / pi ) ) + S;
+	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
+		(180 / pi);
+
+	Lat(i)=latitude;
+	Lon(i)=longitude;
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2lambert.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2lambert.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2lambert.m	(revision 18231)
@@ -0,0 +1,68 @@
+function [lat,lon] = xy2lambert(x,y,sgn,projection_center_lat,projection_center_lon)  
+%XY2LAMBERT - converts xy to lat lon in Lambert Azimuthal
+%
+%   Converts from Ploar Stereographic (X,Y) coordinates to geodetic 
+%   lat lon that are in Lambert Azimuthal (equal area) projection.
+%
+%   Usage:
+%      [lat,lon] = xy2lambert(x,y,sgn)
+%      [lat,lon] = xy2lambert(x,y,sgn,projection_center_lat,projection_center_lon)
+%
+%      - provide lat in [-90,90] and lon in [-180,180].
+%
+%      - sgn = +1 N hemisphere [default projection center lat = 90 lon=0]
+%              -1 S hemisphere [default projection center lat = -90 lon=0]
+
+%Get projection_center_lat and projection_center_lon 
+if nargin==5,
+	latitude0  = projection_center_lat;
+	longitude0 = projection_center_lon;
+elseif nargin==3,
+	if sgn==1,
+		latitude0 = 90; longitude0 = 0;
+		disp('Info: creating coordinates in Lambert Azimuthal equal-area (Projection center lat: 90N lon: 0)');
+	elseif sgn==-1,
+		latitude0 = -90; longitude0 = 0;
+		disp('Info: creating coordinates in Lambert Azimuthal equal-area (Projection center lat: 90S lon: 0)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2lambert
+	error('bad usage');
+end
+
+% Radius of the earth in meters 
+a = 6378137.0;
+% Eccentricity of the Hughes ellipsoid squared
+e = 0.081819191;
+
+% Projection center latitude and longitude in radians 
+phi0 = latitude0 * pi/180; 
+lam0 = longitude0 * pi/180; 
+
+% Some constants based on phi0 and lam0
+% (as in forward calculation)
+qp= (1-e^2)*((1/(1-e^2))-((1/(2*e))*log((1-e)/(1+e))));
+q0=(1-e^2)*((sin(phi0)/(1-e^2*sin(phi0)*sin(phi0)))-((1/(2*e))*log((1-e*sin(phi0))/(1+e*sin(phi0)))));
+Rq=a*sqrt(qp/2);
+b0=asin(q0/qp);
+D =a*(cos(phi0)/sqrt(1-e^2*sin(phi0)*sin(phi0)))/(Rq*cos(b0));
+
+% Some other (x,y) dependent parameters 
+rho=sqrt((x/D)^2+(D*y)^2);
+C=2*asin(rho/(2*Rq));
+b_prime=asin((cos(C)*sin(b0))+((D*y*sin(C)*cos(b0))/rho));
+
+% Calculation of lat and lon 
+dist=sqrt(x^2+y^2);
+if(dist<=0.1)
+	lat=sgn*90.0;
+	lon=0.0;
+else
+	lat_rad=b_prime+((e^2/3+31*e^4/180+517*e^6/5040)*sin(2*b_prime))+((23*e^4/360+251*e^6/3780)*sin(4*b_prime))+((761*e^6/45360)*sin(6*b_prime));
+	lon_rad=lam0+atan(x*sin(C)/(D*rho*cos(b0)*cos(C)-D^2*y*sin(b0)*sin(C)));
+	% in degrees 
+	lat=lat_rad*180/pi;
+	lon=lon_rad*180/pi;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.m	(revision 18231)
@@ -0,0 +1,72 @@
+function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2ll
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+sl  = slat*pi/180.;
+rho = sqrt(x.^2 + y.^2);
+cm = cos(sl) / sqrt(1.0 - ex2 * (sin(sl)^2));
+T = tan((pi / 4.0) - (sl / 2.0)) / ((1.0 - ex * sin(sl)) / (1.0 + ex * sin(sl)))^(ex / 2.0);
+
+if  abs(slat-90.) < 1.e-5
+	T = rho * sqrt((1. + ex)^(1. + ex) * (1. - ex)^(1. - ex)) / 2. / re;
+else
+	T = rho * T / (re * cm);
+end
+
+chi = (pi / 2.0) - 2.0 * atan(T);
+lat = chi + ((ex2 / 2.0) + (5.0 * ex2^2.0 / 24.0) + (ex2^3.0 / 12.0)) * ...
+	sin(2 * chi) + ((7.0 * ex2^2.0 / 48.0) + (29.0 * ex2^3 / 240.0)) * ...
+	sin(4.0 * chi) + (7.0 * ex2^3.0 / 120.0) * sin(6.0 * chi) ;
+
+lat = sgn * lat;
+lon = atan2(sgn * x,-sgn * y);
+lon = sgn * lon;
+
+[res1,res2] = find(rho <= 0.1);
+if res1
+	lat(res1,1) = 90. * sgn;
+	lon(res1,1) = 0.0;
+end
+
+lon = lon * 180. / pi;
+lat = lat * 180. / pi;
+lon = lon - delta; 
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/coordsystems/xy2ll.py	(revision 18231)
@@ -0,0 +1,82 @@
+import numpy as npy
+from math import pi
+
+def xy2ll(x, y, sgn, *args):
+	'''
+	XY2LL - converts xy to lat long
+	
+	Converts Polar  Stereographic (X, Y) coordinates for the polar regions to
+	latitude and longitude Stereographic (X, Y) coordinates for the polar
+	regions.
+	Author: Michael P. Schodlok, December 2003 (map2xy.m)
+	
+	Usage:
+	   [lat, lon] = xy2ll(x, y, sgn);
+	   [lat, lon] = xy2ll(x, y, sgn, central_meridian, standard_parallel);
+	
+	   - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+	                            -1 : south latitude (default is mer=0  lat=71)
+	'''
+
+	#Get central_meridian and standard_parallel depending on hemisphere
+	if len(args) == 2:
+		delta = args[0]
+		slat  = args[1]
+	elif len(args) == 0:
+		if sgn == 1:
+			delta = 45. 
+			slat = 70.
+			print '		xy2ll: creating coordinates in north polar stereographic (Std Latitude: 70degN Meridian: 45deg)'
+		elif sgn == -1:
+			delta = 0.  
+			slat = 71.
+			print '		xy2ll: creating coordinates in south polar stereographic (Std Latitude: 71degS Meridian: 0deg)'
+		else:
+			raise ValueError('sgn should be either +1 or -1')
+	else:
+		raise StandardError('bad usage: type "help(xy2ll)" for details')
+
+	# if x,y passed as lists, convert to numpy arrays
+	if type(x) != "numpy.ndarray":
+		x=npy.array(x)
+	if type(y) != "numpy.ndarray":
+		y=npy.array(y)
+
+	## Conversion constant from degrees to radians
+	cde = 57.29577951
+	## Radius of the earth in meters
+	re = 6378.273*10**3
+	## Eccentricity of the Hughes ellipsoid squared
+	ex2 = .006693883
+	## Eccentricity of the Hughes ellipsoid
+	ex = npy.sqrt(ex2)
+	
+	sl = slat*pi/180.
+	rho = npy.sqrt(x**2 + y**2)
+	cm = npy.cos(sl) / npy.sqrt(1.0 - ex2 * (npy.sin(sl)**2))
+	T = npy.tan((pi/4.0) - (sl/2.0)) / ((1.0 - ex*npy.sin(sl)) / (1.0 + ex*npy.sin(sl)))**(ex / 2.0)
+	
+	if abs(slat-90.) < 1.e-5:
+		T = rho*npy.sqrt((1. + ex)**(1. + ex) * (1. - ex)**(1. - ex)) / 2. / re
+	else:
+		T = rho * T / (re * cm)
+	
+	chi = (pi / 2.0) - 2.0 * npy.arctan(T)
+	lat = chi + ((ex2 / 2.0) + (5.0 * ex2**2.0 / 24.0) + (ex2**3.0 / 12.0)) * \
+		npy.sin(2 * chi) + ((7.0 * ex2**2.0 / 48.0) + (29.0 * ex2**3 / 240.0)) * \
+		npy.sin(4.0 * chi) + (7.0 * ex2**3.0 / 120.0) * npy.sin(6.0 * chi) 
+	
+	lat = sgn * lat
+	lon = npy.arctan2(sgn * x,-sgn * y)
+	lon = sgn * lon
+	
+	res1 = npy.nonzero(rho <= 0.1)[0]
+	if len(res1) > 0:
+		lat[res1] = 90. * sgn
+		lon[res1] = 0.0
+	
+	lon = lon * 180. / pi
+	lat = lat * 180. / pi
+	lon = lon - delta 
+
+	return lat, lon
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.m	(revision 18231)
@@ -0,0 +1,40 @@
+% clear the last warning to focus on the warnings of the ISSM path
+lastwarn(''); 
+
+%Recover ISSM_DIR , or if on a Windows machine, ISSM_DIR_WIN
+if ~ispc,
+	ISSM_DIR=getenv('ISSM_DIR');
+else
+	ISSM_DIR=getenv('ISSM_DIR_WIN');
+end
+if (isempty(ISSM_DIR)),
+	error('''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!');
+end
+
+%Now add all issm code paths necessary to run issm smoothly. 
+%We capture the error output, so that we can warn the user to update 
+%the variable ISSM_DIR in this file, in case it is not correctly setup. 
+
+%ISSM path
+addpath([ISSM_DIR '/src/m/os/']); %load recursivepath
+addpath([ISSM_DIR '/lib']);       %load mex
+addpath(recursivepath([ISSM_DIR '/src/m']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/scotch']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/canos']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/kml']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/export_fig']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/googleearthtoolbox']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/howatmask']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/dem']));
+clear ISSM_DIR;
+
+%Check on any warning messages that might indicate that the paths were not correct. 
+if ~isempty(lastwarn),
+	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_DIR variable in your .cshrc or .bashrc!\n');
+	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
+else
+	fprintf('\n  ISSM development path correctly loaded\n\n');
+end
+
+%disable matlab bell!
+beep off;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/devpath.py	(revision 18231)
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+import os,sys
+
+#Recover ISSM_DIR and USERNAME
+ISSM_DIR=os.getenv('ISSM_DIR')
+USERNAME =os.getenv('USER')
+if(ISSM_DIR==None):
+	raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!')
+
+#Go through src/m and append any directory that contains a *.py file to PATH 
+for root,dirs,files in os.walk(ISSM_DIR+ '/src/m'):
+	if '.svn' in dirs:
+		dirs.remove('.svn')
+	for file in files:
+		if file.find(".py") != -1:
+			if file.find(".pyc") == -1:
+				if root not in sys.path:
+					sys.path.append(root)
+				
+sys.path.append(ISSM_DIR + '/lib')
+sys.path.append(ISSM_DIR + '/src/wrappers/python/.libs')
+
+#Manual imports for commonly used functions
+from plotmodel import plotmodel
+
+#c = get_ipython().config
+#c.InteractiveShellApp.exec_lines = []
+#c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
+#c.InteractiveShellApp.exec_lines.append('%autoreload 2')
+#c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in startup.py to improve performance." ')
+
+print("\n  ISSM development path correctly loaded\n\n")
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.m	(revision 18231)
@@ -0,0 +1,20 @@
+function issmversion(),
+%ISSMVERSION - display ISSM version
+%
+%   Usage:
+%      issmversion()
+
+
+if exist('IssmConfig')~=3,
+	error('ISSM not correctly installed. IssmConfig not found');
+end
+
+disp([' ']);
+disp([IssmConfig('PACKAGE_NAME') ' Version ' IssmConfig('PACKAGE_VERSION')]);
+disp(['(website: ' IssmConfig('PACKAGE_URL') ' contact:' IssmConfig('PACKAGE_BUGREPORT') ')']);
+disp([' ']);
+disp(['Build date: ' IssmConfig('PACKAGE_BUILD_DATE')]);
+disp(['Copyright (c) 2009-2014 California Institute of Technology']);
+disp([' ']);
+disp(['    to get started type: issmdoc']);
+disp([' ']);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/dev/issmversion.py	(revision 18231)
@@ -0,0 +1,20 @@
+from IssmConfig import IssmConfig
+
+def issmversion():
+	"""
+	ISSMVERSION - display ISSM version
+
+		Usage:
+			issmversion()
+	"""
+
+
+print ' '
+print IssmConfig('PACKAGE_NAME')[0]+' Version '+IssmConfig('PACKAGE_VERSION')[0]
+print '(website: '+IssmConfig('PACKAGE_URL')[0]+' contact:'+IssmConfig('PACKAGE_BUGREPORT')[0]+')'
+print ' '
+print 'Build date: '+IssmConfig('PACKAGE_BUILD_DATE')[0]
+print 'Copyright (c) 2009-2013 California Institute of Technology'
+print ' '
+print '    to get started type: issmdoc'
+print ' '
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AbsoluteEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AbsoluteEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AbsoluteEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AbsoluteEnum()
+%ABSOLUTEENUM - Enum of Absolute
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AbsoluteEnum()
+
+macro=StringToEnum('Absolute');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethickness2AnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethickness2AnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethickness2AnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointBalancethickness2AnalysisEnum()
+%ADJOINTBALANCETHICKNESS2ANALYSISENUM - Enum of AdjointBalancethickness2Analysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointBalancethickness2AnalysisEnum()
+
+macro=StringToEnum('AdjointBalancethickness2Analysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethicknessAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointBalancethicknessAnalysisEnum()
+%ADJOINTBALANCETHICKNESSANALYSISENUM - Enum of AdjointBalancethicknessAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointBalancethicknessAnalysisEnum()
+
+macro=StringToEnum('AdjointBalancethicknessAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointEnum()
+%ADJOINTENUM - Enum of Adjoint
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointEnum()
+
+macro=StringToEnum('Adjoint');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointHorizAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointHorizAnalysisEnum()
+%ADJOINTHORIZANALYSISENUM - Enum of AdjointHorizAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointHorizAnalysisEnum()
+
+macro=StringToEnum('AdjointHorizAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointpEnum()
+%ADJOINTPENUM - Enum of Adjointp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointpEnum()
+
+macro=StringToEnum('Adjointp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointxEnum()
+%ADJOINTXENUM - Enum of Adjointx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointxEnum()
+
+macro=StringToEnum('Adjointx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointyEnum()
+%ADJOINTYENUM - Enum of Adjointy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointyEnum()
+
+macro=StringToEnum('Adjointy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdjointzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdjointzEnum()
+%ADJOINTZENUM - Enum of Adjointz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdjointzEnum()
+
+macro=StringToEnum('Adjointz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdolcParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdolcParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AdolcParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AdolcParamEnum()
+%ADOLCPARAMENUM - Enum of AdolcParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AdolcParamEnum()
+
+macro=StringToEnum('AdolcParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AggressiveMigrationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AggressiveMigrationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AggressiveMigrationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AggressiveMigrationEnum()
+%AGGRESSIVEMIGRATIONENUM - Enum of AggressiveMigration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AggressiveMigrationEnum()
+
+macro=StringToEnum('AggressiveMigration');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AirEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AirEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AirEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AirEnum()
+%AIRENUM - Enum of Air
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AirEnum()
+
+macro=StringToEnum('Air');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisCounterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisCounterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisCounterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AnalysisCounterEnum()
+%ANALYSISCOUNTERENUM - Enum of AnalysisCounter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AnalysisCounterEnum()
+
+macro=StringToEnum('AnalysisCounter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AnalysisTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AnalysisTypeEnum()
+%ANALYSISTYPEENUM - Enum of AnalysisType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AnalysisTypeEnum()
+
+macro=StringToEnum('AnalysisType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AndroidFrictionCoefficientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AndroidFrictionCoefficientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AndroidFrictionCoefficientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AndroidFrictionCoefficientEnum()
+%ANDROIDFRICTIONCOEFFICIENTENUM - Enum of AndroidFrictionCoefficient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AndroidFrictionCoefficientEnum()
+
+macro=StringToEnum('AndroidFrictionCoefficient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ApproximationEnum()
+%APPROXIMATIONENUM - Enum of Approximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ApproximationEnum()
+
+macro=StringToEnum('Approximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ArrheniusEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ArrheniusEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ArrheniusEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ArrheniusEnum()
+%ARRHENIUSENUM - Enum of Arrhenius
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ArrheniusEnum()
+
+macro=StringToEnum('Arrhenius');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianREnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianREnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianREnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianREnum()
+%AUGMENTEDLAGRANGIANRENUM - Enum of AugmentedLagrangianR
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianREnum()
+
+macro=StringToEnum('AugmentedLagrangianR');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianRhopEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianRhopEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianRhopEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianRhopEnum()
+%AUGMENTEDLAGRANGIANRHOPENUM - Enum of AugmentedLagrangianRhop
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianRhopEnum()
+
+macro=StringToEnum('AugmentedLagrangianRhop');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianThetaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianThetaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AugmentedLagrangianThetaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianThetaEnum()
+%AUGMENTEDLAGRANGIANTHETAENUM - Enum of AugmentedLagrangianTheta
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianThetaEnum()
+
+macro=StringToEnum('AugmentedLagrangianTheta');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffCbufsizeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffCbufsizeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffCbufsizeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffCbufsizeEnum()
+%AUTODIFFCBUFSIZEENUM - Enum of AutodiffCbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffCbufsizeEnum()
+
+macro=StringToEnum('AutodiffCbufsize');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectIndicesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffDependentObjectIndicesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectIndices');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectNamesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffDependentObjectNamesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectNames');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectTypesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffDependentObjectTypesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectTypes');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffDependentObjectsEnum()
+
+macro=StringToEnum('AutodiffDependentObjects');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDriverEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDriverEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffDriverEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffDriverEnum()
+
+macro=StringToEnum('AutodiffDriver');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosForwardIndexEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffFosForwardIndexEnum()
+
+macro=StringToEnum('AutodiffFosForwardIndex');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosReverseIndexEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffFosReverseIndexEnum()
+
+macro=StringToEnum('AutodiffFosReverseIndex');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFovForwardIndicesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffFovForwardIndicesEnum()
+
+macro=StringToEnum('AutodiffFovForwardIndices');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerMaxSizeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffGcTriggerMaxSizeEnum()
+%AUTODIFFGCTRIGGERMAXSIZEENUM - Enum of AutodiffGcTriggerMaxSize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffGcTriggerMaxSizeEnum()
+
+macro=StringToEnum('AutodiffGcTriggerMaxSize');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerRatioEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerRatioEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffGcTriggerRatioEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffGcTriggerRatioEnum()
+%AUTODIFFGCTRIGGERRATIOENUM - Enum of AutodiffGcTriggerRatio
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffGcTriggerRatioEnum()
+
+macro=StringToEnum('AutodiffGcTriggerRatio');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectNamesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffIndependentObjectNamesEnum()
+
+macro=StringToEnum('AutodiffIndependentObjectNames');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectTypesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffIndependentObjectTypesEnum()
+
+macro=StringToEnum('AutodiffIndependentObjectTypes');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffIndependentObjectsEnum()
+
+macro=StringToEnum('AutodiffIndependentObjects');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIsautodiffEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIsautodiffEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffIsautodiffEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffIsautodiffEnum()
+%AUTODIFFISAUTODIFFENUM - Enum of AutodiffIsautodiff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffIsautodiffEnum()
+
+macro=StringToEnum('AutodiffIsautodiff');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffJacobianEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffJacobianEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffJacobianEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffJacobianEnum()
+%AUTODIFFJACOBIANENUM - Enum of AutodiffJacobian
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffJacobianEnum()
+
+macro=StringToEnum('AutodiffJacobian');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffKeepEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffKeepEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffKeepEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffKeepEnum()
+
+macro=StringToEnum('AutodiffKeep');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffLbufsizeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffLbufsizeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffLbufsizeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffLbufsizeEnum()
+%AUTODIFFLBUFSIZEENUM - Enum of AutodiffLbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffLbufsizeEnum()
+
+macro=StringToEnum('AutodiffLbufsize');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffMassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('AutodiffMassFluxSegmentsPresent');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentObjectsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffNumDependentObjectsEnum()
+
+macro=StringToEnum('AutodiffNumDependentObjects');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumDependentsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumDependentsEnum()
+%AUTODIFFNUMDEPENDENTSENUM - Enum of AutodiffNumDependents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffNumDependentsEnum()
+
+macro=StringToEnum('AutodiffNumDependents');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentObjectsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffNumIndependentObjectsEnum()
+
+macro=StringToEnum('AutodiffNumIndependentObjects');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumIndependentsEnum()
+%AUTODIFFNUMINDEPENDENTSENUM - Enum of AutodiffNumIndependents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffNumIndependentsEnum()
+
+macro=StringToEnum('AutodiffNumIndependents');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffObufsizeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffObufsizeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffObufsizeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffObufsizeEnum()
+%AUTODIFFOBUFSIZEENUM - Enum of AutodiffObufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffObufsizeEnum()
+
+macro=StringToEnum('AutodiffObufsize');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffTbufsizeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffTbufsizeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffTbufsizeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffTbufsizeEnum()
+%AUTODIFFTBUFSIZEENUM - Enum of AutodiffTbufsize
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffTbufsizeEnum()
+
+macro=StringToEnum('AutodiffTbufsize');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffXpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffXpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/AutodiffXpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=AutodiffXpEnum()
+%AUTODIFFXPENUM - Enum of AutodiffXp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AutodiffXpEnum()
+
+macro=StringToEnum('AutodiffXp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2AnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2AnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2AnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Balancethickness2AnalysisEnum()
+%BALANCETHICKNESS2ANALYSISENUM - Enum of Balancethickness2Analysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Balancethickness2AnalysisEnum()
+
+macro=StringToEnum('Balancethickness2Analysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2MisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2MisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2MisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Balancethickness2MisfitEnum()
+%BALANCETHICKNESS2MISFITENUM - Enum of Balancethickness2Misfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Balancethickness2MisfitEnum()
+
+macro=StringToEnum('Balancethickness2Misfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2SolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2SolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Balancethickness2SolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Balancethickness2SolutionEnum()
+%BALANCETHICKNESS2SOLUTIONENUM - Enum of Balancethickness2Solution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Balancethickness2SolutionEnum()
+
+macro=StringToEnum('Balancethickness2Solution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessAnalysisEnum()
+%BALANCETHICKNESSANALYSISENUM - Enum of BalancethicknessAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessAnalysisEnum()
+
+macro=StringToEnum('BalancethicknessAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessApparentMassbalanceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessApparentMassbalanceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessApparentMassbalanceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessApparentMassbalanceEnum()
+%BALANCETHICKNESSAPPARENTMASSBALANCEENUM - Enum of BalancethicknessApparentMassbalance
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessApparentMassbalanceEnum()
+
+macro=StringToEnum('BalancethicknessApparentMassbalance');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessMisfitEnum()
+%BALANCETHICKNESSMISFITENUM - Enum of BalancethicknessMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessMisfitEnum()
+
+macro=StringToEnum('BalancethicknessMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessNuxEnum()
+%BALANCETHICKNESSNUXENUM - Enum of BalancethicknessNux
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessNuxEnum()
+
+macro=StringToEnum('BalancethicknessNux');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessNuyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessNuyEnum()
+%BALANCETHICKNESSNUYENUM - Enum of BalancethicknessNuy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessNuyEnum()
+
+macro=StringToEnum('BalancethicknessNuy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessSoftAnalysisEnum()
+%BALANCETHICKNESSSOFTANALYSISENUM - Enum of BalancethicknessSoftAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSoftAnalysisEnum()
+
+macro=StringToEnum('BalancethicknessSoftAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSoftSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessSoftSolutionEnum()
+%BALANCETHICKNESSSOFTSOLUTIONENUM - Enum of BalancethicknessSoftSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSoftSolutionEnum()
+
+macro=StringToEnum('BalancethicknessSoftSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessSolutionEnum()
+%BALANCETHICKNESSSOLUTIONENUM - Enum of BalancethicknessSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSolutionEnum()
+
+macro=StringToEnum('BalancethicknessSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcpotentialEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcpotentialEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcpotentialEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessSpcpotentialEnum()
+%BALANCETHICKNESSSPCPOTENTIALENUM - Enum of BalancethicknessSpcpotential
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSpcpotentialEnum()
+
+macro=StringToEnum('BalancethicknessSpcpotential');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcthicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessSpcthicknessEnum()
+%BALANCETHICKNESSSPCTHICKNESSENUM - Enum of BalancethicknessSpcthickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSpcthicknessEnum()
+
+macro=StringToEnum('BalancethicknessSpcthickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessStabilizationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessStabilizationEnum()
+%BALANCETHICKNESSSTABILIZATIONENUM - Enum of BalancethicknessStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessStabilizationEnum()
+
+macro=StringToEnum('BalancethicknessStabilization');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThickeningRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessThickeningRateEnum()
+%BALANCETHICKNESSTHICKENINGRATEENUM - Enum of BalancethicknessThickeningRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessThickeningRateEnum()
+
+macro=StringToEnum('BalancethicknessThickeningRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThicknessObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThicknessObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessThicknessObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessThicknessObsEnum()
+%BALANCETHICKNESSTHICKNESSOBSENUM - Enum of BalancethicknessThicknessObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessThicknessObsEnum()
+
+macro=StringToEnum('BalancethicknessThicknessObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVxObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVxObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVxObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessVxObsEnum()
+%BALANCETHICKNESSVXOBSENUM - Enum of BalancethicknessVxObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessVxObsEnum()
+
+macro=StringToEnum('BalancethicknessVxObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVyObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVyObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancethicknessVyObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessVyObsEnum()
+%BALANCETHICKNESSVYOBSENUM - Enum of BalancethicknessVyObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessVyObsEnum()
+
+macro=StringToEnum('BalancethicknessVyObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocityAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocityAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocityAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancevelocityAnalysisEnum()
+%BALANCEVELOCITYANALYSISENUM - Enum of BalancevelocityAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancevelocityAnalysisEnum()
+
+macro=StringToEnum('BalancevelocityAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocitySolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocitySolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BalancevelocitySolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BalancevelocitySolutionEnum()
+%BALANCEVELOCITYSOLUTIONENUM - Enum of BalancevelocitySolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancevelocitySolutionEnum()
+
+macro=StringToEnum('BalancevelocitySolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalFrictionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalFrictionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalFrictionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalFrictionEnum()
+%BASALFRICTIONENUM - Enum of BasalFriction
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalFrictionEnum()
+
+macro=StringToEnum('BasalFriction');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterElevationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterElevationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterElevationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsDeepwaterElevationEnum()
+%BASALFORCINGSDEEPWATERELEVATIONENUM - Enum of BasalforcingsDeepwaterElevation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsDeepwaterElevationEnum()
+
+macro=StringToEnum('BasalforcingsDeepwaterElevation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsDeepwaterMeltingRateEnum()
+%BASALFORCINGSDEEPWATERMELTINGRATEENUM - Enum of BasalforcingsDeepwaterMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsDeepwaterMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsDeepwaterMeltingRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsEnum()
+%BASALFORCINGSENUM - Enum of Basalforcings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsEnum()
+
+macro=StringToEnum('Basalforcings');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsFloatingiceMeltingRateEnum()
+%BASALFORCINGSFLOATINGICEMELTINGRATEENUM - Enum of BasalforcingsFloatingiceMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsFloatingiceMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsFloatingiceMeltingRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGeothermalfluxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsGeothermalfluxEnum()
+%BASALFORCINGSGEOTHERMALFLUXENUM - Enum of BasalforcingsGeothermalflux
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsGeothermalfluxEnum()
+
+macro=StringToEnum('BasalforcingsGeothermalflux');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsGroundediceMeltingRateEnum()
+%BASALFORCINGSGROUNDEDICEMELTINGRATEENUM - Enum of BasalforcingsGroundediceMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsGroundediceMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsGroundediceMeltingRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsUpperwaterElevationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsUpperwaterElevationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BasalforcingsUpperwaterElevationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsUpperwaterElevationEnum()
+%BASALFORCINGSUPPERWATERELEVATIONENUM - Enum of BasalforcingsUpperwaterElevation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsUpperwaterElevationEnum()
+
+macro=StringToEnum('BasalforcingsUpperwaterElevation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BaseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BaseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BaseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BaseEnum()
+%BASEENUM - Enum of Base
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BaseEnum()
+
+macro=StringToEnum('Base');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BedEnum()
+%BEDENUM - Enum of Bed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BedEnum()
+
+macro=StringToEnum('Bed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BedSlopeSolutionEnum()
+%BEDSLOPESOLUTIONENUM - Enum of BedSlopeSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BedSlopeSolutionEnum()
+
+macro=StringToEnum('BedSlopeSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BedSlopeXEnum()
+%BEDSLOPEXENUM - Enum of BedSlopeX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BedSlopeXEnum()
+
+macro=StringToEnum('BedSlopeX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BedSlopeYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BedSlopeYEnum()
+%BEDSLOPEYENUM - Enum of BedSlopeY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BedSlopeYEnum()
+
+macro=StringToEnum('BedSlopeY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BilinearInterpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BilinearInterpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BilinearInterpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BilinearInterpEnum()
+%BILINEARINTERPENUM - Enum of BilinearInterp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BilinearInterpEnum()
+
+macro=StringToEnum('BilinearInterp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BoolExternalResultEnum()
+%BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BoolExternalResultEnum()
+
+macro=StringToEnum('BoolExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BoolInputEnum()
+%BOOLINPUTENUM - Enum of BoolInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BoolInputEnum()
+
+macro=StringToEnum('BoolInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoolParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BoolParamEnum()
+%BOOLPARAMENUM - Enum of BoolParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BoolParamEnum()
+
+macro=StringToEnum('BoolParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoundaryEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoundaryEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/BoundaryEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=BoundaryEnum()
+%BOUNDARYENUM - Enum of Boundary
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BoundaryEnum()
+
+macro=StringToEnum('Boundary');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ClosedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ClosedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ClosedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ClosedEnum()
+%CLOSEDENUM - Enum of Closed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ClosedEnum()
+
+macro=StringToEnum('Closed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ColinearEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ColinearEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ColinearEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ColinearEnum()
+%COLINEARENUM - Enum of Colinear
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ColinearEnum()
+
+macro=StringToEnum('Colinear');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConfigurationTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConfigurationTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConfigurationTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConfigurationTypeEnum()
+%CONFIGURATIONTYPEENUM - Enum of ConfigurationType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConfigurationTypeEnum()
+
+macro=StringToEnum('ConfigurationType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsGEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsGEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsGEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConstantsGEnum()
+%CONSTANTSGENUM - Enum of ConstantsG
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConstantsGEnum()
+
+macro=StringToEnum('ConstantsG');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsReferencetemperatureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConstantsReferencetemperatureEnum()
+%CONSTANTSREFERENCETEMPERATUREENUM - Enum of ConstantsReferencetemperature
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConstantsReferencetemperatureEnum()
+
+macro=StringToEnum('ConstantsReferencetemperature');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsYtsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsYtsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstantsYtsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConstantsYtsEnum()
+%CONSTANTSYTSENUM - Enum of ConstantsYts
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConstantsYtsEnum()
+
+macro=StringToEnum('ConstantsYts');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstraintsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstraintsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConstraintsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConstraintsEnum()
+%CONSTRAINTSENUM - Enum of Constraints
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConstraintsEnum()
+
+macro=StringToEnum('Constraints');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContactEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContactEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContactEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ContactEnum()
+%CONTACTENUM - Enum of Contact
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ContactEnum()
+
+macro=StringToEnum('Contact');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContourEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContourEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContourEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ContourEnum()
+%CONTOURENUM - Enum of Contour
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ContourEnum()
+
+macro=StringToEnum('Contour');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContoursEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContoursEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ContoursEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ContoursEnum()
+%CONTOURSENUM - Enum of Contours
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ContoursEnum()
+
+macro=StringToEnum('Contours');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ControlInputEnum()
+%CONTROLINPUTENUM - Enum of ControlInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ControlInputEnum()
+
+macro=StringToEnum('ControlInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlSteadyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlSteadyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ControlSteadyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ControlSteadyEnum()
+%CONTROLSTEADYENUM - Enum of ControlSteady
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ControlSteadyEnum()
+
+macro=StringToEnum('ControlSteady');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConvergedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConvergedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ConvergedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ConvergedEnum()
+%CONVERGEDENUM - Enum of Converged
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConvergedEnum()
+
+macro=StringToEnum('Converged');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CrouzeixRaviartEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CrouzeixRaviartEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CrouzeixRaviartEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=CrouzeixRaviartEnum()
+%CROUZEIXRAVIARTENUM - Enum of CrouzeixRaviart
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CrouzeixRaviartEnum()
+
+macro=StringToEnum('CrouzeixRaviart');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CuffeyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CuffeyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/CuffeyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=CuffeyEnum()
+%CUFFEYENUM - Enum of Cuffey
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CuffeyEnum()
+
+macro=StringToEnum('Cuffey');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC1Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC1Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC1Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageC1Enum()
+%DAMAGEC1ENUM - Enum of DamageC1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC1Enum()
+
+macro=StringToEnum('DamageC1');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageC2Enum()
+%DAMAGEC2ENUM - Enum of DamageC2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC2Enum()
+
+macro=StringToEnum('DamageC2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC3Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC3Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC3Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageC3Enum()
+%DAMAGEC3ENUM - Enum of DamageC3
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC3Enum()
+
+macro=StringToEnum('DamageC3');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC4Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC4Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageC4Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageC4Enum()
+%DAMAGEC4ENUM - Enum of DamageC4
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageC4Enum()
+
+macro=StringToEnum('DamageC4');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageDEnum()
+%DAMAGEDENUM - Enum of DamageD
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageDEnum()
+
+macro=StringToEnum('DamageD');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDbarEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDbarEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageDbarEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageDbarEnum()
+%DAMAGEDBARENUM - Enum of DamageDbar
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageDbarEnum()
+
+macro=StringToEnum('DamageDbar');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageElementinterpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageElementinterpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageElementinterpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageElementinterpEnum()
+%DAMAGEELEMENTINTERPENUM - Enum of DamageElementinterp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageElementinterpEnum()
+
+macro=StringToEnum('DamageElementinterp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEquivStressEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEquivStressEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEquivStressEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageEquivStressEnum()
+%DAMAGEEQUIVSTRESSENUM - Enum of DamageEquivStress
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEquivStressEnum()
+
+macro=StringToEnum('DamageEquivStress');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionAnalysisEnum()
+%DAMAGEEVOLUTIONANALYSISENUM - Enum of DamageEvolutionAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionAnalysisEnum()
+
+macro=StringToEnum('DamageEvolutionAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionNumRequestedOutputsEnum()
+%DAMAGEEVOLUTIONNUMREQUESTEDOUTPUTSENUM - Enum of DamageEvolutionNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionNumRequestedOutputsEnum()
+
+macro=StringToEnum('DamageEvolutionNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionRequestedOutputsEnum()
+%DAMAGEEVOLUTIONREQUESTEDOUTPUTSENUM - Enum of DamageEvolutionRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionRequestedOutputsEnum()
+
+macro=StringToEnum('DamageEvolutionRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageEvolutionSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageEvolutionSolutionEnum()
+%DAMAGEEVOLUTIONSOLUTIONENUM - Enum of DamageEvolutionSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEvolutionSolutionEnum()
+
+macro=StringToEnum('DamageEvolutionSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageFEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageFEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageFEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageFEnum()
+%DAMAGEFENUM - Enum of DamageF
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageFEnum()
+
+macro=StringToEnum('DamageF');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageHealingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageHealingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageHealingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageHealingEnum()
+%DAMAGEHEALINGENUM - Enum of DamageHealing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageHealingEnum()
+
+macro=StringToEnum('DamageHealing');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageIsdamageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageIsdamageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageIsdamageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageIsdamageEnum()
+%DAMAGEISDAMAGEENUM - Enum of DamageIsdamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageIsdamageEnum()
+
+macro=StringToEnum('DamageIsdamage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageLawEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageLawEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageLawEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageLawEnum()
+%DAMAGELAWENUM - Enum of DamageLaw
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageLawEnum()
+
+macro=StringToEnum('DamageLaw');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxDamageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxDamageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxDamageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageMaxDamageEnum()
+%DAMAGEMAXDAMAGEENUM - Enum of DamageMaxDamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageMaxDamageEnum()
+
+macro=StringToEnum('DamageMaxDamage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxiterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxiterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageMaxiterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageMaxiterEnum()
+%DAMAGEMAXITERENUM - Enum of DamageMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageMaxiterEnum()
+
+macro=StringToEnum('DamageMaxiter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyFactorEnum()
+%DAMAGEPENALTYFACTORENUM - Enum of DamagePenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyFactorEnum()
+
+macro=StringToEnum('DamagePenaltyFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyLockEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyLockEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyLockEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyLockEnum()
+%DAMAGEPENALTYLOCKENUM - Enum of DamagePenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyLockEnum()
+
+macro=StringToEnum('DamagePenaltyLock');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamagePenaltyThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamagePenaltyThresholdEnum()
+%DAMAGEPENALTYTHRESHOLDENUM - Enum of DamagePenaltyThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamagePenaltyThresholdEnum()
+
+macro=StringToEnum('DamagePenaltyThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageSpcdamageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageSpcdamageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageSpcdamageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageSpcdamageEnum()
+%DAMAGESPCDAMAGEENUM - Enum of DamageSpcdamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageSpcdamageEnum()
+
+macro=StringToEnum('DamageSpcdamage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStabilizationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStabilizationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStabilizationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageStabilizationEnum()
+%DAMAGESTABILIZATIONENUM - Enum of DamageStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageStabilizationEnum()
+
+macro=StringToEnum('DamageStabilization');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStressThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStressThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DamageStressThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DamageStressThresholdEnum()
+%DAMAGESTRESSTHRESHOLDENUM - Enum of DamageStressThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageStressThresholdEnum()
+
+macro=StringToEnum('DamageStressThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DataSetParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DataSetParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DataSetParamEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DataSetParamEnum()
+
+macro=StringToEnum('DataSetParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DatasetInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DatasetInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DatasetInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DatasetInputEnum()
+%DATASETINPUTENUM - Enum of DatasetInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DatasetInputEnum()
+
+macro=StringToEnum('DatasetInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DebugProfilingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DebugProfilingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DebugProfilingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DebugProfilingEnum()
+%DEBUGPROFILINGENUM - Enum of DebugProfiling
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DebugProfilingEnum()
+
+macro=StringToEnum('DebugProfiling');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DefaultAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DefaultAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DefaultAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DefaultAnalysisEnum()
+%DEFAULTANALYSISENUM - Enum of DefaultAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DefaultAnalysisEnum()
+
+macro=StringToEnum('DefaultAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DenseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DenseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DenseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DenseEnum()
+%DENSEENUM - Enum of Dense
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DenseEnum()
+
+macro=StringToEnum('Dense');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DependentObjectEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DependentObjectEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DependentObjectEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DependentObjectEnum()
+
+macro=StringToEnum('DependentObject');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DepthAverageAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DepthAverageAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DepthAverageAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DepthAverageAnalysisEnum()
+%DEPTHAVERAGEANALYSISENUM - Enum of DepthAverageAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DepthAverageAnalysisEnum()
+
+macro=StringToEnum('DepthAverageAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressEnum()
+%DEVIATORICSTRESSENUM - Enum of DeviatoricStress
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressEnum()
+
+macro=StringToEnum('DeviatoricStress');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressxxEnum()
+%DEVIATORICSTRESSXXENUM - Enum of DeviatoricStressxx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressxxEnum()
+
+macro=StringToEnum('DeviatoricStressxx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressxyEnum()
+%DEVIATORICSTRESSXYENUM - Enum of DeviatoricStressxy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressxyEnum()
+
+macro=StringToEnum('DeviatoricStressxy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressxzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressxzEnum()
+%DEVIATORICSTRESSXZENUM - Enum of DeviatoricStressxz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressxzEnum()
+
+macro=StringToEnum('DeviatoricStressxz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressyyEnum()
+%DEVIATORICSTRESSYYENUM - Enum of DeviatoricStressyy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressyyEnum()
+
+macro=StringToEnum('DeviatoricStressyy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStressyzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStressyzEnum()
+%DEVIATORICSTRESSYZENUM - Enum of DeviatoricStressyz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStressyzEnum()
+
+macro=StringToEnum('DeviatoricStressyz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStresszzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStresszzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DeviatoricStresszzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DeviatoricStresszzEnum()
+%DEVIATORICSTRESSZZENUM - Enum of DeviatoricStresszz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DeviatoricStresszzEnum()
+
+macro=StringToEnum('DeviatoricStresszz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DivergenceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DivergenceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DivergenceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DivergenceEnum()
+%DIVERGENCEENUM - Enum of Divergence
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DivergenceEnum()
+
+macro=StringToEnum('Divergence');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DhorizontalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DhorizontalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DhorizontalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Domain2DhorizontalEnum()
+%DOMAIN2DHORIZONTALENUM - Enum of Domain2Dhorizontal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Domain2DhorizontalEnum()
+
+macro=StringToEnum('Domain2Dhorizontal');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DverticalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DverticalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain2DverticalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Domain2DverticalEnum()
+%DOMAIN2DVERTICALENUM - Enum of Domain2Dvertical
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Domain2DverticalEnum()
+
+macro=StringToEnum('Domain2Dvertical');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain3DEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain3DEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Domain3DEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Domain3DEnum()
+%DOMAIN3DENUM - Enum of Domain3D
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Domain3DEnum()
+
+macro=StringToEnum('Domain3D');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainDimensionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainDimensionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainDimensionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DomainDimensionEnum()
+%DOMAINDIMENSIONENUM - Enum of DomainDimension
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DomainDimensionEnum()
+
+macro=StringToEnum('DomainDimension');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DomainTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DomainTypeEnum()
+%DOMAINTYPEENUM - Enum of DomainType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DomainTypeEnum()
+
+macro=StringToEnum('DomainType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleExternalResultEnum()
+%DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleExternalResultEnum()
+
+macro=StringToEnum('DoubleExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleInputEnum()
+%DOUBLEINPUTENUM - Enum of DoubleInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleInputEnum()
+
+macro=StringToEnum('DoubleInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatArrayParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatArrayParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatArrayParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleMatArrayParamEnum()
+%DOUBLEMATARRAYPARAMENUM - Enum of DoubleMatArrayParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleMatArrayParamEnum()
+
+macro=StringToEnum('DoubleMatArrayParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleMatExternalResultEnum()
+%DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleMatExternalResultEnum()
+
+macro=StringToEnum('DoubleMatExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleMatParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleMatParamEnum()
+%DOUBLEMATPARAMENUM - Enum of DoubleMatParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleMatParamEnum()
+
+macro=StringToEnum('DoubleMatParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleParamEnum()
+%DOUBLEPARAMENUM - Enum of DoubleParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleParamEnum()
+
+macro=StringToEnum('DoubleParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleVecParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleVecParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DoubleVecParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DoubleVecParamEnum()
+%DOUBLEVECPARAMENUM - Enum of DoubleVecParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DoubleVecParamEnum()
+
+macro=StringToEnum('DoubleVecParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DragCoefficientAbsGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=DragCoefficientAbsGradientEnum()
+%DRAGCOEFFICIENTABSGRADIENTENUM - Enum of DragCoefficientAbsGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DragCoefficientAbsGradientEnum()
+
+macro=StringToEnum('DragCoefficientAbsGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EffectivePressureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EffectivePressureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EffectivePressureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EffectivePressureEnum()
+%EFFECTIVEPRESSUREENUM - Enum of EffectivePressure
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EffectivePressureEnum()
+
+macro=StringToEnum('EffectivePressure');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ElementEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ElementEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ElementEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ElementEnum()
+%ELEMENTENUM - Enum of Element
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ElementEnum()
+
+macro=StringToEnum('Element');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EnthalpyAnalysisEnum()
+%ENTHALPYANALYSISENUM - Enum of EnthalpyAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EnthalpyAnalysisEnum()
+
+macro=StringToEnum('EnthalpyAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EnthalpyEnum()
+%ENTHALPYENUM - Enum of Enthalpy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EnthalpyEnum()
+
+macro=StringToEnum('Enthalpy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyPicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyPicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnthalpyPicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EnthalpyPicardEnum()
+%ENTHALPYPICARDENUM - Enum of EnthalpyPicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EnthalpyPicardEnum()
+
+macro=StringToEnum('EnthalpyPicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnumDefinitions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EnumDefinitions.py	(revision 18231)
@@ -0,0 +1,712 @@
+from StringToEnum import StringToEnum
+
+"""
+
+WARNING: DO NOT MODIFY THIS FILE
+this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+Please read src/c/shared/Enum/README for more information
+
+"""
+
+def AutodiffIsautodiffEnum(): return StringToEnum("AutodiffIsautodiff")[0]
+def AutodiffNumDependentsEnum(): return StringToEnum("AutodiffNumDependents")[0]
+def AutodiffNumDependentObjectsEnum(): return StringToEnum("AutodiffNumDependentObjects")[0]
+def AutodiffDependentObjectNamesEnum(): return StringToEnum("AutodiffDependentObjectNames")[0]
+def AutodiffDependentObjectTypesEnum(): return StringToEnum("AutodiffDependentObjectTypes")[0]
+def AutodiffDependentObjectIndicesEnum(): return StringToEnum("AutodiffDependentObjectIndices")[0]
+def AutodiffDependentObjectsEnum(): return StringToEnum("AutodiffDependentObjects")[0]
+def AutodiffNumIndependentsEnum(): return StringToEnum("AutodiffNumIndependents")[0]
+def AutodiffNumIndependentObjectsEnum(): return StringToEnum("AutodiffNumIndependentObjects")[0]
+def AutodiffIndependentObjectNamesEnum(): return StringToEnum("AutodiffIndependentObjectNames")[0]
+def AutodiffIndependentObjectTypesEnum(): return StringToEnum("AutodiffIndependentObjectTypes")[0]
+def AutodiffIndependentObjectsEnum(): return StringToEnum("AutodiffIndependentObjects")[0]
+def AutodiffJacobianEnum(): return StringToEnum("AutodiffJacobian")[0]
+def AutodiffXpEnum(): return StringToEnum("AutodiffXp")[0]
+def AutodiffDriverEnum(): return StringToEnum("AutodiffDriver")[0]
+def AutodiffFosForwardIndexEnum(): return StringToEnum("AutodiffFosForwardIndex")[0]
+def AutodiffFovForwardIndicesEnum(): return StringToEnum("AutodiffFovForwardIndices")[0]
+def AutodiffFosReverseIndexEnum(): return StringToEnum("AutodiffFosReverseIndex")[0]
+def AutodiffMassFluxSegmentsPresentEnum(): return StringToEnum("AutodiffMassFluxSegmentsPresent")[0]
+def AutodiffKeepEnum(): return StringToEnum("AutodiffKeep")[0]
+def AutodiffObufsizeEnum(): return StringToEnum("AutodiffObufsize")[0]
+def AutodiffLbufsizeEnum(): return StringToEnum("AutodiffLbufsize")[0]
+def AutodiffCbufsizeEnum(): return StringToEnum("AutodiffCbufsize")[0]
+def AutodiffTbufsizeEnum(): return StringToEnum("AutodiffTbufsize")[0]
+def AutodiffGcTriggerRatioEnum(): return StringToEnum("AutodiffGcTriggerRatio")[0]
+def AutodiffGcTriggerMaxSizeEnum(): return StringToEnum("AutodiffGcTriggerMaxSize")[0]
+def BalancethicknessSpcthicknessEnum(): return StringToEnum("BalancethicknessSpcthickness")[0]
+def BalancethicknessStabilizationEnum(): return StringToEnum("BalancethicknessStabilization")[0]
+def BalancethicknessThickeningRateEnum(): return StringToEnum("BalancethicknessThickeningRate")[0]
+def BasalforcingsEnum(): return StringToEnum("Basalforcings")[0]
+def BasalforcingsGeothermalfluxEnum(): return StringToEnum("BasalforcingsGeothermalflux")[0]
+def BasalforcingsGroundediceMeltingRateEnum(): return StringToEnum("BasalforcingsGroundediceMeltingRate")[0]
+def BasalforcingsFloatingiceMeltingRateEnum(): return StringToEnum("BasalforcingsFloatingiceMeltingRate")[0]
+def BasalforcingsDeepwaterMeltingRateEnum(): return StringToEnum("BasalforcingsDeepwaterMeltingRate")[0]
+def BasalforcingsDeepwaterElevationEnum(): return StringToEnum("BasalforcingsDeepwaterElevation")[0]
+def BasalforcingsUpperwaterElevationEnum(): return StringToEnum("BasalforcingsUpperwaterElevation")[0]
+def FloatingMeltRateEnum(): return StringToEnum("FloatingMeltRate")[0]
+def LinearFloatingMeltRateEnum(): return StringToEnum("LinearFloatingMeltRate")[0]
+def BedEnum(): return StringToEnum("Bed")[0]
+def BaseEnum(): return StringToEnum("Base")[0]
+def ConstantsGEnum(): return StringToEnum("ConstantsG")[0]
+def ConstantsReferencetemperatureEnum(): return StringToEnum("ConstantsReferencetemperature")[0]
+def ConstantsYtsEnum(): return StringToEnum("ConstantsYts")[0]
+def DependentObjectEnum(): return StringToEnum("DependentObject")[0]
+def StressbalanceAbstolEnum(): return StringToEnum("StressbalanceAbstol")[0]
+def StressbalanceIsnewtonEnum(): return StringToEnum("StressbalanceIsnewton")[0]
+def StressbalanceMaxiterEnum(): return StringToEnum("StressbalanceMaxiter")[0]
+def StressbalancePenaltyFactorEnum(): return StringToEnum("StressbalancePenaltyFactor")[0]
+def StressbalanceReferentialEnum(): return StringToEnum("StressbalanceReferential")[0]
+def StressbalanceReltolEnum(): return StringToEnum("StressbalanceReltol")[0]
+def StressbalanceNumRequestedOutputsEnum(): return StringToEnum("StressbalanceNumRequestedOutputs")[0]
+def StressbalanceRequestedOutputsEnum(): return StringToEnum("StressbalanceRequestedOutputs")[0]
+def StressbalanceRestolEnum(): return StringToEnum("StressbalanceRestol")[0]
+def StressbalanceRiftPenaltyLockEnum(): return StringToEnum("StressbalanceRiftPenaltyLock")[0]
+def StressbalanceRiftPenaltyThresholdEnum(): return StringToEnum("StressbalanceRiftPenaltyThreshold")[0]
+def StressbalanceShelfDampeningEnum(): return StringToEnum("StressbalanceShelfDampening")[0]
+def StressbalanceSpcvxEnum(): return StringToEnum("StressbalanceSpcvx")[0]
+def StressbalanceSpcvyEnum(): return StringToEnum("StressbalanceSpcvy")[0]
+def StressbalanceSpcvzEnum(): return StringToEnum("StressbalanceSpcvz")[0]
+def StressbalanceFSreconditioningEnum(): return StringToEnum("StressbalanceFSreconditioning")[0]
+def StressbalanceVertexPairingEnum(): return StringToEnum("StressbalanceVertexPairing")[0]
+def StressbalanceViscosityOvershootEnum(): return StringToEnum("StressbalanceViscosityOvershoot")[0]
+def LoadingforceXEnum(): return StringToEnum("LoadingforceX")[0]
+def LoadingforceYEnum(): return StringToEnum("LoadingforceY")[0]
+def LoadingforceZEnum(): return StringToEnum("LoadingforceZ")[0]
+def FlowequationBorderSSAEnum(): return StringToEnum("FlowequationBorderSSA")[0]
+def FlowequationBorderHOEnum(): return StringToEnum("FlowequationBorderHO")[0]
+def FlowequationBorderFSEnum(): return StringToEnum("FlowequationBorderFS")[0]
+def FlowequationElementEquationEnum(): return StringToEnum("FlowequationElementEquation")[0]
+def FlowequationIsSIAEnum(): return StringToEnum("FlowequationIsSIA")[0]
+def FlowequationIsSSAEnum(): return StringToEnum("FlowequationIsSSA")[0]
+def FlowequationIsL1L2Enum(): return StringToEnum("FlowequationIsL1L2")[0]
+def FlowequationIsHOEnum(): return StringToEnum("FlowequationIsHO")[0]
+def FlowequationIsFSEnum(): return StringToEnum("FlowequationIsFS")[0]
+def FlowequationFeSSAEnum(): return StringToEnum("FlowequationFeSSA")[0]
+def FlowequationFeHOEnum(): return StringToEnum("FlowequationFeHO")[0]
+def FlowequationFeFSEnum(): return StringToEnum("FlowequationFeFS")[0]
+def FlowequationVertexEquationEnum(): return StringToEnum("FlowequationVertexEquation")[0]
+def FrictionCoefficientEnum(): return StringToEnum("FrictionCoefficient")[0]
+def FrictionPEnum(): return StringToEnum("FrictionP")[0]
+def FrictionQEnum(): return StringToEnum("FrictionQ")[0]
+def FrictionMEnum(): return StringToEnum("FrictionM")[0]
+def FrictionCEnum(): return StringToEnum("FrictionC")[0]
+def FrictionLawEnum(): return StringToEnum("FrictionLaw")[0]
+def GeometryHydrostaticRatioEnum(): return StringToEnum("GeometryHydrostaticRatio")[0]
+def HydrologyModelEnum(): return StringToEnum("HydrologyModel")[0]
+def HydrologyshreveEnum(): return StringToEnum("Hydrologyshreve")[0]
+def HydrologyshreveSpcwatercolumnEnum(): return StringToEnum("HydrologyshreveSpcwatercolumn")[0]
+def HydrologyshreveStabilizationEnum(): return StringToEnum("HydrologyshreveStabilization")[0]
+def HydrologydcEnum(): return StringToEnum("Hydrologydc")[0]
+def SedimentHeadEnum(): return StringToEnum("SedimentHead")[0]
+def SedimentHeadOldEnum(): return StringToEnum("SedimentHeadOld")[0]
+def SedimentHeadResidualEnum(): return StringToEnum("SedimentHeadResidual")[0]
+def EffectivePressureEnum(): return StringToEnum("EffectivePressure")[0]
+def EplHeadEnum(): return StringToEnum("EplHead")[0]
+def EplHeadOldEnum(): return StringToEnum("EplHeadOld")[0]
+def EplHeadSlopeXEnum(): return StringToEnum("EplHeadSlopeX")[0]
+def EplHeadSlopeYEnum(): return StringToEnum("EplHeadSlopeY")[0]
+def HydrologydcMaxIterEnum(): return StringToEnum("HydrologydcMaxIter")[0]
+def HydrologydcRelTolEnum(): return StringToEnum("HydrologydcRelTol")[0]
+def HydrologydcSpcsedimentHeadEnum(): return StringToEnum("HydrologydcSpcsedimentHead")[0]
+def HydrologydcSedimentCompressibilityEnum(): return StringToEnum("HydrologydcSedimentCompressibility")[0]
+def HydrologydcSedimentPorosityEnum(): return StringToEnum("HydrologydcSedimentPorosity")[0]
+def HydrologydcSedimentThicknessEnum(): return StringToEnum("HydrologydcSedimentThickness")[0]
+def HydrologydcSedimentTransmitivityEnum(): return StringToEnum("HydrologydcSedimentTransmitivity")[0]
+def HydrologydcWaterCompressibilityEnum(): return StringToEnum("HydrologydcWaterCompressibility")[0]
+def HydrologydcSpceplHeadEnum(): return StringToEnum("HydrologydcSpceplHead")[0]
+def HydrologydcMaskEplactiveNodeEnum(): return StringToEnum("HydrologydcMaskEplactiveNode")[0]
+def HydrologydcMaskEplactiveEltEnum(): return StringToEnum("HydrologydcMaskEplactiveElt")[0]
+def HydrologydcEplCompressibilityEnum(): return StringToEnum("HydrologydcEplCompressibility")[0]
+def HydrologydcEplPorosityEnum(): return StringToEnum("HydrologydcEplPorosity")[0]
+def HydrologydcEplInitialThicknessEnum(): return StringToEnum("HydrologydcEplInitialThickness")[0]
+def HydrologydcEplMaxThicknessEnum(): return StringToEnum("HydrologydcEplMaxThickness")[0]
+def HydrologydcEplThicknessEnum(): return StringToEnum("HydrologydcEplThickness")[0]
+def HydrologydcEplThicknessOldEnum(): return StringToEnum("HydrologydcEplThicknessOld")[0]
+def HydrologydcEplConductivityEnum(): return StringToEnum("HydrologydcEplConductivity")[0]
+def HydrologydcIsefficientlayerEnum(): return StringToEnum("HydrologydcIsefficientlayer")[0]
+def HydrologydcSedimentlimitFlagEnum(): return StringToEnum("HydrologydcSedimentlimitFlag")[0]
+def HydrologydcSedimentlimitEnum(): return StringToEnum("HydrologydcSedimentlimit")[0]
+def HydrologydcTransferFlagEnum(): return StringToEnum("HydrologydcTransferFlag")[0]
+def HydrologydcLeakageFactorEnum(): return StringToEnum("HydrologydcLeakageFactor")[0]
+def HydrologydcPenaltyFactorEnum(): return StringToEnum("HydrologydcPenaltyFactor")[0]
+def HydrologydcPenaltyLockEnum(): return StringToEnum("HydrologydcPenaltyLock")[0]
+def HydrologydcBasalMoulinInputEnum(): return StringToEnum("HydrologydcBasalMoulinInput")[0]
+def HydrologyLayerEnum(): return StringToEnum("HydrologyLayer")[0]
+def HydrologySedimentEnum(): return StringToEnum("HydrologySediment")[0]
+def HydrologyEfficientEnum(): return StringToEnum("HydrologyEfficient")[0]
+def HydrologySedimentKmaxEnum(): return StringToEnum("HydrologySedimentKmax")[0]
+def IndependentObjectEnum(): return StringToEnum("IndependentObject")[0]
+def InversionControlParametersEnum(): return StringToEnum("InversionControlParameters")[0]
+def InversionCostFunctionThresholdEnum(): return StringToEnum("InversionCostFunctionThreshold")[0]
+def InversionCostFunctionsCoefficientsEnum(): return StringToEnum("InversionCostFunctionsCoefficients")[0]
+def InversionCostFunctionsEnum(): return StringToEnum("InversionCostFunctions")[0]
+def InversionGradientScalingEnum(): return StringToEnum("InversionGradientScaling")[0]
+def InversionIscontrolEnum(): return StringToEnum("InversionIscontrol")[0]
+def InversionTypeEnum(): return StringToEnum("InversionType")[0]
+def InversionIncompleteAdjointEnum(): return StringToEnum("InversionIncompleteAdjoint")[0]
+def InversionMaxParametersEnum(): return StringToEnum("InversionMaxParameters")[0]
+def InversionMaxiterPerStepEnum(): return StringToEnum("InversionMaxiterPerStep")[0]
+def InversionMaxiterEnum(): return StringToEnum("InversionMaxiter")[0]
+def InversionMaxstepsEnum(): return StringToEnum("InversionMaxsteps")[0]
+def InversionFatolEnum(): return StringToEnum("InversionFatol")[0]
+def InversionFrtolEnum(): return StringToEnum("InversionFrtol")[0]
+def InversionGatolEnum(): return StringToEnum("InversionGatol")[0]
+def InversionGrtolEnum(): return StringToEnum("InversionGrtol")[0]
+def InversionGttolEnum(): return StringToEnum("InversionGttol")[0]
+def InversionAlgorithmEnum(): return StringToEnum("InversionAlgorithm")[0]
+def InversionMinParametersEnum(): return StringToEnum("InversionMinParameters")[0]
+def InversionNstepsEnum(): return StringToEnum("InversionNsteps")[0]
+def InversionDxminEnum(): return StringToEnum("InversionDxmin")[0]
+def InversionNumControlParametersEnum(): return StringToEnum("InversionNumControlParameters")[0]
+def InversionNumCostFunctionsEnum(): return StringToEnum("InversionNumCostFunctions")[0]
+def InversionStepThresholdEnum(): return StringToEnum("InversionStepThreshold")[0]
+def InversionThicknessObsEnum(): return StringToEnum("InversionThicknessObs")[0]
+def InversionVxObsEnum(): return StringToEnum("InversionVxObs")[0]
+def InversionVyObsEnum(): return StringToEnum("InversionVyObs")[0]
+def InversionVzObsEnum(): return StringToEnum("InversionVzObs")[0]
+def MaskIceLevelsetEnum(): return StringToEnum("MaskIceLevelset")[0]
+def QmuMaskIceLevelsetEnum(): return StringToEnum("QmuMaskIceLevelset")[0]
+def MaterialsBetaEnum(): return StringToEnum("MaterialsBeta")[0]
+def MaterialsHeatcapacityEnum(): return StringToEnum("MaterialsHeatcapacity")[0]
+def MaterialsLatentheatEnum(): return StringToEnum("MaterialsLatentheat")[0]
+def MaterialsMeltingpointEnum(): return StringToEnum("MaterialsMeltingpoint")[0]
+def MaterialsMixedLayerCapacityEnum(): return StringToEnum("MaterialsMixedLayerCapacity")[0]
+def MaterialsRheologyBEnum(): return StringToEnum("MaterialsRheologyB")[0]
+def MaterialsRheologyBbarEnum(): return StringToEnum("MaterialsRheologyBbar")[0]
+def MaterialsRheologyLawEnum(): return StringToEnum("MaterialsRheologyLaw")[0]
+def MaterialsRheologyNEnum(): return StringToEnum("MaterialsRheologyN")[0]
+def DamageIsdamageEnum(): return StringToEnum("DamageIsdamage")[0]
+def DamageDEnum(): return StringToEnum("DamageD")[0]
+def DamageFEnum(): return StringToEnum("DamageF")[0]
+def QmuDamageDEnum(): return StringToEnum("QmuDamageD")[0]
+def DamageDbarEnum(): return StringToEnum("DamageDbar")[0]
+def DamageLawEnum(): return StringToEnum("DamageLaw")[0]
+def DamageC1Enum(): return StringToEnum("DamageC1")[0]
+def DamageC2Enum(): return StringToEnum("DamageC2")[0]
+def DamageC3Enum(): return StringToEnum("DamageC3")[0]
+def DamageC4Enum(): return StringToEnum("DamageC4")[0]
+def DamageElementinterpEnum(): return StringToEnum("DamageElementinterp")[0]
+def DamageHealingEnum(): return StringToEnum("DamageHealing")[0]
+def DamageStressThresholdEnum(): return StringToEnum("DamageStressThreshold")[0]
+def DamageStabilizationEnum(): return StringToEnum("DamageStabilization")[0]
+def DamagePenaltyThresholdEnum(): return StringToEnum("DamagePenaltyThreshold")[0]
+def DamagePenaltyLockEnum(): return StringToEnum("DamagePenaltyLock")[0]
+def DamagePenaltyFactorEnum(): return StringToEnum("DamagePenaltyFactor")[0]
+def DamageMaxiterEnum(): return StringToEnum("DamageMaxiter")[0]
+def DamageSpcdamageEnum(): return StringToEnum("DamageSpcdamage")[0]
+def DamageMaxDamageEnum(): return StringToEnum("DamageMaxDamage")[0]
+def DamageEquivStressEnum(): return StringToEnum("DamageEquivStress")[0]
+def DamageEvolutionNumRequestedOutputsEnum(): return StringToEnum("DamageEvolutionNumRequestedOutputs")[0]
+def DamageEvolutionRequestedOutputsEnum(): return StringToEnum("DamageEvolutionRequestedOutputs")[0]
+def NewDamageEnum(): return StringToEnum("NewDamage")[0]
+def MaterialsRhoIceEnum(): return StringToEnum("MaterialsRhoIce")[0]
+def MaterialsRhoSeawaterEnum(): return StringToEnum("MaterialsRhoSeawater")[0]
+def MaterialsRhoFreshwaterEnum(): return StringToEnum("MaterialsRhoFreshwater")[0]
+def MaterialsMuWaterEnum(): return StringToEnum("MaterialsMuWater")[0]
+def MaterialsThermalExchangeVelocityEnum(): return StringToEnum("MaterialsThermalExchangeVelocity")[0]
+def MaterialsThermalconductivityEnum(): return StringToEnum("MaterialsThermalconductivity")[0]
+def MaterialsTemperateiceconductivityEnum(): return StringToEnum("MaterialsTemperateiceconductivity")[0]
+def MaterialsLithosphereShearModulusEnum(): return StringToEnum("MaterialsLithosphereShearModulus")[0]
+def MaterialsLithosphereDensityEnum(): return StringToEnum("MaterialsLithosphereDensity")[0]
+def MaterialsMantleShearModulusEnum(): return StringToEnum("MaterialsMantleShearModulus")[0]
+def MaterialsMantleDensityEnum(): return StringToEnum("MaterialsMantleDensity")[0]
+def MeshAverageVertexConnectivityEnum(): return StringToEnum("MeshAverageVertexConnectivity")[0]
+def MeshElements2dEnum(): return StringToEnum("MeshElements2d")[0]
+def MeshElementsEnum(): return StringToEnum("MeshElements")[0]
+def MeshLowerelementsEnum(): return StringToEnum("MeshLowerelements")[0]
+def MeshNumberofelements2dEnum(): return StringToEnum("MeshNumberofelements2d")[0]
+def MeshNumberofelementsEnum(): return StringToEnum("MeshNumberofelements")[0]
+def MeshNumberoflayersEnum(): return StringToEnum("MeshNumberoflayers")[0]
+def MeshNumberofvertices2dEnum(): return StringToEnum("MeshNumberofvertices2d")[0]
+def MeshNumberofverticesEnum(): return StringToEnum("MeshNumberofvertices")[0]
+def MeshUpperelementsEnum(): return StringToEnum("MeshUpperelements")[0]
+def MeshVertexonbaseEnum(): return StringToEnum("MeshVertexonbase")[0]
+def MeshVertexonsurfaceEnum(): return StringToEnum("MeshVertexonsurface")[0]
+def MeshVertexonboundaryEnum(): return StringToEnum("MeshVertexonboundary")[0]
+def MeshXEnum(): return StringToEnum("MeshX")[0]
+def MeshYEnum(): return StringToEnum("MeshY")[0]
+def MeshZEnum(): return StringToEnum("MeshZ")[0]
+def MeshElementtypeEnum(): return StringToEnum("MeshElementtype")[0]
+def DomainTypeEnum(): return StringToEnum("DomainType")[0]
+def DomainDimensionEnum(): return StringToEnum("DomainDimension")[0]
+def Domain2DhorizontalEnum(): return StringToEnum("Domain2Dhorizontal")[0]
+def Domain2DverticalEnum(): return StringToEnum("Domain2Dvertical")[0]
+def Domain3DEnum(): return StringToEnum("Domain3D")[0]
+def MiscellaneousNameEnum(): return StringToEnum("MiscellaneousName")[0]
+def MasstransportHydrostaticAdjustmentEnum(): return StringToEnum("MasstransportHydrostaticAdjustment")[0]
+def MasstransportIsfreesurfaceEnum(): return StringToEnum("MasstransportIsfreesurface")[0]
+def MasstransportMinThicknessEnum(): return StringToEnum("MasstransportMinThickness")[0]
+def MasstransportPenaltyFactorEnum(): return StringToEnum("MasstransportPenaltyFactor")[0]
+def MasstransportSpcthicknessEnum(): return StringToEnum("MasstransportSpcthickness")[0]
+def MasstransportCalvingrateEnum(): return StringToEnum("MasstransportCalvingrate")[0]
+def MasstransportStabilizationEnum(): return StringToEnum("MasstransportStabilization")[0]
+def MasstransportVertexPairingEnum(): return StringToEnum("MasstransportVertexPairing")[0]
+def MasstransportNumRequestedOutputsEnum(): return StringToEnum("MasstransportNumRequestedOutputs")[0]
+def MasstransportRequestedOutputsEnum(): return StringToEnum("MasstransportRequestedOutputs")[0]
+def QmuIsdakotaEnum(): return StringToEnum("QmuIsdakota")[0]
+def MassFluxSegmentsEnum(): return StringToEnum("MassFluxSegments")[0]
+def MassFluxSegmentsPresentEnum(): return StringToEnum("MassFluxSegmentsPresent")[0]
+def QmuMassFluxSegmentsPresentEnum(): return StringToEnum("QmuMassFluxSegmentsPresent")[0]
+def QmuNumberofpartitionsEnum(): return StringToEnum("QmuNumberofpartitions")[0]
+def QmuNumberofresponsesEnum(): return StringToEnum("QmuNumberofresponses")[0]
+def QmuPartitionEnum(): return StringToEnum("QmuPartition")[0]
+def QmuResponsedescriptorsEnum(): return StringToEnum("QmuResponsedescriptors")[0]
+def QmuVariabledescriptorsEnum(): return StringToEnum("QmuVariabledescriptors")[0]
+def QmuMaterialsRheologyBEnum(): return StringToEnum("QmuMaterialsRheologyB")[0]
+def RiftsNumriftsEnum(): return StringToEnum("RiftsNumrifts")[0]
+def RiftsRiftstructEnum(): return StringToEnum("RiftsRiftstruct")[0]
+def SettingsResultsOnNodesEnum(): return StringToEnum("SettingsResultsOnNodes")[0]
+def SettingsIoGatherEnum(): return StringToEnum("SettingsIoGather")[0]
+def SettingsLowmemEnum(): return StringToEnum("SettingsLowmem")[0]
+def SettingsOutputFrequencyEnum(): return StringToEnum("SettingsOutputFrequency")[0]
+def SettingsWaitonlockEnum(): return StringToEnum("SettingsWaitonlock")[0]
+def DebugProfilingEnum(): return StringToEnum("DebugProfiling")[0]
+def ProfilingCurrentMemEnum(): return StringToEnum("ProfilingCurrentMem")[0]
+def ProfilingCurrentFlopsEnum(): return StringToEnum("ProfilingCurrentFlops")[0]
+def ProfilingSolutionTimeEnum(): return StringToEnum("ProfilingSolutionTime")[0]
+def MaxIterationConvergenceFlagEnum(): return StringToEnum("MaxIterationConvergenceFlag")[0]
+def SteadystateMaxiterEnum(): return StringToEnum("SteadystateMaxiter")[0]
+def SteadystateNumRequestedOutputsEnum(): return StringToEnum("SteadystateNumRequestedOutputs")[0]
+def SteadystateReltolEnum(): return StringToEnum("SteadystateReltol")[0]
+def SteadystateRequestedOutputsEnum(): return StringToEnum("SteadystateRequestedOutputs")[0]
+def SurfaceEnum(): return StringToEnum("Surface")[0]
+def ThermalIsenthalpyEnum(): return StringToEnum("ThermalIsenthalpy")[0]
+def ThermalIsdynamicbasalspcEnum(): return StringToEnum("ThermalIsdynamicbasalspc")[0]
+def ThermalMaxiterEnum(): return StringToEnum("ThermalMaxiter")[0]
+def ThermalPenaltyFactorEnum(): return StringToEnum("ThermalPenaltyFactor")[0]
+def ThermalPenaltyLockEnum(): return StringToEnum("ThermalPenaltyLock")[0]
+def ThermalPenaltyThresholdEnum(): return StringToEnum("ThermalPenaltyThreshold")[0]
+def ThermalSpctemperatureEnum(): return StringToEnum("ThermalSpctemperature")[0]
+def ThermalStabilizationEnum(): return StringToEnum("ThermalStabilization")[0]
+def ThermalNumRequestedOutputsEnum(): return StringToEnum("ThermalNumRequestedOutputs")[0]
+def ThermalRequestedOutputsEnum(): return StringToEnum("ThermalRequestedOutputs")[0]
+def GiaMantleViscosityEnum(): return StringToEnum("GiaMantleViscosity")[0]
+def GiaLithosphereThicknessEnum(): return StringToEnum("GiaLithosphereThickness")[0]
+def ThicknessEnum(): return StringToEnum("Thickness")[0]
+def TimesteppingStartTimeEnum(): return StringToEnum("TimesteppingStartTime")[0]
+def TimesteppingFinalTimeEnum(): return StringToEnum("TimesteppingFinalTime")[0]
+def TimesteppingCflCoefficientEnum(): return StringToEnum("TimesteppingCflCoefficient")[0]
+def TimesteppingTimeAdaptEnum(): return StringToEnum("TimesteppingTimeAdapt")[0]
+def TimesteppingTimeStepEnum(): return StringToEnum("TimesteppingTimeStep")[0]
+def TimesteppingInterpForcingsEnum(): return StringToEnum("TimesteppingInterpForcings")[0]
+def TransientIsstressbalanceEnum(): return StringToEnum("TransientIsstressbalance")[0]
+def TransientIsgroundinglineEnum(): return StringToEnum("TransientIsgroundingline")[0]
+def TransientIsmasstransportEnum(): return StringToEnum("TransientIsmasstransport")[0]
+def TransientIsthermalEnum(): return StringToEnum("TransientIsthermal")[0]
+def TransientIsgiaEnum(): return StringToEnum("TransientIsgia")[0]
+def TransientIsdamageevolutionEnum(): return StringToEnum("TransientIsdamageevolution")[0]
+def TransientIshydrologyEnum(): return StringToEnum("TransientIshydrology")[0]
+def TransientNumRequestedOutputsEnum(): return StringToEnum("TransientNumRequestedOutputs")[0]
+def TransientRequestedOutputsEnum(): return StringToEnum("TransientRequestedOutputs")[0]
+def PotentialEnum(): return StringToEnum("Potential")[0]
+def BalancethicknessSpcpotentialEnum(): return StringToEnum("BalancethicknessSpcpotential")[0]
+def BalancethicknessApparentMassbalanceEnum(): return StringToEnum("BalancethicknessApparentMassbalance")[0]
+def Balancethickness2MisfitEnum(): return StringToEnum("Balancethickness2Misfit")[0]
+def BalancethicknessNuxEnum(): return StringToEnum("BalancethicknessNux")[0]
+def BalancethicknessNuyEnum(): return StringToEnum("BalancethicknessNuy")[0]
+def BalancethicknessVxObsEnum(): return StringToEnum("BalancethicknessVxObs")[0]
+def BalancethicknessVyObsEnum(): return StringToEnum("BalancethicknessVyObs")[0]
+def BalancethicknessThicknessObsEnum(): return StringToEnum("BalancethicknessThicknessObs")[0]
+def SurfaceforcingsEnum(): return StringToEnum("Surfaceforcings")[0]
+def SMBEnum(): return StringToEnum("SMB")[0]
+def SurfaceforcingsMassBalanceEnum(): return StringToEnum("SurfaceforcingsMassBalance")[0]
+def SMBpddEnum(): return StringToEnum("SMBpdd")[0]
+def SurfaceforcingsDelta18oEnum(): return StringToEnum("SurfaceforcingsDelta18o")[0]
+def SurfaceforcingsDelta18oSurfaceEnum(): return StringToEnum("SurfaceforcingsDelta18oSurface")[0]
+def SurfaceforcingsIsdelta18oEnum(): return StringToEnum("SurfaceforcingsIsdelta18o")[0]
+def SurfaceforcingsPrecipitationsPresentdayEnum(): return StringToEnum("SurfaceforcingsPrecipitationsPresentday")[0]
+def SurfaceforcingsTemperaturesPresentdayEnum(): return StringToEnum("SurfaceforcingsTemperaturesPresentday")[0]
+def SurfaceforcingsTemperaturesLgmEnum(): return StringToEnum("SurfaceforcingsTemperaturesLgm")[0]
+def SurfaceforcingsPrecipitationEnum(): return StringToEnum("SurfaceforcingsPrecipitation")[0]
+def SurfaceforcingsDesfacEnum(): return StringToEnum("SurfaceforcingsDesfac")[0]
+def SurfaceforcingsS0pEnum(): return StringToEnum("SurfaceforcingsS0p")[0]
+def SMBgradientsEnum(): return StringToEnum("SMBgradients")[0]
+def SurfaceforcingsMonthlytemperaturesEnum(): return StringToEnum("SurfaceforcingsMonthlytemperatures")[0]
+def SurfaceforcingsHrefEnum(): return StringToEnum("SurfaceforcingsHref")[0]
+def SurfaceforcingsSmbrefEnum(): return StringToEnum("SurfaceforcingsSmbref")[0]
+def SurfaceforcingsBPosEnum(): return StringToEnum("SurfaceforcingsBPos")[0]
+def SurfaceforcingsBNegEnum(): return StringToEnum("SurfaceforcingsBNeg")[0]
+def SMBhenningEnum(): return StringToEnum("SMBhenning")[0]
+def SMBcomponentsEnum(): return StringToEnum("SMBcomponents")[0]
+def SurfaceforcingsAccumulationEnum(): return StringToEnum("SurfaceforcingsAccumulation")[0]
+def SurfaceforcingsEvaporationEnum(): return StringToEnum("SurfaceforcingsEvaporation")[0]
+def SurfaceforcingsRunoffEnum(): return StringToEnum("SurfaceforcingsRunoff")[0]
+def SMBmeltcomponentsEnum(): return StringToEnum("SMBmeltcomponents")[0]
+def SurfaceforcingsMeltEnum(): return StringToEnum("SurfaceforcingsMelt")[0]
+def SurfaceforcingsRefreezeEnum(): return StringToEnum("SurfaceforcingsRefreeze")[0]
+def SurfaceforcingsIspddEnum(): return StringToEnum("SurfaceforcingsIspdd")[0]
+def SurfaceforcingsIssmbgradientsEnum(): return StringToEnum("SurfaceforcingsIssmbgradients")[0]
+def SolutionTypeEnum(): return StringToEnum("SolutionType")[0]
+def AnalysisTypeEnum(): return StringToEnum("AnalysisType")[0]
+def ConfigurationTypeEnum(): return StringToEnum("ConfigurationType")[0]
+def AdjointBalancethicknessAnalysisEnum(): return StringToEnum("AdjointBalancethicknessAnalysis")[0]
+def AdjointBalancethickness2AnalysisEnum(): return StringToEnum("AdjointBalancethickness2Analysis")[0]
+def AdjointHorizAnalysisEnum(): return StringToEnum("AdjointHorizAnalysis")[0]
+def AnalysisCounterEnum(): return StringToEnum("AnalysisCounter")[0]
+def DefaultAnalysisEnum(): return StringToEnum("DefaultAnalysis")[0]
+def BalancethicknessAnalysisEnum(): return StringToEnum("BalancethicknessAnalysis")[0]
+def BalancethicknessSolutionEnum(): return StringToEnum("BalancethicknessSolution")[0]
+def Balancethickness2AnalysisEnum(): return StringToEnum("Balancethickness2Analysis")[0]
+def Balancethickness2SolutionEnum(): return StringToEnum("Balancethickness2Solution")[0]
+def BalancethicknessSoftAnalysisEnum(): return StringToEnum("BalancethicknessSoftAnalysis")[0]
+def BalancethicknessSoftSolutionEnum(): return StringToEnum("BalancethicknessSoftSolution")[0]
+def BalancevelocityAnalysisEnum(): return StringToEnum("BalancevelocityAnalysis")[0]
+def BalancevelocitySolutionEnum(): return StringToEnum("BalancevelocitySolution")[0]
+def L2ProjectionEPLAnalysisEnum(): return StringToEnum("L2ProjectionEPLAnalysis")[0]
+def L2ProjectionBaseAnalysisEnum(): return StringToEnum("L2ProjectionBaseAnalysis")[0]
+def BedSlopeSolutionEnum(): return StringToEnum("BedSlopeSolution")[0]
+def DamageEvolutionSolutionEnum(): return StringToEnum("DamageEvolutionSolution")[0]
+def DamageEvolutionAnalysisEnum(): return StringToEnum("DamageEvolutionAnalysis")[0]
+def StressbalanceAnalysisEnum(): return StringToEnum("StressbalanceAnalysis")[0]
+def StressbalanceSIAAnalysisEnum(): return StringToEnum("StressbalanceSIAAnalysis")[0]
+def StressbalanceSolutionEnum(): return StringToEnum("StressbalanceSolution")[0]
+def StressbalanceVerticalAnalysisEnum(): return StringToEnum("StressbalanceVerticalAnalysis")[0]
+def EnthalpyAnalysisEnum(): return StringToEnum("EnthalpyAnalysis")[0]
+def FlaimAnalysisEnum(): return StringToEnum("FlaimAnalysis")[0]
+def FlaimSolutionEnum(): return StringToEnum("FlaimSolution")[0]
+def HydrologyShreveAnalysisEnum(): return StringToEnum("HydrologyShreveAnalysis")[0]
+def HydrologyDCInefficientAnalysisEnum(): return StringToEnum("HydrologyDCInefficientAnalysis")[0]
+def HydrologyDCEfficientAnalysisEnum(): return StringToEnum("HydrologyDCEfficientAnalysis")[0]
+def HydrologySolutionEnum(): return StringToEnum("HydrologySolution")[0]
+def MeltingAnalysisEnum(): return StringToEnum("MeltingAnalysis")[0]
+def MasstransportAnalysisEnum(): return StringToEnum("MasstransportAnalysis")[0]
+def MasstransportSolutionEnum(): return StringToEnum("MasstransportSolution")[0]
+def FreeSurfaceBaseAnalysisEnum(): return StringToEnum("FreeSurfaceBaseAnalysis")[0]
+def FreeSurfaceTopAnalysisEnum(): return StringToEnum("FreeSurfaceTopAnalysis")[0]
+def SurfaceNormalVelocityEnum(): return StringToEnum("SurfaceNormalVelocity")[0]
+def ExtrudeFromBaseAnalysisEnum(): return StringToEnum("ExtrudeFromBaseAnalysis")[0]
+def ExtrudeFromTopAnalysisEnum(): return StringToEnum("ExtrudeFromTopAnalysis")[0]
+def DepthAverageAnalysisEnum(): return StringToEnum("DepthAverageAnalysis")[0]
+def SteadystateSolutionEnum(): return StringToEnum("SteadystateSolution")[0]
+def SurfaceSlopeSolutionEnum(): return StringToEnum("SurfaceSlopeSolution")[0]
+def SmoothedSurfaceSlopeXAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeXAnalysis")[0]
+def SmoothedSurfaceSlopeYAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeYAnalysis")[0]
+def ThermalAnalysisEnum(): return StringToEnum("ThermalAnalysis")[0]
+def ThermalSolutionEnum(): return StringToEnum("ThermalSolution")[0]
+def TransientSolutionEnum(): return StringToEnum("TransientSolution")[0]
+def UzawaPressureAnalysisEnum(): return StringToEnum("UzawaPressureAnalysis")[0]
+def GiaSolutionEnum(): return StringToEnum("GiaSolution")[0]
+def GiaAnalysisEnum(): return StringToEnum("GiaAnalysis")[0]
+def MeshdeformationSolutionEnum(): return StringToEnum("MeshdeformationSolution")[0]
+def MeshdeformationAnalysisEnum(): return StringToEnum("MeshdeformationAnalysis")[0]
+def LevelsetAnalysisEnum(): return StringToEnum("LevelsetAnalysis")[0]
+def ExtrapolationAnalysisEnum(): return StringToEnum("ExtrapolationAnalysis")[0]
+def LsfReinitializationAnalysisEnum(): return StringToEnum("LsfReinitializationAnalysis")[0]
+def ApproximationEnum(): return StringToEnum("Approximation")[0]
+def NoneApproximationEnum(): return StringToEnum("NoneApproximation")[0]
+def SIAApproximationEnum(): return StringToEnum("SIAApproximation")[0]
+def SSAApproximationEnum(): return StringToEnum("SSAApproximation")[0]
+def SSAHOApproximationEnum(): return StringToEnum("SSAHOApproximation")[0]
+def SSAFSApproximationEnum(): return StringToEnum("SSAFSApproximation")[0]
+def L1L2ApproximationEnum(): return StringToEnum("L1L2Approximation")[0]
+def HOApproximationEnum(): return StringToEnum("HOApproximation")[0]
+def HOFSApproximationEnum(): return StringToEnum("HOFSApproximation")[0]
+def FSApproximationEnum(): return StringToEnum("FSApproximation")[0]
+def FSvelocityEnum(): return StringToEnum("FSvelocity")[0]
+def FSpressureEnum(): return StringToEnum("FSpressure")[0]
+def ConstraintsEnum(): return StringToEnum("Constraints")[0]
+def LoadsEnum(): return StringToEnum("Loads")[0]
+def MaterialsEnum(): return StringToEnum("Materials")[0]
+def NodesEnum(): return StringToEnum("Nodes")[0]
+def ContoursEnum(): return StringToEnum("Contours")[0]
+def ParametersEnum(): return StringToEnum("Parameters")[0]
+def VerticesEnum(): return StringToEnum("Vertices")[0]
+def ResultsEnum(): return StringToEnum("Results")[0]
+def GenericParamEnum(): return StringToEnum("GenericParam")[0]
+def AdolcParamEnum(): return StringToEnum("AdolcParam")[0]
+def BoolInputEnum(): return StringToEnum("BoolInput")[0]
+def BoolParamEnum(): return StringToEnum("BoolParam")[0]
+def ContourEnum(): return StringToEnum("Contour")[0]
+def ControlInputEnum(): return StringToEnum("ControlInput")[0]
+def DatasetInputEnum(): return StringToEnum("DatasetInput")[0]
+def DoubleInputEnum(): return StringToEnum("DoubleInput")[0]
+def DataSetParamEnum(): return StringToEnum("DataSetParam")[0]
+def DoubleMatArrayParamEnum(): return StringToEnum("DoubleMatArrayParam")[0]
+def DoubleMatParamEnum(): return StringToEnum("DoubleMatParam")[0]
+def DoubleParamEnum(): return StringToEnum("DoubleParam")[0]
+def DoubleVecParamEnum(): return StringToEnum("DoubleVecParam")[0]
+def ElementEnum(): return StringToEnum("Element")[0]
+def ExternalResultEnum(): return StringToEnum("ExternalResult")[0]
+def FileParamEnum(): return StringToEnum("FileParam")[0]
+def InputEnum(): return StringToEnum("Input")[0]
+def IntInputEnum(): return StringToEnum("IntInput")[0]
+def InputToExtrudeEnum(): return StringToEnum("InputToExtrude")[0]
+def InputToL2ProjectEnum(): return StringToEnum("InputToL2Project")[0]
+def InputToDepthaverageEnum(): return StringToEnum("InputToDepthaverage")[0]
+def IntParamEnum(): return StringToEnum("IntParam")[0]
+def IntVecParamEnum(): return StringToEnum("IntVecParam")[0]
+def TransientParamEnum(): return StringToEnum("TransientParam")[0]
+def MaticeEnum(): return StringToEnum("Matice")[0]
+def MatdamageiceEnum(): return StringToEnum("Matdamageice")[0]
+def MatparEnum(): return StringToEnum("Matpar")[0]
+def NodeEnum(): return StringToEnum("Node")[0]
+def NumericalfluxEnum(): return StringToEnum("Numericalflux")[0]
+def NumericalfluxTypeEnum(): return StringToEnum("NumericalfluxType")[0]
+def ParamEnum(): return StringToEnum("Param")[0]
+def PengridEnum(): return StringToEnum("Pengrid")[0]
+def PenpairEnum(): return StringToEnum("Penpair")[0]
+def ProfilerEnum(): return StringToEnum("Profiler")[0]
+def MatrixParamEnum(): return StringToEnum("MatrixParam")[0]
+def NodeSIdEnum(): return StringToEnum("NodeSId")[0]
+def VectorParamEnum(): return StringToEnum("VectorParam")[0]
+def RiftfrontEnum(): return StringToEnum("Riftfront")[0]
+def RiftfrontTypeEnum(): return StringToEnum("RiftfrontType")[0]
+def SegmentEnum(): return StringToEnum("Segment")[0]
+def SegmentRiftfrontEnum(): return StringToEnum("SegmentRiftfront")[0]
+def SpcDynamicEnum(): return StringToEnum("SpcDynamic")[0]
+def SpcStaticEnum(): return StringToEnum("SpcStatic")[0]
+def SpcTransientEnum(): return StringToEnum("SpcTransient")[0]
+def StringArrayParamEnum(): return StringToEnum("StringArrayParam")[0]
+def StringParamEnum(): return StringToEnum("StringParam")[0]
+def SegEnum(): return StringToEnum("Seg")[0]
+def SegInputEnum(): return StringToEnum("SegInput")[0]
+def TriaEnum(): return StringToEnum("Tria")[0]
+def TriaInputEnum(): return StringToEnum("TriaInput")[0]
+def TetraEnum(): return StringToEnum("Tetra")[0]
+def TetraInputEnum(): return StringToEnum("TetraInput")[0]
+def PentaEnum(): return StringToEnum("Penta")[0]
+def PentaInputEnum(): return StringToEnum("PentaInput")[0]
+def VertexEnum(): return StringToEnum("Vertex")[0]
+def VertexPIdEnum(): return StringToEnum("VertexPId")[0]
+def VertexSIdEnum(): return StringToEnum("VertexSId")[0]
+def AirEnum(): return StringToEnum("Air")[0]
+def IceEnum(): return StringToEnum("Ice")[0]
+def MelangeEnum(): return StringToEnum("Melange")[0]
+def WaterEnum(): return StringToEnum("Water")[0]
+def ClosedEnum(): return StringToEnum("Closed")[0]
+def FreeEnum(): return StringToEnum("Free")[0]
+def OpenEnum(): return StringToEnum("Open")[0]
+def AdjointpEnum(): return StringToEnum("Adjointp")[0]
+def AdjointxEnum(): return StringToEnum("Adjointx")[0]
+def AdjointyEnum(): return StringToEnum("Adjointy")[0]
+def AdjointzEnum(): return StringToEnum("Adjointz")[0]
+def BalancethicknessMisfitEnum(): return StringToEnum("BalancethicknessMisfit")[0]
+def BedSlopeXEnum(): return StringToEnum("BedSlopeX")[0]
+def BedSlopeYEnum(): return StringToEnum("BedSlopeY")[0]
+def BoundaryEnum(): return StringToEnum("Boundary")[0]
+def ConvergedEnum(): return StringToEnum("Converged")[0]
+def FillEnum(): return StringToEnum("Fill")[0]
+def FractionIncrementEnum(): return StringToEnum("FractionIncrement")[0]
+def FrictionEnum(): return StringToEnum("Friction")[0]
+def InternalEnum(): return StringToEnum("Internal")[0]
+def MassFluxEnum(): return StringToEnum("MassFlux")[0]
+def MeltingOffsetEnum(): return StringToEnum("MeltingOffset")[0]
+def MisfitEnum(): return StringToEnum("Misfit")[0]
+def PressureEnum(): return StringToEnum("Pressure")[0]
+def PressurePicardEnum(): return StringToEnum("PressurePicard")[0]
+def QmuPressureEnum(): return StringToEnum("QmuPressure")[0]
+def QmuVxEnum(): return StringToEnum("QmuVx")[0]
+def QmuVyEnum(): return StringToEnum("QmuVy")[0]
+def QmuVzEnum(): return StringToEnum("QmuVz")[0]
+def QmuThicknessEnum(): return StringToEnum("QmuThickness")[0]
+def QmuBaseEnum(): return StringToEnum("QmuBase")[0]
+def QmuSurfaceEnum(): return StringToEnum("QmuSurface")[0]
+def QmuMeltingEnum(): return StringToEnum("QmuMelting")[0]
+def QmuVxMeshEnum(): return StringToEnum("QmuVxMesh")[0]
+def QmuVyMeshEnum(): return StringToEnum("QmuVyMesh")[0]
+def QmuVzMeshEnum(): return StringToEnum("QmuVzMesh")[0]
+def AndroidFrictionCoefficientEnum(): return StringToEnum("AndroidFrictionCoefficient")[0]
+def ResetPenaltiesEnum(): return StringToEnum("ResetPenalties")[0]
+def SegmentOnIceShelfEnum(): return StringToEnum("SegmentOnIceShelf")[0]
+def SurfaceAbsVelMisfitEnum(): return StringToEnum("SurfaceAbsVelMisfit")[0]
+def SurfaceAreaEnum(): return StringToEnum("SurfaceArea")[0]
+def SurfaceAverageVelMisfitEnum(): return StringToEnum("SurfaceAverageVelMisfit")[0]
+def SurfaceLogVelMisfitEnum(): return StringToEnum("SurfaceLogVelMisfit")[0]
+def SurfaceLogVxVyMisfitEnum(): return StringToEnum("SurfaceLogVxVyMisfit")[0]
+def SurfaceRelVelMisfitEnum(): return StringToEnum("SurfaceRelVelMisfit")[0]
+def SurfaceSlopeXEnum(): return StringToEnum("SurfaceSlopeX")[0]
+def SurfaceSlopeYEnum(): return StringToEnum("SurfaceSlopeY")[0]
+def TemperatureEnum(): return StringToEnum("Temperature")[0]
+def TemperaturePicardEnum(): return StringToEnum("TemperaturePicard")[0]
+def ThicknessAbsMisfitEnum(): return StringToEnum("ThicknessAbsMisfit")[0]
+def VelEnum(): return StringToEnum("Vel")[0]
+def VelocityEnum(): return StringToEnum("Velocity")[0]
+def VxAverageEnum(): return StringToEnum("VxAverage")[0]
+def VxEnum(): return StringToEnum("Vx")[0]
+def VxPicardEnum(): return StringToEnum("VxPicard")[0]
+def VyAverageEnum(): return StringToEnum("VyAverage")[0]
+def VyEnum(): return StringToEnum("Vy")[0]
+def VyPicardEnum(): return StringToEnum("VyPicard")[0]
+def VzEnum(): return StringToEnum("Vz")[0]
+def VzSSAEnum(): return StringToEnum("VzSSA")[0]
+def VzHOEnum(): return StringToEnum("VzHO")[0]
+def VzPicardEnum(): return StringToEnum("VzPicard")[0]
+def VzFSEnum(): return StringToEnum("VzFS")[0]
+def VxMeshEnum(): return StringToEnum("VxMesh")[0]
+def VyMeshEnum(): return StringToEnum("VyMesh")[0]
+def VzMeshEnum(): return StringToEnum("VzMesh")[0]
+def EnthalpyEnum(): return StringToEnum("Enthalpy")[0]
+def EnthalpyPicardEnum(): return StringToEnum("EnthalpyPicard")[0]
+def ThicknessAbsGradientEnum(): return StringToEnum("ThicknessAbsGradient")[0]
+def ThicknessAlongGradientEnum(): return StringToEnum("ThicknessAlongGradient")[0]
+def ThicknessAcrossGradientEnum(): return StringToEnum("ThicknessAcrossGradient")[0]
+def IntMatParamEnum(): return StringToEnum("IntMatParam")[0]
+def RheologyBbarAbsGradientEnum(): return StringToEnum("RheologyBbarAbsGradient")[0]
+def DragCoefficientAbsGradientEnum(): return StringToEnum("DragCoefficientAbsGradient")[0]
+def TransientInputEnum(): return StringToEnum("TransientInput")[0]
+def WaterfractionEnum(): return StringToEnum("Waterfraction")[0]
+def WatercolumnEnum(): return StringToEnum("Watercolumn")[0]
+def BasalFrictionEnum(): return StringToEnum("BasalFriction")[0]
+def ViscousHeatingEnum(): return StringToEnum("ViscousHeating")[0]
+def QmuTemperatureEnum(): return StringToEnum("QmuTemperature")[0]
+def HydrologyWaterVxEnum(): return StringToEnum("HydrologyWaterVx")[0]
+def HydrologyWaterVyEnum(): return StringToEnum("HydrologyWaterVy")[0]
+def SigmaNNEnum(): return StringToEnum("SigmaNN")[0]
+def StressTensorEnum(): return StringToEnum("StressTensor")[0]
+def StressTensorxxEnum(): return StringToEnum("StressTensorxx")[0]
+def StressTensorxyEnum(): return StringToEnum("StressTensorxy")[0]
+def StressTensorxzEnum(): return StringToEnum("StressTensorxz")[0]
+def StressTensoryyEnum(): return StringToEnum("StressTensoryy")[0]
+def StressTensoryzEnum(): return StringToEnum("StressTensoryz")[0]
+def StressTensorzzEnum(): return StringToEnum("StressTensorzz")[0]
+def DeviatoricStressEnum(): return StringToEnum("DeviatoricStress")[0]
+def DeviatoricStressxxEnum(): return StringToEnum("DeviatoricStressxx")[0]
+def DeviatoricStressxyEnum(): return StringToEnum("DeviatoricStressxy")[0]
+def DeviatoricStressxzEnum(): return StringToEnum("DeviatoricStressxz")[0]
+def DeviatoricStressyyEnum(): return StringToEnum("DeviatoricStressyy")[0]
+def DeviatoricStressyzEnum(): return StringToEnum("DeviatoricStressyz")[0]
+def DeviatoricStresszzEnum(): return StringToEnum("DeviatoricStresszz")[0]
+def StrainRateEnum(): return StringToEnum("StrainRate")[0]
+def StrainRatexxEnum(): return StringToEnum("StrainRatexx")[0]
+def StrainRatexyEnum(): return StringToEnum("StrainRatexy")[0]
+def StrainRatexzEnum(): return StringToEnum("StrainRatexz")[0]
+def StrainRateyyEnum(): return StringToEnum("StrainRateyy")[0]
+def StrainRateyzEnum(): return StringToEnum("StrainRateyz")[0]
+def StrainRatezzEnum(): return StringToEnum("StrainRatezz")[0]
+def DivergenceEnum(): return StringToEnum("Divergence")[0]
+def GiaCrossSectionShapeEnum(): return StringToEnum("GiaCrossSectionShape")[0]
+def GiadWdtEnum(): return StringToEnum("GiadWdt")[0]
+def GiaWEnum(): return StringToEnum("GiaW")[0]
+def P0Enum(): return StringToEnum("P0")[0]
+def P1Enum(): return StringToEnum("P1")[0]
+def P1DGEnum(): return StringToEnum("P1DG")[0]
+def P1bubbleEnum(): return StringToEnum("P1bubble")[0]
+def P1bubblecondensedEnum(): return StringToEnum("P1bubblecondensed")[0]
+def P2Enum(): return StringToEnum("P2")[0]
+def P2bubbleEnum(): return StringToEnum("P2bubble")[0]
+def P2bubblecondensedEnum(): return StringToEnum("P2bubblecondensed")[0]
+def P2xP1Enum(): return StringToEnum("P2xP1")[0]
+def P1xP2Enum(): return StringToEnum("P1xP2")[0]
+def P1xP3Enum(): return StringToEnum("P1xP3")[0]
+def P2xP4Enum(): return StringToEnum("P2xP4")[0]
+def P1P1Enum(): return StringToEnum("P1P1")[0]
+def P1P1GLSEnum(): return StringToEnum("P1P1GLS")[0]
+def MINIEnum(): return StringToEnum("MINI")[0]
+def MINIcondensedEnum(): return StringToEnum("MINIcondensed")[0]
+def TaylorHoodEnum(): return StringToEnum("TaylorHood")[0]
+def LATaylorHoodEnum(): return StringToEnum("LATaylorHood")[0]
+def XTaylorHoodEnum(): return StringToEnum("XTaylorHood")[0]
+def OneLayerP4zEnum(): return StringToEnum("OneLayerP4z")[0]
+def CrouzeixRaviartEnum(): return StringToEnum("CrouzeixRaviart")[0]
+def SaveResultsEnum(): return StringToEnum("SaveResults")[0]
+def BoolExternalResultEnum(): return StringToEnum("BoolExternalResult")[0]
+def DoubleExternalResultEnum(): return StringToEnum("DoubleExternalResult")[0]
+def DoubleMatExternalResultEnum(): return StringToEnum("DoubleMatExternalResult")[0]
+def IntExternalResultEnum(): return StringToEnum("IntExternalResult")[0]
+def JEnum(): return StringToEnum("J")[0]
+def StringExternalResultEnum(): return StringToEnum("StringExternalResult")[0]
+def StepEnum(): return StringToEnum("Step")[0]
+def TimeEnum(): return StringToEnum("Time")[0]
+def WaterColumnOldEnum(): return StringToEnum("WaterColumnOld")[0]
+def OutputdefinitionEnum(): return StringToEnum("Outputdefinition")[0]
+def OutputdefinitionListEnum(): return StringToEnum("OutputdefinitionList")[0]
+def MassfluxatgateEnum(): return StringToEnum("Massfluxatgate")[0]
+def MassfluxatgateNameEnum(): return StringToEnum("MassfluxatgateName")[0]
+def MassfluxatgateSegmentsEnum(): return StringToEnum("MassfluxatgateSegments")[0]
+def MisfitNameEnum(): return StringToEnum("MisfitName")[0]
+def MisfitModelEnumEnum(): return StringToEnum("MisfitModelEnum")[0]
+def MisfitObservationEnum(): return StringToEnum("MisfitObservation")[0]
+def MisfitObservationEnumEnum(): return StringToEnum("MisfitObservationEnum")[0]
+def MisfitTimeinterpolationEnum(): return StringToEnum("MisfitTimeinterpolation")[0]
+def MisfitWeightsEnum(): return StringToEnum("MisfitWeights")[0]
+def MisfitWeightsEnumEnum(): return StringToEnum("MisfitWeightsEnum")[0]
+def SurfaceObservationEnum(): return StringToEnum("SurfaceObservation")[0]
+def WeightsSurfaceObservationEnum(): return StringToEnum("WeightsSurfaceObservation")[0]
+def MinVelEnum(): return StringToEnum("MinVel")[0]
+def MaxVelEnum(): return StringToEnum("MaxVel")[0]
+def MinVxEnum(): return StringToEnum("MinVx")[0]
+def MaxVxEnum(): return StringToEnum("MaxVx")[0]
+def MaxAbsVxEnum(): return StringToEnum("MaxAbsVx")[0]
+def MinVyEnum(): return StringToEnum("MinVy")[0]
+def MaxVyEnum(): return StringToEnum("MaxVy")[0]
+def MaxAbsVyEnum(): return StringToEnum("MaxAbsVy")[0]
+def MinVzEnum(): return StringToEnum("MinVz")[0]
+def MaxVzEnum(): return StringToEnum("MaxVz")[0]
+def MaxAbsVzEnum(): return StringToEnum("MaxAbsVz")[0]
+def IceVolumeEnum(): return StringToEnum("IceVolume")[0]
+def IceVolumeAboveFloatationEnum(): return StringToEnum("IceVolumeAboveFloatation")[0]
+def TotalSmbEnum(): return StringToEnum("TotalSmb")[0]
+def AbsoluteEnum(): return StringToEnum("Absolute")[0]
+def IncrementalEnum(): return StringToEnum("Incremental")[0]
+def AugmentedLagrangianREnum(): return StringToEnum("AugmentedLagrangianR")[0]
+def AugmentedLagrangianRhopEnum(): return StringToEnum("AugmentedLagrangianRhop")[0]
+def AugmentedLagrangianThetaEnum(): return StringToEnum("AugmentedLagrangianTheta")[0]
+def NoneEnum(): return StringToEnum("None")[0]
+def AggressiveMigrationEnum(): return StringToEnum("AggressiveMigration")[0]
+def SoftMigrationEnum(): return StringToEnum("SoftMigration")[0]
+def SubelementMigrationEnum(): return StringToEnum("SubelementMigration")[0]
+def SubelementMigration2Enum(): return StringToEnum("SubelementMigration2")[0]
+def ContactEnum(): return StringToEnum("Contact")[0]
+def MaskGroundediceLevelsetEnum(): return StringToEnum("MaskGroundediceLevelset")[0]
+def QmuMaskGroundediceLevelsetEnum(): return StringToEnum("QmuMaskGroundediceLevelset")[0]
+def GaussSegEnum(): return StringToEnum("GaussSeg")[0]
+def GaussTriaEnum(): return StringToEnum("GaussTria")[0]
+def GaussTetraEnum(): return StringToEnum("GaussTetra")[0]
+def GaussPentaEnum(): return StringToEnum("GaussPenta")[0]
+def FSSolverEnum(): return StringToEnum("FSSolver")[0]
+def AdjointEnum(): return StringToEnum("Adjoint")[0]
+def ColinearEnum(): return StringToEnum("Colinear")[0]
+def ControlSteadyEnum(): return StringToEnum("ControlSteady")[0]
+def FsetEnum(): return StringToEnum("Fset")[0]
+def Gradient1Enum(): return StringToEnum("Gradient1")[0]
+def Gradient2Enum(): return StringToEnum("Gradient2")[0]
+def Gradient3Enum(): return StringToEnum("Gradient3")[0]
+def GradientEnum(): return StringToEnum("Gradient")[0]
+def GroundinglineMigrationEnum(): return StringToEnum("GroundinglineMigration")[0]
+def GsetEnum(): return StringToEnum("Gset")[0]
+def IndexEnum(): return StringToEnum("Index")[0]
+def IndexedEnum(): return StringToEnum("Indexed")[0]
+def IntersectEnum(): return StringToEnum("Intersect")[0]
+def NodalEnum(): return StringToEnum("Nodal")[0]
+def OldGradientEnum(): return StringToEnum("OldGradient")[0]
+def OutputFilePointerEnum(): return StringToEnum("OutputFilePointer")[0]
+def OutputFileNameEnum(): return StringToEnum("OutputFileName")[0]
+def LockFileNameEnum(): return StringToEnum("LockFileName")[0]
+def ToolkitsOptionsAnalysesEnum(): return StringToEnum("ToolkitsOptionsAnalyses")[0]
+def ToolkitsOptionsStringsEnum(): return StringToEnum("ToolkitsOptionsStrings")[0]
+def QmuErrNameEnum(): return StringToEnum("QmuErrName")[0]
+def QmuInNameEnum(): return StringToEnum("QmuInName")[0]
+def QmuOutNameEnum(): return StringToEnum("QmuOutName")[0]
+def RegularEnum(): return StringToEnum("Regular")[0]
+def ScaledEnum(): return StringToEnum("Scaled")[0]
+def SeparateEnum(): return StringToEnum("Separate")[0]
+def SsetEnum(): return StringToEnum("Sset")[0]
+def VerboseEnum(): return StringToEnum("Verbose")[0]
+def TriangleInterpEnum(): return StringToEnum("TriangleInterp")[0]
+def BilinearInterpEnum(): return StringToEnum("BilinearInterp")[0]
+def NearestInterpEnum(): return StringToEnum("NearestInterp")[0]
+def XYEnum(): return StringToEnum("XY")[0]
+def XYZEnum(): return StringToEnum("XYZ")[0]
+def DenseEnum(): return StringToEnum("Dense")[0]
+def MpiDenseEnum(): return StringToEnum("MpiDense")[0]
+def MpiSparseEnum(): return StringToEnum("MpiSparse")[0]
+def SeqEnum(): return StringToEnum("Seq")[0]
+def MpiEnum(): return StringToEnum("Mpi")[0]
+def MumpsEnum(): return StringToEnum("Mumps")[0]
+def GslEnum(): return StringToEnum("Gsl")[0]
+def OptionEnum(): return StringToEnum("Option")[0]
+def GenericOptionEnum(): return StringToEnum("GenericOption")[0]
+def OptionCellEnum(): return StringToEnum("OptionCell")[0]
+def OptionStructEnum(): return StringToEnum("OptionStruct")[0]
+def CuffeyEnum(): return StringToEnum("Cuffey")[0]
+def PatersonEnum(): return StringToEnum("Paterson")[0]
+def ArrheniusEnum(): return StringToEnum("Arrhenius")[0]
+def LliboutryDuvalEnum(): return StringToEnum("LliboutryDuval")[0]
+def TransientIslevelsetEnum(): return StringToEnum("TransientIslevelset")[0]
+def ExtrapolationVariableEnum(): return StringToEnum("ExtrapolationVariable")[0]
+def IceMaskNodeActivationEnum(): return StringToEnum("IceMaskNodeActivation")[0]
+def LevelsetfunctionSlopeXEnum(): return StringToEnum("LevelsetfunctionSlopeX")[0]
+def LevelsetfunctionSlopeYEnum(): return StringToEnum("LevelsetfunctionSlopeY")[0]
+def LevelsetfunctionPicardEnum(): return StringToEnum("LevelsetfunctionPicard")[0]
+def MaximumNumberOfDefinitionsEnum(): return StringToEnum("MaximumNumberOfDefinitions")[0]
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EplHeadEnum()
+%EPLHEADENUM - Enum of EplHead
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EplHeadEnum()
+
+macro=StringToEnum('EplHead');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadOldEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadOldEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadOldEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EplHeadOldEnum()
+%EPLHEADOLDENUM - Enum of EplHeadOld
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EplHeadOldEnum()
+
+macro=StringToEnum('EplHeadOld');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EplHeadSlopeXEnum()
+%EPLHEADSLOPEXENUM - Enum of EplHeadSlopeX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EplHeadSlopeXEnum()
+
+macro=StringToEnum('EplHeadSlopeX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/EplHeadSlopeYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=EplHeadSlopeYEnum()
+%EPLHEADSLOPEYENUM - Enum of EplHeadSlopeY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EplHeadSlopeYEnum()
+
+macro=StringToEnum('EplHeadSlopeY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ExternalResultEnum()
+%EXTERNALRESULTENUM - Enum of ExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExternalResultEnum()
+
+macro=StringToEnum('ExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ExtrapolationAnalysisEnum()
+%EXTRAPOLATIONANALYSISENUM - Enum of ExtrapolationAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrapolationAnalysisEnum()
+
+macro=StringToEnum('ExtrapolationAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationVariableEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationVariableEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrapolationVariableEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ExtrapolationVariableEnum()
+%EXTRAPOLATIONVARIABLEENUM - Enum of ExtrapolationVariable
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrapolationVariableEnum()
+
+macro=StringToEnum('ExtrapolationVariable');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromBaseAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromBaseAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromBaseAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ExtrudeFromBaseAnalysisEnum()
+%EXTRUDEFROMBASEANALYSISENUM - Enum of ExtrudeFromBaseAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrudeFromBaseAnalysisEnum()
+
+macro=StringToEnum('ExtrudeFromBaseAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromTopAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromTopAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ExtrudeFromTopAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ExtrudeFromTopAnalysisEnum()
+%EXTRUDEFROMTOPANALYSISENUM - Enum of ExtrudeFromTopAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ExtrudeFromTopAnalysisEnum()
+
+macro=StringToEnum('ExtrudeFromTopAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FSApproximationEnum()
+%FSAPPROXIMATIONENUM - Enum of FSApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FSApproximationEnum()
+
+macro=StringToEnum('FSApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSSolverEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSSolverEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSSolverEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FSSolverEnum()
+%FSSOLVERENUM - Enum of FSSolver
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FSSolverEnum()
+
+macro=StringToEnum('FSSolver');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSpressureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSpressureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSpressureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FSpressureEnum()
+%FSPRESSUREENUM - Enum of FSpressure
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FSpressureEnum()
+
+macro=StringToEnum('FSpressure');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSvelocityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSvelocityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FSvelocityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FSvelocityEnum()
+%FSVELOCITYENUM - Enum of FSvelocity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FSvelocityEnum()
+
+macro=StringToEnum('FSvelocity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FileParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FileParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FileParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FileParamEnum()
+%FILEPARAMENUM - Enum of FileParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FileParamEnum()
+
+macro=StringToEnum('FileParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FillEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FillEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FillEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FillEnum()
+%FILLENUM - Enum of Fill
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FillEnum()
+
+macro=StringToEnum('Fill');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlaimAnalysisEnum()
+%FLAIMANALYSISENUM - Enum of FlaimAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlaimAnalysisEnum()
+
+macro=StringToEnum('FlaimAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlaimSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlaimSolutionEnum()
+%FLAIMSOLUTIONENUM - Enum of FlaimSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlaimSolutionEnum()
+
+macro=StringToEnum('FlaimSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FloatingMeltRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FloatingMeltRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FloatingMeltRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FloatingMeltRateEnum()
+%FLOATINGMELTRATEENUM - Enum of FloatingMeltRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FloatingMeltRateEnum()
+
+macro=StringToEnum('FloatingMeltRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderFSEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderFSEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderFSEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderFSEnum()
+%FLOWEQUATIONBORDERFSENUM - Enum of FlowequationBorderFS
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationBorderFSEnum()
+
+macro=StringToEnum('FlowequationBorderFS');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderHOEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderHOEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderHOEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderHOEnum()
+%FLOWEQUATIONBORDERHOENUM - Enum of FlowequationBorderHO
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationBorderHOEnum()
+
+macro=StringToEnum('FlowequationBorderHO');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderSSAEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderSSAEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationBorderSSAEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderSSAEnum()
+%FLOWEQUATIONBORDERSSAENUM - Enum of FlowequationBorderSSA
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationBorderSSAEnum()
+
+macro=StringToEnum('FlowequationBorderSSA');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationElementEquationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationElementEquationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationElementEquationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationElementEquationEnum()
+%FLOWEQUATIONELEMENTEQUATIONENUM - Enum of FlowequationElementEquation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationElementEquationEnum()
+
+macro=StringToEnum('FlowequationElementEquation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeFSEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeFSEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeFSEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeFSEnum()
+%FLOWEQUATIONFEFSENUM - Enum of FlowequationFeFS
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationFeFSEnum()
+
+macro=StringToEnum('FlowequationFeFS');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeHOEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeHOEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeHOEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeHOEnum()
+%FLOWEQUATIONFEHOENUM - Enum of FlowequationFeHO
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationFeHOEnum()
+
+macro=StringToEnum('FlowequationFeHO');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeSSAEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeSSAEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationFeSSAEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeSSAEnum()
+%FLOWEQUATIONFESSAENUM - Enum of FlowequationFeSSA
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationFeSSAEnum()
+
+macro=StringToEnum('FlowequationFeSSA');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsFSEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsFSEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsFSEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsFSEnum()
+%FLOWEQUATIONISFSENUM - Enum of FlowequationIsFS
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsFSEnum()
+
+macro=StringToEnum('FlowequationIsFS');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsHOEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsHOEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsHOEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsHOEnum()
+%FLOWEQUATIONISHOENUM - Enum of FlowequationIsHO
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsHOEnum()
+
+macro=StringToEnum('FlowequationIsHO');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsL1L2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsL1L2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsL1L2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsL1L2Enum()
+%FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsL1L2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsL1L2Enum()
+
+macro=StringToEnum('FlowequationIsL1L2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSIAEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSIAEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSIAEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsSIAEnum()
+%FLOWEQUATIONISSIAENUM - Enum of FlowequationIsSIA
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsSIAEnum()
+
+macro=StringToEnum('FlowequationIsSIA');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSSAEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSSAEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationIsSSAEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsSSAEnum()
+%FLOWEQUATIONISSSAENUM - Enum of FlowequationIsSSA
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsSSAEnum()
+
+macro=StringToEnum('FlowequationIsSSA');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationVertexEquationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationVertexEquationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FlowequationVertexEquationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FlowequationVertexEquationEnum()
+%FLOWEQUATIONVERTEXEQUATIONENUM - Enum of FlowequationVertexEquation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FlowequationVertexEquationEnum()
+
+macro=StringToEnum('FlowequationVertexEquation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FractionIncrementEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FractionIncrementEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FractionIncrementEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FractionIncrementEnum()
+%FRACTIONINCREMENTENUM - Enum of FractionIncrement
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FractionIncrementEnum()
+
+macro=StringToEnum('FractionIncrement');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FreeEnum()
+%FREEENUM - Enum of Free
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FreeEnum()
+
+macro=StringToEnum('Free');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceBaseAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceBaseAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceBaseAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FreeSurfaceBaseAnalysisEnum()
+%FREESURFACEBASEANALYSISENUM - Enum of FreeSurfaceBaseAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FreeSurfaceBaseAnalysisEnum()
+
+macro=StringToEnum('FreeSurfaceBaseAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceTopAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceTopAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FreeSurfaceTopAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FreeSurfaceTopAnalysisEnum()
+%FREESURFACETOPANALYSISENUM - Enum of FreeSurfaceTopAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FreeSurfaceTopAnalysisEnum()
+
+macro=StringToEnum('FreeSurfaceTopAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionCEnum()
+%FRICTIONCENUM - Enum of FrictionC
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionCEnum()
+
+macro=StringToEnum('FrictionC');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCoefficientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCoefficientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionCoefficientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionCoefficientEnum()
+%FRICTIONCOEFFICIENTENUM - Enum of FrictionCoefficient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionCoefficientEnum()
+
+macro=StringToEnum('FrictionCoefficient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionEnum()
+%FRICTIONENUM - Enum of Friction
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionEnum()
+
+macro=StringToEnum('Friction');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionLawEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionLawEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionLawEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionLawEnum()
+%FRICTIONLAWENUM - Enum of FrictionLaw
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionLawEnum()
+
+macro=StringToEnum('FrictionLaw');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionMEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionMEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionMEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionMEnum()
+%FRICTIONMENUM - Enum of FrictionM
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionMEnum()
+
+macro=StringToEnum('FrictionM');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionPEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionPEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionPEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionPEnum()
+%FRICTIONPENUM - Enum of FrictionP
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionPEnum()
+
+macro=StringToEnum('FrictionP');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionQEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionQEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FrictionQEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FrictionQEnum()
+%FRICTIONQENUM - Enum of FrictionQ
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionQEnum()
+
+macro=StringToEnum('FrictionQ');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/FsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=FsetEnum()
+%FSETENUM - Enum of Fset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FsetEnum()
+
+macro=StringToEnum('Fset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussPentaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussPentaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussPentaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GaussPentaEnum()
+%GAUSSPENTAENUM - Enum of GaussPenta
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GaussPentaEnum()
+
+macro=StringToEnum('GaussPenta');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussSegEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussSegEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussSegEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GaussSegEnum()
+%GAUSSSEGENUM - Enum of GaussSeg
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GaussSegEnum()
+
+macro=StringToEnum('GaussSeg');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTetraEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTetraEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTetraEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GaussTetraEnum()
+%GAUSSTETRAENUM - Enum of GaussTetra
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GaussTetraEnum()
+
+macro=StringToEnum('GaussTetra');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTriaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTriaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GaussTriaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GaussTriaEnum()
+%GAUSSTRIAENUM - Enum of GaussTria
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GaussTriaEnum()
+
+macro=StringToEnum('GaussTria');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericOptionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericOptionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericOptionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GenericOptionEnum()
+%GENERICOPTIONENUM - Enum of GenericOption
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GenericOptionEnum()
+
+macro=StringToEnum('GenericOption');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GenericParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GenericParamEnum()
+%GENERICPARAMENUM - Enum of GenericParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GenericParamEnum()
+
+macro=StringToEnum('GenericParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GeometryHydrostaticRatioEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GeometryHydrostaticRatioEnum()
+%GEOMETRYHYDROSTATICRATIOENUM - Enum of GeometryHydrostaticRatio
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GeometryHydrostaticRatioEnum()
+
+macro=StringToEnum('GeometryHydrostaticRatio');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaAnalysisEnum()
+%GIAANALYSISENUM - Enum of GiaAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaAnalysisEnum()
+
+macro=StringToEnum('GiaAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaCrossSectionShapeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaCrossSectionShapeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaCrossSectionShapeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaCrossSectionShapeEnum()
+%GIACROSSSECTIONSHAPEENUM - Enum of GiaCrossSectionShape
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaCrossSectionShapeEnum()
+
+macro=StringToEnum('GiaCrossSectionShape');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaLithosphereThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaLithosphereThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaLithosphereThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaLithosphereThicknessEnum()
+%GIALITHOSPHERETHICKNESSENUM - Enum of GiaLithosphereThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaLithosphereThicknessEnum()
+
+macro=StringToEnum('GiaLithosphereThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaMantleViscosityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaMantleViscosityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaMantleViscosityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaMantleViscosityEnum()
+%GIAMANTLEVISCOSITYENUM - Enum of GiaMantleViscosity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaMantleViscosityEnum()
+
+macro=StringToEnum('GiaMantleViscosity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaSolutionEnum()
+%GIASOLUTIONENUM - Enum of GiaSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaSolutionEnum()
+
+macro=StringToEnum('GiaSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaWEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaWEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiaWEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiaWEnum()
+%GIAWENUM - Enum of GiaW
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiaWEnum()
+
+macro=StringToEnum('GiaW');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiadWdtEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiadWdtEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GiadWdtEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GiadWdtEnum()
+%GIADWDTENUM - Enum of GiadWdt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GiadWdtEnum()
+
+macro=StringToEnum('GiadWdt');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient1Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient1Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient1Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Gradient1Enum()
+%GRADIENT1ENUM - Enum of Gradient1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Gradient1Enum()
+
+macro=StringToEnum('Gradient1');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Gradient2Enum()
+%GRADIENT2ENUM - Enum of Gradient2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Gradient2Enum()
+
+macro=StringToEnum('Gradient2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient3Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient3Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/Gradient3Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=Gradient3Enum()
+%GRADIENT3ENUM - Enum of Gradient3
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Gradient3Enum()
+
+macro=StringToEnum('Gradient3');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GradientEnum()
+%GRADIENTENUM - Enum of Gradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GradientEnum()
+
+macro=StringToEnum('Gradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GroundinglineMigrationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GroundinglineMigrationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GroundinglineMigrationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GroundinglineMigrationEnum()
+%GROUNDINGLINEMIGRATIONENUM - Enum of GroundinglineMigration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GroundinglineMigrationEnum()
+
+macro=StringToEnum('GroundinglineMigration');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GsetEnum()
+%GSETENUM - Enum of Gset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GsetEnum()
+
+macro=StringToEnum('Gset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GslEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GslEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/GslEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=GslEnum()
+%GSLENUM - Enum of Gsl
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GslEnum()
+
+macro=StringToEnum('Gsl');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HOApproximationEnum()
+%HOAPPROXIMATIONENUM - Enum of HOApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HOApproximationEnum()
+
+macro=StringToEnum('HOApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOFSApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOFSApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HOFSApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HOFSApproximationEnum()
+%HOFSAPPROXIMATIONENUM - Enum of HOFSApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HOFSApproximationEnum()
+
+macro=StringToEnum('HOFSApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCEfficientAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCEfficientAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCEfficientAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyDCEfficientAnalysisEnum()
+%HYDROLOGYDCEFFICIENTANALYSISENUM - Enum of HydrologyDCEfficientAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyDCEfficientAnalysisEnum()
+
+macro=StringToEnum('HydrologyDCEfficientAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCInefficientAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCInefficientAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyDCInefficientAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyDCInefficientAnalysisEnum()
+%HYDROLOGYDCINEFFICIENTANALYSISENUM - Enum of HydrologyDCInefficientAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyDCInefficientAnalysisEnum()
+
+macro=StringToEnum('HydrologyDCInefficientAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyEfficientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyEfficientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyEfficientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyEfficientEnum()
+%HYDROLOGYEFFICIENTENUM - Enum of HydrologyEfficient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyEfficientEnum()
+
+macro=StringToEnum('HydrologyEfficient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyLayerEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyLayerEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyLayerEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyLayerEnum()
+%HYDROLOGYLAYERENUM - Enum of HydrologyLayer
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyLayerEnum()
+
+macro=StringToEnum('HydrologyLayer');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyModelEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyModelEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyModelEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyModelEnum()
+%HYDROLOGYMODELENUM - Enum of HydrologyModel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyModelEnum()
+
+macro=StringToEnum('HydrologyModel');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologySedimentEnum()
+%HYDROLOGYSEDIMENTENUM - Enum of HydrologySediment
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologySedimentEnum()
+
+macro=StringToEnum('HydrologySediment');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentKmaxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentKmaxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySedimentKmaxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologySedimentKmaxEnum()
+%HYDROLOGYSEDIMENTKMAXENUM - Enum of HydrologySedimentKmax
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologySedimentKmaxEnum()
+
+macro=StringToEnum('HydrologySedimentKmax');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyShreveAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyShreveAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyShreveAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyShreveAnalysisEnum()
+%HYDROLOGYSHREVEANALYSISENUM - Enum of HydrologyShreveAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyShreveAnalysisEnum()
+
+macro=StringToEnum('HydrologyShreveAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologySolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologySolutionEnum()
+%HYDROLOGYSOLUTIONENUM - Enum of HydrologySolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologySolutionEnum()
+
+macro=StringToEnum('HydrologySolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyWaterVxEnum()
+%HYDROLOGYWATERVXENUM - Enum of HydrologyWaterVx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyWaterVxEnum()
+
+macro=StringToEnum('HydrologyWaterVx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyWaterVyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyWaterVyEnum()
+%HYDROLOGYWATERVYENUM - Enum of HydrologyWaterVy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyWaterVyEnum()
+
+macro=StringToEnum('HydrologyWaterVy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcBasalMoulinInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcBasalMoulinInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcBasalMoulinInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcBasalMoulinInputEnum()
+%HYDROLOGYDCBASALMOULININPUTENUM - Enum of HydrologydcBasalMoulinInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcBasalMoulinInputEnum()
+
+macro=StringToEnum('HydrologydcBasalMoulinInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEnum()
+%HYDROLOGYDCENUM - Enum of Hydrologydc
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEnum()
+
+macro=StringToEnum('Hydrologydc');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplCompressibilityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplCompressibilityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplCompressibilityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplCompressibilityEnum()
+%HYDROLOGYDCEPLCOMPRESSIBILITYENUM - Enum of HydrologydcEplCompressibility
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplCompressibilityEnum()
+
+macro=StringToEnum('HydrologydcEplCompressibility');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplConductivityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplConductivityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplConductivityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplConductivityEnum()
+%HYDROLOGYDCEPLCONDUCTIVITYENUM - Enum of HydrologydcEplConductivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplConductivityEnum()
+
+macro=StringToEnum('HydrologydcEplConductivity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplInitialThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplInitialThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplInitialThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplInitialThicknessEnum()
+%HYDROLOGYDCEPLINITIALTHICKNESSENUM - Enum of HydrologydcEplInitialThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplInitialThicknessEnum()
+
+macro=StringToEnum('HydrologydcEplInitialThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplMaxThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplMaxThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplMaxThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplMaxThicknessEnum()
+%HYDROLOGYDCEPLMAXTHICKNESSENUM - Enum of HydrologydcEplMaxThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplMaxThicknessEnum()
+
+macro=StringToEnum('HydrologydcEplMaxThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplPorosityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplPorosityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplPorosityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplPorosityEnum()
+%HYDROLOGYDCEPLPOROSITYENUM - Enum of HydrologydcEplPorosity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplPorosityEnum()
+
+macro=StringToEnum('HydrologydcEplPorosity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplThicknessEnum()
+%HYDROLOGYDCEPLTHICKNESSENUM - Enum of HydrologydcEplThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplThicknessEnum()
+
+macro=StringToEnum('HydrologydcEplThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessOldEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessOldEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcEplThicknessOldEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplThicknessOldEnum()
+%HYDROLOGYDCEPLTHICKNESSOLDENUM - Enum of HydrologydcEplThicknessOld
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplThicknessOldEnum()
+
+macro=StringToEnum('HydrologydcEplThicknessOld');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcIsefficientlayerEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcIsefficientlayerEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcIsefficientlayerEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcIsefficientlayerEnum()
+%HYDROLOGYDCISEFFICIENTLAYERENUM - Enum of HydrologydcIsefficientlayer
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcIsefficientlayerEnum()
+
+macro=StringToEnum('HydrologydcIsefficientlayer');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcLeakageFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcLeakageFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcLeakageFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcLeakageFactorEnum()
+%HYDROLOGYDCLEAKAGEFACTORENUM - Enum of HydrologydcLeakageFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcLeakageFactorEnum()
+
+macro=StringToEnum('HydrologydcLeakageFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveEltEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveEltEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveEltEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcMaskEplactiveEltEnum()
+%HYDROLOGYDCMASKEPLACTIVEELTENUM - Enum of HydrologydcMaskEplactiveElt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcMaskEplactiveEltEnum()
+
+macro=StringToEnum('HydrologydcMaskEplactiveElt');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveNodeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveNodeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaskEplactiveNodeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcMaskEplactiveNodeEnum()
+%HYDROLOGYDCMASKEPLACTIVENODEENUM - Enum of HydrologydcMaskEplactiveNode
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcMaskEplactiveNodeEnum()
+
+macro=StringToEnum('HydrologydcMaskEplactiveNode');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaxIterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaxIterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcMaxIterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcMaxIterEnum()
+%HYDROLOGYDCMAXITERENUM - Enum of HydrologydcMaxIter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcMaxIterEnum()
+
+macro=StringToEnum('HydrologydcMaxIter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcPenaltyFactorEnum()
+%HYDROLOGYDCPENALTYFACTORENUM - Enum of HydrologydcPenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcPenaltyFactorEnum()
+
+macro=StringToEnum('HydrologydcPenaltyFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyLockEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyLockEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcPenaltyLockEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcPenaltyLockEnum()
+%HYDROLOGYDCPENALTYLOCKENUM - Enum of HydrologydcPenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcPenaltyLockEnum()
+
+macro=StringToEnum('HydrologydcPenaltyLock');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcRelTolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcRelTolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcRelTolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcRelTolEnum()
+%HYDROLOGYDCRELTOLENUM - Enum of HydrologydcRelTol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcRelTolEnum()
+
+macro=StringToEnum('HydrologydcRelTol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentCompressibilityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentCompressibilityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentCompressibilityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentCompressibilityEnum()
+%HYDROLOGYDCSEDIMENTCOMPRESSIBILITYENUM - Enum of HydrologydcSedimentCompressibility
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentCompressibilityEnum()
+
+macro=StringToEnum('HydrologydcSedimentCompressibility');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentPorosityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentPorosityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentPorosityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentPorosityEnum()
+%HYDROLOGYDCSEDIMENTPOROSITYENUM - Enum of HydrologydcSedimentPorosity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentPorosityEnum()
+
+macro=StringToEnum('HydrologydcSedimentPorosity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentThicknessEnum()
+%HYDROLOGYDCSEDIMENTTHICKNESSENUM - Enum of HydrologydcSedimentThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentThicknessEnum()
+
+macro=StringToEnum('HydrologydcSedimentThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentTransmitivityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentTransmitivityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentTransmitivityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentTransmitivityEnum()
+%HYDROLOGYDCSEDIMENTTRANSMITIVITYENUM - Enum of HydrologydcSedimentTransmitivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentTransmitivityEnum()
+
+macro=StringToEnum('HydrologydcSedimentTransmitivity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentlimitEnum()
+%HYDROLOGYDCSEDIMENTLIMITENUM - Enum of HydrologydcSedimentlimit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentlimitEnum()
+
+macro=StringToEnum('HydrologydcSedimentlimit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitFlagEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitFlagEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSedimentlimitFlagEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSedimentlimitFlagEnum()
+%HYDROLOGYDCSEDIMENTLIMITFLAGENUM - Enum of HydrologydcSedimentlimitFlag
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSedimentlimitFlagEnum()
+
+macro=StringToEnum('HydrologydcSedimentlimitFlag');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpceplHeadEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpceplHeadEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpceplHeadEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSpceplHeadEnum()
+%HYDROLOGYDCSPCEPLHEADENUM - Enum of HydrologydcSpceplHead
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSpceplHeadEnum()
+
+macro=StringToEnum('HydrologydcSpceplHead');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpcsedimentHeadEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpcsedimentHeadEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcSpcsedimentHeadEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcSpcsedimentHeadEnum()
+%HYDROLOGYDCSPCSEDIMENTHEADENUM - Enum of HydrologydcSpcsedimentHead
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcSpcsedimentHeadEnum()
+
+macro=StringToEnum('HydrologydcSpcsedimentHead');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcTransferFlagEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcTransferFlagEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcTransferFlagEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcTransferFlagEnum()
+%HYDROLOGYDCTRANSFERFLAGENUM - Enum of HydrologydcTransferFlag
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcTransferFlagEnum()
+
+macro=StringToEnum('HydrologydcTransferFlag');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcWaterCompressibilityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcWaterCompressibilityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologydcWaterCompressibilityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologydcWaterCompressibilityEnum()
+%HYDROLOGYDCWATERCOMPRESSIBILITYENUM - Enum of HydrologydcWaterCompressibility
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcWaterCompressibilityEnum()
+
+macro=StringToEnum('HydrologydcWaterCompressibility');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyshreveEnum()
+%HYDROLOGYSHREVEENUM - Enum of Hydrologyshreve
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyshreveEnum()
+
+macro=StringToEnum('Hydrologyshreve');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyshreveSpcwatercolumnEnum()
+%HYDROLOGYSHREVESPCWATERCOLUMNENUM - Enum of HydrologyshreveSpcwatercolumn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyshreveSpcwatercolumnEnum()
+
+macro=StringToEnum('HydrologyshreveSpcwatercolumn');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveStabilizationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveStabilizationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/HydrologyshreveStabilizationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=HydrologyshreveStabilizationEnum()
+%HYDROLOGYSHREVESTABILIZATIONENUM - Enum of HydrologyshreveStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologyshreveStabilizationEnum()
+
+macro=StringToEnum('HydrologyshreveStabilization');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IceEnum()
+%ICEENUM - Enum of Ice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceEnum()
+
+macro=StringToEnum('Ice');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceMaskNodeActivationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceMaskNodeActivationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceMaskNodeActivationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IceMaskNodeActivationEnum()
+%ICEMASKNODEACTIVATIONENUM - Enum of IceMaskNodeActivation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceMaskNodeActivationEnum()
+
+macro=StringToEnum('IceMaskNodeActivation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeAboveFloatationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeAboveFloatationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeAboveFloatationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IceVolumeAboveFloatationEnum()
+%ICEVOLUMEABOVEFLOATATIONENUM - Enum of IceVolumeAboveFloatation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceVolumeAboveFloatationEnum()
+
+macro=StringToEnum('IceVolumeAboveFloatation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IceVolumeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IceVolumeEnum()
+%ICEVOLUMEENUM - Enum of IceVolume
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceVolumeEnum()
+
+macro=StringToEnum('IceVolume');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IncrementalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IncrementalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IncrementalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IncrementalEnum()
+%INCREMENTALENUM - Enum of Incremental
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IncrementalEnum()
+
+macro=StringToEnum('Incremental');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndependentObjectEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndependentObjectEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndependentObjectEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IndependentObjectEnum()
+
+macro=StringToEnum('IndependentObject');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IndexEnum()
+%INDEXENUM - Enum of Index
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IndexEnum()
+
+macro=StringToEnum('Index');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IndexedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IndexedEnum()
+%INDEXEDENUM - Enum of Indexed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IndexedEnum()
+
+macro=StringToEnum('Indexed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InputEnum()
+%INPUTENUM - Enum of Input
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputEnum()
+
+macro=StringToEnum('Input');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToDepthaverageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToDepthaverageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToDepthaverageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InputToDepthaverageEnum()
+%INPUTTODEPTHAVERAGEENUM - Enum of InputToDepthaverage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToDepthaverageEnum()
+
+macro=StringToEnum('InputToDepthaverage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToExtrudeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToExtrudeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToExtrudeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InputToExtrudeEnum()
+%INPUTTOEXTRUDEENUM - Enum of InputToExtrude
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToExtrudeEnum()
+
+macro=StringToEnum('InputToExtrude');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToL2ProjectEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToL2ProjectEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InputToL2ProjectEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InputToL2ProjectEnum()
+%INPUTTOL2PROJECTENUM - Enum of InputToL2Project
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToL2ProjectEnum()
+
+macro=StringToEnum('InputToL2Project');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntExternalResultEnum()
+%INTEXTERNALRESULTENUM - Enum of IntExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntExternalResultEnum()
+
+macro=StringToEnum('IntExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntInputEnum()
+%INTINPUTENUM - Enum of IntInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntInputEnum()
+
+macro=StringToEnum('IntInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntMatParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntMatParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntMatParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntMatParamEnum()
+%INTMATPARAMENUM - Enum of IntMatParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntMatParamEnum()
+
+macro=StringToEnum('IntMatParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntParamEnum()
+%INTPARAMENUM - Enum of IntParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntParamEnum()
+
+macro=StringToEnum('IntParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntVecParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntVecParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntVecParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntVecParamEnum()
+%INTVECPARAMENUM - Enum of IntVecParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntVecParamEnum()
+
+macro=StringToEnum('IntVecParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InternalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InternalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InternalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InternalEnum()
+%INTERNALENUM - Enum of Internal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InternalEnum()
+
+macro=StringToEnum('Internal');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntersectEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntersectEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/IntersectEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=IntersectEnum()
+%INTERSECTENUM - Enum of Intersect
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IntersectEnum()
+
+macro=StringToEnum('Intersect');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionAlgorithmEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionAlgorithmEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionAlgorithmEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionAlgorithmEnum()
+%INVERSIONALGORITHMENUM - Enum of InversionAlgorithm
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionAlgorithmEnum()
+
+macro=StringToEnum('InversionAlgorithm');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionControlParametersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionControlParametersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionControlParametersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionControlParametersEnum()
+%INVERSIONCONTROLPARAMETERSENUM - Enum of InversionControlParameters
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionControlParametersEnum()
+
+macro=StringToEnum('InversionControlParameters');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionCostFunctionThresholdEnum()
+%INVERSIONCOSTFUNCTIONTHRESHOLDENUM - Enum of InversionCostFunctionThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionThresholdEnum()
+
+macro=StringToEnum('InversionCostFunctionThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsCoefficientsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionCostFunctionsCoefficientsEnum()
+%INVERSIONCOSTFUNCTIONSCOEFFICIENTSENUM - Enum of InversionCostFunctionsCoefficients
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionsCoefficientsEnum()
+
+macro=StringToEnum('InversionCostFunctionsCoefficients');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionCostFunctionsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionCostFunctionsEnum()
+%INVERSIONCOSTFUNCTIONSENUM - Enum of InversionCostFunctions
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionsEnum()
+
+macro=StringToEnum('InversionCostFunctions');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionDxminEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionDxminEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionDxminEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionDxminEnum()
+%INVERSIONDXMINENUM - Enum of InversionDxmin
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionDxminEnum()
+
+macro=StringToEnum('InversionDxmin');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFatolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFatolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFatolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionFatolEnum()
+%INVERSIONFATOLENUM - Enum of InversionFatol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionFatolEnum()
+
+macro=StringToEnum('InversionFatol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFrtolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFrtolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionFrtolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionFrtolEnum()
+%INVERSIONFRTOLENUM - Enum of InversionFrtol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionFrtolEnum()
+
+macro=StringToEnum('InversionFrtol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGatolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGatolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGatolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionGatolEnum()
+%INVERSIONGATOLENUM - Enum of InversionGatol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionGatolEnum()
+
+macro=StringToEnum('InversionGatol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGradientScalingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGradientScalingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGradientScalingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionGradientScalingEnum()
+%INVERSIONGRADIENTSCALINGENUM - Enum of InversionGradientScaling
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionGradientScalingEnum()
+
+macro=StringToEnum('InversionGradientScaling');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGrtolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGrtolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGrtolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionGrtolEnum()
+%INVERSIONGRTOLENUM - Enum of InversionGrtol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionGrtolEnum()
+
+macro=StringToEnum('InversionGrtol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGttolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGttolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionGttolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionGttolEnum()
+%INVERSIONGTTOLENUM - Enum of InversionGttol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionGttolEnum()
+
+macro=StringToEnum('InversionGttol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIncompleteAdjointEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIncompleteAdjointEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIncompleteAdjointEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionIncompleteAdjointEnum()
+%INVERSIONINCOMPLETEADJOINTENUM - Enum of InversionIncompleteAdjoint
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionIncompleteAdjointEnum()
+
+macro=StringToEnum('InversionIncompleteAdjoint');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIscontrolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIscontrolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionIscontrolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionIscontrolEnum()
+%INVERSIONISCONTROLENUM - Enum of InversionIscontrol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionIscontrolEnum()
+
+macro=StringToEnum('InversionIscontrol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxParametersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxParametersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxParametersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionMaxParametersEnum()
+%INVERSIONMAXPARAMETERSENUM - Enum of InversionMaxParameters
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionMaxParametersEnum()
+
+macro=StringToEnum('InversionMaxParameters');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionMaxiterEnum()
+%INVERSIONMAXITERENUM - Enum of InversionMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionMaxiterEnum()
+
+macro=StringToEnum('InversionMaxiter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterPerStepEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionMaxiterPerStepEnum()
+%INVERSIONMAXITERPERSTEPENUM - Enum of InversionMaxiterPerStep
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionMaxiterPerStepEnum()
+
+macro=StringToEnum('InversionMaxiterPerStep');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxstepsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxstepsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMaxstepsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionMaxstepsEnum()
+%INVERSIONMAXSTEPSENUM - Enum of InversionMaxsteps
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionMaxstepsEnum()
+
+macro=StringToEnum('InversionMaxsteps');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMinParametersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMinParametersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionMinParametersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionMinParametersEnum()
+%INVERSIONMINPARAMETERSENUM - Enum of InversionMinParameters
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionMinParametersEnum()
+
+macro=StringToEnum('InversionMinParameters');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNstepsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNstepsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNstepsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionNstepsEnum()
+%INVERSIONNSTEPSENUM - Enum of InversionNsteps
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionNstepsEnum()
+
+macro=StringToEnum('InversionNsteps');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumControlParametersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumControlParametersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumControlParametersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionNumControlParametersEnum()
+%INVERSIONNUMCONTROLPARAMETERSENUM - Enum of InversionNumControlParameters
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionNumControlParametersEnum()
+
+macro=StringToEnum('InversionNumControlParameters');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumCostFunctionsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionNumCostFunctionsEnum()
+%INVERSIONNUMCOSTFUNCTIONSENUM - Enum of InversionNumCostFunctions
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionNumCostFunctionsEnum()
+
+macro=StringToEnum('InversionNumCostFunctions');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionStepThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionStepThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionStepThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionStepThresholdEnum()
+%INVERSIONSTEPTHRESHOLDENUM - Enum of InversionStepThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionStepThresholdEnum()
+
+macro=StringToEnum('InversionStepThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionThicknessObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionThicknessObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionThicknessObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionThicknessObsEnum()
+%INVERSIONTHICKNESSOBSENUM - Enum of InversionThicknessObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionThicknessObsEnum()
+
+macro=StringToEnum('InversionThicknessObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionTypeEnum()
+%INVERSIONTYPEENUM - Enum of InversionType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionTypeEnum()
+
+macro=StringToEnum('InversionType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVxObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVxObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVxObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionVxObsEnum()
+%INVERSIONVXOBSENUM - Enum of InversionVxObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionVxObsEnum()
+
+macro=StringToEnum('InversionVxObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVyObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVyObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVyObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionVyObsEnum()
+%INVERSIONVYOBSENUM - Enum of InversionVyObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionVyObsEnum()
+
+macro=StringToEnum('InversionVyObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVzObsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVzObsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/InversionVzObsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=InversionVzObsEnum()
+%INVERSIONVZOBSENUM - Enum of InversionVzObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionVzObsEnum()
+
+macro=StringToEnum('InversionVzObs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/JEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/JEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/JEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=JEnum()
+%JENUM - Enum of J
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=JEnum()
+
+macro=StringToEnum('J');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L1L2ApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L1L2ApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L1L2ApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=L1L2ApproximationEnum()
+%L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=L1L2ApproximationEnum()
+
+macro=StringToEnum('L1L2Approximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionBaseAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionBaseAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionBaseAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=L2ProjectionBaseAnalysisEnum()
+%L2PROJECTIONBASEANALYSISENUM - Enum of L2ProjectionBaseAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=L2ProjectionBaseAnalysisEnum()
+
+macro=StringToEnum('L2ProjectionBaseAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionEPLAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionEPLAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/L2ProjectionEPLAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=L2ProjectionEPLAnalysisEnum()
+%L2PROJECTIONEPLANALYSISENUM - Enum of L2ProjectionEPLAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=L2ProjectionEPLAnalysisEnum()
+
+macro=StringToEnum('L2ProjectionEPLAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LATaylorHoodEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LATaylorHoodEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LATaylorHoodEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LATaylorHoodEnum()
+%LATAYLORHOODENUM - Enum of LATaylorHood
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LATaylorHoodEnum()
+
+macro=StringToEnum('LATaylorHood');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LevelsetAnalysisEnum()
+%LEVELSETANALYSISENUM - Enum of LevelsetAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LevelsetAnalysisEnum()
+
+macro=StringToEnum('LevelsetAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionPicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionPicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionPicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LevelsetfunctionPicardEnum()
+%LEVELSETFUNCTIONPICARDENUM - Enum of LevelsetfunctionPicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LevelsetfunctionPicardEnum()
+
+macro=StringToEnum('LevelsetfunctionPicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LevelsetfunctionSlopeXEnum()
+%LEVELSETFUNCTIONSLOPEXENUM - Enum of LevelsetfunctionSlopeX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LevelsetfunctionSlopeXEnum()
+
+macro=StringToEnum('LevelsetfunctionSlopeX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LevelsetfunctionSlopeYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LevelsetfunctionSlopeYEnum()
+%LEVELSETFUNCTIONSLOPEYENUM - Enum of LevelsetfunctionSlopeY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LevelsetfunctionSlopeYEnum()
+
+macro=StringToEnum('LevelsetfunctionSlopeY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LinearFloatingMeltRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LinearFloatingMeltRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LinearFloatingMeltRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LinearFloatingMeltRateEnum()
+%LINEARFLOATINGMELTRATEENUM - Enum of LinearFloatingMeltRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LinearFloatingMeltRateEnum()
+
+macro=StringToEnum('LinearFloatingMeltRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LliboutryDuvalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LliboutryDuvalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LliboutryDuvalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LliboutryDuvalEnum()
+%LLIBOUTRYDUVALENUM - Enum of LliboutryDuval
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LliboutryDuvalEnum()
+
+macro=StringToEnum('LliboutryDuval');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LoadingforceXEnum()
+%LOADINGFORCEXENUM - Enum of LoadingforceX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LoadingforceXEnum()
+
+macro=StringToEnum('LoadingforceX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LoadingforceYEnum()
+%LOADINGFORCEYENUM - Enum of LoadingforceY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LoadingforceYEnum()
+
+macro=StringToEnum('LoadingforceY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceZEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceZEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadingforceZEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LoadingforceZEnum()
+%LOADINGFORCEZENUM - Enum of LoadingforceZ
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LoadingforceZEnum()
+
+macro=StringToEnum('LoadingforceZ');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LoadsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LoadsEnum()
+%LOADSENUM - Enum of Loads
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LoadsEnum()
+
+macro=StringToEnum('Loads');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LockFileNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LockFileNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LockFileNameEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LockFileNameEnum()
+
+macro=StringToEnum('LockFileName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LsfReinitializationAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LsfReinitializationAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/LsfReinitializationAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=LsfReinitializationAnalysisEnum()
+%LSFREINITIALIZATIONANALYSISENUM - Enum of LsfReinitializationAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LsfReinitializationAnalysisEnum()
+
+macro=StringToEnum('LsfReinitializationAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MINIEnum()
+%MINIENUM - Enum of MINI
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MINIEnum()
+
+macro=StringToEnum('MINI');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIcondensedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIcondensedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MINIcondensedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MINIcondensedEnum()
+%MINICONDENSEDENUM - Enum of MINIcondensed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MINIcondensedEnum()
+
+macro=StringToEnum('MINIcondensed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskGroundediceLevelsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskGroundediceLevelsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskGroundediceLevelsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaskGroundediceLevelsetEnum()
+%MASKGROUNDEDICELEVELSETENUM - Enum of MaskGroundediceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaskGroundediceLevelsetEnum()
+
+macro=StringToEnum('MaskGroundediceLevelset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskIceLevelsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskIceLevelsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaskIceLevelsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaskIceLevelsetEnum()
+%MASKICELEVELSETENUM - Enum of MaskIceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaskIceLevelsetEnum()
+
+macro=StringToEnum('MaskIceLevelset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MassFluxEnum()
+%MASSFLUXENUM - Enum of MassFlux
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassFluxEnum()
+
+macro=StringToEnum('MassFlux');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassFluxSegmentsEnum()
+
+macro=StringToEnum('MassFluxSegments');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('MassFluxSegmentsPresent');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateEnum()
+%MASSFLUXATGATEENUM - Enum of Massfluxatgate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateEnum()
+
+macro=StringToEnum('Massfluxatgate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateNameEnum()
+%MASSFLUXATGATENAMEENUM - Enum of MassfluxatgateName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateNameEnum()
+
+macro=StringToEnum('MassfluxatgateName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateSegmentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateSegmentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MassfluxatgateSegmentsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateSegmentsEnum()
+%MASSFLUXATGATESEGMENTSENUM - Enum of MassfluxatgateSegments
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateSegmentsEnum()
+
+macro=StringToEnum('MassfluxatgateSegments');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportAnalysisEnum()
+%MASSTRANSPORTANALYSISENUM - Enum of MasstransportAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportAnalysisEnum()
+
+macro=StringToEnum('MasstransportAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportCalvingrateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportCalvingrateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportCalvingrateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportCalvingrateEnum()
+%MASSTRANSPORTCALVINGRATEENUM - Enum of MasstransportCalvingrate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportCalvingrateEnum()
+
+macro=StringToEnum('MasstransportCalvingrate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportHydrostaticAdjustmentEnum()
+%MASSTRANSPORTHYDROSTATICADJUSTMENTENUM - Enum of MasstransportHydrostaticAdjustment
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportHydrostaticAdjustmentEnum()
+
+macro=StringToEnum('MasstransportHydrostaticAdjustment');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportIsfreesurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportIsfreesurfaceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportIsfreesurfaceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportIsfreesurfaceEnum()
+%MASSTRANSPORTISFREESURFACEENUM - Enum of MasstransportIsfreesurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportIsfreesurfaceEnum()
+
+macro=StringToEnum('MasstransportIsfreesurface');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportMinThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportMinThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportMinThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportMinThicknessEnum()
+%MASSTRANSPORTMINTHICKNESSENUM - Enum of MasstransportMinThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportMinThicknessEnum()
+
+macro=StringToEnum('MasstransportMinThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportNumRequestedOutputsEnum()
+%MASSTRANSPORTNUMREQUESTEDOUTPUTSENUM - Enum of MasstransportNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportNumRequestedOutputsEnum()
+
+macro=StringToEnum('MasstransportNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportPenaltyFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportPenaltyFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportPenaltyFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportPenaltyFactorEnum()
+%MASSTRANSPORTPENALTYFACTORENUM - Enum of MasstransportPenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportPenaltyFactorEnum()
+
+macro=StringToEnum('MasstransportPenaltyFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportRequestedOutputsEnum()
+%MASSTRANSPORTREQUESTEDOUTPUTSENUM - Enum of MasstransportRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportRequestedOutputsEnum()
+
+macro=StringToEnum('MasstransportRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportSolutionEnum()
+%MASSTRANSPORTSOLUTIONENUM - Enum of MasstransportSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportSolutionEnum()
+
+macro=StringToEnum('MasstransportSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSpcthicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSpcthicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportSpcthicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportSpcthicknessEnum()
+%MASSTRANSPORTSPCTHICKNESSENUM - Enum of MasstransportSpcthickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportSpcthicknessEnum()
+
+macro=StringToEnum('MasstransportSpcthickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportStabilizationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportStabilizationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportStabilizationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportStabilizationEnum()
+%MASSTRANSPORTSTABILIZATIONENUM - Enum of MasstransportStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportStabilizationEnum()
+
+macro=StringToEnum('MasstransportStabilization');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportVertexPairingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportVertexPairingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MasstransportVertexPairingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MasstransportVertexPairingEnum()
+%MASSTRANSPORTVERTEXPAIRINGENUM - Enum of MasstransportVertexPairing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MasstransportVertexPairingEnum()
+
+macro=StringToEnum('MasstransportVertexPairing');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatdamageiceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatdamageiceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatdamageiceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MatdamageiceEnum()
+%MATDAMAGEICEENUM - Enum of Matdamageice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MatdamageiceEnum()
+
+macro=StringToEnum('Matdamageice');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsBetaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsBetaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsBetaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsBetaEnum()
+%MATERIALSBETAENUM - Enum of MaterialsBeta
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsBetaEnum()
+
+macro=StringToEnum('MaterialsBeta');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsEnum()
+%MATERIALSENUM - Enum of Materials
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsEnum()
+
+macro=StringToEnum('Materials');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsHeatcapacityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsHeatcapacityEnum()
+%MATERIALSHEATCAPACITYENUM - Enum of MaterialsHeatcapacity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsHeatcapacityEnum()
+
+macro=StringToEnum('MaterialsHeatcapacity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLatentheatEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLatentheatEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLatentheatEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsLatentheatEnum()
+%MATERIALSLATENTHEATENUM - Enum of MaterialsLatentheat
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsLatentheatEnum()
+
+macro=StringToEnum('MaterialsLatentheat');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereDensityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereDensityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereDensityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsLithosphereDensityEnum()
+%MATERIALSLITHOSPHEREDENSITYENUM - Enum of MaterialsLithosphereDensity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsLithosphereDensityEnum()
+
+macro=StringToEnum('MaterialsLithosphereDensity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereShearModulusEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereShearModulusEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsLithosphereShearModulusEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsLithosphereShearModulusEnum()
+%MATERIALSLITHOSPHERESHEARMODULUSENUM - Enum of MaterialsLithosphereShearModulus
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsLithosphereShearModulusEnum()
+
+macro=StringToEnum('MaterialsLithosphereShearModulus');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleDensityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleDensityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleDensityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsMantleDensityEnum()
+%MATERIALSMANTLEDENSITYENUM - Enum of MaterialsMantleDensity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsMantleDensityEnum()
+
+macro=StringToEnum('MaterialsMantleDensity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleShearModulusEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleShearModulusEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMantleShearModulusEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsMantleShearModulusEnum()
+%MATERIALSMANTLESHEARMODULUSENUM - Enum of MaterialsMantleShearModulus
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsMantleShearModulusEnum()
+
+macro=StringToEnum('MaterialsMantleShearModulus');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMeltingpointEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMeltingpointEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMeltingpointEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsMeltingpointEnum()
+%MATERIALSMELTINGPOINTENUM - Enum of MaterialsMeltingpoint
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsMeltingpointEnum()
+
+macro=StringToEnum('MaterialsMeltingpoint');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMixedLayerCapacityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsMixedLayerCapacityEnum()
+%MATERIALSMIXEDLAYERCAPACITYENUM - Enum of MaterialsMixedLayerCapacity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsMixedLayerCapacityEnum()
+
+macro=StringToEnum('MaterialsMixedLayerCapacity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMuWaterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMuWaterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsMuWaterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsMuWaterEnum()
+%MATERIALSMUWATERENUM - Enum of MaterialsMuWater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsMuWaterEnum()
+
+macro=StringToEnum('MaterialsMuWater');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyBEnum()
+%MATERIALSRHEOLOGYBENUM - Enum of MaterialsRheologyB
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyBEnum()
+
+macro=StringToEnum('MaterialsRheologyB');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBbarEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyBbarEnum()
+%MATERIALSRHEOLOGYBBARENUM - Enum of MaterialsRheologyBbar
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyBbarEnum()
+
+macro=StringToEnum('MaterialsRheologyBbar');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyLawEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyLawEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyLawEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyLawEnum()
+%MATERIALSRHEOLOGYLAWENUM - Enum of MaterialsRheologyLaw
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyLawEnum()
+
+macro=StringToEnum('MaterialsRheologyLaw');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyNEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyNEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRheologyNEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyNEnum()
+%MATERIALSRHEOLOGYNENUM - Enum of MaterialsRheologyN
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyNEnum()
+
+macro=StringToEnum('MaterialsRheologyN');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoFreshwaterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRhoFreshwaterEnum()
+%MATERIALSRHOFRESHWATERENUM - Enum of MaterialsRhoFreshwater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRhoFreshwaterEnum()
+
+macro=StringToEnum('MaterialsRhoFreshwater');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoIceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoIceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoIceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRhoIceEnum()
+%MATERIALSRHOICEENUM - Enum of MaterialsRhoIce
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRhoIceEnum()
+
+macro=StringToEnum('MaterialsRhoIce');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoSeawaterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoSeawaterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsRhoSeawaterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsRhoSeawaterEnum()
+%MATERIALSRHOSEAWATERENUM - Enum of MaterialsRhoSeawater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsRhoSeawaterEnum()
+
+macro=StringToEnum('MaterialsRhoSeawater');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsTemperateiceconductivityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsTemperateiceconductivityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsTemperateiceconductivityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsTemperateiceconductivityEnum()
+%MATERIALSTEMPERATEICECONDUCTIVITYENUM - Enum of MaterialsTemperateiceconductivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsTemperateiceconductivityEnum()
+
+macro=StringToEnum('MaterialsTemperateiceconductivity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalExchangeVelocityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsThermalExchangeVelocityEnum()
+%MATERIALSTHERMALEXCHANGEVELOCITYENUM - Enum of MaterialsThermalExchangeVelocity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsThermalExchangeVelocityEnum()
+
+macro=StringToEnum('MaterialsThermalExchangeVelocity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalconductivityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaterialsThermalconductivityEnum()
+%MATERIALSTHERMALCONDUCTIVITYENUM - Enum of MaterialsThermalconductivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaterialsThermalconductivityEnum()
+
+macro=StringToEnum('MaterialsThermalconductivity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaticeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaticeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaticeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaticeEnum()
+%MATICEENUM - Enum of Matice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaticeEnum()
+
+macro=StringToEnum('Matice');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatparEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatparEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatparEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MatparEnum()
+%MATPARENUM - Enum of Matpar
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MatparEnum()
+
+macro=StringToEnum('Matpar');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatrixParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatrixParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MatrixParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MatrixParamEnum()
+%MATRIXPARAMENUM - Enum of MatrixParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MatrixParamEnum()
+
+macro=StringToEnum('MatrixParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxAbsVxEnum()
+%MAXABSVXENUM - Enum of MaxAbsVx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVxEnum()
+
+macro=StringToEnum('MaxAbsVx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxAbsVyEnum()
+%MAXABSVYENUM - Enum of MaxAbsVy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVyEnum()
+
+macro=StringToEnum('MaxAbsVy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxAbsVzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxAbsVzEnum()
+%MAXABSVZENUM - Enum of MaxAbsVz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVzEnum()
+
+macro=StringToEnum('MaxAbsVz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxIterationConvergenceFlagEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxIterationConvergenceFlagEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxIterationConvergenceFlagEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxIterationConvergenceFlagEnum()
+%MAXITERATIONCONVERGENCEFLAGENUM - Enum of MaxIterationConvergenceFlag
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxIterationConvergenceFlagEnum()
+
+macro=StringToEnum('MaxIterationConvergenceFlag');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVelEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVelEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVelEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxVelEnum()
+%MAXVELENUM - Enum of MaxVel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxVelEnum()
+
+macro=StringToEnum('MaxVel');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxVxEnum()
+%MAXVXENUM - Enum of MaxVx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxVxEnum()
+
+macro=StringToEnum('MaxVx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxVyEnum()
+%MAXVYENUM - Enum of MaxVy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxVyEnum()
+
+macro=StringToEnum('MaxVy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaxVzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaxVzEnum()
+%MAXVZENUM - Enum of MaxVz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxVzEnum()
+
+macro=StringToEnum('MaxVz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaximumNumberOfDefinitionsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaximumNumberOfDefinitionsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MaximumNumberOfDefinitionsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MaximumNumberOfDefinitionsEnum()
+%MAXIMUMNUMBEROFDEFINITIONSENUM - Enum of MaximumNumberOfDefinitions
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaximumNumberOfDefinitionsEnum()
+
+macro=StringToEnum('MaximumNumberOfDefinitions');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MelangeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MelangeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MelangeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MelangeEnum()
+%MELANGEENUM - Enum of Melange
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MelangeEnum()
+
+macro=StringToEnum('Melange');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeltingAnalysisEnum()
+%MELTINGANALYSISENUM - Enum of MeltingAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeltingAnalysisEnum()
+
+macro=StringToEnum('MeltingAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingOffsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingOffsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeltingOffsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeltingOffsetEnum()
+%MELTINGOFFSETENUM - Enum of MeltingOffset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeltingOffsetEnum()
+
+macro=StringToEnum('MeltingOffset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshAverageVertexConnectivityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshAverageVertexConnectivityEnum()
+%MESHAVERAGEVERTEXCONNECTIVITYENUM - Enum of MeshAverageVertexConnectivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshAverageVertexConnectivityEnum()
+
+macro=StringToEnum('MeshAverageVertexConnectivity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElements2dEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElements2dEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElements2dEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshElements2dEnum()
+%MESHELEMENTS2DENUM - Enum of MeshElements2d
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshElements2dEnum()
+
+macro=StringToEnum('MeshElements2d');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshElementsEnum()
+%MESHELEMENTSENUM - Enum of MeshElements
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshElementsEnum()
+
+macro=StringToEnum('MeshElements');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementtypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementtypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshElementtypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshElementtypeEnum()
+%MESHELEMENTTYPEENUM - Enum of MeshElementtype
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshElementtypeEnum()
+
+macro=StringToEnum('MeshElementtype');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshLowerelementsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshLowerelementsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshLowerelementsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshLowerelementsEnum()
+%MESHLOWERELEMENTSENUM - Enum of MeshLowerelements
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshLowerelementsEnum()
+
+macro=StringToEnum('MeshLowerelements');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelements2dEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelements2dEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelements2dEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshNumberofelements2dEnum()
+%MESHNUMBEROFELEMENTS2DENUM - Enum of MeshNumberofelements2d
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofelements2dEnum()
+
+macro=StringToEnum('MeshNumberofelements2d');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelementsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelementsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofelementsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshNumberofelementsEnum()
+%MESHNUMBEROFELEMENTSENUM - Enum of MeshNumberofelements
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofelementsEnum()
+
+macro=StringToEnum('MeshNumberofelements');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberoflayersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberoflayersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberoflayersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshNumberoflayersEnum()
+%MESHNUMBEROFLAYERSENUM - Enum of MeshNumberoflayers
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshNumberoflayersEnum()
+
+macro=StringToEnum('MeshNumberoflayers');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofvertices2dEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshNumberofvertices2dEnum()
+%MESHNUMBEROFVERTICES2DENUM - Enum of MeshNumberofvertices2d
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofvertices2dEnum()
+
+macro=StringToEnum('MeshNumberofvertices2d');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofverticesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofverticesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshNumberofverticesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshNumberofverticesEnum()
+%MESHNUMBEROFVERTICESENUM - Enum of MeshNumberofvertices
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofverticesEnum()
+
+macro=StringToEnum('MeshNumberofvertices');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshUpperelementsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshUpperelementsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshUpperelementsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshUpperelementsEnum()
+%MESHUPPERELEMENTSENUM - Enum of MeshUpperelements
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshUpperelementsEnum()
+
+macro=StringToEnum('MeshUpperelements');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonbaseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonbaseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonbaseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshVertexonbaseEnum()
+%MESHVERTEXONBASEENUM - Enum of MeshVertexonbase
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshVertexonbaseEnum()
+
+macro=StringToEnum('MeshVertexonbase');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonboundaryEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonboundaryEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonboundaryEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshVertexonboundaryEnum()
+%MESHVERTEXONBOUNDARYENUM - Enum of MeshVertexonboundary
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshVertexonboundaryEnum()
+
+macro=StringToEnum('MeshVertexonboundary');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonsurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshVertexonsurfaceEnum()
+%MESHVERTEXONSURFACEENUM - Enum of MeshVertexonsurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshVertexonsurfaceEnum()
+
+macro=StringToEnum('MeshVertexonsurface');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshXEnum()
+%MESHXENUM - Enum of MeshX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshXEnum()
+
+macro=StringToEnum('MeshX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshYEnum()
+%MESHYENUM - Enum of MeshY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshYEnum()
+
+macro=StringToEnum('MeshY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshZEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshZEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshZEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshZEnum()
+%MESHZENUM - Enum of MeshZ
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshZEnum()
+
+macro=StringToEnum('MeshZ');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshdeformationAnalysisEnum()
+%MESHDEFORMATIONANALYSISENUM - Enum of MeshdeformationAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshdeformationAnalysisEnum()
+
+macro=StringToEnum('MeshdeformationAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MeshdeformationSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MeshdeformationSolutionEnum()
+%MESHDEFORMATIONSOLUTIONENUM - Enum of MeshdeformationSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MeshdeformationSolutionEnum()
+
+macro=StringToEnum('MeshdeformationSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVelEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVelEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVelEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MinVelEnum()
+%MINVELENUM - Enum of MinVel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MinVelEnum()
+
+macro=StringToEnum('MinVel');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MinVxEnum()
+%MINVXENUM - Enum of MinVx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MinVxEnum()
+
+macro=StringToEnum('MinVx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MinVyEnum()
+%MINVYENUM - Enum of MinVy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MinVyEnum()
+
+macro=StringToEnum('MinVy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MinVzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MinVzEnum()
+%MINVZENUM - Enum of MinVz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MinVzEnum()
+
+macro=StringToEnum('MinVz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MiscellaneousNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MiscellaneousNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MiscellaneousNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MiscellaneousNameEnum()
+%MISCELLANEOUSNAMEENUM - Enum of MiscellaneousName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MiscellaneousNameEnum()
+
+macro=StringToEnum('MiscellaneousName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitEnum()
+%MISFITENUM - Enum of Misfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitEnum()
+
+macro=StringToEnum('Misfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitModelEnumEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitModelEnumEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitModelEnumEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitModelEnumEnum()
+%MISFITMODELENUMENUM - Enum of MisfitModel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitModelEnumEnum()
+
+macro=StringToEnum('MisfitModel');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitNameEnum()
+%MISFITNAMEENUM - Enum of MisfitName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitNameEnum()
+
+macro=StringToEnum('MisfitName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitObservationEnum()
+%MISFITOBSERVATIONENUM - Enum of MisfitObservation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitObservationEnum()
+
+macro=StringToEnum('MisfitObservation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnumEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnumEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitObservationEnumEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitObservationEnumEnum()
+%MISFITOBSERVATIONENUMENUM - Enum of MisfitObservation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitObservationEnumEnum()
+
+macro=StringToEnum('MisfitObservation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitTimeinterpolationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitTimeinterpolationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitTimeinterpolationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitTimeinterpolationEnum()
+%MISFITTIMEINTERPOLATIONENUM - Enum of MisfitTimeinterpolation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitTimeinterpolationEnum()
+
+macro=StringToEnum('MisfitTimeinterpolation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitWeightsEnum()
+%MISFITWEIGHTSENUM - Enum of MisfitWeights
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitWeightsEnum()
+
+macro=StringToEnum('MisfitWeights');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnumEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnumEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MisfitWeightsEnumEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MisfitWeightsEnumEnum()
+%MISFITWEIGHTSENUMENUM - Enum of MisfitWeights
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitWeightsEnumEnum()
+
+macro=StringToEnum('MisfitWeights');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiDenseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiDenseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiDenseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MpiDenseEnum()
+%MPIDENSEENUM - Enum of MpiDense
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MpiDenseEnum()
+
+macro=StringToEnum('MpiDense');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MpiEnum()
+%MPIENUM - Enum of Mpi
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MpiEnum()
+
+macro=StringToEnum('Mpi');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiSparseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiSparseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MpiSparseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MpiSparseEnum()
+%MPISPARSEENUM - Enum of MpiSparse
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MpiSparseEnum()
+
+macro=StringToEnum('MpiSparse');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MumpsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MumpsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/MumpsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=MumpsEnum()
+%MUMPSENUM - Enum of Mumps
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MumpsEnum()
+
+macro=StringToEnum('Mumps');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NearestInterpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NearestInterpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NearestInterpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NearestInterpEnum()
+%NEARESTINTERPENUM - Enum of NearestInterp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NearestInterpEnum()
+
+macro=StringToEnum('NearestInterp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NewDamageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NewDamageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NewDamageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NewDamageEnum()
+%NEWDAMAGEENUM - Enum of NewDamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NewDamageEnum()
+
+macro=StringToEnum('NewDamage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NodalEnum()
+%NODALENUM - Enum of Nodal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NodalEnum()
+
+macro=StringToEnum('Nodal');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NodeEnum()
+%NODEENUM - Enum of Node
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NodeEnum()
+
+macro=StringToEnum('Node');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeSIdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeSIdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodeSIdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NodeSIdEnum()
+%NODESIDENUM - Enum of NodeSId
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NodeSIdEnum()
+
+macro=StringToEnum('NodeSId');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NodesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NodesEnum()
+%NODESENUM - Enum of Nodes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NodesEnum()
+
+macro=StringToEnum('Nodes');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NoneApproximationEnum()
+%NONEAPPROXIMATIONENUM - Enum of NoneApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NoneApproximationEnum()
+
+macro=StringToEnum('NoneApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NoneEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NoneEnum()
+%NONEENUM - Enum of None
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NoneEnum()
+
+macro=StringToEnum('None');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NumericalfluxEnum()
+%NUMERICALFLUXENUM - Enum of Numericalflux
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NumericalfluxEnum()
+
+macro=StringToEnum('Numericalflux');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/NumericalfluxTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=NumericalfluxTypeEnum()
+%NUMERICALFLUXTYPEENUM - Enum of NumericalfluxType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NumericalfluxTypeEnum()
+
+macro=StringToEnum('NumericalfluxType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OldGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OldGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OldGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OldGradientEnum()
+%OLDGRADIENTENUM - Enum of OldGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OldGradientEnum()
+
+macro=StringToEnum('OldGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OneLayerP4zEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OneLayerP4zEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OneLayerP4zEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OneLayerP4zEnum()
+%ONELAYERP4ZENUM - Enum of OneLayerP4z
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OneLayerP4zEnum()
+
+macro=StringToEnum('OneLayerP4z');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OpenEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OpenEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OpenEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OpenEnum()
+%OPENENUM - Enum of Open
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OpenEnum()
+
+macro=StringToEnum('Open');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionCellEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionCellEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionCellEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OptionCellEnum()
+%OPTIONCELLENUM - Enum of OptionCell
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OptionCellEnum()
+
+macro=StringToEnum('OptionCell');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OptionEnum()
+%OPTIONENUM - Enum of Option
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OptionEnum()
+
+macro=StringToEnum('Option');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionStructEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionStructEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OptionStructEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OptionStructEnum()
+%OPTIONSTRUCTENUM - Enum of OptionStruct
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OptionStructEnum()
+
+macro=StringToEnum('OptionStruct');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFileNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFileNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFileNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OutputFileNameEnum()
+%OUTPUTFILENAMEENUM - Enum of OutputFileName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputFileNameEnum()
+
+macro=StringToEnum('OutputFileName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFilePointerEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFilePointerEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputFilePointerEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OutputFilePointerEnum()
+%OUTPUTFILEPOINTERENUM - Enum of OutputFilePointer
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputFilePointerEnum()
+
+macro=StringToEnum('OutputFilePointer');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OutputdefinitionEnum()
+%OUTPUTDEFINITIONENUM - Enum of Outputdefinition
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputdefinitionEnum()
+
+macro=StringToEnum('Outputdefinition');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionListEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionListEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/OutputdefinitionListEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=OutputdefinitionListEnum()
+%OUTPUTDEFINITIONLISTENUM - Enum of OutputdefinitionList
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=OutputdefinitionListEnum()
+
+macro=StringToEnum('OutputdefinitionList');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P0Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P0Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P0Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P0Enum()
+%P0ENUM - Enum of P0
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P0Enum()
+
+macro=StringToEnum('P0');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1DGEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1DGEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1DGEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1DGEnum()
+%P1DGENUM - Enum of P1DG
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1DGEnum()
+
+macro=StringToEnum('P1DG');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1Enum()
+%P1ENUM - Enum of P1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1Enum()
+
+macro=StringToEnum('P1');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1P1Enum()
+%P1P1ENUM - Enum of P1P1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1P1Enum()
+
+macro=StringToEnum('P1P1');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1GLSEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1GLSEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1P1GLSEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1P1GLSEnum()
+%P1P1GLSENUM - Enum of P1P1GLS
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1P1GLSEnum()
+
+macro=StringToEnum('P1P1GLS');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubbleEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubbleEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubbleEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1bubbleEnum()
+%P1BUBBLEENUM - Enum of P1bubble
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1bubbleEnum()
+
+macro=StringToEnum('P1bubble');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubblecondensedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubblecondensedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1bubblecondensedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1bubblecondensedEnum()
+%P1BUBBLECONDENSEDENUM - Enum of P1bubblecondensed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1bubblecondensedEnum()
+
+macro=StringToEnum('P1bubblecondensed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1xP2Enum()
+%P1XP2ENUM - Enum of P1xP2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1xP2Enum()
+
+macro=StringToEnum('P1xP2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP3Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP3Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P1xP3Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P1xP3Enum()
+%P1XP3ENUM - Enum of P1xP3
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P1xP3Enum()
+
+macro=StringToEnum('P1xP3');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P2Enum()
+%P2ENUM - Enum of P2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2Enum()
+
+macro=StringToEnum('P2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubbleEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubbleEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubbleEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P2bubbleEnum()
+%P2BUBBLEENUM - Enum of P2bubble
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2bubbleEnum()
+
+macro=StringToEnum('P2bubble');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubblecondensedEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubblecondensedEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2bubblecondensedEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P2bubblecondensedEnum()
+%P2BUBBLECONDENSEDENUM - Enum of P2bubblecondensed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2bubblecondensedEnum()
+
+macro=StringToEnum('P2bubblecondensed');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP1Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP1Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP1Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P2xP1Enum()
+%P2XP1ENUM - Enum of P2xP1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2xP1Enum()
+
+macro=StringToEnum('P2xP1');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP4Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP4Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/P2xP4Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=P2xP4Enum()
+%P2XP4ENUM - Enum of P2xP4
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2xP4Enum()
+
+macro=StringToEnum('P2xP4');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ParamEnum()
+%PARAMENUM - Enum of Param
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ParamEnum()
+
+macro=StringToEnum('Param');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParametersEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParametersEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ParametersEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ParametersEnum()
+%PARAMETERSENUM - Enum of Parameters
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ParametersEnum()
+
+macro=StringToEnum('Parameters');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PatersonEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PatersonEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PatersonEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PatersonEnum()
+%PATERSONENUM - Enum of Paterson
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PatersonEnum()
+
+macro=StringToEnum('Paterson');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PengridEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PengridEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PengridEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PengridEnum()
+%PENGRIDENUM - Enum of Pengrid
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PengridEnum()
+
+macro=StringToEnum('Pengrid');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PenpairEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PenpairEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PenpairEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PenpairEnum()
+%PENPAIRENUM - Enum of Penpair
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PenpairEnum()
+
+macro=StringToEnum('Penpair');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PentaEnum()
+%PENTAENUM - Enum of Penta
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PentaEnum()
+
+macro=StringToEnum('Penta');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PentaInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PentaInputEnum()
+%PENTAINPUTENUM - Enum of PentaInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PentaInputEnum()
+
+macro=StringToEnum('PentaInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PotentialEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PotentialEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PotentialEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PotentialEnum()
+%POTENTIALENUM - Enum of Potential
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PotentialEnum()
+
+macro=StringToEnum('Potential');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PressureEnum()
+%PRESSUREENUM - Enum of Pressure
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PressureEnum()
+
+macro=StringToEnum('Pressure');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressurePicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressurePicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/PressurePicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=PressurePicardEnum()
+%PRESSUREPICARDENUM - Enum of PressurePicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=PressurePicardEnum()
+
+macro=StringToEnum('PressurePicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilerEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilerEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilerEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ProfilerEnum()
+
+macro=StringToEnum('Profiler');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentFlopsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ProfilingCurrentFlopsEnum()
+%PROFILINGCURRENTFLOPSENUM - Enum of ProfilingCurrentFlops
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ProfilingCurrentFlopsEnum()
+
+macro=StringToEnum('ProfilingCurrentFlops');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentMemEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentMemEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingCurrentMemEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ProfilingCurrentMemEnum()
+%PROFILINGCURRENTMEMENUM - Enum of ProfilingCurrentMem
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ProfilingCurrentMemEnum()
+
+macro=StringToEnum('ProfilingCurrentMem');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingSolutionTimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ProfilingSolutionTimeEnum()
+%PROFILINGSOLUTIONTIMEENUM - Enum of ProfilingSolutionTime
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ProfilingSolutionTimeEnum()
+
+macro=StringToEnum('ProfilingSolutionTime');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuBaseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuBaseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuBaseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuBaseEnum()
+%QMUBASEENUM - Enum of QmuBase
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuBaseEnum()
+
+macro=StringToEnum('QmuBase');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuDamageDEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuDamageDEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuDamageDEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuDamageDEnum()
+%QMUDAMAGEDENUM - Enum of QmuDamageD
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuDamageDEnum()
+
+macro=StringToEnum('QmuDamageD');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuErrNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuErrNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuErrNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuErrNameEnum()
+%QMUERRNAMEENUM - Enum of QmuErrName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuErrNameEnum()
+
+macro=StringToEnum('QmuErrName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuInNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuInNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuInNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuInNameEnum()
+%QMUINNAMEENUM - Enum of QmuInName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuInNameEnum()
+
+macro=StringToEnum('QmuInName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuIsdakotaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuIsdakotaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuIsdakotaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuIsdakotaEnum()
+%QMUISDAKOTAENUM - Enum of QmuIsdakota
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuIsdakotaEnum()
+
+macro=StringToEnum('QmuIsdakota');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskGroundediceLevelsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskGroundediceLevelsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskGroundediceLevelsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuMaskGroundediceLevelsetEnum()
+%QMUMASKGROUNDEDICELEVELSETENUM - Enum of QmuMaskGroundediceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMaskGroundediceLevelsetEnum()
+
+macro=StringToEnum('QmuMaskGroundediceLevelset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskIceLevelsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskIceLevelsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaskIceLevelsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuMaskIceLevelsetEnum()
+%QMUMASKICELEVELSETENUM - Enum of QmuMaskIceLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMaskIceLevelsetEnum()
+
+macro=StringToEnum('QmuMaskIceLevelset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('QmuMassFluxSegmentsPresent');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaterialsRheologyBEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaterialsRheologyBEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMaterialsRheologyBEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuMaterialsRheologyBEnum()
+%QMUMATERIALSRHEOLOGYBENUM - Enum of QmuMaterialsRheologyB
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMaterialsRheologyBEnum()
+
+macro=StringToEnum('QmuMaterialsRheologyB');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMeltingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMeltingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuMeltingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuMeltingEnum()
+%QMUMELTINGENUM - Enum of QmuMelting
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuMeltingEnum()
+
+macro=StringToEnum('QmuMelting');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofpartitionsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuNumberofpartitionsEnum()
+%QMUNUMBEROFPARTITIONSENUM - Enum of QmuNumberofpartitions
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuNumberofpartitionsEnum()
+
+macro=StringToEnum('QmuNumberofpartitions');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofresponsesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofresponsesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuNumberofresponsesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuNumberofresponsesEnum()
+%QMUNUMBEROFRESPONSESENUM - Enum of QmuNumberofresponses
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuNumberofresponsesEnum()
+
+macro=StringToEnum('QmuNumberofresponses');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuOutNameEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuOutNameEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuOutNameEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuOutNameEnum()
+%QMUOUTNAMEENUM - Enum of QmuOutName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuOutNameEnum()
+
+macro=StringToEnum('QmuOutName');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPartitionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPartitionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPartitionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuPartitionEnum()
+%QMUPARTITIONENUM - Enum of QmuPartition
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuPartitionEnum()
+
+macro=StringToEnum('QmuPartition');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPressureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPressureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuPressureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuPressureEnum()
+%QMUPRESSUREENUM - Enum of QmuPressure
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuPressureEnum()
+
+macro=StringToEnum('QmuPressure');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuResponsedescriptorsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuResponsedescriptorsEnum()
+%QMURESPONSEDESCRIPTORSENUM - Enum of QmuResponsedescriptors
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuResponsedescriptorsEnum()
+
+macro=StringToEnum('QmuResponsedescriptors');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuSurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuSurfaceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuSurfaceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuSurfaceEnum()
+%QMUSURFACEENUM - Enum of QmuSurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuSurfaceEnum()
+
+macro=StringToEnum('QmuSurface');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuTemperatureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuTemperatureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuTemperatureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuTemperatureEnum()
+%QMUTEMPERATUREENUM - Enum of QmuTemperature
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuTemperatureEnum()
+
+macro=StringToEnum('QmuTemperature');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuThicknessEnum()
+%QMUTHICKNESSENUM - Enum of QmuThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuThicknessEnum()
+
+macro=StringToEnum('QmuThickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVariabledescriptorsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVariabledescriptorsEnum()
+%QMUVARIABLEDESCRIPTORSENUM - Enum of QmuVariabledescriptors
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVariabledescriptorsEnum()
+
+macro=StringToEnum('QmuVariabledescriptors');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVxEnum()
+%QMUVXENUM - Enum of QmuVx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVxEnum()
+
+macro=StringToEnum('QmuVx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVxMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVxMeshEnum()
+%QMUVXMESHENUM - Enum of QmuVxMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVxMeshEnum()
+
+macro=StringToEnum('QmuVxMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVyEnum()
+%QMUVYENUM - Enum of QmuVy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVyEnum()
+
+macro=StringToEnum('QmuVy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVyMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVyMeshEnum()
+%QMUVYMESHENUM - Enum of QmuVyMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVyMeshEnum()
+
+macro=StringToEnum('QmuVyMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVzEnum()
+%QMUVZENUM - Enum of QmuVz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVzEnum()
+
+macro=StringToEnum('QmuVz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/QmuVzMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=QmuVzMeshEnum()
+%QMUVZMESHENUM - Enum of QmuVzMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=QmuVzMeshEnum()
+
+macro=StringToEnum('QmuVzMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RegularEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RegularEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RegularEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RegularEnum()
+%REGULARENUM - Enum of Regular
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RegularEnum()
+
+macro=StringToEnum('Regular');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResetPenaltiesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResetPenaltiesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResetPenaltiesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ResetPenaltiesEnum()
+%RESETPENALTIESENUM - Enum of ResetPenalties
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ResetPenaltiesEnum()
+
+macro=StringToEnum('ResetPenalties');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResultsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResultsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ResultsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ResultsEnum()
+%RESULTSENUM - Enum of Results
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ResultsEnum()
+
+macro=StringToEnum('Results');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RheologyBbarAbsGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RheologyBbarAbsGradientEnum()
+%RHEOLOGYBBARABSGRADIENTENUM - Enum of RheologyBbarAbsGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RheologyBbarAbsGradientEnum()
+
+macro=StringToEnum('RheologyBbarAbsGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RiftfrontEnum()
+%RIFTFRONTENUM - Enum of Riftfront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RiftfrontEnum()
+
+macro=StringToEnum('Riftfront');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftfrontTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RiftfrontTypeEnum()
+%RIFTFRONTTYPEENUM - Enum of RiftfrontType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RiftfrontTypeEnum()
+
+macro=StringToEnum('RiftfrontType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsNumriftsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsNumriftsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsNumriftsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RiftsNumriftsEnum()
+%RIFTSNUMRIFTSENUM - Enum of RiftsNumrifts
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RiftsNumriftsEnum()
+
+macro=StringToEnum('RiftsNumrifts');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsRiftstructEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsRiftstructEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/RiftsRiftstructEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=RiftsRiftstructEnum()
+%RIFTSRIFTSTRUCTENUM - Enum of RiftsRiftstruct
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RiftsRiftstructEnum()
+
+macro=StringToEnum('RiftsRiftstruct');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SIAApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SIAApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SIAApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SIAApproximationEnum()
+%SIAAPPROXIMATIONENUM - Enum of SIAApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SIAApproximationEnum()
+
+macro=StringToEnum('SIAApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBEnum()
+%SMBENUM - Enum of SMB
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBEnum()
+
+macro=StringToEnum('SMB');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBcomponentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBcomponentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBcomponentsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBcomponentsEnum()
+%SMBCOMPONENTSENUM - Enum of SMBcomponents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBcomponentsEnum()
+
+macro=StringToEnum('SMBcomponents');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBgradientsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBgradientsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBgradientsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBgradientsEnum()
+%SMBGRADIENTSENUM - Enum of SMBgradients
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBgradientsEnum()
+
+macro=StringToEnum('SMBgradients');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBhenningEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBhenningEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBhenningEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBhenningEnum()
+%SMBHENNINGENUM - Enum of SMBhenning
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBhenningEnum()
+
+macro=StringToEnum('SMBhenning');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBmeltcomponentsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBmeltcomponentsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBmeltcomponentsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBmeltcomponentsEnum()
+%SMBMELTCOMPONENTSENUM - Enum of SMBmeltcomponents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBmeltcomponentsEnum()
+
+macro=StringToEnum('SMBmeltcomponents');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBpddEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBpddEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SMBpddEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SMBpddEnum()
+%SMBPDDENUM - Enum of SMBpdd
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBpddEnum()
+
+macro=StringToEnum('SMBpdd');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SSAApproximationEnum()
+%SSAAPPROXIMATIONENUM - Enum of SSAApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SSAApproximationEnum()
+
+macro=StringToEnum('SSAApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAFSApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAFSApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAFSApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SSAFSApproximationEnum()
+%SSAFSAPPROXIMATIONENUM - Enum of SSAFSApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SSAFSApproximationEnum()
+
+macro=StringToEnum('SSAFSApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAHOApproximationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAHOApproximationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SSAHOApproximationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SSAHOApproximationEnum()
+%SSAHOAPPROXIMATIONENUM - Enum of SSAHOApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SSAHOApproximationEnum()
+
+macro=StringToEnum('SSAHOApproximation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SaveResultsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SaveResultsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SaveResultsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SaveResultsEnum()
+%SAVERESULTSENUM - Enum of SaveResults
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SaveResultsEnum()
+
+macro=StringToEnum('SaveResults');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ScaledEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ScaledEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ScaledEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ScaledEnum()
+%SCALEDENUM - Enum of Scaled
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ScaledEnum()
+
+macro=StringToEnum('Scaled');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SedimentHeadEnum()
+%SEDIMENTHEADENUM - Enum of SedimentHead
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SedimentHeadEnum()
+
+macro=StringToEnum('SedimentHead');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadOldEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadOldEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadOldEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SedimentHeadOldEnum()
+%SEDIMENTHEADOLDENUM - Enum of SedimentHeadOld
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SedimentHeadOldEnum()
+
+macro=StringToEnum('SedimentHeadOld');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadResidualEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadResidualEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SedimentHeadResidualEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SedimentHeadResidualEnum()
+%SEDIMENTHEADRESIDUALENUM - Enum of SedimentHeadResidual
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SedimentHeadResidualEnum()
+
+macro=StringToEnum('SedimentHeadResidual');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SegEnum()
+%SEGENUM - Enum of Seg
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegEnum()
+
+macro=StringToEnum('Seg');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SegInputEnum()
+%SEGINPUTENUM - Enum of SegInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegInputEnum()
+
+macro=StringToEnum('SegInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SegmentEnum()
+%SEGMENTENUM - Enum of Segment
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegmentEnum()
+
+macro=StringToEnum('Segment');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentOnIceShelfEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentOnIceShelfEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentOnIceShelfEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SegmentOnIceShelfEnum()
+%SEGMENTONICESHELFENUM - Enum of SegmentOnIceShelf
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegmentOnIceShelfEnum()
+
+macro=StringToEnum('SegmentOnIceShelf');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentRiftfrontEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentRiftfrontEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SegmentRiftfrontEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SegmentRiftfrontEnum()
+%SEGMENTRIFTFRONTENUM - Enum of SegmentRiftfront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SegmentRiftfrontEnum()
+
+macro=StringToEnum('SegmentRiftfront');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeparateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeparateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeparateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SeparateEnum()
+%SEPARATEENUM - Enum of Separate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SeparateEnum()
+
+macro=StringToEnum('Separate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeqEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeqEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SeqEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SeqEnum()
+%SEQENUM - Enum of Seq
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SeqEnum()
+
+macro=StringToEnum('Seq');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsIoGatherEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsIoGatherEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsIoGatherEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SettingsIoGatherEnum()
+%SETTINGSIOGATHERENUM - Enum of SettingsIoGather
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SettingsIoGatherEnum()
+
+macro=StringToEnum('SettingsIoGather');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsLowmemEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsLowmemEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsLowmemEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SettingsLowmemEnum()
+%SETTINGSLOWMEMENUM - Enum of SettingsLowmem
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SettingsLowmemEnum()
+
+macro=StringToEnum('SettingsLowmem');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsOutputFrequencyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SettingsOutputFrequencyEnum()
+%SETTINGSOUTPUTFREQUENCYENUM - Enum of SettingsOutputFrequency
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SettingsOutputFrequencyEnum()
+
+macro=StringToEnum('SettingsOutputFrequency');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsResultsOnNodesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsResultsOnNodesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsResultsOnNodesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SettingsResultsOnNodesEnum()
+%SETTINGSRESULTSONNODESENUM - Enum of SettingsResultsOnNodes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SettingsResultsOnNodesEnum()
+
+macro=StringToEnum('SettingsResultsOnNodes');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsWaitonlockEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsWaitonlockEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SettingsWaitonlockEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SettingsWaitonlockEnum()
+%SETTINGSWAITONLOCKENUM - Enum of SettingsWaitonlock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SettingsWaitonlockEnum()
+
+macro=StringToEnum('SettingsWaitonlock');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SigmaNNEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SigmaNNEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SigmaNNEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SigmaNNEnum()
+%SIGMANNENUM - Enum of SigmaNN
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SigmaNNEnum()
+
+macro=StringToEnum('SigmaNN');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SmoothedSurfaceSlopeXAnalysisEnum()
+%SMOOTHEDSURFACESLOPEXANALYSISENUM - Enum of SmoothedSurfaceSlopeXAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SmoothedSurfaceSlopeXAnalysisEnum()
+
+macro=StringToEnum('SmoothedSurfaceSlopeXAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SmoothedSurfaceSlopeYAnalysisEnum()
+%SMOOTHEDSURFACESLOPEYANALYSISENUM - Enum of SmoothedSurfaceSlopeYAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SmoothedSurfaceSlopeYAnalysisEnum()
+
+macro=StringToEnum('SmoothedSurfaceSlopeYAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SoftMigrationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SoftMigrationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SoftMigrationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SoftMigrationEnum()
+%SOFTMIGRATIONENUM - Enum of SoftMigration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SoftMigrationEnum()
+
+macro=StringToEnum('SoftMigration');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SolutionTypeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SolutionTypeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SolutionTypeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SolutionTypeEnum()
+%SOLUTIONTYPEENUM - Enum of SolutionType
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SolutionTypeEnum()
+
+macro=StringToEnum('SolutionType');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcDynamicEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcDynamicEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcDynamicEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SpcDynamicEnum()
+%SPCDYNAMICENUM - Enum of SpcDynamic
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SpcDynamicEnum()
+
+macro=StringToEnum('SpcDynamic');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcStaticEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcStaticEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcStaticEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SpcStaticEnum()
+%SPCSTATICENUM - Enum of SpcStatic
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SpcStaticEnum()
+
+macro=StringToEnum('SpcStatic');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcTransientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcTransientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SpcTransientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SpcTransientEnum()
+%SPCTRANSIENTENUM - Enum of SpcTransient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SpcTransientEnum()
+
+macro=StringToEnum('SpcTransient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SsetEnum()
+%SSETENUM - Enum of Sset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SsetEnum()
+
+macro=StringToEnum('Sset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateMaxiterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateMaxiterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateMaxiterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SteadystateMaxiterEnum()
+%STEADYSTATEMAXITERENUM - Enum of SteadystateMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SteadystateMaxiterEnum()
+
+macro=StringToEnum('SteadystateMaxiter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SteadystateNumRequestedOutputsEnum()
+%STEADYSTATENUMREQUESTEDOUTPUTSENUM - Enum of SteadystateNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SteadystateNumRequestedOutputsEnum()
+
+macro=StringToEnum('SteadystateNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateReltolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateReltolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateReltolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SteadystateReltolEnum()
+%STEADYSTATERELTOLENUM - Enum of SteadystateReltol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SteadystateReltolEnum()
+
+macro=StringToEnum('SteadystateReltol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SteadystateRequestedOutputsEnum()
+%STEADYSTATEREQUESTEDOUTPUTSENUM - Enum of SteadystateRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SteadystateRequestedOutputsEnum()
+
+macro=StringToEnum('SteadystateRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SteadystateSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SteadystateSolutionEnum()
+%STEADYSTATESOLUTIONENUM - Enum of SteadystateSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SteadystateSolutionEnum()
+
+macro=StringToEnum('SteadystateSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StepEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StepEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StepEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StepEnum()
+%STEPENUM - Enum of Step
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StepEnum()
+
+macro=StringToEnum('Step');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRateEnum()
+%STRAINRATEENUM - Enum of StrainRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateEnum()
+
+macro=StringToEnum('StrainRate');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRatexxEnum()
+%STRAINRATEXXENUM - Enum of StrainRatexx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRatexxEnum()
+
+macro=StringToEnum('StrainRatexx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRatexyEnum()
+%STRAINRATEXYENUM - Enum of StrainRatexy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRatexyEnum()
+
+macro=StringToEnum('StrainRatexy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatexzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRatexzEnum()
+%STRAINRATEXZENUM - Enum of StrainRatexz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRatexzEnum()
+
+macro=StringToEnum('StrainRatexz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRateyyEnum()
+%STRAINRATEYYENUM - Enum of StrainRateyy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateyyEnum()
+
+macro=StringToEnum('StrainRateyy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRateyzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRateyzEnum()
+%STRAINRATEYZENUM - Enum of StrainRateyz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateyzEnum()
+
+macro=StringToEnum('StrainRateyz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatezzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatezzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StrainRatezzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StrainRatezzEnum()
+%STRAINRATEZZENUM - Enum of StrainRatezz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRatezzEnum()
+
+macro=StringToEnum('StrainRatezz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensorEnum()
+%STRESSTENSORENUM - Enum of StressTensor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensorEnum()
+
+macro=StringToEnum('StressTensor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensorxxEnum()
+%STRESSTENSORXXENUM - Enum of StressTensorxx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensorxxEnum()
+
+macro=StringToEnum('StressTensorxx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensorxyEnum()
+%STRESSTENSORXYENUM - Enum of StressTensorxy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensorxyEnum()
+
+macro=StringToEnum('StressTensorxy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorxzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensorxzEnum()
+%STRESSTENSORXZENUM - Enum of StressTensorxz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensorxzEnum()
+
+macro=StringToEnum('StressTensorxz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensoryyEnum()
+%STRESSTENSORYYENUM - Enum of StressTensoryy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensoryyEnum()
+
+macro=StringToEnum('StressTensoryy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensoryzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensoryzEnum()
+%STRESSTENSORYZENUM - Enum of StressTensoryz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensoryzEnum()
+
+macro=StringToEnum('StressTensoryz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorzzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorzzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressTensorzzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressTensorzzEnum()
+%STRESSTENSORZZENUM - Enum of StressTensorzz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressTensorzzEnum()
+
+macro=StringToEnum('StressTensorzz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAbstolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAbstolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAbstolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceAbstolEnum()
+%STRESSBALANCEABSTOLENUM - Enum of StressbalanceAbstol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceAbstolEnum()
+
+macro=StringToEnum('StressbalanceAbstol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceAnalysisEnum()
+%STRESSBALANCEANALYSISENUM - Enum of StressbalanceAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceAnalysisEnum()
+
+macro=StringToEnum('StressbalanceAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceFSreconditioningEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceFSreconditioningEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceFSreconditioningEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceFSreconditioningEnum()
+%STRESSBALANCEFSRECONDITIONINGENUM - Enum of StressbalanceFSreconditioning
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceFSreconditioningEnum()
+
+macro=StringToEnum('StressbalanceFSreconditioning');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceIsnewtonEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceIsnewtonEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceIsnewtonEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceIsnewtonEnum()
+%STRESSBALANCEISNEWTONENUM - Enum of StressbalanceIsnewton
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceIsnewtonEnum()
+
+macro=StringToEnum('StressbalanceIsnewton');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceMaxiterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceMaxiterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceMaxiterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceMaxiterEnum()
+%STRESSBALANCEMAXITERENUM - Enum of StressbalanceMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceMaxiterEnum()
+
+macro=StringToEnum('StressbalanceMaxiter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceNumRequestedOutputsEnum()
+%STRESSBALANCENUMREQUESTEDOUTPUTSENUM - Enum of StressbalanceNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceNumRequestedOutputsEnum()
+
+macro=StringToEnum('StressbalanceNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalancePenaltyFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalancePenaltyFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalancePenaltyFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalancePenaltyFactorEnum()
+%STRESSBALANCEPENALTYFACTORENUM - Enum of StressbalancePenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalancePenaltyFactorEnum()
+
+macro=StringToEnum('StressbalancePenaltyFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReferentialEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReferentialEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReferentialEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceReferentialEnum()
+%STRESSBALANCEREFERENTIALENUM - Enum of StressbalanceReferential
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceReferentialEnum()
+
+macro=StringToEnum('StressbalanceReferential');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReltolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReltolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceReltolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceReltolEnum()
+%STRESSBALANCERELTOLENUM - Enum of StressbalanceReltol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceReltolEnum()
+
+macro=StringToEnum('StressbalanceReltol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRequestedOutputsEnum()
+%STRESSBALANCEREQUESTEDOUTPUTSENUM - Enum of StressbalanceRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceRequestedOutputsEnum()
+
+macro=StringToEnum('StressbalanceRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRestolEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRestolEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRestolEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRestolEnum()
+%STRESSBALANCERESTOLENUM - Enum of StressbalanceRestol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceRestolEnum()
+
+macro=StringToEnum('StressbalanceRestol');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyLockEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyLockEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyLockEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRiftPenaltyLockEnum()
+%STRESSBALANCERIFTPENALTYLOCKENUM - Enum of StressbalanceRiftPenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceRiftPenaltyLockEnum()
+
+macro=StringToEnum('StressbalanceRiftPenaltyLock');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRiftPenaltyThresholdEnum()
+%STRESSBALANCERIFTPENALTYTHRESHOLDENUM - Enum of StressbalanceRiftPenaltyThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceRiftPenaltyThresholdEnum()
+
+macro=StringToEnum('StressbalanceRiftPenaltyThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSIAAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSIAAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSIAAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSIAAnalysisEnum()
+%STRESSBALANCESIAANALYSISENUM - Enum of StressbalanceSIAAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceSIAAnalysisEnum()
+
+macro=StringToEnum('StressbalanceSIAAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceShelfDampeningEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceShelfDampeningEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceShelfDampeningEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceShelfDampeningEnum()
+%STRESSBALANCESHELFDAMPENINGENUM - Enum of StressbalanceShelfDampening
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceShelfDampeningEnum()
+
+macro=StringToEnum('StressbalanceShelfDampening');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSolutionEnum()
+%STRESSBALANCESOLUTIONENUM - Enum of StressbalanceSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceSolutionEnum()
+
+macro=StringToEnum('StressbalanceSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvxEnum()
+%STRESSBALANCESPCVXENUM - Enum of StressbalanceSpcvx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceSpcvxEnum()
+
+macro=StringToEnum('StressbalanceSpcvx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvyEnum()
+%STRESSBALANCESPCVYENUM - Enum of StressbalanceSpcvy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceSpcvyEnum()
+
+macro=StringToEnum('StressbalanceSpcvy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceSpcvzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvzEnum()
+%STRESSBALANCESPCVZENUM - Enum of StressbalanceSpcvz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceSpcvzEnum()
+
+macro=StringToEnum('StressbalanceSpcvz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVertexPairingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVertexPairingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVertexPairingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceVertexPairingEnum()
+%STRESSBALANCEVERTEXPAIRINGENUM - Enum of StressbalanceVertexPairing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceVertexPairingEnum()
+
+macro=StringToEnum('StressbalanceVertexPairing');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVerticalAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVerticalAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceVerticalAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceVerticalAnalysisEnum()
+%STRESSBALANCEVERTICALANALYSISENUM - Enum of StressbalanceVerticalAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceVerticalAnalysisEnum()
+
+macro=StringToEnum('StressbalanceVerticalAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceViscosityOvershootEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceViscosityOvershootEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StressbalanceViscosityOvershootEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StressbalanceViscosityOvershootEnum()
+%STRESSBALANCEVISCOSITYOVERSHOOTENUM - Enum of StressbalanceViscosityOvershoot
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressbalanceViscosityOvershootEnum()
+
+macro=StringToEnum('StressbalanceViscosityOvershoot');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringArrayParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringArrayParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringArrayParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StringArrayParamEnum()
+%STRINGARRAYPARAMENUM - Enum of StringArrayParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StringArrayParamEnum()
+
+macro=StringToEnum('StringArrayParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringExternalResultEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringExternalResultEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringExternalResultEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StringExternalResultEnum()
+%STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StringExternalResultEnum()
+
+macro=StringToEnum('StringExternalResult');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/StringParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=StringParamEnum()
+%STRINGPARAMENUM - Enum of StringParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StringParamEnum()
+
+macro=StringToEnum('StringParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigration2Enum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigration2Enum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigration2Enum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SubelementMigration2Enum()
+%SUBELEMENTMIGRATION2ENUM - Enum of SubelementMigration2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SubelementMigration2Enum()
+
+macro=StringToEnum('SubelementMigration2');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigrationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigrationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SubelementMigrationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SubelementMigrationEnum()
+%SUBELEMENTMIGRATIONENUM - Enum of SubelementMigration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SubelementMigrationEnum()
+
+macro=StringToEnum('SubelementMigration');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAbsVelMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceAbsVelMisfitEnum()
+%SURFACEABSVELMISFITENUM - Enum of SurfaceAbsVelMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceAbsVelMisfitEnum()
+
+macro=StringToEnum('SurfaceAbsVelMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAreaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAreaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAreaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceAreaEnum()
+%SURFACEAREAENUM - Enum of SurfaceArea
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceAreaEnum()
+
+macro=StringToEnum('SurfaceArea');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAverageVelMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceAverageVelMisfitEnum()
+%SURFACEAVERAGEVELMISFITENUM - Enum of SurfaceAverageVelMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceAverageVelMisfitEnum()
+
+macro=StringToEnum('SurfaceAverageVelMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceEnum()
+%SURFACEENUM - Enum of Surface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceEnum()
+
+macro=StringToEnum('Surface');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVelMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceLogVelMisfitEnum()
+%SURFACELOGVELMISFITENUM - Enum of SurfaceLogVelMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceLogVelMisfitEnum()
+
+macro=StringToEnum('SurfaceLogVelMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVxVyMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceLogVxVyMisfitEnum()
+%SURFACELOGVXVYMISFITENUM - Enum of SurfaceLogVxVyMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceLogVxVyMisfitEnum()
+
+macro=StringToEnum('SurfaceLogVxVyMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceNormalVelocityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceNormalVelocityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceNormalVelocityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceNormalVelocityEnum()
+%SURFACENORMALVELOCITYENUM - Enum of SurfaceNormalVelocity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceNormalVelocityEnum()
+
+macro=StringToEnum('SurfaceNormalVelocity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceObservationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceObservationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceObservationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceObservationEnum()
+%SURFACEOBSERVATIONENUM - Enum of SurfaceObservation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceObservationEnum()
+
+macro=StringToEnum('SurfaceObservation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceRelVelMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceRelVelMisfitEnum()
+%SURFACERELVELMISFITENUM - Enum of SurfaceRelVelMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceRelVelMisfitEnum()
+
+macro=StringToEnum('SurfaceRelVelMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeSolutionEnum()
+%SURFACESLOPESOLUTIONENUM - Enum of SurfaceSlopeSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeSolutionEnum()
+
+macro=StringToEnum('SurfaceSlopeSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeXEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeXEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeXEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeXEnum()
+%SURFACESLOPEXENUM - Enum of SurfaceSlopeX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeXEnum()
+
+macro=StringToEnum('SurfaceSlopeX');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceSlopeYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeYEnum()
+%SURFACESLOPEYENUM - Enum of SurfaceSlopeY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeYEnum()
+
+macro=StringToEnum('SurfaceSlopeY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsAccumulationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsAccumulationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsAccumulationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsAccumulationEnum()
+%SURFACEFORCINGSACCUMULATIONENUM - Enum of SurfaceforcingsAccumulation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsAccumulationEnum()
+
+macro=StringToEnum('SurfaceforcingsAccumulation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBNegEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsBNegEnum()
+%SURFACEFORCINGSBNEGENUM - Enum of SurfaceforcingsBNeg
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsBNegEnum()
+
+macro=StringToEnum('SurfaceforcingsBNeg');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBPosEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsBPosEnum()
+%SURFACEFORCINGSBPOSENUM - Enum of SurfaceforcingsBPos
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsBPosEnum()
+
+macro=StringToEnum('SurfaceforcingsBPos');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsDelta18oEnum()
+%SURFACEFORCINGSDELTA18OENUM - Enum of SurfaceforcingsDelta18o
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsDelta18oEnum()
+
+macro=StringToEnum('SurfaceforcingsDelta18o');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsDelta18oSurfaceEnum()
+%SURFACEFORCINGSDELTA18OSURFACEENUM - Enum of SurfaceforcingsDelta18oSurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsDelta18oSurfaceEnum()
+
+macro=StringToEnum('SurfaceforcingsDelta18oSurface');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDesfacEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDesfacEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsDesfacEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsDesfacEnum()
+%SURFACEFORCINGSDESFACENUM - Enum of SurfaceforcingsDesfac
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsDesfacEnum()
+
+macro=StringToEnum('SurfaceforcingsDesfac');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsEnum()
+%SURFACEFORCINGSENUM - Enum of Surfaceforcings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsEnum()
+
+macro=StringToEnum('Surfaceforcings');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEvaporationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEvaporationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsEvaporationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsEvaporationEnum()
+%SURFACEFORCINGSEVAPORATIONENUM - Enum of SurfaceforcingsEvaporation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsEvaporationEnum()
+
+macro=StringToEnum('SurfaceforcingsEvaporation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsHrefEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsHrefEnum()
+
+macro=StringToEnum('SurfaceforcingsHref');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIsdelta18oEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIsdelta18oEnum()
+%SURFACEFORCINGSISDELTA18OENUM - Enum of SurfaceforcingsIsdelta18o
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsIsdelta18oEnum()
+
+macro=StringToEnum('SurfaceforcingsIsdelta18o');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIspddEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIspddEnum()
+%SURFACEFORCINGSISPDDENUM - Enum of SurfaceforcingsIspdd
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsIspddEnum()
+
+macro=StringToEnum('SurfaceforcingsIspdd');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIssmbgradientsEnum()
+%SURFACEFORCINGSISSMBGRADIENTSENUM - Enum of SurfaceforcingsIssmbgradients
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsIssmbgradientsEnum()
+
+macro=StringToEnum('SurfaceforcingsIssmbgradients');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMassBalanceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsMassBalanceEnum()
+%SURFACEFORCINGSMASSBALANCEENUM - Enum of SurfaceforcingsMassBalance
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsMassBalanceEnum()
+
+macro=StringToEnum('SurfaceforcingsMassBalance');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMeltEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMeltEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMeltEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsMeltEnum()
+%SURFACEFORCINGSMELTENUM - Enum of SurfaceforcingsMelt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsMeltEnum()
+
+macro=StringToEnum('SurfaceforcingsMelt');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsMonthlytemperaturesEnum()
+%SURFACEFORCINGSMONTHLYTEMPERATURESENUM - Enum of SurfaceforcingsMonthlytemperatures
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsMonthlytemperaturesEnum()
+
+macro=StringToEnum('SurfaceforcingsMonthlytemperatures');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsPrecipitationEnum()
+%SURFACEFORCINGSPRECIPITATIONENUM - Enum of SurfaceforcingsPrecipitation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsPrecipitationEnum()
+
+macro=StringToEnum('SurfaceforcingsPrecipitation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsPrecipitationsPresentdayEnum()
+%SURFACEFORCINGSPRECIPITATIONSPRESENTDAYENUM - Enum of SurfaceforcingsPrecipitationsPresentday
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsPrecipitationsPresentdayEnum()
+
+macro=StringToEnum('SurfaceforcingsPrecipitationsPresentday');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRefreezeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRefreezeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRefreezeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRefreezeEnum()
+%SURFACEFORCINGSREFREEZEENUM - Enum of SurfaceforcingsRefreeze
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRefreezeEnum()
+
+macro=StringToEnum('SurfaceforcingsRefreeze');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRunoffEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRunoffEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsRunoffEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRunoffEnum()
+%SURFACEFORCINGSRUNOFFENUM - Enum of SurfaceforcingsRunoff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRunoffEnum()
+
+macro=StringToEnum('SurfaceforcingsRunoff');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsS0pEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsS0pEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsS0pEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsS0pEnum()
+%SURFACEFORCINGSS0PENUM - Enum of SurfaceforcingsS0p
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsS0pEnum()
+
+macro=StringToEnum('SurfaceforcingsS0p');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsSmbrefEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 18231)
@@ -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/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsSmbrefEnum()
+
+macro=StringToEnum('SurfaceforcingsSmbref');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsTemperaturesLgmEnum()
+%SURFACEFORCINGSTEMPERATURESLGMENUM - Enum of SurfaceforcingsTemperaturesLgm
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsTemperaturesLgmEnum()
+
+macro=StringToEnum('SurfaceforcingsTemperaturesLgm');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsTemperaturesPresentdayEnum()
+%SURFACEFORCINGSTEMPERATURESPRESENTDAYENUM - Enum of SurfaceforcingsTemperaturesPresentday
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsTemperaturesPresentdayEnum()
+
+macro=StringToEnum('SurfaceforcingsTemperaturesPresentday');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TaylorHoodEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TaylorHoodEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TaylorHoodEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TaylorHoodEnum()
+%TAYLORHOODENUM - Enum of TaylorHood
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TaylorHoodEnum()
+
+macro=StringToEnum('TaylorHood');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperatureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperatureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperatureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TemperatureEnum()
+%TEMPERATUREENUM - Enum of Temperature
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TemperatureEnum()
+
+macro=StringToEnum('Temperature');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperaturePicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperaturePicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TemperaturePicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TemperaturePicardEnum()
+%TEMPERATUREPICARDENUM - Enum of TemperaturePicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TemperaturePicardEnum()
+
+macro=StringToEnum('TemperaturePicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TetraEnum()
+%TETRAENUM - Enum of Tetra
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TetraEnum()
+
+macro=StringToEnum('Tetra');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TetraInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TetraInputEnum()
+%TETRAINPUTENUM - Enum of TetraInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TetraInputEnum()
+
+macro=StringToEnum('TetraInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalAnalysisEnum()
+%THERMALANALYSISENUM - Enum of ThermalAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalAnalysisEnum()
+
+macro=StringToEnum('ThermalAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsdynamicbasalspcEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsdynamicbasalspcEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsdynamicbasalspcEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalIsdynamicbasalspcEnum()
+%THERMALISDYNAMICBASALSPCENUM - Enum of ThermalIsdynamicbasalspc
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalIsdynamicbasalspcEnum()
+
+macro=StringToEnum('ThermalIsdynamicbasalspc');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsenthalpyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsenthalpyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalIsenthalpyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalIsenthalpyEnum()
+%THERMALISENTHALPYENUM - Enum of ThermalIsenthalpy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalIsenthalpyEnum()
+
+macro=StringToEnum('ThermalIsenthalpy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalMaxiterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalMaxiterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalMaxiterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalMaxiterEnum()
+%THERMALMAXITERENUM - Enum of ThermalMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalMaxiterEnum()
+
+macro=StringToEnum('ThermalMaxiter');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalNumRequestedOutputsEnum()
+%THERMALNUMREQUESTEDOUTPUTSENUM - Enum of ThermalNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalNumRequestedOutputsEnum()
+
+macro=StringToEnum('ThermalNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyFactorEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalPenaltyFactorEnum()
+%THERMALPENALTYFACTORENUM - Enum of ThermalPenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyFactorEnum()
+
+macro=StringToEnum('ThermalPenaltyFactor');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyLockEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyLockEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyLockEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalPenaltyLockEnum()
+%THERMALPENALTYLOCKENUM - Enum of ThermalPenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyLockEnum()
+
+macro=StringToEnum('ThermalPenaltyLock');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyThresholdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalPenaltyThresholdEnum()
+%THERMALPENALTYTHRESHOLDENUM - Enum of ThermalPenaltyThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyThresholdEnum()
+
+macro=StringToEnum('ThermalPenaltyThreshold');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalRequestedOutputsEnum()
+%THERMALREQUESTEDOUTPUTSENUM - Enum of ThermalRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalRequestedOutputsEnum()
+
+macro=StringToEnum('ThermalRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalSolutionEnum()
+%THERMALSOLUTIONENUM - Enum of ThermalSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalSolutionEnum()
+
+macro=StringToEnum('ThermalSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSpctemperatureEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSpctemperatureEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalSpctemperatureEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalSpctemperatureEnum()
+%THERMALSPCTEMPERATUREENUM - Enum of ThermalSpctemperature
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalSpctemperatureEnum()
+
+macro=StringToEnum('ThermalSpctemperature');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalStabilizationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalStabilizationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThermalStabilizationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThermalStabilizationEnum()
+%THERMALSTABILIZATIONENUM - Enum of ThermalStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalStabilizationEnum()
+
+macro=StringToEnum('ThermalStabilization');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThicknessAbsGradientEnum()
+%THICKNESSABSGRADIENTENUM - Enum of ThicknessAbsGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThicknessAbsGradientEnum()
+
+macro=StringToEnum('ThicknessAbsGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsMisfitEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThicknessAbsMisfitEnum()
+%THICKNESSABSMISFITENUM - Enum of ThicknessAbsMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThicknessAbsMisfitEnum()
+
+macro=StringToEnum('ThicknessAbsMisfit');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAcrossGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThicknessAcrossGradientEnum()
+%THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThicknessAcrossGradientEnum()
+
+macro=StringToEnum('ThicknessAcrossGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAlongGradientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAlongGradientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessAlongGradientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThicknessAlongGradientEnum()
+%THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThicknessAlongGradientEnum()
+
+macro=StringToEnum('ThicknessAlongGradient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ThicknessEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ThicknessEnum()
+%THICKNESSENUM - Enum of Thickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThicknessEnum()
+
+macro=StringToEnum('Thickness');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimeEnum()
+%TIMEENUM - Enum of Time
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimeEnum()
+
+macro=StringToEnum('Time');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingCflCoefficientEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingCflCoefficientEnum()
+%TIMESTEPPINGCFLCOEFFICIENTENUM - Enum of TimesteppingCflCoefficient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingCflCoefficientEnum()
+
+macro=StringToEnum('TimesteppingCflCoefficient');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingFinalTimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingFinalTimeEnum()
+%TIMESTEPPINGFINALTIMEENUM - Enum of TimesteppingFinalTime
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingFinalTimeEnum()
+
+macro=StringToEnum('TimesteppingFinalTime');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingInterpForcingsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingInterpForcingsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingInterpForcingsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingInterpForcingsEnum()
+%TIMESTEPPINGINTERPFORCINGSENUM - Enum of TimesteppingInterpForcings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingInterpForcingsEnum()
+
+macro=StringToEnum('TimesteppingInterpForcings');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingStartTimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingStartTimeEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingStartTimeEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingStartTimeEnum()
+%TIMESTEPPINGSTARTTIMEENUM - Enum of TimesteppingStartTime
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingStartTimeEnum()
+
+macro=StringToEnum('TimesteppingStartTime');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeAdaptEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingTimeAdaptEnum()
+%TIMESTEPPINGTIMEADAPTENUM - Enum of TimesteppingTimeAdapt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingTimeAdaptEnum()
+
+macro=StringToEnum('TimesteppingTimeAdapt');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeStepEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeStepEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TimesteppingTimeStepEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TimesteppingTimeStepEnum()
+%TIMESTEPPINGTIMESTEPENUM - Enum of TimesteppingTimeStep
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingTimeStepEnum()
+
+macro=StringToEnum('TimesteppingTimeStep');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsAnalysesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsAnalysesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsAnalysesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ToolkitsOptionsAnalysesEnum()
+%TOOLKITSOPTIONSANALYSESENUM - Enum of ToolkitsOptionsAnalyses
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ToolkitsOptionsAnalysesEnum()
+
+macro=StringToEnum('ToolkitsOptionsAnalyses');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsStringsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsStringsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ToolkitsOptionsStringsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ToolkitsOptionsStringsEnum()
+%TOOLKITSOPTIONSSTRINGSENUM - Enum of ToolkitsOptionsStrings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ToolkitsOptionsStringsEnum()
+
+macro=StringToEnum('ToolkitsOptionsStrings');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TotalSmbEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TotalSmbEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TotalSmbEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TotalSmbEnum()
+%TOTALSMBENUM - Enum of TotalSmb
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TotalSmbEnum()
+
+macro=StringToEnum('TotalSmb');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientInputEnum()
+%TRANSIENTINPUTENUM - Enum of TransientInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientInputEnum()
+
+macro=StringToEnum('TransientInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsdamageevolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsdamageevolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsdamageevolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsdamageevolutionEnum()
+%TRANSIENTISDAMAGEEVOLUTIONENUM - Enum of TransientIsdamageevolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsdamageevolutionEnum()
+
+macro=StringToEnum('TransientIsdamageevolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgiaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgiaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgiaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsgiaEnum()
+%TRANSIENTISGIAENUM - Enum of TransientIsgia
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsgiaEnum()
+
+macro=StringToEnum('TransientIsgia');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgroundinglineEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgroundinglineEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsgroundinglineEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsgroundinglineEnum()
+%TRANSIENTISGROUNDINGLINEENUM - Enum of TransientIsgroundingline
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsgroundinglineEnum()
+
+macro=StringToEnum('TransientIsgroundingline');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIshydrologyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIshydrologyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIshydrologyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIshydrologyEnum()
+%TRANSIENTISHYDROLOGYENUM - Enum of TransientIshydrology
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIshydrologyEnum()
+
+macro=StringToEnum('TransientIshydrology');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIslevelsetEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIslevelsetEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIslevelsetEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIslevelsetEnum()
+%TRANSIENTISLEVELSETENUM - Enum of TransientIslevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIslevelsetEnum()
+
+macro=StringToEnum('TransientIslevelset');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsmasstransportEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsmasstransportEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsmasstransportEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsmasstransportEnum()
+%TRANSIENTISMASSTRANSPORTENUM - Enum of TransientIsmasstransport
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsmasstransportEnum()
+
+macro=StringToEnum('TransientIsmasstransport');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsstressbalanceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsstressbalanceEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsstressbalanceEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsstressbalanceEnum()
+%TRANSIENTISSTRESSBALANCEENUM - Enum of TransientIsstressbalance
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsstressbalanceEnum()
+
+macro=StringToEnum('TransientIsstressbalance');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsthermalEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsthermalEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientIsthermalEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientIsthermalEnum()
+%TRANSIENTISTHERMALENUM - Enum of TransientIsthermal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIsthermalEnum()
+
+macro=StringToEnum('TransientIsthermal');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientNumRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientNumRequestedOutputsEnum()
+%TRANSIENTNUMREQUESTEDOUTPUTSENUM - Enum of TransientNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientNumRequestedOutputsEnum()
+
+macro=StringToEnum('TransientNumRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientParamEnum()
+%TRANSIENTPARAMENUM - Enum of TransientParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientParamEnum()
+
+macro=StringToEnum('TransientParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientRequestedOutputsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientRequestedOutputsEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientRequestedOutputsEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientRequestedOutputsEnum()
+%TRANSIENTREQUESTEDOUTPUTSENUM - Enum of TransientRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientRequestedOutputsEnum()
+
+macro=StringToEnum('TransientRequestedOutputs');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientSolutionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientSolutionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TransientSolutionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TransientSolutionEnum()
+%TRANSIENTSOLUTIONENUM - Enum of TransientSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientSolutionEnum()
+
+macro=StringToEnum('TransientSolution');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TriaEnum()
+%TRIAENUM - Enum of Tria
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TriaEnum()
+
+macro=StringToEnum('Tria');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaInputEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaInputEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriaInputEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TriaInputEnum()
+%TRIAINPUTENUM - Enum of TriaInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TriaInputEnum()
+
+macro=StringToEnum('TriaInput');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriangleInterpEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriangleInterpEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/TriangleInterpEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=TriangleInterpEnum()
+%TRIANGLEINTERPENUM - Enum of TriangleInterp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TriangleInterpEnum()
+
+macro=StringToEnum('TriangleInterp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/UzawaPressureAnalysisEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/UzawaPressureAnalysisEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/UzawaPressureAnalysisEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=UzawaPressureAnalysisEnum()
+%UZAWAPRESSUREANALYSISENUM - Enum of UzawaPressureAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=UzawaPressureAnalysisEnum()
+
+macro=StringToEnum('UzawaPressureAnalysis');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VectorParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VectorParamEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VectorParamEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VectorParamEnum()
+%VECTORPARAMENUM - Enum of VectorParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VectorParamEnum()
+
+macro=StringToEnum('VectorParam');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VelEnum()
+%VELENUM - Enum of Vel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VelEnum()
+
+macro=StringToEnum('Vel');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelocityEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelocityEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VelocityEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VelocityEnum()
+%VELOCITYENUM - Enum of Velocity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VelocityEnum()
+
+macro=StringToEnum('Velocity');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerboseEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerboseEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerboseEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VerboseEnum()
+%VERBOSEENUM - Enum of Verbose
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VerboseEnum()
+
+macro=StringToEnum('Verbose');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VertexEnum()
+%VERTEXENUM - Enum of Vertex
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VertexEnum()
+
+macro=StringToEnum('Vertex');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexPIdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexPIdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexPIdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VertexPIdEnum()
+%VERTEXPIDENUM - Enum of VertexPId
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VertexPIdEnum()
+
+macro=StringToEnum('VertexPId');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexSIdEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexSIdEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VertexSIdEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VertexSIdEnum()
+%VERTEXSIDENUM - Enum of VertexSId
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VertexSIdEnum()
+
+macro=StringToEnum('VertexSId');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerticesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerticesEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VerticesEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VerticesEnum()
+%VERTICESENUM - Enum of Vertices
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VerticesEnum()
+
+macro=StringToEnum('Vertices');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ViscousHeatingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ViscousHeatingEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/ViscousHeatingEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=ViscousHeatingEnum()
+%VISCOUSHEATINGENUM - Enum of ViscousHeating
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ViscousHeatingEnum()
+
+macro=StringToEnum('ViscousHeating');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxAverageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxAverageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxAverageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VxAverageEnum()
+%VXAVERAGEENUM - Enum of VxAverage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VxAverageEnum()
+
+macro=StringToEnum('VxAverage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VxEnum()
+%VXENUM - Enum of Vx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VxEnum()
+
+macro=StringToEnum('Vx');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VxMeshEnum()
+%VXMESHENUM - Enum of VxMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VxMeshEnum()
+
+macro=StringToEnum('VxMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxPicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxPicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VxPicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VxPicardEnum()
+%VXPICARDENUM - Enum of VxPicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VxPicardEnum()
+
+macro=StringToEnum('VxPicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyAverageEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyAverageEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyAverageEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VyAverageEnum()
+%VYAVERAGEENUM - Enum of VyAverage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VyAverageEnum()
+
+macro=StringToEnum('VyAverage');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VyEnum()
+%VYENUM - Enum of Vy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VyEnum()
+
+macro=StringToEnum('Vy');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VyMeshEnum()
+%VYMESHENUM - Enum of VyMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VyMeshEnum()
+
+macro=StringToEnum('VyMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyPicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyPicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VyPicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VyPicardEnum()
+%VYPICARDENUM - Enum of VyPicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VyPicardEnum()
+
+macro=StringToEnum('VyPicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzEnum()
+%VZENUM - Enum of Vz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzEnum()
+
+macro=StringToEnum('Vz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzFSEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzFSEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzFSEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzFSEnum()
+%VZFSENUM - Enum of VzFS
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzFSEnum()
+
+macro=StringToEnum('VzFS');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzHOEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzHOEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzHOEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzHOEnum()
+%VZHOENUM - Enum of VzHO
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzHOEnum()
+
+macro=StringToEnum('VzHO');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzMeshEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzMeshEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzMeshEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzMeshEnum()
+%VZMESHENUM - Enum of VzMesh
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzMeshEnum()
+
+macro=StringToEnum('VzMesh');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzPicardEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzPicardEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzPicardEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzPicardEnum()
+%VZPICARDENUM - Enum of VzPicard
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzPicardEnum()
+
+macro=StringToEnum('VzPicard');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzSSAEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzSSAEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/VzSSAEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=VzSSAEnum()
+%VZSSAENUM - Enum of VzSSA
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VzSSAEnum()
+
+macro=StringToEnum('VzSSA');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterColumnOldEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterColumnOldEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterColumnOldEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=WaterColumnOldEnum()
+%WATERCOLUMNOLDENUM - Enum of WaterColumnOld
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WaterColumnOldEnum()
+
+macro=StringToEnum('WaterColumnOld');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=WaterEnum()
+%WATERENUM - Enum of Water
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WaterEnum()
+
+macro=StringToEnum('Water');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WatercolumnEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WatercolumnEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WatercolumnEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=WatercolumnEnum()
+%WATERCOLUMNENUM - Enum of Watercolumn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WatercolumnEnum()
+
+macro=StringToEnum('Watercolumn');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterfractionEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterfractionEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WaterfractionEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=WaterfractionEnum()
+%WATERFRACTIONENUM - Enum of Waterfraction
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WaterfractionEnum()
+
+macro=StringToEnum('Waterfraction');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WeightsSurfaceObservationEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WeightsSurfaceObservationEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/WeightsSurfaceObservationEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=WeightsSurfaceObservationEnum()
+%WEIGHTSSURFACEOBSERVATIONENUM - Enum of WeightsSurfaceObservation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WeightsSurfaceObservationEnum()
+
+macro=StringToEnum('WeightsSurfaceObservation');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XTaylorHoodEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XTaylorHoodEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XTaylorHoodEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=XTaylorHoodEnum()
+%XTAYLORHOODENUM - Enum of XTaylorHood
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=XTaylorHoodEnum()
+
+macro=StringToEnum('XTaylorHood');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=XYEnum()
+%XYENUM - Enum of XY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=XYEnum()
+
+macro=StringToEnum('XY');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYZEnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYZEnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/enum/XYZEnum.m	(revision 18231)
@@ -0,0 +1,11 @@
+function macro=XYZEnum()
+%XYZENUM - Enum of XYZ
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=XYZEnum()
+
+macro=StringToEnum('XYZ');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/clicktoflowline.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/clicktoflowline.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/clicktoflowline.m	(revision 18231)
@@ -0,0 +1,24 @@
+function clicktoflowline(index,x,y,u,v,filename)
+%CLICKTOFLOWLINE - create a flowline ARGUS file
+%
+%   create a flowline contour file (named 'filename') by clicking
+%   on a velocity field once (velocity must be plotted first)
+%
+%   Usage: 
+%      clicktoflowline(index,x,y,u,v,x0,y0,filename)
+%
+%   Example: 
+%      clicktoflowline(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vx_obs,md.inversion.vy_obs,'flowline.exp')
+
+%Get click position
+[x0,y0]=ginput(1);
+
+%Get flowline
+line=flowlines(index,x,y,u,v,x0,y0,200);
+
+%plot
+hold on
+plot(line.x,line.y,'r-');
+
+%Write argus file
+expwrite(line,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/contourlevelzero.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/contourlevelzero.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/contourlevelzero.m	(revision 18231)
@@ -0,0 +1,199 @@
+function contours=contourlevelzero(md,mask,level)
+%CONTOURLEVELZERO - figure out the zero level (or offset thereof, specified by the level value) 
+%                   of a vectorial mask, and vectorialize it into an exp or shp compatible 
+%structure.
+%
+%   Usage:
+%      contours=contourlevelzero(md,mask,level)
+%
+%   See also: PLOT_CONTOUR
+
+%process data 
+if dimension(md.mesh)==3,
+	error('contourlevelzero error message: routine not supported for 3d meshes, project on a layer');
+end
+
+x=md.mesh.x;
+y=md.mesh.y;
+index=md.mesh.elements;
+
+if isempty(mask), error('mask provided is empty'); end
+	if length(mask)~=md.mesh.numberofvertices, error('mask provided should be specified at the vertices of the mesh'); end
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=mask(Seg1);
+Data2=mask(Seg2);
+Data3=mask(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+%find the segments that contain this value
+pos1=(Range1(:,1)<level & Range1(:,2)>level);
+pos2=(Range2(:,1)<level & Range2(:,2)>level);
+pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+%get elements
+poselem12=(pos1 & pos2);
+poselem13=(pos1 & pos3);
+poselem23=(pos2 & pos3);
+poselem=find(poselem12 | poselem13 | poselem23);
+numelems=length(poselem);
+
+%if no element has been flagged, skip to the next level
+if numelems==0,
+	warning('contourlevelzero warning message: no elements found with corresponding level value in mask');
+	contours=struct([]);
+	return;
+end
+
+%go through the elements and build the coordinates for each segment (1 by element)
+x1=zeros(numelems,1);
+x2=zeros(numelems,1);
+y1=zeros(numelems,1);
+y2=zeros(numelems,1);
+edge_l=zeros(numelems,2);
+
+for j=1:numelems,
+
+	weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+	weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+	weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+	if poselem12(poselem(j));
+
+		x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+		x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+		y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+		y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+		edge_l(j,1)=Seg1_num(poselem(j));
+		edge_l(j,2)=Seg2_num(poselem(j));
+
+	elseif poselem13(poselem(j)),
+
+		x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+		x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+		y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+		y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+		edge_l(j,1)=Seg1_num(poselem(j));
+		edge_l(j,2)=Seg3_num(poselem(j));
+
+	elseif poselem23(poselem(j)),
+
+		x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+		x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+		y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+		y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+		edge_l(j,1)=Seg2_num(poselem(j));
+		edge_l(j,2)=Seg3_num(poselem(j));
+	else
+		%it shoud not go here
+	end
+end
+
+%now that we have the segments, we must try to connect them...
+
+%loop over the subcontours
+contours=struct([]);
+
+while ~isempty(edge_l),
+
+	%take the right edge of the second segment and connect it to the next segments if any
+	e1=edge_l(1,1);   e2=edge_l(1,2);
+	xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+	%erase the lines corresponding to this edge
+	edge_l(1,:)=[];
+	x1(1)=[]; x2(1)=[];
+	y1(1)=[]; y2(1)=[];
+
+	[ro1,co1]=find(edge_l==e1);
+
+	while ~isempty(ro1)
+
+		if co1==1,
+			xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+			%next edge:
+			e1=edge_l(ro1,2);
+
+		else
+			xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+			%next edge:
+			e1=edge_l(ro1,1);
+		end
+
+		%erase the lines of this
+		edge_l(ro1,:)=[];
+		x1(ro1)=[]; x2(ro1)=[];
+		y1(ro1)=[]; y2(ro1)=[];
+
+		%next connection
+		[ro1,co1]=find(edge_l==e1);
+	end
+
+	%same thing the other way (to the right)
+	[ro2,co2]=find(edge_l==e2);
+
+	while ~isempty(ro2)
+
+		if co2==1,
+			xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+			%next edge:
+			e2=edge_l(ro2,2);
+		else
+			xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+			%next edge:
+			e2=edge_l(ro2,1);
+		end
+
+		%erase the lines of this
+		edge_l(ro2,:)=[];
+		x1(ro2)=[]; x2(ro2)=[];
+		y1(ro2)=[]; y2(ro2)=[];
+
+		%next connection
+		[ro2,co2]=find(edge_l==e2);
+	end
+
+	%save xc,yc contour: 
+	contours(end+1).x=xc;
+	contours(end).y=yc;
+	contours(end).name='';
+	contours(end).nods=length(xc);
+	contours(end).density=1;
+	contours(end).closed=0;
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/downstreamflowlines.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/downstreamflowlines.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/downstreamflowlines.m	(revision 18231)
@@ -0,0 +1,110 @@
+function flowpath=downstreamflowlines(index,x,y,u,v,x0,y0,varargin)
+%DOWNSTREAMFLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=downstreamflowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=downstreamflowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>9 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==9
+	maxiter=varargin{1};%maximum number of iterations
+	precision=varargin{2}; %division of each segment (higer precision increases number of segments)
+else
+	maxiter=200; %maximum number of iterations
+	precision=1; %division of each segment (higer precision increases number of segments)
+end
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exp2shp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exp2shp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exp2shp.m	(revision 18231)
@@ -0,0 +1,37 @@
+function exp2shp(shapefilename,expfilename,geometry)
+%SHPWRITE - write a shape file from a contour structure
+%
+%   Usage:
+%      exp2shp(shapefilename,expfilename,geometry)
+%
+%   Example:
+%      exp2shp('domainoutline.shp','domainoutline.exp')
+%      exp2shp('domainoutline.shp','domainoutline.exp','Polygon')
+%      exp2shp('massfluxgate.shp','massfluxgate.exp','Line')
+%
+%   See also SHPREAD, SHPWRITE, SHP2EXP
+
+shp=expread(expfilename);
+
+%initialize number of profile
+count=0;
+
+contours=struct([]);
+for i=1:length(shp),
+	if nargin < 3
+		if length(shp(1).x) == 1
+			geometry = 'Point';
+		elseif length(shp(1).x) < 3
+			geometry = 'Line';
+		else
+			geometry = 'Polygon';
+		end
+	end
+	contours(i).Geometry=geometry;
+	contours(i).id=i;
+	contours(i).X=shp(i).x;
+	contours(i).Y=shp(i).y;
+end
+	
+shapewrite(contours,shapefilename);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expbox.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expbox.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expbox.m	(revision 18231)
@@ -0,0 +1,41 @@
+function expbox(filename)
+%EXPBOX - Create an ARGUS file using two clicks
+%
+%   Two clicks on a plot are used to generate a rectangular box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a rectangular domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+x1=x(1);
+x2=x(2);
+x3=x2;
+x4=x1;
+
+y1=y(1);
+y2=y1;
+y3=y(2);
+y4=y3;
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcircle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcircle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcircle.m	(revision 18231)
@@ -0,0 +1,31 @@
+function expcircle(filename,x0,y0,radius,numberofnodes)
+%EXPCIRCLE - create a circular contour corresponding to given parameters
+%
+%   Creates a closed argus contour centered on x,y of radius size.
+%   The contour is made of numberofnodes
+%
+%   Usage:
+%      expcircle(filename,x0,y0,radius,numberofnodes)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(numberofnodes+1,1);
+y_list=ones(numberofnodes+1,1);
+
+theta=(0:2*pi/numberofnodes:2*pi*(1-1/numberofnodes))';
+theta=[theta;0];
+
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+
+%offset x_list and y_list by x0 and y0:
+x_list=x_list+x0;
+y_list=y_list+y0;
+
+contour.x=x_list;
+contour.y=y_list;
+contour.density=1;
+contour.name='circle';
+
+expwrite(contour,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.m	(revision 18231)
@@ -0,0 +1,74 @@
+function expcoarsen(newfile,oldfile,resolution)
+%EXPCOARSEN - coarsen an exp contour
+%
+%   This routine read an Argus file and remove points with respect to
+%   the resolution (in meters) given in input. 
+%
+%   Usage:
+%      expcoarsen(newfile,oldfile,resolution)
+%
+%   Example:
+%       expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+
+%Some checks
+if nargin~=3 | nargout
+	error('expcoarsen usage: expcoarsen(newfile,oldfile,resolution)')
+elseif ~exist(oldfile)
+	error(['expcut error message: the file ' oldfile ' does not exist'])
+elseif exist(newfile),
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return;
+	end
+end
+
+%Get exp oldfile
+[path root ext]=fileparts(oldfile);
+A=expread(oldfile);
+numprofiles=size(A,2);
+
+%Go through the profiles
+count=1;
+while count<=numprofiles,
+
+	%get number of points and initialize j
+	numpoints=length(A(count).x);
+	j=1;
+
+	%stop if we have reached end of profile (always keep the last point)
+	while j<numpoints,
+
+		%See whether we keep this point or not
+		distance=sqrt((A(count).x(j)-A(count).x(j+1))^2+(A(count).y(j)-A(count).y(j+1))^2);
+		if distance<resolution & j<numpoints-1  %do not remove last point
+			A(count).x(j+1)=[];
+			A(count).y(j+1)=[];
+			numpoints=numpoints-1;
+		else
+			division=floor(distance/resolution)+1;
+			if division>=2,
+				x=linspace(A(count).x(j),A(count).x(j+1),division)';
+				y=linspace(A(count).y(j),A(count).y(j+1),division)';
+				A(count).x=[A(count).x(1:j);x(2:end-1); A(count).x(j+1:end)];
+				A(count).y=[A(count).y(1:j);y(2:end-1); A(count).y(j+1:end)];
+
+				%update current point
+				j=j+1+division-2;
+				numpoints=numpoints+division-2;
+			else
+				%update current point
+				j=j+1;
+			end
+		end
+	end
+	if length(A(count).x)<=1,
+		A(count)=[];
+		numprofiles=numprofiles-1;
+	else
+		count=count+1;
+	end
+end
+
+%write output
+expwrite(A,newfile);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcoarsen.py	(revision 18231)
@@ -0,0 +1,77 @@
+import os.path
+import numpy as npy
+from collections import OrderedDict
+from expread import expread
+from expwrite import expwrite
+
+def expcoarsen(newfile,oldfile,resolution):
+	""" 
+	EXPCOARSEN - coarsen an exp contour
+
+	This routine read an Argus file and remove points with respect to
+	the resolution (in meters) given in input. 
+
+	Usage:
+	  expcoarsen(newfile,oldfile,resolution)
+
+	Example:
+	   expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+	""" 
+
+	#Some checks
+	if not os.path.exists(oldfile):
+		raise OSError("expcoarsen error message: file '%s' not found!" % oldfile)
+	if os.path.exists(newfile):
+		choice=raw_input('A file ' + newfile + ' already exists, do you want to modify it? (y/n)')
+		if choice not in 'y': 
+			print('no modification done ... exiting')
+			return 0
+
+	#Get exp oldfile
+	contours=expread(oldfile)
+	newcontours=[]
+
+	for contour in  contours:
+		
+		numpoints=npy.size(contour['x'])
+
+		j=0
+		x=contour['x']
+		y=contour['y']
+
+		#stop if we have reached end of profile (always keep the last point)
+		while j<numpoints-1:
+
+			#see whether we keep this point or not
+			distance=npy.sqrt((x[j]-x[j+1])**2+(y[j]-y[j+1])**2)
+			if distance<resolution and j<numpoints-2:   #do not remove last point
+				x=npy.delete(x,j+1,0)
+				y=npy.delete(y,j+1,0)
+				numpoints=numpoints-1
+			else:
+				division=int(npy.floor(distance/resolution)+1)
+				if division>=2:
+					xi=npy.linspace(x[j],x[j+1],division)
+					yi=npy.linspace(y[j],y[j+1],division)
+					
+					x=npy.hstack((x[0:j+1],xi[1:-1],x[j+1:]))
+					y=npy.hstack((y[0:j+1],yi[1:-1],y[j+1:]))
+
+					#update current point
+					j=j+1+division-2
+					numpoints=numpoints+division-2
+				else:
+					#update current point
+					j=j+1
+		
+		if npy.size(x)>1:
+			#keep the (x,y) contour arond
+			newcontour=OrderedDict()
+			newcontour['nods']=npy.size(x)
+			newcontour['density']=contour['density']
+			newcontour['x']=x
+			newcontour['y']=y
+			newcontours.append(newcontour)
+
+	#write output
+	expwrite(newcontours,newfile)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontourlevelzero.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontourlevelzero.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontourlevelzero.m	(revision 18231)
@@ -0,0 +1,13 @@
+function expcontourlevelzero(md,mask,level,filename)
+%EXPCONTOURLEVELZERO - write an Argus file from a structure recovered from running contourlevelzero 
+%
+%   Usage:
+%      expcontourlevelzero(md,mask,level,filename)
+% 
+%   Example:
+%      expcontourlevelzero(md,md.geometry.thickness,0, 'Level0.exp');
+%
+%   See also CONTOURLEVELZERO, EXPWRITE
+
+contours=contourlevelzero(md,mask,level);
+expwrite(contours,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontract.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontract.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expcontract.m	(revision 18231)
@@ -0,0 +1,33 @@
+function normal_node=expcontract(newfile,oldfile,distance)
+%EXPCONTRACT - contract or expand a profile, according to the normal.
+% 
+%   Usage:
+%      expcontract(newfile,oldfile,distance)
+%
+%   See also EXPMASTER, EXPDOC
+
+contour=expread(oldfile);
+num=numel(contour.x);
+
+normal=zeros(num-1,2);
+normal_node=zeros(num-1,2);
+
+for i=1:num-1,
+	normal(i,:)=[ contour.y(i)-contour.y(i+1) contour.x(i+1)-contour.x(i)];
+	normal(i,:)=normal(i,:)/sqrt(normal(i,1)^2+normal(i,2)^2);
+end
+
+normal_node(2:end,:)=[normal(1:end-1,:)+normal(2:end,:)];
+normal_node(1,:)=normal(1,:)+normal(end,:);
+
+normal_node_norm=sqrt(normal_node(:,1).^2+normal_node(:,2).^2);
+normal_node(:,1)=normal_node(:,1)./normal_node_norm;
+normal_node(:,2)=normal_node(:,2)./normal_node_norm;
+
+contour.x(1:end-1)=contour.x(1:end-1)+distance*normal_node(:,1);
+contour.y(1:end-1)=contour.y(1:end-1)+distance*normal_node(:,2);
+
+contour.x(end)=contour.x(1);
+contour.y(end)=contour.y(1);
+
+expwrite(contour,newfile);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expdisp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expdisp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expdisp.m	(revision 18231)
@@ -0,0 +1,57 @@
+function expdisp(domainoutline,varargin)
+%EXPDISP - plot the contours of a domain outline file
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%
+%   Usage:
+%      expdisp(domainoutline,varargin)
+%      expdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%
+%   Example:
+%      expdisp('Domain.exp',1,'--r',2,10^3);
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>5
+	help expdisp
+	error('expdisp error message: bad usage');
+end
+
+%parse input
+if nargin<=1,
+	figurenumber=1;
+else
+	figurenumber=varargin{1};
+end
+if nargin<=2
+	linestyle='r-';
+else
+	linestyle=varargin{2};
+end
+if nargin<=3
+	linewidth=1;
+else
+	linewidth=varargin{3};
+end
+if nargin<=4
+	unitmultiplier=1;
+else
+	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
+end
+
+domain=expread(domainoutline);
+
+figure(figurenumber),hold on
+for i=1:length(domain),		
+	if domain(i).nods==1
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'o','MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',10);
+	else
+		if (isnumeric(linestyle))
+			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+		else
+			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+	  end
+  end
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expexcludeoutliers.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expexcludeoutliers.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expexcludeoutliers.m	(revision 18231)
@@ -0,0 +1,18 @@
+function excludeoutliers(newcontourname,contourname,domainname)
+%EXCLUDEOUTLIERS - exclude points of contour that are not within the domain
+%contour. return new contours in a different file.
+%
+%        Usage: excludeoutliers('NewContour.exp','Contour.exp','DomainOutline.exp');
+%
+%
+%   See also EXPMASTER, EXPDOC
+
+contour=expread(contourname);
+
+for i=1:length(contour),
+	flags=ContourToNodes(contour(i).x,contour(i).y,domainname,0);
+	contour(i).x=contour(i).x(find(flags));
+	contour(i).y=contour(i).y(find(flags));
+end
+
+expwrite(contour,newcontourname);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expflip.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expflip.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expflip.m	(revision 18231)
@@ -0,0 +1,15 @@
+function expflip(domainname)
+%EXPFLIP: flip orientation of all contours and domains in domainname exp file.
+%
+%Usage: expflip('MassFlux1.exp');a
+%
+%
+
+a=expread(domainname);
+
+for i=1:length(a),
+	a(i).x=flipud(a(i).x);
+	a(i).y=flipud(a(i).y);
+end
+
+expwrite(a,domainname);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/explink.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/explink.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/explink.m	(revision 18231)
@@ -0,0 +1,28 @@
+function explink(domainoutline,minthreshold,step)
+%EXPLINK - allow to link several segments of domain outline together
+%
+%   Takes a domain outline made of various segments, and links them together in one 
+%   domain outline. Use expview to see end result.
+%
+%   Usage:
+%      explink(domainoutline,minthreshold,step)
+%
+%   See also EXPMASTER, EXPDOC
+
+notdone=1;
+
+while notdone,
+
+	for i=1:1000,
+		status=expconcatenate(domainoutline,minthreshold+(i-1)*step);
+		if status==0,
+			return;
+		end
+		if status==1,
+			break;
+		end
+		if status==-1,
+			continue;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expll2xy.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expll2xy.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expll2xy.m	(revision 18231)
@@ -0,0 +1,36 @@
+function expll2xy(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expll2xy(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expll2xy
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).x domain(i).y]= ll2xy(domain(i).y,domain(i).x,sgn,delta,slat);
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.m	(revision 18231)
@@ -0,0 +1,81 @@
+function Struct=expread(filename)
+%EXPREAD - read a file exp and build a Structure
+%
+%   This routine reads a file .exp and build a Structure containing the 
+%   fields x and y corresponding to the coordinates, one for the filename of
+%   the exp file, for the density, for the nodes, and a field closed to 
+%   indicate if the domain is closed. 
+%   The first argument is the .exp file to be read and the second one (optional) 
+%   indicate if the last point shall be read (1 to read it, 0 not to).
+%
+%   Usage:
+%      Struct=expread(filename)
+%
+%   Example:
+%      Struct=expread('domainoutline.exp')
+%      Struct=expread('domainoutline.exp')
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+
+%initialize number of profile
+count=0;
+
+%open file
+fid=fopen(filename,'r');
+
+%loop over the number of profiles
+while (~feof(fid)),
+
+	%update number of profiles
+	count=count+1;
+
+	%Get file name
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Name:',7), break; end
+	if length(A)>7, 
+		Struct(count).name=A(8:end);
+	else
+		Struct(count).name='';
+	end
+
+	%Get Icon
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Icon:',7), break; end
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',4);
+	if ~strncmp(A,'#Points',7), break; end
+
+	%Get number of nodes and density
+	A=fscanf(fid,'%f %f',[1 2]);
+	Struct(count).nods=A(1);
+	Struct(count).density=A(2);
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',5);
+	if ~strncmp(A,'#XposYpos',9), break; end
+
+	%Get Coordinates
+	A=fscanf(fid,'%f %f',[2 Struct(count).nods]);
+	Struct(count).x=A(1,:)';
+	Struct(count).y=A(2,:)';
+
+	if(Struct(count).nods~=length(Struct(count).x))error(['Profile ' num2str(count) ' reports incorrect length']); end;
+
+	%Check if closed
+	if (Struct(count).nods > 1) && ...
+	   (Struct(count).x(end) == Struct(count).x(1)) && ...
+	   (Struct(count).y(end) == Struct(count).y(1))
+		Struct(count).closed=true;
+	else
+		Struct(count).closed=false;
+	end
+end
+
+%close file
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expread.py	(revision 18231)
@@ -0,0 +1,100 @@
+import os.path
+import numpy
+from collections import OrderedDict
+import MatlabFuncs as m
+
+def expread(filename):
+	"""
+	EXPREAD - read a file exp and build a Structure
+
+	   This routine reads a file .exp and builds a list of dicts containing the 
+	   fields x and y corresponding to the coordinates, one for the filename of
+	   the exp file, for the density, for the nodes, and a field closed to 
+	   indicate if the domain is closed. 
+	   The first argument is the .exp file to be read and the second one (optional) 
+	   indicate if the last point shall be read (1 to read it, 0 not to).
+
+	   Usage:
+	      contours=expread(filename)
+
+	   Example:
+	      contours=expread('domainoutline.exp')
+	      contours=expread('domainoutline.exp')
+
+	   See also EXPDOC, EXPWRITEASVERTICES
+	"""
+
+	#some checks
+	if not os.path.exists(filename):
+		raise OSError("expread error message: file '%s' not found!" % filename)
+
+	#initialize number of profile
+	contours=[]
+
+	#open file
+	fid=open(filename,'r')
+
+	#loop over the number of profiles
+	while True:
+
+		#update number of profiles
+		contour=OrderedDict()
+
+		#Get file name
+		A=fid.readline()
+		while A=='\n':
+			A=fid.readline()
+		if not A:
+			break
+		A=A.split(None,1)
+		if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Name:',5)):
+			break
+		if len(A[1])>5: 
+			contour['name']=A[1][5:-1]
+		else:
+			contour['name']=''
+
+		#Get Icon
+		A=fid.readline().split(None,1)
+		if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Icon:',5)):
+			break
+
+		#Get Info
+		A=fid.readline().split()
+		if not (len(A) == 4 and m.strcmp(A[0],'#') and m.strcmp(A[1],'Points')):
+			break
+
+		#Get number of nodes and density
+		A=fid.readline().split()
+		contour['nods']=int(A[0])
+		contour['density']=float(A[1])
+
+		#Get Info
+		A=fid.readline().split()
+		if not (len(A) == 5 and m.strcmp(A[0],'#') and m.strcmp(A[1],'X') and m.strcmp(A[2],'pos') \
+		                                         and m.strcmp(A[3],'Y') and m.strcmp(A[4],'pos')):
+			break
+
+		#Get Coordinates
+		contour['x']=numpy.empty(contour['nods'])
+		contour['y']=numpy.empty(contour['nods'])
+		for i in xrange(int(contour['nods'])):
+			A=fid.readline().split()
+			contour['x'][i]=float(A[0])
+			contour['y'][i]=float(A[1])
+
+		#Check if closed
+		if (contour['nods'] > 1) and \
+		   (contour['x'][-1] == contour['x'][0]) and \
+		   (contour['y'][-1] == contour['y'][0]):
+			contour['closed']=True
+		else:
+			contour['closed']=False
+
+		contours.append(contour)
+
+	#close file
+	fid.close()
+
+	return contours
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expsquare.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expsquare.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expsquare.m	(revision 18231)
@@ -0,0 +1,45 @@
+function expsquare(filename)
+%EXPBOX - Create a ARGUS file using to clicks
+%
+%   Two clicks on a plot are used to generate a square box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a square domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+xmiddle=mean(x);
+ymiddle=mean(y);
+
+x1=x(1); y1=y(1);
+x3=x(2); y3=y(2);
+
+Diag=[x1-xmiddle;y1-ymiddle];
+
+Vector=[xmiddle;ymiddle]+[-Diag(2);Diag(1)];
+x2=Vector(1); y2=Vector(2);
+
+Vector=[xmiddle;ymiddle]-[-Diag(2);Diag(1)];
+x4=Vector(1); y4=Vector(2);
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expswapxy.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expswapxy.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expswapxy.m	(revision 18231)
@@ -0,0 +1,22 @@
+function expswapxy(filename)
+%EXPSWAP - swap x and y fields
+% 
+%   Usage:
+%      expswap(file)
+%
+%   See also EXPMASTER, EXPDOC
+
+contours=expread(filename,1);
+
+newcontours=contours(1);
+
+for i=1:length(contours), 
+	contour=contours(i);
+	newcontour=contour;
+	newcontour.x=contour.y;
+	newcontour.y=contour.x;
+	newcontours(end+1)=newcontour;
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exptool.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exptool.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/exptool.m	(revision 18231)
@@ -0,0 +1,350 @@
+function exptool(newfile,varargin)
+%EXPTOOL - allow to create, modify, add, cut, .. segments of domain outline together
+%
+%   this routine is used to create, modify, cut,... an Argus file (.exp)
+%
+%   exptool(newprofile,'optionname',optionvalue)
+%      creation of an argus file newprofile
+%
+%   Available options:
+%      - include: include list of existing ARGUS files
+%      - color: line color (default='r')
+%      - selectioncolor: line color of selected profiles (default='b')
+%      - linestyle (default='-')
+%      - linewidth (default=0.2)
+%      - marker (default='+')
+%      - markersize (default=7)
+%      - markeredgecolor (default='r')
+%
+%   Usage:
+%      exptool(newfile,varargin)
+%
+%   Example:
+%      exptool('domain.exp','include',{'domain1.exp' 'domain2.exp'},'color','g','marker','+')
+%
+%   See also EXPDOC
+
+%recover options
+options=pairoptions(varargin{:});
+
+%Some checks
+if ~nargin | nargout
+	error('exptool usage: exptool(newfile,varargin)')
+elseif exist(newfile,'file'),
+	%recursive call to exptool if file already exists
+	if ~exist(options,'include'),
+		exptool(newfile,'include',newfile,varargin{:});
+		return;
+	end
+
+	%check modification
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Add default options
+options=addfielddefault(options,'color','r');
+options=addfielddefault(options,'selectioncolor','b');
+options=addfielddefault(options,'LineStyle','-');
+options=addfielddefault(options,'LineWidth',0.2);
+options=addfielddefault(options,'Marker','+');
+options=addfielddefault(options,'MarkerSize',7);
+options=addfielddefault(options,'MarkerEdgeColor','r');
+
+%put all the argus profiles given in input in one structure A
+A=struct([]);
+numprofiles=0;
+numpoints=0;
+closed=[];
+
+%initialize the variables with files provided by 'include' option
+if exist(options,'include'),
+	files=getfieldvalue(options,'include');
+	if ischar(files), files={files}; end
+	for i=1:length(files),
+		filename=files{i};
+		if ~exist(filename,'file'),
+			error(['exptool error message:, ' filename ' does not exist. Exiting...']);
+		else
+			%read file
+			B=expread(filename);
+			%go through all profiles of B
+			for i=1:size(B,2)
+				%plug profile in A
+				if numprofiles
+					A(numprofiles+1)=B(i);
+				else
+					A=B(i);
+				end
+				%update numprofiles and numpoints
+				numpoints=numpoints+length(B(i).x);
+				numprofiles=numprofiles+1;
+				%figure out if the profile is closed or not
+				if (B(i).x(1)==B(i).x(end) & B(i).y(1)==B(i).y(end) & length(B(i).x)>1 )
+					closed(numprofiles)=1;
+				else
+					closed(numprofiles)=0;
+				end
+			end
+		end
+	end
+end
+
+%Get root of newfile
+[path root ext]=fileparts(newfile);
+
+%get current figure
+if ~isempty(get(0,'children')),%if there is already a figure (return the number of opened figures)
+	set(gcf,'Renderer','zbuffer'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+	P=get(gcf,'position');
+	F=getframe(gca);
+	F=F.cdata;
+	%get current axis
+	xlim=get(gca,'Xlim');
+	ylim=get(gca,'Ylim');
+	%recreate x_m and y_m
+	x_m=linspace(xlim(1),xlim(2),size(F,2));
+	y_m=linspace(ylim(2),ylim(1),size(F,1)); %getframe reverse axis...
+	%plot the data in another figure
+	figure; set(gcf,'position',P);
+	imagesc(x_m,y_m,F); set(gca,'Ydir','normal');
+	prevplot=1;
+	prevplot2=1;
+else
+	figure
+	prevplot=0;
+	prevplot2=0;
+end
+
+%plot existing profile if any
+hold on
+
+%Build backup structre for do and redo
+backup=cell(1,3);
+backup{1,1}=A;
+backup{1,2}=numprofiles;
+backup{1,3}=numpoints;
+backup{1,4}=closed;
+
+loop=1;
+counter=1;
+while loop
+
+	%Go through A and rule out the empty profiles
+	list=[];
+	for i=1:size(A,2);
+		if length(A(i).x)==0
+			list(end+1)=i;
+			numprofiles=numprofiles-1;
+		end
+	end
+	A(list)=[];
+	closed(list)=[];
+
+	%Now erase all that have been done and plot the new structure A as it is
+	undoplots(prevplot);
+	if numprofiles
+		prevplot2=1;
+		for i=1:numprofiles
+			if length(A(i).x)==1,
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+			else
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			prevplot2=prevplot2+1;
+		end
+	end
+
+	%display menu
+	title('Main Menu','FontSize',14);
+   UIControl_FontSize_bak = get(0, 'DefaultUIControlFontSize');
+   set(0, 'DefaultUIControlFontSize',10);
+   button=menu('exptool menu',...
+      'add a profile (open)',...                %1
+      'add a contour (closed)',...              %2
+      'remove a profile',...                    %3
+      'modify the position of a point',...      %4
+      'add points inside a profile',...         %5
+      'add points at the end of a profile',...  %6
+      'remove points',...                       %7
+      'remove several points',...               %8
+      'cut a segment',...                       %9
+      'cut a large area',...                    %10
+      'merge profiles',...                      %11
+      'close profile',...                       %12
+		'change orientation',...                  %13
+      'undo',...                                %14
+      'redo',...                                %15
+      'quit');                                  %16
+   set(0, 'DefaultUIControlFontSize', UIControl_FontSize_bak);
+
+	%UNDO??
+	if button==14;
+		if counter==1
+			disp('Already at oldest change');
+		else
+			counter=counter-1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	%REDO??
+	elseif button==15
+		if counter==size(backup,1)
+			disp('Already at newest change');
+		else
+			counter=counter+1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	end
+
+	switch button
+
+		case 1
+
+			[A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 2
+
+			[A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 3
+
+			[A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 4
+
+			[A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 5
+
+			[A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 6
+
+			[A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 7
+
+			[A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 8
+
+			[A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 9
+
+			[A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 10
+
+			[A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 11
+
+			[A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 12
+
+			[A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 13
+
+			[A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+			%QUIT
+		case 16
+
+			loop=0;
+
+		otherwise
+			%do nothing
+	end
+
+end
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting...','FontSize',14);
+if isempty(A)
+	disp('Profile empty, no file written')
+else
+	expwrite(A,newfile);
+end
+
+%close window
+close;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.m	(revision 18231)
@@ -0,0 +1,57 @@
+function expwrite(a,filename)
+%EXPWRITE - write an Argus file from a structure given in input
+%
+%   This routine write an Argus file form a structure containing the fields:
+%   x and y of the coordinates of the points.
+%   The first argument is the structure containing the points coordinates 
+%   and the second one the file to be write.
+%
+%   Usage:
+%      expwrite(a,filename)
+% 
+%   Example:
+%      expwrite(coordstruct,'domainoutline.exp')
+%
+%   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+
+%check input variable
+if ~isstruct(a),
+	error('first argument is not a structure');
+end
+
+%Add density if it's not there
+if ~isfield(a,'density'),
+	for n=1:length(a),
+		a(n).density=1;
+	end
+end
+
+fid=fopen(filename,'w');
+for n=1:length(a),
+	if(length(a(n).x)~=length(a(n).y)),
+		error('contours x and y coordinates must be of identical size');
+	end
+
+	if isfield(a,'name'),
+		fprintf(fid,'%s%s\n','## Name:',a(n).name);
+	else
+		fprintf(fid,'%s%s\n','## Name:',filename);
+	end
+
+	fprintf(fid,'%s\n','## Icon:0');
+	fprintf(fid,'%s\n','# Points Count Value');
+	if isfield(a,'density'),
+		if ~isempty(a(n).density),
+			fprintf(fid,'%i %f\n',[length(a(n).x) a(n).density]);
+		else
+			fprintf(fid,'%i %f\n',[length(a(n).x) 1.]);
+		end
+	else
+		fprintf(fid,'%i %f\n',[length(a(n).x) 1.]);
+	end
+	fprintf(fid,'%s\n','# X pos Y pos');
+	fprintf(fid,'%10.10f %10.10f\n',[a(n).x(:) a(n).y(:)]');
+	fprintf(fid,'\n');
+
+end
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expwrite.py	(revision 18231)
@@ -0,0 +1,44 @@
+import numpy
+
+def expwrite(contours,filename):
+	"""
+	EXPWRITE - write an Argus file from a structure given in input
+
+	   This routine writes an Argus file from a list of dict's containing the fields:
+	   x and y of the coordinates of the points.
+	   The first argument is the list containing the points coordinates 
+	   and the second one the file to be written.
+
+	   Usage:
+	      expwrite(contours,filename)
+
+	   Example:
+	      expwrite(coordstruct,'domainoutline.exp')
+
+	   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+	"""
+
+	fid=open(filename,'w')
+	for contour in contours:
+		if numpy.size(contour['x'])!=numpy.size(contour['y']):
+			raise RuntimeError("contours x and y coordinates must be of identical size")
+   
+		if 'name' in contour:
+			fid.write("%s%s\n" % ('## Name:',contour['name']))
+		else:
+			fid.write("%s%s\n" % ('## Name:',filename))
+   
+		#Add density if it's not there
+		if 'density' not in contour:
+			contour['density']=1
+
+		fid.write("%s\n" % '## Icon:0')
+		fid.write("%s\n" % '# Points Count Value')
+		fid.write("%i %f\n" % (numpy.size(contour['x']),contour['density']))
+		fid.write("%s\n" % '# X pos Y pos')
+		for x,y in zip(contour['x'],contour['y']):
+			fid.write("%10.10f %10.10f\n" % (x,y))
+		fid.write("\n")
+
+	fid.close()
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expxy2ll.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expxy2ll.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/expxy2ll.m	(revision 18231)
@@ -0,0 +1,36 @@
+function expxy2ll(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expxy2ll(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expxy2ll
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).y domain(i).x]= xy2ll(domain(i).x,domain(i).y,sgn,delta,slat); %watch out to swap lat and long
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/flowlines.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/flowlines.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/flowlines.m	(revision 18231)
@@ -0,0 +1,167 @@
+function flowpath=flowlines(index,x,y,u,v,x0,y0,varargin)
+%FLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=flowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=flowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>8 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==8
+	maxiter=varargin{1};
+else
+	maxiter=200; %maximum number of iterations
+end
+precision=1; %division of each segment (higer precision increases number of segments)
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+%tria=tsearch(x,y,index,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+	%tria=tsearch(x,y,index,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
+
+%same process but reverse (vel=-vel) to have a vcomplete flow line
+queue=[];
+counter=1;
+X=x0; Y=y0;
+done=zeros(N,1);
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+	%tria=tsearch(x,y,index,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(1)=[];
+		flowpath(queue(listnan(i))).y(1)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=-u(tria); vt=-v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going backward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision; flowpath(queue(i)).x];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision; flowpath(queue(i)).y];
+	end
+end
+
+%EXP compatibility
+for i=1:length(queue)
+	flowpath(queue(i)).name=['flowline' num2str(i)];
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/masktoexp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/masktoexp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/masktoexp.m	(revision 18231)
@@ -0,0 +1,32 @@
+function masktoexp(x,y,mask,threshold,filename)
+%MASKTOEXP - mask to exp file
+%
+%   Usage:
+%      masktoexp(x,y,mask,threshold,filename)
+%
+%   Example:
+%      if A is a matrix of 0 and 1, and we want an exp for
+%      the transition:
+%      masktoexp(x,y,A,0.5,'contour.exp');
+%      To be combined with ExpSimplify
+
+%Create contour for threshold
+c=contourc(double(x),double(y),double(mask),[threshold threshold]);
+done=0; i=1; j=1;
+while (i<length(c))
+	num=c(2,i); i=i+1;
+	s(j).x=c(1,i:(i+num-1));
+	s(j).y=c(2,i:(i+num-1));
+	s(j).v=c(1,i);
+	i=i+num; j=j+1;
+end;
+
+%Create exp structure
+A=struct();
+for i=1:j-1,
+	A(i).x=s(i).x;
+	A(i).y=s(i).y;
+end;
+
+%write exp
+expwrite(A,filename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addcontour.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addcontour.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addcontour.m	(revision 18231)
@@ -0,0 +1,50 @@
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDCONTOUR - add a closed contour
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				x(end+1)=x(1);
+				y(end+1)=y(1);
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=1;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addendprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addendprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addendprofile.m	(revision 18231)
@@ -0,0 +1,86 @@
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDENDPROFILE - add point at the end of a n existing profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if ~any(~closed)
+		disp('all profiles are closed')
+		return
+	end	   
+	%select a profile first
+	if numprofiles>1
+		%first step, select a profile
+		isclosed=1;
+		title('click on a profile, RETURN to exit','FontSize',14)
+		while isclosed
+			[xi,yi] = ginput(1);
+			if ~isempty(xi)
+				%get the closest point 
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if closed(profsel)
+					disp('selected profile is closed, make another selection')
+				else
+					isclosed=0;
+				end
+
+			else
+				%RETURN -> out
+				return
+			end
+		end
+	else
+		profsel=1;
+	end
+
+	%initialize x and y
+	x=A(profsel).x;
+	y=A(profsel).y;
+
+	%plot the selected profile
+	hold on
+	plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+		'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	loop=1;
+	while loop
+
+		%first step, select a profile
+		title('click to add point to the selected profile, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize')+2,'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(profsel).x=x; 
+				A(profsel).y=y; 
+				A(profsel).name=root; 
+				A(profsel).density=1; 
+				numpoints=numpoints+length(x);
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addinsideprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addinsideprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addinsideprofile.m	(revision 18231)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDINSIDEPROFILE - add apoint inside a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are required, exiting...')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%first step, select a segment
+		title('click on a segment, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		%first click
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least two points in one profile are required, exiting...')
+				return
+			end
+
+			%highlight selected segment
+			plot([A(profsel).x(indsel) A(profsel).x(indsel+1)],[A(profsel).y(indsel) A(profsel).y(indsel+1)],...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%next click
+			title('click on the new point''s location, RETURN to exit','FontSize',14)
+			[xi,yi,but] = ginput(1);
+
+			%second click
+			if ~isempty(xi)
+
+				%add point to A
+				A(profsel).x=[A(profsel).x(1:indsel,1); xi; A(profsel).x(indsel+1:end,1)];
+				A(profsel).y=[A(profsel).y(1:indsel,1); yi; A(profsel).y(indsel+1:end,1)];
+				numpoints=numpoints+1;
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+
+			else
+				%RETURN->exit
+				return
+			end
+		else
+			%RETURN-> exit
+			return
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/addprofile.m	(revision 18231)
@@ -0,0 +1,48 @@
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDPROFILE - add a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=0;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closeprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closeprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closeprofile.m	(revision 18231)
@@ -0,0 +1,68 @@
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CLOSEPROFILE - close one or several profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile to be closed')
+		return
+	end
+
+	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks,
+		if numprofiles==0    
+			disp('no profile present, exiting...')
+			return            
+		end  
+		if ~any(~closed),
+			disp('All the profiles are closed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from the selection
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			elseif closed(profsel),
+				%profile already closed, do nothing
+				disp('selected profile aready closed, make another selection'),
+			else
+				%add the profile to the list to be closed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%close the profiles
+			for i=1:length(selection),
+				A(selection(i)).x(end+1)=A(selection(i)).x(1);
+				A(selection(i)).y(end+1)=A(selection(i)).y(1);
+				numpoints=numpoints+1;
+				closed(selection(i))=1;
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestpoint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestpoint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestpoint.m	(revision 18231)
@@ -0,0 +1,21 @@
+function [profsel indsel]=closestpoint(A,numprofiles,xi,yi)
+%CLOSESTPOINT - find the closest point of a profile
+%
+%   This routine find the point of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the point
+%
+%   Usage:
+%     [profsel indsel]=closestpoint(A,numprofiles,xi,yi) 
+
+	%loop over the points of each profile, find the closest to (xi,yi)
+	for i=1:numprofiles,
+		distance=(xi-A(i).x).^2+(yi-A(i).y).^2;
+		[newdistance p]=min(distance);
+		if ((i==1) | (newdistance<olddistance)),
+			indsel=p;
+			profsel=i;
+			olddistance=newdistance;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestsegment.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestsegment.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/closestsegment.m	(revision 18231)
@@ -0,0 +1,28 @@
+function [profsel indsel]=closestsegment(A,numprofiles,xi,yi)
+%CLOSESTSEGMENT - find the closest segment of a profile
+%
+%   This routine find the segment of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the first point belonging to this closest segment
+%
+%   Usage:
+%     [profsel indsel]=closestsegment(A,numprofiles,xi,yi) 
+
+	%loop over the middles of each profile, find the closest to (xi,yi)
+	profsel=0;
+	indsel=0;
+	first=1;
+	for i=1:numprofiles,
+		if length(A(i).x)>1
+			middles=[(A(i).x(1:end-1)+A(i).x(2:end))/2 (A(i).y(1:end-1)+A(i).y(2:end))/2];
+			distance=(xi-middles(:,1)).^2+(yi-middles(:,2)).^2;
+			[newdistance p]=min(distance);
+			if (first | (newdistance<olddistance)),
+				first=0;
+				indsel=p;
+				profsel=i;
+				olddistance=newdistance;
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutarea.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutarea.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutarea.m	(revision 18231)
@@ -0,0 +1,156 @@
+function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CUTAREA - cut several point of a profile
+%
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must click 3 times to select the
+%   area to be removed. Twice to select the tips and one to select
+%   the part of the profile to be removed
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile present, exiting...')
+			return
+		end	   
+		if numpoints<3
+			disp('at least two points are needed, exiting...')
+			return
+		end	   
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be cut, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						x=A(selection).x; y=A(selection).y;
+						if p1<p2
+							if p3>p1 & p3<p2
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p2:end-1,1);A(selection).x(1:p1,1)];
+									A(selection).y=[A(selection).y(p2:end-1,1);A(selection).y(1:p1,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									A(selection).x=x(1:p1);
+									A(selection).y=y(1:p1);
+									closed(selection)=0;
+									A(end+1).x=x(p2:end);
+									A(end).y=y(p2:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p2-p1-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								A(selection).x=x(p1:p2);
+								A(selection).y=y(p1:p2);
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						else
+							if p3>p2 & p3<p1
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p1:end-1,1);A(selection).x(1:p2,1)];
+									A(selection).y=[A(selection).y(p1:end-1,1);A(selection).y(1:p2,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									closed(selection)=0;
+									A(selection).x=x(1:p2);
+									A(selection).y=y(1:p2);
+									A(end+1).x=x(p1:end);
+									A(end).y=y(p1:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p1-p2-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								x(1:p2-1)=[];x(p1-p2+2:end)=[];%it should have been x(p2+1:end)
+								y(1:p2-1)=[];y(p1-p2+2:end)=[];
+								A(selection).x=x;
+								A(selection).y=y;
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						end
+
+						%plot new profile
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/cutprofile.m	(revision 18231)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CUTPROFILE - cut a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are needed')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%select a segment
+		title('click the segment to cut, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least 2 points are required');
+				return,
+			end
+
+			if ((closed(profsel) & length(A(profsel).x)<3) | (~closed(profsel) & length(A(profsel).x)<2))
+				disp('at least 2 points are required, make another selection');
+			else
+				%cut A
+				if closed(profsel)
+					%open the contour
+					A(profsel).x=[A(profsel).x(indsel+1:end-1,1);A(profsel).x(1:indsel,1)];
+					A(profsel).y=[A(profsel).y(indsel+1:end-1,1);A(profsel).y(1:indsel,1)];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				else
+					%cut the contour in 2 profiles
+					A(end+1).x=A(profsel).x(indsel+1:end,1);
+					A(end).y=A(profsel).y(indsel+1:end,1);
+					A(end).name=root; 
+					A(end).density=1; 
+					A(profsel).x=A(profsel).x(1:indsel,1);
+					A(profsel).y=A(profsel).y(1:indsel,1);
+					numprofiles=numprofiles+1;
+					closed(end+1)=0;
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			end
+		else
+			%RETURN->exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/mergeprofiles.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/mergeprofiles.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/mergeprofiles.m	(revision 18231)
@@ -0,0 +1,152 @@
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+%MERGEPROFILES - merge profiles
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must select the two tips that
+%   he/she wants to merge
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+hold on
+loop=1;
+
+%Take all the tips coordinates of open profiles
+counter=1; tips=[];
+for i=1:numprofiles
+	if ~closed(i),
+		%x and y coord, profile number, 1 if beginning, 2 and if end
+		if length(A(i).x)==1,
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			counter=counter+1;
+		else
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+			counter=counter+2;
+		end
+	end
+end
+
+if size(tips,1)<2
+	disp('at least one unclosed profile is required')
+	return
+end
+
+%plot the tips only
+plot(tips(:,1),tips(:,2),...
+	'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+firsttip=1;
+
+%loop (at least 2 clicks needed)
+while loop
+
+	%some checks
+	if size(tips,1)<2
+		disp('at least one unclosed profiles are required')
+		return
+	end
+
+	%select a point
+	if firsttip
+		title('click on the first tip, RETURN to exit','FontSize',14)
+	else
+		title('click on the second tip, RETURN to exit','FontSize',14)
+	end
+
+	[xi,yi] = ginput(1);
+
+	if ~isempty(xi)
+
+		if firsttip
+			%find the selected tip
+			distance=(xi-tips(:,1)).^2+(yi-tips(:,2)).^2;
+			[dmin tip1]=min(distance);
+			numprofile1=tips(tip1,3);
+			firsttip=0;
+
+			%remove tip1 from tips list
+			newtips=tips;
+			newtips(tip1,:)=[];
+
+			%plot selected tip
+			plot(tips(tip1,1),tips(tip1,2),...
+				'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(A(numprofile1).x,A(numprofile1).y,...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+
+		%second selection
+		else
+			distance=(xi-newtips(:,1)).^2+(yi-newtips(:,2)).^2;
+			[dmin tip2]=min(distance);
+			numprofile2=newtips(tip2,3);
+
+			if numprofile1==numprofile2
+				%close the profile
+				A(numprofile1).x(end+1)=A(numprofile1).x(1);
+				A(numprofile1).y(end+1)=A(numprofile1).y(1);
+				numpoints=numpoints+1;
+				closed(numprofile1)=1;
+
+			else
+
+				if tips(tip1,4)==1 & newtips(tip2,4)==1,
+					A(numprofile1).x=[flipud(A(numprofile2).x); A(numprofile1).x];
+					A(numprofile1).y=[flipud(A(numprofile2).y); A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==1 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile2).x; A(numprofile1).x];
+					A(numprofile1).y=[A(numprofile2).y; A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==1,
+					A(numprofile1).x=[A(numprofile1).x; A(numprofile2).x];
+					A(numprofile1).y=[A(numprofile1).y; A(numprofile2).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile1).x; flipud(A(numprofile2).x)];
+					A(numprofile1).y=[A(numprofile1).y; flipud(A(numprofile2).y)];
+					numprofiles=numprofiles-1;
+				end
+
+				%delete profile2
+				A(numprofile2)=[];
+				closed(numprofile2)=[];
+
+			end
+
+			%update tips
+			counter=1; tips=[];
+			for i=1:numprofiles
+				if ~closed(i),
+					%x and y coord, profile number, 1 if beginning, 2 and if end
+					if length(A(i).x)==1,
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						counter=counter+1;
+					else
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+						counter=counter+2;
+					end
+				end
+			end
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			if ~isempty(tips)
+				plot(tips(:,1),tips(:,2),...
+					'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			end
+
+			%back to beginning
+			firsttip=1;
+		end
+	else
+		%RETRUN-> quit
+		loop=0;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/modifyposition.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/modifyposition.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/modifyposition.m	(revision 18231)
@@ -0,0 +1,77 @@
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+%MODIFYPOSITION - modify the prosition of a point of a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting..')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	while loop
+
+		%select a point to be modified 
+		title('click on the point to be modified, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%plot the point in blue
+			plot(A(profsel).x(indsel),A(profsel).y(indsel),...
+				'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%select new location
+			title('click on the new location, RETURN to exit','FontSize',14)
+			[xi,yi] = ginput(1);
+
+			if ~isempty(xi)
+
+				%modification of its coordinates
+				A(profsel).x(indsel)=xi;
+				A(profsel).y(indsel)=yi;
+
+				%modify the last point if the profile is closed and indsel=end or 1
+				if closed(profsel)
+					if indsel==1 
+						A(profsel).x(end)=xi;
+						A(profsel).y(end)=yi;
+					elseif indsel==length(A(profsel).x)
+						A(profsel).x(1)=xi;
+						A(profsel).y(1)=yi;
+					end
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			else
+				%RETURN-> exit
+				loop=0;
+			end
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/orientprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/orientprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/orientprofile.m	(revision 18231)
@@ -0,0 +1,54 @@
+function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ORIENTPROFILE - cahnge profile orientation
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be reoriented, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be reoriented, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from list
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%reorient profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				A(selection(i)).x=flipud(A(selection(i)).x);
+				A(selection(i)).y=flipud(A(selection(i)).y);
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removepoints.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removepoints.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removepoints.m	(revision 18231)
@@ -0,0 +1,85 @@
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVEPOINTS - remove a point from a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	end
+
+	while loop
+
+		%check that at least one point is present
+		if numpoints==0
+			disp('at least one point are needed')
+			return
+		end	   
+
+		%select a point to be deleted
+		title('click on the point to be removed, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%remove point of A
+			A(profsel).x(indsel)=[];
+			A(profsel).y(indsel)=[];
+
+			%unclose the domain if only 2 points remaining
+			if closed(profsel)
+				if length(A(profsel).x)==3
+					A(profsel).x(end)=[];
+					A(profsel).y(end)=[];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				end
+			end
+
+			%remove the last point if the profile is closed and indsel=end or 1
+			if closed(profsel)
+				if indsel==1 
+					A(profsel).x(end)=A(profsel).x(1);
+					A(profsel).y(end)=A(profsel).y(1);
+				elseif indsel==length(A(profsel).x)
+					A(profsel).x(1)=A(profsel).x(end);
+					A(profsel).y(1)=A(profsel).y(end);
+				end
+			end
+			numpoints=numpoints-1;
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				if length(A(i).x)==1
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+				end
+			end
+
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeprofile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeprofile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeprofile.m	(revision 18231)
@@ -0,0 +1,56 @@
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVEPROFILE - delete a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be removed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be removed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%remove the profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				numprofiles=numprofiles-1;
+				numpoints=numpoints-length(A(selection(i)-(i-1)).x);
+				A(selection(i)-(i-1))=[];
+				closed(selection(i)-(i-1))=[];
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeseveralpoints.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeseveralpoints.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/removeseveralpoints.m	(revision 18231)
@@ -0,0 +1,130 @@
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVESEVERALPOINTS - remove several point
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<3
+		disp('at least 3 points are required, exiting...')
+		return
+	end	   
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numpoints<3
+			disp('at least 3 points are required, exiting...')
+			return
+		end
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be removed, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+				%disp(['p1= ' num2str(indsel)]),
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+						%disp(['p2= ' num2str(indsel)]),
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						%disp(['p3= ' num2str(indsel)]),
+						if p1<p2
+							if p3>p1 & p3<p2
+								A(selection).x(p1+1:p2-1)=[];
+								A(selection).y(p1+1:p2-1)=[];
+								numpoints=numpoints-(p2-p1-1);
+							else
+								A(selection).x=A(selection).x(p1:p2);
+								A(selection).y=A(selection).y(p1:p2);
+								numpoints=numpoints-(numpoints-1-p2)-(p1-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						else
+							if p3>p2 & p3<p1
+								A(selection).x(p2+1:p1-1)=[];
+								A(selection).y(p2+1:p1-1)=[];
+								numpoints=numpoints-(p1-p2-1);
+							else
+								A(selection).x=A(selection).x(p2:p1);
+								A(selection).y=A(selection).y(p2:p1);
+								numpoints=numpoints-(numpoints-1-p1)-(p2-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						end
+
+						%plot new profiles
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/undoplots.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/undoplots.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/exp/operation/undoplots.m	(revision 18231)
@@ -0,0 +1,12 @@
+function  undoplots(prevplot)
+%UNDOPLOTS - undo plots
+%
+%   Usage:undoplots(prevplot)
+
+	%erase all previous plots
+	g=get(gca,'children');
+	L=length(g);
+	for i=1:L-prevplot
+		delete(g(i));
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.m	(revision 18231)
@@ -0,0 +1,33 @@
+function  vector_average=DepthAverage(md,vector)
+%DEPTHAVERAGE - computes depth average of 3d vector using the trapezoidal rule, and returns the value on 2d mesh. 
+%
+%   Usage:
+%      vector_average=DepthAverage(md,vector);
+%
+%   Example:
+%      vel_bar=DepthAverage(md,md.initialization.vel);
+
+%check that the model given in input is 3d
+if ~strcmp(md.mesh.elementtype(),'Penta');
+	error('DepthAverage error message: the model given in input must be 3d')
+end
+
+%nods data
+if (length(vector)==md.mesh.numberofvertices),
+	vector_average=zeros(md.mesh.numberofvertices2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+(project2d(md,vector,i)+project2d(md,vector,i+1))/2.*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+%element data
+elseif (length(vector)==md.mesh.numberofelements),
+	vector_average=zeros(md.mesh.numberofelements2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+project2d(md,vector,i).*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+else
+	error('vector size not supported yet');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/DepthAverage.py	(revision 18231)
@@ -0,0 +1,50 @@
+import numpy as npy
+from project2d import project2d
+
+def DepthAverage(md,vector):
+	'''
+	computes depth average of 3d vector using the trapezoidal rule, and returns
+	the value on the 2d mesh. 
+	
+	Usage:
+		vector_average=DepthAverage(md,vector)
+	
+	Example:
+		vel_bar=DepthAverage(md,md.initialization.vel)
+	'''
+
+	#check that the model given in input is 3d
+	if md.mesh.elementtype() != 'Penta':
+		raise TypeError('DepthAverage error message: the model given in input must be 3d')
+
+	# coerce to array in case float is passed
+	if type(vector)!=npy.ndarray:
+		print 'coercing array'
+		vector=npy.array(value)
+
+	vec2d=False
+	if vector.ndim==2:
+		vec2d=True
+		vector=vector.reshape(-1,)
+
+	#nods data
+	if vector.shape[0]==md.mesh.numberofvertices:
+		vector_average=npy.zeros(md.mesh.numberofvertices2d)
+		for i in xrange(1,md.mesh.numberoflayers):
+			vector_average=vector_average+(project2d(md,vector,i)+project2d(md,vector,i+1))/2.*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i))
+		vector_average=vector_average/project2d(md,md.geometry.thickness,1)
+	
+	#element data
+	elif vector.shape[0]==md.mesh.numberofelements:
+		vector_average=npy.zeros(md.mesh.numberofelements2d)
+		for i in xrange(1,md.mesh.numberoflayers):
+			vector_average=vector_average+project2d(md,vector,i)*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i))
+		vector_average=vector_average/project2d(md,md.geometry.thickness,1)
+	
+	else:
+		raise ValueError('vector size not supported yet');
+
+	if vec2d:
+		vector_average=vector_average.reshape(-1,1)
+
+	return vector_average
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.m	(revision 18231)
@@ -0,0 +1,36 @@
+function projection_value=project2d(md3d,value,layer)
+%PROJECT2D - returns the value of a field for a given layer of the mesh
+%
+%   project 'value' vector taken at layer 'layer' from extruded 2d-3d mesh onto 2d mesh 
+%   used to do the extrusion. This routine is used to compare values between a 2d-3d mesh
+%   at a certain layer, and the equivalent value (if it exists), on the original 2d mesh. 
+%   This routine relies heavily on projections (contained in 3d model md) recored during 
+%   the extrude operation.
+%
+%   Usage:
+%      projection_value=project2d(md3d,value,layer)
+%
+%   Example:
+%      vel2=project2d(md3d,md3d.vel,2);
+
+%some checks on list of arguments
+if ((nargin~=3) ),
+	help project2d
+	error('project2d error message');
+end
+
+if ~strcmp(md3d.mesh.domaintype,'3D');
+	error('wrong model type ... should be ''3d''');
+end
+
+if ((layer<1) | (layer>md3d.mesh.numberoflayers)),
+	error(['layer must be between 1 and ' num2str(md3d.mesh.numberoflayers)]);
+end
+
+if size(value,1)==md3d.mesh.numberofvertices,
+	projection_value=value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:);
+elseif size(value,1)==md3d.mesh.numberofvertices+1,
+	projection_value=[value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:); value(end,:)];
+else
+	projection_value=value((layer-1)*md3d.mesh.numberofelements2d+1:layer*md3d.mesh.numberofelements2d,:);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project2d.py	(revision 18231)
@@ -0,0 +1,53 @@
+import numpy as npy
+
+def project2d(md3d,value,layer):
+	'''
+	returns the value of a field for a given layer of the mesh
+	
+	project 'value' vector taken at layer 'layer' from extruded 2d-3d
+	mesh onto 2d mesh used to do the extrusion. This routine is used to
+	compare values between a 2d-3d mesh at a certain layer, and the
+	equivalent value (if it exists), on the original 2d mesh.	
+
+	Note: for consistency with usage in ISSM, layers are indexed starting
+	from one.  This routine accounts for the fact that python indexes from
+	zero.  In other words, when using this function consider the bottom
+	layer as layer=1.  
+
+   Usage:
+      projection_value=project2d(md3d,value,layer)
+
+   Example:
+      vel2=project2d(md3d,md3d.vel,2)
+	'''
+
+	if md3d.mesh.domaintype().lower() != '3d':
+		raise StandardError("model passed to project2d function should be 3D")
+
+	if layer<1 or layer>md3d.mesh.numberoflayers:
+		raise ValueError("layer must be between 0 and %i" % md3d.mesh.numberoflayers)
+	
+	# coerce to array in case float is passed
+	if type(value)!=npy.ndarray:
+		print 'coercing array'
+		value=npy.array(value)
+
+	vec2d=False
+	if value.ndim==2 and value.shape[1]==1: 
+		value=value.reshape(-1,)
+		vec2d=True
+
+	if value.size==1:
+		projection_value=value[(layer-1)*md3d.mesh.numberofelements2d:layer*md3d.mesh.numberofelements2d]
+	elif value.shape[0]==md3d.mesh.numberofvertices:
+		#print 'indices: ', (layer-1)*md3d.mesh.numberofvertices2d, layer*md3d.mesh.numberofvertices2d
+		projection_value=value[(layer-1)*md3d.mesh.numberofvertices2d:layer*md3d.mesh.numberofvertices2d]
+	elif value.shape[0]==md3d.mesh.numberofvertices+1:
+		projection_value=[value[(layer-1)*md3d.mesh.numberofvertices2d:layer*md3d.mesh.numberofvertices2d], value[-1]]
+	else:
+		projection_value=value[(layer-1)*md3d.mesh.numberofelements2d:layer*md3d.mesh.numberofelements2d]
+
+	if vec2d:
+		projection_value=projection_value.reshape(-1,1)
+
+	return projection_value
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.m	(revision 18231)
@@ -0,0 +1,85 @@
+function projected_vector=project3d(md,varargin)
+%PROJECT3D - vertically project a vector from 2d mesh
+%
+%   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+%   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+%   element vector of size (md.mesh.numberofelements2d,N/A). 
+%   arguments: 
+%      'vector': 2d vector
+%      'type': 'element' or 'node'. 
+%   options: 
+%      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+%             value of the 2d vector.
+%      'padding': default to 0 (value adopted by other 3d layers not being projected0
+%
+%   Egs:
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node');
+
+%some regular checks
+if nargin==0,
+	help project3d
+	error('bad usage');
+end
+if ~strcmp(elementtype(md.mesh),'Penta')
+	error('input model is not 3d');
+end
+
+%retrieve parameters from options.
+options      = pairoptions(varargin{:});
+vector2d     = getfieldvalue(options,'vector');     %mandatory
+type         = getfieldvalue(options,'type');       %mandatory
+layer        = getfieldvalue(options,'layer',0);    %optional (do all layers otherwise)
+paddingvalue = getfieldvalue(options,'padding',0);  %0 by default
+
+if length(vector2d)==1,
+	projected_vector=vector2d;
+
+elseif strcmpi(type,'node'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofvertices2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofvertices2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:md.mesh.numberoflayers,
+			projected_vector(((i-1)*md.mesh.numberofvertices2d+1):(i*md.mesh.numberofvertices2d),:)=vector2d;
+		end
+	else
+		projected_vector(((layer-1)*md.mesh.numberofvertices2d+1):(layer*md.mesh.numberofvertices2d),:)=vector2d;
+	end
+
+elseif strcmpi(type,'element'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofelements2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofelements2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:(md.mesh.numberoflayers-1),
+			projected_vector( ((i-1)*md.mesh.numberofelements2d+1):(i*md.mesh.numberofelements2d),:)=vector2d;
+		end
+	else
+		projected_vector( ((layer-1)*md.mesh.numberofelements2d+1):(layer*md.mesh.numberofelements2d),:)=vector2d;
+	end
+
+else
+	error('project3d error message: unknown projection type');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/extrusion/project3d.py	(revision 18231)
@@ -0,0 +1,90 @@
+import numpy
+from pairoptions import pairoptions
+
+def project3d(md,*args):
+	"""
+	PROJECT3D - vertically project a vector from 2d mesh
+
+	   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+	   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+	   element vector of size (md.mesh.numberofelements2d,N/A). 
+	   arguments: 
+	      'vector': 2d vector
+	      'type': 'element' or 'node'. 
+	   options: 
+	      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+	             value of the 2d vector.
+	      'padding': default to 0 (value adopted by other 3d layers not being projected
+
+	   Examples:
+	      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN)
+	      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0)
+	      extruded_vector=project3d(md,'vector',vector2d,'type','node')
+	"""
+
+	#some regular checks
+	if not md:
+		raise TypeError("bad usage")
+	if md.mesh.domaintype().lower() != '3d':
+		raise TypeError("input model is not 3d")
+
+	#retrieve parameters from options.
+	options      = pairoptions(*args)
+	vector2d     = options.getfieldvalue('vector')       #mandatory
+	vectype      = options.getfieldvalue('type')         #mandatory
+	layer        = options.getfieldvalue('layer',0)      #optional (do all layers otherwise)
+	paddingvalue = options.getfieldvalue('padding',0)    #0 by default
+
+	vector1d=False
+	if isinstance(vector2d,numpy.ndarray) and numpy.ndim(vector2d)==1:
+		vector1d=True
+		vector2d=vector2d.reshape(-1,1)
+
+	if isinstance(vector2d,(bool,int,long,float)) or numpy.size(vector2d)==1:
+		projected_vector=vector2d
+
+	elif vectype.lower()=='node':
+
+		#Initialize 3d vector
+		if vector2d.shape[0]==md.mesh.numberofvertices2d:
+			projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices,  numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
+		elif vector2d.shape[0]==md.mesh.numberofvertices2d+1:
+			projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
+			projected_vector[-1,:]=vector2d[-1,:]
+			vector2d=vector2d[:-1,:]
+		else:
+			raise TypeError("vector length not supported")
+
+		#Fill in
+		if layer==0:
+			for i in xrange(md.mesh.numberoflayers):
+				projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d
+		else:
+			projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d
+
+	elif vectype.lower()=='element':
+
+		#Initialize 3d vector
+		if vector2d.shape[0]==md.mesh.numberofelements2d:
+			projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements,  numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
+		elif vector2d.shape[0]==md.mesh.numberofelements2d+1:
+			projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
+			projected_vector[-1,:]=vector2d[-1,:]
+			vector2d=vector2d[:-1,:]
+		else:
+			raise TypeError("vector length not supported")
+
+		#Fill in
+		if layer==0:
+			for i in xrange(md.mesh.numberoflayers-1):
+				projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d
+		else:
+			projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d
+
+	else:
+		raise TypeError("project3d error message: unknown projection type")
+
+	if vector1d:
+		projected_vector=projected_vector.reshape(-1,)
+
+	return projected_vector
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.m	(revision 18231)
@@ -0,0 +1,59 @@
+function flag=FlagElements(md,region),
+%FLAGELEMENTS - flag the elements in an region
+%
+%   The region can be given with an exp file, a list of elements or vertices
+%
+%   Usage: 
+%      flag=FlagElements(md,region);
+%
+%   Example:
+%      flag=FlagElements(md,'all');
+%      flag=FlagElements(md,'');
+%      flag=FlagElements(md,'Domain.exp');
+%      flag=FlagElements(md,'~Domain.exp');
+
+	if ischar(region),
+		if isempty(region),
+			flag=zeros(md.mesh.numberofelements,1);
+			invert=0;
+		elseif strcmpi(region,'all')
+			flag=ones(md.mesh.numberofelements,1);
+			invert=0;
+		else
+			%make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region(1),'~'),
+				region=region(2:length(region));
+				invert=1;
+			else
+				invert=0;
+			end
+
+			%does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if ~exist(region,'file'),
+				if (length(region)>3 & ~strcmp(region(end-3),'.exp')),
+					error(['Error: File ' region ' not found!']);
+				end
+				[xlim,ylim]=basinzoom('basin',region);
+				flag_nodes=double(md.mesh.x<xlim(2) & md.mesh.x>xlim(1) &  md.mesh.y<ylim(2) & md.mesh.y>ylim(1));
+				flag=prod(flag_nodes(md.mesh.elements),2);
+			else
+				%ok, flag elements
+				flag=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,region,'element',1);
+			end
+		end
+		if invert,
+			flag=~flag;
+		end
+	elseif isfloat(region) | islogical(region),
+		if size(region,1)==md.mesh.numberofelements,
+			flag=region;
+		elseif size(region,1)==md.mesh.numberofvertices,
+			flag=logical(sum(region(md.mesh.elements)>0,2)==size(md.mesh.elements,2));
+		else
+			help FlagElements
+			error('Flaglist for region must be of same size as number of elements in model');
+		end
+	else
+		error('Invalid region option');
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/FlagElements.py	(revision 18231)
@@ -0,0 +1,67 @@
+import numpy
+import os
+#from basinzoom import basinzoon
+from ContourToMesh import ContourToMesh
+import MatlabFuncs as m
+import PythonFuncs as p
+
+def FlagElements(md,region):
+	"""
+	FLAGELEMENTS - flag the elements in an region
+
+	   The region can be given with an exp file, a list of elements or vertices
+
+	   Usage: 
+	      flag=FlagElements(md,region);
+
+	   Example:
+	      flag=FlagElements(md,'all');
+	      flag=FlagElements(md,'');
+	      flag=FlagElements(md,'Domain.exp');
+	      flag=FlagElements(md,'~Domain.exp');
+	"""
+
+	if   isinstance(region,(str,unicode)):
+		if   not region:
+			flag=numpy.zeros(md.mesh.numberofelements,bool)
+			invert=0
+		elif m.strcmpi(region,'all'):
+			flag=numpy.ones(md.mesh.numberofelements,bool)
+			invert=0
+		else:
+			#make sure that we actually don't want the elements outside the domain outline!
+			if m.strcmpi(region[0],'~'):
+				region=region[1:]
+				invert=1
+			else:
+				invert=0
+
+			#does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if not os.path.exists(region):
+				if len(region)>3 and not m.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=p.logical_and_n(md.mesh.x<xlim[1],md.mesh.x>xlim[0],md.mesh.y<ylim[1],md.mesh.y>ylim[0])
+				flag=numpy.prod(flag_nodes[md.mesh.elements],axis=1).astype(bool)
+			else:
+				#ok, flag elements
+				[flag,dum]=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x,md.mesh.y,region,'element',1)
+				flag=flag.astype(bool)
+
+		if invert:
+			flag=numpy.logical_not(flag)
+
+	elif isinstance(region,numpy.ndarray) or isinstance(region,bool):
+		if numpy.size(region,0)==md.mesh.numberofelements:
+			flag=region
+		elif numpy.size(region,0)==md.mesh.numberofvertices:
+			flag=(numpy.sum(region[md.mesh.elements-1]>0,axis=1)==numpy.size(md.mesh.elements,1))
+		else:
+			raise TypeError("Flaglist for region must be of same size as number of elements in model.")
+
+	else:
+		raise TypeError("Invalid region option")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.m	(revision 18231)
@@ -0,0 +1,51 @@
+function areas=GetAreas(index,x,y,varargin)
+%GETAREAS - compute areas or volumes of elements
+%
+%   compute areas of triangular elements or volumes 
+%   of pentahedrons
+%
+%   Usage:
+%      areas  =GetAreas(index,x,y);
+%      volumes=GetAreas(index,x,y,z);
+%
+%   Examples:
+%      areas  =GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+%      volumes=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y,md.z);
+
+%get number of elements and number of nodes
+nels=size(index,1);
+nods=length(x);
+if nargin==4, z=varargin{1}; end
+
+%some checks
+if nargout~=1 | (nargin~=3 & nargin~=4),
+	help GetAreas
+	error('GetAreas error message: bad usage')
+end
+if ((length(y)~=nods) | (nargin==4 & length(z)~=nods)),
+	error('GetAreas error message: x,y and z do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetAreas error message: index should not have values above ' num2str(nods) ])
+end
+if (nargin==3 & size(index,2)~=3),
+	error('GetAreas error message: index should have 3 columns for 2d meshes.')
+end
+if (nargin==4 & size(index,2)~=6),
+	error('GetAreas error message: index should have 6 columns for 3d meshes.')
+end
+
+%initialization
+areas=zeros(nels,1);
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+
+%compute the volume of each element
+if nargin==3,
+	%compute the surface of the triangle
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+else
+	%V=area(triangle)*1/3(z1+z2+z3)
+	thickness=mean(z(index(:,4:6)),2)-mean(z(index(:,1:3)),2);
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1))).*thickness;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/GetAreas.py	(revision 18231)
@@ -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]-1]
+	x2=x[index[:,1]-1]
+	x3=x[index[:,2]-1]
+	y1=y[index[:,0]-1]
+	y2=y[index[:,1]-1]
+	y3=y[index[:,2]-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]-1])-numpy.mean(z[index[:,0:3]-1])
+		areas=(0.5*((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)))*thickness
+
+	return areas
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/NowickiProfile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/NowickiProfile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/NowickiProfile.m	(revision 18231)
@@ -0,0 +1,39 @@
+function [b h sea] = NowickiProfile(x),
+%NOWICKIPROFILE - Create profile at the transition zone based on Sophie Nowicki's thesis
+%
+%   Usage:
+%      [b h] = NowickiProfile(x)
+%
+%      - h = ice thickness
+%      - b = ice base
+%      - x = along flow coordinate
+
+%Constant for theoretical profile
+delta = 0.1;          % ratio of water density and ice density -1
+hg    = 1;            % ice thickness at grounding line
+sea   = hg/(1+delta); % sea level
+lamda = 0.1;          % ration of deviatoric stress and water pressure
+beta  = 5;            % friction coefficient
+ms    = 0.005;        % surface accumulation rat
+mu    = 5;            % viscosity
+q     = 0.801;        % ice mass flux
+
+%mesh parameters
+b=zeros(numel(x),1);
+h=zeros(numel(x),1);
+
+%upstream of the GL
+for i = 1:ceil(numel(x)/2)
+	ss=roots([1,4*lamda*beta,0,0,6*lamda*ms*x(i)^2+12*lamda*q*x(i)-hg^4-4*lamda*beta*hg^3]);
+	for j=1:4
+		if (real(ss(j)) > 0) && (imag(ss(j)) == 0), s(i)=ss(j); end
+	end
+	h(i) = s(i);
+	b(i) = 0.;
+end
+
+%downstream of the GL
+for i = ceil(numel(x)/2):numel(x)
+	h(i) = (x(i)/(4*(delta+1)*q)+hg^(-2))^(-0.5); % ice thickness for ice shelf from (3.1)
+	b(i) = sea-h(i)*(1/(1+delta));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.m	(revision 18231)
@@ -0,0 +1,79 @@
+function bval=SegIntersect(seg1,seg2)
+%SEGINTERSECT - test of segments intersection
+%
+%   return 1 if the two segments intersect
+%   seg1=[x1 y1; x2 y2]
+%   seg2=[x1 y1; x2 y2]
+%
+%   Usage:
+%      bval=SegIntersect(seg1,seg2)
+
+bval=1;
+
+xA=seg1(1,1); yA=seg1(1,2);
+xB=seg1(2,1); yB=seg1(2,2);
+xC=seg2(1,1); yC=seg2(1,2);
+xD=seg2(2,1); yD=seg2(2,2);
+
+O2A=[xA;yA]-[xD/2.+xC/2.;yD/2.+yC/2.];
+O2B=[xB;yB]-[xD/2.+xC/2.;yD/2.+yC/2.];
+O1C=[xC;yC]-[xA/2.+xB/2.;yB/2.+yA/2.];
+O1D=[xD;yD]-[xA/2.+xB/2.;yB/2.+yA/2.];
+
+n1=[yA-yB;xB-xA]; %normal vector to segA
+n2=[yC-yD;xD-xC]; %normal vector to segB
+
+test1=n2'*O2A;
+test2=n2'*O2B;
+
+if test1*test2>0
+	bval=0;
+	return;
+end
+
+test3=n1'*O1C;
+test4=n1'*O1D;
+
+if test3*test4>0
+	bval=0;
+	return;
+end
+
+%if colinear
+if test1*test2==0 & test3*test4==0 & det([n1 n2])==0
+
+	%projection on the axis O1O2
+	O2O1=[xA/2.+xB/2.;yB/2.+yA/2.]-[xD/2.+xC/2.;yD/2.+yC/2.];
+	O1A=O2O1'*(O2A-O2O1);
+	O1B=O2O1'*(O2B-O2O1);
+	O1C=O2O1'*O1C;
+	O1D=O2O1'*O1D;
+
+	%test if one point is included in the other segment (->bval=1)
+	if (O1C-O1A)*(O1D-O1A)<0
+		bval=1;
+		return;
+	end
+	if (O1C-O1B)*(O1D-O1B)<0
+		bval=1;
+		return;
+	end
+	if (O1A-O1C)*(O1B-O1C)<0
+		bval=1;
+		return;
+	end
+	if (O1A-O1D)*(O1B-O1D)<0
+		bval=1;
+		return;
+	end
+
+	 %test if the 2 segments have the same middle (->bval=1)
+	if O2O1==0
+		bval=1;
+		return;
+	end
+
+	%else
+	bval=0;
+	return;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/SegIntersect.py	(revision 18231)
@@ -0,0 +1,82 @@
+import numpy
+
+def SegIntersect(seg1,seg2):
+	"""
+	SEGINTERSECT - test of segments intersection
+
+	   return 1 if the two segments intersect
+	   seg1=[x1 y1; x2 y2]
+	   seg2=[x1 y1; x2 y2]
+
+	   Usage:
+	      bval=SegIntersect(seg1,seg2)
+	"""
+
+	bval=1
+
+	xA=seg1[0,0]
+	yA=seg1[0,1]
+	xB=seg1[1,0]
+	yB=seg1[1,1]
+	xC=seg2[0,0]
+	yC=seg2[0,1]
+	xD=seg2[1,0]
+	yD=seg2[1,1]
+
+	O2A=numpy.array([xA,yA])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+	O2B=numpy.array([xB,yB])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+	O1C=numpy.array([xC,yC])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
+	O1D=numpy.array([xD,yD])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
+
+	n1=numpy.array([yA-yB,xB-xA])    #normal vector to segA
+	n2=numpy.array([yC-yD,xD-xC])    #normal vector to segB
+
+	test1=numpy.dot(n2,O2A)
+	test2=numpy.dot(n2,O2B)
+
+	if test1*test2>0:
+		bval=0
+		return bval
+
+	test3=numpy.dot(n1,O1C)
+	test4=numpy.dot(n1,O1D)
+
+	if test3*test4>0:
+		bval=0
+		return bval
+
+	#if colinear
+	if test1*test2==0 and test3*test4==0 and numpy.linalg.det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
+
+		#projection on the axis O1O2
+		O2O1=numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+		O1A=numpy.dot(O2O1,(O2A-O2O1))
+		O1B=numpy.dot(O2O1,(O2B-O2O1))
+		O1C=numpy.dot(O2O1,O1C)
+		O1D=numpy.dot(O2O1,O1D)
+
+		#test if one point is included in the other segment (->bval=1)
+		if (O1C-O1A)*(O1D-O1A)<0:
+			bval=1
+			return bval
+		if (O1C-O1B)*(O1D-O1B)<0:
+			bval=1
+			return bval
+		if (O1A-O1C)*(O1B-O1C)<0:
+			bval=1
+			return bval
+		if (O1A-O1D)*(O1B-O1D)<0:
+			bval=1
+			return bval
+
+		#test if the 2 segments have the same middle (->bval=1)
+		if O2O1==0:
+			bval=1
+			return bval
+
+		#else
+		bval=0
+		return bval
+
+	return bval
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/ThicknessCorrection.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/ThicknessCorrection.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/ThicknessCorrection.m	(revision 18231)
@@ -0,0 +1,77 @@
+function md=ThicknessCorrection(md,varargin)
+%THICKNESSCORRECTION - correct the thickness of the ice shelf near the grounding line
+%
+%   This routine corrects the thickness and the bed on the transition zone
+%   by forcing the hydrostatic equilibrium.
+%   the thickness is modified as follows:
+%      thickness = (1-coeff) * thickness_observation + coeff * thickness_hydrostatic
+%   where:
+%      coeff=(d/distance)^2;
+%      distance=10km by default but can be specified
+%
+%   Usage:
+%      md=ThicknessCorrection(md,varargin);
+%
+%   Example:
+%      md=ThicknessCorrection(md);
+%      md=ThicknessCorrection(md,15000);
+
+%initialize thickness with the observations, and get hydrostatic thickness from the dem
+thickness=md.geometry.thickness;
+thickness_hydro=md.geometry.surface/(1-md.materials.rho_ice/md.materials.rho_water);
+hydrostatic_ratio=zeros(size(md.geometry.thickness));
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(md.mask.groundedice_levelset<0.);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+debug=(length(pos_shelf)>50000);
+
+%check that there is a GL
+if isempty(pos_GL)
+	error('ThicknessCorrection error message: no grounding line has been detected. Check the model mask');
+end
+
+%get distance
+if nargin==2,
+	distance=varargin{1};
+else
+	distance=10000;
+end
+
+%modify thickness
+if (debug), fprintf('%s','      correction progress:   0.00 %'); end
+for i=1:length(pos_shelf)
+
+	if (debug & mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d>distance,
+
+		%if d > 15km, hydrostatic equilibrium
+		hydrostatic_ratio(pos_shelf(i))=1;
+		thickness(pos_shelf(i))=thickness_hydro(pos_shelf(i));
+
+	else
+
+		%else: quadratic combination of hydrostatic equilibrium and observations
+		hydrostatic_ratio(pos_shelf(i))=(d/distance)^2;
+		thickness(pos_shelf(i))=(1-hydrostatic_ratio(pos_shelf(i)))*thickness(pos_shelf(i))+hydrostatic_ratio(pos_shelf(i))*thickness_hydro(pos_shelf(i));
+
+	end
+end
+if (debug), fprintf('\b\b\b\b\b\b\b%5.2f%s\n',100,' %'); end
+
+%check the computed thickness
+minth=1/(1-md.materials.rho_ice/md.materials.rho_water);
+pos=find(isnan(thickness) | (thickness<=0));
+thickness(pos)=minth;
+hydrostatic_ratio(pos)=-1;
+
+%change bed to take into account the changes in thickness
+md.geometry.thickness=thickness;
+md.geometry.hydrostatic_ratio=hydrostatic_ratio;
+md.geometry.base=md.geometry.surface-md.geometry.thickness;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/find_point.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/find_point.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/find_point.m	(revision 18231)
@@ -0,0 +1,14 @@
+function f=find_point(tabx,taby,pointx,pointy)
+%FIND_POINT - find closest point
+%
+%   find which point of the list (tabx,taby) is
+%   the closest to (poinx,pointy)
+%
+%   Usage:
+%      f=find_point(tabx,taby,pointx,pointy)
+
+%Compute distance between point and cloud of points
+distance=sqrt((tabx-pointx).^2+(taby-pointy).^2);
+
+%find index of the minimum distance and return the first one only
+f=find(distance==min(min(distance)),1);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/isconnected.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/isconnected.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/isconnected.m	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.m	(revision 18231)
@@ -0,0 +1,36 @@
+function [sx,sy,s]=slope(md,surf)
+%SLOPE - compute the surface slope
+%
+%   Usage:
+%      [sx,sy,s]=slope(md)
+%      [sx,sy,s]=slope(md,md.results.TransientSolution(1).Surface)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if dimension(md.mesh)==2,
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+if nargin==1,
+	surf=md.geometry.surface;
+end
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+sx=(surf(index).*alpha)*summation;
+sy=(surf(index).*beta)*summation;
+s=sqrt(sx.^2+sy.^2);
+
+if dimension(md.mesh)==3,
+	sx=project3d(md,'vector',sx,'type','element');
+	sy=project3d(md,'vector',sy,'type','element');
+	s=sqrt(sx.^2+sy.^2);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/geometry/slope.py	(revision 18231)
@@ -0,0 +1,46 @@
+import numpy as npy
+from GetNodalFunctionsCoeff import  GetNodalFunctionsCoeff
+
+def slope(md,*args):
+	"""
+	SLOPE - compute the surface slope
+
+	Usage:
+		sx,sy,s=slope(md)
+		sx,sy,s=slope(md,md.results.TransientSolution(1).Surface)
+	"""
+
+	#load some variables (it is much faster if the variables are loaded from md once for all) 
+	if md.mesh.dimension()==2:
+		numberofelements=md.mesh.numberofelements
+		numberofnodes=md.mesh.numberofvertices
+		index=md.mesh.elements
+		x=md.mesh.x ; y=md.mesh.y
+	else:
+		numberofelements=md.mesh.numberofelements2d
+		numberofnodes=md.mesh.numberofvertices2d
+		index=md.mesh.elements2d
+		x=md.mesh.x2d; y=md.mesh.y2d
+
+	if len(args)==0:
+		surf=md.geometry.surface
+	elif len(args)==1:
+		surf=args[0]
+	else:
+		raise RuntimeError("slope.py usage error")
+
+	#%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+	alpha,beta=GetNodalFunctionsCoeff(index,x,y)[0:2]
+
+	summation=npy.array([[1],[1],[1]])
+	sx=npy.dot(surf[index-1]*alpha,summation).reshape(-1,)
+	sy=npy.dot(surf[index-1]*beta,summation).reshape(-1,)
+
+	s=npy.sqrt(sx**2+sy**2)
+
+	if md.mesh.dimension()==3:
+		sx=project3d(md,'vector',sx,'type','element')
+		sy=project3d(md,'vector',sy,'type','element')
+		s=npy.sqrt(sx**2+sy**2)
+
+	return (sx,sy,s)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/InterpFromFile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/InterpFromFile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/InterpFromFile.m	(revision 18231)
@@ -0,0 +1,203 @@
+function data_out=InterpFromFile(x,y,filename,default_value)
+%INTERPFROMFILE - load data and interpolate on the given nodes
+%
+%   load a matlab file (extension .mat) which holds 3 or 4 variables
+%   and interpolate the data on the mesh and plug it onto the model.
+%
+%   o 3 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a vector or matrix data (if the name of the variable do not begin with the field name, an error can appear)
+%   o 4 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a matrix with 3 columns (if the name of the variable do not begin with "index" or "elements", an error can appear)
+%     - a vector data (if the name of the variable do not begin with the field name, an error can appear)
+%
+%   Usage:
+%      data=InterpFromFile(x,y,filename,default_value);
+%
+%   Example:
+%      md.geometry.surface=InterpFromFile(md.mesh.x,md.mesh.y,'surfacefile.mat',0);
+%
+%   See also: PLUGVELOCITIES, INTERPFROMGRID, INTERPFROMMESH2D, INTERPFROMMESH3D
+
+%some checks
+if nargin~=4 | nargout~=1
+	help InterpFromFile
+	error('plugdata error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugdata error message: file ' filename  ' does not exist']);
+end
+if length(x)~=length(y),
+	error('plugdata error message: x and y should have the same length');
+end
+
+%load file
+Names=FieldFindVarNames(filename);
+Data=load(filename);
+disp('WARNING: function deprecated, replace InterpFromFile by the following command:');
+if strcmpi(Names.interp,'node'),
+	disp(['   data=InterpFromGridToMesh(' Names.xname ',' Names.yname ',' Names.dataname ',x,y,default_value);']);
+	data_out=InterpFromGridToMesh(Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y,default_value);
+else
+	disp(['   data=InterpFromMeshToMesh2d(' Names.indexname ',' Names.xname ',' Names.yname ',' Names.dataname ',x,y);']);
+	data_out=InterpFromMeshToMesh2d(Data.(Names.indexname),Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y);
+end
+
+end
+function Names=FieldFindVarNames(filename)
+%FIELDFINDVARNAMES - find names of variables in a data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,data)
+%   or (index,x,y,data)
+%
+%   Usage:
+%      Names=FieldFindVarNames(filename)
+%
+%   Example:
+%      Names=FieldFindVarNames('thickness.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help FieldFindVarNames
+	error('FieldFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['FieldFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; dataenum=NaN; indexenum=NaN;
+if length(A)==3,
+	isnode=1;
+	for i=1:3
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+elseif length(A)==4,
+	isnode=0;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,'index',5) | strncmpi(A(i).name,'elements',7));
+			indexenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+else
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (it should hold 3 variables x,y and data (for nodes) OR 4 variables  x,y,index and data (for mesh))']);
+end
+
+%2: if only one item is missing, find it by elimination
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%assum that we have found at least xenum and yenum
+if ( isnan(xenum) | isnan(yenum))
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (the coordinates vectors should be named x and y)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:4
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['FieldFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%4: last chance
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%last check
+if isnan(dataenum)
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (data not found)']);
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.dataname=A(dataenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/PointValues.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/PointValues.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/PointValues.m	(revision 18231)
@@ -0,0 +1,14 @@
+function [data_interp]=PointValues(md,data,xpoint,ypoint)
+%POINTVALUES - compute the value of a field on a single point
+%
+%   This routine gets the value of a given field of the model on points
+%
+%   Usage:
+%      [z,data]=PointValues(md,data,X,Y,Z)
+
+%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+%offset=10^-3;
+%bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.bed,1),xpoint,ypoint)+offset;
+%surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),xpoint,ypoint)-offset;
+
+data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,xpoint,ypoint);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/ProfileValues.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/ProfileValues.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/ProfileValues.m	(revision 18231)
@@ -0,0 +1,21 @@
+function [Z,data_interp]=ProfileValues(md,data,xprof,yprof,resolution)
+%PROFILEVALUES - compute the value of a field on a vertical profile
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [z,data]=ProfileValues(md,data,filename,resolution)
+%      [z,data]=ProfileValues(md,data,profile_structure,resolution)
+
+%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+offset=10^-3;
+bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.base,1),xprof,yprof)+offset;
+surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),xprof,yprof)-offset;
+
+%Some useful parameters
+layers=ceil(mean(md.geometry.thickness)/resolution);
+Z=(bed:resolution:surface)';
+X=xprof*ones(size(Z));
+Y=yprof*ones(size(Z));
+data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X,Y,Z,NaN);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.m	(revision 18231)
@@ -0,0 +1,126 @@
+function [index,X,Y,Z,S,data_interp]=SectionValues(md,data,infile,resolution)
+%SECTIONVALUES - compute the value of a field on a section
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [elements,x,y,z,s,data]=SectionValues(md,data,filename,resolution)
+%      [elements,x,y,z,s,data]=SectionValues(md,data,profile_structure,resolution)
+
+%check what we have for profile as input
+if ischar(infile),
+	%read infile:
+	profile=expread(infile);
+	nods=profile.nods;
+	x=profile.x;
+	y=profile.y;
+else
+	%read infile:
+	nods=infile.nods;
+	x=infile.x;
+	y=infile.y;
+end
+
+%get the specified resolution
+if isnumeric(resolution(1))
+	res_h=resolution(1);
+else
+	error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+end
+if dimension(md.mesh)==3
+	if (length(resolution)==2 & isnumeric(resolution(2)))
+		res_v=resolution(2);
+	else
+		error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+	end
+end
+
+%initialization
+X=[]; %X-coordinate
+Y=[]; %Y-coordinate
+S=0;  %curvilinear coordinate
+
+for i=1:nods-1
+
+	x_start=x(i);
+	x_end=x(i+1);
+	y_start=y(i);
+	y_end=y(i+1);
+	s_start=S(end);
+
+	length_segment=sqrt((x_end-x_start)^2+(y_end-y_start)^2);
+	portion=ceil(length_segment/res_h);
+
+	x_segment=zeros(portion,1);
+	y_segment=zeros(portion,1);
+	s_segment=zeros(portion,1);
+
+	for j=1:portion
+		x_segment(j)=x_start+(j-1)*(x_end-x_start)/portion;
+		y_segment(j)=y_start+(j-1)*(y_end-y_start)/portion;
+		s_segment(j)=s_start+j*length_segment/portion;
+	end
+
+	%plug into X and Y
+	X=[X;x_segment];
+	Y=[Y;y_segment];
+	S=[S;s_segment];
+end
+X(end+1)=x(nods);
+Y(end+1)=y(nods);
+
+%Number of nodes:
+numberofnodes=size(X,1);
+
+%Compute Z
+Z=zeros(numberofnodes,1);
+
+%New mesh and Data interpolation
+if (dimension(md.mesh)==2)
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=griddata(md.mesh.x,md.mesh.y,data,X,Y);
+
+	%Compute index
+	index=[1:1:(numberofnodes-1);2:1:numberofnodes]';
+
+else
+
+	%vertically extrude mesh
+
+	%Get base and surface for each 2d point, offset to make sure that it is inside the glacier system
+	offset=10^-3;
+	base=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.base,1),X,Y)+offset;
+	surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),X,Y)-offset;
+
+	%Some useful parameters
+	layers=ceil(mean(md.geometry.thickness)/res_v);
+	nodesperlayer=numberofnodes;
+	nodestot=nodesperlayer*layers;
+	elementsperlayer=nodesperlayer-1;
+	elementstot=(nodesperlayer-1)*(layers-1);
+
+	%initialization
+	X3=zeros(nodesperlayer*layers,1); Y3=zeros(nodesperlayer*layers,1); Z3=zeros(nodesperlayer*layers,1); S3=zeros(nodesperlayer*layers,1); index3=zeros(elementstot,4);
+
+	%Get new coordinates in 3d
+	for i=1:layers
+		X3(i:layers:end)=X;
+		Y3(i:layers:end)=Y;
+		Z3(i:layers:end)=base+(i-1)*(surface-base)/(layers-1);
+		S3(i:layers:end)=S;
+
+		if i<layers %Build index3 with quads
+			index3((i-1)*elementsperlayer+1:i*elementsperlayer,:)=[i:layers:nodestot-layers; i+1:layers:nodestot-layers; i+layers+1:layers:nodestot; i+layers:layers:nodestot]';
+		end
+	end
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,NaN);
+
+	%build outputs
+	X=X3; Y=Y3; Z=Z3;  S=S3; index=index3;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/SectionValues.py	(revision 18231)
@@ -0,0 +1,139 @@
+import os
+from expread import expread
+import numpy as npy
+from project2d import project2d
+#from InterpFromMesh2d import InterpFromMesh2d
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from InterpFromMeshToMesh3d import InterpFromMeshToMesh3d
+
+def SectionValues(md,data,infile,resolution):
+	'''
+	compute the value of a field on a section
+	
+	This routine gets the value of a given field of the model on points
+	given in the file infile (Argus type file). Resolution must be a list
+	[horizontal_resolution, vertical_resolution]
+	
+	Usage:
+	[elements,x,y,z,s,data]=SectionValues(md,data,filename,resolution)
+	[elements,x,y,z,s,data]=SectionValues(md,data,profile_structure,resolution)
+	'''
+
+	if os.path.isfile(infile):
+		profile=expread(infile)[0]
+		nods=profile['nods']
+		x=profile['x']
+		y=profile['y']
+	else:
+		raise IOError('file %s not found' % infile)
+
+	#get the specified resolution
+	if len(resolution)!=2:
+		raise ValueError('SectionValues error message: Resolution must be a list [horizontal_resolution, vertical_resolution]')
+	else:
+		res_h=resolution[0]
+
+	if md.mesh.domaintype().lower() == '3d':
+		if isinstance(resolution[1],int) or isinstance(resolution[1],float):
+			res_v=resolution[1]
+		else:
+			raise ValueError('SectionValues error: resolution must be a length-2 list of integers or floats')
+
+	#initialization
+	X=npy.array([]) #X-coordinate
+	Y=npy.array([]) #Y-coordinate
+	S=npy.array([0.])  #curvilinear coordinate
+	
+	for i in xrange(nods-1):
+	
+		x_start=x[i]
+		x_end=x[i+1]
+		y_start=y[i]
+		y_end=y[i+1]
+		s_start=S[-1]
+	
+		length_segment=npy.sqrt((x_end-x_start)**2+(y_end-y_start)**2)
+		portion=npy.ceil(length_segment/res_h)
+	
+		x_segment=npy.zeros(portion)
+		y_segment=npy.zeros(portion)
+		s_segment=npy.zeros(portion)
+
+		for j in xrange(int(portion)):
+			x_segment[j]=x_start+(j-1)*(x_end-x_start)/portion
+			y_segment[j]=y_start+(j-1)*(y_end-y_start)/portion
+			s_segment[j]=s_start+j*length_segment/portion
+	
+		#plug into X and Y
+		X=npy.append(X,x_segment)
+		Y=npy.append(Y,y_segment)
+		S=npy.append(S,s_segment)
+
+	X=npy.append(X,x[nods-1])
+	Y=npy.append(Y,y[nods-1])
+	
+	#Number of nodes:
+	numberofnodes=X.shape[0]
+	
+	#Compute Z
+	Z=npy.zeros(numberofnodes)
+	
+	#New mesh and Data interpolation
+	if '2d' in md.mesh.domaintype().lower():
+	
+		#Interpolation of data on specified points
+		#data_interp=InterpFromMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y)[0]
+		data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y)[0]
+		#data_interp=griddata(md.mesh.x,md.mesh.y,data,X,Y)
+	
+		#Compute index
+		index=npy.array([range(1,numberofnodes),range(2,numberofnodes+1)]).T
+	
+	else:
+	
+		#vertically extrude mesh
+	
+		#Get base and surface for each 2d point, offset to make sure that it is inside the glacier system
+		offset=1.e-3
+		base=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.base,1),X,Y)[0]+offset
+		base=base.reshape(-1,)
+		surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),X,Y)[0]-offset
+		surface=surface.reshape(-1,)
+	
+		#Some useful parameters
+		layers=int(npy.ceil(npy.mean(md.geometry.thickness)/res_v))
+		nodesperlayer=int(numberofnodes)
+		nodestot=int(nodesperlayer*layers)
+		elementsperlayer=int(nodesperlayer-1)
+		elementstot=int((nodesperlayer-1)*(layers-1))
+	
+		#initialization
+		X3=npy.zeros(nodesperlayer*layers) 
+		Y3=npy.zeros(nodesperlayer*layers) 
+		Z3=npy.zeros(nodesperlayer*layers) 
+		S3=npy.zeros(nodesperlayer*layers) 
+		index3=npy.zeros((elementstot,4))
+	
+		#Get new coordinates in 3d
+		for i in xrange(1,layers+1):
+			X3[i-1::layers]=X
+			Y3[i-1::layers]=Y
+			Z3[i-1::layers]=base+(i-1)*(surface-base)/(layers-1)
+			S3[i-1::layers]=S
+	
+			if i<layers-1:  #Build index3 with quads
+				ids=npy.vstack((npy.arange(i,nodestot-layers,layers),npy.arange(i+1,nodestot-layers,layers),npy.arange(i+layers+1,nodestot,layers),npy.arange(i+layers,nodestot,layers))).T
+				index3[(i-1)*elementsperlayer:i*elementsperlayer,:]=ids
+
+		#Interpolation of data on specified points
+		data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,npy.nan)
+	
+		#build outputs
+		X=X3 
+		Y=Y3 
+		Z=Z3  
+		S=S3 
+
+		index=index3
+
+	return index,X,Y,Z,S,data_interp
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.m	(revision 18231)
@@ -0,0 +1,90 @@
+function average=averaging(md,data,iterations,varargin)
+%AVERAGING - smooths the input over the mesh
+%
+%   This routine takes a list over the elements or the nodes in input
+%   and return a list over the nodes.
+%   For each iterations it computes the average over each element (average 
+%   of the vertices values) and then computes the average over each node
+%   by taking the average of the element around a node weighted by the
+%   elements volume
+%   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
+%
+%   Usage:
+%      smoothdata=averaging(md,data,iterations)
+%      smoothdata=averaging(md,data,iterations,layer)
+%
+%   Examples:
+%      velsmoothed=averaging(md,md.initialization.vel,4);
+%      pressure=averaging(md,md.initialization.pressure,0);
+%      temperature=averaging(md,md.initialization.temperature,1,1);
+
+if ((nargin~=4) & (nargin~=3)),
+	error('averaging error message: wrong number of arguments');
+end
+if (length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices),
+	error('averaging error message: data not supported yet');
+end
+if dimension(md.mesh)==3 & nargin==4,
+	if varargin{1}<=0 | varargin{1}>md.mesh.numberoflayers,
+		error('layer should be between 1 and md.mesh.numberoflayers');
+	end
+	layer=varargin{1};
+else
+	layer=0;
+end
+
+%initialization
+if layer==0,
+	weights=zeros(md.mesh.numberofvertices,1);
+	data=data(:);
+else 
+	weights=zeros(md.mesh.numberofvertices2d,1);
+	data=data((layer-1)*md.mesh.numberofvertices2d+1:layer*md.mesh.numberofvertices2d,:);
+end
+
+%load some variables (it is much faster if the variabes are loaded from md once for all)
+if layer==0,
+	index=md.mesh.elements;
+	numberofnodes=md.mesh.numberofvertices;
+	numberofelements=md.mesh.numberofelements;
+else
+	index=md.mesh.elements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	numberofelements=md.mesh.numberofelements2d;
+end
+
+%build some variables
+line=index(:);
+if dimension(md.mesh)==3 & layer==0,
+	rep=6;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z);
+elseif dimension(md.mesh)==2,
+	rep=3;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y);
+else
+	rep=3;
+	areas=GetAreas(index,md.mesh.x2d,md.mesh.y2d);
+end
+summation=1/rep*ones(rep,1);
+linesize=rep*numberofelements;
+
+%update weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,rep,1),numberofnodes,1);
+
+%initialization
+if length(data)==numberofelements
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*data,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+else
+	average_node=data;
+end
+
+%loop over iteration
+for i=1:iterations
+	average_el=average_node(index)*summation;
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*average_el,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+end
+
+%return output as a full matrix (C code do not like sparse matrices)
+average=full(average_node);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/averaging.py	(revision 18231)
@@ -0,0 +1,93 @@
+import numpy as npy
+from GetAreas import GetAreas
+from scipy.sparse import csc_matrix
+import MatlabFuncs as m
+
+def averaging(md,data,iterations,layer=0):
+	'''
+	AVERAGING - smooths the input over the mesh
+	
+	   This routine takes a list over the elements or the nodes in input
+	   and return a list over the nodes.
+	   For each iterations it computes the average over each element (average 
+	   of the vertices values) and then computes the average over each node
+	   by taking the average of the element around a node weighted by the
+	   elements volume
+	   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
+	
+	   Usage:
+	      smoothdata=averaging(md,data,iterations)
+	      smoothdata=averaging(md,data,iterations,layer)
+	
+	   Examples:
+	      velsmoothed=averaging(md,md.initialization.vel,4)
+	      pressure=averaging(md,md.initialization.pressure,0)
+	      temperature=averaging(md,md.initialization.temperature,1,1)
+	'''
+
+	if len(data)!=md.mesh.numberofelements and len(data)!=md.mesh.numberofvertices:
+		raise StandardError('averaging error message: data not supported yet')
+	if md.mesh.dimension()==3 and layer!=0:
+		if layer<=0 or layer>md.mesh.numberoflayers:
+			raise ValueError('layer should be between 1 and md.mesh.numberoflayers')
+	else:
+		layer=0
+	
+	#initialization
+	if layer==0:
+		weights=npy.zeros(md.mesh.numberofvertices,)
+		data=data.flatten(1)
+	else:
+		weights=npy.zeros(md.mesh.numberofvertices2d,)
+		data=data[(layer-1)*md.mesh.numberofvertices2d+1:layer*md.mesh.numberofvertices2d,:]
+	
+	#load some variables (it is much faster if the variabes are loaded from md once for all)
+	if layer==0:
+		index=md.mesh.elements
+		numberofnodes=md.mesh.numberofvertices
+		numberofelements=md.mesh.numberofelements
+	else:
+		index=md.mesh.elements2d
+		numberofnodes=md.mesh.numberofvertices2d
+		numberofelements=md.mesh.numberofelements2d
+
+	
+	#build some variables
+	if md.mesh.dimension()==3 and layer==0:
+		rep=6
+		areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z)
+	elif md.mesh.dimension()==2:
+		rep=3
+		areas=GetAreas(index,md.mesh.x,md.mesh.y)
+	else:
+		rep=3
+		areas=GetAreas(index,md.mesh.x2d,md.mesh.y2d)
+
+	index=index-1 # since python indexes starting from zero
+	line=index.flatten(1)
+	areas=npy.vstack(areas).reshape(-1,)
+	summation=1./rep*npy.ones(rep,)
+	linesize=rep*numberofelements
+	
+	#update weights that holds the volume of all the element holding the node i
+	weights=csc_matrix( (npy.tile(areas,(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+	
+	#initialization
+	if len(data)==numberofelements:
+		average_node=csc_matrix( (npy.tile(areas*data,(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+		average_node=average_node/weights
+		average_node = csc_matrix(average_node)
+	else:
+		average_node=csc_matrix(data.reshape(-1,1))
+
+	#loop over iteration
+	for i in npy.arange(1,iterations+1):
+		average_el=npy.asarray(npy.dot(average_node.todense()[index].reshape(numberofelements,rep),npy.vstack(summation))).reshape(-1,)
+		average_node=csc_matrix( (npy.tile(areas*average_el.reshape(-1),(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+		average_node=average_node/weights
+		average_node=csc_matrix(average_node)
+	
+	#return output as a full matrix (C code do not like sparse matrices)
+	average=npy.asarray(average_node.todense()).reshape(-1,)
+
+	return average
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/holefiller.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/holefiller.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/holefiller.py	(revision 18231)
@@ -0,0 +1,46 @@
+import numpy as npy
+from scipy.spatial import cKDTree
+
+def nearestneighbors(x,y,data,goodids,badids,knn):
+	'''
+	fill holes using nearest neigbors.  Arguments include:
+
+
+	x,y:		the coordinates of data to be filled 
+	data:		the data field to be filled (full field, including holes)
+	goodids:	id's into the vertices that have good data
+	badids:	id's into the vertices with missing/bad data
+	knn:		integer representing the k nearest neighbors to use for filling
+				holes.  The average data value over the k nearest neighbors is 
+				then used to fill the hole.
+
+	Usage:
+		filleddata=nearestneighbors(x,y,data,goodids,badids,knn)
+
+	Example:
+		filledthickness=nearestneighbors(x,y,data,goodids,badids,5)
+	'''
+
+	if type(knn) != int or knn<1:
+		raise TypeError('nearestneighbors error: knn should be an integer>1')
+
+	if len(x) != len(data) or len(y) != len(data):
+		raise StandardError('nearestneighbors error: x and y should have the same length as "data"')
+
+	filled=data
+	
+	XYGood=npy.dstack([x[goodids],y[goodids]])[0]
+	XYBad=npy.dstack([x[badids],y[badids]])[0]
+	tree=cKDTree(XYGood)
+	nearest=tree.query(XYBad,k=knn)[1]
+	
+	if knn==1:
+		filled[badids]=filled[goodids][nearest] # can add k=N to return the N nearest neighbors
+	else:
+		for i in range(len(badids)):
+			neardat=[]
+			for j in range(knn):
+				neardat.append(filled[goodids][nearest[i][j]])
+				filled[badids[i]]=npy.mean(neardat)
+				
+	return filled
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/interp.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/interp.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/interp.py	(revision 18231)
@@ -0,0 +1,240 @@
+# module for inperpolating/smoothing data
+import numpy as npy
+from scipy.interpolate import CloughTocher2DInterpolator, Rbf
+from scipy.spatial import cKDTree
+try:
+	import matplotlib.pyplot as plt
+except ImportError:
+	print 'could not import matplotlib, no plotting functions enabled.\
+			Set plotonly=False in function call'
+
+def MeshSplineToMesh2d(x,y,data,xi,yi,tol=1e-6,fill_nans=False,**kwargs):#{{{
+	'''
+	Piecewise cubic, C1 smooth, curvature-minimizing interpolant in 2D.
+	The interpolant is guaranteed to be continuously differentiable,
+	and the gradients are chosen such that the curvature of the interpolant
+	is approximately minimized.
+
+	Uses scipy.interpolate.CloughTocher2DInterpolator
+
+	x,y:			data point coordinates
+	data:			data to be interpolated (same length as x,y)
+	xi,yi:		coordintes to interpolate data onto
+	tol:			tolerance for gradient estimation (default 1e-6)
+	fill_nans:	fill nan's (holes) in data using the spline fit? 
+	**kwargs:	optional keywork arguments:
+					maxiter: maximum iterations in gradient estimation
+	
+	Returns interpolated data at given x,y coordinates.
+
+	Usage:
+		interpdata=CloughToucher2d(x,y,data)
+
+	Examples:
+		interpdata=CloughToucher2d(md.mesh.x,md.mesh.y,data)
+		interpdata=CloughToucher2d(md.mesh.x,md.mesh.y,data,tol=1e-3,maxiter=100)
+	'''
+
+	# unpack kwargs
+	maxiter=kwargs.pop('maxiter',None)
+	if 'maxiter' in kwargs: del kwargs['maxiter']
+	if maxiter:
+		assert type(maxiter)==int, 'error, maxiter should be an integer'
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	# create sub-vectors that just cover the limits of xi and yi
+	# TODO x,y not necessarily a grid, so need a better definition of dx,dy (e.g. average element size)
+	dx=500
+	dy=500
+	#dx=x[1]-x[0]
+	#dy=y[1]-y[0]
+	xlim=[min(xi)-dx,max(xi)+dx]
+	ylim=[min(yi)-dy,max(yi)+dy]
+	xflag=npy.logical_and(x>xlim[0],x<xlim[1])
+	yflag=npy.logical_and(y>ylim[0],y<ylim[1])
+	bothind=npy.nonzero(npy.logical_and(xflag,yflag))
+	subdata=data[bothind]
+	subx=x[bothind]
+	suby=y[bothind]
+	points=npy.array([subx,suby]).T
+
+	# mask out any nan's in the data and corresponding coordinate points
+	mask=npy.isnan(subdata)
+	ind=npy.nonzero(mask)[0]
+	if len(ind) and fill_nans:
+		print "		WARNING: filling nans using spline fit through good data points, which may or may not be appropriate. Check results carefully."
+	subdata=npy.delete(subdata,ind)
+	points=npy.delete(points,ind,axis=0)
+
+	if maxiter:
+		spline=CloughTocher2DInterpolator(points,subdata,tol,maxiter=maxiter)
+	else:
+		spline=CloughTocher2DInterpolator(points,subdata,tol)
+
+	interpdata=spline(xi,yi)
+	
+	if not fill_nans:
+		# identify nan's in xi,yi using nearest neighbors
+		xyinterp=npy.dstack([xi,yi])[0]
+		xg,yg=npy.meshgrid(subx,suby)
+		xydata=npy.dstack([subx,suby])[0]
+		tree=cKDTree(xydata)
+		nearest=tree.query(xyinterp)[1]
+		pos=npy.nonzero(npy.isnan(subdata[nearest]))
+		interpdata[pos]=subdata[nearest][pos]
+
+	return interpdata
+#}}}
+def GridSplineToMesh2d(x,y,data,xi,yi,default_value=npy.nan,plotonly=False,fill_nans=False):#{{{
+	'''
+	python analog to InterpFromGridToMesh.  This routine uses
+	scipy.interpolate.CloughTocher2dInterpolator to create a bivariate spline
+	interpolation of the input data and then return values of the spline
+	on the x,y coordinates of the model mesh.  The interpolant is piece-wise
+	cubic, C1 smooth (continuously differentiable) and has approximately 
+	minimized curvature.  See "help(scipy.interpolate.CloughTocher2dInterpolator)"
+	for more information on the routine.
+
+	NOTE: this routine will not be appropriate if there are large holes (nan's) in 
+	the input data.  A non-spline interpolation scheme should be used in that case.
+
+	x,y:				vectors defining the coordinates of the input data
+	data:				2D array of input data
+	xi,yi:			x and y coordinates to be interpolated onto
+	default_value:	default value if points lie outside the convex hull of input
+						points (defaults to nan if not specified)
+	plotonly:		plot the data to be interpolated using imshow (useful for
+	fill_nans:		fill nan's (holes) in data using the spline fit? 
+
+	Usage:
+		interpdata=GridToMesh(x,y,data,xi,yi,default_value=npy.nan,plotonly=False,fill_nans=False)
+
+	Examples:
+		interpdata=GridToMesh(x_m,y_m,data,md.mesh.x,md.mesh.y,0)
+	'''
+
+	if npy.ndim(x)==2:
+		x=x.reshape(-1,)
+	if npy.ndim(y)==2:
+		y=y.reshape(-1,)
+	if len(x) != data.shape[1]+1 and len(x) != data.shape[1]:
+		raise ValueError('x should have same length as ncols(data) or ncols(data)+1')
+	if len(y) != data.shape[0]+1 and len(y) != data.shape[0]:
+		raise ValueError('y should have same length as nrows(data) or nrows(data)+1')
+	
+	# create sub-grid that just covers the limits of xi and yi
+	dx=x[1]-x[0]
+	dy=y[1]-y[0]
+	xlim=[min(xi)-dx,max(xi)+dx]
+	ylim=[min(yi)-dy,max(yi)+dy]
+
+	# TODO create grid differently depending on whether data is defined at x,y
+	# or at the center of a grid cell with corner coordinates defined by xi,yi
+	# create points array and flattened data array
+	if len(x)==data.shape[1] and len(y)==data.shape[0]:
+		print '		x,y taken to define the center of data grid cells'
+		xind=npy.nonzero(npy.logical_and(x>xlim[0],x<xlim[1]))[0]
+		yind=npy.nonzero(npy.logical_and(y>ylim[0],y<ylim[1]))[0]
+		xg,yg=npy.meshgrid(x[xind],y[yind])
+		subdata=data[yind[0]:yind[-1]+1,xind[0]:xind[-1]+1]
+	elif len(x)==data.shape[1]+1 and len(y)==data.shape[0]+1:
+		print '		x,y taken to define the corners of data grid cells'
+		xcenter=npy.fromiter(((x[i]+x[i+1])/2 for i in range(len(x)-1)),npy.float)
+		ycenter=npy.fromiter(((y[i]+y[i+1])/2 for i in range(len(y)-1)),npy.float)
+		xind=npy.nonzero(npy.logical_and(xcenter>xlim[0],xcenter<xlim[1]))[0]
+		yind=npy.nonzero(npy.logical_and(ycenter>ylim[0],ycenter<ylim[1]))[0]
+		xg,yg=npy.meshgrid(xcenter[xind],ycenter[yind])
+		subdata=data[yind[0]:yind[-1]+1,xind[0]:xind[-1]+1]
+	else:
+		raise ValueError('x and y have inconsistent sizes: both should have length ncols(data)/nrows(data) or ncols(data)+1/nrows(data)+1')
+
+	points=npy.array([xg.ravel(),yg.ravel()]).T
+	flatsubdata=subdata.ravel()
+
+	if plotonly:
+		plt.imshow(npy.flipud(subdata),origin='upper')
+		plt.show()
+		return
+
+	# mask out any nan's in the data and corresponding coordinate points
+	mask=npy.isnan(flatsubdata)
+	ind=npy.nonzero(mask)[0]
+	if len(ind) and fill_nans:
+		print "		WARNING: filling nans using spline fit through good data points, which may or may not be appropriate. Check results carefully."
+	goodsubdata=npy.delete(flatsubdata,ind)
+	goodpoints=npy.delete(points,ind,axis=0)
+
+	# create spline and index spline at mesh points
+	spline=CloughTocher2DInterpolator(goodpoints,goodsubdata)
+	interpdata=spline(xi,yi)
+
+	if not fill_nans:
+		# identify nan's in xi,yi using nearest neighbors
+		xyinterp=npy.dstack([xi,yi])[0]
+		xydata=npy.dstack([xg.ravel(),yg.ravel()])[0]
+		tree=cKDTree(xydata)
+		nearest=tree.query(xyinterp)[1]
+		pos=npy.nonzero(npy.isnan(flatsubdata[nearest]))
+		interpdata[pos]=flatsubdata[nearest][pos]
+
+	return interpdata
+#}}}
+def RadialInterp(x,y,data,xi,yi,**kwargs):#{{{
+	'''
+	Interpolation using a radial basis function in 2 or 3 dimensions.
+	Useful for smoothing input data after interpolation.
+
+	Uses scipy.interpolate.Rbf
+
+	x,y:			data point coordinates
+	data:			data to be interpolated (same length as x,y)
+	xi,yi:		coordinates to interpolate onto
+	function:	form of radial basis function for interpolation:
+					'multiquadric': sqrt((r/self.epsilon)**2 + 1) (default)
+					'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
+					'gaussian': exp(-(r/self.epsilon)**2)
+					'linear': r
+					'cubic': r**3
+					'quintic': r**5
+					'thin_plate': r**2 * log(r)
+	epsilon:		adjustable constant for scaling radial distance.  Defaults to 
+					approximate average distance between nodes.
+	smooth:		float>0, adjusts the amount of smoothing applied.  Defaults to 0,
+					such that the function always passes through nodal points.
+	z:				coordinate array if interpolating in 3 dimensions
+	zi:			coordinate array if interpolating in 3 dimensions
+
+	Usage:
+		interpdata=RadialInterp(x,y,data,**kwargs)
+
+	Examples:
+		interpdata=RadialInterp(md.mesh.x,md.mesh.y,data)
+		interpdata=RadialInterp(md.mesh.x,md.mesh.y,data,function='gaussian',epsilon=100,smooth=1)
+	'''
+
+	# unpack kwargs
+	function=kwargs.pop('function','gaussian')
+	if 'function' in kwargs: del kwargs['function']
+	epsilon=kwargs.pop('epsilon',None)
+	if 'epsilon' in kwargs: del kwargs['epsilon']
+	smooth=kwargs.pop('smooth',0)
+	if 'smooth' in kwargs: del kwargs['smooth']
+	z=kwargs.pop('z',None)
+	if 'z' in kwargs: del kwargs['z']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	if z:
+		if epsilon:
+			rbfi=Rbf(x,y,z,data,function=function,smooth=smooth,epsilon=epsilon)
+		else:
+			rbfi=Rbf(x,y,z,data,function=function,smooth=smooth)
+		interpdata=rbfi(xi,yi,zi)
+	else:
+		if epsilon:
+			rbfi=Rbf(x,y,data,function=function,smooth=smooth,epsilon=epsilon)
+		else:
+			rbfi=Rbf(x,y,data,function=function,smooth=smooth)
+		interpdata=rbfi(xi,yi)
+	
+	return interpdata
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/plugvelocities.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/plugvelocities.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/interp/plugvelocities.m	(revision 18231)
@@ -0,0 +1,167 @@
+function md=plugvelocities(md,filename,default_value)
+%PLUGVELOCITIES - load velocities on a model
+%
+%   load a matlab file (extension .mat) which holds 4 variables
+%   x,y,vx,vy to be plugged onto the model (or similar names)
+%   x and y must be vectors, vx, vy matrices
+%
+%   Usage:
+%      md=plugvelocities(md,filename,default_value)
+%
+%   Example:
+%      md=plugvelocities(md,'velocityfile.mat',0);
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+disp('WARNING: deprecated functions (plugvelocities)');
+%some checks
+if nargin~=3 | nargout~=1
+	help plugvelocities
+	error('plugvelocities error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugvelocities error message: file ' filename  ' does not exist']);
+end
+
+%load velocities 
+Names=VelFindVarNames(filename);
+Vel=load(filename);
+
+%Interpolation
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+end
+
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx=md.inversion.vx_obs;
+md.initialization.vy=md.inversion.vy_obs;
+md.initialization.vel=md.inversion.vel_obs;
+end
+
+function Names=VelFindVarNames(filename)
+%VELFINDVARNAMES - find names of variables in a velocity data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,vx,vy)
+%   or (index,x,y,vx,vy)
+%
+%   Usage:
+%      Names=VelFindVarNames(filename)
+%
+%   Example:
+%      Names=VelFindVarNames('velocities.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help VelFindVarNames
+	error('VelFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['VelFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; vxenum=NaN; vyenum=NaN; indexenum=NaN;
+if length(A)==4,
+	isnode=1;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+elseif length(A)==5,
+	isnode=0;
+	for i=1:5
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strcmpi(A(i).name(1),'index') | strcmpi(A(i).name(1),'elements'));
+			indexenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+else
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (it should hold 4 variables x,y,vx and vy (for nodes) OR 5 variables  x,y,index,vx and vy (for mesh))']);
+end
+
+%assum that we have found at least vxenum and vyenum
+if ( isnan(vxenum) | isnan(vyenum))
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (the velocities should be named vx and vy)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:5
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['VelFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%find x y
+if (isnan(xenum) | isnan(yenum))
+
+	%check the size
+	if A(vxenum).size(1)==A(vxenum).size(2),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (velocities is a square matrix, save x and y with another name)']);
+	end
+	if ~(A(vxenum).size(1)==A(vyenum).size(1) & A(vxenum).size(2)==A(vyenum).size(2)),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (vx and vy matrices do not have the same size)']);
+	end
+
+	%find xenum and yenum
+	for i=1:4
+		lengthi=max(A(i).size);
+		if ((i~=vxenum) & (lengthi==A(vxenum).size(1) | lengthi==A(vxenum).size(1)+1)),
+			yenum=i;
+		elseif ((i~=vxenum) & (lengthi==A(vxenum).size(2) | lengthi==A(vxenum).size(2)+1)),
+			xenum=i;
+		end
+	end
+
+	%last check
+	if (isnan(xenum) | isnan(yenum))
+		error(['plugdata error message: file ' filename  ' not supported yet']);
+	end
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.vxname=A(vxenum).name;
+Names.vyname=A(vyenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/MisfitDeinterlace.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/MisfitDeinterlace.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/MisfitDeinterlace.m	(revision 18231)
@@ -0,0 +1,21 @@
+function Jstruct=MisfitDeinterlace(misfit,type)
+%MISFITDEINTERLACE - deinterlace misfits that are mixed together, using type.
+%
+%   Usage:
+%      Jstruct=MisfitDeinterlace(misfit,type)
+%
+%   Example:
+%      Jstruct=MisfitDeinterlace(md.results.stressbalance.J,md.fit)
+%
+%
+Jstruct=struct();
+
+count=1;
+for i=0:max(type),
+	pos=find(type==i);
+	if length(pos),
+		Jstruct(count).type=i;
+		Jstruct(count).J=misfit(pos);
+		count=count+1;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontrolB.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontrolB.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontrolB.m	(revision 18231)
@@ -0,0 +1,121 @@
+function md=parametercontrolB(md,varargin),
+%PARAMETERCONTROLB - parameterization for control method on B
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of B, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontrolB(md,varargin)
+%
+%   Example:
+%      md=parametercontrolB(md)
+%      md=parametercontrolB(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontrolB(md,'cm_min',10,'cm_max',10^8,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontrolB(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also  PARAMETERCONTROLDRAG
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',paterson(273.15+5)*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',paterson(273.15-70)*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.9*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.9*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[ 101:105])),
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[2*10^8*ones(3,1);10^8*ones(third-3,1);10^7*ones(2*third,1);];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.m	(revision 18231)
@@ -0,0 +1,121 @@
+function md=parametercontroldrag(md,varargin),
+%PARAMETERCONTROLDRAG - parameterization for control method on drag
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of the drag, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontroldrag(md,varargin)
+%
+%   Example:
+%      md=parametercontroldrag(md)
+%      md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also PARAMETERCONTROLB
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'FrictionCoefficient'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',1*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',250*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.8*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.8*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[101 105]))
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/parametercontroldrag.py	(revision 18231)
@@ -0,0 +1,118 @@
+def parametercontroldrag(md,*args):
+	"""
+	PARAMETERCONTROLDRAG - parameterization for control method on drag
+
+	It is possible to specify the number of steps, values for the
+	minimum and maximum values of the drag, the 
+	kind of cm_responses to use or the the optscal.
+
+	Usage:
+	   md=parametercontroldrag(md,varargin)
+
+	Example:
+	  md=parametercontroldrag(md)
+	  md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+	  md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+	  md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+
+	See also PARAMETERCONTROLB
+	"""
+
+	#process options
+	options=pairoptions(*args)
+
+	#control type
+	md.inversion.control_parameters='FrictionCoefficient'
+
+	#weights
+	weights=options.getfieldvalue('weights',npy.ones(md.mesh.numberofvertices))
+	if npy.size(weights)!=md.mesh.numberofvertices:
+		md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices)
+	else:
+		md.inversion.cost_functions_coefficients=weights
+
+	#nsteps
+	nsteps=options.getfieldvalue('nsteps',100);
+	if (npy.size(nsteps)!=1) | (nsteps<=0) | (floor(nsteps)!=nsteps):
+		md.inversion.nsteps=100
+	else:
+		md.inversion.nsteps=nsteps
+
+	#cm_min
+	cm_min=options.getfieldvalue('cm_min',ones(md.mesh.numberofvertices))
+	if (npy.size(cm_min)==1):
+		md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices)
+	elif (npy.size(cm_min)==md.mesh.numberofvertices):
+		md.inversion.min_parameters=cm_min
+	else:
+		md.inversion.min_parameters=cm_min;
+
+	#cm_max
+	cm_max=options.getfieldvalue('cm_max',250*ones(md.mesh.numberofvertices))
+	if (npy.size(cm_max)==1):
+		md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices)
+	elif (npy.size(cm_max)==md.mesh.numberofvertices):
+		md.inversion.max_parameters=cm_max
+	else:
+		md.inversion.max_parameters=cm_max
+
+	#eps_cm
+	eps_cm=optoins.getfieldvalue('eps_cm',float('nan'))
+	if (npy.size(eps_cm)~=1 | eps_cm<0 ):
+		md.inversion.cost_function_threshold=float('nan')
+	else:
+		md.inversion.cost_function_threshold=eps_cm
+
+	#maxiter
+	maxiter=options.getfieldvalue('maxiter',10*ones(md.inversion.nsteps))
+	if (npy.any(maxiter<0) | npy.any(floor(maxiter)~=maxiter)):
+		md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps)
+	else:
+		raise RuntimeError("not implemented yet, see below matlab lines")
+		#md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+		#md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+
+	#cm_jump
+	cm_jump=options.getfieldvalue('cm_jump',0.8*ones(md.inversion.nsteps))
+	if !npy.isreal(cm_jump):
+		md.inversion.step_threshold=0.8*ones(md.inversion.nsteps)
+	else:
+		raise RuntimeError("not implemented yet, see below matlab lines")
+		#md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+		#md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+
+	#cm_responses
+	found=0;
+	if options.exist('cm_responses'):
+		cm_responses=options.getfieldvalue('cm_responses')
+		if ~any(~ismember(cm_responses,[101 105])):
+			md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+			md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+			found=1;
+	if ~found
+		third=ceil(md.inversion.nsteps/3);
+		md.inversion.cost_functions=[...
+			103*ones(third,1);...
+			101*ones(third,1);...
+			repmat([101;101;103;101],third,1)...
+			];
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+	end
+
+	%optscal
+	found=0;
+	if exist(options,'optscal'),
+		optscal=getfieldvalue(options,'optscal');
+		if ~any(optscal<0),
+			md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+			md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+			found=1;
+		end
+	end
+	if ~found
+		third=ceil(md.inversion.nsteps/3);
+		md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+	end
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/velocitymisfit.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/velocitymisfit.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/inversions/velocitymisfit.m	(revision 18231)
@@ -0,0 +1,39 @@
+function J=misfit(md)
+%MISFIT - compute misfit
+%
+%   Usage:
+%      J=misfit(md)
+%
+%   Example:
+%      J=misfit(md)
+%
+
+if dimension(md.mesh)==2,
+	elements=md.mesh.elements;
+	x=md.mesh.x;
+	y=md.mesh.y;
+	%vx=md.initialization.vx;
+	%vy=md.initialization.vy;
+	vx=md.results.StressbalanceSolution.Vx;
+	vy=md.results.StressbalanceSolution.Vy;
+	vx_obs=md.inversion.vx_obs;
+	vy_obs=md.inversion.vy_obs;
+else
+	elements=md.mesh.elements2d;
+	x=md.mesh.x2d;
+	y=md.mesh.y2d;
+	vx=project2d(md,md.initialization.vx,md.mesh.numberoflayers);
+	vy=project2d(md,md.initialization.vy,md.mesh.numberoflayers);
+	vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
+	vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
+end
+
+%compute areas;
+areas=GetAreas(elements,x,y);
+
+%compute delta v on elements
+deltav=1/2*(   (vx-vx_obs).^2+(vy-vy_obs).^2)/md.constants.yts^2;
+deltav_elem=deltav(elements)*[1;1;1]/3;
+
+%compute misfit
+J=sum(deltav_elem.*areas);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/io/getShapeTypeInfo.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/getShapeTypeInfo.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/getShapeTypeInfo.m	(revision 18231)
@@ -0,0 +1,181 @@
+function result = getShapeTypeInfo(shapeTypeCode,requestOrQuery)
+
+% CAUTION:  This file contains experimental code that has had only
+%           minimal, informal testing.
+%
+%GETSHAPETYPEINFO   Get information about a shape type.
+%   Returns a single value, based on the second argument:
+%     'TypeString'             -- Return a string
+%     'IsValid'                -- Return a scalar logical
+%     'IsSupported'            -- Return a scalar logical
+%     'BoundingBoxSubscripts'  -- Return a 1-by-n double array
+%     'ShapeRecordReadFcn'     -- Return a function handle
+%     'ShapeDataFieldNames'    -- Return a cell array of string.
+
+% Copyright 1996-2010 The MathWorks, Inc.
+% $Revision$  $Date$
+
+lutFields = { 'TypeCode',...
+              'TypeString',...
+              'IsValid',...
+              'IsSupported',...
+              'BoundingBoxSubscripts',...
+              'ShapeRecordReadFcn',...
+              'ShapeDataFieldNames' };
+
+% Three kinds of bounding box subscripts
+bbs2D = [1 2; 3 4];
+bbsZ  = [1 2 5; 3 4 6]; % Ignore M for now, otherwise use [1 2 5 7; 3 4 6 8]
+bbsM  = [1 2 7; 3 4 8];
+
+typeLUT = {...
+   -1, 'Not Valid',   false, false, [],    [], {''};... 
+    0, 'Null Shape',  true,  true,  [],    [], {''};... 
+    1, 'Point',       true,  true,  bbs2D, @readPoint,      {'Geometry','X','Y'};... 
+    3, 'PolyLine',    true,  true,  bbs2D, @readPolyLine,   {'Geometry','BoundingBox','X','Y'};...
+    5, 'Polygon',     true,  true,  bbs2D, @readPolygon,    {'Geometry','BoundingBox','X','Y'};...
+    8, 'MultiPoint',  true,  true,  bbs2D, @readMultiPoint, {'Geometry','BoundingBox','X','Y'};...
+   11, 'PointZ',      true,  false, bbsZ,  [], {''};...
+   13, 'PolyLineZ',   true,  true,  bbsZ,  @readPolyLineZ,  {'Geometry','BoundingBox','X','Y','Z'};... 
+   15, 'PolygonZ',    true,  true,  bbsZ,  @readPolygonZ,   {'Geometry','BoundingBox','X','Y','Z'};... 
+   18, 'MultiPointZ', true,  false, bbsZ,  [], {''};... 
+   21, 'PointM',      true,  false, bbsM,  [], {''};... 
+   23, 'PolyLineM',   true,  false, bbsM,  [], {''};... 
+   25, 'PolygonM',    true,  false, bbsM,  [], {''};... 
+   28, 'MultiPointM', true,  false, bbsM,  [], {''};... 
+   31, 'MultiPatch',  true,  false, bbsZ,  [], {''};... 
+  };
+notValidRow = 1;
+types = [typeLUT{:,1}];
+
+% MAINTENANCE NOTE: To add support for additional types, add more rows
+% to the type look up table (typeLUT), but be sure to keep 'Not Valid'
+% in the first row.
+
+row = find(shapeTypeCode == types);
+if length(row) ~= 1
+    row = notValidRow;
+end
+
+col = strmatch(lower(requestOrQuery),lower(lutFields));
+if length(col) ~= 1;
+    eid = sprintf('%s:%s:internalProblem',getcomp,mfilename);
+    error(eid,'Internal error: Invalid second argument in private function.');
+end
+
+result = typeLUT{row,col};
+
+%---------------------------------------------------------------------------
+function shp = readPoint(fid)
+
+point = fread(fid,[2 1],'double','ieee-le');
+shp = {'Point', point(1), point(2)};
+
+%---------------------------------------------------------------------------
+function shp = readMultiPoint(fid)
+
+boundingBox    = fread(fid,4,'double','ieee-le');
+numPoints      = fread(fid,1,'uint32','ieee-le');
+points         = fread(fid,[2 numPoints],'double','ieee-le')';
+shp = {'MultiPoint', boundingBox([1 2; 3 4]), points(:,1)', points(:,2)'};
+
+%---------------------------------------------------------------------------
+function shp = readPolyLine(fid)
+
+boundingBox    = fread(fid,4,'double','ieee-le');
+numPartsPoints = fread(fid,2,'uint32','ieee-le');
+partOffsets    = fread(fid,[1 numPartsPoints(1)],'uint32','ieee-le');
+points         = fread(fid,[2 numPartsPoints(2)],'double','ieee-le')';
+[x,y] = organizeParts2D(partOffsets,points);
+shp = {'Line', boundingBox([1 2; 3 4]), x, y};
+
+%---------------------------------------------------------------------------
+function shp = readPolygon(fid)
+
+boundingBox    = fread(fid,4,'double','ieee-le');
+numPartsPoints = fread(fid,2,'uint32','ieee-le');
+partOffsets    = fread(fid,[1 numPartsPoints(1)],'uint32','ieee-le');
+points         = fread(fid,[2 numPartsPoints(2)],'double','ieee-le')';
+[x,y] = organizeParts2D(partOffsets,points);
+shp = {'Polygon', boundingBox([1 2; 3 4]), x, y};
+
+%---------------------------------------------------------------------------
+function [x,y] = organizeParts2D(partOffsets,points)
+
+numParts  = size(partOffsets,2);
+numPoints = size(points,1);
+% Initialize x and y to be row vectors of NaN
+% with length numPoints * numParts
+x = NaN + zeros(1, numPoints + numParts);
+y = x;
+if numParts == 1
+    x(1, 1:numPoints) = points(:,1);
+    y(1, 1:numPoints) = points(:,2);
+else
+    partStart = 1 + partOffsets;
+    partEnd   = [partOffsets(2:end) numPoints];
+    for k = 1:numParts
+        xyStart = partStart(k) + (k - 1);
+        xyEnd   = partEnd(k)   + (k - 1);
+        x(1, xyStart:xyEnd) = points(partStart(k):partEnd(k), 1);
+        y(1, xyStart:xyEnd) = points(partStart(k):partEnd(k), 2);
+    end
+end
+
+%---------------------------------------------------------------------------
+function shp = readPolyLineZ(fid)
+
+boundingBox    = fread(fid,4,'double','ieee-le');
+numPartsPoints = fread(fid,2,'uint32','ieee-le');
+partOffsets    = fread(fid,[1 numPartsPoints(1)],'uint32','ieee-le');
+points         = fread(fid,[2 numPartsPoints(2)],'double','ieee-le')';
+zRange         = fread(fid,2,'double','ieee-le'); %#ok
+zArray         = fread(fid, numPartsPoints(2), 'double', 'ieee-le');
+[x,y,z] = organizeParts3D(partOffsets,points,zArray);
+% shp = {'Line', [boundingBox([1 2; 3 4]) zRange], x, y, z};
+% Note:
+%   Keep bounding box 2-D for now for compatibility with
+%   mapshow and geoshow.
+shp = {'Line', boundingBox([1 2; 3 4]), x, y, z};
+
+%---------------------------------------------------------------------------
+function shp = readPolygonZ(fid)
+
+boundingBox    = fread(fid,4,'double','ieee-le');
+numPartsPoints = fread(fid,2,'uint32','ieee-le');
+partOffsets    = fread(fid,[1 numPartsPoints(1)],'uint32','ieee-le');
+points         = fread(fid,[2 numPartsPoints(2)],'double','ieee-le')';
+zRange         = fread(fid,2,'double','ieee-le'); %#ok
+zArray         = fread(fid, numPartsPoints(2), 'double', 'ieee-le');
+[x,y,z] = organizeParts3D(partOffsets,points,zArray);
+% shp = {'Polygon', [boundingBox([1 2; 3 4]) zRange], x, y, z};
+% Note:
+%   Keep bounding box 2-D for now for compatibility with
+%   mapshow and geoshow.
+shp = {'Polygon', boundingBox([1 2; 3 4]), x, y, z};
+
+%---------------------------------------------------------------------------
+function [x,y,z] = organizeParts3D(partOffsets,points,zArray)
+
+numParts  = size(partOffsets,2);
+numPoints = size(points,1);
+% Initialize x and y to be row vectors of NaN
+% with length numPoints * numParts
+x = NaN + zeros(1, numPoints + numParts);
+y = x;
+z = x;
+if numParts == 1
+    x(1, 1:numPoints) = points(:,1);
+    y(1, 1:numPoints) = points(:,2);
+    z(1, 1:numPoints) = zArray(:,1);
+else
+    partStart = 1 + partOffsets;
+    partEnd   = [partOffsets(2:end) numPoints];
+    for k = 1:numParts
+        xyzStart = partStart(k) + (k - 1);
+        xyzEnd   = partEnd(k)   + (k - 1);
+        x(1, xyzStart:xyzEnd) = points(partStart(k):partEnd(k), 1);
+        y(1, xyzStart:xyzEnd) = points(partStart(k):partEnd(k), 2);
+        z(1, xyzStart:xyzEnd) = zArray(partStart(k):partEnd(k), 1);
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.m	(revision 18231)
@@ -0,0 +1,46 @@
+function varargout=loadmodel(path)
+%LOADMODEL - load a model using built-in load module
+%
+%   check that model prototype has not changed. if so, adapt to new model prototype.
+%
+%   Usage:
+%      md=loadmodel(path)
+%      loadmodel path
+
+%check nargout
+if nargout>1,
+	error('loadmodel usage error: md=loadmodel(path)');
+end
+
+%check existence
+if exist(path,'file')
+	%do nothing
+elseif exist([path '.mat'],'file')
+	%add extension
+	path = [path '.mat'];
+else
+	error(['loadmodel error message: file ' path ' does not exist']);
+end
+
+try,
+	%recover model on file and name it md
+	warning off MATLAB:unknownElementsNowStruc;
+	warning off MATLAB:load:classNotFound
+	struc=load(path,'-mat');
+	warning on MATLAB:unknownElementsNowStruc;
+	warning on MATLAB:load:classNotFound
+
+	name=char(fieldnames(struc));
+	if size(name,1)>1,
+		error(['loadmodel error message: file ' path ' contains several variables. Only one model should be present.']); 
+	end
+	md=struc.(name);
+	if nargout,
+		varargout{1}=md;
+	else
+		assignin('caller',name,md);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodel.py	(revision 18231)
@@ -0,0 +1,35 @@
+from loadvars import loadvars
+from whichdb import whichdb
+
+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 of database (independent of file extension!)
+	if whichdb(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/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodellist.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodellist.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadmodellist.m	(revision 18231)
@@ -0,0 +1,50 @@
+function varargout=loadmodellist(path)
+%LOADMODELLIST- load a model using built-in load module
+%
+%   check that modellist prototype has not changed. if so, adapt to new modellist prototype.
+%
+%   Usage:
+%      mds=loadmodellist(path)
+%      loadmodellist path
+
+%check nargout
+if nargout>1,
+	error('loadmodellist usage error: mds=loadmodellist(path)');
+end
+%check existence
+if ~exist(path)
+	error(['loadmodellist error message: file ' path ' does not exist']);
+end
+
+%check that the file is readable
+[stat,mess]=fileattrib(path);
+if( stat==0 | mess.UserRead~=1),
+	error(['loadmodellist error message: file ' path ' is not readable (permission dinied).']);
+end
+
+%check number of variables
+if length(whos('-file',path))>1,
+	error(['loadmodellist error message: file ' path ' contains several variables. Only one model should be present.']);
+end
+
+try,
+	struc=load(path,'-mat');
+
+	%get name of model variable
+	fieldname=char(fieldnames(struc));
+	mds=eval(['struc.' fieldname]);
+	if ~strcmpi(class(mds),'model'),
+		mds2=modellist;
+		mds2=structtomodel(mds2,mds);
+		mds=mds2;
+		clear mds2;
+	end
+	if nargout,
+		varargout{1}=mds;
+	else
+		assignin('caller',fieldname,mds);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadvars.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadvars.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/loadvars.py	(revision 18231)
@@ -0,0 +1,84 @@
+import shelve
+import os.path
+from whichdb import whichdb
+
+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 whichdb(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/branches/trunk-jpl-ad2-integrated/src/m/io/savevars.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/savevars.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/savevars.py	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/io/structtonc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/io/structtonc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/io/structtonc.m	(revision 18231)
@@ -0,0 +1,131 @@
+function [var_id,counter] = structtonc(ncid,fieldname,field,depth,var_id,counter,step);
+%STRUCTTONC- fill nc file with structure fields
+%
+%   WARNING: Do not use this function, this function is called
+%            by netcdf(model);
+%
+
+%update counter
+counter   = counter+1;
+
+%Check that field is not empty
+if isempty(field) | (isa(field,'struct') & numel(fields(field))==0),
+	if(step==1), disp(['skipping ' fieldname ' (empty)...']); end
+	return;
+end
+
+%Write field class
+[var_id,counter] = declareclass(ncid,[fieldname '_class'],class(field),depth,var_id,counter,step);
+
+%Double scalar
+if isa(field,'double') & numel(field)==1,
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+
+%Double vector
+elseif isa(field,'double') & size(field,2)==1,
+	if step==1,
+		dim_id          = netcdf.defDim(ncid,[fieldname '_size1'],size(field,1));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+
+%double matrix
+elseif isa(field,'double') & size(field,2)>1,
+	if step==1,
+		dim1_id         = netcdf.defDim(ncid,[fieldname '_size1'],size(field,1));
+		dim2_id         = netcdf.defDim(ncid,[fieldname '_size2'],size(field,2));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',[dim2_id dim1_id]);
+	else
+		netcdf.putVar(ncid,var_id(counter),transpose(field));
+	end
+
+%string
+elseif isa(field,'char') 
+		if step==1,
+			dim_id          = netcdf.defDim(ncid,[fieldname '_size1'],numel(field));
+			var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_CHAR',dim_id);
+		else
+			netcdf.putVar(ncid,var_id(counter),field);
+		end
+
+%Boolean of size 1
+elseif isa(field,'logical') & numel(field)==1,
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_BYTE',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),int8(field));
+	end
+
+%Structures
+elseif isa(field,'struct'),
+	sublength = numel(field);
+	subfields = fields(field);
+	allsubfields = '';
+	for i=1:length(subfields),
+		allsubfields=[allsubfields subfields{i}];
+		if i~=length(subfields), allsubfields=[allsubfields ' ']; end
+	end
+	%Write size
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_length'],'NC_INT',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),sublength);
+	end
+	counter=counter+1;
+	%Write fields
+	if step==1,
+
+		dim_id          = netcdf.defDim(ncid,[fieldname '_fields_length'],numel(allsubfields));
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_fields'],'NC_CHAR',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),allsubfields);
+	end
+	for n=1:sublength,
+		for i=1:length(subfields),
+			[var_id,counter] = structtonc(ncid,[fieldname '.' subfields{i} '(' num2str(n) ')'],field(n).(subfields{i}),depth+1,var_id,counter,step);
+		end
+	end
+
+%Cell
+elseif isa(field,'cell'),
+	sublength = numel(field);
+	%Write size
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_length'],'NC_INT',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),sublength);
+	end
+	for i=1:sublength,
+		[var_id,counter] = structtonc(ncid,[fieldname '{' num2str(i) '}'],field{i},depth+1,var_id,counter,step);
+	end
+
+%Objects
+elseif isobject(field),
+	subfields = fields(field);
+	for i=1:length(subfields),
+		[var_id,counter] = structtonc(ncid,[fieldname '.' subfields{i}],field.(subfields{i}),depth+1,var_id,counter,step);
+	end
+else
+	disp(['skipping ' fieldname ' (format not supported)...']);
+end
+
+function [var_id,counter] = declareclass(ncid,fieldname,field,depth,var_id,counter,step);
+
+if isa(field,'char') 
+	if step==1,
+		dim_id          = netcdf.defDim(ncid,[fieldname '_length'],numel(field));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_CHAR',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+else
+	error('class name is not a string');
+end
+
+%update counter
+counter   = counter+1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/README.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/README.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/README.txt	(revision 18231)
@@ -0,0 +1,66 @@
+The Matlab scripts in the kml directory may be divided into three areas:
+    1. kml class definitions
+    2. kml utilities
+    3. kml drivers
+
+Each of the three will be discussed below.
+
+I.  KML Class Definitions
+
+All the kml is defined using the reference:
+http://code.google.com/apis/kml/documentation/kmlreference.html
+
+Many of the kml objects described in the first figure of the kml reference are defined as Matlab objects, with most or all of the kml properties.  The classes consist of one base class and several levels of derived classes (super and sub, respectively, in Matlab terminology).  The hierarchy of these classes are as follows.
+
+kml_object.m
+    kml_feature.m
+        kml_placemark.m
+        kml_container.m
+            kml_folder.m
+            kml_document.m
+    kml_geometry.m
+        kml_point.m
+        kml_linestring.m
+        kml_linearring.m
+        kml_polygon.m
+        kml_multigeometry.m
+    kml_styleselector.m
+        kml_style.m
+    kml_substyle.m
+        kml_colorstyle.m
+            kml_linestyle.m
+            kml_polystyle.m
+
+For each class, the methods consist of a constructor, a display method, a fieldnames method (since objects can not use the Matlab "fieldnames" function), a set method, and a write method.  All of the methods, as well as the properties, inherit the base classes where appropriate rather than repeating any functionality.  The Matlab "help" command can be used to list the documentation for any of the classes.
+
+II.  KML Utilities
+
+The kml utilities take an ISSM model (and optionally results) and write it into a kml object, typically a kml folder, in various ways.  The kml object could then be written into a file, by itself or with others, and imported into Google Earth.  Note that kml polygons can only be one color, not interpolated.
+
+The following kml utilities have been written.  The kml_mesh_elem and kml_partitions are probably the most useful, because the rest are intermediate results.  The Matlab "help" command can again be used to list the documentation.
+
+kml_mesh_elem.m      - write a kml folder with each ISSM element as a kml polygon (color-coded by results, if provided)
+kml_part_flagedges.m - write a kml folder with each segment between two ISSM partitions as a kml linestring
+kml_unsh_edges.m     - write a kml folder with each unshared segment of an ISSM partition as a kml linestring
+kml_part_elems.m     - write a kml folder with all the elements of each ISSM partition as kml polygons, noting that elements are repeated for each partition in which they have nodes (color-coded by results, if provided)
+kml_part_edges.m     - write a kml folder with all the edges of each ISSM partition as a kml linestring (color-coded by results, if provided)
+kml_partitions.m     - write a kml folder with each ISSM partition as a kml polygon (color-coded by results, if provided)
+
+In order the write any and all kml objects that have been constructed to a file for import into Google Earth, the following function has been written.
+
+kml_file_write.m     - write a kml file of the specified kml objects (may open and/or close file)
+
+III.  KML Drivers
+
+There is one kml driver, which may be used as a model for custom drivers.  It takes an ISSM model, converts the data from node to element (if necessary), and writes some kml headers and style templates.  In addition, it constructs six kml folders for the first six kml utilities above, then writes those to the file and closes the file.
+
+kml_mesh_write.m     - write a kml file of the ISSM model (color-coded by results, if provided)
+
+IV.  Other Utilities
+
+There are some other utilities that are used in the construction of topological tables for the kml writing.
+
+kmlnodeconnectivity.m   - create a node connectivity table (nnodes x mxepg+1)
+edgeadjacency.m      - create an edge adjacency array (elems x edges)
+edgeperimeter.m      - create an edge perimeter (edgeper x 2) and element perimeter (edgeper x 1) list
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeadjacency.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeadjacency.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeadjacency.m	(revision 18231)
@@ -0,0 +1,47 @@
+%
+%  create an edge adjacency table for the elements in the model.
+%
+%  [edgeadj]=edgeadjacency(elem,nodecon)
+%
+%  where the required input is:
+%    elem          (numeric, element connectivity array (elems x nodes))
+%    nodecon       (numeric, node connectivity array (nodes x elems+1))
+%
+%  and the required output is:
+%    edgeadj       (numeric, edge adjacency array (elems x edges))
+%
+function [edgeadj]=edgeadjacency(elem,nodecon)
+
+if ~nargin
+    help edgeadjacency
+    return
+end
+
+%%  create the edge adjacency array
+
+edgeadj=zeros(size(elem));
+
+%  loop over the elements
+
+for i=1:size(elem,1)
+
+%  loop over the edges for each element (trias only for now)
+
+    for j=1:size(elem,2)
+        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
+
+        for k=1:nodecon(inode1,end)
+            if (nodecon(inode1,k) ~= i) && ...
+               ~isempty(find(elem(nodecon(inode1,k),:)==inode2,1))
+                edgeadj(i,j)=nodecon(inode1,k);
+                break;
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeperimeter.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeperimeter.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/edgeperimeter.m	(revision 18231)
@@ -0,0 +1,87 @@
+%
+%  create an edge perimeter list for the elements in the model.
+%
+%  [edgeper,elemper,iloop]=edgeperimeter(elem,nodecon,edgeadj)
+%
+%  where the required input is:
+%    elem          (numeric, element connectivity array (elems x nodes))
+%    nodecon       (numeric, node connectivity array (nodes x elems+1))
+%
+%  and the required output is:
+%    edgeper       (numeric, edge perimeter list (edgeper x 2))
+%    elemper       (numeric, element perimeter list (edgeper x 1))
+%    iloop         (numeric, index for each loop (nloop))
+%
+%  the optional input is:
+%    edgeadj       (numeric, edge adjacency array (elems x edges))
+%
+function [edgeper,elemper,iloop]=edgeperimeter(elem,nodecon,edgeadj)
+
+if ~nargin
+    help edgeperimeter
+    return
+end
+
+%%  create the edge adjacency array
+
+if ~exist('edgeadj','var') || isempty(edgeadj)
+    edgeadj=edgeadjacency(elem,nodecon);
+end
+
+%%  create the unshared edge list
+
+[icol,irow]=find(edgeadj'==0);
+edgeuns=zeros(length(irow),2);
+elemuns=zeros(length(irow),1);
+
+%  loop over the edges
+
+for i=1:length(irow)
+    edgeuns(i,1)=elem(irow(i),icol(i));
+    edgeuns(i,2)=elem(irow(i),mod(icol(i),size(elem,2))+1);
+    elemuns(i)=irow(i);
+end
+
+%%  create the edge perimeter list
+
+edgeper=zeros(size(edgeuns));
+elemper=zeros(size(elemuns));
+iloop=[];
+ipt=0;
+
+%  find the beginning of a loop
+
+while ~isempty(find(edgeuns,1))
+    ipt=ipt+1;
+    iloop(end+1)=ipt;
+    [irow,icol]=find(edgeuns,1);
+    edgeper(ipt,:)=edgeuns(irow,:);
+    elemper(ipt)  =elemuns(irow);
+    edgeuns(irow,:)=[0 0];
+    elemuns(irow)  =0;
+    [irow,icol]=find(edgeuns==edgeper(ipt,2),1);
+
+%  continue following the loop
+
+    while ~isempty(irow)
+        ipt=ipt+1;
+        if (icol == 1)
+            edgeper(ipt,:)=edgeuns(irow,:);
+        else
+            edgeper(ipt,1)=edgeuns(irow,2);
+            edgeper(ipt,2)=edgeuns(irow,1);
+        end
+        elemper(ipt)  =elemuns(irow);
+        edgeuns(irow,:)=[0 0];
+        elemuns(irow)  =0;
+        [irow,icol]=find(edgeuns==edgeper(ipt,2),1);
+    end
+
+%  check to see if loop is closed
+
+    if (edgeper(iloop(end),1) ~= edgeper(ipt,2))
+        warning('Loop %d is not closed.\n',length(loop));
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2exp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2exp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2exp.m	(revision 18231)
@@ -0,0 +1,26 @@
+function kml2exp(input,output)
+%KML2EXP: transform kml file Argus exp file.
+%
+% Usage:    kmltoexp('temp.kml','temp2.exp')
+%
+%
+
+%First, read polygon kml file.
+structure=kml_shapefile(input);
+
+%create exp file: 
+domain=struct();
+for i=1:length(structure),
+
+	if isfield(structure,'name'),
+		domain(end+1).name=structure(i).name;
+	else
+		domain(end+1).name='NaN';
+	end
+
+	domain(end).density=1;
+	domain(end).x=structure(i).X;
+	domain(end).y=structure(i).Y;
+end
+domain=domain(2:end);
+expwrite(domain,output);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2expg.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2expg.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml2expg.m	(revision 18231)
@@ -0,0 +1,13 @@
+function kml2expg(filename)
+
+	[path,name,ext]=fileparts(filename);
+
+	if strcmpi(ext,'.kmz'),
+		eval(['!unzip ' filename]);
+		eval(['!mv doc.kml ' name '.kml']);
+		kml2exp([name '.kml'],[name '.exp']);
+		expll2xy([name '.exp'],1);
+	end
+
+	kml2exp([name '.kml'],[name '.exp']);
+	expll2xy([name '.exp'],1);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_colorstyle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_colorstyle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_colorstyle.m	(revision 18231)
@@ -0,0 +1,201 @@
+%
+%  definition for the kml_colorstyle super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_colorstyle(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, colorstyle id, '')
+%    color         (char, opacity/color in hex aabbggrr, 'ffffffff')
+%    colormode     (char, color mode , 'normal')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_colorstyle < kml_substyle
+    properties
+        color     ='ffffffff';
+        colormode ='normal';
+    end
+
+    methods
+        function [kml]=kml_colorstyle(varargin)
+
+            kml=kml@kml_substyle(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_colorstyle());
+
+                        for i=length(fieldnames(kml_substyle()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_colorstyle')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_substyle(kml(i));
+                disp(sprintf('         color: ''%s'''  ,kml(i).color));
+                if strcmp(class(kml),'kml_colorstyle')
+                    disp(sprintf('     colormode: ''%s''\n',kml(i).colormode));
+                else
+                    disp(sprintf('     colormode: ''%s'''  ,kml(i).colormode));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_substyle());
+            fnames={fnames{:} ...
+                    'color' ...
+                    'colormode' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the colorstyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_colorstyle')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!ColorStyle id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!ColorStyle>\n',indent);
+                    end
+                end
+                kml_write@kml_substyle(kmli,fid,indent);
+                if ~isempty(kmli.color)
+                    fprintf(fid,'%s  <color>%s</color>\n',indent,kmli.color);
+                end
+                if ~isempty(kmli.colormode)
+                    fprintf(fid,'%s  <colorMode>%s</colorMode>\n',indent,kmli.colormode);
+                end
+                if strcmp(class(kml),'kml_colorstyle')
+                    fprintf(fid,'%s</!ColorStyle>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the colorstyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_colorstyle')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!ColorStyle id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!ColorStyle>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_substyle(kmli,sbuf,indent);
+                if ~isempty(kmli.color)
+                    sbuf=add(sbuf,sprintf('%s  <color>%s</color>\n',indent,kmli.color));
+                end
+                if ~isempty(kmli.colormode)
+                    sbuf=add(sbuf,sprintf('%s  <colorMode>%s</colorMode>\n',indent,kmli.colormode));
+                end
+                if strcmp(class(kml),'kml_colorstyle')
+                    sbuf=add(sbuf,sprintf('%s</!ColorStyle>\n',indent));
+                end
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_container.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_container.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_container.m	(revision 18231)
@@ -0,0 +1,198 @@
+%
+%  definition for the kml_container super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_container(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, container id, '')
+%    name          (char, name, '')
+%    visibility    (logical, visibility, true)
+%    open          (logical, open, false)
+%    snippet       (char, snippet, '')
+%    descript      (char, description, '')
+%    styleurl      (char, style url, '')
+%    style         (cell array, styles)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_container < kml_feature
+    properties
+    end
+
+    methods
+        function [kml]=kml_container(varargin)
+
+            kml=kml@kml_feature(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_container());
+
+                        for i=length(fieldnames(kml_feature()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_container')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_feature(kml(i));
+                if strcmp(class(kml),'kml_container')
+                    disp(sprintf('\n'));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_feature());
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the containers
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_container')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!Container id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!Container>\n',indent);
+                    end
+                end
+                kml_write@kml_feature(kmli,fid,indent);
+                if strcmp(class(kml),'kml_container')
+                    fprintf(fid,'%s<!/Container>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the containers
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_container')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!Container id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!Container>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_feature(kmli,sbuf,indent);
+                if strcmp(class(kml),'kml_container')
+                    sbuf=add(sbuf,sprintf('%s<!/Container>\n',indent));
+                end
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the containers
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+                delete@kml_feature(kmli);
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_document.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_document.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_document.m	(revision 18231)
@@ -0,0 +1,235 @@
+%
+%  definition for the kml_document sub (derived) class.
+%
+%  [kml]=kml_document(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, document id, '')
+%    name          (char, name, '')
+%    visibility    (logical, visibility, true)
+%    open          (logical, open, false)
+%    snippet       (char, snippet, '')
+%    descript      (char, description, '')
+%    styleurl      (char, style url, '')
+%    style         (cell array, styles)
+%    feature       (cell array, placemark features)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_document < kml_container
+    properties
+        feature   ={};
+    end
+
+    methods
+        function [kml]=kml_document(varargin)
+
+            kml=kml@kml_container(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_document());
+
+                        for i=length(fieldnames(kml_container()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_container(kml(i));
+                disp(sprintf('       feature: %s %s\n' ,string_size(kml(i).feature),...
+                             class(kml(i).feature)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_feature());
+            fnames={fnames{:} ...
+                    'feature' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the documents
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<Document id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<Document>\n',indent);
+                end
+                kml_write@kml_container(kmli,fid,indent);
+
+%  loop over the features for each document
+
+                for j=1:numel(kmli.feature)
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            kml_write(kmli.feature{j},fid,[indent '  ']);
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+
+                fprintf(fid,'%s</Document>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the documents
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<Document id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<Document>\n',indent));
+                end
+                sbuf=kml_swrite@kml_container(kmli,sbuf,indent);
+
+%  loop over the features for each document
+
+                for j=1:numel(kmli.feature)
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            sbuf=kml_swrite(kmli.feature{j},sbuf,[indent '  ']);
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+
+                sbuf=add(sbuf,sprintf('%s</Document>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the documents
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+                delete@kml_container(kmli);
+
+%  loop over the features for each document
+
+                for j=numel(kmli.feature):-1:1
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            delete(kmli.feature{j});
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+                kmli.feature   ={};
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_feature.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_feature.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_feature.m	(revision 18231)
@@ -0,0 +1,294 @@
+%
+%  definition for the kml_feature super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_feature(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, feature id, '')
+%    name          (char, name, '')
+%    visibility    (logical, visibility, true)
+%    open          (logical, open, false)
+%    snippet       (char, snippet, '')
+%    descript      (char, description, '')
+%    styleurl      (char, style url, '')
+%    style         (cell array, styles)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_feature < kml_object
+    properties
+        name      ='';
+        visibility=true;
+        open      =false;
+        snippet   ='';
+        descript  ='';
+        styleurl  ='';
+        style     ={};
+    end
+
+    methods
+        function [kml]=kml_feature(varargin)
+
+            kml=kml@kml_object(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_feature());
+
+                        for i=length(fieldnames(kml_object()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_feature')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_object(kml(i));
+                disp(sprintf('          name: ''%s'''  ,kml(i).name));
+                disp(sprintf('    visibility: %g'      ,kml(i).visibility));
+                disp(sprintf('          open: %g'      ,kml(i).open));
+                disp(sprintf('       snippet: ''%s'''  ,kml(i).snippet));
+                disp(sprintf('      descript: ''%s'''  ,kml(i).descript));
+                disp(sprintf('      styleurl: ''%s'''  ,kml(i).styleurl));
+                if strcmp(class(kml),'kml_feature')
+                    disp(sprintf('         style: %s %s\n' ,string_size(kml(i).style),...
+                                 class(kml(i).style)));
+                else
+                    disp(sprintf('         style: %s %s'   ,string_size(kml(i).style),...
+                                 class(kml(i).style)));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_object());
+            fnames={fnames{:} ...
+                    'name' ...
+                    'visibility' ...
+                    'open' ...
+                    'snippet' ...
+                    'descript' ...
+                    'styleurl' ...
+                    'style' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the features
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_feature')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!Feature id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!Feature>\n',indent);
+                    end
+                end
+                kml_write@kml_object(kmli,fid,indent);
+                if ~isempty(kmli.name)
+                    fprintf(fid,'%s  <name>%s</name>\n',indent,kmli.name);
+                end
+                fprintf(fid,'%s  <visibility>%d</visibility>\n',indent,kmli.visibility);
+                fprintf(fid,'%s  <open>%d</open>\n',indent,kmli.open);
+                if ~isempty(kmli.snippet)
+                    fprintf(fid,'%s  <Snippet maxLines="2">%s</Snippet>\n',indent,kmli.snippet);
+                end
+                if ~isempty(kmli.descript)
+                    fprintf(fid,'%s  <description>%s</description>\n',indent,kmli.descript);
+                end
+                if ~isempty(kmli.styleurl)
+                    fprintf(fid,'%s  <styleUrl>%s</styleUrl>\n',indent,kmli.styleurl);
+                end
+
+%  loop over the styles for each feature
+
+                for j=1:numel(kmli.style)
+                    if ~isempty(kmli.style{j})
+                        if isa(kmli.style{j},'kml_styleselector')
+                            kml_write(kmli.style{j},fid,[indent '  ']);
+                        else
+                            warning('kml(%d).style{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.style{j}),'kml_styleselector');
+                        end
+                    end
+                end
+
+                if strcmp(class(kml),'kml_feature')
+                    fprintf(fid,'%s<!/Feature>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the features
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_feature')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!Feature id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!Feature>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_object(kmli,sbuf,indent);
+                if ~isempty(kmli.name)
+                    sbuf=add(sbuf,sprintf('%s  <name>%s</name>\n',indent,kmli.name));
+                end
+                sbuf=add(sbuf,sprintf('%s  <visibility>%d</visibility>\n',indent,kmli.visibility));
+                sbuf=add(sbuf,sprintf('%s  <open>%d</open>\n',indent,kmli.open));
+                if ~isempty(kmli.snippet)
+                    sbuf=add(sbuf,sprintf('%s  <Snippet maxLines="2">%s</Snippet>\n',indent,kmli.snippet));
+                end
+                if ~isempty(kmli.descript)
+                    sbuf=add(sbuf,sprintf('%s  <description>%s</description>\n',indent,kmli.descript));
+                end
+                if ~isempty(kmli.styleurl)
+                    sbuf=add(sbuf,sprintf('%s  <styleUrl>%s</styleUrl>\n',indent,kmli.styleurl));
+                end
+
+%  loop over the styles for each feature
+
+                for j=1:numel(kmli.style)
+                    if ~isempty(kmli.style{j})
+                        if isa(kmli.style{j},'kml_styleselector')
+                            sbuf=kml_swrite(kmli.style{j},sbuf,[indent '  ']);
+                        else
+                            warning('kml(%d).style{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.style{j}),'kml_styleselector');
+                        end
+                    end
+                end
+
+                if strcmp(class(kml),'kml_feature')
+                    sbuf=add(sbuf,sprintf('%s<!/Feature>\n',indent));
+                end
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the features
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+
+%  loop over the styles for each feature
+
+                for j=numel(kmli.style):-1:1
+                    if ~isempty(kmli.style{j})
+                        if isa(kmli.style{j},'kml_styleselector')
+                            delete(kmli.style{j});
+                        else
+                            warning('kml(%d).style{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.style{j}),'kml_styleselector');
+                        end
+                    end
+                end
+                kmli.style     ={};
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_swrite.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_swrite.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_swrite.m	(revision 18231)
@@ -0,0 +1,131 @@
+%
+%  string write a kml file of the kml objects.
+%
+%  [fid]=kml_file_swrite(kobj,filek,indent)
+%
+%  where the required input is:
+%    kobj          (kml_object, kml object to be written)
+%     or
+%    kobj          (cell array, array of kml objects)
+%
+%  the optional input is:
+%    filek         (char, name of .kml file)
+%     or
+%    filek         (numeric, file ID of already-open file,
+%                            noting 1=stdout and 2=stderr)
+%    indent        (char, indention string)
+%
+%  and the optional output is:
+%    fid           (numeric, file ID of still-open file)
+%
+function [fid]=kml_file_swrite(kobj,filek,indent)
+
+if ~nargin
+    help kml_file_swrite
+    return
+end
+
+%%  process input data
+
+if ~iscell(kobj)
+    kobj={kobj};
+end
+
+fid=0;
+if ~exist('filek' ,'var') || (~ischar(filek) && ~isnumeric(filek))
+    filek='';
+elseif ischar(filek)
+    if     strcmpi(filek,'stdout')
+        fid=1;
+    elseif strcmpi(filek,'stderr')
+        fid=2;
+    end
+elseif isnumeric(filek)
+    fid=filek;
+    if     (fid == 1)
+        filek='stdout';
+    elseif (fid == 2)
+        filek='stderr';
+    else
+        filek='';
+    end
+end
+
+if ~exist('indent','var') || ~ischar(indent)
+    indent='  ';
+end
+
+%%  string write kml file
+
+sbuf=string_buf;
+
+%  open file and write header data (if necessary)
+
+if ~fid
+    if isempty(filek)
+        filek=input('kml file to write?  ','s');
+    end
+    [pathstr,name,ext,versn] = fileparts(filek);
+    if isempty(ext)
+        ext='.kml';
+    end
+    filek=fullfile(pathstr,[name ext versn]);
+
+    display(sprintf('Opening kml file ''%s''.',filek));
+    fid=fopen(sprintf('%s',filek),'w');
+    if (fid < 0)
+        error('File ''%s'' could not be opened.',filek);
+    end
+
+    sbuf=add(sbuf,sprintf('<?xml version="1.0" encoding="UTF-8"?>\n'));
+    sbuf=add(sbuf,sprintf('<kml xmlns="http://www.opengis.net/kml/2.2">\n'));
+end
+
+%  string write kml objects
+
+if ~isempty(filek)
+    display(sprintf('Writing to kml file ''%s'':',filek));
+else
+    display(sprintf('Writing to kml file id=%d:',fid));
+end
+for i=1:numel(kobj)
+    if isa(kobj{i},'kml_object')
+        display(sprintf('  Writing object %d of class ''%s'' and size %s.',...
+            i,class(kobj{i}),string_size(kobj{i})));
+        sbuf=kml_swrite(kobj{i},sbuf,indent);
+    else
+        if ~isempty(inputname(1))
+            warning('Object ''%s{%d}'' is a ''%s'' class object, not ''%s''.',...
+                inputname(1),i,class(kobj{i}),'kml_object');
+        else
+            warning('Object {%d} is a ''%s'' class object, not ''%s''.',...
+                             i,class(kobj{i}),'kml_object');
+        end
+    end
+end
+
+%  write trailer data and close file (if necessary)
+
+if ~nargout && (fid >= 3)
+    sbuf=add(sbuf,sprintf('</kml>\n'));
+    fprintf(fid,'%s',str(sbuf));
+
+    if (fclose(fid) < 0)
+        if ~isempty(filek)
+            error('File ''%s'' could not be closed.',filek);
+        else
+            error('File id=%d could not be closed.',fid);
+        end
+    else
+        if ~isempty(filek)
+            disp(['End of file ''' filek ''' successfully written.']);
+        else
+            disp(['End of file successfully written.']);
+        end
+    end
+
+else
+    fprintf(fid,'%s',str(sbuf));
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_file_write.m	(revision 18231)
@@ -0,0 +1,125 @@
+%
+%  write a kml file of the kml objects.
+%
+%  [fid]=kml_file_write(kobj,filek,indent)
+%
+%  where the required input is:
+%    kobj          (kml_object, kml object to be written)
+%     or
+%    kobj          (cell array, array of kml objects)
+%
+%  the optional input is:
+%    filek         (char, name of .kml file)
+%     or
+%    filek         (numeric, file ID of already-open file,
+%                            noting 1=stdout and 2=stderr)
+%    indent        (char, indention string)
+%
+%  and the optional output is:
+%    fid           (numeric, file ID of still-open file)
+%
+function [fid]=kml_file_write(kobj,filek,indent)
+
+if ~nargin
+    help kml_file_write
+    return
+end
+
+%%  process input data
+
+if ~iscell(kobj)
+    kobj={kobj};
+end
+
+fid=0;
+if ~exist('filek' ,'var') || (~ischar(filek) && ~isnumeric(filek))
+    filek='';
+elseif ischar(filek)
+    if     strcmpi(filek,'stdout')
+        fid=1;
+    elseif strcmpi(filek,'stderr')
+        fid=2;
+    end
+elseif isnumeric(filek)
+    fid=filek;
+    if     (fid == 1)
+        filek='stdout';
+    elseif (fid == 2)
+        filek='stderr';
+    else
+        filek='';
+    end
+end
+
+if ~exist('indent','var') || ~ischar(indent)
+    indent='  ';
+end
+
+%%  write kml file
+
+%  open file and write header data (if necessary)
+
+if ~fid
+    if isempty(filek)
+        filek=input('kml file to write?  ','s');
+    end
+    [pathstr,name,ext,versn] = fileparts(filek);
+    if isempty(ext)
+        ext='.kml';
+    end
+    filek=fullfile(pathstr,[name ext versn]);
+
+    display(sprintf('Opening kml file ''%s''.',filek));
+    fid=fopen(sprintf('%s',filek),'w');
+    if (fid < 0)
+        error('File ''%s'' could not be opened.',filek);
+    end
+
+    fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n');
+    fprintf(fid,'<kml xmlns="http://www.opengis.net/kml/2.2">\n');
+end
+
+%  write kml objects
+
+if ~isempty(filek)
+    display(sprintf('Writing to kml file ''%s'':',filek));
+else
+    display(sprintf('Writing to kml file id=%d:',fid));
+end
+for i=1:numel(kobj)
+    if isa(kobj{i},'kml_object')
+        display(sprintf('  Writing object %d of class ''%s'' and size %s.',...
+            i,class(kobj{i}),string_size(kobj{i})));
+        kml_write(kobj{i},fid,indent);
+    else
+        if ~isempty(inputname(1))
+            warning('Object ''%s{%d}'' is a ''%s'' class object, not ''%s''.',...
+                inputname(1),i,class(kobj{i}),'kml_object');
+        else
+            warning('Object {%d} is a ''%s'' class object, not ''%s''.',...
+                             i,class(kobj{i}),'kml_object');
+        end
+    end
+end
+
+%  write trailer data and close file (if necessary)
+
+if ~nargout && (fid >= 3)
+    fprintf(fid,'</kml>\n');
+
+    if (fclose(fid) < 0)
+        if ~isempty(filek)
+            error('File ''%s'' could not be closed.',filek);
+        else
+            error('File id=%d could not be closed.',fid);
+        end
+    else
+        if ~isempty(filek)
+            disp(['End of file ''' filek ''' successfully written.']);
+        else
+            disp(['End of file successfully written.']);
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_folder.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_folder.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_folder.m	(revision 18231)
@@ -0,0 +1,235 @@
+%
+%  definition for the kml_folder sub (derived) class.
+%
+%  [kml]=kml_folder(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, folder id, '')
+%    name          (char, name, '')
+%    visibility    (logical, visibility, true)
+%    open          (logical, open, false)
+%    snippet       (char, snippet, '')
+%    descript      (char, description, '')
+%    styleurl      (char, style url, '')
+%    style         (cell array, styles)
+%    feature       (cell array, placemark features)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_folder < kml_container
+    properties
+        feature   ={};
+    end
+
+    methods
+        function [kml]=kml_folder(varargin)
+
+            kml=kml@kml_container(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_folder());
+
+                        for i=length(fieldnames(kml_container()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_container(kml(i));
+                disp(sprintf('       feature: %s %s\n' ,string_size(kml(i).feature),...
+                             class(kml(i).feature)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_container());
+            fnames={fnames{:} ...
+                    'feature' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the folders
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<Folder id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<Folder>\n',indent);
+                end
+                kml_write@kml_container(kmli,fid,indent);
+
+%  loop over the features for each folder
+
+                for j=1:numel(kmli.feature)
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            kml_write(kmli.feature{j},fid,[indent '  ']);
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+
+                fprintf(fid,'%s</Folder>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the folders
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<Folder id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<Folder>\n',indent));
+                end
+                sbuf=kml_swrite@kml_container(kmli,sbuf,indent);
+
+%  loop over the features for each folder
+
+                for j=1:numel(kmli.feature)
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            sbuf=kml_swrite(kmli.feature{j},sbuf,[indent '  ']);
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+
+                sbuf=add(sbuf,sprintf('%s</Folder>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the folders
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+                delete@kml_container(kmli);
+
+%  loop over the features for each folder
+
+                for j=numel(kmli.feature):-1:1
+                    if ~isempty(kmli.feature{j})
+                        if isa(kmli.feature{j},'kml_feature')
+                            delete(kmli.feature{j});
+                        else
+                            warning('kml(%d).feature{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmli.feature{j}),'kml_feature');
+                        end
+                    end
+                end
+                kmli.feature   ={};
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_geometry.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_geometry.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_geometry.m	(revision 18231)
@@ -0,0 +1,178 @@
+%
+%  definition for the kml_geometry super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_geometry(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, geometry id, '')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_geometry < kml_object
+    properties
+    end
+
+    methods
+        function [kml]=kml_geometry(varargin)
+
+            kml=kml@kml_object(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_geometry());
+
+                        for i=length(fieldnames(kml_object()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_geometry')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_object(kml(i));
+                if strcmp(class(kml),'kml_geometry')
+                    disp(sprintf('\n'));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_object());
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the geometries
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_geometry')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!Geometry id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!Geometry>\n',indent);
+                    end
+                end
+                kml_write@kml_object(kmli,fid,indent);
+                if strcmp(class(kml),'kml_geometry')
+                    fprintf(fid,'%s</!Geometry>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the geometries
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_geometry')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!Geometry id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!Geometry>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_object(kmli,sbuf,indent);
+                if strcmp(class(kml),'kml_geometry')
+                    sbuf=add(sbuf,sprintf('%s</!Geometry>\n',indent));
+                end
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linearring.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linearring.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linearring.m	(revision 18231)
@@ -0,0 +1,208 @@
+%
+%  definition for the kml_linearring sub (derived) class.
+%
+%  [kml]=kml_linearring(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, linearring id, '')
+%    extrude       (logical, extrusion, false)
+%    tessellate    (logical, tessellation, false)
+%    altmode       (char, altitude mode, 'clampToGround')
+%    coords        (numeric, long/lat/alt (n x 3), empty)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_linearring < kml_geometry
+    properties
+        extrude   =false;
+        tessellate=false;
+        altmode   ='clampToGround';
+        coords    =zeros(0,3);
+    end
+
+    methods
+        function [kml]=kml_linearring(varargin)
+
+            kml=kml@kml_geometry(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_linearring());
+
+                        for i=length(fieldnames(kml_geometry()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_geometry(kml(i));
+                disp(sprintf('       extrude: %g'      ,kml(i).extrude));
+                disp(sprintf('    tessellate: %g'      ,kml(i).tessellate));
+                disp(sprintf('       altmode: ''%s'''  ,kml(i).altmode));
+                disp(sprintf('        coords: %s %s\n' ,string_size(kml(i).coords),...
+                             class(kml(i).coords)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_geometry());
+            fnames={fnames{:} ...
+                    'extrude' ...
+                    'tessellate' ...
+                    'altmode' ...
+                    'coords' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+            if ~exist('fid','var') || isempty(fid)
+                fid=1;
+            end
+            if ~exist('indent','var') || isempty(indent)
+                indent='';
+            end
+
+%  loop over the linearrings
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<LinearRing id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<LinearRing>\n',indent);
+                end
+                kml_write@kml_geometry(kmli,fid,indent);
+                fprintf(fid,'%s  <extrude>%d</extrude>\n',indent,kmli.extrude);
+                fprintf(fid,'%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate);
+                fprintf(fid,'%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode);
+                fprintf(fid,'%s  <coordinates>\n',indent);
+
+%  loop over the coordinates for each linearring
+
+                for j=1:size(kmli.coords,1)
+                    fprintf(fid,'%s    %0.16g,%0.16g,%0.16g\n',indent,kmli.coords(j,:));
+                end
+
+                fprintf(fid,'%s  </coordinates>\n',indent);
+                fprintf(fid,'%s</LinearRing>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+            if ~exist('sbuf','var') || isempty(sbuf)
+                sbuf=string_buf;
+            end
+            if ~exist('indent','var') || isempty(indent)
+                indent='';
+            end
+
+%  loop over the linearrings
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<LinearRing id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<LinearRing>\n',indent));
+                end
+                sbuf=kml_swrite@kml_geometry(kmli,sbuf,indent);
+                sbuf=add(sbuf,sprintf('%s  <extrude>%d</extrude>\n',indent,kmli.extrude));
+                sbuf=add(sbuf,sprintf('%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate));
+                sbuf=add(sbuf,sprintf('%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode));
+                sbuf=add(sbuf,sprintf('%s  <coordinates>\n',indent));
+
+%  loop over the coordinates for each linearring
+
+                for j=1:size(kmli.coords,1)
+                    sbuf=add(sbuf,sprintf('%s    %0.16g,%0.16g,%0.16g\n',indent,kmli.coords(j,:)));
+                end
+
+                sbuf=add(sbuf,sprintf('%s  </coordinates>\n',indent));
+                sbuf=add(sbuf,sprintf('%s</LinearRing>\n',indent));
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestring.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestring.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestring.m	(revision 18231)
@@ -0,0 +1,208 @@
+%
+%  definition for the kml_linestring sub (derived) class.
+%
+%  [kml]=kml_linestring(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, linestring id, '')
+%    extrude       (logical, extrusion, false)
+%    tessellate    (logical, tessellation, false)
+%    altmode       (char, altitude mode, 'clampToGround')
+%    coords        (numeric, long/lat/alt (n x 3), empty)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_linestring < kml_geometry
+    properties
+        extrude   =false;
+        tessellate=false;
+        altmode   ='clampToGround';
+        coords    =zeros(0,3);
+    end
+
+    methods
+        function [kml]=kml_linestring(varargin)
+
+            kml=kml@kml_geometry(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_linestring());
+
+                        for i=length(fieldnames(kml_geometry()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_geometry(kml(i));
+                disp(sprintf('       extrude: %g'      ,kml(i).extrude));
+                disp(sprintf('    tessellate: %g'      ,kml(i).tessellate));
+                disp(sprintf('       altmode: ''%s'''  ,kml(i).altmode));
+                disp(sprintf('        coords: %s %s\n' ,string_size(kml(i).coords),...
+                             class(kml(i).coords)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_geometry());
+            fnames={fnames{:} ...
+                    'extrude' ...
+                    'tessellate' ...
+                    'altmode' ...
+                    'coords' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+            if ~exist('fid','var') || isempty(fid)
+                fid=1;
+            end
+            if ~exist('indent','var') || isempty(indent)
+                indent='';
+            end
+
+%  loop over the linestrings
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<LineString id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<LineString>\n',indent);
+                end
+                kml_write@kml_geometry(kmli,fid,indent);
+                fprintf(fid,'%s  <extrude>%d</extrude>\n',indent,kmli.extrude);
+                fprintf(fid,'%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate);
+                fprintf(fid,'%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode);
+                fprintf(fid,'%s  <coordinates>\n',indent);
+
+%  loop over the coordinates for each linestring
+
+                for j=1:size(kmli.coords,1)
+                    fprintf(fid,'%s    %0.16g,%0.16g,%0.16g\n',indent,kmli.coords(j,:));
+                end
+
+                fprintf(fid,'%s  </coordinates>\n',indent);
+                fprintf(fid,'%s</LineString>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+            if ~exist('sbuf','var') || isempty(sbuf)
+                sbuf=string_buf;
+            end
+            if ~exist('indent','var') || isempty(indent)
+                indent='';
+            end
+
+%  loop over the linestrings
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<LineString id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<LineString>\n',indent));
+                end
+                sbuf=kml_swrite@kml_geometry(kmli,sbuf,indent);
+                sbuf=add(sbuf,sprintf('%s  <extrude>%d</extrude>\n',indent,kmli.extrude));
+                sbuf=add(sbuf,sprintf('%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate));
+                sbuf=add(sbuf,sprintf('%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode));
+                sbuf=add(sbuf,sprintf('%s  <coordinates>\n',indent));
+
+%  loop over the coordinates for each linestring
+
+                for j=1:size(kmli.coords,1)
+                    sbuf=add(sbuf,sprintf('%s    %0.16g,%0.16g,%0.16g\n',indent,kmli.coords(j,:)));
+                end
+
+                sbuf=add(sbuf,sprintf('%s  </coordinates>\n',indent));
+                sbuf=add(sbuf,sprintf('%s</LineString>\n',indent));
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestyle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestyle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_linestyle.m	(revision 18231)
@@ -0,0 +1,175 @@
+%
+%  definition for the kml_linestyle sub (derived) class.
+%
+%  [kml]=kml_linestyle(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, linestyle id, '')
+%    color         (char, opacity/color in hex aabbggrr, 'ffffffff')
+%    colormode     (char, color mode , 'normal')
+%    width         (numeric, line width (in pixels), 1)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_linestyle < kml_colorstyle
+    properties
+        width     =1;
+    end
+
+    methods
+        function [kml]=kml_linestyle(varargin)
+
+            kml=kml@kml_colorstyle(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_linestyle());
+
+                        for i=length(fieldnames(kml_colorstyle()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_colorstyle(kml(i));
+                disp(sprintf('         width: %d\n'    ,kml(i).width));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_colorstyle());
+            fnames={fnames{:} ...
+                    'width' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the linestyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<LineStyle id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<LineStyle>\n',indent);
+                end
+                kml_write@kml_colorstyle(kmli,fid,indent);
+                fprintf(fid,'%s  <width>%d</width>\n',indent,kmli.width);
+                fprintf(fid,'%s</LineStyle>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the linestyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<LineStyle id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<LineStyle>\n',indent));
+                end
+                sbuf=kml_swrite@kml_colorstyle(kmli,sbuf,indent);
+                sbuf=add(sbuf,sprintf('%s  <width>%d</width>\n',indent,kmli.width));
+                sbuf=add(sbuf,sprintf('%s</LineStyle>\n',indent));
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_elem.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_elem.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_elem.m	(revision 18231)
@@ -0,0 +1,176 @@
+%%
+%  create kml polygons for the element mesh.
+%
+%  [kfold]=kml_mesh_elem(md,params)
+%
+%  where the required input is:
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    data          (numeric, element or nodal results data)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    cmin          (numeric, minimum of color map)
+%    cmax          (numeric, maximum of color map)
+%    cmap          (char or numeric, colormap definition)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of polygon placemarks)
+%
+function [kfold]=kml_mesh_elem(varargin)
+
+if ~nargin
+    help kml_mesh_elem
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','data','alt',...
+                 'cmin','cmax','cmap'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    if strcmpi(varargin{iarg},'data')
+        cdata=inputname(iarg+1);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if exist('data','var') && ~isempty(data)
+    if     (numel(data)==md.mesh.numberofelements)
+        edata=data;
+    elseif (numel(data)==md.mesh.numberofvertices)
+        ndata=data;
+        display('Averaging nodal data to element data.');
+        edata=zeros(1,md.mesh.numberofelements);
+        for i=1:size(md.mesh.elements,1)
+            for j=1:size(md.mesh.elements,2)
+                edata(i)=edata(i)+ndata(md.mesh.elements(i,j));
+            end
+            edata(i)=edata(i)/size(md.mesh.elements,2);
+        end
+    else
+        error(['Data has incorrect number of ' num2str(numel(data)) ' values.']);
+    end
+end
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+hfig=figure('Visible','off');
+if exist('cmap','var')
+    colormap(cmap)
+end
+cmap=colormap;
+close(hfig)
+
+if exist('edata','var')
+    if ~exist('cmin','var')
+        cmin=min(min(edata));
+    end
+    if ~exist('cmax','var')
+        cmax=max(max(edata));
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  write folder for mesh
+
+kfold=kml_folder();
+if exist('cdata','var') && ~isempty(cdata)
+    kfold.name      =sprintf('Data: %s',cdata);
+else
+    kfold.name      =sprintf('Mesh');
+end
+kfold.visibility=1;
+kfold.descript  =sprintf('Elements=%d, Nodes=%d',...
+    md.mesh.numberofelements,md.mesh.numberofvertices);
+% see matlab_oop, "initializing a handle object array"
+%kfold.feature   ={repmat(kml_placemark(),1,size(md.mesh.elements,1))};
+kfeat(size(md.mesh.elements,1))=kml_placemark();
+kfold.feature={kfeat};
+
+%  write each element as a polygon placemark
+
+disp(['Writing ' num2str(size(md.mesh.elements,1)) ' tria elements as KML polygons.']);
+for i=1:size(md.mesh.elements,1)
+    kplace=kml_placemark();
+    kplace.name      =sprintf('Element %d',i);
+    kplace.visibility=1;
+    if exist('edata','var')
+%        kplace.descript  =sprintf('Element data: %g',edata(i));
+        kplace.descript  =sprintf('campaign{\n  deformation 1 %g quad_pol ascending right asap;\n}',edata(i));
+        imap = fix((edata(i)-cmin)/(cmax-cmin)*size(cmap,1))+1;
+        if     (imap >= 1) && (imap <= size(cmap,1))
+            kplace.styleurl  =sprintf('#MatlabColor%d',imap);
+        elseif (edata(i) == cmax)
+            kplace.styleurl  =sprintf('#MatlabColor%d',size(cmap,1));
+        else
+            kplace.styleurl  =sprintf('#BlackLineEmptyPoly');
+        end
+    else
+        kplace.styleurl  =sprintf('#BlackLineRandomPoly');
+    end
+
+    kpoly=kml_polygon();
+    kpoly.extrude   =1;
+    kpoly.altmode   ='relativeToGround';
+
+    kring=kml_linearring();
+    kring.coords    =zeros(size(md.mesh.elements,2)+1,3);
+
+    for j=1:size(md.mesh.elements,2)
+        kring.coords(j,:)=[md.mesh.long(md.mesh.elements(i,j)) md.mesh.lat(md.mesh.elements(i,j)) alt];
+    end
+    kring.coords(end,:)=kring.coords(1,:);
+
+    kpoly.outer=kring;
+    kplace.geometry=kpoly;
+    kfold.feature{1}(i)=kplace;
+    clear kring kpoly kplace
+
+    if ~mod(i,1000)
+        disp(['  ' num2str(i) ' tria elements written.']);
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_mesh_write.m	(revision 18231)
@@ -0,0 +1,260 @@
+%%
+%  write a kml file of the mesh from the model.
+%
+%  []=kml_mesh_write(filek,md,params)
+%
+%  where the required input is:
+%    filek         (char, name of .kml file)
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    data          (numeric, element or nodal results data)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    lwidth        (numeric, line width in pixels, default 1)
+%    popac         (numeric, polygon opacity, default 0.50)
+%    cmin          (numeric, minimum of color map)
+%    cmax          (numeric, maximum of color map)
+%    cmap          (char or numeric, colormap definition)
+%    prtplt        (char, 'off'/'no' for partition segment plot)
+%
+function []=kml_mesh_write(varargin)
+
+if ~nargin
+    help kml_mesh_write
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    filek=varargin{1};
+end
+
+iarg=iarg+1;
+if (nargin >= 2)
+    md=varargin{2};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','data','alt','lwidth','popac',...
+                 'cmin','cmax','cmap','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    if strcmpi(varargin{iarg},'data')
+        cdata=inputname(iarg+1);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if exist('data','var') && ~isempty(data)
+    if     (numel(data)==md.mesh.numberofelements)
+        edata=data;
+    elseif (numel(data)==md.mesh.numberofvertices)
+        ndata=data;
+        display('Averaging nodal data to element data.');
+        edata=zeros(1,md.mesh.numberofelements);
+        for i=1:size(md.mesh.elements,1)
+            for j=1:size(md.mesh.elements,2)
+                edata(i)=edata(i)+ndata(md.mesh.elements(i,j));
+            end
+            edata(i)=edata(i)/size(md.mesh.elements,2);
+        end
+    else
+        error(['Data has incorrect number of ' num2str(numel(data)) ' values.']);
+    end
+end
+
+if exist('edata','var')
+    if ~exist('cmin','var')
+        cmin=min(min(edata));
+    end
+    if ~exist('cmax','var')
+        cmax=max(max(edata));
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  construct kml document
+
+kdoc=kml_document();
+kdoc.name      =sprintf('ISSM Mesh: %s',md.miscellaneous.name);
+kdoc.open      =1;
+ifirst=true;
+for i=1:numel(md.miscellaneous.notes)
+    if ~isempty(md.miscellaneous.notes{i})
+        if ~ifirst
+            kdoc.descript  =[kdoc.descript sprintf('\n')];
+        end
+        ifirst=false;
+        kdoc.descript  =[kdoc.descript sprintf('%s',md.miscellaneous.notes{i})];
+    end
+end
+clear ifirst
+kdoc.style     ={repmat(kml_style(),0,0)};
+kdoc.feature   ={repmat(kml_folder(),0,0)};
+
+%  write style templates for defaults and for each color of the matlab
+%  colormap (note that matlab colormap format is rgb, where each varies
+%  from 0 to 1, whereas the kml color format is aabbggrr, where each
+%  varies from 00 to ff.)
+
+if ~exist('lwidth','var')
+    lwidth=1;
+end
+if ~exist('popac','var')
+    popac=0.50;
+end
+
+klsty=kml_linestyle();
+klsty.color     ='ff000000';
+klsty.colormode ='normal';
+klsty.width     =lwidth;
+kpsty=kml_polystyle();
+kpsty.color     =sprintf('%02xffffff',round(popac*255));
+kpsty.colormode ='random';
+kstyle=kml_style();
+kstyle.id        =sprintf('BlackLineRandomPoly');
+kstyle.line      =klsty;
+kstyle.poly      =kpsty;
+kdoc.style{1}(end+1)=kstyle;
+clear kstyle kpsty klsty
+
+klsty=kml_linestyle();
+klsty.color     ='ff000000';
+klsty.colormode ='normal';
+klsty.width     =lwidth;
+kpsty=kml_polystyle();
+kpsty.color     =sprintf('00ffffff');
+kpsty.colormode ='random';
+kstyle=kml_style();
+kstyle.id        =sprintf('BlackLineEmptyPoly');
+kstyle.line      =klsty;
+kstyle.poly      =kpsty;
+kdoc.style{1}(end+1)=kstyle;
+clear kstyle kpsty klsty
+
+klsty=kml_linestyle();
+klsty.color     ='ff0000ff';
+klsty.colormode ='normal';
+klsty.width     =lwidth;
+kpsty=kml_polystyle();
+kpsty.color     =sprintf('%02x0000ff',round(popac*255));
+kpsty.colormode ='random';
+kstyle=kml_style();
+kstyle.id        =sprintf('RedLineRedPoly');
+kstyle.line      =klsty;
+kstyle.poly      =kpsty;
+kdoc.style{1}(end+1)=kstyle;
+clear kstyle kpsty klsty
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+if exist('edata','var')
+    hfig=figure('Visible','off');
+    if exist('cmap','var')
+        colormap(cmap)
+    end
+    cmap=colormap;
+    close(hfig)
+
+    disp(['Writing ' num2str(size(cmap,1)) ' Matlab colors as KML style templates.']);
+    for i=1:size(cmap,1)
+        klsty=kml_linestyle();
+        klsty.color     ='ff000000';
+        klsty.colormode ='normal';
+        klsty.width     =lwidth;
+        kpsty=kml_polystyle();
+        kpsty.color     =sprintf('%02x%02x%02x%02x',round(popac*255),...
+            round(cmap(i,3)*255),round(cmap(i,2)*255),round(cmap(i,1)*255));
+        kpsty.colormode ='normal';
+        kstyle=kml_style();
+        kstyle.id        =sprintf('MatlabColor%d',i);
+        kstyle.line      =klsty;
+        kstyle.poly      =kpsty;
+        kdoc.style{1}(end+1)=kstyle;
+        clear kstyle kpsty klsty
+    end
+end
+
+%  write folder for mesh
+
+kdoc.feature{1}(end+1)=kml_mesh_elem(md,varargin{3:end});
+
+%  write folder for partition segments
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kdoc.feature{1}(end+1)=kml_part_flagedges(md,varargin{3:end});
+end
+
+%  write folder for unshared edges
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kdoc.feature{1}(end+1)=kml_unsh_edges(md,varargin{3:end});
+end
+
+%  write folder for partition elements
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kdoc.feature{1}(end+1)=kml_part_elems(md,varargin{3:end});
+end
+
+%  write folder for partition edges
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kdoc.feature{1}(end+1)=kml_part_edges(md,varargin{3:end});
+end
+
+%  write folder for partitions
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kdoc.feature{1}(end+1)=kml_partitions(md,varargin{3:end});
+end
+
+%%  write kml file
+
+kml_file_write(kdoc,filek);
+% kml_file_swrite(kdoc,filek);
+delete(kdoc);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_multigeometry.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_multigeometry.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_multigeometry.m	(revision 18231)
@@ -0,0 +1,230 @@
+%
+%  definition for the kml_multigeometry sub (derived) class.
+%
+%  [kml]=kml_multigeometry(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, multigeometry id, '')
+%    geometry      (cell array, multigeometry geometry)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_multigeometry < kml_geometry
+    properties
+        geometry  ={};
+    end
+
+    methods
+        function [kml]=kml_multigeometry(varargin)
+
+            kml=kml@kml_geometry(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_multigeometry());
+
+                        for i=length(fieldnames(kml_geometry()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_geometry(kml(i));
+                disp(sprintf('      geometry: %s %s\n' ,string_size(kml(i).geometry),...
+                             class(kml(i).geometry)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_geometry());
+            fnames={fnames{:} ...
+                    'geometry' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the multigeometry
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<MultiGeometry id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<MultiGeometry>\n',indent);
+                end
+                kml_write@kml_geometry(kmli,fid,indent);
+
+%  loop over the geometry elements for each multigeometry
+
+                for j=1:numel(kmli.geometry)
+                    kmlij=kmli.geometry{j};
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            kml_write(kmlij,fid,[indent '  ']);
+                        else
+                            warning('kml(%d).geometry{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+
+                fprintf(fid,'%s</MultiGeometry>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the multigeometry
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<MultiGeometry id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<MultiGeometry>\n',indent));
+                end
+                sbuf=kml_swrite@kml_geometry(kmli,sbuf,indent);
+
+%  loop over the geometry elements for each multigeometry
+
+                for j=1:numel(kmli.geometry)
+                    kmlij=kmli.geometry{j};
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            sbuf=kml_swrite(kmlij,sbuf,[indent '  ']);
+                        else
+                            warning('kml(%d).geometry{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+
+                sbuf=add(sbuf,sprintf('%s</MultiGeometry>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the multigeometry
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+
+%  loop over the geometry elements for each multigeometry
+
+                for j=numel(kmli.geometry):-1:1
+                    kmlij=kmli.geometry{j};
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            delete(kmlij);
+                        else
+                            warning('kml(%d).geometry{%d} is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+                kmli.geometry  ={};
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_object.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_object.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_object.m	(revision 18231)
@@ -0,0 +1,179 @@
+%
+%  definition for the kml_object super (base) abstract class.
+%
+%  [kml]=kml_object(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, object id, '')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_object < handle
+    properties
+        id        ='';
+    end
+
+    methods
+        function [kml]=kml_object(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_object());
+
+                        for i=1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_object')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+
+                if strcmp(class(kml),'kml_object')
+                    disp(sprintf('            id: ''%s''\n',kml(i).id));
+                else
+                    disp(sprintf('            id: ''%s'''  ,kml(i).id));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames={'id'};
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the objects
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_object')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!Object id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!Object>\n',indent);
+                    end
+                end
+
+                if strcmp(class(kml),'kml_object')
+                    fprintf(fid,'%s</!Object>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the objects
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_object')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!Object id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!Object>\n',indent));
+                    end
+                end
+
+                if strcmp(class(kml),'kml_object')
+                    sbuf=add(sbuf,sprintf('%s</!Object>\n',indent));
+                end
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_edges.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_edges.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_edges.m	(revision 18231)
@@ -0,0 +1,482 @@
+%%
+%  create kml linestrings for the partition edges.
+%
+%  [kfold]=kml_part_edges(md,params)
+%
+%  where the required input is:
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    data          (numeric, element or nodal results data)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    cmin          (numeric, minimum of color map)
+%    cmax          (numeric, maximum of color map)
+%    cmap          (char or numeric, colormap definition)
+%    prtplt        (char, 'off'/'no' for partition segment plot)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of linestring placemarks)
+%
+function [kfold]=kml_part_edges(varargin)
+
+if ~nargin
+    help kml_part_edges
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','data','alt',...
+                 'cmin','cmax','cmap','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    if strcmpi(varargin{iarg},'data')
+        cdata=inputname(iarg+1);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if exist('data','var') && ~isempty(data)
+    if     (numel(data)==md.mesh.numberofelements)
+        edata=data;
+    elseif (numel(data)==md.mesh.numberofvertices)
+        ndata=data;
+        display('Averaging nodal data to element data.');
+        edata=zeros(1,md.mesh.numberofelements);
+        for i=1:size(md.mesh.elements,1)
+            for j=1:size(md.mesh.elements,2)
+                edata(i)=edata(i)+ndata(md.mesh.elements(i,j));
+            end
+            edata(i)=edata(i)/size(md.mesh.elements,2);
+        end
+    else
+        error(['Data has incorrect number of ' num2str(numel(data)) ' values.']);
+    end
+end
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+hfig=figure('Visible','off');
+if exist('cmap','var')
+    colormap(cmap)
+end
+cmap=colormap;
+close(hfig)
+
+if exist('edata','var')
+    if ~exist('cmin','var')
+        cmin=min(min(edata));
+    end
+    if ~exist('cmax','var')
+        cmax=max(max(edata));
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  write folder for partition edges
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kfold=kml_folder();
+    kfold.name      ='Partition Edges';
+    kfold.visibility=1;
+    kfold.descript  =sprintf('Partitions=%d, Nodes=%d',...
+        md.qmu.numberofpartitions,md.mesh.numberofvertices);
+    kfold.feature   ={repmat(kml_placemark(),1,md.qmu.numberofpartitions)};
+
+%  write each partition as a linestring multigeometry placemark
+
+    disp(['Writing ' num2str(md.qmu.numberofpartitions) ' partitions as KML linestrings.']);
+    epart=md.qmu.partition(md.mesh.elements)+1;
+    if exist('ndata','var') || exist('edata','var')
+        pdata=zeros(1,md.qmu.numberofpartitions);
+        pdata(:)=NaN;
+    end
+
+%  loop over each partition
+
+    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)
+
+        [icol,irow]=find(epart'==k);
+        if isempty(irow)
+            continue;
+        end
+        irow=unique(irow);
+        elemp=md.mesh.elements(irow,:);
+        epartp=epart(irow,:);
+        nodeconp=kmlnodeconnectivity(elemp,md.mesh.numberofvertices);
+        [edgeadjp]=edgeadjacency(elemp,nodeconp);
+        [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)
+
+        if exist('ndata','var')
+            pdata(k)=ndata(find(md.qmu.partition+1==k,1));
+        elseif exist('edata','var')
+            for i=1:size(epartp,1)
+                if isempty(find(epart(i,:)~=k,1))
+                    pdata(k)=edata(irow(i));
+                    break
+                end
+            end
+            if isnan(pdata(k))
+                warning('Data for Partition %d is not defined.\n',k)
+            end
+        end
+
+%  set up the placemark with multigeometry
+
+        kplace=kml_placemark();
+        if (length(iloop)-1 > 1)
+            kplace.name      =sprintf('Partition %d (%d loops)',k,length(iloop)-1);
+        else
+            kplace.name      =sprintf('Partition %d',k);
+        end
+        kplace.visibility=1;
+        if exist('pdata','var')
+            kplace.descript  =sprintf('Partition data: %g',pdata(k));
+            imap = fix((pdata(k)-cmin)/(cmax-cmin)*size(cmap,1))+1;
+            if     (imap >= 1) && (imap <= size(cmap,1))
+                kplace.styleurl  =sprintf('#MatlabColor%d',imap);
+            elseif (pdata(k) == cmax)
+                kplace.styleurl  =sprintf('#MatlabColor%d',size(cmap,1));
+            else
+                kplace.styleurl  =sprintf('#BlackLineEmptyPoly');
+            end
+        else
+            kplace.styleurl  =sprintf('#BlackLineRandomPoly');
+        end
+
+        kmgeom=kml_multigeometry();
+        kmgeom.geometry  ={repmat(kml_linestring(),1,length(iloop)-1)};
+
+%  loop over each loop of the perimeter for the given partition
+
+        for i=1:length(iloop)-1
+            kline=kml_linestring();
+            kline.extrude   =1;
+            kline.tessellate=1;
+            kline.altmode   ='relativeToGround';
+            kline.coords    =zeros(0,3);
+
+            elast=0;
+            nlast=0;
+            slast=0;
+            lat=[];
+            long=[];
+
+%  loop over the element edges on the loop of the partition
+
+            j=iloop(i);
+            while (j < iloop(i+1))
+%  find which side of element is referenced in perimeter list
+                for l=1:size(elemp,2)
+                    if ((elemp(elemper(j),l)          == edgeper(j,1)) && ...
+                        (elemp(elemper(j),mod(l,3)+1) == edgeper(j,2))) || ...
+                       ((elemp(elemper(j),l)          == edgeper(j,2)) && ...
+                        (elemp(elemper(j),mod(l,3)+1) == edgeper(j,1)))
+                        jedge=l;
+                        break
+                    end
+                end
+
+%  check if element side connects nodes in partition
+                if (epartp(elemper(j),jedge)          == k) && ...
+                   (epartp(elemper(j),mod(jedge,3)+1) == k)
+%  write out specified element side
+%                    disp(['segment j=' int2str(j) ' unshared edge ' int2str(edgeper(j,1)) ' to ' int2str(edgeper(j,2)) ' on side ' int2str(jedge) ' from element ' int2str(elemper(j)) ' written.'])
+%  if first edge, write out first node
+                    if ~elast
+                        kline.coords(end+1,:)=[md.mesh.long(edgeper(j,1)) md.mesh.lat(edgeper(j,1)) alt];
+                    end
+                    kline.coords(end+1,:)=[md.mesh.long(edgeper(j,2)) md.mesh.lat(edgeper(j,2)) alt];
+                    elast=elemper(j);
+                    nlast=edgeper(j,2);
+                    slast=0;
+                    j=j+1;
+
+%  element not entirely within partition, so figure out boundary
+                else
+%                    disp(['segment j=' int2str(j) ' from element ' int2str(elemper(j)) ' shared by other partitions.'])
+                    ielem=elemper(j);
+
+%  follow partition boundary through elements not wholly in partition
+%  (may include elements not in perimeter list)
+
+                    while 1
+%  if first edge, figure out direction from perimeter edge direction
+                        if ~nlast && ~slast
+                            nlast=find(elemp(ielem,:)==edgeper(j,1));
+                            nnext=find(elemp(ielem,:)==edgeper(j,2));
+                            if     (nlast+nnext == 3)
+                                slast=1;
+                            elseif (nlast+nnext == 5)
+                                slast=2;
+                            elseif (nlast+nnext == 4)
+                                slast=3;
+                            end
+                            if     (nnext+(6-nlast-nnext) == 3)
+                                snext=1;
+                            elseif (nnext+(6-nlast-nnext) == 5)
+                                snext=2;
+                            elseif (nnext+(6-nlast-nnext) == 4)
+                                snext=3;
+                            end
+
+%  find how many nodes of current element are in current partition
+%  (1 or 2, not 3) and handle each permutation separately
+                            ipart=find(epartp(ielem,:)==k);
+%  two nodes are in current partition, so cut off other node
+                            if (length(ipart) == 2)
+                                switch 6-sum(ipart)
+                                    case nlast
+                                        slast=6-slast-snext;
+                                        nlast=0;
+                                    case nnext
+                                        if (epartp(ielem,nnext) == k)
+                                            nlast=nnext;
+                                        end
+                                    otherwise
+                                        slast=6-slast-snext;
+                                        nlast=0;
+                                end
+%  one node is in current partition
+                            else
+%  all different, so cut through centroid
+                                if (epartp(ielem,1) ~= epartp(ielem,2)) && ...
+                                   (epartp(ielem,2) ~= epartp(ielem,3)) && ...
+                                   (epartp(ielem,3) ~= epartp(ielem,1))
+                                    switch ipart
+                                        case {nlast,nnext}
+                                            if (epartp(ielem,nnext) == k)
+                                                nlast=nnext;
+                                            end
+                                        otherwise
+                                            slast=6-slast-snext;
+                                            nlast=0;
+                                    end
+%  other two are in the same partition, so cut them off
+                                else
+                                    switch ipart
+                                        case nlast
+                                            if (epartp(ielem,nnext) == k)
+                                                nlast=nnext;
+                                            end
+                                        case nnext
+                                            slast=snext;
+                                            nlast=0;
+                                        otherwise
+                                            slast=6-slast-snext;
+                                            nlast=0;
+                                    end
+                                end
+                            end
+
+%  last edge exited last element at node
+                            if nlast
+%  write out first node of first side for half-edge to midpoint
+%                                disp(['segment j=' int2str(j) ' unshared half edge from node ' int2str(elemp(ielem,nlast)) ' (node ' int2str(nlast) ') on side ' int2str(slast) ' from element ' int2str(ielem) ' written.'])
+                                kline.coords(end+1,:)=[md.mesh.long(elemp(ielem,nlast)) ...
+                                                       md.mesh.lat(elemp(ielem,nlast)) alt];
+                            end
+                            nlast=0;
+
+%  write out midpoint of first side
+                            kline.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
+                                                   +md.mesh.long(elemp(ielem,mod(slast,3)+1)))/2. ...
+                                                   (md.mesh.lat(elemp(ielem,slast))...
+                                                   +md.mesh.lat(elemp(ielem,mod(slast,3)+1)))/2. alt];
+                        end
+
+%  last edge exited last element at node
+                        if nlast
+                            if elast
+%  find where last node on previous element occurs on current element
+                                nlast=find(elemp(ielem,:)==nlast,1);
+                            end
+%  half-edge occurs on unshared side from current node (unique unless mesh
+%  is only attached at node)
+                            switch nlast
+                                case 1
+                                    if ~edgeadjp(ielem,1)
+                                        nnext=2;
+                                        slast=1;
+                                    else
+                                        nnext=3;
+                                        slast=3;
+                                    end
+                                case 2
+                                    if ~edgeadjp(ielem,2)
+                                        nnext=3;
+                                        slast=2;
+                                    else
+                                        nnext=1;
+                                        slast=1;
+                                    end
+                                case 3
+                                    if ~edgeadjp(ielem,3)
+                                        nnext=1;
+                                        slast=3;
+                                    else
+                                        nnext=2;
+                                        slast=2;
+                                    end
+                            end
+%  write out half-edge from current node to midpoint of unshared side
+%                            disp(['segment j=' int2str(j) ' unshared half edge from node ' int2str(elemp(ielem,nlast)) ' (node ' int2str(nlast) ') on side ' int2str(slast) ' from element ' int2str(ielem) ' written.'])
+                            kline.coords(end+1,:)=[(md.mesh.long(elemp(ielem,nlast))...
+                                                   +md.mesh.long(elemp(ielem,nnext)))/2. ...
+                                                   (md.mesh.lat(elemp(ielem,nlast))...
+                                                   +md.mesh.lat(elemp(ielem,nnext)))/2. alt];
+                            nlast=0;
+
+%  last edge exited last element at midpoint of side
+                        elseif slast
+                            if elast
+%  find where last side on previous element occurs on current element
+                                slast=find(edgeadjp(ielem,:)==elast,1);
+                            end
+                        end
+
+%  find how many nodes of current element are in current partition
+%  (1 or 2, not 3) and handle each permutation separately
+                        ipart=find(epartp(ielem,:)==k);
+                        if (length(ipart) == 2)
+%  two nodes are in current partition, so cut off other node
+                            switch 6-sum(ipart)
+                                case 1
+                                    snext=3+1-slast;
+                                case 2
+                                    snext=1+2-slast;
+                                case 3
+                                    snext=2+3-slast;
+                            end
+                        else
+                            if (epartp(ielem,1) ~= epartp(ielem,2)) && ...
+                               (epartp(ielem,2) ~= epartp(ielem,3)) && ...
+                               (epartp(ielem,3) ~= epartp(ielem,1))
+%  all different, so cut through centroid
+%                                disp(['element ielem=' int2str(ielem) ' centroid written.'])
+                                kline.coords(end+1,:)=[sum(md.mesh.long(elemp(ielem,:)))/3. ...
+                                                       sum(md.mesh.lat(elemp(ielem,:)))/3. alt];
+                            end
+%  one node is in current partition, so cut off other two nodes
+                            switch ipart
+                                case 1
+                                    snext=3+1-slast;
+                                case 2
+                                    snext=1+2-slast;
+                                case 3
+                                    snext=2+3-slast;
+                            end
+                        end
+%  write out midpoint of opposite side
+%                        disp(['segment j=' int2str(j) ' internal edge from side ' int2str(slast) ' to side ' int2str(snext) ' from element ' int2str(ielem) ' written.'])
+                        kline.coords(end+1,:)=[(md.mesh.long(elemp(ielem,snext))...
+                                               +md.mesh.long(elemp(ielem,mod(snext,3)+1)))/2. ...
+                                               (md.mesh.lat(elemp(ielem,snext))...
+                                               +md.mesh.lat(elemp(ielem,mod(snext,3)+1)))/2. alt];
+                        elast=ielem;
+                        nlast=0;
+                        slast=snext;
+%  find adjacent element to opposite side
+                        ielem=edgeadjp(elast,slast);
+%  if opposite side is unshared, find it in edge perimeter list
+                        if ~ielem
+                            jlast=find(elemper(j:end)==elast)+j-1;
+                            j=0;
+                            for l=1:length(jlast)
+                                if ((elemp(elast,slast)          == edgeper(jlast(l),1)) && ...
+                                    (elemp(elast,mod(slast,3)+1) == edgeper(jlast(l),2))) || ...
+                                   ((elemp(elast,slast)          == edgeper(jlast(l),2)) && ...
+                                    (elemp(elast,mod(slast,3)+1) == edgeper(jlast(l),1)))
+                                    j=jlast(l);
+                                    break
+                                end
+                            end
+                            if ~j
+                                j=iloop(i+1)-1;
+                            end
+%  write out half-edge from midpoint of unshared side to node
+                            if (epartp(elast,slast) == k)
+                                nnext=slast;
+                            else
+                                nnext=mod(slast,3)+1;
+                            end
+%                            disp(['segment j=' int2str(j) ' unshared half edge on side ' int2str(slast) ' to node ' int2str(elemp(elast,nnext)) ' (node ' int2str(nnext) ') from element ' int2str(elast) ' written.'])
+                            kline.coords(end+1,:)=[md.mesh.long(elemp(elast,nnext)) ...
+                                                   md.mesh.lat(elemp(elast,nnext)) alt];
+                            break
+%  if not unshared, advance perimeter list and watch for end
+                        else
+                            if (elast == elemper(j))
+                                if (j+1 < iloop(i+1)) && ...
+                                   ~isempty(find(elemper(j+1:end)~=elast,1))
+                                    j=j+find(elemper(j+1:end)~=elast,1);
+                                else
+                                    break
+                                end
+                            end
+                        end
+                    end
+                    j=j+1;
+                end
+            end
+
+            kmgeom.geometry{1}(i)=kline;
+            clear kline
+        end
+
+        kplace.geometry=kmgeom;
+        kfold.feature{1}(k)=kplace;
+        clear kmgeom kplace
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_elems.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_elems.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_elems.m	(revision 18231)
@@ -0,0 +1,216 @@
+%%
+%  create kml polygons for the partition elements.
+%
+%  [kfold]=kml_part_elems(md,params)
+%
+%  where the required input is:
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    data          (numeric, element or nodal results data)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    cmin          (numeric, minimum of color map)
+%    cmax          (numeric, maximum of color map)
+%    cmap          (char or numeric, colormap definition)
+%    prtplt        (char, 'off'/'no' for partition segment plot)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of polygon placemarks)
+%
+function [kfold]=kml_part_elems(varargin)
+
+if ~nargin
+    help kml_part_elems
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','data','alt',...
+                 'cmin','cmax','cmap','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    if strcmpi(varargin{iarg},'data')
+        cdata=inputname(iarg+1);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if exist('data','var') && ~isempty(data)
+    if     (numel(data)==md.mesh.numberofelements)
+        edata=data;
+    elseif (numel(data)==md.mesh.numberofvertices)
+        ndata=data;
+        display('Averaging nodal data to element data.');
+        edata=zeros(1,md.mesh.numberofelements);
+        for i=1:size(md.mesh.elements,1)
+            for j=1:size(md.mesh.elements,2)
+                edata(i)=edata(i)+ndata(md.mesh.elements(i,j));
+            end
+            edata(i)=edata(i)/size(md.mesh.elements,2);
+        end
+    else
+        error(['Data has incorrect number of ' num2str(numel(data)) ' values.']);
+    end
+end
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+hfig=figure('Visible','off');
+if exist('cmap','var')
+    colormap(cmap)
+end
+cmap=colormap;
+close(hfig)
+
+if exist('edata','var')
+    if ~exist('cmin','var')
+        cmin=min(min(edata));
+    end
+    if ~exist('cmax','var')
+        cmax=max(max(edata));
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%  write folder for partition elements
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kfold=kml_folder();
+    kfold.name      ='Partition Elements';
+    kfold.visibility=1;
+    kfold.descript  =sprintf('Partitions=%d, Nodes=%d\n',...
+        md.qmu.numberofpartitions,md.mesh.numberofvertices);
+    kfold.feature   ={repmat(kml_placemark(),1,md.qmu.numberofpartitions)};
+
+%  write each partition loop as a polygon multigeometry placemark
+
+    disp(['Writing ' num2str(md.qmu.numberofpartitions) ' partitions as KML polygons.']);
+    epart=md.qmu.partition(md.mesh.elements)+1;
+    if exist('ndata','var') || exist('edata','var')
+        pdata=zeros(1,md.qmu.numberofpartitions);
+        pdata(:)=NaN;
+    end
+
+%  loop over each partition
+
+    for k=1:md.qmu.numberofpartitions
+
+%  for each partition, find all the included elements
+
+        [icol,irow]=find(epart'==k);
+        if isempty(irow)
+            continue;
+        end
+        irow=unique(irow);
+        elem=md.mesh.elements(irow,:);
+
+%  determine the data to be used for the colors (if any)
+
+        if exist('ndata','var')
+            pdata(k)=ndata(find(md.qmu.partition+1==k,1));
+        elseif exist('edata','var')
+            for i=1:size(epart,1)
+                if isempty(find(epart(i,:)~=k,1))
+                    pdata(k)=edata(i);
+                    break
+                end
+            end
+            if isnan(pdata(k))
+                warning('Data for Partition %d is not defined.\n',k)
+            end
+        end
+
+%  set up the placemark with multigeometry
+
+        kplace=kml_placemark();
+        kplace.name      =sprintf('Partition %d (%d elements)',k,size(elem,1));
+        kplace.visibility=1;
+        if exist('pdata','var')
+            kplace.descript  =sprintf('Partition data: %g',pdata(k));
+            imap = fix((pdata(k)-cmin)/(cmax-cmin)*size(cmap,1))+1;
+            if     (imap >= 1) && (imap <= size(cmap,1))
+                kplace.styleurl  =sprintf('#MatlabColor%d',imap);
+            elseif (pdata(k) == cmax)
+                kplace.styleurl  =sprintf('#MatlabColor%d',size(cmap,1));
+            else
+                kplace.styleurl  =sprintf('#BlackLineEmptyPoly');
+            end
+        else
+            kplace.styleurl  =sprintf('#BlackLineRandomPoly');
+        end
+
+        kmgeom=kml_multigeometry();
+        kmgeom.geometry  ={repmat(kml_polygon(),1,size(elem,1))};
+
+%  loop over each element for the given partition
+
+        for i=1:size(elem,1)
+            kpoly=kml_polygon();
+            kpoly.extrude   =1;
+            kpoly.altmode   ='relativeToGround';
+
+            kring=kml_linearring();
+            kring.coords    =zeros(size(elem,2)+1,3);
+
+%  loop over the element nodes
+
+            for j=1:size(elem,2)
+                kring.coords(j,:)=[md.mesh.long(elem(i,j)) md.mesh.lat(elem(i,j)) alt];
+            end
+            kring.coords(end,:)=kring.coords(1,:);
+
+            kpoly.outer=kring;
+            kmgeom.geometry{1}(i)=kpoly;
+            clear kring kpoly
+        end
+
+        kplace.geometry=kmgeom;
+        kfold.feature{1}(k)=kplace;
+        clear kmgeom kplace
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_flagedges.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_flagedges.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_part_flagedges.m	(revision 18231)
@@ -0,0 +1,109 @@
+%%
+%  create kml linestrings for the flagged partition edges.
+%
+%  [kfold]=kml_part_flagedges(md,params)
+%
+%  where the required input is:
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    prtplt        (char, 'off'/'no' for partition edge plot)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of linestring placemarks)
+%
+function [kfold]=kml_part_flagedges(varargin)
+
+if ~nargin
+    help kml_part_flagedges
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','alt','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  write folder for partition segments
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    [latseg,lonseg]=flagedges(md.mesh.elements,md.mesh.lat,md.mesh.long,md.qmu.partition);
+    kfold=kml_folder();
+    kfold.name      ='Partition Segments';
+    kfold.visibility=1;
+    kfold.descript  =sprintf('Partitions=%d, Segments=%d',...
+        md.qmu.numberofpartitions,size(latseg,1));
+    kfold.feature   ={repmat(kml_placemark(),1,size(latseg,1))};
+
+%  write each segment as a linestring placemark
+
+    disp(['Writing ' num2str(size(latseg,1)) ' partition segments as KML linestrings.']);
+    for i=1:size(latseg,1)
+        kplace=kml_placemark();
+        kplace.name      =sprintf('Segment %d',i);
+        kplace.visibility=1;
+        kplace.styleurl  ='#RedLineRedPoly';
+
+        kline=kml_linestring();
+        kline.extrude   =1;
+        kline.tessellate=1;
+        kline.altmode   ='relativeToGround';
+        kline.coords    =zeros(2,3);
+
+        for j=1:2
+            kline.coords(j,:)=[lonseg(i,j) latseg(i,j) alt];
+        end
+
+        kplace.geometry=kline;
+        kfold.feature{1}(i)=kplace;
+        clear kline kplace
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_partitions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_partitions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_partitions.m	(revision 18231)
@@ -0,0 +1,485 @@
+%%
+%  create kml polygons for the partitions.
+%
+%  [kfold]=kml_partitions(fid,md,params)
+%
+%  where the required input is:
+%    fid           (char, file ID of .kml file)
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    data          (numeric, element or nodal results data)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    cmin          (numeric, minimum of color map)
+%    cmax          (numeric, maximum of color map)
+%    cmap          (char or numeric, colormap definition)
+%    prtplt        (char, 'off'/'no' for partition segment plot)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of polygon placemarks)
+%
+function [kfold]=kml_partitions(varargin)
+
+if ~nargin
+    help kml_part_edges
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','data','alt',...
+                 'cmin','cmax','cmap','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    if strcmpi(varargin{iarg},'data')
+        cdata=inputname(iarg+1);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if exist('data','var') && ~isempty(data)
+    if     (numel(data)==md.mesh.numberofelements)
+        edata=data;
+    elseif (numel(data)==md.mesh.numberofvertices)
+        ndata=data;
+        display('Averaging nodal data to element data.');
+        edata=zeros(1,md.mesh.numberofelements);
+        for i=1:size(md.mesh.elements,1)
+            for j=1:size(md.mesh.elements,2)
+                edata(i)=edata(i)+ndata(md.mesh.elements(i,j));
+            end
+            edata(i)=edata(i)/size(md.mesh.elements,2);
+        end
+    else
+        error(['Data has incorrect number of ' num2str(numel(data)) ' values.']);
+    end
+end
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+hfig=figure('Visible','off');
+if exist('cmap','var')
+    colormap(cmap)
+end
+cmap=colormap;
+close(hfig)
+
+if exist('edata','var')
+    if ~exist('cmin','var')
+        cmin=min(min(edata));
+    end
+    if ~exist('cmax','var')
+        cmax=max(max(edata));
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  write folder for partitions
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    kfold=kml_folder();
+    kfold.name      ='Partitions';
+    kfold.visibility=1;
+    kfold.descript  =sprintf('Partitions=%d, Nodes=%d',...
+        md.qmu.numberofpartitions,md.mesh.numberofvertices);
+    kfold.feature   ={repmat(kml_placemark(),1,md.qmu.numberofpartitions)};
+
+%  write each partition as a polygon multigeometry placemark
+
+    disp(['Writing ' num2str(md.qmu.numberofpartitions) ' partitions as KML polygons.']);
+    epart=md.qmu.partition(md.mesh.elements)+1;
+    if exist('ndata','var') || exist('edata','var')
+        pdata=zeros(1,md.qmu.numberofpartitions);
+        pdata(:)=NaN;
+    end
+
+%  loop over each partition
+
+    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)
+
+        [icol,irow]=find(epart'==k);
+        if isempty(irow)
+            continue;
+        end
+        irow=unique(irow);
+        elemp=md.mesh.elements(irow,:);
+        epartp=epart(irow,:);
+        nodeconp=kmlnodeconnectivity(elemp,md.mesh.numberofvertices);
+        [edgeadjp]=edgeadjacency(elemp,nodeconp);
+        [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)
+
+        if exist('ndata','var')
+            pdata(k)=ndata(find(md.qmu.partition+1==k,1));
+        elseif exist('edata','var')
+            for i=1:size(epartp,1)
+                if isempty(find(epart(i,:)~=k,1))
+                    pdata(k)=edata(irow(i));
+                    break
+                end
+            end
+            if isnan(pdata(k))
+                warning('Data for Partition %d is not defined.\n',k)
+            end
+        end
+
+%  set up the placemark with multigeometry
+
+        kplace=kml_placemark();
+        if (length(iloop)-1 > 1)
+            kplace.name      =sprintf('Partition %d (%d loops)',k,length(iloop)-1);
+        else
+            kplace.name      =sprintf('Partition %d',k);
+        end
+        kplace.visibility=1;
+        if exist('pdata','var')
+            kplace.descript  =sprintf('Partition data: %g',pdata(k));
+            imap = fix((pdata(k)-cmin)/(cmax-cmin)*size(cmap,1))+1;
+            if     (imap >= 1) && (imap <= size(cmap,1))
+                kplace.styleurl  =sprintf('#MatlabColor%d',imap);
+            elseif (pdata(k) == cmax)
+                kplace.styleurl  =sprintf('#MatlabColor%d',size(cmap,1));
+            else
+                kplace.styleurl  =sprintf('#BlackLineEmptyPoly');
+            end
+        else
+            kplace.styleurl  =sprintf('#BlackLineRandomPoly');
+        end
+
+        kmgeom=kml_multigeometry();
+        kmgeom.geometry  ={repmat(kml_polygon(),1,length(iloop)-1)};
+
+%  loop over each loop of the perimeter for the given partition
+
+        for i=1:length(iloop)-1
+            kpoly=kml_polygon();
+            kpoly.extrude   =1;
+            kpoly.altmode   ='relativeToGround';
+
+            kring=kml_linearring();
+            kring.coords    =zeros(0,3);
+
+            elast=0;
+            nlast=0;
+            slast=0;
+            lat=[];
+            long=[];
+
+%  loop over the element edges on the loop of the partition
+
+            j=iloop(i);
+            while (j < iloop(i+1))
+%  find which side of element is referenced in perimeter list
+                for l=1:size(elemp,2)
+                    if ((elemp(elemper(j),l)          == edgeper(j,1)) && ...
+                        (elemp(elemper(j),mod(l,3)+1) == edgeper(j,2))) || ...
+                       ((elemp(elemper(j),l)          == edgeper(j,2)) && ...
+                        (elemp(elemper(j),mod(l,3)+1) == edgeper(j,1)))
+                        jedge=l;
+                        break
+                    end
+                end
+
+%  check if element side connects nodes in partition
+                if (epartp(elemper(j),jedge)          == k) && ...
+                   (epartp(elemper(j),mod(jedge,3)+1) == k)
+%  write out specified element side
+%                    disp(['segment j=' int2str(j) ' unshared edge ' int2str(edgeper(j,1)) ' to ' int2str(edgeper(j,2)) ' on side ' int2str(jedge) ' from element ' int2str(elemper(j)) ' written.'])
+%  if first edge, write out first node
+                    if ~elast
+                        kring.coords(end+1,:)=[md.mesh.long(edgeper(j,1)) md.mesh.lat(edgeper(j,1)) alt];
+                    end
+                    kring.coords(end+1,:)=[md.mesh.long(edgeper(j,2)) md.mesh.lat(edgeper(j,2)) alt];
+                    elast=elemper(j);
+                    nlast=edgeper(j,2);
+                    slast=0;
+                    j=j+1;
+
+%  element not entirely within partition, so figure out boundary
+                else
+%                    disp(['segment j=' int2str(j) ' from element ' int2str(elemper(j)) ' shared by other partitions.'])
+                    ielem=elemper(j);
+
+%  follow partition boundary through elements not wholly in partition
+%  (may include elements not in perimeter list)
+
+                    while 1
+%  if first edge, figure out direction from perimeter edge direction
+                        if ~nlast && ~slast
+                            nlast=find(elemp(ielem,:)==edgeper(j,1));
+                            nnext=find(elemp(ielem,:)==edgeper(j,2));
+                            if     (nlast+nnext == 3)
+                                slast=1;
+                            elseif (nlast+nnext == 5)
+                                slast=2;
+                            elseif (nlast+nnext == 4)
+                                slast=3;
+                            end
+                            if     (nnext+(6-nlast-nnext) == 3)
+                                snext=1;
+                            elseif (nnext+(6-nlast-nnext) == 5)
+                                snext=2;
+                            elseif (nnext+(6-nlast-nnext) == 4)
+                                snext=3;
+                            end
+
+%  find how many nodes of current element are in current partition
+%  (1 or 2, not 3) and handle each permutation separately
+                            ipart=find(epartp(ielem,:)==k);
+%  two nodes are in current partition, so cut off other node
+                            if (length(ipart) == 2)
+                                switch 6-sum(ipart)
+                                    case nlast
+                                        slast=6-slast-snext;
+                                        nlast=0;
+                                    case nnext
+                                        if (epartp(ielem,nnext) == k)
+                                            nlast=nnext;
+                                        end
+                                    otherwise
+                                        slast=6-slast-snext;
+                                        nlast=0;
+                                end
+%  one node is in current partition
+                            else
+%  all different, so cut through centroid
+                                if (epartp(ielem,1) ~= epartp(ielem,2)) && ...
+                                   (epartp(ielem,2) ~= epartp(ielem,3)) && ...
+                                   (epartp(ielem,3) ~= epartp(ielem,1))
+                                    switch ipart
+                                        case {nlast,nnext}
+                                            if (epartp(ielem,nnext) == k)
+                                                nlast=nnext;
+                                            end
+                                        otherwise
+                                            slast=6-slast-snext;
+                                            nlast=0;
+                                    end
+%  other two are in the same partition, so cut them off
+                                else
+                                    switch ipart
+                                        case nlast
+                                            if (epartp(ielem,nnext) == k)
+                                                nlast=nnext;
+                                            end
+                                        case nnext
+                                            slast=snext;
+                                            nlast=0;
+                                        otherwise
+                                            slast=6-slast-snext;
+                                            nlast=0;
+                                    end
+                                end
+                            end
+
+%  last edge exited last element at node
+                            if nlast
+%  write out first node of first side for half-edge to midpoint
+%                                disp(['segment j=' int2str(j) ' unshared half edge from node ' int2str(elemp(ielem,nlast)) ' (node ' int2str(nlast) ') on side ' int2str(slast) ' from element ' int2str(ielem) ' written.'])
+                                kring.coords(end+1,:)=[md.mesh.long(elemp(ielem,nlast)) ...
+                                                       md.mesh.lat(elemp(ielem,nlast)) alt];
+                            end
+                            nlast=0;
+
+%  write out midpoint of first side
+                            kring.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
+                                                   +md.mesh.long(elemp(ielem,mod(slast,3)+1)))/2. ...
+                                                   (md.mesh.lat(elemp(ielem,slast))...
+                                                   +md.mesh.lat(elemp(ielem,mod(slast,3)+1)))/2. alt];
+                        end
+
+%  last edge exited last element at node
+                        if nlast
+                            if elast
+%  find where last node on previous element occurs on current element
+                                nlast=find(elemp(ielem,:)==nlast,1);
+                            end
+%  half-edge occurs on unshared side from current node (unique unless mesh
+%  is only attached at node)
+                            switch nlast
+                                case 1
+                                    if ~edgeadjp(ielem,1)
+                                        nnext=2;
+                                        slast=1;
+                                    else
+                                        nnext=3;
+                                        slast=3;
+                                    end
+                                case 2
+                                    if ~edgeadjp(ielem,2)
+                                        nnext=3;
+                                        slast=2;
+                                    else
+                                        nnext=1;
+                                        slast=1;
+                                    end
+                                case 3
+                                    if ~edgeadjp(ielem,3)
+                                        nnext=1;
+                                        slast=3;
+                                    else
+                                        nnext=2;
+                                        slast=2;
+                                    end
+                            end
+%  write out half-edge from current node to midpoint of unshared side
+%                            disp(['segment j=' int2str(j) ' unshared half edge from node ' int2str(elemp(ielem,nlast)) ' (node ' int2str(nlast) ') on side ' int2str(slast) ' from element ' int2str(ielem) ' written.'])
+                            kring.coords(end+1,:)=[(md.mesh.long(elemp(ielem,nlast))...
+                                                   +md.mesh.long(elemp(ielem,nnext)))/2. ...
+                                                   (md.mesh.lat(elemp(ielem,nlast))...
+                                                   +md.mesh.lat(elemp(ielem,nnext)))/2. alt];
+                            nlast=0;
+
+%  last edge exited last element at midpoint of side
+                        elseif slast
+                            if elast
+%  find where last side on previous element occurs on current element
+                                slast=find(edgeadjp(ielem,:)==elast,1);
+                            end
+                        end
+
+%  find how many nodes of current element are in current partition
+%  (1 or 2, not 3) and handle each permutation separately
+                        ipart=find(epartp(ielem,:)==k);
+                        if (length(ipart) == 2)
+%  two nodes are in current partition, so cut off other node
+                            switch 6-sum(ipart)
+                                case 1
+                                    snext=3+1-slast;
+                                case 2
+                                    snext=1+2-slast;
+                                case 3
+                                    snext=2+3-slast;
+                            end
+                        else
+                            if (epartp(ielem,1) ~= epartp(ielem,2)) && ...
+                               (epartp(ielem,2) ~= epartp(ielem,3)) && ...
+                               (epartp(ielem,3) ~= epartp(ielem,1))
+%  all different, so cut through centroid
+%                                disp(['element ielem=' int2str(ielem) ' centroid written.'])
+                                kring.coords(end+1,:)=[sum(md.mesh.long(elemp(ielem,:)))/3. ...
+                                                       sum(md.mesh.lat(elemp(ielem,:)))/3. alt];
+                            end
+%  one node is in current partition, so cut off other two nodes
+                            switch ipart
+                                case 1
+                                    snext=3+1-slast;
+                                case 2
+                                    snext=1+2-slast;
+                                case 3
+                                    snext=2+3-slast;
+                            end
+                        end
+%  write out midpoint of opposite side
+%                        disp(['segment j=' int2str(j) ' internal edge from side ' int2str(slast) ' to side ' int2str(snext) ' from element ' int2str(ielem) ' written.'])
+                        kring.coords(end+1,:)=[(md.mesh.long(elemp(ielem,snext))...
+                                               +md.mesh.long(elemp(ielem,mod(snext,3)+1)))/2. ...
+                                               (md.mesh.lat(elemp(ielem,snext))...
+                                               +md.mesh.lat(elemp(ielem,mod(snext,3)+1)))/2. alt];
+                        elast=ielem;
+                        nlast=0;
+                        slast=snext;
+%  find adjacent element to opposite side
+                        ielem=edgeadjp(elast,slast);
+%  if opposite side is unshared, find it in edge perimeter list
+                        if ~ielem
+                            jlast=find(elemper(j:end)==elast)+j-1;
+                            j=0;
+                            for l=1:length(jlast)
+                                if ((elemp(elast,slast)          == edgeper(jlast(l),1)) && ...
+                                    (elemp(elast,mod(slast,3)+1) == edgeper(jlast(l),2))) || ...
+                                   ((elemp(elast,slast)          == edgeper(jlast(l),2)) && ...
+                                    (elemp(elast,mod(slast,3)+1) == edgeper(jlast(l),1)))
+                                    j=jlast(l);
+                                    break
+                                end
+                            end
+                            if ~j
+                                j=iloop(i+1)-1;
+                            end
+%  write out half-edge from midpoint of unshared side to node
+                            if (epartp(elast,slast) == k)
+                                nnext=slast;
+                            else
+                                nnext=mod(slast,3)+1;
+                            end
+%                            disp(['segment j=' int2str(j) ' unshared half edge on side ' int2str(slast) ' to node ' int2str(elemp(elast,nnext)) ' (node ' int2str(nnext) ') from element ' int2str(elast) ' written.'])
+                            kring.coords(end+1,:)=[md.mesh.long(elemp(elast,nnext)) ...
+                                                   md.mesh.lat(elemp(elast,nnext)) alt];
+                            break
+%  if not unshared, advance perimeter list and watch for end
+                        else
+                            if (elast == elemper(j))
+                                if (j+1 < iloop(i+1)) && ...
+                                   ~isempty(find(elemper(j+1:end)~=elast,1))
+                                    j=j+find(elemper(j+1:end)~=elast,1);
+                                else
+                                    break
+                                end
+                            end
+                        end
+                    end
+                    j=j+1;
+                end
+            end
+
+            kpoly.outer=kring;
+            kmgeom.geometry{1}(i)=kpoly;
+            clear kring kpoly
+        end
+
+        kplace.geometry=kmgeom;
+        kfold.feature{1}(k)=kplace;
+        clear kmgeom kplace
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_placemark.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_placemark.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_placemark.m	(revision 18231)
@@ -0,0 +1,238 @@
+%
+%  definition for the kml_placemark sub (derived) class.
+%
+%  [kml]=kml_placemark(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, placemark id, '')
+%    name          (char, name, '')
+%    visibility    (logical, visibility, true)
+%    open          (logical, open, false)
+%    snippet       (char, snippet, '')
+%    descript      (char, description, '')
+%    styleurl      (char, style url, '')
+%    style         (cell array, styles)
+%    geometry      (kml_geometry, placemark geometry)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_placemark < kml_feature
+    properties
+        geometry  =kml_geometry.empty();
+    end
+
+    methods
+        function [kml]=kml_placemark(varargin)
+
+            kml=kml@kml_feature(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_placemark());
+
+                        for i=length(fieldnames(kml_feature()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_feature(kml(i));
+                disp(sprintf('      geometry: %s %s\n' ,string_size(kml(i).geometry),...
+                             class(kml(i).geometry)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_feature());
+            fnames={fnames{:} ...
+                    'geometry' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the placemarks
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<Placemark id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<Placemark>\n',indent);
+                end
+                kml_write@kml_feature(kmli,fid,indent);
+
+%  loop over the geometry elements for each placemark
+
+                for j=1:min(1,numel(kmli.geometry))
+                    kmlij=kmli.geometry(j);
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            kml_write(kmlij,fid,[indent '  ']);
+                        else
+                            warning('kml(%d).geometry(%d) is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+
+                fprintf(fid,'%s</Placemark>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the placemarks
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<Placemark id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<Placemark>\n',indent));
+                end
+                sbuf=kml_swrite@kml_feature(kmli,sbuf,indent);
+
+%  loop over the geometry elements for each placemark
+
+                for j=1:min(1,numel(kmli.geometry))
+                    kmlij=kmli.geometry(j);
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            sbuf=kml_swrite(kmlij,sbuf,[indent '  ']);
+                        else
+                            warning('kml(%d).geometry(%d) is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+
+                sbuf=add(sbuf,sprintf('%s</Placemark>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the placemarks
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+                delete@kml_feature(kmli);
+
+%  loop over the geometry elements for each placemark
+
+                for j=min(1,numel(kmli.geometry)):-1:1
+                    kmlij=kmli.geometry(j);
+                    if ~isempty(kmlij)
+                        if isa(kmlij,'kml_geometry')
+                            delete(kmlij);
+                        else
+                            warning('kml(%d).geometry(%d) is a ''%s'' class object, not ''%s''.',...
+                                i,j,class(kmlij),'kml_geometry');
+                        end
+                    end
+                end
+                kmli.geometry  =kml_geometry.empty();
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polygon.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polygon.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polygon.m	(revision 18231)
@@ -0,0 +1,271 @@
+%
+%  definition for the kml_polygon sub (derived) class.
+%
+%  [kml]=kml_polygon(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, polygon id, '')
+%    extrude       (logical, extrusion, false)
+%    tessellate    (logical, tessellation, false)
+%    altmode       (char, altitude mode, 'clampToGround')
+%    outer         (kml_linearring, outer boundary)
+%    inner         (kml_linearring, inner boundaries)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_polygon < kml_geometry
+    properties
+        extrude   =false;
+        tessellate=false;
+        altmode   ='clampToGround';
+        outer     =kml_linearring.empty();
+        inner     =kml_linearring.empty();
+    end
+
+    methods
+        function [kml]=kml_polygon(varargin)
+
+            kml=kml@kml_geometry(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_polygon());
+
+                        for i=length(fieldnames(kml_geometry()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_geometry(kml(i));
+                disp(sprintf('       extrude: %g'      ,kml(i).extrude));
+                disp(sprintf('    tessellate: %g'      ,kml(i).tessellate));
+                disp(sprintf('       altmode: ''%s'''  ,kml(i).altmode));
+                disp(sprintf('         outer: %s %s'   ,string_size(kml(i).outer),...
+                             class(kml(i).outer)));
+                disp(sprintf('         inner: %s %s\n' ,string_size(kml(i).inner),...
+                             class(kml(i).inner)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_geometry());
+            fnames={fnames{:} ...
+                    'extrude' ...
+                    'tessellate' ...
+                    'altmode' ...
+                    'outer' ...
+                    'inner' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the polygons
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<Polygon id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<Polygon>\n',indent);
+                end
+                kml_write@kml_geometry(kmli,fid,indent);
+                fprintf(fid,'%s  <extrude>%d</extrude>\n',indent,kmli.extrude);
+                fprintf(fid,'%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate);
+                fprintf(fid,'%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode);
+                fprintf(fid,'%s  <outerBoundaryIs>\n',indent);
+                if isa(kmli.outer,'kml_linearring')
+                    kml_write(kmli.outer,fid,[indent '    ']);
+                else
+                    warning('kml(%d).outer is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.outer),'kml_linearring');
+                end
+                fprintf(fid,'%s  </outerBoundaryIs>\n',indent);
+
+%  loop over any inner boundaries for each polygon
+
+                if isa(kmli.inner,'kml_linearring')
+                    for j=1:numel(kmli.inner)
+                        fprintf(fid,'%s  <innerBoundaryIs>\n',indent);
+                        kml_write(kmli.inner(j),fid,[indent '    ']);
+                        fprintf(fid,'%s  </innerBoundaryIs>\n',indent);
+                    end
+                else
+                    warning('kml(%d).inner is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.inner),'kml_linearring');
+                end
+
+                fprintf(fid,'%s</Polygon>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the polygons
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<Polygon id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<Polygon>\n',indent));
+                end
+                sbuf=kml_swrite@kml_geometry(kmli,sbuf,indent);
+                sbuf=add(sbuf,sprintf('%s  <extrude>%d</extrude>\n',indent,kmli.extrude));
+                sbuf=add(sbuf,sprintf('%s  <tessellate>%d</tessellate>\n',indent,kmli.tessellate));
+                sbuf=add(sbuf,sprintf('%s  <altitudeMode>%s</altitudeMode>\n',indent,kmli.altmode));
+                sbuf=add(sbuf,sprintf('%s  <outerBoundaryIs>\n',indent));
+                if isa(kmli.outer,'kml_linearring')
+                    sbuf=kml_swrite(kmli.outer,sbuf,[indent '    ']);
+                else
+                    warning('kml(%d).outer is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.outer),'kml_linearring');
+                end
+                sbuf=add(sbuf,sprintf('%s  </outerBoundaryIs>\n',indent));
+
+%  loop over any inner boundaries for each polygon
+
+                if isa(kmli.inner,'kml_linearring')
+                    for j=1:numel(kmli.inner)
+                        sbuf=add(sbuf,sprintf('%s  <innerBoundaryIs>\n',indent));
+                        sbuf=kml_swrite(kmli.inner(j),sbuf,[indent '    ']);
+                        sbuf=add(sbuf,sprintf('%s  </innerBoundaryIs>\n',indent));
+                    end
+                else
+                    warning('kml(%d).inner is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.inner),'kml_linearring');
+                end
+
+                sbuf=add(sbuf,sprintf('%s</Polygon>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the polygons
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+                if isa(kmli.outer,'kml_linearring')
+                    delete(kmli.outer);
+                else
+                    warning('kml(%d).outer is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.outer),'kml_linearring');
+                end
+                kmli.outer     =kml_linearring.empty();
+
+%  loop over any inner boundaries for each polygon
+
+                if isa(kmli.inner,'kml_linearring')
+                    for j=numel(kmli.inner):-1:1
+                        delete(kmli.inner(j));
+                    end
+                else
+                    warning('kml(%d).inner is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.inner),'kml_linearring');
+                end
+                kmli.inner     =kml_linearring.empty();
+
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polystyle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polystyle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_polystyle.m	(revision 18231)
@@ -0,0 +1,181 @@
+%
+%  definition for the kml_polystyle sub (derived) class.
+%
+%  [kml]=kml_polystyle(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, polystyle id, '')
+%    color         (char, opacity/color in hex aabbggrr, 'ffffffff')
+%    colormode     (char, color mode , 'normal')
+%    fill          (logical, polygon fill, true)
+%    outline       (logical, polygon outline, true)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_polystyle < kml_colorstyle
+    properties
+        fill      =true;
+        outline   =true;
+    end
+
+    methods
+        function [kml]=kml_polystyle(varargin)
+
+            kml=kml@kml_colorstyle(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_polystyle());
+
+                        for i=length(fieldnames(kml_colorstyle()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_colorstyle(kml(i));
+                disp(sprintf('          fill: %d'      ,kml(i).fill));
+                disp(sprintf('       outline: %d\n'    ,kml(i).outline));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_colorstyle());
+            fnames={fnames{:} ...
+                    'fill' ...
+                    'outline' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the polystyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<PolyStyle id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<PolyStyle>\n',indent);
+                end
+                kml_write@kml_colorstyle(kmli,fid,indent);
+                fprintf(fid,'%s  <fill>%d</fill>\n',indent,kmli.fill);
+                fprintf(fid,'%s  <outline>%d</outline>\n',indent,kmli.outline);
+                fprintf(fid,'%s</PolyStyle>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the polystyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<PolyStyle id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<PolyStyle>\n',indent));
+                end
+                sbuf=kml_swrite@kml_colorstyle(kmli,sbuf,indent);
+                sbuf=add(sbuf,sprintf('%s  <fill>%d</fill>\n',indent,kmli.fill));
+                sbuf=add(sbuf,sprintf('%s  <outline>%d</outline>\n',indent,kmli.outline));
+                sbuf=add(sbuf,sprintf('%s</PolyStyle>\n',indent));
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_style.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_style.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_style.m	(revision 18231)
@@ -0,0 +1,327 @@
+%
+%  definition for the kml_style sub (derived) class.
+%
+%  [kml]=kml_style(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, style id, '')
+%    icon          (char, icon style, '')
+%    label         (char, label style, '')
+%    line          (char, line style, '')
+%    poly          (char, poly style, '')
+%    balloon       (char, balloon style, '')
+%    list          (char, list style, '')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_style < kml_styleselector
+    properties
+%         icon      =kml_iconstyle.empty();
+%         label     =kml_labelstyle.empty();
+        icon      =[];
+        label     =[];
+        line      =kml_linestyle.empty();
+        poly      =kml_polystyle.empty();
+%         balloon   =kml_balloonstyle.empty();
+%         list      =kml_liststyle.empty();
+        balloon   =[];
+        list      =[];
+    end
+
+    methods
+        function [kml]=kml_style(varargin)
+
+            kml=kml@kml_styleselector(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_style());
+
+                        for i=length(fieldnames(kml_styleselector()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(kml),inputname(1),string_dim(kml,i)));
+                disp@kml_styleselector(kml(i));
+                disp(sprintf('          icon: %s %s'   ,string_size(kml(i).icon),...
+                             class(kml(i).icon)));
+                disp(sprintf('         label: %s %s'   ,string_size(kml(i).label),...
+                             class(kml(i).label)));
+                disp(sprintf('          line: %s %s'   ,string_size(kml(i).line),...
+                             class(kml(i).line)));
+                disp(sprintf('          poly: %s %s'   ,string_size(kml(i).poly),...
+                             class(kml(i).poly)));
+                disp(sprintf('       balloon: %s %s'   ,string_size(kml(i).balloon),...
+                             class(kml(i).balloon)));
+                disp(sprintf('          list: %s %s\n' ,string_size(kml(i).list),...
+                             class(kml(i).list)));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_styleselector());
+            fnames={fnames{:} ...
+                    'icon' ...
+                    'label' ...
+                    'line' ...
+                    'poly' ...
+                    'balloon' ...
+                    'list' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the styles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    fprintf(fid,'%s<Style id="%s">\n',indent,kmli.id);
+                else
+                    fprintf(fid,'%s<Style>\n',indent);
+                end
+                kml_write@kml_styleselector(kmli,fid,indent);
+%                 if isa(kmli.icon,'kml_iconstyle')
+%                     kml_write(kmli.icon,fid,[indent '  ']);
+%                 else
+%                     warning('kml(%d).icon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.icon),'kml_iconstyle');
+%                 end
+%                 if isa(kmli.label,'kml_labelstyle')
+%                     kml_write(kmli.label,fid,[indent '  ']);
+%                 else
+%                     warning('kml(%d).label is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.label),'kml_labelstyle');
+%                 end
+                if isa(kmli.line,'kml_linestyle')
+                    kml_write(kmli.line,fid,[indent '  ']);
+                else
+                    warning('kml(%d).line is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.line),'kml_linestyle');
+                end
+                if isa(kmli.poly,'kml_polystyle')
+                    kml_write(kmli.poly,fid,[indent '  ']);
+                else
+                    warning('kml(%d).poly is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.poly),'kml_polystyle');
+                end
+%                 if isa(kmli.balloon,'kml_balloonstyle')
+%                     kml_write(kmli.balloon,fid,[indent '  ']);
+%                 else
+%                     warning('kml(%d).balloon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.balloon),'kml_balloonstyle');
+%                 end
+%                 if isa(kmli.list,'kml_liststyle')
+%                     kml_write(kmli.list,fid,[indent '  ']);
+%                 else
+%                     warning('kml(%d).list is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.list),'kml_liststyle');
+%                 end
+                fprintf(fid,'%s</Style>\n',indent);
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the styles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if ~isempty(kmli.id)
+                    sbuf=add(sbuf,sprintf('%s<Style id="%s">\n',indent,kmli.id));
+                else
+                    sbuf=add(sbuf,sprintf('%s<Style>\n',indent));
+                end
+                sbuf=kml_swrite@kml_styleselector(kmli,sbuf,indent);
+%                 if isa(kmli.icon,'kml_iconstyle')
+%                     sbuf=kml_swrite(kmli.icon,sbuf,[indent '  ']);
+%                 else
+%                     warning('kml(%d).icon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.icon),'kml_iconstyle');
+%                 end
+%                 if isa(kmli.label,'kml_labelstyle')
+%                     sbuf=kml_swrite(kmli.label,sbuf,[indent '  ']);
+%                 else
+%                     warning('kml(%d).label is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.label),'kml_labelstyle');
+%                 end
+                if isa(kmli.line,'kml_linestyle')
+                    sbuf=kml_swrite(kmli.line,sbuf,[indent '  ']);
+                else
+                    warning('kml(%d).line is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.line),'kml_linestyle');
+                end
+                if isa(kmli.poly,'kml_polystyle')
+                    sbuf=kml_swrite(kmli.poly,sbuf,[indent '  ']);
+                else
+                    warning('kml(%d).poly is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.poly),'kml_polystyle');
+                end
+%                 if isa(kmli.balloon,'kml_balloonstyle')
+%                     sbuf=kml_swrite(kmli.balloon,sbuf,[indent '  ']);
+%                 else
+%                     warning('kml(%d).balloon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.balloon),'kml_balloonstyle');
+%                 end
+%                 if isa(kmli.list,'kml_liststyle')
+%                     sbuf=kml_swrite(kmli.list,sbuf,[indent '  ']);
+%                 else
+%                     warning('kml(%d).list is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.list),'kml_liststyle');
+%                 end
+                sbuf=add(sbuf,sprintf('%s</Style>\n',indent));
+            end
+
+        end
+
+%  delete the object
+
+        function []=delete(kml)
+
+%  loop over the styles
+
+            for i=numel(kml):-1:1
+                kmli=kml(i);
+%                 if isa(kmli.icon,'kml_iconstyle')
+%                     delete(kmli.icon);
+%                 else
+%                     warning('kml(%d).icon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.icon),'kml_iconstyle');
+%                 end
+%                 kmli.icon      =kml_iconstyle.empty();
+%                 if isa(kmli.label,'kml_labelstyle')
+%                     delete(kmli.label);
+%                 else
+%                     warning('kml(%d).label is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.label),'kml_labelstyle');
+%                 end
+%                 kmli.label     =kml_labelstyle.empty();
+                if isa(kmli.line,'kml_linestyle')
+                    delete(kmli.line);
+                else
+                    warning('kml(%d).line is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.line),'kml_linestyle');
+                end
+                kmli.line      =kml_linestyle.empty();
+                if isa(kmli.poly,'kml_polystyle')
+                    delete(kmli.poly);
+                else
+                    warning('kml(%d).poly is a ''%s'' class object, not ''%s''.',...
+                        i,class(kmli.poly),'kml_polystyle');
+                end
+                kmli.poly      =kml_polystyle.empty();
+%                 if isa(kmli.balloon,'kml_balloonstyle')
+%                     delete(kmli.balloon);
+%                 else
+%                     warning('kml(%d).balloon is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.balloon),'kml_balloonstyle');
+%                 end
+%                 kmli.balloon   =kml_balloonstyle.empty();
+%                 if isa(kmli.list,'kml_liststyle')
+%                     delete(kmli.list);
+%                 else
+%                     warning('kml(%d).list is a ''%s'' class object, not ''%s''.',...
+%                         i,class(kmli.list),'kml_liststyle');
+%                 end
+%                 kmli.list      =kml_liststyle.empty();
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_styleselector.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_styleselector.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_styleselector.m	(revision 18231)
@@ -0,0 +1,178 @@
+%
+%  definition for the kml_styleselector super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_styleselector(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, styleselector id, '')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_styleselector < kml_object
+    properties
+    end
+
+    methods
+        function [kml]=kml_styleselector(varargin)
+
+            kml=kml@kml_object(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_styleselector());
+
+                        for i=length(fieldnames(kml_object()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_styleselector')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_object(kml(i));
+                if strcmp(class(kml),'kml_styleselector')
+                    disp(sprintf('\n'));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_object());
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the styleselectors
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_styleselector')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!StyleSelector id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!StyleSelector>\n',indent);
+                    end
+                end
+                kml_write@kml_object(kmli,fid,indent);
+                if strcmp(class(kml),'kml_styleselector')
+                    fprintf(fid,'%s</!StyleSelector>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the styleselectors
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_styleselector')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!StyleSelector id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!StyleSelector>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_object(kmli,sbuf,indent);
+                if strcmp(class(kml),'kml_styleselector')
+                    sbuf=add(sbuf,sprintf('%s</!StyleSelector>\n',indent));
+                end
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_substyle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_substyle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_substyle.m	(revision 18231)
@@ -0,0 +1,178 @@
+%
+%  definition for the kml_substyle super (base) and sub (derived) abstract class.
+%
+%  [kml]=kml_substyle(varargin)
+%
+%  where the optional varargin and defaults are:
+%    id            (char, substyle id, '')
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef kml_substyle < kml_object
+    properties
+    end
+
+    methods
+        function [kml]=kml_substyle(varargin)
+
+            kml=kml@kml_object(varargin{:});
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(kml))
+                        kml=varargin{1};
+
+                    else
+                        fnames=fieldnames(kml_substyle());
+
+                        for i=length(fieldnames(kml_object()))+1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(kml.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    kml.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(kml.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+        end
+
+%  display the object
+
+        function []=disp(kml)
+
+            for i=1:numel(kml)
+                if strcmp(class(kml),'kml_substyle')
+                    disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                        class(kml),inputname(1),string_dim(kml,i)));
+                end
+                disp@kml_object(kml(i));
+                if strcmp(class(kml),'kml_substyle')
+                    disp(sprintf('\n'));
+                end
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(kml)
+
+%  fieldnames for a sub (derived) class list those before super (base)
+
+            fnames=fieldnames(kml_object());
+
+        end
+
+%  set the properties of the object
+
+        function [kml]=setprops(kml,varargin)
+
+            kmlref=feval(class(kml));
+            fnames=fieldnames(kmlref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(kmlref.(varargin{i})))
+                        kml.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(kmlref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(kmlref));
+                end
+            end
+
+        end
+
+%  write the object
+
+        function []=kml_write(kml,fid,indent)
+
+           if ~exist('fid','var') || isempty(fid)
+               fid=1;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the substyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_substyle')
+                    if ~isempty(kmli.id)
+                        fprintf(fid,'%s<!SubStyle id="%s">\n',indent,kmli.id);
+                    else
+                        fprintf(fid,'%s<!SubStyle>\n',indent);
+                    end
+                end
+                kml_write@kml_object(kmli,fid,indent);
+                if strcmp(class(kml),'kml_substyle')
+                    fprintf(fid,'%s<!/SubStyle>\n',indent);
+                end
+            end
+
+        end
+
+%  string write the object
+
+        function [sbuf]=kml_swrite(kml,sbuf,indent)
+
+           if ~exist('sbuf','var') || isempty(sbuf)
+               sbuf=string_buf;
+           end
+           if ~exist('indent','var') || isempty(indent)
+               indent='';
+           end
+
+%  loop over the substyles
+
+            for i=1:numel(kml)
+                kmli=kml(i);
+                if strcmp(class(kml),'kml_substyle')
+                    if ~isempty(kmli.id)
+                        sbuf=add(sbuf,sprintf('%s<!SubStyle id="%s">\n',indent,kmli.id));
+                    else
+                        sbuf=add(sbuf,sprintf('%s<!SubStyle>\n',indent));
+                    end
+                end
+                sbuf=kml_swrite@kml_object(kmli,sbuf,indent);
+                if strcmp(class(kml),'kml_substyle')
+                    sbuf=add(sbuf,sprintf('%s<!/SubStyle>\n',indent));
+                end
+            end
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_unsh_edges.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_unsh_edges.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kml_unsh_edges.m	(revision 18231)
@@ -0,0 +1,115 @@
+%%
+%  create kml linestrings for the unshared element edges.
+%
+%  [kfold]=kml_unsh_edges(md,params)
+%
+%  where the required input is:
+%    md            (model, model class object)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    latsgn        (numeric, +1/-1 for north/south latitude)
+%    alt           (numeric, altitude for polygons, default 10000)
+%    prtplt        (char, 'off'/'no' for partition edge plot)
+%
+%  and the required output is:
+%    kfold         (kml_folder, folder of linestring placemarks)
+%
+function [kfold]=kml_unsh_edges(varargin)
+
+if ~nargin
+    help kml_unsh_edges
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if (nargin >= 1)
+    md=varargin{1};
+end
+if ~exist('md','var') || isempty(md) || ~isa(md,'model')
+    error(['Model ''' inputname(iarg) ''' is unrecognized class ''' class(md) '''.']);
+end
+
+%  parameters
+
+iarg=iarg+1;
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'latsgn','alt','prtplt'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1},20) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1},20) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if isempty(md.mesh.lat)  || ((numel(md.mesh.lat) == 1)  && isnan(md.mesh.lat)) || ...
+   isempty(md.mesh.long) || ((numel(md.mesh.long) == 1) && isnan(md.mesh.long))
+    if     ~exist('latsgn','var')
+        error(['Missing ''latsgn'' parameter to calculate missing lat/long data.']);
+    elseif (abs(latsgn) ~= 1)
+        error(['Incorrect latsgn=' num2str(latsgn) ' parameter to calculate missing lat/long data.']);
+    else
+        display('Converting x/y data to lat/long data.');
+        [md.mesh.lat,md.mesh.long]=xy2ll(md.x,md.y,latsgn);
+    end
+end
+
+if ~exist('alt','var')
+    alt=10000;
+end
+
+%%  write folder for unshared edges
+
+if (~exist('prtplt','var') || strncmpi(prtplt,'on' ,2) || strncmpi(prtplt,'y',1)) && ...
+    md.qmu.numberofpartitions
+    [edgeadj]=edgeadjacency(md.mesh.elements,md.kmlnodeconnectivity);
+    [icol,irow]=find(edgeadj'==0);
+    edgeuns=zeros(length(irow),2);
+    for i=1:length(irow)
+        edgeuns(i,1)=md.mesh.elements(irow(i),icol(i));
+        edgeuns(i,2)=md.mesh.elements(irow(i),mod(icol(i),size(md.mesh.elements,2))+1);
+    end
+    kfold=kml_folder();
+    kfold.name      ='Unshared Edges';
+    kfold.visibility=1;
+    kfold.descript  =sprintf('Partitions=%d, Edges=%d',...
+        md.qmu.numberofpartitions,size(edgeuns,1));
+    kfold.feature   ={repmat(kml_placemark(),1,size(edgeuns,1))};
+
+%  write each edge as a linestring placemark
+
+    disp(['Writing ' num2str(size(edgeuns,1)) ' unshared edges as KML linestrings.']);
+    for i=1:size(edgeuns,1)
+        kplace=kml_placemark();
+        kplace.name      =sprintf('Edge %d',i);
+        kplace.visibility=1;
+        kplace.styleurl  ='#RedLineRedPoly';
+
+        kline=kml_linestring();
+        kline.extrude   =1;
+        kline.tessellate=1;
+        kline.altmode   ='relativeToGround';
+        kline.coords    =zeros(2,3);
+
+        for j=1:2
+            kline.coords(j,:)=[md.mesh.long(edgeuns(i,j)) md.mesh.lat(edgeuns(i,j)) alt];
+        end
+
+        kplace.geometry=kline;
+        kfold.feature{1}(i)=kplace;
+        clear kline kplace
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlimagesc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlimagesc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlimagesc.m	(revision 18231)
@@ -0,0 +1,67 @@
+function kmlimagesc(md,fieldname,varargin)
+%KMLIMAGESC - create lat,long kml image
+%
+%   Usage:
+%      kmlimagesc(md,field,options);
+%
+%   Options: 
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%      'posting': default .1 degree
+%
+
+%process varargin for options: 
+options=pairoptions(varargin{:});
+
+%recover field: 
+field=md.(fieldname);
+
+%recover some options, and set defaults
+fontsize=getfieldvalue(options,'fontsize',12);
+posting=getfieldvalue(options,'posting',.1);
+minlong=getfieldvalue(options,'minlong',min(md.mesh.long));
+maxlong=getfieldvalue(options,'maxlong',max(md.mesh.long));
+minlat=getfieldvalue(options,'minlat',min(md.mesh.lat));
+maxlat=getfieldvalue(options,'maxlat',max(md.mesh.lat));
+minfield=getfieldvalue(options,'minfield',min(field));
+maxfield=getfieldvalue(options,'maxfield',max(field));
+
+%do we have hemisphere setup?:
+if ~isstr(md.mesh.hemisphere),
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+if strcmpi(md.mesh.hemisphere,'s'),
+	hemisphere=1;
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+elseif strcmpi(md.mesh.hemisphere,'n'),
+	hemisphere=-1;
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+else
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+%figure out nlines and ncols in our image
+nlines=(maxlat-minlat)/posting;
+ncols=(maxlong-minlong)/posting;
+
+%regrid to lat,long grid
+[x_m,y_m,field]=InterpFromMeshToGrid(md.mesh.elements,md.mesh.long,md.mesh.lat,field,minlong,maxlat,posting,posting,nlines,ncols,NaN);
+field=flipud(field);
+
+%massage  and log:
+pos=find(field<minfield); field(pos)=minfield;
+pos=find(field>maxfield);field(pos)=maxfield;
+
+%create google earth kml file out of this regridded dataset:
+imagestr=ge_imagesc(x_m,y_m,field,'imgURL',[fieldname '.png'],'name',fieldname);
+imagestr=ge_folder(fieldname,imagestr);
+colorbarstr=ge_colorbar((min(x_m)+max(x_m))/2,(min(y_m)+max(y_m))/2,field,'name',fieldname);
+colorbarstr=ge_folder('Colorbar',colorbarstr);
+ge_output([fieldname '.kml'],[imagestr colorbarstr]);
+
+%now, create kmz file:
+system(['mv ' [fieldname '.kml'] ' doc.kml && zip ' [fieldname '.kmz'] ' doc.kml ' fieldname '.png && rm -rf doc.kml ' [fieldname '.png'] ]);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlnodeconnectivity.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlnodeconnectivity.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/kmlnodeconnectivity.m	(revision 18231)
@@ -0,0 +1,58 @@
+%
+%  create a node connectivity table for the elements in the model.
+%
+%  [nodecon]=edgeadjacency(elem,nnodes,mxepg)
+%
+%  where the required input is:
+%    elem          (numeric, element connectivity array (elems x nodes))
+%
+%  and the required output is:
+%    nodecon       (numeric, node connectivity array (nnodes x mxepg+1))
+%
+%  the optional input is:
+%    nnodes        (numeric, number of nodes)
+%    mxepg         (numeric, max elements per node)
+%
+function [nodecon]=kmlnodeconnectivity(elem,nnodes,mxepg)
+
+if ~nargin
+    help kmlnodeconnectivity
+    return
+end
+
+if ~exist('nnodes','var') || isempty(nnodes)
+    nnodes=max(max(elem));
+end
+if ~exist('mxepg','var') || isempty(mxepg)
+    mxepg=25;
+end
+
+%%  create the node connectivity array
+
+nodecon=zeros(nnodes,mxepg+1);
+
+%  loop over the elements
+
+for i=1:size(elem,1)
+
+%  loop over the nodes for each element
+
+    for j=1:size(elem,2)
+        if elem(i,j)
+            nodecon(elem(i,j),nodecon(elem(i,j),end)+1)=i;
+            nodecon(elem(i,j),end)=nodecon(elem(i,j),end)+1;
+        end
+    end
+end
+
+%%  sort the node connectivity array
+
+%  loop over the nodes
+
+for i=1:size(nodecon,1)
+    if (nodecon(i,end) > 1)
+        nodecon(i,1:nodecon(i,end))=sort(nodecon(i,1:nodecon(i,end)));
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/string_buf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/string_buf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/kml/string_buf.m	(revision 18231)
@@ -0,0 +1,188 @@
+%
+%  definition for the string_buf class.
+%
+%  [sbuf]=string_buf(varargin)
+%
+%  where the optional varargin and defaults are:
+%    init          (numeric, initial size)
+%    inc           (numeric, incremental size)
+%    max           (numeric, maximum size)
+%
+%  and the protected properties are:
+%    string        (char, string buffer)
+%    size          (numeric, current size of buffer)
+%    len           (numeric, current length of string in buffer)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and two or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef string_buf < handle
+    properties
+        init      =10000000;
+        inc       =1000000;
+        max       =100000000;
+    end
+%     properties (SetAccess = private, GetAccess = private)
+    properties (SetAccess = private)
+        string    ='';
+        size      =0;
+        len       =0;
+    end
+
+    methods
+        function [sbuf]=string_buf(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if (nargin == 1) && isa(varargin{1},class(string_buf))
+                        sbuf=varargin{1};
+
+                    else
+                        fnames=fieldnames(string_buf());
+
+                        for i=1:min(nargin,length(fnames))
+                            if isa(varargin{i},class(sbuf.(fnames{i})))
+                                if ~isempty(varargin{i})
+                                    sbuf.(fnames{i})=varargin{i};
+                                end
+                            else
+                                if ~isempty(inputname(i))
+                                    warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        inputname(i),fnames{i},class(varargin{i}),class(sbuf.(fnames{i})));
+                                else
+                                    warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                        i           ,fnames{i},class(varargin{i}),class(sbuf.(fnames{i})));
+                                end
+                            end
+                        end
+                    end
+
+            end
+
+            sbuf.string=blanks(sbuf.init);
+            sbuf.size  =sbuf.init;
+
+        end
+
+%  display the object
+
+        function []=disp(sbuf)
+
+            for i=1:numel(sbuf)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(sbuf),inputname(1),string_dim(sbuf,i)));
+                disp(sprintf('          init: %d'      ,sbuf(i).init));
+                disp(sprintf('           inc: %d'      ,sbuf(i).inc));
+                disp(sprintf('           max: %d'      ,sbuf(i).max));
+                disp(sprintf('        string: %s'      ,any2str(sbuf(i).string,40)));
+                disp(sprintf('          size: %d'      ,sbuf(i).size));
+                disp(sprintf('           len: %d\n'    ,sbuf(i).len));
+            end
+
+        end
+
+%  return the fieldnames of the object
+
+        function [fnames]=fieldnames(sbuf)
+
+            fnames={'init' ...
+                    'inc' ...
+                    'max' ...
+                   }';
+
+        end
+
+%  set the properties of the object
+
+        function [sbuf]=set(sbuf,varargin)
+
+            sbufref=feval(class(sbuf));
+            fnames=fieldnames(sbufref);
+
+%  loop through each parameter in the input list (comparing to the reference
+%  object in case property types have been changed)
+
+            for i=1:2:length(varargin)
+                if ismember(varargin{i},fnames) && (i+1 <= length(varargin))
+                    if isa(varargin{i+1},class(sbufref.(varargin{i})))
+                        sbuf.(varargin{i})=varargin{i+1};
+                    else
+                        if ~isempty(inputname(i+1))
+                            warning('Argument ''%s'' for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                inputname(i+2),varargin{i},class(varargin{i+1}),class(sbufref.(varargin{i})));
+                        else
+                            warning('Argument %d for property ''%s'' is a ''%s'' class object, not ''%s''.',...
+                                i+2           ,varargin{i},class(varargin{i+1}),class(sbufref.(varargin{i})));
+                        end
+                    end
+                else
+                    warning('Property ''%s'' for class ''%s'' does not exist.',...
+                        varargin{i},class(sbufref));
+                end
+            end
+
+        end
+
+%  add a string to the object
+
+        function [sbuf]=add(sbuf,str)
+
+            if ~ischar(str)
+                if ~isempty(inputname(2))
+                    warning('Argument ''%s'' for string is a ''%s'' class object, not ''%s''.',...
+                        inputname(2),class(str),'char');
+                else
+                    warning('Argument %d for string is a ''%s'' class object, not ''%s''.',...
+                        2           ,class(str),'char');
+                end
+            end
+
+%  check the buffer size and increase as necessary
+
+            slen=length(str);
+            while (sbuf.len+slen > sbuf.size)
+                if (sbuf.size+sbuf.inc <= sbuf.max)
+                    sbuf.string=[sbuf.string blanks(sbuf.inc)];
+                    sbuf.size  =sbuf.size+sbuf.inc;
+                else
+                    error('String buffer length of %d would exceed maximum of %d.',...
+                        sbuf.size+sbuf.inc,sbuf.max);
+                end
+            end
+
+%  copy the string into the buffer
+
+            sbuf.string(sbuf.len+1:sbuf.len+slen)=str;
+            sbuf.len=sbuf.len+slen;
+
+        end
+
+%  return the string from the object
+
+        function [str]=str(sbuf)
+
+           str=sbuf.string(1:sbuf.len);
+
+        end
+
+%  reset the object
+
+        function [sbuf]=reset(sbuf)
+
+            string    ='';
+            size      =0;
+            len       =0;
+
+        end
+
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.m	(revision 18231)
@@ -0,0 +1,25 @@
+function Tbar=DepthAvgTempCond(md)
+%DEPTHAVGTEMPCOND- compute conduction dependent temperature profile for an ice sheet. 
+%
+%   Usage:
+%   Tbar=DepthAvgTempCond(md)
+
+Tpmp=TMeltingPoint(md.materials.meltingpoint,0); %pressure melting point at 0 pressure.
+k=md.materials.thermalconductivity;
+G=md.basalforcings.geothermalflux; 
+H=md.geometry.thickness;
+Ts=md.initialization.temperature;
+alpha=G.*H/k;
+
+Tbar=zeros(md.mesh.numberofvertices,1);
+
+%find temperature average when we are below melting point: 
+pos=find( (Ts+alpha) <Tpmp);
+Tbar(pos)=Ts(pos)+alpha(pos)/2;
+
+pos=find( (Ts+alpha) >=Tpmp);
+Tbar(pos)=Tpmp+(Tpmp^2-Ts(pos).^2)/2./alpha(pos)+ Tpmp*(Ts(pos)-Tpmp)./alpha(pos);
+
+%on ice shelf, easier: 
+pos=find(md.mask.groundedice_levelset<=0);
+Tbar(pos)=(Ts(pos)+Tpmp)/2;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/DepthAvgTempCond.py	(revision 18231)
@@ -0,0 +1,34 @@
+import numpy as npy
+from TMeltingPoint  import TMeltingPoint
+
+def DepthAvgTempCond(md):
+   ''' compute conduction dependent temperature profile for an ice sheet. 
+   Usage:
+   Tbar=DepthAvgTempCond(md)
+   '''
+
+   Tpmp=TMeltingPoint(md.materials.meltingpoint,0) #pressure melting point at 0 pressure.
+
+   k=md.materials.thermalconductivity
+   G=md.basalforcings.geothermalflux
+   H=md.geometry.thickness[:,0]
+   Ts=md.initialization.temperature
+   alpha=G*H/k
+
+   Tbar=npy.zeros(md.mesh.numberofvertices,)
+
+   #find temperature average when we are below melting point: 
+   pos=npy.nonzero( Ts+alpha < Tpmp)
+   if pos:
+	   Tbar[pos]=Ts[pos]+alpha[pos]/2 
+
+   pos=npy.nonzero( Ts+alpha>= Tpmp)
+   if pos:
+	   Tbar[pos]=Tpmp+(Tpmp**2-Ts[pos]**2)/2/alpha[pos]+ Tpmp*(Ts[pos]-Tpmp)/alpha[pos]
+   
+   #on ice shelf, easier: 
+   pos=npy.nonzero(md.mask.groundedice_levelset[0]<=0)
+   if pos:
+	   Tbar[pos]=(Ts[pos]+Tpmp)/2
+
+   return Tbar
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.m	(revision 18231)
@@ -0,0 +1,15 @@
+function Tm=TMeltingPoint(reftemp, pressure)
+%TMELTINGPOINT- calculate pressure melting point of ice
+%
+%   reftemp is the melting temperature at atmospheric pressure (initialized in md.materials.meltingpoint)   
+%
+%   pressure is in Pa   
+%
+%   Usage:
+%   Tm=TMeltingPoint(md.materials.meltingpoint,pressure)
+
+%variables
+beta=7.9e-8; % K Pa^-1
+
+Tm=reftemp-beta*pressure;
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/TMeltingPoint.py	(revision 18231)
@@ -0,0 +1,21 @@
+import numpy as npy
+
+def TMeltingPoint(reftemp,pressure):
+	'''
+	Calculate the pressure melting point of ice at a given pressure
+
+	reftemp is the melting temperature in K at atmospheric pressure (initialized in md.materials.meltingpoint)
+
+	pressure is in Pa
+
+	Usage:
+		Tm=TMeltingPoint(md.materials.meltingpoint,pressure)
+	'''
+
+	#variables
+	beta=7.9e-8
+
+	#ensure ref is same dimension as pressure
+	ref=reftemp*npy.ones_like(pressure)
+
+	return reftemp-beta*pressure
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/arrhenius.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/arrhenius.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/arrhenius.m	(revision 18231)
@@ -0,0 +1,82 @@
+function rigidity=arrhenius(temperature, waterfraction, pressure)
+%ARRHENIUS - figure out the rigidity of ice for a given temperature and waterfraction
+%
+%   rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+%   temperature is in Kelvin degrees
+%   
+%   Usage:
+%   rigidity=arrhenius(temperature, waterfraction, pressure)
+
+%variables
+T0=273.15;
+n=3.;
+beta=7.9e-8; % K Pa^-1
+R=8.314; % J mol^-1 K^-1  
+T_switch=T0-10.;
+
+if(temperature<0)
+    error('input temperature should be in Kelvin (positive)');
+end
+
+if(temperature>TMeltingPoint(pressure))
+    error('input temperature is above pressure melting point.');
+end
+
+if(isnan(waterfraction))
+    waterfraction=zeros(size(temperature));
+end
+
+if(waterfraction<0)
+    error('waterfraction is negative');
+end
+
+wf_max=1.;
+if(any(waterfraction>wf_max))
+    error(['waterfraction exceeds permitted maximum of ' num2str(wf_max) '.']);
+end
+
+%limit waterfraction to 1%
+pos1p=find(waterfraction>0.01);
+waterfraction(pos1p)=0.01;
+
+pos=find((temperature<TMeltingPoint(pressure)) & (waterfraction>0)); % cold, wet ice
+if (length(pos)>0)
+    error('cold ice with positive waterfraction detected.');
+end
+
+%   values for Activation energy Q and pre-exponential constants from
+%   Grewe/Blatter 2009, p54
+
+    function A0=GetA0(T)
+        A0=zeros(size(T));
+        pos0=find(T<T_switch);
+        pos1=find(T>=T_switch);
+        A0(pos0)=3.985e-13; %Grewe Blatter 2009
+        A0(pos1)=1.916e3;
+    end
+
+    function Q=GetQa(T)
+        Q=zeros(size(T));
+        pos0=find(T<T_switch);
+        pos1=find(T>=T_switch);
+        Q(pos0)=6.e4; % J mol^-1 % Paterson 2010
+        Q(pos1)=1.39e5;
+    end
+
+    function A=GetA(T, w)
+        Qa=GetQa(T); 
+        A0=GetA0(T);
+        if(w>0.01)
+           w=0.01;
+        end
+        A=A0.*exp(-Qa./(R*T)).*(1+181.25*w);        
+    end
+    
+    function B=GetRigidity(T,w,pressure)
+        Thom=TMeltingPoint(T, pressure);
+        A=GetA(Thom, w);
+        B=1./(A.^(1/n));
+    end
+
+rigidity=GetRigidity(temperature, waterfraction, pressure);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.m	(revision 18231)
@@ -0,0 +1,41 @@
+function rigidity=cuffey(temperature)
+%CUFFEY - calculates ice rigidity as a function of temperature
+%
+%   rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3)
+%   (Cuffey and Paterson, p75). 
+%   temperature is in Kelvin degrees
+%
+%   Usage:
+%      rigidity=cuffey(temperature)
+
+if any(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+%The routine below is equivalent to:
+% n=3; T=temperature-273;
+% %From cuffey
+% Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+% A=[2.4*10^-24;1.7*10^-24;9.3*10^-25;3.5*10^-25;2.1*10^-25;1.2*10^-25;6.8*10^-26;3.7*10^-26;2.0*10^-26;1.0*10^-26;5.2*10^-27;2.6*10^-27];%s-1(Pa-3)
+% %Convert into rigidity B
+% B=A.^(-1/n); %s^(1/3)Pa
+% %Now, do a cubic fit between Temp and B: 
+% fittedmodel=fit(Temp,B,'cubicspline');
+% rigidity=fittedmodel(temperature);
+
+rigidity=zeros(length(T),1);
+pos=find(T<=-45);         rigidity(pos)=10^8*(-0.000396645116301*(T(pos)+50).^3+ 0.013345579471334*(T(pos)+50).^2  -0.356868703259105*(T(pos)+50)+7.272363035371383);
+pos=find(-45<=T & T<-40); rigidity(pos)=10^8*(-0.000396645116301*(T(pos)+45).^3+ 0.007395902726819*(T(pos)+45).^2  -0.253161292268336*(T(pos)+45)+5.772078366321591);
+pos=find(-40<=T & T<-35); rigidity(pos)=10^8*(0.000408322072669*(T(pos)+40).^3+  0.001446225982305*(T(pos)+40).^2  -0.208950648722716*(T(pos)+40)+4.641588833612773);
+pos=find(-35<=T & T<-30); rigidity(pos)=10^8*(-0.000423888728124*(T(pos)+35).^3+ 0.007571057072334*(T(pos)+35).^2  -0.163864233449525*(T(pos)+35)+3.684031498640382);
+pos=find(-30<=T & T<-25); rigidity(pos)=10^8*(0.000147154327025*(T(pos)+30).^3+ 0.001212726150476*(T(pos)+30).^2  -0.119945317335478*(T(pos)+30)+3.001000667185614);
+pos=find(-25<=T & T<-20); rigidity(pos)=10^8*(-0.000193435838672*(T(pos)+25).^3+ 0.003420041055847*(T(pos)+25).^2  -0.096781481303861*(T(pos)+25)+2.449986525148220);
+pos=find(-20<=T & T<-15); rigidity(pos)=10^8*(0.000219771255067*(T(pos)+20).^3+  0.000518503475772*(T(pos)+20).^2  -0.077088758645767*(T(pos)+20)+2.027400665191131);
+pos=find(-15<=T & T<-10); rigidity(pos)=10^8*(-0.000653438900191*(T(pos)+15).^3+ 0.003815072301777*(T(pos)+15).^2  -0.055420879758021*(T(pos)+15)+1.682390865739973);
+pos=find(-10<=T & T<-5);  rigidity(pos)=10^8*(0.000692439419762*(T(pos)+10).^3 -0.005986511201093 *(T(pos)+10).^2 -0.066278074254598*(T(pos)+10)+1.418983411970382);
+pos=find(-5<=T & T<-2);   rigidity(pos)=10^8*(-0.000132282004110*(T(pos)+5).^3 +0.004400080095332*(T(pos)+5).^2    -0.074210229783403*(T(pos)+5)+ 1.024485188140279);
+pos=find(-2<=T);          rigidity(pos)=10^8*(-0.000132282004110*(T(pos)+2).^3 +0.003209542058346*(T(pos)+2).^2    -0.051381363322371*(T(pos)+2)+ 0.837883605537096);
+
+%Now make sure that rigidity is positive
+pos=find(rigidity<0);        rigidity(pos)=10^6;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/cuffey.py	(revision 18231)
@@ -0,0 +1,49 @@
+import numpy
+
+def cuffey(temperature):
+	"""
+	CUFFEY - calculates ice rigidity as a function of temperature
+
+	   rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3)
+		(Cuffey and Paterson, p75). 
+	   temperature is in Kelvin degrees
+
+	   Usage:
+	      rigidity=cuffey(temperature)
+	"""
+	
+	if numpy.any(temperature<0.):
+		raise RuntimeError("input temperature should be in Kelvin (positive)")
+	
+	T = temperature.reshape(-1,)-273.15
+
+	rigidity=numpy.zeros_like(T)
+	pos=numpy.nonzero(T<=-45)
+	rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+50)**3+ 0.013345579471334*(T[pos]+50)**2  -0.356868703259105*(T[pos]+50)+7.272363035371383)
+	pos=numpy.nonzero(numpy.logical_and(-45<=T,T<-40))
+	rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+45)**3+ 0.007395902726819*(T[pos]+45)**2  -0.253161292268336*(T[pos]+45)+5.772078366321591)
+	pos=numpy.nonzero(numpy.logical_and(-40<=T,T<-35))
+	rigidity[pos]=10**8*(0.000408322072669*(T[pos]+40)**3+  0.001446225982305*(T[pos]+40)**2  -0.208950648722716*(T[pos]+40)+4.641588833612773)
+	pos=numpy.nonzero(numpy.logical_and(-35<=T,T<-30))
+	rigidity[pos]=10**8*(-0.000423888728124*(T[pos]+35)**3+ 0.007571057072334*(T[pos]+35)**2  -0.163864233449525*(T[pos]+35)+3.684031498640382)
+	pos=numpy.nonzero(numpy.logical_and(-30<=T,T<-25))
+	rigidity[pos]=10**8*(0.000147154327025*(T[pos]+30)**3+ 0.001212726150476*(T[pos]+30)**2  -0.119945317335478*(T[pos]+30)+3.001000667185614)
+	pos=numpy.nonzero(numpy.logical_and(-25<=T,T<-20))
+	rigidity[pos]=10**8*(-0.000193435838672*(T[pos]+25)**3+ 0.003420041055847*(T[pos]+25)**2  -0.096781481303861*(T[pos]+25)+2.449986525148220)
+	pos=numpy.nonzero(numpy.logical_and(-20<=T,T<-15))
+	rigidity[pos]=10**8*(0.000219771255067*(T[pos]+20)**3+  0.000518503475772*(T[pos]+20)**2  -0.077088758645767*(T[pos]+20)+2.027400665191131)
+	pos=numpy.nonzero(numpy.logical_and(-15<=T,T<-10))
+	rigidity[pos]=10**8*(-0.000653438900191*(T[pos]+15)**3+ 0.003815072301777*(T[pos]+15)**2  -0.055420879758021*(T[pos]+15)+1.682390865739973)
+	pos=numpy.nonzero(numpy.logical_and(-10<=T,T<-5))
+	rigidity[pos]=10**8*(0.000692439419762*(T[pos]+10)**3 -0.005986511201093 *(T[pos]+10)**2 -0.066278074254598*(T[pos]+10)+1.418983411970382)
+	pos=numpy.nonzero(numpy.logical_and(-5<=T,T<-2))
+	rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+5)**3 +0.004400080095332*(T[pos]+5)**2    -0.074210229783403*(T[pos]+5)+ 1.024485188140279)
+	pos=numpy.nonzero(-2<=T)
+	rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2    -0.051381363322371*(T[pos]+2)+ 0.837883605537096)
+
+	#Now make sure that rigidity is positive
+	pos=numpy.nonzero(rigidity<0)
+	rigidity[pos]=1**6 
+
+	return rigidity
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.m	(revision 18231)
@@ -0,0 +1,42 @@
+function rigidity=paterson(temperature)
+%PATERSON - figure out the rigidity of ice for a given temperature
+%
+%   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 any(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+%The routine below is equivalent to:
+
+% n=3; T=temperature-273;
+% %From paterson,
+% Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+% A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+% 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+% %Convert into rigidity B
+% B=A.^(-1/n)*10^3; %s^(1/3)Pa
+% %Now, do a cubic fit between Temp and B: 
+% fittedmodel=fit(Temp,B,'cubicspline');
+% rigidity=fittedmodel(temperature);
+
+rigidity=zeros(length(T),1);
+pos1=find(T<=-45);           rigidity(pos1)=10^8*(-0.000292866376675*(T(pos1)+50).^3+ 0.011672640664130*(T(pos1)+50).^2  -0.325004442485481*(T(pos1)+50)+  6.524779401948101);
+pos2=find(-45<=T & T<-40);   rigidity(pos2)=10^8*(-0.000292866376675*(T(pos2)+45).^3+ 0.007279645014004*(T(pos2)+45).^2  -0.230243014094813*(T(pos2)+45)+  5.154964909039554);
+pos3=find(-40<=T & T<-35);   rigidity(pos3)=10^8*(0.000072737147457*(T(pos3)+40).^3+  0.002886649363879*(T(pos3)+40).^2  -0.179411542205399*(T(pos3)+40)+  4.149132666831214);
+pos4=find(-35<=T & T<-30);   rigidity(pos4)=10^8*(-0.000086144770023*(T(pos4)+35).^3+ 0.003977706575736*(T(pos4)+35).^2  -0.145089762507325*(T(pos4)+35)+  3.333333333333331);
+pos5=find(-30<=T & T<-25);   rigidity(pos5)=10^8*(-0.000043984685769*(T(pos5)+30).^3+ 0.002685535025386*(T(pos5)+30).^2  -0.111773554501713*(T(pos5)+30)+  2.696559088937191);
+pos6=find(-25<=T & T<-20);   rigidity(pos6)=10^8*(-0.000029799523463*(T(pos6)+25).^3+ 0.002025764738854*(T(pos6)+25).^2  -0.088217055680511*(T(pos6)+25)+  2.199331606342181);
+pos7=find(-20<=T & T<-15);   rigidity(pos7)=10^8*(0.000136920904777*(T(pos7)+20).^3+  0.001578771886910*(T(pos7)+20).^2  -0.070194372551690*(T(pos7)+20)+  1.805165505978111);
+pos8=find(-15<=T & T<-10);   rigidity(pos8)=10^8*(-0.000899763781026*(T(pos8)+15).^3+ 0.003632585458564*(T(pos8)+15).^2  -0.044137585824322*(T(pos8)+15)+  1.510778053489523);
+pos9=find(-10<=T & T<-5);    rigidity(pos9)=10^8*(0.001676964325070*(T(pos9)+10).^3-  0.009863871256831*(T(pos9)+10).^2  -0.075294014815659*(T(pos9)+10)+  1.268434288203714);
+pos10=find(-5<=T & T<-2);    rigidity(pos10)=10^8*(-0.003748937622487*(T(pos10)+5).^3+0.015290593619213*(T(pos10)+5).^2  -0.048160403003748*(T(pos10)+5)+  0.854987973338348);
+pos11=find(-2<=T);           rigidity(pos11)=10^8*(-0.003748937622488*(T(pos11)+2).^3-0.018449844983174*(T(pos11)+2).^2  -0.057638157095631*(T(pos11)+2)+  0.746900791092860);
+
+%Now make sure that rigidity is positive
+pos=find(rigidity<0);        rigidity(pos)=10^6;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/materials/paterson.py	(revision 18231)
@@ -0,0 +1,79 @@
+import numpy
+
+def paterson(temperature):
+	"""
+	PATERSON - figure out the rigidity of ice for a given temperature
+
+	   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)")
+
+	if numpy.ndim(temperature)==2:
+		#T = temperature.reshape(-1,)-273.15
+		T = temperature.flatten()-273.15
+	elif isinstance(temperature,float) or isinstance(temperature,int):
+		T = numpy.array([temperature])-273.15
+	else:
+		T = temperature-273.15
+
+	#The routine below is equivalent to:
+
+	# n=3; T=temperature-273;
+	# %From paterson,
+	# Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+	# A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+	# 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+	# %Convert into rigidity B
+	# B=A.^(-1/n)*10^3; %s^(1/3)Pa
+	# %Now, do a cubic fit between Temp and B: 
+	# fittedmodel=fit(Temp,B,'cubicspline');
+	# rigidity=fittedmodel(temperature);
+
+	rigidity=numpy.zeros_like(T)
+	pos1=numpy.nonzero(T<=-45)[0]
+	if len(pos1):
+		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))[0]
+	if len(pos2):
+		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))[0]
+	if len(pos3):
+		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))[0]
+	if len(pos4):
+		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))[0]
+	if len(pos5):
+		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))[0]
+	if len(pos6):
+		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))[0]
+	if len(pos7):
+		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))[0]
+	if len(pos8):
+		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))[0]
+	if len(pos9):
+		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))[0]
+	if len(pos10):
+		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)[0]
+	if len(pos11):
+		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=numpy.nonzero(rigidity<0)[0]
+	if len(pos):
+		rigidity[pos]=1.e6 
+
+	return rigidity
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.m	(revision 18231)
@@ -0,0 +1,105 @@
+function [damage,B,backstress]=analyticaldamage(md,varargin)
+%ANALYTICALDAMAGE - compute damage for an ice shelf 
+%
+%	 This routine computes damage as a function of water/ice
+%	 material properties, ice thickness, strain rate, and ice 
+%	 rigidity.  The model must contain computed strain rates,
+%	 either from observed or modeled ice velocities.
+%
+%   Available options:
+%		- 'eq'			: analytical equation to use in the calculation.  Must be one of:
+%								'Weertman1D' for a confined ice shelf free to flow in one direction
+%								'Weertman2D' for an unconfined ice shelf free to spread in any direction
+%								'Thomas' for a 2D ice shelf, taking into account full strain rate tensor (default)
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'sigmab'		: a-priori backstress in opposition to the driving stress.
+%								Defaults to 0 everywhere. 
+
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values:
+%		'damage' which is truncated in the range [0,1-1e-9]
+%
+%	   'B' is the ice rigidity calculated assuming D=0 everywhere. 
+%
+%		'backstress' is the inferred backstress necessary to balance the
+%		analytical solution (keeping damage within its appropriate limits, e.g. D
+%		in [0,1]).
+%
+%   Usage:
+%      [damage,B,backstress]=analyticaldamage(md,options)
+%
+%   Example:
+%      [damage,B,backstress]=analyticaldamage(md,'eq','Weertman2D','smoothing',2,'sigmab',10e3,'coordsys','longitudinal');
+
+% check inputs
+if (nargin<1),
+	help analyticaldamage
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+eq = getfieldvalue(options,'eq','Thomas');
+smoothing = getfieldvalue(options,'smoothing',0);
+sigmab = getfieldvalue(options,'sigmab',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+if length(sigmab)==1,
+	sigmab=sigmab*ones(md.mesh.numberofvertices,1);
+end
+
+[a,b,theta,ex]=thomasparams(md,'eq',eq,'smoothing',smoothing,'coordsys',coordsys);
+
+% spreading stress
+rhoi=md.materials.rho_ice;
+rhow=md.materials.rho_water;
+C=0.5*rhoi*md.constants.g*(1-rhoi/rhow);
+T=C*md.geometry.thickness;
+
+% rheology
+B=md.materials.rheology_B;
+n=averaging(md,md.materials.rheology_n,0);
+
+D=1-(1+a+a.^2+b.^2).^((n-1)./(2*n))./abs(ex).^(1./n).*(T-sigmab)./B./(2+a)./sign(ex);
+
+% D>1 where (2+a).*sign(ex)<0, compressive regions where high backstress needed
+pos=find(D>1);
+D(pos)=0;
+
+backstress=zeros(md.mesh.numberofvertices,1);
+
+% backstress to bring D down to one 
+backstress(pos)=T(pos)-(1-D(pos)).*B(pos).*sign(ex(pos)).*(2+a(pos)).*abs(ex(pos)).^(1./n(pos))./(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos));
+
+pos=find(D<0);
+mask=ismember(1:md.mesh.numberofvertices,pos);
+D(pos)=0;
+
+% backstress to bring negative damage to zero
+backstress(pos)=T(pos)-(1-D(pos)).*B(pos).*sign(ex(pos)).*(2+a(pos)).*abs(ex(pos)).^(1./n(pos))./(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos));
+
+pos=find(backstress<0);
+backstress(pos)=0;
+
+% rigidity from Thomas relation for D=0 and backstress=0
+B=sign(ex)./(2+a).*(1+a+a.^2).^((n-1)/2./n).*T./(abs(ex).^(1./n));
+pos=find(B<0);
+B(pos)=md.materials.rheology_B(pos);
+
+damage=D;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/analyticaldamage.py	(revision 18231)
@@ -0,0 +1,106 @@
+import numpy as npy
+from averaging import averaging
+#from plotmodel import plotmodel
+from thomasparams import thomasparams
+
+def analyticaldamage(md,**kwargs):
+	'''
+	ANALYTICALDAMAGE - compute damage for an ice shelf 
+	
+		 This routine computes damage as a function of water/ice
+		 material properties, ice thickness, strain rate, and ice 
+		 rigidity.  The model must contain computed strain rates,
+		 either from observed or modeled ice velocities.
+	
+	   Available options:
+			-eq			: analytical equation to use in the calculation.  Must be one of:
+									'Weertman1D' for a confined ice shelf free to flow in one direction
+									'Weertman2D' for an unconfined ice shelf free to spread in any direction
+									'Thomas' for a 2D ice shelf, taking into account full strain rate tensor (default)
+			-smoothing	: the amount of smoothing to be applied to the strain rate data.
+									Type 'help averaging' for more information on its usage.
+			-coordsys	: coordinate system for calculating the strain rate
+						components. Must be one of:
+			-sigmab		: a compressive backstress term to be subtracted from the driving stress 
+									in the damage calculation
+	
+	   Return values:
+			'damage' which is truncated in the range [0,1-1e-9]
+	
+		   'B' is the rigidity, which is equal to md.materials.rheology_B in areas outside
+			those defined by 'mask.'  Within areas defined by 'mask,' where negative damage 
+			is inferred, 'B' is updated to make damage equal to zero.  
+	
+			'backstress' is the inferred backstress necessary to balance the analytical solution
+			(keeping damage within its appropriate limits, e.g. D in [0,1]).
+	
+	   Usage:
+	      damage,B,backstress=analyticaldamage(md,kwargs)
+	
+	   Example:
+	      damage,B,backstress=analyticaldamage(md,eq='Weertman2D',smoothing=2,sigmab=10e3)
+	'''
+
+	#unpack kwargs
+	eq=kwargs.pop('eq','Thomas')
+	if 'eq' in kwargs: del kwargs['eq']
+	smoothing=kwargs.pop('smoothing',0)
+	if 'smoothing' in kwargs: del kwargs['smoothing']
+	coordsys=kwargs.pop('coordsys','longitudinal')
+	if 'coordsys' in kwargs: del kwargs['coordsys']
+	sigmab=kwargs.pop('sigmab',0)
+	if 'sigmab' in kwargs: del kwargs['sigmab']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	if isinstance(sigmab,(int,float)):
+		sigmab=sigmab*npy.ones((md.mesh.numberofvertices,))
+
+	# check inputs
+	if 'strainrate' not in md.results.__dict__:
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if npy.any(md.flowequation.element_equation!=2):
+		print 'Warning: the model has some non SSA elements. These will be treated like SSA elements'
+
+	a,b,theta,ex=thomasparams(md,eq=eq,smoothing=smoothing,coordsys=coordsys)
+	
+	# spreading stress
+	rhoi=md.materials.rho_ice
+	rhow=md.materials.rho_water
+	C=0.5*rhoi*md.constants.g*(1.-rhoi/rhow)
+	T=C*md.geometry.thickness
+	
+	# rheology
+	B=md.materials.rheology_B
+	n=averaging(md,md.materials.rheology_n,0)
+	
+	D=1.-(1.+a+a**2+b**2)**((n-1.)/(2.*n))/npy.abs(ex)**(1./n)*(T-sigmab)/B/(2.+a)/npy.sign(ex)
+	
+	# D>1 where (2+a).*sign(ex)<0, compressive regions where high backstress needed
+	pos=npy.nonzero(D>1)
+	D[pos]=0
+	
+	backstress=npy.zeros((md.mesh.numberofvertices,))
+
+	# backstress to bring D down to one 
+	backstress[pos]=T[pos]-(1.-D[pos])*B[pos]*npy.sign(ex[pos])*(2.+a[pos])*npy.abs(ex[pos])**(1./n[pos])/(1.+a[pos]+a[pos]**2)**((n[pos]-1.)/2./n[pos])
+	
+	pos=npy.nonzero(D<0)
+	#mask=ismember(1:md.mesh.numberofvertices,pos);
+	D[pos]=0
+	
+	# backstress to bring negative damage to zero
+	backstress[pos]=T[pos]-(1.-D[pos])*B[pos]*npy.sign(ex[pos])*(2.+a[pos])*npy.abs(ex[pos])**(1./n[pos])/(1.+a[pos]+a[pos]**2)**((n[pos]-1.)/2./n[pos])
+	
+	pos=npy.nonzero(backstress<0)
+	backstress[pos]=0
+	
+	# rigidity from Thomas relation for D=0 and backstress=0
+	B=npy.sign(ex)/(2.+a)*(1.+a+a**2)**((n-1.)/2./n)*T/(npy.abs(ex)**(1./n))
+	pos=npy.nonzero(B<0)
+	B[pos]=md.materials.rheology_B[pos]
+	
+	damage=D
+	
+	return damage, B, backstress
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.m	(revision 18231)
@@ -0,0 +1,70 @@
+function backstress=backstressfrominversion(md,varargin)
+%BACKSTRESSFROMINVERSION - compute ice shelf backstress from inversion results 
+%
+%	 This routine computes backstress based on the analytical formalism of
+%	 Thomas (1973) and Borstad et al. (2013).  The model must contain inversion
+%	 results for ice rigidity.  Strain rates must also be included, either from
+%	 observed or modeled velocities.  Ice rigidity B is assumed to be
+%	 parameterized by the ice temperature in md.materials.rheology_B.
+%
+%   Available options:
+%		- 'tempmask'	: mask the inverted rigidity to be no more than
+%							appropriate for the temperature of the ice?  
+%							Boolean, defaults to false.
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values:
+%		'backstress' is the inferred backstress based on the analytical
+%		solution for ice shelf creep
+%
+%   Usage:
+%      backstress=backstressfrominversion(md,options)
+%
+%   Example:
+%      backstress=backstressfrominversion(md,'smoothing',2,'coordsys','longitudinal','tempmask',true);
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+tempmask = getfieldvalue(options,'tempmask',false);
+
+T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness;
+n=averaging(md,md.materials.rheology_n,0);
+B=md.materials.rheology_B;
+Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar;
+
+[a0,b0,theta0,ex0]=thomasparams(md,'eq','Thomas','smoothing',smoothing,'coordsys',coordsys);
+
+if tempmask
+	Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar;
+   pos=find(Bi>md.materials.rheology_B);
+   Bi(pos)=md.materials.rheology_B(pos);
+end
+
+% analytical backstress solution
+backstress=T-Bi.*sign(ex0).*(2+a0).*abs(ex0).^(1./n)./((1+a0+a0.^2+b0.^2).^((n-1)/2./n));
+backstress(find(backstress<0))=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/backstressfrominversion.py	(revision 18231)
@@ -0,0 +1,74 @@
+import numpy as npy
+from averaging import averaging
+from thomasparams import thomasparams
+
+def backstressfrominversion(md,**kwargs):
+	'''
+	Compute ice shelf backstress from inversion results.
+
+	This routine computes backstress based on the analytical formalism of
+	Thomas (1973) and Borstad et al. (2013, The Cryosphere).  The model
+	must contain inversion results for ice rigidity.  Strain rates must
+	also be included, either from observed or modeled velocities.  Ice
+	rigidity B is assumed to be parameterized by the ice temperature in
+	md.materials.rheology_B.
+
+   Available options:
+		- 'tempmask'	: mask the inverted rigidity to be no more than
+							appropriate for the temperature of the ice?  
+							Boolean, defaults to false.
+		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+								Type 'help averaging' for more information on its
+								usage. Defaults to 0.
+		- 'coordsys'	: coordinate system for calculating the strain rate
+							components. Must be one of: 
+				'longitudinal': x axis aligned along a flowline at every point (default)
+				'principal': x axis aligned along maximum principal strain rate
+					at every point
+				'xy': x and y axes same as in polar stereographic projection 
+
+   Return values:
+		'backstress' is the inferred backstress based on the analytical
+		solution for ice shelf creep
+
+   Usage:
+      backstress=backstressfrominversion(md,options)
+
+   Example:
+      backstress=backstressfrominversion(md,'smoothing',2,'coordsys','longitudinal','tempmask',true);
+	'''
+
+	# unpack kwargs
+	tempmask=kwargs.pop('tempmask',False)
+	if 'tempmask' in kwargs: del kwargs['maxiter']
+	smoothing=kwargs.pop('smoothing',0)
+	if 'smoothing' in kwargs: del kwargs['smoothing']
+	coordsys=kwargs.pop('coordsys','longitudinal')
+	if 'coordsys' in kwargs: del kwargs['coordsys']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	# some checks
+	if not hasattr(md.results,'strainrate'):
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if any(md.flowequation.element_equation!=2):
+		raise StandardError('Warning: the model has some non-SSA elements.  These will be treated like SSA elements')
+
+	T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness
+	n=averaging(md,md.materials.rheology_n,0)
+	B=md.materials.rheology_B
+	Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar.reshape(-1,)
+	
+	a0,b0,theta0,ex0=thomasparams(md,eq='Thomas',smoothing=smoothing,coordsys=coordsys)
+	
+	if tempmask:
+		Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar
+		pos=npy.nonzero(Bi>md.materials.rheology_B)
+		Bi[pos]=md.materials.rheology_B[pos]
+	
+	# analytical backstress solution
+	backstress=T-Bi*npy.sign(ex0)*(2+a0)*npy.abs(ex0)**(1./n)/((1+a0+a0**2+b0**2)**((n-1.)/2./n))
+	backstress[npy.nonzero(backstress<0)]=0
+
+	return backstress
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/basalstress.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/basalstress.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/basalstress.m	(revision 18231)
@@ -0,0 +1,23 @@
+function [bx by b]=basalstress(md)
+%BASALSTRESS - compute basal stress from basal drag and geometric information. 
+%
+%      Computes basal stress from geometric information and ice velocity in md.initialization.
+%
+%   Usage:
+%      [bx by b]=basalstress(md);
+%
+%   See also: plot_basaldrag
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+ubx=md.initialization.vx/md.constants.yts;
+uby=md.initialization.vy/md.constants.yts;
+
+%compute basal drag
+bx=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*ubx.^s;
+by=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*uby.^s;
+b=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*ub.^s;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.m	(revision 18231)
@@ -0,0 +1,64 @@
+function backstress=calcbackstress(md,varargin)
+%BACKSTRESSFROMINVERSION - compute ice shelf backstress  
+%
+%	 This routine computes backstress based on the analytical formalism of
+%	 Thomas (1973) and Borstad et al. (2013) based on the ice rigidity,
+%	 thickness, the densities of ice and seawater, and (optionally)
+%	 damage. Strain rates must also be included, either from observed or
+%	 modeled velocities.
+
+%   Available options:
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values:
+%		'backstress' is the inferred backstress based on the analytical
+%		solution for ice shelf creep
+%
+%   Usage:
+%      backstress=calcbackstress(md,options)
+%
+%   Example:
+%      backstress=backstressfrominversion(md,'smoothing',2,'coordsys','longitudinal');
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+tempmask = getfieldvalue(options,'tempmask',false);
+
+T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness;
+n=averaging(md,md.materials.rheology_n,0);
+B=md.materials.rheology_B;
+if md.damage.isdamage,
+	D=md.damage.D
+else
+	D=0.
+
+[a0,b0,theta0,ex0]=thomasparams(md,'eq','Thomas','smoothing',smoothing,'coordsys',coordsys);
+
+% analytical backstress solution
+backstress=T-(1.-D).*B.*sign(ex0).*(2+a0).*abs(ex0).^(1./n)./((1+a0+a0.^2+b0.^2).^((n-1)/2./n));
+backstress(find(backstress<0))=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/calcbackstress.py	(revision 18231)
@@ -0,0 +1,66 @@
+import numpy as npy
+from averaging import averaging
+from thomasparams import thomasparams
+
+def calcbackstress(md,**kwargs):
+	'''
+	Compute ice shelf backstress.
+
+	This routine computes backstress based on the analytical formalism of
+	Thomas (1973) and Borstad et al. (2013, The Cryosphere) based on the
+	ice rigidity, thickness, the densities of ice and seawater, and
+	(optionally) damage.  Strain rates must also be included, either from
+	observed or modeled velocities. 
+	
+	Available options:
+		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+								Type 'help averaging' for more information on its
+								usage. Defaults to 0.
+		- 'coordsys'	: coordinate system for calculating the strain rate
+							components. Must be one of: 
+				'longitudinal': x axis aligned along a flowline at every point (default)
+				'principal': x axis aligned along maximum principal strain rate
+					at every point
+				'xy': x and y axes same as in polar stereographic projection 
+
+   Return values:
+		'backstress' is the inferred backstress based on the analytical
+		solution for ice shelf creep
+
+   Usage:
+      backstress=calcbackstress(md,options)
+
+   Example:
+      backstress=calcbackstress(md,'smoothing',2,'coordsys','longitudinal')
+	'''
+
+	# unpack kwargs
+	smoothing=kwargs.pop('smoothing',0)
+	if 'smoothing' in kwargs: del kwargs['smoothing']
+	coordsys=kwargs.pop('coordsys','longitudinal')
+	if 'coordsys' in kwargs: del kwargs['coordsys']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	# some checks
+	if not hasattr(md.results,'strainrate'):
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if any(md.flowequation.element_equation!=2):
+		raise StandardError('Warning: the model has some non-SSA elements.  These will be treated like SSA elements')
+
+	T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness
+	n=averaging(md,md.materials.rheology_n,0)
+	B=md.materials.rheology_B
+	if md.damage.isdamage:
+		D=md.damage.D
+	else:
+		D=0.
+	
+	a0,b0,theta0,ex0=thomasparams(md,eq='Thomas',smoothing=smoothing,coordsys=coordsys)
+	
+	# analytical backstress solution
+	backstress=T-(1.-D)*B*npy.sign(ex0)*(2+a0)*npy.abs(ex0)**(1./n)/((1+a0+a0**2+b0**2)**((n-1.)/2./n))
+	backstress[npy.nonzero(backstress<0)]=0
+
+	return backstress
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/cfl_step.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/cfl_step.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/cfl_step.m	(revision 18231)
@@ -0,0 +1,23 @@
+function maxtime=cfl_step(md,vx,vy)
+%CFL_STEP - return the maximum time step for the model in years
+%
+%   Dt < 0.5 / ( u/Dx +v/Dy )
+%
+%   Usage:
+%      maxtime=cfl_step(md,vx,vy);
+%
+%   Example:
+%      dt=cfl_step(md,md.results.StressbalanceSolution.Vx,md.results.StressbalanceSolution.Vy)
+
+%Check length of velocities 
+if size(vx,1)~=md.mesh.numberofvertices & size(vy,1)~=md.mesh.numberofvertices,
+	error('timestpes error message: size of velocity components must be the same as md.mesh.numberofvertices');
+end
+
+index=md.mesh.elements;
+edgex=max(md.mesh.x(index),[],2)-min(md.mesh.x(index),[],2);
+edgey=max(md.mesh.y(index),[],2)-min(md.mesh.y(index),[],2);
+vx=max(abs(vx(index)),[],2);
+vy=max(abs(vy(index)),[],2);
+
+maxtime=1/2*min(1./(vx./edgex+vy./edgey));
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.m	(revision 18231)
@@ -0,0 +1,33 @@
+function damage=damagefrominversion(md)
+%DAMAGEFROMINVERSION - compute ice shelf damage from inversion results
+%
+%	This routine computes damage based on the analytical formalism of Borstad et
+%	al. (2013).  The model must contain inversion results for ice rigidity.  Ice
+%	rigidity B is assumed to be parameterized by the ice temperature in
+%	md.materials.rheology_B. 
+%
+%	Usage:
+%		damage=damagefrominversion(md)
+%
+%	Example:
+%		damage=damagefrominversion(md)
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+damage=zeros(md.mesh.numberofvertices,1);
+% Damage where Bi softer than B(T)
+pos=find(md.results.StressbalanceSolution.MaterialsRheologyBbar<md.materials.rheology_B);
+damage(pos)=1-md.results.StressbalanceSolution.MaterialsRheologyBbar(pos)./md.materials.rheology_B(pos);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/damagefrominversion.py	(revision 18231)
@@ -0,0 +1,44 @@
+import numpy as npy
+
+def damagefrominversion(md):
+	'''
+	compute ice shelf damage from inversion results
+
+	This routine computes damage based on the analytical formalism of Borstad et
+	al. (2013, The Cryosphere).  The model must contain inversion results for
+	ice rigidity.  Ice rigidity B is assumed to be parameterized by the ice
+	temperature in md.materials.rheology_B. 
+	
+	Usage:
+		damage=damagefrominversion(md)
+	
+	Example:
+		damage=damagefrominversion(md)
+	'''
+
+	# check inputs
+	if not hasattr(md.results,'strainrate'):
+		raise StandardError('md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if any(md.flowequation.element_equation!=2):
+		raise StandardError('Warning: the model has some non-SSA elements.  These will be treated like SSA elements')
+	if npy.ndim(md.results.StressbalanceSolution.MaterialsRheologyBbar)==2:
+		Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar.reshape(-1,)
+	else:
+		Bi=md.results.StressbalanceSolution.MaterialsRheologyBbar
+	if npy.ndim(md.materials.rheology_B)==2:
+		BT=md.materials.rheology_B.reshape(-1,)
+	else:
+		BT=md.materials.rheology_B
+
+	damage=npy.zeros_like(Bi)
+
+	# Damage where Bi softer than B(T)
+	pos=npy.nonzero(Bi<BT)[0]
+	damage[pos]=1.-Bi[pos]/BT[pos]
+	
+	pos=npy.nonzero(damage<0)
+	damage[pos]=0
+
+	return damage
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/drivingstress.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/drivingstress.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/drivingstress.m	(revision 18231)
@@ -0,0 +1,18 @@
+function [px,py,pmag]=drivingstress(md)
+%DRIVINGSTRESS -  evaluates the driving stress
+%
+%   The driving stress is computed according to the following formula: 
+%   driving stress= rho_ice*g*H*slope
+%
+%   Usage:
+%      [Fx,Fy,Fmag]=drivingstress(md)
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness over elements
+thickness_bar=(md.geometry.thickness(md.mesh.elements(:,1))+md.geometry.thickness(md.mesh.elements(:,2))+md.geometry.thickness(md.mesh.elements(:,3)))/3;
+
+px=md.materials.rho_ice*md.constants.g*thickness_bar.*sx;
+py=md.materials.rho_ice*md.constants.g*thickness_bar.*sy;
+pmag=sqrt(px.^2+py.^2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.m	(revision 18231)
@@ -0,0 +1,146 @@
+function md=mechanicalproperties(md,vx,vy)
+%MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+%
+%   this routine computes the components of the (deviatoric) stress tensor,
+%   the strain rate tensor, and their respective principal directions.
+%   The results are in the model md: md.results
+%
+%   Usage:
+%      md=mechanicalproperties(md,vx,vy)
+%
+%   Example:
+%      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy);
+%      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs);
+
+%some checks
+if length(vx)~=md.mesh.numberofvertices | length(vy)~=md.mesh.numberofvertices,
+	%error(['the input velocity should be of size ' num2str(md.mesh.numberofvertices) '!'])
+end
+if dimension(md.mesh)~=2
+	error('only 2d model supported yet');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA''s elements');
+end
+
+%initialization
+numberofelements=md.mesh.numberofelements;
+index=md.mesh.elements;
+summation=[1;1;1];
+directionsstress=zeros(numberofelements,4);
+directionsstrain=zeros(numberofelements,4);
+valuesstress=zeros(numberofelements,2);
+valuesstrain=zeros(numberofelements,2);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y);
+
+%compute shear
+vxlist=vx(index)/md.constants.yts;
+vylist=vy(index)/md.constants.yts;
+ux=(vxlist.*alpha)*summation;
+uy=(vxlist.*beta)*summation;
+vx=(vylist.*alpha)*summation;
+vy=(vylist.*beta)*summation;						
+uyvx=(vx+uy)./2;
+clear vxlist vylist
+
+%compute viscosity
+nu=zeros(numberofelements,1);
+B_bar=md.materials.rheology_B(index)*summation/3;
+power=(md.materials.rheology_n-1)./(2*md.materials.rheology_n);
+second_inv=(ux.^2+vy.^2+((uy+vx).^2)/4+ux.*vy);
+
+%some corrections
+location=find(second_inv==0 & power~=0);
+nu(location)=10^18; 	%arbitrary maximum viscosity to apply where there is no effective shear
+
+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
+
+%compute stress
+tau_xx=nu.*ux;
+tau_yy=nu.*vy;
+tau_xy=nu.*uyvx;
+
+%compute principal properties of stress
+for i=1:numberofelements,
+
+	%compute stress and strainrate matrices
+	stress=[tau_xx(i) tau_xy(i)
+	tau_xy(i)  tau_yy(i)];
+	strain=[ux(i) uyvx(i)
+	uyvx(i)  vy(i)];
+
+	%eigen values and vectors
+	[directions,value]=eig(stress);
+	%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(:)';
+end
+
+%plug onto the model
+%NB: Matlab sorts the eigen value in increasing order, we want the reverse
+%NOTE: all stresses below are deviatoric
+stress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+stress.xx=tau_xx;
+stress.yy=tau_yy;
+stress.xy=tau_xy;
+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); % effective shear stress (sqrt(J2))
+md.results.stress=stress;
+
+strainrate=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+strainrate.xx=ux*md.constants.yts; %strain rate in 1/a instead of 1/s
+strainrate.yy=vy*md.constants.yts; 
+strainrate.xy=uyvx*md.constants.yts; 
+strainrate.principalvalue1=valuesstrain(:,1)*md.constants.yts; 
+strainrate.principalaxis1=directionsstrain(:,1:2);
+strainrate.principalvalue2=valuesstrain(:,2)*md.constants.yts; 
+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;
+
+%exact same stress as above
+deviatoricstress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+deviatoricstress.xx=tau_xx;
+deviatoricstress.yy=tau_yy;
+deviatoricstress.xy=tau_xy;
+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;
+
+viscosity=struct('nu',[]);
+viscosity.nu=nu;
+md.results.viscosity=viscosity;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/mechanicalproperties.py	(revision 18231)
@@ -0,0 +1,151 @@
+import numpy as npy
+from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
+from results import results
+from averaging import averaging
+
+def mechanicalproperties(md,vx,vy):
+	"""
+	MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+	
+   this routine computes the components of the stress tensor
+   strain rate tensor and their respective principal directions.
+   the results are in the model md: md.results
+	
+   Usage:
+      md=mechanicalproperties(md,vx,vy)
+	
+   Example:
+      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy)
+      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs)
+	"""
+
+	#some checks
+	if len(vx)!=md.mesh.numberofvertices or len(vy)!=md.mesh.numberofvertices:
+		raise ValueError('the input velocity should be of size ' + md.mesh.numberofvertices)
+	
+	#if md.mesh.dimension!=2:
+	#	raise StandardError('only 2D model supported currently')
+
+	if npy.any(md.flowequation.element_equation!=2):
+		print 'Warning: the model has some non SSA elements. These will be treated like SSA elements'
+
+	if npy.ndim(vx)==2:
+		vx=vx.reshape(-1,)
+	if npy.ndim(vy)==2:
+		vy=vy.reshape(-1,)
+	
+	#initialization
+	numberofelements=md.mesh.numberofelements
+	numberofvertices=md.mesh.numberofvertices
+	index=md.mesh.elements
+	summation=npy.array([[1],[1],[1]])
+	directionsstress=npy.zeros((numberofelements,4))
+	directionsstrain=npy.zeros((numberofelements,4))
+	valuesstress=npy.zeros((numberofelements,2))
+	valuesstrain=npy.zeros((numberofelements,2))
+	
+	#compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+	alpha,beta=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y)[0:2]
+	
+	#compute shear
+	vxlist=vx[index-1]/md.constants.yts
+	vylist=vy[index-1]/md.constants.yts
+	ux=npy.dot((vxlist*alpha),summation).reshape(-1,)
+	uy=npy.dot((vxlist*beta),summation).reshape(-1,)
+	vx=npy.dot((vylist*alpha),summation).reshape(-1,)
+	vy=npy.dot((vylist*beta),summation).reshape(-1,)
+	uyvx=(vx+uy)/2.
+	#clear vxlist vylist
+	
+	#compute viscosity
+	nu=npy.zeros((numberofelements,))
+	B_bar=npy.dot(md.materials.rheology_B[index-1],summation/3.).reshape(-1,)
+	power=((md.materials.rheology_n-1.)/(2.*md.materials.rheology_n)).reshape(-1,)
+	second_inv=(ux**2.+vy**2.+((uy+vx)**2.)/4.+ux*vy).reshape(-1,)
+	
+	#some corrections
+	location=npy.nonzero(npy.logical_and(second_inv==0,power!=0))
+	nu[location]=10^18 	#arbitrary maximum viscosity to apply where there is no effective shear
+	
+	if 'matice' in md.materials.__module__:
+		location=npy.nonzero(second_inv)
+		nu[location]=B_bar[location]/(second_inv[location]**power[location])
+		location=npy.nonzero(npy.logical_and(second_inv==0,power==0))
+		nu[location]=B_bar[location]
+		location=npy.nonzero(npy.logical_and(second_inv==0,power!=0))
+		nu[location]=10^18
+	elif 'matdamageice' in md.materials.__module__:
+		print 'computing damage-dependent properties!'
+		Zinv=npy.dot(1-md.damage.D[index-1],summation/3.).reshape(-1,)
+		location=npy.nonzero(second_inv)
+		nu[location]=Zinv[location]*B_bar[location]/npy.power(second_inv[location],power[location])
+		location=npy.nonzero(npy.logical_and(second_inv==0,power==0))
+		nu[location]=Zinv[location]*B_bar[location]
+		#clear Zinv
+	else:
+		raise StandardError('class of md.materials (' + md.materials.__module__ + ') not recognized or not supported')
+	
+	#compute stress
+	tau_xx=nu*ux
+	tau_yy=nu*vy
+	tau_xy=nu*uyvx
+	
+	#compute principal properties of stress
+	for i in npy.arange(numberofelements):
+	
+		#compute stress and strainrate matrices
+		stress=npy.array([ [tau_xx[i], tau_xy[i]], [tau_xy[i], tau_yy[i]] ])
+		strain=npy.array([ [ux[i], uyvx[i]], [uyvx[i], vy[i]] ])
+	
+		#eigenvalues and vectors for stress
+		value,directions=npy.linalg.eig(stress);
+		idx=abs(value).argsort()[::-1] # sort in descending order
+		value=value[idx]
+		directions=directions[:,idx]
+		valuesstress[i,:]=[value[0],value[1]]
+		directionsstress[i,:]=directions.transpose().flatten()
+
+		#eigenvalues and vectors for strain
+		value,directions=npy.linalg.eig(strain);
+		idx=abs(value).argsort()[::-1] # sort in descending order
+		value=value[idx]
+		directions=directions[:,idx]
+		valuesstrain[i,:]=[value[0],value[1]]
+		directionsstrain[i,:]=directions.transpose().flatten()
+
+	##plug onto the model
+	##NB: Matlab sorts the eigen value in increasing order, we want the reverse
+	stress=results()
+	stress.xx=tau_xx
+	stress.yy=tau_yy
+	stress.xy=tau_xy
+	stress.principalvalue1=valuesstress[:,0]
+	stress.principalaxis1=directionsstress[:,0:2]
+	stress.principalvalue2=valuesstress[:,1]
+	stress.principalaxis2=directionsstress[:,2:4]
+	stress.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
+	md.results.stress=stress
+	
+	strainrate=results()
+	strainrate.xx=ux*md.constants.yts #strain rate in 1/a instead of 1/s
+	strainrate.yy=vy*md.constants.yts 
+	strainrate.xy=uyvx*md.constants.yts 
+	strainrate.principalvalue1=valuesstrain[:,0]*md.constants.yts 
+	strainrate.principalaxis1=directionsstrain[:,0:2]
+	strainrate.principalvalue2=valuesstrain[:,1]*md.constants.yts 
+	strainrate.principalaxis2=directionsstrain[:,2:4]
+	strainrate.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(strainrate.xx**2+strainrate.yy**2+2.*strainrate.xy**2)
+	md.results.strainrate=strainrate
+	
+	deviatoricstress=results()
+	deviatoricstress.xx=tau_xx
+	deviatoricstress.yy=tau_yy
+	deviatoricstress.xy=tau_xy
+	deviatoricstress.principalvalue1=valuesstress[:,0]
+	deviatoricstress.principalaxis1=directionsstress[:,1:2]
+	deviatoricstress.principalvalue2=valuesstress[:,1]
+	deviatoricstress.principalaxis2=directionsstress[:,2:4]
+	deviatoricstress.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
+	md.results.deviatoricstress=deviatoricstress
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.m	(revision 18231)
@@ -0,0 +1,42 @@
+function tprofile=robintemperature(heatflux,accumrate,thickness,surftemp,z)
+%ROBINTEMPERATURE - compute vertical temperature profile of an ice sheet (Robin, 1955)
+%
+%	This routine computes the vertical temperature profile of an 
+%	ice sheet according to the solution of Robin (1955), neglecting 
+%	friction and horizontal advection.  The solution is thus most
+%  appropriate at an ice divide.
+%
+%	The coordinate system for the solution runs from z=0 at the base 
+%	to z=H at the surface of the ice.
+%
+%	Parameters (SI units):
+%		-heatflux	Geothermal heat flux (W m^-2)
+%		-accumrate	Surface accumulation rate (m s^-1 ice equivalent)
+%		-thickness	Ice thickness (m)
+%		-surftemp	Surface temperature (K)
+%		-z				Vertical position at which to calculate temperature
+%						(z can be a scalar or a vector)
+%
+%	Returns a vector the same length as z containing the temperature in K
+%
+%	Usage:
+%		tprofile=robintemperature(heatflux,accumrate,thickness,surftemp,z)
+
+%checks
+if nargin~=5
+	help robintemperature
+	error('bad usage - wrong number of arguments.')
+end
+
+%some constants (from Holland and Jenkins, 1999)
+alphaT=1.14e-6; % thermal diffusivity (m^2 s^-1)
+c=2009; % specific heat capacity (J kg^-1 K^-1)
+rho=917; % ice density (kg m^-3)
+
+%create vertical coordinate variable
+zstar=sqrt(2*alphaT*thickness./accumrate);
+
+tprofile=surftemp+sqrt(2*thickness*pi./accumrate/alphaT).*(-heatflux)/2/rho/c.*(erf(z./zstar)-erf(thickness./zstar));
+
+% difference between surface and base temperature for check (Cuffey2010 p412):
+% tprofile-surftemp
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/robintemperature.py	(revision 18231)
@@ -0,0 +1,42 @@
+import numpy as npy
+from scipy.special import erf
+
+def robintemperature(heatflux,accumrate,thickness,surftemp,z):
+	'''
+	Compute vertical temperature profile of an ice sheet (Robin, 1955)
+
+	This routine computes the vertical temperature profile of an ice sheet
+	according to the solution of Robin (1955), neglecting friction and
+	horizontal advection.  The solution is thus most appropriate at an ice
+	divide.
+
+	The coordinate system for the solution runs from z=0 at the base 
+	to z=H at the surface of the ice.
+
+	Parameters (SI units):
+		-heatflux	Geothermal heat flux (W m^-2)
+		-accumrate	Surface accumulation rate (m s^-1 ice equivalent)
+		-thickness	Ice thickness (m)
+		-surftemp	Surface temperature (K)
+		-z				Vertical position at which to calculate temperature
+						(z can be a scalar or a vector)
+
+	Returns a vector the same length as z containing the temperature in K
+
+	Usage:
+		tprofile=robintemperature(heatflux,accumrate,thickness,surftemp,z)
+	'''
+
+	# some constants (from Holland and Jenkins, 1999)
+	alphaT=1.14e-6 # thermal diffusivity (m^2 s^-1)
+	c=2009. # specific heat capacity (J kg^-1 K^-1)
+	rho=917.  # ice density (kg m^-3)
+	
+	#create vertical coordinate variable
+	zstar=npy.sqrt(2.*alphaT*thickness/accumrate)
+	
+	tprofile=surftemp+npy.sqrt(2.*thickness*npy.pi/accumrate/alphaT)*(-heatflux)/2./rho/c*(erf(z/zstar)-erf(thickness/zstar))
+
+	return tprofile	
+	# difference between surface and base temperature for check (Cuffey2010 p412):
+	# print tprofile-surftemp
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/shear2d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/shear2d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/shear2d.m	(revision 18231)
@@ -0,0 +1,23 @@
+function [sx,sy,sxy,s]=shear2d(md)
+%SHEAR2D - computes 2d strain rate
+%
+%   This routine computes the strain rate of 2d models
+%
+%   Usage:
+%      [sx,sy,sxy,s]=shear2d(md);
+%      s=shear2d(md);
+
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+summation=[1;1;1];
+sx=(md.initialization.vx(md.mesh.elements).*alpha)*summation;
+uy=(md.initialization.vx(md.mesh.elements).*beta)*summation;
+vx=(md.initialization.vy(md.mesh.elements).*alpha)*summation;
+sy=(md.initialization.vy(md.mesh.elements).*beta)*summation;						
+sxy=(uy+vx)/2;
+s=sqrt(sx.^2+sy.^2+sxy.^2+sx.*sy);
+
+%if user requested only one output, it must be the norm
+if nargout==1,
+	sx=s;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.m	(revision 18231)
@@ -0,0 +1,60 @@
+function temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+%STEADYSTATEICESHELFTEMP - compute depth-averaged steady-state temperature of an ice shelf 
+%
+%   This routine computes the depth-averaged temperature accounting for vertical advection 
+%   and diffusion of heat into the base of the ice shelf as a function of surface and 
+%   basal temperature and the basal melting rate.  Horizontal advection is ignored.
+%   The solution is a depth-averaged version of Equation 25 in Holland and Jenkins (1999).
+%
+%	 In addition to supplying md, the surface and basal temperatures of the ice shelf must
+%	 be supplied in degrees Kelvin.
+%
+%	 The model md must also contain the fields: 
+%	 md.geometry.thickness
+%	 md.basalforcings.floatingice_melting_rate (positive for melting, negative for freezing)
+
+%   Usage:
+%      temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+
+if (length(md.geometry.thickness)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: thickness should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%surface and basal temperatures in degrees C
+if (length(surfacetemp)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: surfacetemp should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+if (length(basaltemp)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: basaltemp should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+% Convert temps to Celsius for Holland and Jenkins (1999) equation
+Ts=-273.15+surfacetemp;
+Tb=-273.15+basaltemp;
+
+Hi=md.geometry.thickness;
+ki=1.14e-6*md.constants.yts; % ice shelf thermal diffusivity from Holland and Jenkins (1999) converted to m^2/yr 
+
+%vertical velocity of ice shelf, calculated from melting rate 
+wi=md.materials.rho_water/md.materials.rho_ice.*md.basalforcings.floatingice_melting_rate; 
+
+%temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
+temperature=(Ts+Tb)/2;  % where wi~=0
+
+pos=find(abs(wi)>=1e-4); % to avoid division by zero
+
+%calculate depth-averaged temperature (in Celsius)
+temperature(pos)=-( (Tb(pos)-Ts(pos))*ki./wi(pos) + Hi(pos).*Tb(pos) - (Hi(pos).*Ts(pos) + (Tb(pos)-Ts(pos))*ki./wi(pos)).*exp(Hi(pos).*wi(pos)/ki) )./( Hi(pos).*(exp(Hi(pos).*wi(pos)/ki)-1));
+%temperature(pos)=-( ((Tb(pos)-Ts(pos))*ki./wi(pos) + Hi(pos).*Tb(pos))./exp(Hi(pos).*wi(pos)/ki) - Hi(pos).*Ts(pos) + (Tb(pos)-Ts(pos))*ki./wi(pos))./( Hi(pos).*(1-exp(-Hi(pos).*wi(pos)/ki)));
+
+%temperature should not be less than surface temp
+pos=find(temperature<Ts);
+temperature(pos)=Ts(pos);
+
+% NaN where melt rates are too high (infinity/infinity in exponential)
+pos=find(isnan(temperature));
+temperature(pos)=Ts(pos);
+
+%convert to Kelvin
+temperature=temperature+273.15;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/steadystateiceshelftemp.py	(revision 18231)
@@ -0,0 +1,65 @@
+import numpy as npy
+
+def steadystateiceshelftemp(md,surfacetemp,basaltemp):
+	"""
+	Compute the depth-averaged steady-state temperature of an ice shelf 
+	This routine computes the depth-averaged temperature accounting for vertical advection 
+	and diffusion of heat into the base of the ice shelf as a function of surface and basal 
+	temperature and the basal melting rate.  Horizontal advection is ignored.
+   The solution is a depth-averaged version of Equation 25 in Holland and Jenkins (1999).
+
+	In addition to supplying md, the surface and basal temperatures of the ice shelf must be supplied in degrees Kelvin.
+
+	The model md must also contain the fields: 
+	md.geometry.thickness
+	md.basalforcings.floatingice_melting_rate (positive for melting, negative for freezing)
+
+   Usage:
+      temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+	"""
+
+	if len(md.geometry.thickness)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: thickness should have a length of ' + md.mesh.numberofvertices)
+	
+	#surface and basal temperatures in degrees C
+	if len(surfacetemp)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: surfacetemp should have a length of ' + md.mesh.numberofvertices)
+	
+	if len(basaltemp)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: basaltemp should have a length of ' +md.mesh.numberofvertices)
+	
+	# Convert temps to Celsius for Holland and Jenkins (1999) equation
+	Ts=-273.15+surfacetemp
+	Tb=-273.15+basaltemp
+	
+	Hi=md.geometry.thickness
+	ki=1.14e-6*md.constants.yts # ice shelf thermal diffusivity from Holland and Jenkins (1999) converted to m^2/yr 
+	
+	#vertical velocity of ice shelf, calculated from melting rate 
+	wi=md.materials.rho_water/md.materials.rho_ice*md.basalforcings.floatingice_melting_rate 
+	
+	#temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
+	temperature=(Ts+Tb)/2  # where wi~=0
+	
+	pos=npy.nonzero(abs(wi)>=1e-4) # to avoid division by zero
+
+	npy.seterr(over='raise',divide='raise') # raise errors if floating point exceptions are encountered in following calculation
+	#calculate depth-averaged temperature (in Celsius)
+	try:
+		temperature[pos]=-( (Tb[pos]-Ts[pos])*ki/wi[pos] + Hi[pos]*Tb[pos] - (Hi[pos]*Ts[pos] + (Tb[pos]-Ts[pos])*ki/wi[pos])*npy.exp(Hi[pos]*wi[pos]/ki) )/( Hi[pos]*(npy.exp(Hi[pos]*wi[pos]/ki)-1))
+	except FloatingPointError:
+		print 'steadystateiceshelf warning: overflow encountered in multipy/divide/exp, trying another formulation.' 
+		temperature[pos]=-( ((Tb[pos]-Ts[pos])*ki/wi[pos] + Hi[pos]*Tb[pos])/npy.exp(Hi[pos]*wi[pos]/ki) - Hi[pos]*Ts[pos] + (Tb[pos]-Ts[pos])*ki/wi[pos])/( Hi[pos]*(1-npy.exp(-Hi[pos]*wi[pos]/ki)))
+	
+	#temperature should not be less than surface temp
+	pos=npy.nonzero(temperature<Ts)
+	temperature[pos]=Ts[pos]
+	
+	# NaN where melt rates are too high (infinity/infinity in exponential)
+	pos=npy.nonzero(npy.isnan(temperature))
+	temperature[pos]=Ts[pos]
+	
+	#convert to Kelvin
+	temperature=temperature+273.15
+
+	return temperature
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/strainrateuncert.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/strainrateuncert.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/strainrateuncert.m	(revision 18231)
@@ -0,0 +1,73 @@
+function md=strainratuncert(md,vx,vy,dvx,dvy)
+%STRAINRATEUNCERT - compute uncertainty in strain rate components
+%
+%   this routine computes the uncertainties in the strain rate tensor
+%	 components given the uncertainty in surface velocity data.
+%   The results are stored in md.results
+%
+%	 'dvx' and 'dvy' are velocity errors in x and y components in m/yr.  
+%   These can either be scalars or arrays of length md.mesh.numberofvertices
+%
+%   Usage:
+%      md=strainrateuncert(md,vx,vy,dv)
+%
+%   Example:
+%      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy,5);
+%      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs,dv);
+
+%some checks
+if length(vx)~=md.mesh.numberofvertices | length(vy)~=md.mesh.numberofvertices,
+	error(['the input velocity should be of size ' num2str(md.mesh.numberofvertices) '!'])
+end
+if length(dvx)==1,
+	dvx=dvx*ones(md.mesh.numberofelements,1);
+end
+if length(dvx)~=md.mesh.numberofelements,
+	error(['the velocity error dvx should be of size ' num2str(md.mesh.numberofelements) ' or 1!'])
+end
+if length(dvy)==1,
+	dvy=dvy*ones(md.mesh.numberofelements,1);
+end
+if length(dvy)~=md.mesh.numberofelements,
+	error(['the velocity error dvy should be of size ' num2str(md.mesh.numberofelements) ' or 1!'])
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported yet');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA''s elements');
+end
+
+%initialization
+index=md.mesh.elements;
+summation=[1;1;1];
+dvxlist=dvx(index);
+dvylist=dvy(index);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y);
+
+strainrateuncert=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalvalue2',[],'effectivevalue',[]);
+
+strainrateuncert.xx=sqrt((dvxlist.*alpha).^2*summation);
+strainrateuncert.yy=sqrt((dvylist.*beta).^2*summation);
+strainrateuncert.xy=0.5*sqrt((dvxlist.*beta).^2*summation+(dvylist.*alpha).^2*summation);
+
+exx=md.results.strainrate.xx; 
+eyy=md.results.strainrate.yy;
+exy=md.results.strainrate.xy;
+p1a=strainrateuncert.xx.*(0.5+0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p2a=strainrateuncert.yy.*(0.5-0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p3a=strainrateuncert.xy.*((((exx-eyy)/2).^2+exy.^2).^(-1./2).*exy);
+p1b=strainrateuncert.xx.*(0.5-0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p2b=strainrateuncert.yy.*(0.5+0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p3b=strainrateuncert.xy.*(-(((exx-eyy)/2).^2+exy.^2).^(-1./2).*exy);
+strainrateuncert.principalvalue1=sqrt(p1a.^2+p2a.^2+p3a.^2);
+strainrateuncert.principalvalue2=sqrt(p1b.^2+p2b.^2+p3b.^2);
+
+effa=strainrateuncert.xx/sqrt(2).*(exx.^2+eyy.^2+2*exy.^2).^(-1./2).*exx;
+effb=strainrateuncert.yy/sqrt(2).*(exx.^2+eyy.^2+2*exy.^2).^(-1./2).*eyy;
+effc=2*strainrateuncert.xy/sqrt(2).*(exx.^2+eyy.^2+2*exy.^2).^(-1./2).*exy;
+strainrateuncert.effectivevalue=sqrt(effa.^2+effb.^2+effc.^2);
+
+md.results.strainrateuncert=strainrateuncert;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.m	(revision 18231)
@@ -0,0 +1,151 @@
+function [alpha,beta,theta,ex,sigxx]=thomasparams(md,varargin)
+%THOMASPARAMS - compute Thomas' geometric parameters for an ice shelf 
+%
+%	 This routine computes geometric parameters representing ratios between
+%	 components of the horizontal strain rate tensor for an ice shelf, as
+%	 originally developed in Thomas (1973).  The model must contain computed
+%	 strain rates, either from observed or modeled ice velocities.
+%
+%   Available options:
+%	 -'eq'			: analytical equation to use in the calculation.  Must be one of:
+%				'Thomas' for a 2D ice shelf, taking into account full strain rate
+%					tensor (default)
+%				'Weertman1D' for a confined ice shelf free to flow in one direction
+%				'Weertman2D' for an unconfined ice shelf free to spread in any direction
+%
+%	 -'smoothing'	: an integer smoothing parameter for the averaging function
+%						(default 0) Type 'help averaging' for more information on its usage.
+%
+%	 -'coordsys'	: coordinate system for calculating the strain rate
+%						components. Must be one of:
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values: 
+%
+%		'alpha' which is the ratio e_yy/e_xx between components of the strain
+%		rate tensor
+%
+%		'beta' which is the ratio e_xy/e_xx between components of the strain rate
+%		tensor
+%
+%		'theta' which is a combination of alpha and beta arising from the form of
+%		the equivalent stress
+%
+%		'exx' is the strain rate along a coordinate system defined by 'coordsys' 
+%
+%		'sigxx' is the deviatoric stress along a coordinate system defined by 'coordsys' 
+%
+%   Usage: [alpha,beta,theta,exx,sigxx]=ThomasParams(md,options)
+%
+%   Example: [alpha,beta,theta,exx,sigxx]=ThomasParams(md,'eq','Thomas','smoothing',2,'coordsys','longitudinal')
+
+%some checks
+if (nargin<4)
+	help ThomasParams
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)'])
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+eq = getfieldvalue(options,'eq','Thomas');
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+
+% average element strain rates onto vertices
+e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts; % convert to s^-1
+e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts;
+exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts;
+eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts;
+exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts;
+
+% checks: any of e1 or e2 equal to zero?
+pos=find(e1==0);
+if any(pos==1)
+	disp('WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e1(pos)=1e-13;
+end
+pos=find(e2==0);
+if any(pos==1)
+	disp('WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e2(pos)=1e-13;
+end
+
+% rheology
+n=averaging(md,md.materials.rheology_n,0);
+B=md.materials.rheology_B;
+
+switch coordsys
+	case 'principal'
+		b=zeros(md.mesh.numberofvertices,1);
+		ex=e1;
+		a=e2./e1;
+		pos=find(e1<0 & e2>0); % longitudinal compression and lateral tension
+		a(pos)=e1(pos)./e2(pos);
+		ex(pos)=e2(pos);
+		pos2=find(e1<0 & e2<0 & abs(e1)<abs(e2)); % lateral and longitudinal compression
+		a(pos2)=e1(pos2)./e2(pos2);
+		ex(pos2)=e2(pos2);
+		pos3=find(e1>0 & e2>0 & abs(e1)<abs(e2)); % lateral and longitudinal tension
+		a(pos3)=e1(pos3)./e2(pos3);
+		ex(pos3)=e2(pos3);
+		id=find(e1<0 & e2<0);
+		a(id)=-a(id); % where both strain rates are compressive, enforce negative alpha
+		sigxx=(abs(ex)./((1+a+a.^2).^((n-1)/2))).^(1./n).*B;
+		%mask=ismember(1:md.mesh.numberofvertices,id);
+		%plotmodel(md,'data',ex,'mask',mask)
+	case 'xy'
+		ex=exx;
+		a=eyy./exx;
+		b=exy./exx;
+	case 'longitudinal'
+		% using longitudinal strain rates defined by observed velocity vector
+		velangle=atan(md.initialization.vy./md.initialization.vx);
+		pos=find(md.initialization.vx==0);
+		velangle(pos)=pi/2;
+		ex=0.5*(exx+eyy)+0.5*(exx-eyy).*cos(2*velangle)+exy.*sin(2*velangle);
+		ey=exx+eyy-ex; % trace of strain rate tensor is invariant
+		exy=-0.5*(exx-eyy).*sin(2*velangle)+exy.*cos(2*velangle);
+		a=ey./ex;
+		b=exy./ex;
+		%pos=find(ex<0 & ey<0);
+		%a(pos)=-a(pos);
+		%sigxx=(abs(ex)./((1+a+a.^2+b.^2).^((n-1)/2))).^(1./n).*B;
+		sigxx=abs(ex).^(1./n-1).*ex./((1+a+a.^2+b.^2).^((n-1)./(2*n))).*B;
+	otherwise
+		error('argument passed to "coordsys" not valid');
+end
+
+% a < -1 in areas of strong lateral compression or longitudinal compression and
+% theta flips sign at a = -2
+pos=find(abs((abs(a)-2))<1e-3);
+if length(pos)>0,
+	disp(['Warning: ', num2str(length(pos)), ' vertices have alpha within 1e-3 of -2'])
+end
+a(pos)=-2+1e-3;
+
+switch eq
+	case 'Weertman1D'
+		theta=1./8;
+		a=zeros(md.mesh.numberofvertices,1);
+	case 'Weertman2D'
+		theta=1./9;
+		a=ones(md.mesh.numberofvertices,1);
+	case 'Thomas'
+		theta=((1+a+a.^2+b.^2).^((n-1)/2))./(abs(2+a).^n);
+	otherwise
+		error('argument passed to "eq" not valid.  Type "help zinv" for usage');
+end
+alpha=a;
+beta=b;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mech/thomasparams.py	(revision 18231)
@@ -0,0 +1,145 @@
+import numpy as npy
+from averaging import averaging
+
+def thomasparams(md,**kwargs):
+	'''
+	compute Thomas' geometric parameters for an ice shelf 
+
+	This routine computes geometric parameters representing ratios between
+	components of the horizontal strain rate tensor for an ice shelf, as
+	originally developed in Thomas (1973).  The model must contain computed
+	strain rates, either from observed or modeled ice velocities.
+
+   Available options:
+	 -eq			: analytical equation to use in the calculation.  Must be one of:
+				'Thomas' for a 2D ice shelf, taking into account full strain rate
+					tensor (default)
+				'Weertman1D' for a confined ice shelf free to flow in one direction
+				'Weertman2D' for an unconfined ice shelf free to spread in any direction
+
+	 -smoothing	: an integer smoothing parameter for the averaging function
+						(default 0) Type 'help averaging' for more information on its usage.
+
+	 -coordsys	: coordinate system for calculating the strain rate
+						components. Must be one of:
+				'longitudinal': x axis aligned along a flowline at every point (default)
+				'principal': x axis aligned along maximum principal strain rate
+					at every point
+				'xy': x and y axes same as in polar stereographic projection 
+
+   Return values: 
+
+		'alpha' which is the ratio e_yy/e_xx between components of the strain
+		rate tensor
+
+		'beta' which is the ratio e_xy/e_xx between components of the strain rate
+		tensor
+
+		'theta' which is a combination of alpha and beta arising from the form of
+		the equivalent stress
+
+		'exx' is the strain rate along a coordinate system defined by 'coordsys' 
+
+		'sigxx' is the deviatoric stress along a coordinate system defined by 'coordsys' 
+
+   Usage: 
+		alpha,beta,theta,exx,sigxx=thomasparams(md)
+
+   Example: 
+		alpha,beta,theta,exx,sigxx=thomasparams(md,eq='Thomas',smoothing=2,coordsys='longitudinal')
+	'''
+
+	#unpack kwargs
+	eq=kwargs.pop('eq','Thomas')
+	if 'eq' in kwargs: del kwargs['eq']
+	smoothing=kwargs.pop('smoothing',0)
+	if 'smoothing' in kwargs: del kwargs['smoothing']
+	coordsys=kwargs.pop('coordsys','longitudinal')
+	if 'coordsys' in kwargs: del kwargs['coordsys']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	# some checks
+	if not hasattr(md.results,'strainrate'):
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if any(md.flowequation.element_equation!=2):
+		raise StandardError('Warning: the model has some non-SSA elements.  These will be treated like SSA elements')
+
+	# average element strain rates onto vertices
+	e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts # convert to s^-1
+	e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts
+	exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts
+	eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts
+	exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts
+	
+	# checks: any of e1 or e2 equal to zero?
+	pos=npy.nonzero(e1==0)
+	if npy.any(pos==1):
+		print 'WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1'
+		e1[pos]=1.e-13
+	pos=npy.nonzero(e2==0)
+	if npy.any(pos==1):
+		print 'WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1'
+		e2[pos]=1.e-13
+	
+	# rheology
+	n=averaging(md,md.materials.rheology_n,0)
+	B=md.materials.rheology_B
+	
+	if coordsys=='principal':
+		b=npy.zeros((md.mesh.numberofvertices,))
+		ex=e1
+		a=e2/e1
+		pos=npy.nonzero(npy.logical_and(e1<0,e2>0)) # longitudinal compression and lateral tension
+		a[pos]=e1[pos]/e2[pos]
+		ex[pos]=e2[pos]
+		pos2=npy.nonzero(e1<0 & e2<0 & npy.abs(e1)<npy.abs(e2)) # lateral and longitudinal compression
+		a[pos2]=e1[pos2]/e2[pos2]
+		ex[pos2]=e2[pos2]
+		pos3=npy.nonzero(e1>0 & e2>0 & npy.abs(e1)<npy.abs(e2)) # lateral and longitudinal tension
+		a[pos3]=e1[pos3]/e2[pos3]
+		ex[pos3]=e2[pos3]
+		ind=npy.nonzero(e1<0 & e2<0)
+		a[ind]=-a[ind] # where both strain rates are compressive, enforce negative alpha
+		sigxx=(npy.abs(ex)/((1.+a+a**2)**((n-1.)/2.)))**(1./n)*B
+	elif coordsys=='xy':
+		ex=exx
+		a=eyy/exx
+		b=exy/exx
+	elif coordsys=='longitudinal':
+		# using longitudinal strain rates defined by observed velocity vector
+		velangle=npy.arctan(md.initialization.vy/md.initialization.vx)
+		pos=npy.nonzero(md.initialization.vx==0)
+		velangle[pos]=npy.pi/2
+		ex=0.5*(exx+eyy)+0.5*(exx-eyy)*npy.cos(2.*velangle)+exy*npy.sin(2.*velangle)
+		ey=exx+eyy-ex # trace of strain rate tensor is invariant
+		exy=-0.5*(exx-eyy)*npy.sin(2.*velangle)+exy*npy.cos(2.*velangle)
+		a=ey/ex
+		b=exy/ex
+		sigxx=abs(ex)**(1./n-1.)*ex/((1.+a+a**2+b**2)**((n-1.)/(2.*n)))*B
+	else:
+		raise ValueError('argument passed to "coordsys" not valid')
+	
+	# a < -1 in areas of strong lateral compression or longitudinal compression and
+	# theta flips sign at a = -2
+	pos=npy.nonzero(npy.abs((npy.abs(a)-2.))<1.e-3)
+	if len(pos)>0:
+		print 'Warning: ', len(pos), ' vertices have alpha within 1e-3 of -2'
+	a[pos]=-2+1e-3
+
+	if eq=='Weertman1D':
+		theta=1./8
+		a=npy.zeros((md.mesh.numberofvertices,))
+	elif eq=='Weertman2D':
+		theta=1./9
+		a=npy.ones((md.mesh.numberofvertices,))
+	elif eq=='Thomas':
+		theta=((1.+a+a**2+b**2)**((n-1.)/2.))/(npy.abs(2.+a)**n)
+	else:
+		raise ValueError('argument passed to "eq" not valid')
+
+	alpha=a
+	beta=b
+
+	return alpha,beta,theta,ex
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.m	(revision 18231)
@@ -0,0 +1,60 @@
+function hessian=ComputeHessian(index,x,y,field,type)
+%COMPUTEHESSIAN - compute hessian matrix from a field
+%
+%   Compute the hessian matrix of a given field
+%   return the three components Hxx Hxy Hyy
+%   for each element or each node
+%
+%   Usage:
+%      hessian=ComputeHessian(index,x,y,field,type)
+%
+%   Example:
+%      hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vel_obs,'node')
+
+%some variables
+numberofnodes=length(x);
+numberofelements=size(index,1);
+
+%some checks
+if length(field)~=numberofnodes & length(field)~=numberofelements,
+	error('ComputeHessian error message: the given field size not supported yet');
+end
+if ~strcmpi(type,'node') & ~strcmpi(type,'element'),
+	error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
+end
+
+%initialization
+line=index(:);
+linesize=3*numberofelements;
+
+%get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+areas=GetAreas(index,x,y);
+
+%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);
+
+%compute field on nodes if on elements
+if length(field)==numberofelements,
+	field=sparse(line,ones(linesize,1),repmat(areas.*field,3,1),numberofnodes,1)./weights ;
+end
+
+%Compute gradient for each element
+grad_elx=sum(field(index).*alpha,2); 
+grad_ely=sum(field(index).*beta,2);
+
+%Compute gradient for each node (average of the elements around)
+gradx=sparse(line,ones(linesize,1),repmat(areas.*grad_elx,3,1),numberofnodes,1);
+grady=sparse(line,ones(linesize,1),repmat(areas.*grad_ely,3,1),numberofnodes,1);
+gradx=gradx./weights;
+grady=grady./weights;
+
+%Compute hessian for each element
+hessian=[sum(gradx(index).*alpha,2) sum(grady(index).*alpha,2) sum(grady(index).*beta,2)];
+
+if strcmpi(type,'node')
+	%Compute Hessian on the nodes (average of the elements around)
+	hessian=[sparse(line,ones(linesize,1),repmat(areas.*hessian(:,1),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,2),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,3),3,1),numberofnodes,1)./weights ];
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeHessian.py	(revision 18231)
@@ -0,0 +1,66 @@
+import numpy
+from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
+from GetAreas import GetAreas
+import MatlabFuncs as m
+
+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 m.strcmpi(type,'node') and not m.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=m.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=m.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-1,0]*alpha,axis=1) 
+	grad_ely=numpy.sum(field[index-1,0]*beta,axis=1)
+
+	#Compute gradient for each node (average of the elements around)
+	gradx=m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*grad_elx).reshape(-1,1),(3,1)),numberofnodes,1)
+	grady=m.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-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*beta,axis=1).reshape(-1,1)))
+
+	if m.strcmpi(type,'node'):
+		#Compute Hessian on the nodes (average of the elements around)
+		hessian=numpy.hstack((m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,0]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
+			m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,1]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
+			m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,2]).reshape(-1,1),(3,1)),numberofnodes,1)/weights ))
+
+	return hessian
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.m	(revision 18231)
@@ -0,0 +1,66 @@
+function metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%COMPUTEMETRIC - compute metric from an Hessian
+%
+%   Usage:
+%      metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%      pos is contains the positions where the metric is wished to be maximized (water?)
+%
+%   Example:
+%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,[])
+
+%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));
+pos1=find(lambda1==0.);
+pos2=find(lambda2==0.);
+pos3=find(b==0. & lambda1==lambda2);
+
+%Modify the eigen values to control the shape of the elements
+lambda1=min(max(abs(lambda1)*scale/epsilon,1./hmax^2),1./hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1./hmax^2),1./hmin^2);
+
+%compute eigen vectors
+norm1=sqrt(8.*b.^2+2.*(d-a).^2+2.*(d-a).*sqrt((a-d).^2+4.*b.^2));
+v1x=2.*b./norm1;
+v1y=((d-a)+sqrt((a-d).^2+4.*b.^2))./norm1;
+norm2=sqrt(8.*b.^2+2.*(d-a).^2-2.*(d-a).*sqrt((a-d).^2+4.*b.^2));
+v2x=2.*b./norm2;
+v2y=((d-a)-sqrt((a-d).^2+4.*b.^2))./norm2;
+
+v1x(pos3)=1.; v1y(pos3)=0.;
+v2x(pos3)=0.; v2y(pos3)=1.;
+
+%Compute new metric (for each node M=V*Lambda*V^-1)
+metric=full([(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v2y.*v1x-lambda2.*v1y.*v2x) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v1y.*v2y-lambda2.*v1y.*v2y) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(-lambda1.*v2x.*v1y+lambda2.*v1x.*v2y)]);
+
+%some corrections for 0 eigen values
+metric(pos1,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos1),1);
+metric(pos2,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos2),1);
+
+%take care of water elements
+metric(pos,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos),1);
+
+%take care of NaNs if any (use Matlab eig in a loop)
+[pos posj]=find(isnan(metric)); clear posj;
+if ~isempty(pos),
+	fprintf(' %i %s',length(pos),'NaN found in the metric. Use Matlab routine...');
+	for i=1:length(pos)
+		H=[hessian(pos(i),1) hessian(pos(i),2)
+		hessian(pos(i),2) hessian(pos(i),3)];
+		[u,v]=eig(full(H));
+		lambda1=v(1,1);
+		lambda2=v(2,2);
+		v(1,1)=min(max(abs(lambda1)*scale/epsilon,1./hmax^2),1./hmin^2);
+		v(2,2)=min(max(abs(lambda2)*scale/epsilon,1./hmax^2),1./hmin^2);
+
+		metricTria=u*v*u^(-1);
+		metric(pos(i),:)=[metricTria(1,1) metricTria(1,2) metricTria(2,2)];
+	end
+end
+
+if any(isnan(metric)),
+	error('ComputeMetric error message: NaN in the metric despite our efforts...')
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ComputeMetric.py	(revision 18231)
@@ -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,[])
+	"""
+
+	#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 numpy.size(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/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.m	(revision 18231)
@@ -0,0 +1,15 @@
+function edgeelements=ElementsFromEdge(elements,A,B)
+%ELEMENTSFROMEDGE: find elements connected to one edge defined by nodes A and B
+%
+%   Usage: edgeelements=ElementsFromEdge(elements,A,B) 
+%
+%   Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
+%
+%
+edgeelements=find(...
+	(elements(:,1)==A & elements(:,2)==B )| ...
+	(elements(:,1)==A & elements(:,3)==B )| ...
+	(elements(:,2)==A & elements(:,3)==B )| ...
+	(elements(:,2)==A & elements(:,1)==B )| ...
+	(elements(:,3)==A & elements(:,1)==B )| ...
+	(elements(:,3)==A & elements(:,2)==B ));
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ElementsFromEdge.py	(revision 18231)
@@ -0,0 +1,24 @@
+import numpy
+import PythonFuncs as p
+
+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(\
+		p.logical_or_n(numpy.logical_and(elements[:,0]==A,elements[:,1]==B), \
+					 numpy.logical_and(elements[:,0]==A,elements[:,2]==B), \
+					 numpy.logical_and(elements[:,1]==A,elements[:,2]==B), \
+					 numpy.logical_and(elements[:,1]==A,elements[:,0]==B), \
+					 numpy.logical_and(elements[:,2]==A,elements[:,0]==B), \
+					 numpy.logical_and(elements[:,2]==A,elements[:,1]==B), \
+		))[0]+1
+
+	return edgeelements
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ExportGmsh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ExportGmsh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ExportGmsh.m	(revision 18231)
@@ -0,0 +1,52 @@
+function ExportGmsh(md,filename)
+%EXPORTGMSH - export mesh to gmsh format
+%
+%   Usage:
+%      ExportGmsh(md,filename)
+
+t1=clock;fprintf('%s',['writing gmsh mesh file']);
+fid=fopen(filename,'w');
+
+%initialiaion
+fprintf(fid,'$MeshFormat \n');
+fprintf(fid,'2.2 0 8 \n');
+fprintf(fid,'$EndMeshFormat \n');
+fprintf(fid,'$Nodes \n');
+fprintf(fid,'%i \n',md.mesh.numberofvertices);
+np=0;
+%printing point positions
+for ii=1:md.mesh.numberofvertices
+	np = np+1;
+	fprintf(fid,'%g %14.7e %14.7e 0.0 \n',np,md.mesh.x(np),md.mesh.y(np));
+end
+
+fprintf(fid,'$EndNodes \n');
+fprintf(fid,'$Elements \n');
+fprintf(fid,'%i \n',md.mesh.numberofelements+size(md.mesh.segments,1));
+np=0;
+
+%printing elements caracteristics for boundaries
+
+for ii=1:size(md.mesh.segments,1)
+	np = np+1;
+	if(md.mesh.x(md.mesh.segments(np,1))==max(md.mesh.x(:))&&md.mesh.x(md.mesh.segments(np,2))==max(md.mesh.x(:))),
+		bc_id=1;
+	elseif(md.mesh.y(md.mesh.segments(np,1))==max(md.mesh.y(:))&&md.mesh.y(md.mesh.segments(np,2))==max(md.mesh.y(:))),
+		bc_id=2;
+	elseif(md.mesh.x(md.mesh.segments(np,1))==min(md.mesh.x(:))&&md.mesh.x(md.mesh.segments(np,2))==min(md.mesh.x(:))),
+		bc_id=3;
+	elseif(md.mesh.y(md.mesh.segments(np,1))==min(md.mesh.y(:))&&md.mesh.y(md.mesh.segments(np,2))==min(md.mesh.y(:))),
+		bc_id=4;
+  end
+		fprintf(fid,'%g 1 2 %g 1 %g %g \n',np,bc_id,md.mesh.segments(np,1),md.mesh.segments(np,2));
+end
+%and for the body
+body_id=1;
+for ii=1:md.mesh.numberofelements
+  np = np+1;
+  fprintf(fid,'%g 2 2 %g 3 %g %g %g \n',np,body_id,md.mesh.elements(ii,1),md.mesh.elements(ii,2),md.mesh.elements(ii,3));
+end
+fprintf(fid,'$EndElements \n');
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/FixMesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/FixMesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/FixMesh.m	(revision 18231)
@@ -0,0 +1,45 @@
+function  [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+% FIXMESH - FixMesh fix mesh with broken triangles, orphan vertices, etc ...
+%
+%   Usage: 
+%      [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+%      where index,x,y is a delaunay triangulation, 
+%      value is a field on the input triangulation, with values at the vertices
+%      index2,x2,y2,value2 is the repaired triangulation, with new values on new vertices
+%
+%
+
+%duplicate inputs
+index2=index;
+x2=x;
+y2=y;
+value2=value;
+
+%First, look for orphan vertices, and take them out.
+flags=zeros(length(x2),1); flags(index2)=1;
+orphans=find(flags==0);
+
+while ~isempty(orphans),
+
+	%take the first orphan, the lower numbered, and take it out
+	orphan=orphans(1);
+
+	%first x,y,value
+	x2(orphan)=[];
+	y2(orphan)=[];
+	value2(orphan)=[];
+
+	%now, the index:
+	pos=find(index2>orphan); index2(pos)=index2(pos)-1;
+
+	%look again for orphans on new mesh
+	flags=zeros(length(x2),1);flags(index2)=1;
+	orphans=find(flags==0);
+end
+
+%Check all triangles are well oriented.
+aires=GetAreas(index2,x2,y2);
+pos=find(aires<0);
+temp=index2(pos,1);
+index2(pos,1)=index2(pos,2);
+index2(pos,2)=temp;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 18231)
@@ -0,0 +1,56 @@
+function [alpha beta varargout]=GetNodalFunctionsCoeff(index,x,y)
+%GETNODELFUNCTIONSCOEFF - compute nodal functions coefficients
+%
+%   Compute the coefficients alpha beta and optionaly gamma of
+%   2d triangular elements. For each element, the nodal function
+%   is defined as:
+%   N(x,y)=sum(i=1:3) alpha_i * x + beta_i * y + gamma_i
+%
+%   Usage:
+%      [alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(index,x,y);
+%
+%   Example:
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%make columns out of x and y
+x=x(:); y=y(:);
+
+%get nels and nods
+nels=size(index,1);
+nods=length(x);
+
+%some checks
+if nargin~=3 | (nargout~=2 & nargout~=3),
+	help GetNodalFunctionsCoeff
+	error('GetNodalFunctionsCoeff error message: bad usage')
+end
+if length(y)~=nods,
+	error('GetNodalFunctionsCoeff error message: x and y do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetNodalFunctionsCoeff error message: index should not have values above ' num2str(nods) ])
+end
+if size(index,2)~=3,
+	error('GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.')
+end
+
+%initialize output
+alpha=zeros(nels,3);
+beta=zeros(nels,3);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+invdet=1./(x1.*(y2-y3)-x2.*(y1-y3)+x3.*(y1-y2));
+
+%get alpha and beta
+alpha=[invdet.*(y2-y3) invdet.*(y3-y1) invdet.*(y1-y2)];
+beta =[invdet.*(x3-x2) invdet.*(x1-x3) invdet.*(x2-x1)];
+
+%get gamma if requested
+if nargout==3,
+	gamma=zeros(nels,3);
+	gamma=[invdet.*(x2.*y3-x3.*y2) invdet.*(y1.*x3-y3.*x1) invdet.*(x1.*y2-x2.*y1)];
+	varargout{1}=gamma;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/GetNodalFunctionsCoeff.py	(revision 18231)
@@ -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]-1]
+	x2=x[index[:,1]-1]
+	x3=x[index[:,2]-1]
+	y1=y[index[:,0]-1]
+	y2=y[index[:,1]-1]
+	y3=y[index[:,2]-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/branches/trunk-jpl-ad2-integrated/src/m/mesh/MergeMetrics.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/MergeMetrics.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/MergeMetrics.m	(revision 18231)
@@ -0,0 +1,15 @@
+function metric=MergeMetrics(metric1,metric2)
+
+M1xx=metric1(:,1); M1xy=metric1(:,2); M1yy=metric1(:,3);
+M1lambda1=0.5*((M1xx+M1yy)+sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+M1lambda2=0.5*((M1xx+M1yy)-sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+lambda1=min(M1lambda1,M1lambda2);
+
+M2xx=metric1(:,1); M2xy=metric1(:,2); M2yy=metric1(:,3);
+M2lambda1=0.5*((M2xx+M2yy)+sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+M2lambda2=0.5*((M2xx+M2yy)-sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+lambda2=min(M2lambda2,M2lambda2);
+
+metric=metric1;
+pos=find(lambda2<lambda1);
+metric(pos,:)=metric2(pos,:);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/MeshQuality.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/MeshQuality.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/MeshQuality.m	(revision 18231)
@@ -0,0 +1,77 @@
+function quality=MeshQuality(md,epsilon,hmin,hmax)
+%MESHQUALITY - compute mesh quality
+%
+%   Usage:
+%      MeshQuality(md,epsilon,hmin,hmax);
+
+%Get some variables from the model
+index=md.mesh.elements;
+x=md.mesh.x;
+y=md.mesh.y;
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+hessian=ComputeHessian(index,x,y,md.inversion.vel_obs,'node');
+
+%Compute metric
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
+
+%Get Areas
+areas=GetAreas(index,x,y);
+
+%length edges vectors
+e1x=[x(index(:,2))-x(index(:,1))];
+e1y=[y(index(:,2))-y(index(:,1))];
+e2x=[x(index(:,3))-x(index(:,2))];
+e2y=[y(index(:,3))-y(index(:,2))];
+e3x=[x(index(:,1))-x(index(:,3))];
+e3y=[y(index(:,1))-y(index(:,3))];
+
+%metric of each the 3 nodes for each element
+M1=metric(index(:,1),:);
+M2=metric(index(:,2),:);
+M3=metric(index(:,3),:);
+
+%Get edge length in the metric
+L1=1/2*(sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y))+sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y)));
+L2=1/2*(sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y))+sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y)));
+L3=1/2*(sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y))+sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y)));
+
+%area in the metric
+V=1/3*areas.*(sqrt(M1(:,1).*M1(:,3)-M1(:,2).^2)+sqrt(M2(:,1).*M2(:,3)-M2(:,2).^2)+sqrt(M3(:,1).*M3(:,3)-M3(:,2).^2));
+
+%compute quality:
+quality=4*sqrt(3)*V./(L1+L2+L3);
+
+%compute error
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+a=a(index)*[1;1;1]/3;
+b=b(index)*[1;1;1]/3;
+d=d(index)*[1;1;1]/3;
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+if length(md.nodeonwater)==md.mesh.numberofvertices;
+	pos=find(md.nodeonwater);
+	lambda1(pos)=0;
+	lambda2(pos)=0;
+end
+lambda1=lambda1(index)*[1;1;1]/3;
+lambda2=lambda2(index)*[1;1;1]/3;
+
+lambdamax=max(lambda1,lambda2);
+hmax=max(max(sqrt(e1x.^2+e1y.^2),sqrt(e2x.^2+e2y.^2)),sqrt(e3x.^2+e3y.^2));
+epsilon=scale*hmax.^2.*lambdamax;
+
+%display
+%X=0:0.1:4; hist(quality,X); xlim([0 3]); title('mesh quality distribution','FontSize',14);
+%plotmodel(md,'data',epsilon,'title','Interpolation error','figure',2)
+disp(sprintf('\n%s','Mesh Quality'));
+disp(sprintf('   %s %g','Average Mesh quality: ',mean(quality)));
+disp(sprintf('   %s %g','Worst Element quality:',max(quality)));
+disp(sprintf('\n%s','Interpolation Error'));
+disp(sprintf('   %s %g %s','Average interpolation error:',mean(epsilon),'m/yr'));
+disp(sprintf('   %s %g %s','Maximum interpolation error:',max(epsilon),'m/yr'));
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/NodeInElement.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/NodeInElement.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/NodeInElement.m	(revision 18231)
@@ -0,0 +1,42 @@
+function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity)
+% NODEINELEMENT - find for a list of nodes (in newx,newy), which elements in the mesh (elements,x,y) they belong to.
+%
+%    Usage:
+%      node_in_element=NodeInElement(newx,newy,elements,x,y,md.mesh.vertexconnectivity);
+%
+%  See also Nodeconnectivity
+%
+epsilon=10^-10;
+
+%compute some quantities that will speed up the process
+x3x1=x(elements(:,1))-x(elements(:,3));
+y3y1=y(elements(:,1))-y(elements(:,3));
+x3x2=x(elements(:,2))-x(elements(:,3));
+y3y2=y(elements(:,2))-y(elements(:,3));
+x3=x(elements(:,3));
+y3=y(elements(:,3));
+delta=x(elements(:,2)).*y(elements(:,3))-y(elements(:,2)).*x(elements(:,3))-x(elements(:,1)).*y(elements(:,3))+y(elements(:,1)).*x(elements(:,3))+x(elements(:,1)).*y(elements(:,2))-y(elements(:,1)).*x(elements(:,2));
+
+%max connectivity:
+max_connectivity=max(nodeconnectivity(:,end));
+node_in_element=zeros(length(newx),max_connectivity+1); %last column is the number of elements to which the row node is connected.
+
+for i=1:length(newx),
+	x0=newx(i);
+	y0=newy(i);
+
+	%first area coordinate
+	area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
+	%second area coordinate
+	area_2=(x3x1.*(y0-y3)-y3y1.*(x0-x3))./delta;
+	%third area coordinate
+	area_3=1-area_1-area_2;
+
+	%get elements for which all area coordinates are positive (meaning (x0,y0) belongs to these elements
+	pos=find((area_1>=0-epsilon) & (area_2>=0-epsilon) & (area_3>=0-epsilon));
+
+	num_elements=length(pos);
+
+	node_in_element(i,1:num_elements)=pos;
+	node_in_element(i,end)=num_elements;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ProfileProjectOntoMesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ProfileProjectOntoMesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/ProfileProjectOntoMesh.m	(revision 18231)
@@ -0,0 +1,66 @@
+function mesh_profile=ProfileProjectOntoMesh(md,profile)
+%PROFILEPROJECTONTOMESH: project a profile (made of arbitrary points) onto a mesh, so that we end 
+%                        up with a list of segments self contained onto elements.
+%
+% Usage: mesh_profile=ProfileProjectOntoMesh(md,profile)
+%
+% See also intersections.m
+
+%make a curve out of the mesh, to use the intersections routine.
+rows=[md.mesh.elements md.mesh.elements(:,1)]'; rows=rows(:);
+x=md.mesh.x(rows);
+y=md.mesh.y(rows);
+
+%[x0,y0] = intersections(profile.x,profile.y,x,y,1);
+[x0,y0,indices,j] = intersections(profile.x,profile.y,x,y);
+
+%  sort intersections to create segments in order and continuous along profile
+[indices,isort]=sort(indices);
+j =j (isort);
+x0=x0(isort);
+y0=y0(isort);
+
+%process x0,y0 so they do not include profile.x or profile.y
+processed_indices=[];
+processed_x=[];
+processed_y=[];
+for i=1:numel(indices),
+	if(((indices(i)-floor(indices(i)))~=0) && ((ceil(indices(i))-indices(i))~=0))
+		processed_indices=[processed_indices;floor(indices(i))];
+		processed_x=[processed_x;x0(i)];
+		processed_y=[processed_y;y0(i)];
+	end
+end
+
+%now merge profile.x,profile.y with processed_x,processed_y, at locations processed_indices:
+newx=profile.x;
+newy=profile.y;
+
+count=1;
+for i=1:numel(profile.x),
+	pos=find(processed_indices==i);
+	if ~isempty(pos),
+		newx=[newx(1:count); processed_x(pos); newx(count+1:end)];
+		newy=[newy(1:count); processed_y(pos); newy(count+1:end)];
+		count=count+length(pos)+1;
+	end
+end
+
+%now, for each node, figure out which element it belongs to.
+node_in_element=NodeInElement(newx,newy,md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.vertexconnectivity);
+
+% eliminate nodes that don't fall in any element
+% (profile may start and/or end externally and/or cross holes in the model)
+
+ind=find(node_in_element(:,end)>0);
+newx=newx(ind,:);
+newy=newy(ind,:);
+node_in_element=node_in_element(ind,:);
+
+mesh_profile=[newx(1:end-1) newy(1:end-1) newx(2:end) newy(2:end) zeros(length(newy(2:end)),1)];
+
+%find which element each segment belongs to.
+for i=1:length(newx)-1,
+	common=intersect(node_in_element(i,1:node_in_element(i,end)), node_in_element(i+1,1:node_in_element(i+1,end)));
+	mesh_profile(i,end)=common(1);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/argusmesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/argusmesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/argusmesh.m	(revision 18231)
@@ -0,0 +1,91 @@
+function md=argusmesh(md,infile)
+%ARGUSMESH - load an Argus mesh onto a model
+%
+%   Convert an Argus mesh contained in a file into
+%   fields needed for the mesh in a model md.
+%
+%   Usage:
+%      md=argusmesh(md,infile)
+%
+%   Example:
+%     md=argusmesh(md,'TriMesh.exp')
+
+%some argument check: 
+if nargin~=2 | nargout~=1,
+	help argustomodel;
+	error('argustomodel error message: bad usage');
+end
+
+%determine root of infile: strip extension
+[a,root,b,c]=fileparts(infile);
+
+%inform user we start the script: 
+disp(['   Translating argus file ''' infile ''' into matlab model object']);
+
+%open infile: 
+fileid=fopen(infile,'r');
+if fileid==-1,
+	error(['Could not open file ' infile  ' for reading']);
+end
+
+%Read first line of the argus mesh: node and element parameters
+[buffer,bytecount]=fscanf(fileid,'%i %i %i %i',[1 4]);
+if bytecount~=4, 
+	error(['Problem reading ' infile ' file at line #1']);
+end
+nel=buffer(1);
+nods=buffer(2);
+num_element_parameters=buffer(3);
+num_node_parameters=buffer(4);
+disp(['      argus model '''   root ''' contains ' num2str(nel) ' elements and ' num2str(nods) ' nodes.']);
+
+%initialize elements and nodes
+elements=zeros(nel,3);
+element_parameters=zeros(nel,num_element_parameters);
+x=zeros(nods,1);
+y=zeros(nods,1);
+z=zeros(nods,1);
+node_parameters=zeros(nods,num_node_parameters);
+
+%read nodes:
+format_string='%s %i %f %f ';
+for n=1:num_node_parameters,
+	format_string=[format_string ' %i '];
+end
+
+for n=1:nods,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_node_parameters+4]);
+	x(n)=buffer(3);
+	y(n)=buffer(4);
+	node_parameters(n,:)=buffer(5:length(buffer));
+end
+
+%read elements: 
+format_string='%s %i %i %i %i';
+for n=1:num_element_parameters,
+	format_string=[format_string ' %i '];
+end
+for n=1:nel,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_element_parameters+5]);
+	elements(n,:)=buffer(3:5);
+	element_parameters(n,:)=buffer(6:length(buffer));
+end
+
+%Create a name and a note for this model: 
+notes=['Model created by Argus from input file: ' infile ' and parameter file: ' root '.par on: ' date];
+name=root;
+
+%Finally, use model constructor to build a complete model: 
+md.mesh=mesh2d();
+md.mesh.elements=elements;
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.numberofvertices=size(md.mesh.x,1);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md=addnote(md,notes);
+
+%Add segments and nodes on boundary
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary(md.mesh.segments(:,1))=1;
+md.mesh.vertexonboundary(md.mesh.segments(:,2))=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.m	(revision 18231)
@@ -0,0 +1,520 @@
+function md=bamg(md,varargin)
+%BAMG - mesh generation
+%
+%   Available options (for more details see ISSM website http://issm.jpl.nasa.gov/):
+%
+%   - domain :            followed by an ARGUS file that prescribes the domain outline
+%   - hmin :              minimum edge length (default is 10^-100)
+%   - hmax :              maximum edge length (default is 10^100)
+%   - hVertices :         imposed edge length for each vertex (geometry or mesh)
+%   - hminVertices :      minimum edge length for each vertex (mesh)
+%   - hmaxVertices :      maximum edge length for each vertex (mesh)
+%
+%   - anisomax :          maximum ratio between the smallest and largest edges (default is 10^30)
+%   - coeff :             coefficient applied to the metric (2-> twice as many elements, default is 1)
+%   - cutoff :            scalar used to compute the metric when metric type 2 or 3 are applied
+%   - err :               error used to generate the metric from a field
+%   - errg :              geometric error (default is 0.1)
+%   - field :             field of the model that will be used to compute the metric
+%                         to apply several fields, use one column per field
+%   - gradation :         maximum ratio between two adjacent edges
+%   - Hessiantype :       0 -> use double L2 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)
+%
+%   - vertical :          is this a 2d vertical mesh (flowband, default is 0)
+%   - rifts :             followed by an ARGUS file that prescribes the rifts
+%   - toltip :            tolerance to move tip on an existing point of the domain outline
+%   - tracks :            followed by an ARGUS file that prescribes the tracks that the mesh will stick to
+%   - RequiredVertices :  mesh vertices that are required. [x,y,ref]; ref is optional
+%   - tol :               if the distance between 2 points of the domain outline is less than tol, they
+%                         will be merged
+%
+%   Examples:
+%      md=bamg(md,'domain','DomainOutline.exp','hmax',3000);
+%      md=bamg(md,'field',[md.inversion.vel_obs md.geometry.thickness],'hmax',20000,'hmin',1000);
+%      md=bamg(md,'metric',A,'hmin',1000,'hmax',20000,'gradation',3,'anisomax',1);
+
+%process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%initialize the structures required as input of Bamg
+bamg_options=struct();
+bamg_geometry=bamggeom();
+bamg_mesh=bamgmesh();
+
+% Bamg Geometry parameters {{{
+if exist(options,'domain'),
+
+	%Check that file exists
+	domainfile=getfieldvalue(options,'domain');
+	if ischar(domainfile),
+		if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found']); end
+
+		%read domain according to its extension: 
+		[path,name,ext]=fileparts(domainfile);
+		if strcmp(ext,'.exp'),
+			domain=expread(domainfile);
+		elseif strcmp(ext,'.shp'),
+			domain=shpread(domainfile);
+		else
+			error(['bamg error message: file ' domainfile ' format not supported (.shp or .exp)']);
+		end
+	elseif isstruct(domainfile),
+		domain = domainfile;
+	else
+		error('''domain'' type not supported yet');
+	end
+
+	%Build geometry 
+	count=0;
+	for i=1:length(domain),
+
+		%Check that the domain is closed
+		if (domain(i).x(1)~=domain(i).x(end) | domain(i).y(1)~=domain(i).y(end)),
+			error('bamg error message: all contours provided in ''domain'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		if i>1,
+			flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0);
+			if any(~flags),
+				error('bamg error message: All holes should be strictly inside the principal domain');
+			end
+		end
+
+		%Add all points to bamg_geometry
+		nods=domain(i).nods-1; %the domain are closed 1=end;
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [domain(i).x(1:nods) domain(i).y(1:nods) ones(nods,1)]];
+		bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1.*ones(nods,1)]];
+		if i>1, bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 1]; end
+
+		%update counter
+		count=count+nods;
+	end
+	if getfieldvalue(options,'vertical',0),
+		if numel(getfieldvalue(options,'Markers',[]))~=size(bamg_geometry.Edges,1),
+			error(['for 2d vertical mesh, ''Markers'' option is required, and should be of size ' num2str(size(bamg_geometry.Edges,1))]);
+		end
+	end
+	if numel(getfieldvalue(options,'Markers',[]))==size(bamg_geometry.Edges,1),
+		bamg_geometry.Edges(:,3)=getfieldvalue(options,'Markers');
+	end
+
+	%take care of rifts
+	if exist(options,'rifts'),
+
+		%Check that file exists
+		riftfile=getfieldvalue(options,'rifts');
+		if ~exist(riftfile,'file')
+			error(['bamg error message: file ' riftfile ' not found ']);
+		end
+		rift=expread(riftfile);
+
+		for i=1:length(rift),
+
+			%detect 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 its points outside of the domain outline'),
+
+			elseif any(~flags),
+				%We LOTS of work to do
+				disp('Rift tip outside of or on the domain has been detected and is being processed...');
+
+				%check that only one point is outside (for now)
+				if sum(~flags)~=1,
+					error('bamg error message: only one point outside of the domain is supported yet');
+				end
+
+				%Move tip outside to the first position
+				if flags(1)==0,
+					%OK, first point is outside (do nothing),
+				elseif (flags(end)==0),
+					rift(i).x=flipud(rift(i).x);
+					rift(i).y=flipud(rift(i).y);
+				else
+					error('bamg error message: only a rift tip can be outside of the domain');
+				end
+
+				%Get cordinate of intersection point
+				x1=rift(i).x(1); y1=rift(i).y(1);
+				x2=rift(i).x(2); y2=rift(i).y(2);
+				for j=1:length(domain(1).x)-1;
+					if SegIntersect([x1 y1; x2 y2],[domain(1).x(j) domain(1).y(j); domain(1).x(j+1) domain(1).y(j+1)]),
+
+						%Get position of the two nodes of the edge in domain
+						i1=j;
+						i2=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(1).x(i1); y3=domain(1).y(i1);
+						x4=domain(1).x(i2); y4=domain(1).y(i2);
+						x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+						y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+						segdis= sqrt((x4-x3)^2+(y4-y3)^2);
+						tipdis=[sqrt((x-x3)^2+(y-y3)^2)  sqrt((x-x4)^2+(y-y4)^2)];
+
+						if (min(tipdis)/segdis) < getfieldvalue(options,'toltip',0),
+							disp('moving tip-domain intersection point');
+
+							%Get position of the closer point
+							if tipdis(1)>tipdis(2),
+								pos=i2;
+							else
+								pos=i1;
+							end
+
+							%This point is only in Vertices (number pos).
+							%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)]];
+							count=count+nods;
+
+							break;
+
+						else
+							%Add intersection point to Vertices
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; x y 1];
+							count=count+1;
+
+							%Decompose the crossing edge into 2 subedges
+							pos=find(bamg_geometry.Edges(:,1)==i1 & bamg_geometry.Edges(:,2)==i2);
+							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:end,:)];
+
+							%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)]];
+							count=count+nods;
+
+							break;
+						end
+					end
+				end
+			else
+				nods=rift(i).nods-1;
+				bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(:) rift(i).y(:) ones(nods+1,1)]];
+				bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose(count+2:count+nods+1)  (1+i)*ones(nods,1)]];
+				count=count+nods+1;
+			end
+		end
+	end
+
+	%Deal with tracks
+	if exist(options,'tracks'),
+
+		%read tracks
+		track=getfieldvalue(options,'tracks');
+		if all(ischar(track)),
+			A=expread(track);
+			track=[A.x A.y];
+		else
+			track=double(track); %for some reason, it is of class "single"
+		end
+		if(size(track,2)==2), track=[track 3.*ones(size(track,1),1)]; end
+
+		%only keep those inside
+		flags=ContourToNodes(track(:,1),track(:,2),domainfile,0);
+		track=track(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(track,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; track];
+		bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose(count+2:count+nods)  3.*ones(nods-1,1)]];
+
+		%update counter
+		count=count+nods;
+	end
+
+	%Deal with vertices that need to be kept by mesher
+	if exist(options,'RequiredVertices'),
+
+		%recover RequiredVertices
+		requiredvertices=double(getfieldvalue(options,'RequiredVertices')); %for some reason, it is of class "single"
+		if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4.*ones(size(requiredvertices,1),1)]; end
+
+		%only keep those inside
+		flags=ContourToNodes(requiredvertices(:,1),requiredvertices(:,2),domain(1),0);
+		requiredvertices=requiredvertices(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(requiredvertices,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; requiredvertices];
+
+		%update counter
+		count=count+nods;
+
+	end
+
+	%process geom
+	%bamg_geometry=processgeometry(bamg_geometry,getfieldvalue(options,'tol',NaN),domain(1));
+
+elseif isstruct(md.private.bamg) & isfield(md.private.bamg,'geometry'),
+	bamg_geometry=bamggeom(md.private.bamg.geometry); 
+else
+	%do nothing...
+end
+%}}}
+% Bamg Mesh parameters {{{
+if (~exist(options,'domain') & md.mesh.numberofvertices~=0 & strcmp(elementtype(md.mesh),'Tria')),
+
+	if isstruct(md.private.bamg) & isfield(md.private.bamg,'mesh'),
+		bamg_mesh=bamgmesh(md.private.bamg.mesh);
+	else
+		bamg_mesh.Vertices=[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)];
+		bamg_mesh.Triangles=[md.mesh.elements ones(md.mesh.numberofelements,1)];
+	end
+
+	if isstruct(md.rifts.riftstruct)
+		error('bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg');
+	end
+end
+%}}}
+% Bamg Options {{{
+bamg_options.Crack=getfieldvalue(options,'Crack',0);
+bamg_options.anisomax=getfieldvalue(options,'anisomax',10.^30);
+bamg_options.coeff=getfieldvalue(options,'coeff',1.);
+bamg_options.cutoff=getfieldvalue(options,'cutoff',10.^-5);
+bamg_options.err=getfieldvalue(options,'err',0.01);
+bamg_options.errg=getfieldvalue(options,'errg',0.1);
+bamg_options.field=getfieldvalue(options,'field',[]);
+bamg_options.gradation=getfieldvalue(options,'gradation',1.5);
+bamg_options.Hessiantype=getfieldvalue(options,'Hessiantype',0);
+bamg_options.hmin=getfieldvalue(options,'hmin',10.^-100);
+bamg_options.hmax=getfieldvalue(options,'hmax',10.^100);
+bamg_options.hminVertices=getfieldvalue(options,'hminVertices',[]);
+bamg_options.hmaxVertices=getfieldvalue(options,'hmaxVertices',[]);
+bamg_options.hVertices=getfieldvalue(options,'hVertices',[]);
+bamg_options.KeepVertices=getfieldvalue(options,'KeepVertices',1);
+bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10.);
+bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
+bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10.);
+bamg_options.metric=getfieldvalue(options,'metric',[]);
+bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
+bamg_options.nbjacobi=getfieldvalue(options,'nbjacobi',1);
+bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
+bamg_options.omega=getfieldvalue(options,'omega',1.8);
+bamg_options.power=getfieldvalue(options,'power',1.);
+bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
+bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
+bamg_options.random=getfieldvalue(options,'rand',true);
+bamg_options.verbose=getfieldvalue(options,'verbose',1);
+%}}}
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgMesher(bamg_mesh,bamg_geometry,bamg_options);
+
+if getfieldvalue(options,'vertical',0),
+	md.mesh=mesh2dvertical();
+	md.mesh.x=bamgmesh_out.Vertices(:,1);
+	md.mesh.y=bamgmesh_out.Vertices(:,2);
+	md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+	md.mesh.edges=bamgmesh_out.IssmEdges;
+	md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+	md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+	%Fill in rest of fields:
+	md.mesh.numberofelements=size(md.mesh.elements,1);
+	md.mesh.numberofvertices=length(md.mesh.x);
+	md.mesh.numberofedges=size(md.mesh.edges,1);
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+	%Now, build the connectivity tables for this mesh.
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+else
+	md.mesh=mesh2d();
+	md.mesh.x=bamgmesh_out.Vertices(:,1);
+	md.mesh.y=bamgmesh_out.Vertices(:,2);
+	md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+	md.mesh.edges=bamgmesh_out.IssmEdges;
+	md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+	md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+	%Fill in rest of fields:
+	md.mesh.numberofelements=size(md.mesh.elements,1);
+	md.mesh.numberofvertices=length(md.mesh.x);
+	md.mesh.numberofedges=size(md.mesh.edges,1);
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+end
+
+%Bamg private fields
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.elementconnectivity=md.private.bamg.mesh.ElementConnectivity;
+md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+%Check for orphan
+if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
+	error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
+end
+end 
+
+function geom=processgeometry(geom,tol,outline) % {{{
+
+%Deal with edges
+disp('Checking Edge crossing...');
+i=0;
+while (i<size(geom.Edges,1)),
+
+	%edge counter
+	i=i+1;
+
+	%Get coordinates
+	x1=geom.Vertices(geom.Edges(i,1),1);
+	y1=geom.Vertices(geom.Edges(i,1),2);
+	x2=geom.Vertices(geom.Edges(i,2),1);
+	y2=geom.Vertices(geom.Edges(i,2),2);
+	color1=geom.Edges(i,3);
+
+	j=i; %test edges located AFTER i only
+	while (j<size(geom.Edges,1)),
+
+		%edge counter
+		j=j+1;
+
+		%Skip if the two edges already have a vertex in common
+		if any(ismember(geom.Edges(i,1:2),geom.Edges(j,1:2))),
+			continue
+		end
+
+		%Get coordinates
+		x3=geom.Vertices(geom.Edges(j,1),1);
+		y3=geom.Vertices(geom.Edges(j,1),2);
+		x4=geom.Vertices(geom.Edges(j,2),1);
+		y4=geom.Vertices(geom.Edges(j,2),2);
+		color2=geom.Edges(j,3);
+
+		%Check if the two edges are crossing one another
+		if SegIntersect([x1 y1; x2 y2],[x3 y3; x4 y4]),
+
+			%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+			x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+			y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+			%Add vertex to the list of vertices
+			geom.Vertices(end+1,:)=[x y min(color1,color2)];
+			id=size(geom.Vertices,1);
+
+			%Update edges i and j
+			edgei=geom.Edges(i,:);
+			edgej=geom.Edges(j,:);
+			geom.Edges(i,:)    =[edgei(1) id       edgei(3)];
+			geom.Edges(end+1,:)=[id       edgei(2) edgei(3)];
+			geom.Edges(j,:)    =[edgej(1) id       edgej(3)];
+			geom.Edges(end+1,:)=[id       edgej(2) edgej(3)];
+
+			%update current edge second tip
+			x2=x; y2=y;
+		end
+	end
+
+end
+
+%Check point outside
+disp('Checking for points outside the domain...');
+i=0;
+num=0;
+while (i<size(geom.Vertices,1)),
+
+	%vertex counter
+	i=i+1;
+
+	%Get coordinates
+	x=geom.Vertices(i,1);
+	y=geom.Vertices(i,2);
+	color=geom.Vertices(i,3);
+
+	%Check that the point is inside the domain
+	if (color~=1 & ~ContourToNodes(x,y,outline(1),1)),
+
+		%Remove points from list of Vertices
+		num=num+1;
+		geom.Vertices(i,:)=[];
+
+		%update edges
+		[posedges dummy]=find(geom.Edges==i);
+		geom.Edges(posedges,:)=[];
+		posedges=find(geom.Edges>i);
+		geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+		%update counter
+		i=i-1;
+	end
+end
+if num,
+	disp(['WARNING: ' num2str(num) ' points outside the domain outline have been removed']);
+end
+
+%Check point spacing
+if ~isnan(tol),
+	disp('Checking point spacing...');
+	i=0;
+	while (i<size(geom.Vertices,1)),
+
+		%vertex counter
+		i=i+1;
+
+		%Get coordinates
+		x1=geom.Vertices(i,1);
+		y1=geom.Vertices(i,2);
+
+		j=i; %test edges located AFTER i only
+		while (j<size(geom.Vertices,1)),
+
+			%vertex counter
+			j=j+1;
+
+			%Get coordinates
+			x2=geom.Vertices(j,1);
+			y2=geom.Vertices(j,2);
+
+			%Check whether the two vertices are too close
+			if ((x2-x1)^2+(y2-y1)^2<tol^2)
+
+				%Remove points from list of Vertices
+				geom.Vertices(j,:)=[];
+
+				%update edges
+				posedges=find(ismember(geom.Edges,j));
+				geom.Edges(posedges)=i;
+				posedges=find(geom.Edges>j);
+				geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+				%update counter
+				j=j-1;
+
+			end
+		end
+	end
+end
+%remove empty edges
+geom.Edges(find(geom.Edges(:,1)==geom.Edges(:,2)),:)=[];
+end % }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamg.py	(revision 18231)
@@ -0,0 +1,486 @@
+import os.path
+import numpy
+from mesh2d import mesh2d
+from collections import OrderedDict
+from pairoptions import pairoptions
+from bamggeom import bamggeom
+from bamgmesh import bamgmesh
+from expread import expread
+from expwrite import expwrite
+from SegIntersect import SegIntersect
+import MatlabFuncs as m
+from BamgMesher import BamgMesher
+from ContourToNodes import ContourToNodes
+
+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'],domaini['y'],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'],rifti['y'],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=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],requiredvertices[:,1],domainfile,0)[0]
+			requiredvertices=requiredvertices[numpy.nonzero(flags)[0],:]
+
+			#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 m.strcmp(md.mesh.elementtype(),'Tria'):
+
+		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['random']=options.getfieldvalue('rand',True)
+	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 = mesh2d()
+	md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
+	md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
+	md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
+	md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
+	md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+	md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
+
+	#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.numberofedges=numpy.size(md.mesh.edges,axis=0)
+	md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices,bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+	md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity
+	md.mesh.elementconnectivity[numpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0
+	md.mesh.elementconnectivity=md.mesh.elementconnectivity.astype(int)
+
+	#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(m.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(m.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/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamgflowband.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamgflowband.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/bamgflowband.m	(revision 18231)
@@ -0,0 +1,36 @@
+function md=bamgflowband(md,x,surf,base,varargin);
+%BAMGFLOWBAND - create flowband mesh with bamg
+%
+%   Usage:
+%      md=bamgflowband(md,x,surf,base,OPTIONS)
+%
+%      surf and bed are the surface elevation and base for each x provided
+%      x must be increasing
+%      OPTIONS are bamg options
+%
+%   Example:
+%      x =[1:100:3000];
+%      h=linspace(1000,300,numel(x));
+%      b=-917/1023*h;
+%      md=bamgflowband(model,b+h,b,'hmax',80,'vertical',1,'Markers',m);
+
+%Write expfile with domain outline
+A=struct();
+A.x=[x;flipud(x);x(1)];
+A.y=[base;flipud(surf);base(1)];
+A.nods = numel(A.x);
+
+%markers:
+m                          = ones(numel(A.x)-1,1); % base        = 1
+m(numel(x))                = 2;                    % right side  = 2
+m(numel(x)+1:2*numel(x)-1) = 3;                    % top surface = 3
+m(2*numel(x))              = 4;                    % left side   = 4
+
+%mesh domain
+md=bamg(model(),'domain',A,'vertical',1,'Markers',m,varargin{:});
+
+%Deal with vertices on bed
+md.mesh.vertexonbase=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbase(find(vertexflags(md.mesh,1)))=1;
+md.mesh.vertexonsurface=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface(find(vertexflags(md.mesh,3)))=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/findsegments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/findsegments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/findsegments.m	(revision 18231)
@@ -0,0 +1,92 @@
+function segments=findsegments(md,varargin)
+%FINDSEGMENTS - build segments model field
+%
+%   Optional inputs:
+%      'mesh.elementconnectivity'
+%
+%   Usage:
+%      segments=findsegments(md,varargin);
+
+%get options
+options=pairoptions(varargin{:});
+
+%Get connectivity
+mesh.elementconnectivity=getfieldvalue(options,'mesh.elementconnectivity',md.mesh.elementconnectivity);
+
+%Now, build the connectivity tables for this mesh if not correclty done
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	if exist(options,'mesh.elementconnectivity'),
+		error(' ''mesh.elementconnectivity'' option does not have thge right size.');
+	else
+		mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+	end
+end
+
+%Recreate the segments
+elementonboundary=double(mesh.elementconnectivity(:,3)==0);
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+%loop over the segments
+for i=1:num_segments,
+
+	%get current element on boundary
+	el1=pos(i);
+
+	%get elements connected to el1
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+
+	%el1 is connected to 2 other elements
+	if length(els2)>1,
+
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the common vertices to the two elements connected to el1 (1 or 2)
+		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
+
+		%get the vertices on the boundary and build segment
+		nods1(find(ismember(nods1,flag)))=[];
+		segments(count,:)=[nods1 el1];
+
+		%swap segment nodes if necessary
+		ord1=find(nods1(1)==md.mesh.elements(el1,:));
+		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+
+	%el1 is connected to only one element
+	else
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the vertex  the el1 to not share with els2
+		flag=setdiff(nods1,md.mesh.elements(els2,:));
+
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+
+				segments(count,:)=[nods el1];
+
+				%swap segment nodes if necessary
+				ord1=find(nods(1)==md.mesh.elements(el1,:));
+				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/intersections.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/intersections.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/intersections.m	(revision 18231)
@@ -0,0 +1,279 @@
+function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
+%INTERSECTIONS Intersections of curves.
+%   Computes the (x,y) locations where two curves intersect.  The curves
+%   can be broken with NaNs or have vertical segments.
+%
+% Example:
+%   [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% where X1 and Y1 are equal-length vectors of at least two points and
+% represent curve 1.  Similarly, X2 and Y2 represent curve 2.
+% X0 and Y0 are column vectors containing the points at which the two
+% curves intersect.
+%
+% ROBUST (optional) set to 1 or true means to use a slight variation of the
+% algorithm that might return duplicates of some intersection points, and
+% then remove those duplicates.  The default is true, but since the
+% algorithm is slightly slower you can set it to false if you know that
+% your curves don't intersect at any segment boundaries.  Also, the robust
+% version properly handles parallel and overlapping segments.
+%
+% The algorithm can return two additional vectors that indicate which
+% segment pairs contain intersections and where they are:
+%
+%   [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
+% (how far along this segment the intersection is).  For example, if I(k) =
+% 45.25 then the intersection lies a quarter of the way between the line
+% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)).  Similarly for
+% the vector J and the segments in (X2,Y2).
+%
+% You can also get intersections of a curve with itself.  Simply pass in
+% only one curve, i.e.,
+%
+%   [X0,Y0] = intersections(X1,Y1,ROBUST);
+%
+% where, as before, ROBUST is optional.
+
+% Version: 1.10, 25 February 2008
+% Author:  Douglas M. Schwarz
+% Email:   dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
+% Real_email = regexprep(Email,{'=','*'},{'@','.'})
+
+
+% Theory of operation:
+%
+% Given two line segments, L1 and L2,
+%
+%   L1 endpoints:  (x1(1),y1(1)) and (x1(2),y1(2))
+%   L2 endpoints:  (x2(1),y2(1)) and (x2(2),y2(2))
+%
+% we can write four equations with four unknowns and then solve them.  The
+% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
+% L1 and L2, t1 is the distance from the starting point of L1 to the
+% intersection relative to the length of L1 and t2 is the distance from the
+% starting point of L2 to the intersection relative to the length of L2.
+%
+% So, the four equations are
+%
+%    (x1(2) - x1(1))*t1 = x0 - x1(1)
+%    (x2(2) - x2(1))*t2 = x0 - x2(1)
+%    (y1(2) - y1(1))*t1 = y0 - y1(1)
+%    (y2(2) - y2(1))*t2 = y0 - y2(1)
+%
+% Rearranging and writing in matrix form,
+%
+%  [x1(2)-x1(1)       0       -1   0;      [t1;      [-x1(1);
+%        0       x2(2)-x2(1)  -1   0;   *   t2;   =   -x2(1);
+%   y1(2)-y1(1)       0        0  -1;       x0;       -y1(1);
+%        0       y2(2)-y2(1)   0  -1]       y0]       -y2(1)]
+%
+% Let's call that A*T = B.  We can solve for T with T = A\B.
+%
+% Once we have our solution we just have to look at t1 and t2 to determine
+% whether L1 and L2 intersect.  If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
+% line segments cross and we can include (x0,y0) in the output.
+%
+% In principle, we have to perform this computation on every pair of line
+% segments in the input data.  This can be quite a large number of pairs so
+% we will reduce it by doing a simple preliminary check to eliminate line
+% segment pairs that could not possibly cross.  The check is to look at the
+% smallest enclosing rectangles (with sides parallel to the axes) for each
+% line segment pair and see if they overlap.  If they do then we have to
+% compute t1 and t2 (via the A\B computation) to see if the line segments
+% cross, but if they don't then the line segments cannot cross.  In a
+% typical application, this technique will eliminate most of the potential
+% line segment pairs.
+
+
+% Input checks.
+error(nargchk(2,5,nargin))
+
+% Adjustments when fewer than five arguments are supplied.
+switch nargin
+	case 2
+		robust = true;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 3
+		robust = x2;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 4
+		robust = true;
+		self_intersect = false;
+	case 5
+		self_intersect = false;
+end
+
+% x1 and y1 must be vectors with same number of points (at least 2).
+if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
+		length(x1) ~= length(y1)
+	error('X1 and Y1 must be equal-length vectors of at least 2 points.')
+end
+% x2 and y2 must be vectors with same number of points (at least 2).
+if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
+		length(x2) ~= length(y2)
+	error('X2 and Y2 must be equal-length vectors of at least 2 points.')
+end
+
+
+% Force all inputs to be column vectors.
+x1 = x1(:);
+y1 = y1(:);
+x2 = x2(:);
+y2 = y2(:);
+
+% Compute number of line segments in each curve and some differences we'll
+% need later.
+n1 = length(x1) - 1;
+n2 = length(x2) - 1;
+xy1 = [x1 y1];
+xy2 = [x2 y2];
+dxy1 = diff(xy1);
+dxy2 = diff(xy2);
+
+% Determine the combinations of i and j where the rectangle enclosing the
+% i'th line segment of curve 1 overlaps with the rectangle enclosing the
+% j'th line segment of curve 2.
+[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...
+	repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...
+	repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...
+	repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...
+	repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...
+	repmat(min(y2(1:end-1),y2(2:end)).',n1,1));
+
+% For one segment in x1,y1, i and j are returned as row vectors.  They
+% need to be column vectors, or iout and jout below will err out.
+% (jes, 6/11/10)
+
+if (size(i,1) == 1)
+    i=i';
+end
+if (size(j,1) == 1)
+    j=j';
+end
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+% At the same time we can remove redundant combinations of i and j in the
+% case of finding intersections of a line with itself.
+if self_intersect
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
+else
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+end
+i(remove) = [];
+j(remove) = [];
+
+% Initialize matrices.  We'll put the T's and B's in matrices and use them
+% one column at a time.  AA is a 3-D extension of A where we'll use one
+% plane at a time.
+n = length(i);
+T = zeros(4,n);
+AA = zeros(4,4,n);
+AA([1 2],3,:) = -1;
+AA([3 4],4,:) = -1;
+AA([1 3],1,:) = dxy1(i,:).';
+AA([2 4],2,:) = dxy2(j,:).';
+B = -[x1(i) x2(j) y1(i) y2(j)].';
+
+% Loop through possibilities.  Trap singularity warning and then use
+% lastwarn to see if that plane of AA is near singular.  Process any such
+% segment pairs to determine if they are colinear (overlap) or merely
+% parallel.  That test consists of checking to see if one of the endpoints
+% of the curve 2 segment lies on the curve 1 segment.  This is done by
+% checking the cross product
+%
+%   (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
+%
+% If this is close to zero then the segments overlap.
+
+% If the robust option is false then we assume no two segment pairs are
+% parallel and just go ahead and do the computation.  If A is ever singular
+% a warning will appear.  This is faster and obviously you should use it
+% only when you know you will never have overlapping or parallel segment
+% pairs.
+
+if robust
+	overlap = false(1,n);
+	warning_state = warning('off','MATLAB:singularMatrix');
+	% Use try-catch to guarantee original warning state is restored.
+	try
+		lastwarn('')
+		for k = 1:n
+			T(:,k) = AA(:,:,k)\B(:,k);
+			[unused,last_warn] = lastwarn;
+			lastwarn('')
+			if strcmp(last_warn,'MATLAB:singularMatrix')
+				% Force in_range(k) to be false.
+				T(1,k) = NaN;
+				% Determine if these segments overlap or are just parallel.
+				overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
+			end
+		end
+		warning(warning_state)
+	catch
+		warning(warning_state)
+		rethrow(lasterror)
+	end
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1;
+	% For overlapping segment pairs the algorithm will return an
+	% intersection point that is at the center of the overlapping region.
+	if any(overlap)
+		ia = i(overlap);
+		ja = j(overlap);
+		% set x0 and y0 to middle of overlapping region.
+		T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
+			min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
+		T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
+			min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
+		selected = in_range | overlap;
+	else
+		selected = in_range;
+	end
+	xy0 = T(3:4,selected).';
+	
+	% Remove duplicate intersection points.
+	[xy0,index] = unique(xy0,'rows');
+	x0 = xy0(:,1);
+	y0 = xy0(:,2);
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		sel_index = find(selected);
+		sel = sel_index(index);
+		iout = i(sel) + T(1,sel).';
+		jout = j(sel) + T(2,sel).';
+	end
+else % non-robust option
+	for k = 1:n
+		[L,U] = lu(AA(:,:,k));
+		T(:,k) = U\(L\B(:,k));
+	end
+	
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1;
+	x0 = T(3,in_range).';
+	y0 = T(4,in_range).';
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		iout = i(in_range) + T(1,in_range).';
+		jout = j(in_range) + T(2,in_range).';
+	end
+end
+
+% Plot the results (useful for debugging).
+% plot(x1,y1,x2,y2,x0,y0,'ok');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.m	(revision 18231)
@@ -0,0 +1,41 @@
+function md=meshconvert(md,varargin)
+%CONVERTMESH - convert mesh to bamg mesh
+%
+%   Usage:
+%      md=meshconvert(md);
+%      md=meshconvert(md,index,x,y);
+
+if nargin~=1 & nargin~=4,
+	help meshconvert
+	error('meshconvert error message: bad usage');
+end
+
+if nargin==1,
+	index = md.mesh.elements;
+	x     = md.mesh.x;
+	y     = md.mesh.y;
+else
+	index = varargin{1};
+	x     = varargin{2};
+	y     = varargin{3};
+end
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgConvertMesh(index,x,y);
+
+% plug results onto model
+md.private.bamg          = struct();
+md.private.bamg.mesh     = bamgmesh(bamgmesh_out);
+md.private.bamg.geometry = bamggeom(bamggeom_out);
+md.mesh.x              = bamgmesh_out.Vertices(:,1);
+md.mesh.y              = bamgmesh_out.Vertices(:,2);
+md.mesh.elements       = bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges          = bamgmesh_out.IssmEdges;
+md.mesh.segments       = bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers = bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.numberofelements = size(md.mesh.elements,1);
+md.mesh.numberofvertices = length(md.mesh.x);
+md.mesh.numberofedges    = size(md.mesh.edges,1);
+md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2)) = 1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/meshconvert.py	(revision 18231)
@@ -0,0 +1,52 @@
+import numpy
+from collections import OrderedDict
+from BamgConvertMesh import BamgConvertMesh 
+from mesh2d   import mesh2d
+from bamgmesh import bamgmesh
+from bamggeom import bamggeom
+
+def meshconvert(md,*args):
+	"""
+	CONVERTMESH - convert mesh to bamg mesh
+
+	   Usage:
+	      md=meshconvert(md);
+	      md=meshconvert(md,index,x,y);
+	"""
+
+	if not len(args)==0 and not len(args)==3:
+		raise TypeError("meshconvert error message: bad usage")
+
+	if not len(args):
+		index = md.mesh.elements
+		x     = md.mesh.x
+		y     = md.mesh.y
+	else:
+		index = args[0]
+		x     = args[1]
+		y     = args[2]
+
+	#call Bamg
+	bamgmesh_out,bamggeom_out=BamgConvertMesh(index,x,y)
+
+	# plug results onto model
+	md.private.bamg             = OrderedDict()
+	md.private.bamg['mesh']     = bamgmesh(bamgmesh_out)
+	md.private.bamg['geometry'] = bamggeom(bamggeom_out)
+	md.mesh                     = mesh2d()
+	md.mesh.x                   = bamgmesh_out['Vertices'][:,0].copy()
+	md.mesh.y                   = bamgmesh_out['Vertices'][:,1].copy()
+	md.mesh.elements            = bamgmesh_out['Triangles'][:,0:3].astype(int)
+	md.mesh.edges               = bamgmesh_out['IssmEdges'].astype(int)
+	md.mesh.segments            = bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+	md.mesh.segmentmarkers      = bamgmesh_out['IssmSegments'][:,3].astype(int)
+
+	#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.numberofedges      = numpy.size(md.mesh.edges,axis=0)
+	md.mesh.vertexonboundary   = numpy.zeros(md.mesh.numberofvertices,bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/mesh_refine_tri4.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/mesh_refine_tri4.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/mesh_refine_tri4.m	(revision 18231)
@@ -0,0 +1,143 @@
+function [ FV ] = mesh_refine_tri4(FV)
+
+% mesh_refine_tri4 - creates 4 triangle from each triangle of a mesh
+%
+% [ FV ] = mesh_refine_tri4( FV )
+%
+% FV.vertices   - mesh vertices (Nx3 matrix)
+% FV.faces      - faces with indices into 3 rows
+%                 of FV.vertices (Mx3 matrix)
+% 
+% For each face, 3 new vertices are created at the 
+% triangle edge midpoints.  Each face is divided into 4
+% faces and returned in FV.
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+% 
+% It is assumed that the vertices are listed in clockwise order in
+% FV.faces (A,B,C above), as viewed from the outside in a RHS coordinate
+% system.
+% 
+% See also: mesh_refine, sphere_tri, sphere_project
+% 
+
+% ---this method is not implemented, but the idea here remains...
+% This can be done until some minimal distance (D) of the mean 
+% distance between vertices of all triangles is achieved.  If
+% no D argument is given, the function refines the mesh once.
+% Alternatively, it could be done until some minimum mean 
+% area of faces is achieved.  As is, it just refines once.
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:35 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  05/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+tic;
+fprintf('...refining mesh (tri4)...')
+
+% NOTE
+% The centroid is located one third of the way from each vertex to 
+% the midpoint of the opposite side. Each median divides the triangle 
+% into two equal areas; all the medians together divide it into six 
+% equal parts, and the lines from the median point to the vertices 
+% divide the whole into three equivalent triangles.
+
+% Each input triangle with vertices labelled [A,B,C] as shown
+% below will be turned into four new triangles:
+%
+% Make new midpoints
+% a = (A+B)/2
+% b = (B+C)/2
+% c = (C+A)/2
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+%
+
+% Initialise a new vertices and faces matrix
+Nvert = size(FV.vertices,1);
+Nface = size(FV.faces,1);
+V2 = zeros(Nface*3,3);
+F2 = zeros(Nface*4,3);
+
+for f = 1:Nface,
+
+    % Get the triangle vertex indices
+    NA = FV.faces(f,1);
+    NB = FV.faces(f,2);
+    NC = FV.faces(f,3);
+
+    % Get the triangle vertex coordinates
+    A = FV.vertices(NA,:);
+    B = FV.vertices(NB,:);
+    C = FV.vertices(NC,:);
+
+    % Now find the midpoints between vertices
+    a = (A + B) ./ 2;
+    b = (B + C) ./ 2;
+    c = (C + A) ./ 2;
+
+    % Find the length of each median
+    %A2blen = sqrt ( sum( (A - b).^2, 2 ) );
+    %B2clen = sqrt ( sum( (B - c).^2, 2 ) );
+    %C2alen = sqrt ( sum( (C - a).^2, 2 ) );
+
+    % Store the midpoint vertices, while
+    % checking if midpoint vertex already exists
+    [FV, Na] = mesh_find_vertex(FV,a);
+    [FV, Nb] = mesh_find_vertex(FV,b);
+    [FV, Nc] = mesh_find_vertex(FV,c);
+
+    % Create new faces with orig vertices plus midpoints
+    F2(f*4-3,:) = [ NA, Na, Nc ];
+    F2(f*4-2,:) = [ Na, NB, Nb ];
+    F2(f*4-1,:) = [ Nc, Nb, NC ];
+    F2(f*4-0,:) = [ Na, Nb, Nc ];
+
+end
+
+% Replace the faces matrix
+FV.faces = F2;
+
+t=toc; fprintf('done (%5.2f sec)\n',t);
+
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [FV, N] = mesh_find_vertex(FV,vertex)
+
+    Vn = size(FV.vertices,1);
+    Va = repmat(vertex,Vn,1);
+    Vexist = find( FV.vertices(:,1) == Va(:,1) & ...
+                   FV.vertices(:,2) == Va(:,2) & ...
+                   FV.vertices(:,3) == Va(:,3) );
+    if Vexist,
+        if size(Vexist) == [1,1],
+            N = Vexist;
+        else,
+            msg = sprintf('replicated vertices');
+            error(msg);
+        end
+    else
+        FV.vertices(end+1,:) = vertex;
+        N = size(FV.vertices,1);
+    end
+
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/planettrimesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/planettrimesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/planettrimesh.m	(revision 18231)
@@ -0,0 +1,19 @@
+function md=planettrimesh(md,shape,radius,refinement)
+%PLANETTRIMESH: build 2d shell mesh
+%
+% Usage: md=planettrimesh(md,shape,radius,refinement)
+%
+
+results = sphere_tri(shape,refinement,radius);
+md.mesh=meshplanet(); %???
+md.mesh.x=results.vertices(:,1);
+md.mesh.y=results.vertices(:,2);
+md.mesh.z=results.vertices(:,3);
+md.mesh.elements=results.faces;
+
+md.mesh.r=sqrt(md.mesh.x.^2+md.mesh.y.^2+md.mesh.z.^2);
+md.mesh.theta=acos(md.mesh.z./md.mesh.r);
+md.mesh.phi=atan2(md.mesh.y,md.mesh.x);
+
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_project.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_project.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_project.m	(revision 18231)
@@ -0,0 +1,65 @@
+function V = sphere_project(v,r,c)
+
+% sphere_project - project point X,Y,Z to the surface of sphere radius r
+% 
+% V = sphere_project(v,r,c)
+% 
+% Cartesian inputs:
+% v is the vertex matrix, Nx3 (XYZ)
+% r is the sphere radius, 1x1 (default 1)
+% c is the sphere centroid, 1x3 (default 0,0,0)
+%
+% XYZ are converted to spherical coordinates and their radius is
+% adjusted according to r, from c toward XYZ (defined with theta,phi)
+% 
+% V is returned as Cartesian 3D coordinates
+% 
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:36 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  06/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~exist('v','var'),
+    msg = sprintf('SPHERE_PROJECT: No input vertices (X,Y,Z)\n');
+    error(msg);
+end
+
+X = v(:,1);
+Y = v(:,2);
+Z = v(:,3);
+
+if ~exist('c','var'),
+    xo = 0;
+    yo = 0;
+    zo = 0;
+else
+    xo = c(1);
+    yo = c(2);
+    zo = c(3);
+end
+
+if ~exist('r','var'), r = 1; end
+
+% alternate method is to use unit vector of V
+% [ n = 'magnitude(V)'; unitV = V ./ n; ]
+% to change the radius, multiply the unitV
+% by the radius required.  This avoids the
+% use of arctan functions, which have branches.
+
+% Convert Cartesian X,Y,Z to spherical (radians)
+theta = atan2( (Y-yo), (X-xo) );
+phi   = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );
+% do not calc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);
+
+%   Recalculate X,Y,Z for constant r, given theta & phi.
+R = ones(size(phi)) * r;
+x = R .* sin(phi) .* cos(theta);
+y = R .* sin(phi) .* sin(theta);
+z = R .* cos(phi);
+
+V = [x y z];
+
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_tri.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_tri.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/planet/sphere_tri.m	(revision 18231)
@@ -0,0 +1,200 @@
+function [FV] = sphere_tri(shape,maxlevel,r,winding)
+
+% sphere_tri - generate a triangle mesh approximating a sphere
+% 
+% Usage: FV = sphere_tri(shape,Nrecurse,r,winding)
+% 
+%   shape is a string, either of the following:
+%   'ico'   starts with icosahedron (most even, default)
+%   'oct'   starts with octahedron
+%   'tetra' starts with tetrahedron (least even)
+%
+%   Nrecurse is int >= 0, setting the recursions (default 0)
+%
+%   r is the radius of the sphere (default 1)
+%
+%   winding is 0 for clockwise, 1 for counterclockwise (default 0).  The
+%   matlab patch command gives outward surface normals for clockwise
+%   order of vertices in the faces (viewed from outside the surface).
+%
+%   FV has fields FV.vertices and FV.faces.  The vertices 
+%   are listed in clockwise order in FV.faces, as viewed 
+%   from the outside in a RHS coordinate system.
+% 
+% The function uses recursive subdivision.  The first
+% approximation is an platonic solid, either an  icosahedron,
+% octahedron or a tetrahedron.  Each level of refinement 
+% subdivides each triangle face by a factor of 4 (see also 
+% mesh_refine).  At each refinement, the vertices are 
+% projected to the sphere surface (see sphere_project).
+% 
+% A recursion level of 3 or 4 is a good sphere surface, if
+% gouraud shading is used for rendering.
+% 
+% The returned struct can be used in the patch command, eg:
+% 
+% % create and plot, vertices: [2562x3] and faces: [5120x3]
+% FV = sphere_tri('ico',4,1);
+% lighting phong; shading interp; figure;
+% patch('vertices',FV.vertices,'faces',FV.faces,...
+%       'facecolor',[1 0 0],'edgecolor',[.2 .2 .6]);
+% axis off; camlight infinite; camproj('perspective');
+% 
+% See also: mesh_refine, sphere_project
+%
+
+% $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% Jon Leech (leech @ cs.unc.edu) 3/24/89
+% icosahedral code added by Jim Buddenhagen (jb1556@daditz.sbc.com) 5/93
+% 06/2002, adapted from c to matlab by Darren.Weber_at_radiology.ucsf.edu
+% 05/2004, reorder of the faces for the 'ico' surface so they are indeed
+% clockwise!  Now the surface normals are directed outward.  Also reset the
+% default recursions to zero, so we can get out just the platonic solids.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+eegversion = '$Revision: 1.2 $';
+fprintf('SPHERE_TRI [v %s]\n',eegversion(11:15)); tic
+
+if ~exist('shape','var') || isempty(shape),
+    shape = 'ico';
+end
+fprintf('...creating sphere tesselation based on %s\n',shape);
+
+% default maximum subdivision level
+if ~exist('maxlevel','var') || isempty(maxlevel) || maxlevel < 0,
+    maxlevel = 0;
+end
+
+% default radius
+if ~exist('r','var') || isempty(r),
+    r = 1;
+end
+
+if ~exist('winding','var') || isempty(winding),
+    winding = 0;
+end
+
+% -----------------
+% define the starting shapes
+
+shape = lower(shape);
+
+switch shape,
+case 'tetra',
+
+    % Vertices of a tetrahedron
+    sqrt_3 = 0.5773502692;
+
+    tetra.v = [  sqrt_3,  sqrt_3,  sqrt_3 ;   % +X, +Y, +Z  - PPP
+                -sqrt_3, -sqrt_3,  sqrt_3 ;   % -X, -Y, +Z  - MMP
+                -sqrt_3,  sqrt_3, -sqrt_3 ;   % -X, +Y, -Z  - MPM
+                 sqrt_3, -sqrt_3, -sqrt_3 ];  % +X, -Y, -Z  - PMM
+
+    % Structure describing a tetrahedron
+    tetra.f = [ 1, 2, 3;
+                1, 4, 2;
+                3, 2, 4;
+                4, 1, 3 ];
+
+    FV.vertices = tetra.v;
+    FV.faces    = tetra.f;
+
+case 'oct',
+
+    % Six equidistant points lying on the unit sphere
+    oct.v = [  1,  0,  0 ;  %  X
+              -1,  0,  0 ; 	% -X
+               0,  1,  0 ;  %  Y
+               0, -1,  0 ; 	% -Y
+               0,  0,  1 ; 	%  Z
+               0,  0, -1 ];	% -Z
+
+    % Join vertices to create a unit octahedron
+    oct.f = [ 1 5 3 ;    %  X  Z  Y  -  First the top half
+              3 5 2 ;    %  Y  Z -X
+              2 5 4 ;    % -X  Z -Y
+              4 5 1 ;    % -Y  Z  X
+              1 3 6 ;    %  X  Y -Z  -  Now the bottom half
+              3 2 6 ;    %  Y  Z -Z
+              2 4 6 ;    % -X  Z -Z
+              4 1 6 ];   % -Y  Z -Z
+
+    FV.vertices = oct.v;
+    FV.faces    = oct.f;
+
+case 'ico',
+
+    % Twelve vertices of icosahedron on unit sphere
+    tau = 0.8506508084; % t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2)
+    one = 0.5257311121; % one=1/sqrt(1+t^2) , unit sphere
+
+    ico.v( 1,:) = [  tau,  one,    0 ]; % ZA
+    ico.v( 2,:) = [ -tau,  one,    0 ]; % ZB
+    ico.v( 3,:) = [ -tau, -one,    0 ]; % ZC
+    ico.v( 4,:) = [  tau, -one,    0 ]; % ZD
+    ico.v( 5,:) = [  one,   0 ,  tau ]; % YA
+    ico.v( 6,:) = [  one,   0 , -tau ]; % YB
+    ico.v( 7,:) = [ -one,   0 , -tau ]; % YC
+    ico.v( 8,:) = [ -one,   0 ,  tau ]; % YD
+    ico.v( 9,:) = [   0 ,  tau,  one ]; % XA
+    ico.v(10,:) = [   0 , -tau,  one ]; % XB
+    ico.v(11,:) = [   0 , -tau, -one ]; % XC
+    ico.v(12,:) = [   0 ,  tau, -one ]; % XD
+
+    % Structure for unit icosahedron
+    ico.f = [  5,  8,  9 ;
+               5, 10,  8 ;
+               6, 12,  7 ;
+               6,  7, 11 ;
+               1,  4,  5 ;
+               1,  6,  4 ;
+               3,  2,  8 ;
+               3,  7,  2 ;
+               9, 12,  1 ;
+               9,  2, 12 ;
+              10,  4, 11 ;
+              10, 11,  3 ;
+               9,  1,  5 ;
+              12,  6,  1 ;
+               5,  4, 10 ;
+               6, 11,  4 ;
+               8,  2,  9 ;
+               7, 12,  2 ;
+               8, 10,  3 ;
+               7,  3, 11 ];
+
+    FV.vertices = ico.v;
+    FV.faces    = ico.f;
+end
+
+% -----------------
+% refine the starting shapes with subdivisions
+if maxlevel,
+
+    % Subdivide each starting triangle (maxlevel) times
+    for level = 1:maxlevel,
+
+        % Subdivide each triangle and normalize the new points thus
+        % generated to lie on the surface of a sphere radius r.
+        FV = mesh_refine_tri4(FV);
+        FV.vertices = sphere_project(FV.vertices,r);
+
+        % An alternative might be to define a min distance
+        % between vertices and recurse or use fminsearch
+
+    end
+end
+
+if winding,
+    fprintf('...returning counterclockwise vertex order (viewed from outside)\n');
+    FV.faces = FV.faces(:,[1 3 2]);
+else
+    fprintf('...returning clockwise vertex order (viewed from outside)\n');
+end
+
+t=toc; fprintf('...done (%6.2f sec)\n\n',t);
+
+return
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshaddrifts.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshaddrifts.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshaddrifts.m	(revision 18231)
@@ -0,0 +1,85 @@
+function md=meshaddrifts(md,riftname)
+%MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
+%
+%   Usage:
+%      md=meshaddrifts(md,riftname);
+%
+%        where md is a model with a preexisting mesh, and riftname is the name of an .exp file.
+%        The format of the riftname file is as follows: a list of pairs of closed and open contours. 
+%        The closed contour defines the envelop of the rift, the open contour that follows in the 
+%        file defines the rift. The density of the rift should be chosen carefully in the file, as it 
+%        will be used to define the rift contour density of the mesh. The open contour density will 
+%        be preserved. There can be as many pairs of closed contour and rift contour as wished.
+
+%read rift: 
+domains=expread(riftname,1);
+contours=domains(1:2:end);
+rifts=domains(2:2:end);
+
+%now loop over rifts: 
+for rift_i=1:length(rifts),
+
+	%refine rift to desired resolution: 
+	contour=contours(rift_i);
+	rift=rifts(rift_i);
+
+	delete('Meshaddrifts.Rift.exp');
+	expwrite(rift,'Meshaddrifts.Rift.Coarse.exp');
+	expcoarsen('Meshaddrifts.Rift.exp','Meshaddrifts.Rift.Coarse.exp',rift.density);
+	delete('Meshaddrifts.Rift.Coarse.exp');
+
+	%extract model:
+	expwrite(contour,'Meshaddrifts.Contour.exp');
+	md2=modelextract(md,'Meshaddrifts.Contour.exp');
+
+	%create domain of md2 model: 
+	md2.mesh.segments=contourenvelope(md2,'Meshaddrifts.Contour.exp');
+	domain_index=md2.mesh.segments(1,1:2);
+	while (domain_index(end)~=domain_index(1)),
+		pos=find(md2.mesh.segments(:,1)==domain_index(end));
+		domain_index(end+1)=md2.mesh.segments(pos,2);
+	end
+
+	domain.x=md2.mesh.x(domain_index);
+	domain.y=md2.mesh.y(domain_index);
+	domain.name='Meshaddrifts.Domain.exp';
+	domain.density=1;
+	expwrite(domain,'Meshaddrifts.Domain.exp');
+
+	%unloop domain index: used for later.
+	domain_index=domain_index(1:end-1);
+
+	%remesh md2 using new domain outline, and rift profile: 
+	md2=meshnodensity(md2,'Meshaddrifts.Domain.exp','Meshaddrifts.Rift.exp');
+	md2=meshprocessrifts(md2);
+
+	%plug md2 mesh into md mesh: 
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,md.mesh.numberofelements,md.mesh.numberofvertices,elconv,nodeconv,elconv2,nodeconv2]=meshplug(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,...
+								md2.mesh.elements,md2.mesh.x,md2.mesh.y,md2.mesh.z,md2.extractednodes,md2.extractedelements,domain_index);
+
+	%update md2 rifts using elconv and nodeconv, and plug them into md: 
+	md2.rifts=updateriftindexing(md2.rifts,elconv2,nodeconv2);
+
+	for i=1:md.rifts.numrifts,
+		md.rifts.riftstruct(i)=updateriftindexing(md.rifts.riftstruct(i),elconv,nodeconv);
+	end
+
+	if md.rifts.numrifts==0,
+		md.rifts.riftstruct=md2.rifts;
+		md.rifts.numrifts=1;
+	else
+		md.rifts.riftstruct(end+1,1)=md2.rifts;
+		md.rifts.numrifts=md.rifts.numrifts+1;
+	end
+
+	md.mesh.segments(:,1:2)=nodeconv(md.mesh.segments(:,1:2));
+	md.mesh.segments(:,3)=elconv(md.mesh.segments(:,3));
+
+end
+
+%finish up "a la" mesh.h
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshplug.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshplug.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshplug.m	(revision 18231)
@@ -0,0 +1,85 @@
+function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain)
+%MESHPLUG - embed mesh into another one
+%     See also meshaddrifts
+
+%initialize elconv,nodeconv conversion tables from md mesh to new md mesh
+elconv=1:size(elements,1); elconv=elconv';
+nodeconv=1:size(x,1); nodeconv=nodeconv';
+
+%take away old elements in area of interest: 
+elements(extractedelements,:)=[];
+element_offset=size(elements,1);
+
+%update elconv after having extracted the area of interest elements
+temp_elconv=elconv; temp_elconv(extractedelements)=[];
+temp_elconvnum=1:length(temp_elconv);
+elconv(temp_elconv)=temp_elconvnum;
+elconv(extractedelements)=NaN;
+
+%initialize elconv2 and nodeconv2, conversion tables from md2 mesh to new md mesh
+elconv2=1:size(elements2,1);elconv2=elconv2'+element_offset;
+nodeconv2=(size(x,1)+1):(size(x,1)+size(x2,1)); nodeconv2=nodeconv2';
+
+extractednodes_minusborder=extractednodes;
+extractednodes_minusborder(domain)=[];
+
+x(extractednodes_minusborder)=NaN;
+y(extractednodes_minusborder)=NaN;
+
+%now, plug md2 mesh: 
+
+%first, offset all ids of md2 mesh
+elements2=elements2+length(x);
+
+%NaN border nodes in second mesh
+x2(1:length(domain))=NaN;
+y2(1:length(domain))=NaN;
+
+%redirect border nodes in elements2  to elements
+for i=1:length(domain),
+	pos=find(elements2==(i+length(x)));
+	elements2(pos)=extractednodes(domain(i));
+end
+
+%same deal for nodeconv2:
+for i=1:length(domain),
+	nodeconv2(i)=extractednodes(domain(i));
+end
+
+%plug elements
+elements=[elements;elements2];
+
+%now, increase number of nodes
+x=[x; x2];
+y=[y; y2];
+z=[z; z2];
+
+%now, get rid of NaN in x:
+while  ~isempty(find(isnan(x))),
+
+	pos=find(isnan(x));
+	node=pos(1);
+
+	%collapse node
+	x(node)=[];
+	y(node)=[];
+	z(node)=[];
+
+	%renumber all nodes > node in elements
+	pos=find(elements>node);
+	elements(pos)=elements(pos)-1;
+
+	%same deal for nodeconv2: 
+	pos=find(nodeconv2>node);
+	nodeconv2(pos)=nodeconv2(pos)-1;
+
+end
+
+numberofnodes=length(x);
+numberofelements=length(elements);
+
+%finish nodeconv: 
+temp_nodeconv=nodeconv;  temp_nodeconv(extractednodes_minusborder)=[];
+temp_nodeconvnum=1:length(temp_nodeconv);
+nodeconv(temp_nodeconv)=temp_nodeconvnum;
+nodeconv(extractednodes_minusborder)=NaN;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 18231)
@@ -0,0 +1,100 @@
+function md=meshprocessoutsiderifts(md,domainoutline)
+%MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline
+%
+%   Usage:
+%      md=meshprocessoutsiderifts(md,domain)
+%
+
+%go through rifts, and figure out which ones touch the domain outline
+for i=1:length(md.rifts.riftstruct),
+
+	%first, flag nodes that belong to the domain outline
+	flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+
+	rift=md.rifts.riftstruct(i);
+	tips=rift.tips;
+	outsidetips=tips(find(flags(rift.tips)==0));
+
+	%we have found outsidetips, tips that touch the domain outline. go through them
+	for j=1:length(outsidetips),
+
+		tip=outsidetips(j);
+		%find tip in the segments, take first segment (there should be 2) that holds tip, 
+		%and node_connected_to_tip is the other node on this segment:
+		tipindex=find(rift.segments(:,1)==tip); 
+		if length(tipindex),
+			tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,2);
+		else
+			tipindex=find(rift.segments(:,2)==tip); tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,1);
+		end
+
+		%ok, we have the tip node, and the first node connected to it, on the rift. Now, 
+		%identify all the elements that are connected to the tip, and that are on the same 
+		%side of the rift.
+		A=tip;
+		B=node_connected_to_tip;
+
+		elements=[];
+
+		while flags(B), %as long as B does not belong to the domain outline, keep looking.
+			%detect elements on edge A,B:
+			edgeelements=ElementsFromEdge(md.mesh.elements,A,B);
+			%rule out those we already detected
+			already_detected=ismember(edgeelements,elements);
+			nextelement=edgeelements(find(~already_detected));
+			%add new detected element to the list of elements we are looking for.
+			elements=[elements;nextelement];
+			%new B:
+			B=md.mesh.elements(nextelement,find(~ismember(md.mesh.elements(nextelement,:),[A B])));
+		end
+
+		%take the list of elements on one side of the rift that connect to the tip, 
+		%and duplicate the tip on them, so as to open the rift to the outside.
+		num=length(md.mesh.x)+1;
+		md.mesh.x=[md.mesh.x;md.mesh.x(tip)];
+		md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
+		md.mesh.numberofvertices=num;
+
+		%replace tip in elements
+		newelements=md.mesh.elements(elements,:);
+		pos=find(newelements==tip);
+		newelements(pos)=num;
+		md.mesh.elements(elements,:)=newelements;
+		md.rifts.riftstruct(i).tips=[md.rifts.riftstruct(i).tips num];
+
+		%deal with segments
+		tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
+		for k=1:length(tipsegments),
+			segment_index=tipsegments(k);
+			pos=find(md.mesh.segments(segment_index,1:2)~=tip);
+			other_node=md.mesh.segments(segment_index,pos);
+			if ~isconnected(md.mesh.elements,other_node,tip),
+				pos=find(md.mesh.segments(segment_index,1:2)==tip);
+				md.mesh.segments(segment_index,pos)=num;
+			end
+		end
+	end
+end
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+end
+
+function flag=isconnected(elements,A,B)% {{{
+	%ISCONNECTED: are two nodes connected by a triangulation?
+	%
+	%   Usage: flag=isconnected(elements,A,B)
+	%
+	%
+
+	elements=ElementsFromEdge(elements,A,B);
+	if isempty(elements),
+		flag=0;
+	else
+		flag=1;
+	end
+end % }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessoutsiderifts.py	(revision 18231)
@@ -0,0 +1,104 @@
+import numpy
+from ElementsFromEdge import ElementsFromEdge
+import MatlabFuncs as m
+
+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,md.mesh.y,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,int)
+
+			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=m.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(m.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-1,:]
+			pos=numpy.nonzero(newelements==tip)
+			newelements[pos]=num
+			md.mesh.elements[elements-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.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x),bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+	md.rifts.numrifts=length(md.rifts.riftstruct)
+
+	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/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.m	(revision 18231)
@@ -0,0 +1,64 @@
+function md=meshprocessrifts(md,domainoutline)
+%MESHPROCESSRIFTS - process mesh when rifts are present
+%
+%   split rifts inside mesh (rifts are defined by presence of
+%   segments inside the domain outline)
+%   if domain outline is provided, check for rifts that could touch it, and open them up.
+%
+%   Usage:
+%      md=meshprocessrifts(md,domainoutline)
+%
+%   Ex: 
+%      md=meshprocessrifts(md,'DomainOutline.exp');
+%
+
+%some checks on arguments: 
+if nargout~=1,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+if nargin~=2,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+%Call MEX file
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers);
+if ~isstruct(md.rifts.riftstruct),
+	error('TriMeshProcessRifts did not find any rift');
+end
+
+%Fill in rest of fields:
+numrifts=length(md.rifts.riftstruct);
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%get coordinates of rift tips
+for i=1:numrifts,
+	md.rifts.riftstruct(i).tip1coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(1)) md.mesh.y(md.rifts.riftstruct(i).tips(1))];
+	md.rifts.riftstruct(i).tip2coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(2)) md.mesh.y(md.rifts.riftstruct(i).tips(2))];
+end
+
+%In case we have rifts that open up the domain outline, we need to open them: 
+flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+found=0;
+for i=1:numrifts,
+	if flags(md.rifts.riftstruct(i).tips(1))==0,
+		found=1;
+		break;
+	end
+	if flags(md.rifts.riftstruct(i).tips(2))==0,
+		found=1;
+		break;
+	end
+end
+if found,
+	md=meshprocessoutsiderifts(md,domainoutline);
+end
+
+%get elements that are not correctly oriented in the correct direction:
+aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+pos=find(aires<0);
+md.mesh.elements(pos,:)=[md.mesh.elements(pos,2) md.mesh.elements(pos,1) md.mesh.elements(pos,3)];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshprocessrifts.py	(revision 18231)
@@ -0,0 +1,64 @@
+import numpy
+from TriMeshProcessRifts import TriMeshProcessRifts
+from ContourToMesh import ContourToMesh
+from meshprocessoutsiderifts import meshprocessoutsiderifts
+from GetAreas import GetAreas
+
+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.elements=md.mesh.elements.astype(int)
+	md.mesh.x=md.mesh.x.reshape(-1)
+	md.mesh.y=md.mesh.y.reshape(-1)
+	md.mesh.segments=md.mesh.segments.astype(int)
+	md.mesh.segmentmarkers=md.mesh.segmentmarkers.astype(int)
+	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.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x),bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+
+	#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,md.mesh.y,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/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshyamsrecreateriftsegments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 18231)
@@ -0,0 +1,90 @@
+function md=meshyamsrecreateriftsegments(md)
+
+	%recreate rift segments: just used for yams. temporaroy routine.
+	pos_record=[];
+	if md.rifts.numrifts,
+		for i=1:md.rifts.numrifts,
+			rift=md.rifts.riftstruct(i);
+
+			%closed rifts first:
+			if length(rift.tips)==2,
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos,1);
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos,1);
+
+				%start from tip1, and build segments of this rift. 
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2];
+
+			else
+				%ok, this is a rift that opens up to the domain outline.  One tip is going to be 
+				%double, the other one, single. We are going to start from the single tip, towards the two 
+				%other doubles
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos1=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos1,1);
+				pos2=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos2,1);
+				if length(tip1)==2,
+					%swap.
+					temp=tip1; tip1=tip2; tip2=temp;
+					temp=pos1; pos1=pos2; pos2=temp;
+					pos=pos1;
+				else
+					pos=pos1;
+				end
+
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if ((riftsegs(end,2)==tip2(1)) | (riftsegs(end,2)==tip2(2))), 
+						%figure out which tip we reached
+						if riftsegs(end,2)==tip2(1), index=2; else index=1; end
+						break;
+					end
+				end
+
+				%ok, now, we start from the other tip2, towards tip1
+				pos=pos2(index);
+				pos_record=[pos_record; pos];
+				riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2(1) tip2(2)];
+
+			end
+		end
+	end
+	%take out rift segments from segments
+	md.mesh.segments(pos_record,:)=[];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsonmesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsonmesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsonmesh.m	(revision 18231)
@@ -0,0 +1,25 @@
+function tips=rifttipsonmesh(md,riftoutline)
+%RIFTTIPSONMESH: identify, using a rift outline, the nodes that are tips of 
+%                rifts.
+
+%read rifts from outline file
+rifts=expread(riftoutline);
+
+tips=[];
+
+for i=1:length(rifts),
+	rift=rifts(i);
+
+	x_tip=rift.x(1);
+	y_tip=rift.y(1);
+
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+	x_tip=rift.x(end);
+	y_tip=rift.y(end);
+
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsrefine.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsrefine.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/rifttipsrefine.m	(revision 18231)
@@ -0,0 +1,26 @@
+function md=rifttipsrefine(md,filename,resolution,circleradius)
+%RIFTTIPSREFINE - refine mesh near rift tips
+%
+%   Usage:
+%      md=rifttipsrefine(md,filename,resolution,circleradius);
+
+numberofnodes=50;
+
+%take rifts, and create refinement circles around tips
+rifts=expread(filename,1);
+
+!echo -n "" > Circles.exp
+for i=1:length(rifts),
+	tip1=[rifts(i).x(1) rifts(i).y(1)];
+	tip2=[rifts(i).x(end) rifts(i).y(end)];
+	%create circle around tip
+	expcreatecircle('Circle1.exp',tip1(1),tip1(2),circleradius,numberofnodes);
+	expcreatecircle('Circle2.exp',tip2(1),tip2(2),circleradius,numberofnodes);
+	!cat Circles.exp Circle1.exp Circle2.exp > Circles2.exp
+	!mv Circles2.exp Circles.exp
+	!rm -rf Circle1.exp Circle2.exp
+end
+
+md=meshexprefine(md,'Circles.exp',resolution);
+
+system('rm -rf Circles.exp');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/updateriftindexing.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/updateriftindexing.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/rifts/updateriftindexing.m	(revision 18231)
@@ -0,0 +1,11 @@
+function rift=updateriftindexing(rift,elconv,nodeconv)
+%UPDATERIFTINDEXING - update rift indexing, using mesh to new mesh conversion tables
+%     See also meshaddrift
+
+rift.segments(:,1:2)=nodeconv(rift.segments(:,1:2));
+rift.segments(:,3)=elconv(rift.segments(:,3));
+rift.pairs=elconv(rift.pairs);
+rift.tips=nodeconv(rift.tips);
+
+rift.penaltypairs(:,1:2)=nodeconv(rift.penaltypairs(:,1:2));
+rift.penaltypairs(:,3:4)=elconv(rift.penaltypairs(:,3:4));
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.m	(revision 18231)
@@ -0,0 +1,47 @@
+function md=roundmesh(md,radius,resolution)
+%ROUNDMESH - create an unstructured round mesh 
+%
+%   This script will generate a structured round mesh
+%   - radius     : specifies the radius of the circle in meters
+%   - resolution : specifies the resolution in meters
+%
+%   Usage:
+%      md=roundmesh(md,radius,resolution)
+
+%First we have to create the domain outline 
+
+%Get number of points on the circle
+pointsonedge=floor((2.*pi*radius) / resolution);
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
+theta=(0.:2.*pi/pointsonedge:2.*pi*(1.-1./pointsonedge))';
+x_list=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');
+
+%Call Bamg
+md=triangle(md,'RoundDomainOutline.exp',resolution);
+%md=bamg(md,'domain','RoundDomainOutline.exp','hmin',resolution);
+
+%move the closest node to the center
+[mini pos]=min(md.mesh.x.^2+md.mesh.y.^2);
+md.mesh.x(pos)=0.;
+md.mesh.y(pos)=0.;
+
+%delete domain
+delete('RoundDomainOutline.exp')
+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/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/roundmesh.py	(revision 18231)
@@ -0,0 +1,61 @@
+import numpy
+import os
+from collections import OrderedDict
+from expwrite import expwrite
+from triangle import triangle
+
+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/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.m	(revision 18231)
@@ -0,0 +1,70 @@
+function md=squaremesh(md,Lx,Ly,nx,ny)
+%SQUAREMESH - create a structured square mesh 
+%
+%   This script will generate a structured square mesh
+%   Lx and Ly are the dimension of the domain (in meters)
+%   nx anx ny are the number of nodes in the x and y direction
+%   The coordinates x and y returned are in meters.
+%
+%   Usage:
+%      [md]=squaremesh(md,Lx,Ly,nx,ny)
+
+%get number of elements and number of nodes
+nel=(nx-1)*(ny-1)*2;
+nods=nx*ny;
+
+%initialization
+index=zeros(nel,3);
+x=zeros(nx*ny,1);
+y=zeros(nx*ny,1);
+
+%create coordinates
+for n=1:nx,
+	for m=1:ny,
+		x((n-1)*ny+m)=(n-1.);
+		y((n-1)*ny+m)=(m-1.);
+	end
+end
+
+%create index
+for n=1:(nx-1)
+	for m=1:(ny-1),
+		A=(n-1)*ny+m;
+		B=A+1;
+		C=n*ny+m;
+		D=C+1;
+		index((n-1)*(ny-1)*2+2*(m-1)+1,:)=[A C B];
+		index((n-1)*(ny-1)*2+2*m,:)=[B C D];
+	end
+end
+
+%Scale  x and y
+x=x/max(x)*Lx;
+y=y/max(y)*Ly;
+
+%create segments
+segments=zeros(2*(nx-1)+2*(ny-1),3);
+%left edge:
+segments(1:ny-1,:)=[[2:ny]' [1:ny-1]' 2*[1:ny-1]'-1];
+%right edge:
+segments(ny:2*(ny-1),:)=[[ny*(nx-1)+1:nx*ny-1]' [ny*(nx-1)+2:nx*ny]' 2*[(ny-1)*(nx-2)+1:(nx-1)*(ny-1)]'];
+%front edge:
+segments(2*(ny-1)+1:2*(ny-1)+(nx-1),:)=[[2*ny:ny:ny*nx]' [ny:ny:ny*(nx-1)]' [2*(ny-1):2*(ny-1):2*(nx-1)*(ny-1)]'];
+%back edge
+segments(2*(ny-1)+(nx-1)+1:2*(nx-1)+2*(ny-1),:)=[[1:ny:(nx-2)*ny+1]' [ny+1:ny:ny*(nx-1)+1]' [1:2*(ny-1):2*(nx-2)*(ny-1)+1]'];
+
+%plug coordinates and nodes
+md.mesh=mesh2d();
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.numberofvertices=nods;
+md.mesh.vertexonboundary=zeros(nods,1);md.mesh.vertexonboundary(segments(:,1:2))=1;
+
+%plug elements
+md.mesh.elements=index;
+md.mesh.segments=segments;
+md.mesh.numberofelements=nel;
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/squaremesh.py	(revision 18231)
@@ -0,0 +1,76 @@
+import numpy
+from NodeConnectivity import NodeConnectivity
+from ElementConnectivity import ElementConnectivity 
+from mesh2d import mesh2d
+
+def squaremesh(md,Lx,Ly,nx,ny):
+	"""
+	SQUAREMESH - create a structured square mesh 
+
+	   This script will generate a structured square mesh
+	   Lx and Ly are the dimension of the domain (in meters)
+	   nx anx ny are the number of nodes in the x and y direction
+	   The coordinates x and y returned are in meters.
+
+	   Usage:
+	      [md]=squaremesh(md,Lx,Ly,nx,ny)
+	"""
+
+	#get number of elements and number of nodes
+	nel=(nx-1)*(ny-1)*2
+	nods=nx*ny
+
+	#initialization
+	index=numpy.zeros((nel,3),int)
+	x=numpy.zeros((nx*ny))
+	y=numpy.zeros((nx*ny))
+
+	#create coordinates
+	for n in xrange(0,nx):
+		for m in xrange(0,ny):
+			x[n*ny+m]=float(n)
+			y[n*ny+m]=float(m)
+
+	#create index
+	for n in xrange(0,nx-1):
+		for m in xrange(0,ny-1):
+			A=n*ny+(m+1)
+			B=A+1
+			C=(n+1)*ny+(m+1)
+			D=C+1
+			index[n*(ny-1)*2+2*m,:]=[A,C,B]
+			index[n*(ny-1)*2+2*(m+1)-1,:]=[B,C,D]
+
+	#Scale  x and y
+	x=x/numpy.max(x)*Lx
+	y=y/numpy.max(y)*Ly
+
+	#create segments
+	segments=numpy.zeros((2*(nx-1)+2*(ny-1),3),int)
+	#left edge:
+	segments[0:ny-1,:]=numpy.hstack((numpy.arange(2,ny+1).reshape(-1,1),numpy.arange(1,ny).reshape(-1,1),(2*numpy.arange(1,ny)-1).reshape(-1,1)))
+	#right edge:
+	segments[ny-1:2*(ny-1),:]=numpy.hstack((numpy.arange(ny*(nx-1)+1,nx*ny).reshape(-1,1),numpy.arange(ny*(nx-1)+2,nx*ny+1).reshape(-1,1),2*numpy.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1).reshape(-1,1)))
+	#front edge:
+	segments[2*(ny-1):2*(ny-1)+(nx-1),:]=numpy.hstack((numpy.arange(2*ny,ny*nx+1,ny).reshape(-1,1),numpy.arange(ny,ny*(nx-1)+1,ny).reshape(-1,1),numpy.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)).reshape(-1,1)))
+	#back edge
+	segments[2*(ny-1)+(nx-1):2*(nx-1)+2*(ny-1),:]=numpy.hstack((numpy.arange(1,(nx-2)*ny+2,ny).reshape(-1,1),numpy.arange(ny+1,ny*(nx-1)+2,ny).reshape(-1,1),numpy.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)).reshape(-1,1)))
+
+	#plug coordinates and nodes
+	md.mesh=mesh2d()
+	md.mesh.x=x
+	md.mesh.y=y
+	md.mesh.numberofvertices=nods
+	md.mesh.vertexonboundary=numpy.zeros((nods),bool)
+	md.mesh.vertexonboundary[segments[:,0:2]-1]=True
+
+	#plug elements
+	md.mesh.elements=index
+	md.mesh.segments=segments
+	md.mesh.numberofelements=nel
+
+	#Now, build the connectivity tables for this mesh.
+	[md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)
+	[md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.m	(revision 18231)
@@ -0,0 +1,75 @@
+function md=triangle(md,domainname,varargin)
+%TRIANGLE - create model mesh using the triangle package
+%
+%   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+%   where md is a @model object, domainname is the name of an Argus domain outline file, 
+%   and resolution is a characteristic length for the mesh (same unit as the domain outline
+%   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+%
+%   Usage:
+%      md=triangle(md,domainname,resolution)
+%   or md=triangle(md,domainname,riftname, resolution)
+%
+%   Examples:
+%      md=triangle(md,'DomainOutline.exp',1000);
+%      md=triangle(md,'DomainOutline.exp','Rifts.exp',1500);
+
+%Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would 
+%be made of 1000*1000 area squares). 
+if (nargin==3),
+	resolution=varargin{1};
+	riftname='';
+end
+if (nargin==4),
+	riftname=varargin{1};
+	resolution=varargin{2};
+end
+
+%Check that mesh was not already run, and warn user: 
+if md.mesh.numberofelements~=0,
+	choice=input('This model already has a mesh. Are you sure you want to go ahead? (y/n)','s');
+	if ~strcmp(choice,'y')
+		disp('no meshing done ... exiting');
+		return
+	end
+end
+
+area=resolution^2;
+
+%Mesh using TriMesh
+[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area);
+
+%check that all the created nodes belong to at least one element
+orphan=find(~ismember([1:length(x)],sort(unique(elements(:)))));
+for i=1:length(orphan),
+	disp('WARNING: removing orphans');
+	%get rid of the orphan node i
+	%update x and y
+	x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+	y=[y(1:orphan(i)-(i-1)-1); y(orphan(i)-(i-1)+1:end)];
+	%update elements
+	pos=find(elements>orphan(i)-(i-1));
+	elements(pos)=elements(pos)-1;
+	%update segments
+	pos1=find(segments(:,1)>orphan(i)-(i-1));
+	pos2=find(segments(:,2)>orphan(i)-(i-1));
+	segments(pos1,1)=segments(pos1,1)-1;
+	segments(pos2,2)=segments(pos2,2)-1;
+end
+
+%plug into md
+md.mesh=mesh2d();
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.elements=elements;
+md.mesh.segments=segments;
+md.mesh.segmentmarkers=segmentmarkers;
+
+%Fill in rest of fields:
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle.py	(revision 18231)
@@ -0,0 +1,62 @@
+import numpy
+from mesh2d import mesh2d
+from TriMesh import TriMesh
+from NodeConnectivity import NodeConnectivity
+from ElementConnectivity import ElementConnectivity
+import MatlabFuncs as m
+
+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:
+		choice = raw_input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
+		if not m.strcmp(choice,'y'):
+			print 'no meshing done ... exiting'
+			return None
+
+	area = resolution**2
+
+	#Mesh using TriMesh
+	md.mesh=mesh2d()
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMesh(domainname,riftname,area)
+	md.mesh.elements=md.mesh.elements.astype(int)
+	md.mesh.segments=md.mesh.segments.astype(int)
+	md.mesh.segmentmarkers=md.mesh.segmentmarkers.astype(int)
+
+	#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.vertexonboundary = numpy.zeros(md.mesh.numberofvertices,bool)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
+
+	#Now, build the connectivity tables for this mesh.
+	[md.mesh.vertexconnectivity] = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
+	[md.mesh.elementconnectivity] = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle2dvertical.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle2dvertical.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/mesh/triangle2dvertical.m	(revision 18231)
@@ -0,0 +1,62 @@
+function md=triangle(md,domainname,resolution)
+%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)
+%
+%   Examples:
+%      md=triangle(md,'DomainOutline.exp',1000);
+
+%Check that mesh was not already run, and warn user: 
+if md.mesh.numberofelements~=0,
+	choice=input('This model already has a mesh. Are you sure you want to go ahead? (y/n)','s');
+	if ~strcmp(choice,'y')
+		disp('no meshing done ... exiting');
+		return
+	end
+end
+
+area=resolution^2;
+
+%Mesh using TriMesh
+[elements,x,z,segments,segmentmarkers]=TriMesh(domainname,'',area);
+
+%check that all the created nodes belong to at least one element
+orphan=find(~ismember([1:length(x)],sort(unique(elements(:)))));
+for i=1:length(orphan),
+	disp('WARNING: removing orphans');
+	%get rid of the orphan node i
+	%update x and y
+	x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+	z=[z(1:orphan(i)-(i-1)-1); z(orphan(i)-(i-1)+1:end)];
+	%update elements
+	pos=find(elements>orphan(i)-(i-1));
+	elements(pos)=elements(pos)-1;
+	%update segments
+	pos1=find(segments(:,1)>orphan(i)-(i-1));
+	pos2=find(segments(:,2)>orphan(i)-(i-1));
+	segments(pos1,1)=segments(pos1,1)-1;
+	segments(pos2,2)=segments(pos2,2)-1;
+end
+
+%plug into md
+md.mesh=mesh2dvertical();
+md.mesh.x=x;
+md.mesh.z=z;
+md.mesh.elements=elements;
+md.mesh.segments=segments;
+md.mesh.segmentmarkers=segmentmarkers;
+
+%Fill in rest of fields:
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/MatlabFuncs.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/MatlabFuncs.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/MatlabFuncs.py	(revision 18231)
@@ -0,0 +1,107 @@
+def oshostname():
+	import socket
+
+	return socket.gethostname()
+
+def ispc():
+	import platform
+
+	if 'Windows' in platform.system():
+		return True
+	else:
+		return False
+
+def ismac():
+	import platform
+
+	if 'Darwin' in platform.system():
+		return True
+	else:
+		return False
+
+def strcmp(s1,s2):
+
+	if s1 == s2:
+		return True
+	else:
+		return False
+
+def strncmp(s1,s2,n):
+
+	if s1[0:n] == s2[0:n]:
+		return True
+	else:
+		return False
+
+def strcmpi(s1,s2):
+
+	if s1.lower() == s2.lower():
+		return True
+	else:
+		return False
+
+def strncmpi(s1,s2,n):
+
+	if s1.lower()[0:n] == s2.lower()[0:n]:
+		return True
+	else:
+		return False
+
+def ismember(a,s):
+	import numpy
+
+	if not isinstance(s,(tuple,list,dict,numpy.ndarray)):
+		s=[s]
+
+	if not isinstance(a,(tuple,list,dict,numpy.ndarray)):
+		a=[a]
+
+	if not isinstance(a,numpy.ndarray):
+		b=[item in s for item in a]
+
+	else:
+		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
+
+def heaviside(x):
+	import numpy
+
+	y=numpy.zeros_like(x)
+	y[numpy.nonzero(x> 0.)]=1.
+	y[numpy.nonzero(x==0.)]=0.5
+
+	return y
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/PythonFuncs.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/PythonFuncs.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/PythonFuncs.py	(revision 18231)
@@ -0,0 +1,24 @@
+def logical_and_n(*arg):
+	from numpy import logical_and
+
+	if len(arg):
+		result=arg[0]
+		for item in arg[1:]:
+			result=logical_and(result,item)
+		return result
+
+	else:
+		return None
+
+def logical_or_n(*arg):
+	from numpy import logical_or
+
+	if len(arg):
+		result=arg[0]
+		for item in arg[1:]:
+			result=logical_or(result,item)
+		return result
+
+	else:
+		return None
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.m	(revision 18231)
@@ -0,0 +1,151 @@
+function fielddisplay(md,name,comment)
+%FIELDDISPLAY - display model field
+%
+%   Usage:
+%      fielddisplay(md,name,comment)
+
+	%get field
+	field=md.(name);
+
+	%disp corresponding line as a function of field type (offset set as 9 spaces)
+	parsedisplay('         ',name,field,comment);
+
+end %function
+
+function parsedisplay(offset,name,field,comment) %{{{
+
+	%string
+	if ischar(field),
+
+		if length(field)>30;
+			displayunit(offset,name,'not displayed',comment),
+		else
+			displayunit(offset,name,['''' field ''''],comment),
+		end
+
+	%numeric
+	elseif isnumeric(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%double
+		if max(fieldsize)==1,
+			displayunit(offset,name,num2str(field),comment),
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+	%logical
+	elseif islogical(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%single value
+		if max(fieldsize)==1,
+			if (field)
+				displayunit(offset,name,'true',comment),
+			else
+				displayunit(offset,name,'false',comment),
+			end
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+	%structure
+	elseif isstruct(field),
+		struct_display(offset,name,field,comment),
+
+	%cell
+	elseif iscell(field),
+		cell_display(offset,name,field,comment),
+
+	else
+		displayunit(offset,name,'not displayed',comment),
+
+	end
+end%}}}
+
+function struct_display(offset,name,field,comment) % {{{
+
+	if ~isempty(fields(field))
+		displayunit(offset,name,'(structure)',comment),
+		offset=[offset '   '];
+
+		structure_fields=fields(field);
+
+		for i=1:length(structure_fields),
+
+			%get current field
+			sfield=field.(structure_fields{i});
+
+			%display value
+			parsedisplay(offset,structure_fields{i},sfield,'');
+		end
+
+	else
+		displayunit(offset,name,'N/A',comment),
+
+	end
+end% }}}
+function cell_display(offset,name,field,comment) % {{{
+
+	%initialization
+	string='{';
+
+	%go through the cell and fill string
+	if length(field)<5;
+		for i=1:length(field),
+			if ischar(field{i}),
+				string=[string ''''  field{i} ''','];
+			elseif (isnumeric(field{i}) & length(field{i})==1)
+				string=[string num2str(field{i}) ',' ];
+			else
+				string='{';
+				break
+			end
+		end
+	end
+	if strcmp(string,'{'),
+		string=['(' num2str(size(field,1)) 'x' num2str(size(field,2)) ')'];
+	else
+		string=[string(1:end-1) '}'];
+	end
+
+	%call displayunit
+	displayunit(offset,name,string,comment);
+end% }}}
+function displayunit(offset,name,characterization,comment),% {{{
+
+	%take care of name
+	if length(name)>23,
+		name=[name(1:20) '...'];
+	end
+
+	%take care of characterization
+	if (strcmp(characterization,['''' '''']) | strcmp(characterization,'NaN')),
+		characterization='N/A';
+	end
+	if length(characterization)>15,
+		characterization=[characterization(1:12) '...'];
+	end
+
+	%print
+	if isempty(comment)
+		disp(sprintf('%s%-23s: %-15s',offset,name,characterization));
+	else
+		if ischar(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment));
+		elseif iscell(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment{1}));
+			for i=2:length(comment),
+				disp(sprintf('%s%-23s  %-15s    %s',offset,'','',comment{i}));
+			end
+		else
+			error('fielddisplay error message: format for comment not supported yet');
+		end
+	end
+end% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/fielddisplay.py	(revision 18231)
@@ -0,0 +1,140 @@
+#Module import 
+import numpy
+from math import isnan
+import MatlabFuncs as m
+
+def fielddisplay(md,name,comment):
+	"""
+	FIELDDISPLAY - display model field
+
+	   Usage:
+	      fielddisplay(md,name,comment)
+	"""
+
+	#get field
+	field=getattr(md,name)
+
+	#disp corresponding line as a function of field type (offset set as 9 spaces)
+	return parsedisplay("         ",name,field,comment);
+
+def parsedisplay(offset,name,field,comment):    # {{{ 
+
+	#string
+	if isinstance(field,(str,unicode)):
+
+		if len(field)>30:
+			string=displayunit(offset,name,"not displayed",comment)
+		else:
+			string=displayunit(offset,name,"'%s'" % field,comment)
+
+	#numeric
+	elif isinstance(field,(int,long,float)):
+		string=displayunit(offset,name,str(field),comment) 
+
+	#matrix
+	elif isinstance(field,numpy.ndarray):
+		string=displayunit(offset,name,str(field.shape),comment)
+
+	#logical
+	elif isinstance(field,bool):
+		if field:
+			string=displayunit(offset,name,"True",comment)
+		else:
+			string=displayunit(offset,name,"False",comment)
+	
+	#dictionary
+	elif isinstance(field,dict):
+		string=dict_display(offset,name,field,comment)
+
+	#list or tuple
+	elif isinstance(field,(list,tuple)):
+		string=list_display(offset,name,field,comment)
+
+	#None
+	elif field is None:
+		string=displayunit(offset,name,"None",comment)
+
+	else:
+		string=displayunit(offset,name,"not displayed",comment)
+		
+	return string
+	# }}}
+
+def dict_display(offset,name,field,comment):    # {{{
+
+	if field:
+		string =displayunit(offset,name,'{dictionary}',comment)+'\n'
+		offset+='   '
+
+		for structure_field,sfield in field.iteritems():
+			string+=parsedisplay(offset,str(structure_field),sfield,'')+'\n'
+
+		if string and string[-1]=='\n':
+			string=string[:-1]
+
+	else:
+		string=displayunit(offset,name,'N/A',comment)
+
+	return string
+	# }}}
+
+def list_display(offset,name,field,comment):    # {{{
+
+	#initialization
+	if   isinstance(field,list):
+		sbeg='['
+		send=']'
+	elif isinstance(field,tuple):
+		sbeg='('
+		send=')'
+	string=sbeg
+
+	#go through the cell and fill string
+	if len(field)<5:
+		for fieldi in field:
+			if   isinstance(fieldi,(str,unicode)):
+				string+="'%s'," % fieldi
+			elif isinstance(fieldi,(bool,int,long,float)):
+				string+="%s," % str(fieldi)
+			else:
+				string=sbeg
+				break
+
+	if m.strcmp(string,sbeg):
+		string="%s%dx1%s" % (sbeg,len(field),send)
+	else:
+		string=string[:-1]+send
+
+	#call displayunit
+	return displayunit(offset,name,string,comment)
+	# }}}
+
+def displayunit(offset,name,characterization,comment):    # {{{
+
+	#take care of name
+	if len(name)>23:
+		name="%s..." % name[:20]
+	
+	#take care of characterization
+	if m.strcmp(characterization,"''") or m.strcmp(characterization,'""') or m.strcmpi(characterization,'nan'):
+		characterization="N/A"
+	
+	if len(characterization)>15:
+		characterization="%s..." % characterization[:12]
+	
+	#print
+	if not comment:
+		string="%s%-23s: %-15s" % (offset,name,characterization)
+	else:
+		if   isinstance(comment,(str,unicode)):
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment)
+		elif isinstance(comment,list):
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment[0])
+			for commenti in comment:
+				string+="\n%s%-23s  %-15s    %s" % (offset,'','',commenti)
+		else:
+			raise RuntimeError("fielddisplay error message: format for comment not supported yet")
+
+	return string
+	# }}}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.m	(revision 18231)
@@ -0,0 +1,14 @@
+function returnvalue=isnans(array)
+%ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+%
+%  Usage:    isnans(array)
+%
+%  See also : ISNAN 
+
+if isstruct(array), 
+	returnvalue=0;
+elseif iscell(array)
+	returnvalue=0;
+else
+	returnvalue=isnan(array);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/isnans.py	(revision 18231)
@@ -0,0 +1,18 @@
+import numpy
+
+def isnans(array):
+	"""
+	ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+
+	   Usage:    isnans(array)
+
+	      See also : ISNAN 
+	"""
+
+	if   isinstance(array,(tuple,list,dict)): 
+		returnvalue=0
+	else:
+		returnvalue=numpy.isnan(array)
+
+	return returnvalue
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/issmdoc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/issmdoc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/issmdoc.m	(revision 18231)
@@ -0,0 +1,15 @@
+%Quick documentation for ISSM
+
+%First get ISSM tier: 
+ISSM_DIR=issmdir();
+
+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,''SSA'',''all'');','%defines all elements as SSA''s SSA'));
+disp(sprintf('%-63s %s','       md=solve(md,StressbalanceSolutionEnum());','%solve for stress balance'));
+disp(sprintf('%-63s %s','       plotmodel(md,''data'',md.results.StressbalanceSolution.Vel);','%displays the velocity (type plotdoc for plotmodel help)'));
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/netcdf2struct.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/netcdf2struct.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/netcdf2struct.m	(revision 18231)
@@ -0,0 +1,166 @@
+function S=netcdf2struct(File)
+%NETCDF2STRUCT - load netcdf file and convert to a matlab structure
+%
+%   Usage:
+%      S=netcdf2struct(File);
+
+%Read netcdf file
+data=readnetcdf(File);
+
+%initialize output
+S=struct();
+
+%All the variables are in VarArray field
+variables=data.VarArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(squeeze(variables(i).Data));
+	S.(fieldname)=fieldvalue;
+end
+
+%All the variables are in AttArray field
+variables=data.AttArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(variables(i).Val);
+	S.(fieldname)=fieldvalue;
+end
+end
+
+function S = readnetcdf(File,varargin)
+% Function to read NetCDF files
+%   S = netcdf(File)
+% Input Arguments
+%   File = NetCDF file to read
+% Optional Input Arguments:
+%   'Var',Var - Read data for VarArray(Var), default [1:length(S.VarArray)]
+%   'Rec',Rec - Read data for Record(Rec), default [1:S.NumRecs]
+% Output Arguments:
+%   S    = Structure of NetCDF data organised as per NetCDF definition
+% Notes:
+%   Only version 1, classic 32bit, NetCDF files are supported. By default
+% data are extracted into the S.VarArray().Data field for all variables.
+% To read the header only call S = netcdf(File,'Var',[]);
+%
+% SEE ALSO
+% ---------------------------------------------------------------------------
+S = [];
+
+try
+   if exist(File,'file') fp = fopen(File,'r','b');
+   else fp = []; error('File not found'); end
+   if fp == -1   error('Unable to open file'); end
+
+% Read header
+   Magic = fread(fp,4,'uint8=>char');
+   if strcmp(Magic(1:3),'CDF') error('Not a NetCDF file'); end
+   if uint8(Magic(4))~=1       error('Version not supported'); end
+   S.NumRecs  = fread(fp,1,'uint32=>uint32');
+   S.DimArray = DimArray(fp);
+   S.AttArray = AttArray(fp);
+   S.VarArray = VarArray(fp);
+
+% Setup indexing to arrays and records
+   Var = ones(1,length(S.VarArray));
+   Rec = ones(1,S.NumRecs);
+   for i = 1:2:length(varargin)
+      if     strcmp(upper(varargin{i}),'VAR') Var=Var*0; Var(varargin{i+1})=1;
+      elseif strcmp(upper(varargin{i}),'REC') Rec=Rec*0; Rec(varargin{i+1})=1;
+      else error('Optional input argument not recognised'); end
+   end
+   if sum(Var)==0 fclose(fp); return; end
+
+% Read non-record variables
+   Dim = double(cat(2,S.DimArray.Dim));
+   ID  = double(cat(2,S.VarArray.Type));
+
+   for i = 1:length(S.VarArray)
+      D = Dim(S.VarArray(i).DimID+1); N = prod(D); RecID{i}=find(D==0);
+      if isempty(RecID{i})
+         if length(D)==0 D = [1,1]; N = 1; elseif length(D)==1 D=[D,1]; end
+         if Var(i)
+            S.VarArray(i).Data = ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D);
+            fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8');
+         else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+      else S.VarArray(i).Data = []; end
+   end
+
+% Read record variables
+   for k = 1:S.NumRecs
+      for i = 1:length(S.VarArray)
+         if ~isempty(RecID{i})
+            D = Dim(S.VarArray(i).DimID+1); D(RecID{i}) = 1; N = prod(D);
+            if length(D)==1 D=[D,1]; end
+            if Var(i) & Rec(k)
+               S.VarArray(i).Data = cat(RecID{i},S.VarArray(i).Data,...
+                  ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D));
+               if N > 1 fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); end
+            else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+         end
+      end
+   end
+
+   fclose(fp);
+catch
+   Err = lasterror; fprintf('%s\n',Err.message);
+   if ~isempty(fp) && fp ~= -1 fclose(fp); end
+end
+
+% ---------------------------------------------------------------------------------------
+% Utility functions
+
+function S = Size(ID)
+% Size of NetCDF data type, ID, in bytes
+   S = subsref([1,1,2,4,4,8],struct('type','()','subs',{{ID}}));
+
+function T = Type(ID)
+% Matlab string for CDF data type, ID
+   T = subsref({'int8','char','int16','int32','single','double'},...
+               struct('type','{}','subs',{{ID}}));
+
+function N = Pad(Num,ID)
+% Number of elements to read after padding to 4 bytes for type ID
+   N = (double(Num) + mod(4-double(Num)*Size(ID),4)/Size(ID)).*(Num~=0);
+
+function S = String(fp)
+% Read a CDF string; Size,[String,[Padding]]
+   S = fread(fp,Pad(fread(fp,1,'uint32=>uint32'),1),'uint8=>char').';
+
+function A = ReOrder(A,S)
+% Rearrange CDF array A to size S with matlab ordering
+   A = permute(reshape(A,fliplr(S)),fliplr(1:length(S)));
+
+function S = DimArray(fp)
+% Read DimArray into structure
+   if fread(fp,1,'uint32=>uint32') == 10 % NC_DIMENSION
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         S(i).Dim = fread(fp,1,'uint32=>uint32');
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = AttArray(fp)
+% Read AttArray into structure
+   if fread(fp,1,'uint32=>uint32') == 12 % NC_ATTRIBUTE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         ID       = fread(fp,1,'uint32=>uint32');
+         Num      = fread(fp,1,'uint32=>uint32');
+         S(i).Val = fread(fp,Pad(Num,ID),[Type(ID),'=>',Type(ID)]).';
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = VarArray(fp)
+% Read VarArray into structure
+   if fread(fp,1,'uint32=>uint32') == 11 % NC_VARIABLE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str      = String(fp);
+         Num           = double(fread(fp,1,'uint32=>uint32'));
+         S(i).DimID    = double(fread(fp,Num,'uint32=>uint32'));
+         S(i).AttArray = AttArray(fp);
+         S(i).Type     = fread(fp,1,'uint32=>uint32');
+         S(i).VSize    = fread(fp,1,'uint32=>uint32');
+         S(i).Begin    = fread(fp,1,'uint32=>uint32'); % Classic 32 bit format only
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normcdf_issm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normcdf_issm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normcdf_issm.m	(revision 18231)
@@ -0,0 +1,8 @@
+%
+%  wrapper for normcdf to avoid using the matlab statistics toolbox.
+%
+function [p]=normcdf_issm(x,mu,sigma)
+
+	p=(1.+erf((x-mu)/(sigma*sqrt(2.))))/2.;
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normfit_issm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normfit_issm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/normfit_issm.m	(revision 18231)
@@ -0,0 +1,61 @@
+%
+%  wrapper for normfit to avoid using the matlab statistics toolbox.
+%
+function [muhat,sigmahat,muci,sigmaci]=normfit_issm(x,alpha)
+
+	if ~exist('alpha','var')
+		alpha=0.05;
+	end
+
+%  check for any NaN in any columns
+
+	if ~any(any((isnan(x))))
+
+%  explicitly calculate the moments
+
+		muhat   =mean(x);
+		sigmahat=std(x);
+
+		if (nargout>2)
+			prob=1.-alpha/2.;
+
+			if (size(x,1) == 1)
+				% operate like matlab normfit, mean, std, etc.
+				n=length(x);
+			else
+				n=size(x,1);
+			end
+
+			muci    =zeros(2,length(muhat   ));
+			sigmaci =zeros(2,length(sigmahat));
+
+			try
+				muci(1,:)   =muhat-tinv(prob,n-1)*sigmahat/sqrt(n);
+				muci(2,:)   =muhat+tinv(prob,n-1)*sigmahat/sqrt(n);
+				sigmaci(1,:)=sigmahat*sqrt((n-1)/chi2inv(prob   ,n-1));
+				sigmaci(2,:)=sigmahat*sqrt((n-1)/chi2inv(1.-prob,n-1));
+			catch me
+				muci(1,:)   =muhat;
+				muci(2,:)   =muhat;
+				sigmaci(1,:)=sigmahat;
+				sigmaci(2,:)=sigmahat;
+			end
+		end
+
+	else
+
+%  must loop over columns, since number of elements could be different
+
+		muhat   =zeros(1,size(x,2));
+		sigmahat=zeros(1,size(x,2));
+		muci    =zeros(2,size(x,2));
+		sigmaci =zeros(2,size(x,2));
+
+%  remove any NaN and recursively call column
+
+		for j=1:size(x,2)
+			[muhat(j),sigmahat(j),muci(:,j),sigmaci(:,j)]=normfit_issm(x(~isnan(x(:,j)),j),alpha);
+		end
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/norminv_issm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/norminv_issm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/norminv_issm.m	(revision 18231)
@@ -0,0 +1,8 @@
+%
+%  wrapper for norminv to avoid using the matlab statistics toolbox.
+%
+function [x]=norminv_issm(p,mu,sigma)
+
+	x=mu+sigma*sqrt(2.)*erfinv(2.*p-1.);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.m	(revision 18231)
@@ -0,0 +1,22 @@
+function [i1,i2]=parallelrange(rank,numprocs,globalsize)
+%PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+%
+%   Usage: 
+%      [i1,i1]=parallelrange(rank,numprocs,globalsize)
+
+num_local_rows=zeros(numprocs,1);
+
+for i=1:numprocs,
+	%we use floor. we under distribute rows. The rows left  are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows(i)=floor(globalsize/numprocs);
+end
+
+%There may be some rows left. Distribute evenly.
+row_rest=globalsize - numprocs*floor(globalsize/numprocs);
+
+for i=1:row_rest,
+	num_local_rows(i)=num_local_rows(i)+1;
+end
+
+i1=sum(num_local_rows(1:rank-1))+1;
+i2=i1+num_local_rows(rank)-1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/parallelrange.py	(revision 18231)
@@ -0,0 +1,25 @@
+#! /usr/bin/env python
+def parallelrange(rank,numprocs,globalsize):
+	"""
+	PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+ 
+	   Usage: 
+	      i1,i2=parallelrange(rank,numprocs,globalsize)
+	"""
+
+	#We use floor. we under distribute rows. The rows left are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows=[int(globalsize/numprocs) for i in xrange(numprocs)]
+
+	#There may be some rows left. Distribute evenly.
+	row_rest=globalsize - numprocs*int(globalsize/numprocs)
+
+	for i in xrange(row_rest):
+		num_local_rows[i]=num_local_rows[i]+1
+
+	i1=0
+	for i in xrange(rank-1):
+		i1+=num_local_rows[i]
+	i2=i1+num_local_rows[rank-1]-1
+
+	return i1,i2
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/prctile_issm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/prctile_issm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/prctile_issm.m	(revision 18231)
@@ -0,0 +1,86 @@
+%
+%  wrapper for prctile to avoid using the matlab statistics toolbox.
+%
+function [y]=prctile_issm(x,p,dim)
+
+	try
+		y=prctile(argin{:});
+
+	catch me
+
+		if length(size(x)) > 2
+			error('Number of dimensions %d not implemented.',length(size(x)));
+		end
+		if ~exist('dim','var')
+			dim=0;
+			for i=1:length(size(x))
+				if ~dim && size(x,i)>1
+					dim=i;
+				end
+			end
+			if ~dim
+				dim=1;
+			end
+		end
+
+		psize=size(p);
+		if size(p,2)>1
+			p=transpose(p);
+		end
+
+		xsize=size(x);
+		if dim==2
+			x=transpose(x);
+		end
+
+%  check for any NaN in any columns
+
+		if ~any(any((isnan(x))))
+			x=sort(x,1);
+			n=size(x,1);
+
+%  branch based on number of elements
+
+			if     n>1
+
+%  set up percent values and interpolate
+
+				xi=transpose(100.*([1:n]-0.5)/n);
+				y=interp1q(xi,x,p);
+
+%  fill in high and low values
+
+				y(p<xi(1),:)=repmat(x(1,:),nnz(p<xi(1)),1);
+				y(p>xi(n),:)=repmat(x(n,:),nnz(p>xi(n)),1);
+
+%  if one value, just copy it
+
+			elseif n==1
+				y=repmat(x(1,:),length(p),1);
+
+%  if no values, use NaN
+
+			else
+				y=repmat(NaN,size(p,1),size(x,2));
+			end
+
+		else
+
+%  must loop over columns, since number of elements could be different
+
+			y=zeros(size(p,1),size(x,2));
+			for j=1:size(x,2)
+
+%  remove any NaN and recursively call column
+
+				y(:,j)=prctile_issm(x(~isnan(x(:,j)),j),p);
+			end
+		end
+
+		if (min(xsize)==1 && xsize(dim)>1 && psize(2)>1) || ...
+		   (min(xsize)> 1 && dim==2)
+			y=transpose(y);
+		end
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/round_ice.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/round_ice.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/round_ice.m	(revision 18231)
@@ -0,0 +1,36 @@
+function new_x=round_ice(x,numnonzeros)
+%ROUND_ICE - rounds up x so that it has only numnonzeros non zero digits
+%
+%   numnonzeros must be an integer larger or equal to 1
+%
+%   Usage:
+%      new_x=round_ice(x,numnonzeros)
+
+%some checks
+if (nargin ~=2 | nargout>1),
+	error('round_ice usage: new_x=round_ice(x,numonzeros)');
+end
+if ~isnumeric(x)
+	error('round_ice error message: x must be a number and numzeros an integer');
+end
+if round(numnonzeros)~=numnonzeros
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if any(numnonzeros<1)
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if (length(numnonzeros)~=1 & size(numnonzeros)~=size(x))
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1 or a list of integers of length length(x)')
+end
+
+%figure out how long x is
+lengthx=ceil(log10(abs(x)));
+
+%if x contains 0, lengthx=-Inf
+lengthx(isinf(lengthx))=1;
+
+%get its sign
+si=sign(x);
+
+%rule out zeros
+new_x=si.*round(abs(x).*10.^(-lengthx+numnonzeros)).*10.^(lengthx-numnonzeros);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/structtoobj.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/structtoobj.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/structtoobj.m	(revision 18231)
@@ -0,0 +1,16 @@
+function obj=structtoobj(obj,S),
+%Convert struct to object
+
+	%Get object and structure fields
+	structfields=fields(S);
+	objprops    =properties(class(obj));
+
+	%recover object properties
+	for i=1:length(structfields),
+		fieldname =structfields{i};
+		if ismember(fieldname,objprops),
+			fieldvalue=getfield(S,fieldname);
+			obj=setfield(obj,fieldname,fieldvalue);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/vorticity.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/vorticity.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/miscellaneous/vorticity.m	(revision 18231)
@@ -0,0 +1,33 @@
+function rot = vorticity(md,vx,vy)
+%VORTICITY - calculates 2d vorticity
+%
+%   rot = d/dx(vy) - d/dy(vx)
+%
+%   Usage:
+%      rot = vorticity(vx,vy)
+
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if ~strcmpi(md.mesh.domaintype(),'3D'),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+dvydx=(vy(index).*alpha)*summation;
+dvxdy=(vx(index).*beta)*summation;
+rot=dvxdy - dvydx;
+
+if strcmpi(meshtype(md.mesh),'3D'),
+	rot=project3d(md,'vector',rot,'type','element');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/aggregation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/aggregation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/aggregation.m	(revision 18231)
@@ -0,0 +1,64 @@
+function [mask,varargout]=aggregation(mask,windowsize,threshhold,varargin)
+%AGGREGATION - aggregation of an image to a lower sized image
+% 
+%  mask is an image of arbitrary size, format binary, with values 1 for foreground, and 0 for background
+%  mask is first convoluted with a square matrix of size windowsize (where windowsize is an even number), 
+%       it is then filtered according to the threshhold value, and finally subsampled using 1/windowsize as 
+%       sample scaling. 
+%  x,y can be provided as optional arguments, as coordinates of the center points of the mask. aggregation will 
+%       then return subsampled x,y arguments in output.
+% 
+%  Usage:   mask2=aggregation(mask,7,7^2/2);
+%           [mask2,x2,y2]=aggregation(mask,7,7^2,x,y];
+%
+%  See also CLOSING, OPENING, DILATION, EROSION
+
+%check input arguments  %{{{
+%even windowsize
+if mod(windowsize,2)==0,
+	error('windowsize should be an even number');
+end
+
+%check on presence of varargin: 
+optional=0;
+if nargin>3,
+	if nargin~=5,
+		help aggregation;
+		error('wrong number of optional arguments specified');
+	else
+		optional=1;
+		x=varargin{1};
+		y=varargin{2};
+	end
+end
+
+%check on presence of varargout: 
+if optional,
+	if nargout~=3,
+		help aggregation;
+		error('wrong number of optional output arguments specified');
+	end
+end
+%}}}
+
+%convolve mask
+matrix=ones(windowsize,windowsize); 
+mask=filter2(matrix,mask,'same');
+
+%apply threshhold
+pos=find(mask>threshhold); 
+pos2=find(mask<=threshhold); 
+mask(pos)=1;
+mask(pos2)=0;
+
+%mask has been transformed into double format from the filter2  operation. Bring back to binary. 
+mask=logical(mask);
+
+%subsample: 
+s=size(mask);
+mask=mask(1:windowsize:s(1),1:windowsize:s(2));
+
+if optional,
+	varargout{1}=x(1:windowsize:s(2));
+	varargout{2}=y(1:windowsize:s(1));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/closing.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/closing.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/closing.m	(revision 18231)
@@ -0,0 +1,5 @@
+function mask=closing(mask,neighboorhood)
+%closing algorithm using neighboorhood pixel neighboors.
+
+mask=dilation(mask,neighboorhood);
+mask=erosion(mask,neighboorhood);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/dilation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/dilation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/dilation.m	(revision 18231)
@@ -0,0 +1,25 @@
+function mask=dilation(mask,neighboorhood)
+%deletion algorithm using 4 pixel neighboors.
+
+%convolve: 
+
+matrix=ones(3,3); 
+
+%4 neighboorhood: 
+%corners
+if neighboorhood==4,
+	matrix(1,1)=0;
+	matrix(1,3)=0;
+	matrix(3,1)=0;
+	matrix(3,3)=0;
+end
+%center
+matrix(2,2)=0;
+
+%convolve mask: 
+convol=filter2(matrix,mask,'same');
+
+pos=find(mask==0);
+pos2=find(convol(pos)~=0);
+
+mask(pos(pos2))=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/erosion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/erosion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/erosion.m	(revision 18231)
@@ -0,0 +1,26 @@
+function mask=erosion(mask,neighboorhood)
+%erosion algorithm using neighboorhood pixel neighboors.
+
+%convolve: 
+
+matrix=ones(3,3); 
+
+%4 neighboorhood: 
+%corners
+if neighboorhood==4,
+	matrix(1,1)=0;
+	matrix(1,3)=0;
+	matrix(3,1)=0;
+	matrix(3,3)=0;
+end
+
+%center
+matrix(2,2)=0;
+
+%convolve mask: 
+convol=filter2(matrix,mask,'same');
+
+pos=find(mask==1);
+pos2=find(convol(pos)<neighboorhood);
+
+mask(pos(pos2))=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/nunataks.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/nunataks.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/nunataks.m	(revision 18231)
@@ -0,0 +1,20 @@
+function [mask]=nunataks(mask)
+%NUNATAKS - bias mask towards increased 0 coverage
+% 
+%  mask is an image of arbitrary size, format binary, with values 1 for foreground, and 0 for background
+% 
+%  Usage:   mask=nunataks(mask)
+%           [mask]=aggregation(mask);
+%
+%  See also CLOSING, OPENING, DILATION, EROSION, AGGREGATION
+
+rocks=~mask;
+
+%matrices for convolution: 
+matrix=[0 1 0; 1 0 1; 0 1 0];
+
+%do not exist, i.e. locations that stand pretty much alone. 
+mask=filter2(matrix1,mask,'same');
+pos=find(~crocks & rocks);
+
+mask(pos)=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/opening.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/opening.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/opening.m	(revision 18231)
@@ -0,0 +1,5 @@
+function mask=opening(mask,neighboorhood)
+%opening algorithm using neighboorhood pixel neighboors.
+
+mask=erosion(mask,neighboorhood);
+mask=dilation(mask,neighboorhood);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/vectorialize.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/vectorialize.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/morphological/vectorialize.m	(revision 18231)
@@ -0,0 +1,11 @@
+function contours=vectorialize(mask,connectivity);
+
+	vec=bwboundaries(mask,connectivity);
+
+	contours=struct([]);
+	for i=1:length(vec),
+		contours(end+1).x=vec{i}(:,2);
+		contours(end).y=vec{i}(:,1);
+		contours(end).density=1;
+	end
+	contours(1).name='';
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/flaimdir.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/flaimdir.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/flaimdir.m	(revision 18231)
@@ -0,0 +1,7 @@
+function FLAIM_DIR=flaimdir()
+%ISSMDIR - Get FLAIM installation directory
+%
+%   Usage:
+%      FLAIM_DIR=flaimdir()
+
+FLAIM_DIR=[issmdir() '/externalpackages/flaim/install'];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpin.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpin.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpin.m	(revision 18231)
@@ -0,0 +1,47 @@
+function issmbbftpin(host, login,port,numstreams,path, packages)
+%BBFTPIN get packages from host, using bbftp. assuming unix system here.
+%
+%   usage: scpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; get Antarctica.outbin' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; '];
+	for i=1:length(packages),
+		command=[command 'get ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+
+	eval(command);
+
+	%check bbftp worked
+	for i=1:numel(packages),
+		if ~exist(['./' packages{i}]),
+			error('scpin error message: could not call scp on *nix system');
+		end
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpout.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpout.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmbbftpout.m	(revision 18231)
@@ -0,0 +1,30 @@
+function issmbbftpout(host,path,login,port,numstreams,packages)
+%BBFTPOUT put packages onto host, using bbftp. assuming unix system here.
+%
+%   usage: bbftpout(host,path,login,port,numstream,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; put Antarctica.tar.gz' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; ']
+	for i=1:length(packages),
+		command=[command 'put ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+
+	eval(command);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.m	(revision 18231)
@@ -0,0 +1,18 @@
+function ISSM_DIR=issmdir()
+%ISSMDIR - Get ISSM_DIR environment variable
+%
+%   Usage:
+%      ISSM_DIR=issmdir()
+
+if ~ispc(),
+	ISSM_DIR =getenv('ISSM_DIR');
+else
+	ISSM_DIR =getenv('ISSM_DIR_WIN');
+	if strcmpi(ISSM_DIR(end),'/') | strcmpi(ISSM_DIR(end),'\'),
+		ISSM_DIR = ISSM_DIR(1:end-1); %shave off the last '/'
+	end
+end
+
+if (isempty(ISSM_DIR)),
+	error('issmdir error message: ''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmdir.py	(revision 18231)
@@ -0,0 +1,23 @@
+import os
+import MatlabFuncs as m
+
+def issmdir():
+	"""
+	ISSMDIR - Get ISSM_DIR environment variable
+ 
+	   Usage:
+	      ISSM_DIR=issmdir()
+	"""
+
+	if not m.ispc():
+		ISSM_DIR =os.environ['ISSM_DIR']
+	else:
+		ISSM_DIR =os.environ['ISSM_DIR_WIN']
+		if m.strcmpi(ISSM_DIR[-1],'/') or m.strcmpi(ISSM_DIR[-1],'\\'):
+			ISSM_DIR = ISSM_DIR[:-1]    #shave off the last '/'
+
+	if not ISSM_DIR:
+		raise RuntimeError("issmdir error message: 'ISSM_DIR' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!")
+
+	return ISSM_DIR
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.m	(revision 18231)
@@ -0,0 +1,77 @@
+function issmscpin(host, login,port,path, packages)
+%ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	if ispc(),
+		%use the putty project pscp.exe: it should be in the path.
+
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpin error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' host ':' path '/' packages{i} ' ./']);
+			if status, 
+				error('issmscpin error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%string to copy multiple files using scp: 
+		if numel(packages)==1,
+			string=packages{1};
+		else
+			string='\{';
+			for i=1:numel(packages)-1,
+				string=[string packages{i} ','];
+			end
+			string=[string packages{end} '\}'];
+		end
+
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' login '@localhost:' path '/' string ' ./']);
+		else
+			eval(['!scp ' login '@' host ':' path '/' string ' ./']);
+		end
+
+		%check scp worked
+		for i=1:numel(packages),
+			if ~exist(['./' packages{i}]),
+				error('issmscpin error message: could not call scp on *nix system');
+			end
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpin.py	(revision 18231)
@@ -0,0 +1,74 @@
+from socket import gethostname
+import subprocess
+import os
+import shutil
+import MatlabFuncs as m
+
+def issmscpin(host, login,port,path, packages):
+	"""
+	ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpin(host,packages,path)
+	"""
+
+	#first get hostname
+	hostname=gethostname()
+
+	#first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+	#remove warnings in case the files do not exist
+	for package in packages:
+		try:
+			os.remove(package)
+		except OSError as e:
+			pass
+
+	#if hostname and host are the same, do a simple copy
+	if m.strcmpi(hostname,host):
+
+		for package in packages:
+			try:
+				shutil.copy(os.path.join(path,package),os.getcwd())    #keep going, even if success=0
+			except OSError as e:
+				pass
+
+	else:
+
+		if m.ispc():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmscpin error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s:%s %s' % (ISSM_DIR,username,key,host,os.path.join(path,package),os.getcwd()),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("issmscpin error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#string to copy multiple files using scp: 
+			if len(packages)==1:
+				string=packages[0]
+			else:
+				string='{'
+				for package in packages:
+					string+=packages[i]+','
+				string=string[:-1]+'}'
+
+			if port:
+				subprocess.call('scp -P %d %s@localhost:%s %s' % (port,login,os.path.join(path,string),os.getcwd),shell=True)
+			else:
+				subprocess.call('scp %s@%s:%s %s' % (login,host,os.path.join(path,string),os.getcwd),shell=True)
+		
+			#check scp worked
+			for package in packages:
+				if not os.path.exists(os.path.join('.',package)):
+					raise OSError("issmscpin error message: could not call scp on *nix system.")
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.m	(revision 18231)
@@ -0,0 +1,68 @@
+function issmscpout(host,path,login,port,packages,varargin)
+%ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpout(host,path,login,port,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%are we dis-allowing symbolic links? 
+if nargin==6,
+	no_symlinks=1;
+else
+	no_symlinks=0;
+end
+
+%if hostname and host are the same, do a simple copy
+
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		if no_symlinks,
+			system(['cp  ' here '/' packages{i} ' .']);
+		else
+			system(['ln -s ' here '/' packages{i} ' .']);
+		end
+		eval(['cd ' here]);
+	end
+else 
+	if ispc(),
+		%use the putty project pscp.exe: it should be in the path.
+
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpout error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' packages{i} ' ' host ':' path]);
+			if status, 
+				error('issmscpout error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%create string of packages being sent
+		string='';
+		for i=1:numel(packages),
+			string=[string ' ' packages{i}];
+		end
+		string=[string ' '];
+
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
+		else
+			eval(['!scp ' string ' ' login '@' host ':' path]);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmscpout.py	(revision 18231)
@@ -0,0 +1,59 @@
+from socket  import gethostname
+import subprocess
+import os
+import MatlabFuncs as m
+
+def issmscpout(host,path,login,port,packages):
+	"""
+	ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpout(host,path,packages)
+	"""
+
+	#get hostname
+	hostname=gethostname();
+
+	#if hostname and host are the same, do a simple copy
+
+	if m.strcmpi(host,hostname):
+		for package in packages:
+			here=os.getcwd()
+			os.chdir(path)
+			try:
+				os.remove(package)
+			except OSError as e:
+				pass
+			subprocess.call('ln -s %s %s' % (os.path.join(here,package),path),shell=True)
+			os.chdir(here)
+	else:
+		if m.ispc():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmscpout error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s %s:%s' % (ISSM_DIR,username,key,package,host,path),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("issmscpout error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#create string of packages being sent
+			string=''
+			for package in packages:
+				string+=' '+package
+			string+=' '
+		
+			if port:
+				subprocess.call('scp -P %d %s %s@localhost:%s' % (port,string,login,path),shell=True)
+			else:
+				subprocess.call('scp %s %s@%s:%s' % (string,login,host,path),shell=True)
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.m	(revision 18231)
@@ -0,0 +1,37 @@
+function issmssh(host,login,port,command)
+%ISSMSSH - wrapper for OS independent ssh command.
+%
+%   usage: 
+%      issmssh(host,command)
+
+%first get hostname 
+hostname=oshostname();
+
+%if same as host, just run the command. 
+if strcmpi(host,hostname),
+	system(command);
+else
+	if ispc(),
+		%use the putty project plink.exe: it should be in the path.
+
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmssh error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		system([ISSM_DIR '/externalpackages/ssh/plink.exe -ssh -l "' username '" -pw "' key '" ' host ' "' command '"']);
+
+	else
+		%just use standard unix ssh
+		if port,
+			eval(['!ssh -l ' login ' -p ' num2str(port) ' localhost "' command '"']);
+		else
+			eval(['!ssh -l ' login ' ' host ' "' command '"']);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmssh.py	(revision 18231)
@@ -0,0 +1,59 @@
+from socket import gethostname
+import subprocess
+import os
+import MatlabFuncs as m
+
+def issmssh(host,login,port,command):
+	"""
+	ISSMSSH - wrapper for OS independent ssh command.
+ 
+	   usage: 
+	      issmssh(host,command)
+	"""
+
+	#first get hostname 
+	hostname=gethostname()
+
+	#if same as host, just run the command. 
+	if m.strcmpi(host,hostname):
+		subprocess.call(command,shell=True)
+	else:
+		if m.ispc():
+			#use the putty project plink.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmssh error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			subprocess.call('%s/externalpackages/ssh/plink.exe -ssh -l "%s" -pw "%s" %s "%s"' % (ISSM_DIR,username,key,host,command),shell=True);
+
+		else:
+			#just use standard unix ssh
+			if port:
+				subprocess.call('ssh -l %s -p %d localhost "%s"' % (login,port,command),shell=True)
+			else:
+				subprocess.call('ssh -l %s %s "%s"' % (login,host,command),shell=True)
+
+	# 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/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpin.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpin.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpin.m	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpout.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpout.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstscpout.m	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/os/issmstssh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstssh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/issmstssh.m	(revision 18231)
@@ -0,0 +1,9 @@
+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/branches/trunk-jpl-ad2-integrated/src/m/os/jplsvn.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/jplsvn.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/jplsvn.m	(revision 18231)
@@ -0,0 +1,15 @@
+function JPL_SVN=jplsvn()
+%ISSMDIR - Get JPL_SVN environment variable
+%
+%   Usage:
+%      JPL_SVN=jplsvn()
+
+if ~ispc(),
+	JPL_SVN =getenv('JPL_SVN');
+else
+	JPL_SVN =getenv('JPL_SVN_WIN');
+end
+
+if (isempty(JPL_SVN)),
+	error('jplsvn error message: ''JPL_SVN'' environment variable is empty! You should define JPL_SVN in your .cshrc or .bashrc');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfiles.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfiles.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfiles.m	(revision 18231)
@@ -0,0 +1,22 @@
+function list=listfiles()
+%LISTFILES list files inside a directory
+%        this is very OS dependent.
+%
+%   usage: list=listfiles;
+%
+%
+%   see also LS DIR
+
+%use dir, as it seems to act OS independent
+
+first_list=dir;
+list={};
+
+for i=1:numel(first_list),
+	if (  ~strcmpi(first_list(i).name,'.') &...
+			~strcmpi(first_list(i).name,'..') &...
+			~strcmpi(first_list(i).name,'NightlyRun') &...
+			~strcmpi(first_list(i).name,'.svn')),
+		list{end+1}=first_list(i).name;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfilesparallel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfilesparallel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/listfilesparallel.m	(revision 18231)
@@ -0,0 +1,15 @@
+function list=listfilesparallel(rank,numprocs)
+%LISTFILESPARALLEL list files inside a directory, depending on rank  and number of processors running this routine.
+%        this is very OS dependent.
+%
+%   usage: list=listfilesparallel(rank,numprocs);
+%
+%
+%   see also LS DIR LISTFILES
+
+list=listfiles';
+numfiles=numel(list);
+
+%we now have a list, split it between all the processors.
+[i1,i2]=parallelrange(rank,numprocs,numfiles);
+list=list(i1:i2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/oshostname.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/oshostname.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/oshostname.m	(revision 18231)
@@ -0,0 +1,25 @@
+function hostname=oshostname()
+%OSHOSTNAME figure out hostname, irrespective of os type
+%
+%   usage: hostname=oshostname();
+%
+%
+
+if ispc(),
+	[status,hostname]=system('hostname');
+	if status, 
+		error('oshostname error message: could not run hostname command on windows os');
+	end
+else
+	%See http://www.mathworks.com/help/matlab/ref/system.html "tips" section
+	%We need to add < /dev/null otherwise what is in the clipboard is added
+	[status,hostname]=system('hostname < /dev/null');
+	hostname = strrep(hostname,'-','');
+	if status, 
+		error('oshostname error message: could not run hostname command on *nix os');
+	end
+end
+
+%remove carriage return and blank spaces
+hostname=hostname(1:end-1);
+hostname=ddewhite(hostname);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/recursivepath.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/recursivepath.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/recursivepath.m	(revision 18231)
@@ -0,0 +1,39 @@
+function p = recursivepath(d)
+%RECURSIVEPATH - generate paths in a directory
+%
+%   this routine is equivalent to Matlab's genpath except that it skips CVS and
+%   .svn directories
+%
+%   Usage:
+%      p = recursivepath(d)
+
+%initialize path to be returned
+p = '';
+sep=pathsep;  %directory separator
+
+% Generate path based on given root directory
+files=dir(d);
+if isempty(files)
+	return
+end
+
+% Add d to the path even if it is empty.
+p = [p d sep];
+
+% set logical vector for subdirectory entries in d
+isdir = logical(cat(1,files.isdir));
+
+% Recursively goes through the subdirectories of d
+dirs=files(isdir); % select only directory entries from the current listing
+for i=1:length(dirs)
+	dirname=dirs(i).name;
+	if ~strcmp(dirname,'.')    & ...
+		~strcmp(dirname,'..')   & ...
+		~strcmp(dirname,'.svn') & ...
+		~strcmp(dirname,'CVS')  & ...
+		~strncmp(dirname,'@',1) & ... %Method directories not allowed in MATLAB path
+		~strcmp(dirname,'private')    %private directories not allowed in MATLAB path
+
+		p = [p recursivepath(fullfile(d,dirname))];
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/os/starcluster.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/os/starcluster.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/os/starcluster.m	(revision 18231)
@@ -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 '/proj-group/CloudComputing/starcluster.config'];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.m	(revision 18231)
@@ -0,0 +1,138 @@
+function segments=contourenvelope(md,varargin)
+%CONTOURENVELOPE - build a set of segments enveloping a contour .exp
+%
+%   Usage:
+%      segments=contourenvelope(md,varargin)
+%
+%   Example:
+%      segments=contourenvelope(md,'Stream.exp');
+%      segments=contourenvelope(md);
+
+%some checks
+if nargin>2,
+	help contourenvelope
+	error('contourenvelope error message: bad usage');
+end
+if nargin==2,
+	flags=varargin{1};
+
+	if ischar(flags),
+		file=flags;
+		if ~exist(file),
+			error(['contourenvelope error message: file ' file ' not found']);
+		end
+		isfile=1;
+	elseif isnumeric(flags),
+		%do nothing for now
+		isfile=0;
+	else
+		error('contourenvelope error message:  second argument should be a file or an elements flag');
+	end
+end
+
+%Now, build the connectivity tables for this mesh.
+%Computing connectivity
+if (size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices & size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices2d),
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if (size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements & size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements2d),
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%get nodes inside profile
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+if dimension(md.mesh)==2,
+	mesh.elements=md.mesh.elements;
+	mesh.x=md.mesh.x;
+	mesh.y=md.mesh.y;
+	mesh.numberofvertices=md.mesh.numberofvertices;
+	mesh.numberofelements=md.mesh.numberofelements;
+else
+	mesh.elements=md.mesh.elements2d;
+	mesh.x=md.mesh.x2d;
+	mesh.y=md.mesh.y2d;
+	mesh.numberofvertices=md.mesh.numberofvertices2d;
+	mesh.numberofelements=md.mesh.numberofelements2d;
+end
+
+if nargin==2,
+
+	if isfile,
+		%get flag list of elements and nodes inside the contour
+		nodein=ContourToMesh(mesh.elements,mesh.x,mesh.y,file,'node',1);
+		elemin=(sum(nodein(mesh.elements),2)==size(mesh.elements,2));
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	else
+		%get flag list of elements and nodes inside the contour
+		nodein=zeros(mesh.numberofvertices,1);
+		elemin=zeros(mesh.numberofelements,1);
+
+		pos=find(flags);
+		elemin(pos)=1;
+		nodein(mesh.elements(pos,:))=1;
+
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	end
+end
+
+%Find element on boundary
+%First: find elements on the boundary of the domain
+flag=mesh.elementconnectivity;
+if nargin==2,
+	flag(find(flag))=elemin(flag(find(flag)));
+end
+elementonboundary=double(prod(flag,2)==0 & sum(flag,2)>0);
+
+%Find segments on boundary
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments*3,3);
+count=1;
+
+for i=1:num_segments,
+	el1=pos(i);
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+	if length(els2)>1,
+		flag=intersect(intersect(mesh.elements(els2(1),:),mesh.elements(els2(2),:)),mesh.elements(el1,:));
+		nods1=mesh.elements(el1,:);
+		nods1(find(nods1==flag))=[];
+		segments(count,:)=[nods1 el1];
+
+		ord1=find(nods1(1)==mesh.elements(el1,:));
+		ord2=find(nods1(2)==mesh.elements(el1,:));
+
+		%swap segment nodes if necessary
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+	else
+		nods1=mesh.elements(el1,:);
+		flag=setdiff(nods1,mesh.elements(els2,:));
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+				segments(count,:)=[nods el1];
+				ord1=find(nods(1)==mesh.elements(el1,:));
+				ord2=find(nods(2)==mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
+segments=segments(1:count-1,:);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/contourenvelope.py	(revision 18231)
@@ -0,0 +1,135 @@
+import os.path
+import numpy
+import copy
+from NodeConnectivity import NodeConnectivity
+from ElementConnectivity import ElementConnectivity
+from mesh2d import mesh2d
+from mesh3dprisms import mesh3dprisms
+import MatlabFuncs as m
+
+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);
+	"""
+
+	#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
+	elementconnectivity=copy.deepcopy(md.mesh.elementconnectivity)
+	if md.mesh.dimension()==2:
+		elements=copy.deepcopy(md.mesh.elements)
+		x=copy.deepcopy(md.mesh.x)
+		y=copy.deepcopy(md.mesh.y)
+		numberofvertices=copy.deepcopy(md.mesh.numberofvertices)
+		numberofelements=copy.deepcopy(md.mesh.numberofelements)
+	else:
+		elements=copy.deepcopy(md.mesh.elements2d)
+		x=copy.deepcopy(md.mesh.x2d)
+		y=copy.deepcopy(md.mesh.y2d)
+		numberofvertices=copy.deepcopy(md.mesh.numberofvertices2d)
+		numberofelements=copy.deepcopy(md.mesh.numberofelements2d)
+
+	if len(args)==1:
+
+		if isfile:
+			#get flag list of elements and nodes inside the contour
+			nodein=ContourToMesh(elements,x,y,file,'node',1)
+			elemin=(numpy.sum(nodein(elements),axis=1)==numpy.size(elements,axis=1))
+			#modify element connectivity
+			elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
+			elementconnectivity[elemout,:]=0
+			elementconnectivity[numpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
+		else:
+			#get flag list of elements and nodes inside the contour
+			nodein=numpy.zeros(numberofvertices)
+			elemin=numpy.zeros(numberofelements)
+
+			pos=numpy.nonzero(flags)
+			elemin[pos]=1
+			nodein[elements[pos,:]-1]=1
+
+			#modify element connectivity
+			elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
+			elementconnectivity[elemout,:]=0
+			elementconnectivity[numpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
+
+	#Find element on boundary
+	#First: find elements on the boundary of the domain
+	flag=copy.deepcopy(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)
+
+	#Find segments on boundary
+	pos=numpy.nonzero(elementonboundary)[0]
+	num_segments=numpy.size(pos)
+	segments=numpy.zeros((num_segments*3,3),int)
+	count=0
+
+	for el1 in pos:
+		els2=elementconnectivity[el1,numpy.nonzero(elementconnectivity[el1,:])[0]]-1
+		if numpy.size(els2)>1:
+			flag=numpy.intersect1d(numpy.intersect1d(elements[els2[0],:],elements[els2[1],:]),elements[el1,:])
+			nods1=elements[el1,:]
+			nods1=numpy.delete(nods1,numpy.nonzero(nods1==flag))
+			segments[count,:]=[nods1[0],nods1[1],el1+1]
+
+			ord1=numpy.nonzero(nods1[0]==elements[el1,:])[0][0]
+			ord2=numpy.nonzero(nods1[1]==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=elements[el1,:]
+			flag=numpy.setdiff1d(nods1,elements[els2,:])
+			for j in xrange(0,3):
+				nods=numpy.delete(nods1,j)
+				if numpy.any(m.ismember(flag,nods)):
+					segments[count,:]=[nods[0],nods[1],el1+1]
+					ord1=numpy.nonzero(nods[0]==elements[el1,:])[0][0]
+					ord2=numpy.nonzero(nods[1]==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/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.m	(revision 18231)
@@ -0,0 +1,57 @@
+function md=parameterize(md,parametername)
+%PARAMETERIZE - parameterize a model
+%
+%   from a parameter matlab file, start filling in all the @model fields that were not 
+%   filled in by the mesh.m and mask.m @model methods.
+%   Warning: the parameter file must be able to be run in Matlab
+%
+%   Usage:
+%      md=parameterize(md,parametername)
+%
+%   Example:
+%      md=parameterize(md,'Square.par');
+
+%some checks
+if ~exist(parametername),
+	error(['parameterize error message: file ' parametername ' not found!']);
+end
+
+%Try and run parameter file.
+temporaryname=['TemporaryParameterFile' num2str(feature('GetPid')) ];
+copyfile(parametername,[temporaryname '.m']);
+
+%WARNING: this is a bug of matlab: the TemporaryParameterFile must be cleared
+%otherwise matlab keeps the previous version of this file which is not what
+%we want!!!
+eval(['clear ' temporaryname]);
+
+try,
+	eval(temporaryname);
+	delete([temporaryname '.m']);
+catch me,
+	delete([temporaryname '.m']);
+
+	%copy error message
+	me2=struct('message',me.message,'stack',me.stack);
+
+	%rename parameter file
+	me2.message=regexprep(me2.message,[temporaryname '.m'],parametername);
+	for i=1:length(me2.stack)-1,
+		me2.stack(i).file=regexprep(me2.stack(i).file,[temporaryname '.m'],parametername);
+		me2.stack(i).name=regexprep(me2.stack(i).name,[temporaryname],parametername);
+		if strcmp(me2.stack(i).name,'parameterize'),
+			%remove error (eval(temporaryname);) misleading
+			me2.stack(i)=[];
+		end
+	end
+
+	%throw error message
+	rethrow(me2);
+end
+
+%Name and notes
+if isempty(md.miscellaneous.name), 
+	[path,root,ext]=fileparts(parametername);
+	md.miscellaneous.name=root; 
+end
+md.miscellaneous.notes=['Model created by using parameter file: ' parametername ' on: ' datestr(now)];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/parameterize.py	(revision 18231)
@@ -0,0 +1,33 @@
+import os
+import datetime
+
+def parameterize(md,parametername):
+	"""
+	PARAMETERIZE - parameterize a model
+
+	   from a parameter python file, start filling in all the model fields that were not 
+	   filled in by the mesh.py and mask.py model methods.
+	   Warning: the parameter file must be able to be run in Python
+
+	   Usage:
+	      md=parameterize(md,parametername)
+
+	   Example:
+	      md=parameterize(md,'Square.par');
+	"""
+
+	#some checks
+	if not os.path.exists(parametername):
+		raise IOError("parameterize error message: file '%s' not found!" % parametername)
+
+	#Try and run parameter file.
+	execfile(parametername)
+
+	#Name and notes
+	if not md.miscellaneous.name:
+		md.miscellaneous.name=os.path.basename(parametername).split('.')[0]
+
+	md.miscellaneous.notes="Model created by using parameter file: '%s' on: %s." % (parametername,datetime.datetime.strftime(datetime.datetime.now(),'%c'))
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.m	(revision 18231)
@@ -0,0 +1,301 @@
+function md=setflowequation(md,varargin)
+%SETFLOWEQUATION - associate a solution type to each element
+%
+%   This routine works like plotmodel: it works with an even number of inputs
+%   'SIA','SSA','L1L2','HO','FS' and 'fill' are the possible options
+%   that must be followed by the corresponding exp file or flags list
+%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+%   If user wants every element outside the domain to be 
+%   setflowequationd, add '~' to the name of the domain file (ex: '~HO.exp');
+%   an empty string '' will be considered as an empty domain
+%   a string 'all' will be considered as the entire domain
+%   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+%   NB: L1L2 cannot currently be coupled to any other ice flow model
+%
+%   Usage:
+%      md=setflowequation(md,varargin)
+%
+%   Example:
+%      md=setflowequation(md,'HO','HO.exp',fill','SIA','coupling','tiling');
+
+%some checks on list of arguments
+if ((nargin<2) | (nargout~=1)),
+	error('setflowequation error message');
+end
+
+%Process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%Find_out what kind of coupling to use
+coupling_method=getfieldvalue(options,'coupling','tiling');
+if (~strcmpi(coupling_method,'tiling') & ~strcmpi(coupling_method,'penalties')),
+	error('coupling type can only be: tiling or penalties');
+end
+
+%recover elements distribution
+SIAflag  = FlagElements(md,getfieldvalue(options,'SIA',''));
+SSAflag  = FlagElements(md,getfieldvalue(options,'SSA',''));
+HOflag   = FlagElements(md,getfieldvalue(options,'HO',''));
+L1L2flag = FlagElements(md,getfieldvalue(options,'L1L2',''));
+FSflag   = FlagElements(md,getfieldvalue(options,'FS',''));
+filltype = getfieldvalue(options,'fill','none');
+displayunused(options);
+
+%Flag the elements that have not been flagged as filltype
+if strcmpi(filltype,'SIA'),
+	SIAflag(find(~(SSAflag | HOflag)))=1;
+elseif strcmpi(filltype,'SSA'),
+	SSAflag(find(~(SIAflag | HOflag | FSflag)))=1;
+elseif strcmpi(filltype,'HO'),
+	HOflag(find(~(SIAflag | SSAflag | FSflag)))=1;
+end
+
+%check that each element has at least one flag
+if any(SIAflag+SSAflag+HOflag+L1L2flag+FSflag==0),
+	error('elements type not assigned, supported models are ''SIA'',''SSA'',''HO'' and ''FS''')
+end
+
+%check that each element has only one flag
+if any(SIAflag+SSAflag+HOflag+L1L2flag+FSflag>1),
+	disp('setflowequation warning message: some elements have several types, higher order type is used for them')
+	SIAflag(find(SIAflag & SSAflag))=0;
+	SIAflag(find(SIAflag & HOflag))=0;
+	SSAflag(find(SSAflag & HOflag))=0;
+end
+
+%check that L1L2 is not coupled to any other model for now
+if any(L1L2flag) & any(SIAflag | SSAflag | HOflag | FSflag)
+	error('L1L2 cannot be coupled to any other model');
+end
+
+%Check that no HO or FS for 2d mesh
+if strcmp(domaintype(md.mesh),'2Dhorizontal')
+	if any(FSflag | HOflag)
+		error('FS and HO elements not allowed in 2d mesh, extrude it first')
+	end
+end
+
+%FS can only be used alone for now:
+if any(FSflag) &any(SIAflag),
+	error('FS cannot be used with any other model for now, put FS everywhere')
+end
+
+%Initialize node fields
+nodeonSIA=zeros(md.mesh.numberofvertices,1);
+nodeonSIA(md.mesh.elements(find(SIAflag),:))=1;
+nodeonSSA=zeros(md.mesh.numberofvertices,1);
+nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+nodeonHO=zeros(md.mesh.numberofvertices,1);
+nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+nodeonL1L2=zeros(md.mesh.numberofvertices,1);
+nodeonL1L2(md.mesh.elements(find(L1L2flag),:))=1;
+nodeonFS=zeros(md.mesh.numberofvertices,1);
+noneflag=zeros(md.mesh.numberofelements,1);
+
+%First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
+if any(FSflag),
+	fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS));         %find all the nodes on the boundary of the domain without icefront
+	fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+	FSflag(find(fullspcelems))=0;
+	nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+end
+
+%Then complete with NoneApproximation or the other model used if there is no FS
+if any(FSflag), 
+	if any(HOflag), %fill with HO
+		HOflag(~FSflag)=1;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+	elseif any(SSAflag), %fill with SSA
+		SSAflag(~FSflag)=1;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+	else %fill with none 
+		noneflag(find(~FSflag))=1;
+	end
+end
+
+%Now take care of the coupling between SSA and HO
+md.stressbalance.vertex_pairing=[];
+nodeonSSAHO=zeros(md.mesh.numberofvertices,1);
+nodeonHOFS=zeros(md.mesh.numberofvertices,1);
+nodeonSSAFS=zeros(md.mesh.numberofvertices,1);
+SSAHOflag=zeros(md.mesh.numberofelements,1);
+SSAFSflag=zeros(md.mesh.numberofelements,1);
+HOFSflag=zeros(md.mesh.numberofelements,1);
+if strcmpi(coupling_method,'penalties'),
+	%Create the border nodes between HO and SSA and extrude them
+	numnodes2d=md.mesh.numberofvertices2d;
+	numlayers=md.mesh.numberoflayers;
+	bordernodes2d=find(nodeonHO(1:numnodes2d) & nodeonSSA(1:numnodes2d)); %Nodes connected to two different types of elements
+
+	%initialize and fill in penalties structure
+	if ~isnan(bordernodes2d),
+		penalties=[];
+		for	i=1:numlayers-1,
+			penalties=[penalties; [bordernodes2d bordernodes2d+md.mesh.numberofvertices2d*(i)]];
+		end
+		md.stressbalance.vertex_pairing=penalties;
+	end
+elseif strcmpi(coupling_method,'tiling'),
+	if any(SSAflag) & any(HOflag), %coupling SSA HO
+		%Find node at the border
+		nodeonSSAHO(find(nodeonSSA & nodeonHO))=1;
+		%SSA elements in contact with this layer become SSAHO elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonSSAHO));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(HOflag))=0; %only one layer: the elements previously in SSA
+		SSAflag(find(commonelements))=0; %these elements are now SSAHOelements
+		SSAHOflag(find(commonelements))=1;
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(SSAHOflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonSSA(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonHO(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		SSAflag(pos(pos1))=1;
+		SSAHOflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		HOflag(pos(pos2))=1;
+		SSAHOflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+		nodeonHO(:)=0;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+		nodeonSSAHO(:)=0;
+		nodeonSSAHO(md.mesh.elements(find(SSAHOflag),:))=1;
+
+	elseif any(HOflag) & any(FSflag), %coupling HO FS
+		%Find node at the border
+		nodeonHOFS(find(nodeonHO & nodeonFS))=1;
+		%FS elements in contact with this layer become HOFS elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonHOFS));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(HOflag))=0; %only one layer: the elements previously in SSA
+		FSflag(find(commonelements))=0; %these elements are now SSAHOelements
+		HOFSflag(find(commonelements))=1;
+		nodeonFS=zeros(md.mesh.numberofvertices,1);
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(HOFSflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonFS(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonHO(md.mesh.elements(pos,:)),2),2);
+		pos1=find(elist==1);
+		FSflag(pos(pos1))=1;
+		HOFSflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		HOflag(pos(pos2))=1;
+		HOFSflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonFS(:)=0;
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+		nodeonHO(:)=0;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+		nodeonHOFS(:)=0;
+		nodeonHOFS(md.mesh.elements(find(HOFSflag),:))=1;
+
+	elseif any(FSflag) & any(SSAflag),
+		%Find node at the border
+		nodeonSSAFS(find(nodeonSSA & nodeonFS))=1;
+		%FS elements in contact with this layer become SSAFS elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonSSAFS));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(SSAflag))=0; %only one layer: the elements previously in SSA
+		FSflag(find(commonelements))=0; %these elements are now SSASSAelements
+		SSAFSflag(find(commonelements))=1;
+		nodeonFS=zeros(md.mesh.numberofvertices,1);
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(SSAFSflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonSSA(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonFS(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		SSAflag(pos(pos1))=1;
+		SSAFSflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		FSflag(pos(pos2))=1;
+		SSAFSflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+		nodeonFS(:)=0;
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+		nodeonSSAFS(:)=0;
+		nodeonSSAFS(md.mesh.elements(find(SSAFSflag),:))=1;
+
+	elseif any(FSflag) & any(SIAflag),
+		error('type of coupling not supported yet');
+	end
+end
+
+%Create element equations
+md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
+md.flowequation.element_equation(find(noneflag))=0;
+md.flowequation.element_equation(find(SIAflag))=1;
+md.flowequation.element_equation(find(SSAflag))=2;
+md.flowequation.element_equation(find(L1L2flag))=3;
+md.flowequation.element_equation(find(HOflag))=4;
+md.flowequation.element_equation(find(FSflag))=5;
+md.flowequation.element_equation(find(SSAHOflag))=6;
+md.flowequation.element_equation(find(SSAFSflag))=7;
+md.flowequation.element_equation(find(HOFSflag))=8;
+
+%border
+md.flowequation.borderHO=nodeonHO;
+md.flowequation.borderSSA=nodeonSSA;
+md.flowequation.borderFS=nodeonFS;
+
+%Create vertices_type
+md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
+pos=find(nodeonSIA);
+md.flowequation.vertex_equation(pos)=1;
+pos=find(nodeonSSA);
+md.flowequation.vertex_equation(pos)=2;
+pos=find(nodeonL1L2);
+md.flowequation.vertex_equation(pos)=3;
+pos=find(nodeonHO);
+md.flowequation.vertex_equation(pos)=4;
+pos=find(nodeonFS);
+md.flowequation.vertex_equation(pos)=5;
+if any(FSflag),
+	pos=find(~nodeonFS);
+	if(~any(HOflag) & ~any(SSAflag)),
+		md.flowequation.vertex_equation(pos)=0;
+	end
+end
+pos=find(nodeonSSAHO);
+md.flowequation.vertex_equation(pos)=6;
+pos=find(nodeonHOFS);
+md.flowequation.vertex_equation(pos)=7;
+pos=find(nodeonSSAFS);
+md.flowequation.vertex_equation(pos)=8;
+
+%figure out solution types
+md.flowequation.isSIA  = double(any(md.flowequation.element_equation == 1));
+md.flowequation.isSSA  = double(any(md.flowequation.element_equation == 2));
+md.flowequation.isL1L2 = double(any(md.flowequation.element_equation == 3));
+md.flowequation.isHO   = double(any(md.flowequation.element_equation == 4));
+md.flowequation.isFS   = double(any(md.flowequation.element_equation == 5));
+
+return
+
+%Check that tiling can work:
+if any(md.flowequation.borderSSA) & any(md.flowequation.borderHO) & any(md.flowequation.borderHO + md.flowequation.borderSSA ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.borderSSA) & any(md.flowequation.borderFS) & any(md.flowequation.borderFS + md.flowequation.borderSSA ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.borderFS) & any(md.flowequation.borderHO) & any(md.flowequation.borderHO + md.flowequation.borderFS~=1),
+	error('error coupling domain too irregular');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setflowequation.py	(revision 18231)
@@ -0,0 +1,287 @@
+import numpy
+from model import model
+from pairoptions import pairoptions
+import MatlabFuncs as m
+import PythonFuncs as p
+from FlagElements import FlagElements
+
+def setflowequation(md,*args):
+	"""
+	SETFLOWEQUATION - associate a solution type to each element
+
+	   This routine works like plotmodel: it works with an even number of inputs
+	   'SIA','SSA','HO','L1L2','FS' and 'fill' are the possible options
+	   that must be followed by the corresponding exp file or flags list
+	   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+	   If user wants every element outside the domain to be 
+	   setflowequationd, add '~' to the name of the domain file (ex: '~HO.exp');
+	   an empty string '' will be considered as an empty domain
+	   a string 'all' will be considered as the entire domain
+	   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+
+	   Usage:
+	      md=setflowequation(md,varargin)
+
+	   Example:
+	      md=setflowequation(md,'HO','HO.exp',fill','SIA','coupling','tiling');
+	"""
+
+	#some checks on list of arguments
+	if not isinstance(md,model) or not len(args):
+		raise TypeError("setflowequation error message")
+
+	#process options
+	options=pairoptions(*args)
+#	options=deleteduplicates(options,1);
+
+	#Find_out what kind of coupling to use
+	coupling_method=options.getfieldvalue('coupling','tiling')
+	if not m.strcmpi(coupling_method,'tiling') and not m.strcmpi(coupling_method,'penalties'):
+		raise TypeError("coupling type can only be: tiling or penalties")
+
+	#recover elements distribution
+	SIAflag   = FlagElements(md,options.getfieldvalue('SIA',''))
+	SSAflag = FlagElements(md,options.getfieldvalue('SSA',''))
+	HOflag   = FlagElements(md,options.getfieldvalue('HO',''))
+	L1L2flag     = FlagElements(md,options.getfieldvalue('L1L2',''))
+	FSflag   = FlagElements(md,options.getfieldvalue('FS',''))
+	filltype     = options.getfieldvalue('fill','none')
+
+	#Flag the elements that have not been flagged as filltype
+	if   m.strcmpi(filltype,'SIA'):
+		SIAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SSAflag,HOflag)))]=True
+	elif m.strcmpi(filltype,'SSA'):
+		SSAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,HOflag,FSflag)))]=True
+	elif m.strcmpi(filltype,'HO'):
+		HOflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,SSAflag,FSflag)))]=True
+
+	#check that each element has at least one flag
+	if not any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag):
+		raise TypeError("elements type not assigned, supported models are 'SIA','SSA','HO' and 'FS'")
+
+	#check that each element has only one flag
+	if any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag>1):
+		print "setflowequation warning message: some elements have several types, higher order type is used for them"
+		SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,SSAflag))]=False
+		SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,HOflag))]=False
+		SSAflag[numpy.nonzero(numpy.logical_and(SSAflag,HOflag))]=False
+
+	#FS can only be used alone for now:
+	if any(FSflag) and any(SIAflag):
+		raise TypeError("FS cannot be used with any other model for now, put FS everywhere")
+
+	#Initialize node fields
+	nodeonSIA=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSIA[md.mesh.elements[numpy.nonzero(SIAflag),:]-1]=True
+	nodeonSSA=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+	nodeonL1L2=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonL1L2[md.mesh.elements[numpy.nonzero(L1L2flag),:]-1]=True
+	nodeonHO=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+	nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
+	noneflag=numpy.zeros(md.mesh.numberofelements,bool)
+
+	#First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
+	if any(FSflag):
+#		fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS));         %find all the nodes on the boundary of the domain without icefront
+		fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.stressbalance.spcvz)).astype(int)==3, \
+		                              numpy.logical_and(nodeonHO,nodeonFS)).astype(int)    #find all the nodes on the boundary of the domain without icefront
+#		fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+		fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
+		FSflag[numpy.nonzero(fullspcelems.reshape(-1))]=False
+		nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+
+	#Then complete with NoneApproximation or the other model used if there is no FS
+	if any(FSflag): 
+		if   any(HOflag):    #fill with HO
+			HOflag[numpy.logical_not(FSflag)]=True
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+		elif any(SSAflag):    #fill with SSA
+			SSAflag[numpy.logical_not(FSflag)]=True
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+		else:    #fill with none 
+			noneflag[numpy.nonzero(numpy.logical_not(FSflag))]=True
+
+	#Now take care of the coupling between SSA and HO
+	md.stressbalance.vertex_pairing=numpy.array([])
+	nodeonSSAHO=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonHOFS=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSSAFS=numpy.zeros(md.mesh.numberofvertices,bool)
+	SSAHOflag=numpy.zeros(md.mesh.numberofelements,bool)
+	SSAFSflag=numpy.zeros(md.mesh.numberofelements,bool)
+	HOFSflag=numpy.zeros(md.mesh.numberofelements,bool)
+	if   m.strcmpi(coupling_method,'penalties'):
+		#Create the border nodes between HO and SSA and extrude them
+		numnodes2d=md.mesh.numberofvertices2d
+		numlayers=md.mesh.numberoflayers
+		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
+
+		#initialize and fill in penalties structure
+		if numpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):
+			penalties=numpy.zeros((0,2))
+			for	i in xrange(1,numlayers):
+				penalties=numpy.vstack((penalties,numpy.hstack((bordernodes2d.reshape(-1,1),bordernodes2d.reshape(-1,1)+md.mesh.numberofvertices2d*(i)))))
+			md.stressbalance.vertex_pairing=penalties
+
+	elif m.strcmpi(coupling_method,'tiling'):
+		if   any(SSAflag) and any(HOflag):    #coupling SSA HO
+			#Find node at the border
+			nodeonSSAHO[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonHO))]=True
+			#SSA elements in contact with this layer become SSAHO elements
+			matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAHO)[0])
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
+			SSAflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
+			SSAHOflag[numpy.nonzero(commonelements)]=True
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(SSAHOflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
+			SSAflag[pos[pos1]]=True
+			SSAHOflag[pos[pos1]]=False
+			pos2=numpy.nonzero(elist==-1)[0]
+			HOflag[pos[pos2]]=True
+			SSAHOflag[pos[pos2]]=False
+
+			#Recompute nodes associated to these elements
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+			nodeonHO[:]=False
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+			nodeonSSAHO[:]=False
+			nodeonSSAHO[md.mesh.elements[numpy.nonzero(SSAHOflag),:]-1]=True
+
+		elif any(HOflag) and any(FSflag):    #coupling HO FS
+			#Find node at the border
+			nodeonHOFS[numpy.nonzero(numpy.logical_and(nodeonHO,nodeonFS))]=True
+			#FS elements in contact with this layer become HOFS elements
+			matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonHOFS)[0])
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
+			FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
+			HOFSflag[numpy.nonzero(commonelements)]=True
+			nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(HOFSflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
+			FSflag[pos[pos1]]=True
+			HOFSflag[pos[pos1]]=False
+			pos2=numpy.nonzero(elist==-1)[0]
+			HOflag[pos[pos2]]=True
+			HOFSflag[pos[pos2]]=False
+
+			#Recompute nodes associated to these elements
+			nodeonFS[:]=False
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+			nodeonHO[:]=False
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+			nodeonHOFS[:]=False
+			nodeonHOFS[md.mesh.elements[numpy.nonzero(HOFSflag),:]-1]=True
+
+		elif any(FSflag) and any(SSAflag):
+			#Find node at the border
+			nodeonSSAFS[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonFS))]=True
+			#FS elements in contact with this layer become SSAFS elements
+			matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAFS)[0])
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(SSAflag)]=False    #only one layer: the elements previously in SSA
+			FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSASSAelements
+			SSAFSflag[numpy.nonzero(commonelements)]=True
+			nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(SSAFSflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
+			SSAflag[pos[pos1]]=True
+			SSAFSflag[pos[pos1]]=False
+			pos2=numpy.nonzero(elist==-1)[0]
+			FSflag[pos[pos2]]=True
+			SSAFSflag[pos[pos2]]=False
+
+			#Recompute nodes associated to these elements
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+			nodeonFS[:]=False
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+			nodeonSSAFS[:]=False
+			nodeonSSAFS[md.mesh.elements[numpy.nonzero(SSAFSflag),:]-1]=True
+
+		elif any(FSflag) and any(SIAflag):
+			raise TypeError("type of coupling not supported yet")
+
+	#Create SSAHOApproximation where needed
+	md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements,int)
+	md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
+	md.flowequation.element_equation[numpy.nonzero(SIAflag)]=1
+	md.flowequation.element_equation[numpy.nonzero(SSAflag)]=2
+	md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=3
+	md.flowequation.element_equation[numpy.nonzero(HOflag)]=4
+	md.flowequation.element_equation[numpy.nonzero(FSflag)]=5
+	md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=6
+	md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=7
+	md.flowequation.element_equation[numpy.nonzero(HOFSflag)]=8
+
+	#border
+	md.flowequation.borderHO=nodeonHO
+	md.flowequation.borderSSA=nodeonSSA
+	md.flowequation.borderFS=nodeonFS
+
+	#Create vertices_type
+	md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices,int)
+	pos=numpy.nonzero(nodeonSIA)
+	md.flowequation.vertex_equation[pos]=1
+	pos=numpy.nonzero(nodeonSSA)
+	md.flowequation.vertex_equation[pos]=2
+	pos=numpy.nonzero(nodeonL1L2)
+	md.flowequation.vertex_equation[pos]=3
+	pos=numpy.nonzero(nodeonHO)
+	md.flowequation.vertex_equation[pos]=4
+	pos=numpy.nonzero(nodeonFS)
+	md.flowequation.vertex_equation[pos]=5
+	if any(FSflag):
+		pos=numpy.nonzero(numpy.logical_not(nodeonFS))
+		if not (any(HOflag) or any(SSAflag)):
+			md.flowequation.vertex_equation[pos]=0
+	pos=numpy.nonzero(nodeonSSAHO)
+	md.flowequation.vertex_equation[pos]=6
+	pos=numpy.nonzero(nodeonHOFS)
+	md.flowequation.vertex_equation[pos]=7
+	pos=numpy.nonzero(nodeonSSAFS)
+	md.flowequation.vertex_equation[pos]=8
+
+	#figure out solution types
+	md.flowequation.isSIA=any(md.flowequation.element_equation==1)
+	md.flowequation.isSSA=any(md.flowequation.element_equation==2)
+	md.flowequation.isL1L2=any(md.flowequation.element_equation==3)
+	md.flowequation.isHO=any(md.flowequation.element_equation==4)
+	md.flowequation.isFS=any(md.flowequation.element_equation==5)
+
+	return md
+
+	#Check that tiling can work:
+	if any(md.flowequation.borderSSA) and any(md.flowequation.borderHO) and any(md.flowequation.borderHO + md.flowequation.borderSSA !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.borderSSA) and any(md.flowequation.borderFS) and any(md.flowequation.borderFS + md.flowequation.borderSSA !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.borderFS) and any(md.flowequation.borderHO) and any(md.flowequation.borderHO + md.flowequation.borderFS !=1):
+		raise TypeError("error coupling domain too irregular")
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.m	(revision 18231)
@@ -0,0 +1,70 @@
+function md=setmask(md,floatingicename,groundedicename,varargin)
+%SETMASK - establish boundaries between grounded and floating ice.
+%
+%   By default, ice is considered grounded. The contour floatingicename defines nodes 
+%   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+%   that are grounded (ie: ice rises, islands, etc ...)
+%   All input files are in the Argus format (extension .exp).
+%
+%   Usage:
+%      md=setmask(md,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask(md,'all','');
+%      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+%some checks on list of arguments
+if ((mod(nargin,2)==0) | (nargout~=1)),
+	help mask
+	error('mask error message');
+end
+
+if(nargin>3)
+	if(varargin(1)=='icedomain'),
+		icedomainname=varargin(2);	
+	else
+		error('mask error message: wrong field specified. Only icedomain allowed for now.');
+	end
+	if ~exist(icedomainname),
+        error(['setmask error message: file ' icedomainname ' not found!']);
+	end
+end
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+
+%the order here is important. we choose vertexongroundedice as default on the grounding line.
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+vertexonfloatingice(find(~vertexongroundedice))=1;
+%}}}
+
+%level sets
+md.mask.groundedice_levelset=vertexongroundedice;
+md.mask.groundedice_levelset(find(vertexongroundedice==0.))=-1.;
+
+if(nargin>3)
+	if(varargin(1)=='icedomain')
+		md.mask.ice_levelset = 1.*ones(md.mesh.numberofvertices,1);
+		%use contourtomesh to set ice values inside ice domain
+		[vertexinsideicedomain,elementinsideicedomain]=ContourToMesh(elements,x,y,icedomainname,'node',1);
+		pos=find(vertexinsideicedomain==1.);
+		md.mask.ice_levelset(pos) = -1.;
+	end
+else
+	md.mask.ice_levelset = -1.*ones(md.mesh.numberofvertices,1);
+end
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask.py	(revision 18231)
@@ -0,0 +1,71 @@
+import numpy
+import os
+from model import model
+from FlagElements import FlagElements
+import pairoptions
+from ContourToMesh import ContourToMesh
+
+def setmask(md, floatingicename, groundedicename, *args):
+	"""
+	SETMASK - establish boundaries between grounded and floating ice.
+
+	   By default, ice is considered grounded. The contour floatingicename defines nodes 
+	   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+	   that are grounded (ie: ice rises, islands, etc ...)
+	   All input files are in the Argus format (extension .exp).
+
+	   Usage:
+	      md=setmask(md,floatingicename,groundedicename)
+
+	   Examples:
+	      md=setmask(md,'all','');
+	      md=setmask(md,'Iceshelves.exp','Islands.exp');
+	"""
+	#some checks on list of arguments
+	if not isinstance(md,model):
+		raise TypeError("setmask error message")
+
+	if len(args)%2:
+		raise TypeError("odd number of arguments provided in setmask")
+
+	#process options
+	options=pairoptions.pairoptions(*args)
+
+	#Get assigned fields
+	x = md.mesh.x
+	y = md.mesh.y
+	elements = md.mesh.elements
+
+	#Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
+	elementonfloatingice = FlagElements(md, floatingicename)
+	elementongroundedice = FlagElements(md, groundedicename) 
+
+	#Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+	#arrays come from domain outlines that can intersect one another: 
+
+	elementonfloatingice = 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 = numpy.zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice = numpy.zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=True
+	vertexonfloatingice[numpy.nonzero(numpy.logical_not(vertexongroundedice))]=True
+	#}}}
+
+	#level sets
+	md.mask.groundedice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
+	md.mask.groundedice_levelset[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=1.
+
+	if(len(args)):
+		md.mask.ice_levelset = 1.*numpy.ones(md.mesh.numberofvertices)
+		icedomainfile = options.getfieldvalue('icedomain','none')
+		if not os.path.exists(icedomainfile):
+			raise IOError("setmask error message: ice domain file '%s' not found." % icedomainfile)
+		#use contourtomesh to set ice values inside ice domain
+		[vertexinsideicedomain,elementinsideicedomain]=ContourToMesh(elements,x,y,icedomainfile,'node',1)
+		md.mask.ice_levelset[numpy.nonzero(vertexinsideicedomain)[0]] = -1.
+	else:
+		md.mask.ice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask2.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask2.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/parameterization/setmask2.m	(revision 18231)
@@ -0,0 +1,141 @@
+function md=setmask2(md,landname,floatingicename,groundedicename)
+%GEOGRAPHY2 - establish land, ice sheet and ice shelf areas in a domains.
+%
+%   Usage:
+%      md=setmask2(md,landname,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask2(md,'LandName.exp','Iceshelves.exp','Islands.exp');
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%recover elements and nodes on land.
+if ischar(landname),
+	[vertexonland,elementonland]=ContourToMesh(elements,x,y,landname,'element and node',2);
+elseif isfloat(landname),
+	if size(landname,1)~=md.mesh.numberofelements,
+		error('Landname for area must be of same size as number of elements in model');
+	end
+	elementonland=landname;
+	vertexonland=zeros(md.mesh.numberofvertices,1);
+	vertexonland(md.mesh.elements(find(elementonland),:))=1;
+else
+	error('Invalid area option option');
+end
+
+%Now, build the connectivity tables for this mesh.
+if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%any element with 3 nodes on land should be on land:
+elementsonwater=find(~elementonland);
+wrongelements=elementsonwater(find(( vertexonland(md.mesh.elements(elementsonwater,1)) + vertexonland(md.mesh.elements(elementsonwater,2)) + vertexonland(md.mesh.elements(elementsonwater,3)) ...
+                  )==3));
+elementonland(wrongelements)=1;
+
+%any element with its barycentre on land should be on land: (only if landname is an expfile)
+if ischar(landname),
+weights={[1;1;1],[2;1;1],[1;2;1],[1;1;2]};
+	for i=1:length(weights),
+		xelem=x(md.mesh.elements)*weights{i}/sum(weights{i});
+		yelem=y(md.mesh.elements)*weights{i}/sum(weights{i});
+	end
+	baryonland=ContourToNodes(xelem,yelem,landname,1);
+	pos=find(~baryonland); elementonland(pos)=0;
+	pos=find(baryonland); elementonland(pos)=1;
+end
+
+%figure out which elements on land are actually in the middle of the ocean!
+pos1=find(elementonland); 
+connectedtoland=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtoland); connectedtoland(pos)=1-elementonland(connectedtoland(pos));
+connectedtolandsum=sum(connectedtoland,2);
+waterelements=pos1(find(connectedtolandsum==3));
+elementonland(waterelements)=0;
+
+%figure out which elements on water  are actually in the middle of the land!
+pos1=find(~elementonland); 
+connectedtowater=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtowater); connectedtowater(pos)=elementonland(connectedtowater(pos));
+connectedtowatersum=sum(connectedtowater,2);
+landelements=pos1(find(connectedtowatersum==3));
+elementonland(landelements)=1;
+
+%recover arrays of ice shelf nodes and elements, and ice sheet nodes and elements.
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+vertexonfloatingice(md.mesh.elements(find(elementonfloatingice),:))=1;
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+
+%now correct, so that none of the floatingice and groundedice elements and nodes are in the water.
+pos=find(~elementonland);
+elementonfloatingice(pos)=0; 
+elementongroundedice(pos)=0;
+
+pos=find(~vertexonland);
+vertexonfloatingice(pos)=0; 
+vertexongroundedice(pos)=0;
+
+%create vertexonwater and elementonwater: 
+vertexonwater=double(~vertexonland);
+elementonwater=double(~elementonland);
+
+%correct for islands:
+vertexonfloatingice=double(vertexonfloatingice & ~vertexongroundedice);
+elementonfloatingice=double(elementonfloatingice & ~elementongroundedice);
+
+%now, groundedices are everything except iceshelves and water
+vertexongroundedice=double(~vertexonfloatingice & ~vertexonwater);
+elementongroundedice=double(~elementonfloatingice & ~elementonwater);
+
+%Deal with segments on neumann:
+
+%Get current connectivity
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+
+%put 0 for elements on water
+pos=find(mesh.elementconnectivity);
+mesh.elementconnectivity(pos)=mesh.elementconnectivity(pos).*(~elementonwater(mesh.elementconnectivity(pos)));
+
+%put line of ones for elements on water
+pos=find(elementonwater);
+mesh.elementconnectivity(pos,:)=1;% line of ones for elements on water so they won't be considered
+
+%resort lines (zeros must be at the last column for findsegments)
+mesh.elementconnectivity=sort(mesh.elementconnectivity,2,'descend');
+
+%call findsegments to build segment using THIS conectivity
+md.mesh.segments=findsegments(md,'mesh.elementconnectivity',mesh.elementconnectivity);
+
+%some final checks: 
+%check that no node thinks it's on an ice shelf or ice sheet, and lies actually in the middle of the water.
+nodesgrounded=find(~vertexonwater);
+lengthconnectivity=size(md.mesh.vertexconnectivity,2);
+groundedcounters=md.mesh.vertexconnectivity(nodesgrounded,lengthconnectivity);
+groundedconnectivity=md.mesh.vertexconnectivity(nodesgrounded,1:lengthconnectivity-1);
+pos=find(groundedconnectivity);
+groundedconnectivity(pos)=elementonwater(groundedconnectivity(pos));
+groundedsum=sum(groundedconnectivity,2);
+errorflags=find(groundedsum==groundedcounters);
+errornodes=nodesgrounded(errorflags);
+
+vertexonwater(errornodes)=1;
+vertexongroundedice(errornodes)=0;
+vertexonfloatingice(errornodes)=0;
+
+%Return: 
+md.mesh.segmentmarkers(:)=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/AreaAverageOntoPartition.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/AreaAverageOntoPartition.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/AreaAverageOntoPartition.m	(revision 18231)
@@ -0,0 +1,55 @@
+function partvector=AreaAverageOntoPartition(md,vector,layer)
+%AREAAVERAGEONTOPARTITION 
+%   compute partition values for a certain vector expressed on the vertices of the mesh.
+%   Use area weighted average.
+%
+%   Usage:
+%      average=AreaAverageOntoPartition(md,vector)
+%      average=AreaAverageOntoPartition(md,vector,layer) %if in 3D, chose which layer is partitioned
+
+%some checks
+if dimension(md.mesh)==3,
+	if nargin~=3,
+		error('layer should be provided onto which Area Averaging occurs');
+	end
+	%save 3D model
+	md3d=md;
+
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+
+	%run connectivity routine
+	md=adjacency(md);
+
+	%finally, project vector: 
+	vector=project2d(md3d,vector,layer);
+	md.qmu.partition=project2d(md3d,md3d.qmu.partition,layer);
+end
+
+%ok, first check that part is Matlab indexed
+part=md.qmu.partition+1;
+
+%some check: 
+if md.qmu.numberofpartitions~=max(part),
+	error('AreaAverageOntoPartition error message: ''npart'' should be equal to max(md.qmu.partition)');
+end
+
+%initialize output
+partvector=zeros(max(part),1);
+
+%start weight average
+weightedvector=vector.*md.qmu.vertex_weight;
+for i=1:max(part),
+	pos=find(part==i);
+	partvector(i)=sum(weightedvector(pos))/sum(md.qmu.vertex_weight(pos));
+end
+
+%in 3D, restore 3D model:
+if dimension(md.mesh)==3,
+	md=md3d;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/adjacency.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/adjacency.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/adjacency.m	(revision 18231)
@@ -0,0 +1,26 @@
+function md=adjacency(md)
+%ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
+%
+%  function to create the adjacency matrix from the connectivity table.
+%
+%  the required output is:
+%    md.adj_mat     (double [sparse nv x nv], vertex adjacency matrix)
+%    md.qmu.vertex_weight        (double [nv], vertex weights)
+
+indi=[md.mesh.elements(:,1);md.mesh.elements(:,2);md.mesh.elements(:,3)];
+indj=[md.mesh.elements(:,2);md.mesh.elements(:,3);md.mesh.elements(:,1)];
+values=1;
+
+md.qmu.adjacency=sparse(indi,indj,values,md.mesh.numberofvertices,md.mesh.numberofvertices);
+md.qmu.adjacency=double([md.qmu.adjacency | md.qmu.adjacency']);
+
+%now, build vwgt:
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%get node connectivity
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+
+connectivity=md.mesh.vertexconnectivity(:,1:end-1);
+pos=find(connectivity);
+connectivity(pos)=areas(connectivity(pos))/3;
+md.qmu.vertex_weight=sum(connectivity,2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/flagedges.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/flagedges.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/flagedges.m	(revision 18231)
@@ -0,0 +1,45 @@
+function [xsegments ysegments]=flagedges(elements,x,y,partition)
+%FLAGEDGES - return pairs of x,y segments, delimiting partitions.
+%
+%   Usage:
+%      [xsegments ysegments]=flagedges(elements,x,y,partition)
+
+xsegments=[];
+ysegments=[];
+
+for i=1:size(elements,1),
+	m1=partition(elements(i,1));
+	m2=partition(elements(i,2));
+	m3=partition(elements(i,3));
+	x1=x(elements(i,1));
+	x2=x(elements(i,2));
+	x3=x(elements(i,3));
+	y1=y(elements(i,1));
+	y2=y(elements(i,2));
+	y3=y(elements(i,3));
+
+	if (m1~=m2) & (m1~=m3) & (m2~=m3),
+		xmiddle=(x1+x2+x3)/3;
+		ymiddle=(y1+y2+y3)/3;
+		xsegments=[xsegments; (x1+x2)/2 xmiddle];
+		xsegments=[xsegments; (x1+x3)/2 xmiddle];
+		xsegments=[xsegments; (x2+x3)/2 xmiddle];
+		ysegments=[ysegments; (y1+y2)/2 ymiddle];
+		ysegments=[ysegments; (y1+y3)/2 ymiddle];
+		ysegments=[ysegments; (y2+y3)/2 ymiddle];
+	end
+
+	if (m1==m2) & (m1~=m3),
+		xsegments=[xsegments; (x1+x3)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y3)/2 (y2+y3)/2];
+	end
+	if (m1==m3) & (m2~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y2+y3)/2];
+	end
+
+	if (m2==m3) & (m1~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x1+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y1+y3)/2];
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/partitioner.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/partitioner.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/partition/partitioner.m	(revision 18231)
@@ -0,0 +1,109 @@
+function md=partitioner(md,varargin)
+%PARTITIONER - partition mesh 
+%
+%   List of options to partitioner: 
+%
+%   package: 'chaco', 'metis' or 'scotch'
+%   npart: number of partitions.
+%   weighting: 'on' or 'off': default off
+%   section:  1 by defaults(1=bisection, 2=quadrisection, 3=octasection)
+%   recomputeadjacency:  'on' by default (set to 'off' to compute existing one)
+%   Output: md.qmu.partition recover the partition vector
+%   
+%   Usage:
+%      md=partitioner(md,'package','chaco','npart',100,'weighting','on');
+%
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'package','chaco');
+options=addfielddefault(options,'npart',10);
+options=addfielddefault(options,'weighting','on');
+options=addfielddefault(options,'section',1);
+options=addfielddefault(options,'recomputeadjacency','on');
+
+%get package: 
+package=getfieldvalue(options,'package');
+npart=getfieldvalue(options,'npart');
+recomputeadjacency=getfieldvalue(options,'recomputeadjacency');
+
+if(dimension(md.mesh)==3),
+	%partitioning essentially happens in 2D. So partition in 2D, then 
+	%extrude the partition vector vertically. 
+	md3d=md; %save  for later
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+end
+
+%adjacency matrix if needed:
+if strcmpi(recomputeadjacency,'on'),
+	md=adjacency(md);
+else
+	disp('skipping adjacency matrix computation as requested in the options');
+end
+
+if strcmpi(package,'chaco'),
+
+	%  default method (from chaco.m)
+	method=[1 1 0 0 1 1 50 0 .001 7654321]';
+	method(1)=3;    %  global method (3=inertial (geometric))
+	method(3)=0;    %  vertex weights (0=off, 1=on)
+
+	%specify bisection
+	method(6)=getfieldvalue(options,'section');%  ndims (1=bisection, 2=quadrisection, 3=octasection)
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+		method(3)=1;
+	else 
+		weights=[];
+	end
+
+	%  partition into nparts
+	if isa(md.mesh,'mesh2d'),
+		part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y,zeros(md.mesh.numberofvertices,1),method,npart,[])'+1; %index partitions from 1 up. like metis.
+	else
+		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.
+	end
+
+elseif strcmpi(package,'scotch'),
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+	end
+	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
+
+	part=maptab(:,2);%index partitions from 1 up. like metis.
+
+elseif strcmpi(package,'linear'),
+
+	part=1:1:md.mesh.numberofvertices;
+
+elseif strcmpi(package,'metis'),
+
+	[element_partitioning,part]=MeshPartition(md.mesh,md.qmu.numberofpartitions);
+
+else
+
+	error(['partitioner error message: could not find ' package ' partitioner']);
+	help partitioner
+end
+
+%extrude if we are in 3D:
+if dimension(md.mesh)==3,
+	md3d.qmu.vertex_weight=md.qmu.vertex_weight;
+	md3d.qmu.adjacency=md.qmu.adjacency;
+	md=md3d;
+	part=project3d(md,'vector',part','type','node');
+end
+
+md.qmu.partition=part;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.m	(revision 18231)
@@ -0,0 +1,505 @@
+function applyoptions(md,data,options)
+%APPLYOPTIONS - apply the options to current plot
+%
+%   Usage:
+%      applyoptions(md,data,options)
+%
+%   See also: PLOTMODEL, PARSE_OPTIONS
+
+%some defaults
+if isfield(md.mesh,'hemisphere'),
+	if strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
+	elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
+	end
+end
+
+%fontsize
+fontsize=getfieldvalue(options,'fontsize',14);
+
+%fontweight
+fontweight=getfieldvalue(options,'fontweight','normal');
+
+%title
+if exist(options,'title')
+	titlevalue=getfieldvalue(options,'title');
+	if iscell(titlevalue),
+		title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+	else
+		if ~isnan(titlevalue),
+			title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+		end
+	end
+end
+
+%xlabel, ylabel and zlabel
+if exist(options,'xlabel');
+	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'ylabel');
+	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'zlabel');
+	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%xticks, yticks and zticks
+if exist(options,'xtick'), set(gca,'XTick',getfieldvalue(options,'xtick')); end
+if exist(options,'ytick'), set(gca,'YTick',getfieldvalue(options,'ytick')); end
+if exist(options,'ztick'), set(gca,'ZTick',getfieldvalue(options,'ztick')); end
+
+%view 
+if dimension(md.mesh)==3 & ~exist(options,'layer'),
+	view(getfieldvalue(options,'view',3));
+else
+	view(getfieldvalue(options,'view',2));
+end
+
+%axis
+set(gca,'FontSize',getfieldvalue(options,'axisfontsize',fontsize));;
+if exist(options,'axis')
+	eval(['axis ' getfieldvalue(options,'axis')]);
+else
+	if strcmp(domaintype(md.mesh),'3D'),
+		if ~exist(options,'layer'),
+			axis auto tight
+		else
+			axis tight equal
+		end
+	elseif strcmp(domaintype(md.mesh),'2Dvertical'),
+		axis auto tight
+	elseif strcmp(domaintype(md.mesh),'2Dhorizontal'),
+		axis tight equal;
+	else
+		error('type of domain not supported');
+	end
+end
+
+%box
+if exist(options,'box')
+	eval(['box ' getfieldvalue(options,'box')]);
+end
+
+%xlim, ylim and zlim
+if exist(options,'xlim');
+	xlim(getfieldvalue(options,'xlim'));
+end
+if exist(options,'ylim');
+	ylim(getfieldvalue(options,'ylim'));
+end
+if exist(options,'zlim');
+	zlim(getfieldvalue(options,'zlim'));
+end
+
+%latlon
+%Must be done here (before xlim and ylim??) so that it uses the same xlim and ylim as plot_overlay
+%these are changed by axis that follows
+if ~strcmpi(getfieldvalue(options,'latlon','off'),'off')
+	latlonoverlay(md,options);
+end
+
+%Basinzoom
+if exist(options,'basin');
+	basinzoom(options);
+end
+
+%ShowBasins
+if strcmpi(getfieldvalue(options,'showbasins','off'),'on')
+	showbasins(options);
+end
+
+%Caxis
+if exist(options,'caxis'),
+	caxis(getfieldvalue(options,'caxis'));
+end
+
+%shading
+if exist(options,'shading'),
+	shading(getfieldvalue(options,'shading'));
+end
+
+%grid
+if exist(options,'grid'),
+	if strcmpi(getfieldvalue(options,'grid'),'on'),
+		grid on;
+	end
+end
+
+%colormap
+c = getcolormap(options);
+h = colormap(c);
+
+%wrapping
+if exist(options,'wrapping'),
+	if ~exist(options,'colormap'),
+		h=jet;
+	end
+	colormap(repmat(h,getfieldvalue(options,'wrapping',1),1));
+end
+
+%colorbar
+if getfieldvalue(options,'colorbar',1)==1,
+	if exist(options,'colorbarcornerposition'),
+		c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
+	else 
+		c=colorbar('peer',gca);
+	end
+	set(c,'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'YColor',getfieldvalue(options,'FontColor','k'));
+	if exist(options,'wrapping')
+		lim=get(c,'Ylim');
+		lim=[lim(1) lim(1)+(lim(2)-lim(1))/getfieldvalue(options,'wrapping')];
+		set(c,'Ylim',lim);
+	end
+	if exist(options,'colorbarpos'),
+		set(c,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	if exist(options,'log'),
+		nlab=length(get(c,'YTick'));
+		logvalue=getfieldvalue(options,'log');
+
+		scaleminmax=caxis;
+		Min=min(scaleminmax);
+		Max=max(scaleminmax);
+		set(c,'YLim',[Min Max]); % set colorbar limits
+		set(c,'YTick',linspace(Min,Max,nlab));     % set tick mark locations
+
+		labels = cell(1,nlab);
+		tick_vals = linspace(Min,Max,nlab);
+		tick_vals = exp(log(logvalue)*tick_vals);
+		warning off MATLAB:log:logOfZero;
+		for i = 1:nlab
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+			%labels{i} = sprintf('%-.4g',round_ice(tick_vals(i),2));
+		end
+		warning on MATLAB:log:logOfZero;
+		set(c,'YTickLabel',labels);
+	end 
+ 	if exist(options,'cbYLim'); 
+		set(c,'YLim',getfieldvalue(options,'cbYLim'));
+	end
+	if exist(options,'colorbartitle'),
+		set(get(c,'title'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbartitle'),...
+			'Color',getfieldvalue(options,'FontColor','k'));
+	end
+	if exist(options,'colorbarYLabel'),
+		set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
+			'Color',getfieldvalue(options,'FontColor','k'));
+	end
+	if exist(options,'colorbarwidth'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarwidth',1);
+		position=get(c,'Position');
+		dx=position(3);
+		newdx=dx*alpha;
+		position(1)=position(1)+(dx-newdx)/2;
+		position(3)=newdx;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'colorbarheight'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarheight',1);
+		position=get(c,'Position');
+		dy=position(4);
+		newdy=dy*alpha;
+		position(2)=position(2)+(dy-newdy)/2;
+		position(4)=newdy;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'cbYTickLabel');
+		tick_vals=getfieldvalue(options,'cbYTickLabel');
+		if ~isnumeric(tick_vals) & strcmp(tick_vals,'on')
+			tick_vals=get(c,'YTick')';
+			if exist(options,'log')
+				logval= getfieldvalue(options,'log');
+				for i= 1:numel(tick_vals)
+					tick_vals(i)= logval^(tick_vals(i));
+				end
+			elseif numel(tick_vals) == 3
+				tick_vals=[tick_vals(1); mean(tick_vals(1:2)); tick_vals(2); ...
+					mean(tick_vals(2:3)); tick_vals(3)];
+				set(c,'YTick',tick_vals);
+			end
+		else
+			if exist(options,'log')
+				logvalue=getfieldvalue(options,'log');
+				set(c,'YTick',log(tick_vals)./log(logvalue));
+			else
+				set(c,'YTick',tick_vals);
+			end
+		end
+		labels = cell(1,numel(tick_vals));
+		for i = 1:numel(tick_vals)
+			labels{i} = num2str(tick_vals(i));
+		end
+		set(c,'YTickLabel',labels);
+	end
+
+elseif getfieldvalue(options,'colorbar',1)==0,
+	colorbar('off');
+else
+	%do nothing
+
+end
+
+%area
+if exist(options,'area'),
+	antzoom(getfieldvalue(options,'area'));
+end
+
+%expdisp
+if exist(options,'expdisp'),
+	filename=(getfieldvalue(options,'expdisp'));
+	style=(getfieldvalue(options,'expstyle'));
+	linewidth=(getfieldvalue(options,'linewidth',1));
+	for i=1:length(getfieldvalue(options,'expdisp')),
+		filenamei=filename{i};
+		stylei=style{i};
+		if length(linewidth)==1,
+			linewidthi=linewidth;
+		else
+			linewidthi=linewidth{i};
+		end
+		expdisp(filenamei,gcf,stylei,linewidthi,getfieldvalue(options,'unit',1));
+	end
+end
+
+%text (default value is empty, not NaN...)
+if exist(options,'text');
+	textstring=getfieldvalue(options,'text');
+	textweight=getfieldvalue(options,'textweight','b');
+	textsize=getfieldvalue(options,'textsize');
+	textcolor=getfieldvalue(options,'textcolor');
+	textposition=getfieldvalue(options,'textposition');
+	textrotation=getfieldvalue(options,'textrotation');
+	for i=1:length(getfieldvalue(options,'text'));
+		textstringi=textstring{i};
+		textweighti=textweight{i};
+		textsizei=textsize{i};
+		textcolori=textcolor{i};
+		textpositioni=textposition{i};
+		textrotationi=textrotation{i};
+		h=text(textpositioni(1),textpositioni(2),10,textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
+		set(h,'Clipping','on'); %prevent text from appearing outside of the box
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	northarrow(getfieldvalue(options,'northarrow'));
+end
+
+%curved arrow
+if exist(options,'curvedarrow'),
+	curvedoptions=getfieldvalue(options,'curvedarrow');
+	curvedarrow(curvedoptions{:});
+end
+
+%Scale ruler
+if exist(options,'scaleruler'),
+	scaleruler(options);
+end
+
+%streamliness
+if exist(options,'streamlines'),
+	plot_streamlines(md,options);
+end
+
+%contours
+if exist(options,'contourlevels'),
+	plot_contour(md,data,options);
+end
+
+%YTickLabel
+if exist(options,'yticklabel'),
+	set(gca,'YTickLabel',getfieldvalue(options,'YTickLabel'));
+end
+
+%XTickLabel
+if exist(options,'xticklabel'),
+	set(gca,'XTickLabel',getfieldvalue(options,'XTickLabel'));
+end
+
+%xtick
+if exist(options,'xtick'),
+	set(gca,'xtick',getfieldvalue(options,'xtick'));
+end
+
+%ytick
+if exist(options,'ytick'),
+	set(gca,'ytick',getfieldvalue(options,'ytick'));
+end
+
+%Axis positions
+if exist(options,'offsetaxispos'),
+	offset=getfieldvalue(options,'offsetaxispos');
+	P=get(gca,'pos');
+	P(1)=P(1)+offset(1);
+	P(2)=P(2)+offset(2);
+	P(3)=P(3)+offset(3);
+	P(3)=P(4)+offset(4);
+	set(gca,'pos',P);
+end
+if exist(options,'axispos'),
+	Axis=getfieldvalue(options,'axispos');
+	hold on
+	set(gca,'pos',Axis);
+end
+
+%axes position
+if exist(options,'axesPosition')
+	set(gca,'Position',getfieldvalue(options,'axesPosition'));
+end
+
+%showregion
+if strcmpi(getfieldvalue(options,'showregion','off'),'on'),
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+	%get current plos position
+	cplotpos=get(maingca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	axes('pos',PosInset);
+	axis equal off
+	%box off
+	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+		A=expread('/u/astrid-r1b/ModelData/Exp/GreenlandBoxFront.exp');
+		[A.x A.y]=ll2xy(A.x,A.y,+1,45,70);
+		A.x = A.x(1:30:end);
+		A.y = A.y(1:30:end);
+	elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+		A=expread('/u/astrid-r1b/ModelData/Exp/Antarctica.exp');
+	else
+		error('applyoptions error message: hemisphere not defined');
+	end
+	offset=3*10^4;
+	Ax=[min(A.x)-offset max(A.x)+offset];
+	Ay=[min(A.y)-offset max(A.y)+offset];
+	%if we are zooming on a basin, don't take the mesh for the boundaries!
+	if exist(options,'basin'),
+		[mdx mdy]=basinzoom(options);
+	else
+		mdx=[min(md.mesh.x)-offset max(md.mesh.x)+offset];
+		mdy=[min(md.mesh.y)-offset max(md.mesh.y)+offset];
+	end
+	line(A.x,A.y,ones(size(A.x)),'color','b');
+	patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
+	patch([mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+	colorbar('off');
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
+
+%flag edges of a partition
+if exist(options,'partitionedges')
+	[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
+	xsegments=xsegments*getfieldvalue(options,'unit',1);
+	ysegments=ysegments*getfieldvalue(options,'unit',1);
+	color=getfieldvalue(options,'partitionedgescolor','r-');
+	linewidth=getfieldvalue(options,'linewidth',1);
+	hold on;
+	for i=1:length(xsegments),
+		plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
+	end
+end
+
+%Scatter
+if exist(options,'scatter')
+	data=getfieldvalue(options,'scatter');
+	hold on
+	plot_scatter(data(:,1),data(:,2),data(:,3),options);
+end
+
+%backgroundcolor
+set(gca,'color',getfieldvalue(options,'backgroundcolor','none'));
+
+%lighting
+if strcmpi(getfieldvalue(options,'light','off'),'on'),
+	set(gca,'FaceLighting','gouraud','FaceColor','interp','AmbientStrength',0.5);
+	light('Position',[0 0.1 0.1],'Style','infinite');
+end
+
+%cloud of points: 
+if exist(options,'cloud'),
+	field=getfieldvalue(options,'cloud');
+	x=field(:,1);
+	y=field(:,2);
+	%unit multiplier:
+	if exist(options,'unit'),
+		unit=getfieldvalue(options,'unit');
+		x=x*unit;
+		y=y*unit;
+	end
+	hold on,p=plot(x,y,'k.');
+	markersize=getfieldvalue(options,'markersize',5);
+	color=getfieldvalue(options,'cloudcolor','k');
+	set(p,'Color',color);
+	set(p,'MarkerSize',markersize);
+end
+
+%========================%
+%OK VERY LAST STEP: INSET|
+%========================%
+if exist(options,'inset'),
+
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.56 0.55 0.35 0.35]);
+	%get current plot position
+	cplotpos=get(gca,'pos');
+
+	X1=getfieldvalue(options,'insetx',xlim);
+	Y1=getfieldvalue(options,'insety',ylim);
+
+	for i=1:length(getfieldvalue(options,'insetx')),
+		if length(insetpos)==4,
+			insetposi=insetpos;
+		else
+			insetposi=insetpos{i};
+		end
+		PosInseti=[cplotpos(1)+insetposi(1)*cplotpos(3),cplotpos(2)+insetposi(2)*cplotpos(4), insetposi(3)*cplotpos(3), insetposi(4)*cplotpos(4)];
+		%show pos
+		if iscell(X1),
+			X1i=X1{i};
+		else
+			X1i=X1;
+		end
+		if iscell(Y1),
+			Y1i=Y1{i};
+		else
+			Y1i=Y1;
+		end
+		if strcmpi(getfieldvalue(options,'showinset','off'),'on')
+			line(X1i([1 2 2 1 1]),Y1i([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
+		end
+
+		%Get current figure
+		ax1=gca;
+
+		%plot inset
+		axes('pos',PosInseti);
+		copyobj(get(ax1,'children'),gca);
+		patch('Faces',[1 2 3 4 1],'Vertices',[X1i([1 2 2 1])' Y1i([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
+
+		%apply options
+		options=removefield(options,'text',0);
+		options=removefield(options,'title',0);
+		options=removefield(options,'xlabel',0);
+		options=removefield(options,'ylabel',0);
+		options=removefield(options,'inset',0);
+		options=removefield(options,'offsetaxispos',0);
+		options=removefield(options,'showregion',0);
+		options=changefieldvalue(options,'colorbar',0);
+		options=changefieldvalue(options,'latlon','off');
+		options=changefieldvalue(options,'axis','equal off');
+		options=changefieldvalue(options,'xlim',X1i);
+		options=changefieldvalue(options,'ylim',Y1i);
+		applyoptions(md,data,options);
+
+		%back to main gca
+		set(gcf,'CurrentAxes',maingca)
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/applyoptions.py	(revision 18231)
@@ -0,0 +1,288 @@
+import numpy as npy
+from cmaptools import truncate_colormap
+from plot_contour import plot_contour
+
+try:
+	from matplotlib.ticker import MaxNLocator
+	from mpl_toolkits.axes_grid1 import make_axes_locatable
+	import matplotlib as mpl
+	import pylab as p
+	import matplotlib.pyplot as plt
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+def applyoptions(md,data,options,fig,ax):
+	'''
+	APPLYOPTIONS - apply options to current plot
+
+	'plotobj' is the object returned by the specific plot call used to
+	render the data.  This object is used for adding a colorbar.
+
+		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)
+
+	# get handle to current figure and axes instance
+	#fig = p.gcf()
+	#ax=p.gca()
+
+	#font {{{
+	fontsize=options.getfieldvalue('fontsize',8)
+	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
+		ax.set_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'):
+		ax.set_xlabel(options.getfieldvalue('xlabel'),**labelfont)
+	if options.exist('ylabel'):
+		ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont)
+	if options.exist('zlabel'):
+		ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont)
+	#}}}
+
+	#xticks, yticks, zticks (tick locations) {{{
+	if options.exist('xticks'):
+		if options.exist('xticklabels'):
+			xticklabels=options.getfieldvalue('xticklabels')
+			ax.set_xticks(options.getfieldvalue('xticks'),xticklabels)
+		else:
+			ax.set_xticks(options.getfieldvalue('xticks'))
+	if options.exist('yticks'):
+		if options.exist('yticklabels'):
+			yticklabels=options.getfieldvalue('yticklabels')
+			ax.set_yticks(options.getfieldvalue('yticks'),yticklabels)
+		else:
+			ax.set_yticks(options.getfieldvalue('yticks'))
+	if options.exist('zticks'):
+		if options.exist('zticklabels'):
+			zticklabels=options.getfieldvalue('zticklabels')
+			ax.set_zticks(options.getfieldvalue('zticks'),zticklabels)
+		else:
+			ax.set_zticks(options.getfieldvalue('zticks'))
+	#}}}
+
+	#xticklabels,yticklabels,zticklabels {{{
+	if options.getfieldvalue('ticklabels','off')=='off' or options.getfieldvalue('ticklabels',0)==0:
+		options.addfielddefault('xticklabels',[])
+		options.addfielddefault('yticklabels',[])
+		# TODO check if ax has a z-axis (e.g. is 3D)
+	if options.exist('xticklabels'):
+		xticklabels=options.getfieldvalue('xticklabels')
+		ax.set_xticklabels(xticklabels)
+	if options.exist('yticklabels'):
+		yticklabels=options.getfieldvalue('yticklabels')
+		ax.set_yticklabels(yticklabels)
+	if options.exist('zticklabels'):
+		zticklabels=options.getfieldvalue('zticklabels')
+		ax.set_zticklabels(zticklabels)
+	#}}}
+
+	#ticklabel notation {{{
+	#ax.ticklabel_format(style='sci',scilimits=(0,0))
+	#}}}
+
+	#ticklabelfontsize {{{
+	if options.exist('ticklabelfontsize'):
+		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 {{{
+	if options.exist('axis'):
+		if options.getfieldvalue('axis',True)=='off':
+			ax.ticklabel_format(style='plain')
+			p.setp(ax.get_xticklabels(), visible=False)
+			p.setp(ax.get_yticklabels(), visible=False)
+	# }}}
+
+	#box
+
+	#xlim, ylim, zlim {{{
+	if options.exist('xlim'):
+		ax.set_xlim(options.getfieldvalue('xlim'))
+	if options.exist('ylim'):
+		ax.set_ylim(options.getfieldvalue('ylim'))
+	if options.exist('zlim'):
+		ax.set_zlim(options.getfieldvalue('zlim'))
+	#}}}
+
+	#latlon
+
+	#Basinzoom
+
+	#ShowBasins
+
+	#clim {{{
+	if options.exist('clim'):
+		lims=options.getfieldvalue('clim')
+		assert len(lims)==2, 'error, clim should be passed as a list of length 2'
+	elif options.exist('caxis'):
+		lims=options.getfieldvalue('caxis')
+		assert len(lims)==2, 'error, caxis should be passed as a list of length 2'
+		options.addfielddefault('clim',lims)
+	else:
+		if len(data)>0: lims=[data.min(),data.max()]
+		else: lims=[0,1]
+	#}}}
+
+	#shading
+
+	#grid {{{
+	if options.exist('grid'):
+		if 'on' in options.getfieldvalue('grid','on'):
+			ax.grid()
+	#}}}
+
+	#colormap {{{
+	# default sequential colormap
+	defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
+	cmap=options.getfieldvalue('colormap',defaultmap)
+	norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
+	options.addfield('colornorm',norm)
+	cbar_extend=0
+	if options.exist('cmap_set_over'):
+		over=options.getfieldvalue('cmap_set_over','0.5')
+		cmap.set_over(over)
+		cbar_extend+=1
+	if options.exist('cmap_set_under'):
+		under=options.getfieldvalue('cmap_set_under','0.5')
+		cmap.set_under(under)
+		cbar_extend+=2
+	options.addfield('colormap',cmap)
+	#}}}
+
+	#contours {{{
+	if options.exist('contourlevels'):
+		plot_contour(md,data,options,ax)
+	#}}}
+
+	#wrapping
+
+	#colorbar {{{
+	if options.getfieldvalue('colorbar',1)==1:
+		if cbar_extend==0:
+			extend='neither'
+		elif cbar_extend==1:
+			extend='max'
+		elif cbar_extend==2:
+			extend='min'
+		elif cbar_extend==3:
+			extend='both'
+		cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
+		if options.exist('alpha'):
+			cb.set_alpha(options.getfieldvalue('alpha'))
+		if options.exist('colorbarnumticks'):
+			cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
+		else:
+			cb.locator=MaxNLocator(nbins=5) # default 5 ticks
+		if options.exist('colorbartickspacing'):
+			locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
+			cb.set_ticks(locs)
+		if options.exist('colorbarlines'):
+			locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines'))
+			cb.add_lines(locs,['k' for i in range(len(locs))],npy.ones_like(locs))
+		if options.exist('colorbartitle'):
+			if options.exist('colorbartitlepad'):
+				cb.set_label(options.getfieldvalue('colorbartitle'),\
+						labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize)
+			else:
+				cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
+		cb.ax.tick_params(labelsize=fontsize)
+		cb.update_ticks()
+		plt.sca(ax) # return to original axes control
+	#}}}
+
+	#area
+
+	#expdisp
+
+	#text {{{
+	if options.exist('text'):
+		text=options.getfieldvalue('text')
+		textx=options.getfieldvalue('textx')
+		texty=options.getfieldvalue('texty')
+		textsize=options.getfieldvalue('textsize')
+		textcolor=options.getfieldvalue('textcolor')
+		textweight=options.getfieldvalue('textweight')
+		textrotation=options.getfieldvalue('textrotation')
+		for label,x,y,size,color,weight,rotation in zip(text,textx,texty,textsize,textcolor,textweight,textrotation):
+			ax.text(x,y,label,transform=ax.transAxes,fontsize=size,color=color,weight=weight,rotation=rotation)
+	#}}}
+
+	#north arrow
+
+	#scale ruler
+
+	#streamlines
+
+
+	#axis positions
+
+	#figure position
+
+	#axes position
+
+	#showregion
+
+	#flat edges of a partition
+
+	#scatter
+
+	#backgroundcolor
+
+	#figurebackgroundcolor
+
+	#lighting
+
+	#point cloud
+
+	#inset
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/arrow.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/arrow.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/arrow.m	(revision 18231)
@@ -0,0 +1,59 @@
+function arrow(x0,y0,x1,y1,varargin)
+%ARROW - plot arrow, using (x0,y0) and (x1,y1) as initial and end points. options can be specified.
+%
+%   Usage:
+%      arrow(x1,y1,x2,y2,options)
+%      where options is a lit of paired arguments of string OR enums
+%      options can be: 
+%            'ratio': default .5 (ratio headarrow/length)
+%            'widthratio': default is 1/10 of length
+
+%recover options
+options=pairoptions(varargin{:});
+ratio=getfieldvalue(options,'ratio',.5);
+widthratio=getfieldvalue(options,'widthratio',.1);
+color=getfieldvalue(options,'color','k');
+
+%compute some values out of (x1,y1) and (x2,y2)
+length=sqrt((x1-x0)^2+(y1-y0)^2);
+width=length*widthratio;
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0; y(1)=y0;
+x(2)=x1; y(2)=y1;
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],color);
+set(p1,'EdgeColor',color); set(p1,'FaceColor',color);
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],color);
+set(p2,'EdgeColor',color); set(p2,'FaceColor',color);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.m	(revision 18231)
@@ -0,0 +1,207 @@
+function options=checkplotoptions(md,options)
+%PARSE_OPTIONS - build a structure that holds all plot options
+%
+%   Usage:
+%      options=checkplotoptions(md,options);
+%
+%   See also: PLOTMODEL
+
+%units
+if exist(options,'unit'),
+	if strcmpi(getfieldvalue(options,'unit'),'km')
+		options=changefieldvalue(options,'unit',10^-3);
+	end
+	if strcmpi(getfieldvalue(options,'unit'),'100km')
+		options=changefieldvalue(options,'unit',10^-5);
+	end
+
+end
+
+%density
+if exist(options,'density'),
+	density=getfieldvalue(options,'density');
+	options=changefieldvalue(options,'density',abs(ceil(density)));
+end
+
+%Show section
+if exist(options,'showsection'),
+	if strcmpi(getfieldvalue(options,'showsection'),'on')
+		options=changefieldvalue(options,'showsection',4);
+	end
+end
+
+%smooth values
+if exist(options,'smooth'),
+	if strcmpi(getfieldvalue(options,'smooth'),'on')
+		options=changefieldvalue(options,'smooth',0);
+	end
+end
+
+%contouronly values
+if exist(options,'contouronly'),
+	if strcmpi(getfieldvalue(options,'contouronly'),'on')
+		options=changefieldvalue(options,'contouronly',1);
+	end
+end
+
+%Colorbar;
+if exist(options,'colorbar'),
+	if strcmpi(getfieldvalue(options,'colorbar'),'on')
+		options=changefieldvalue(options,'colorbar',1);
+	elseif strcmpi(getfieldvalue(options,'colorbar'),'off')
+			options=changefieldvalue(options,'colorbar',0);
+	end
+end
+
+%text
+if exist(options,'text'),
+	%1: textvalue
+	textvalues=getfieldvalue(options,'text');
+	%ischar if only one expstyle -> create a cell
+	if ischar(textvalues),
+		textvalues={textvalues};
+		numtext=1;
+	elseif iscell(textvalues),
+		numtext=length(textvalues);
+	else
+		error('plot error message: ''text'' option should be either a string or a cell');
+	end
+
+	%2: textweight
+	if exist(options,'textweight'),
+		textweightvalues=getfieldvalue(options,'textweight');
+		%ischar if only one textweight -> create a cell
+		if ischar(textweightvalues),
+			textweightvalues={textweightvalues};
+		elseif ~iscell(textweightvalues);
+			error('plot error message: ''textweight'' option should be either a string or a cell');
+		end
+	else
+		textweightvalues={'n'};
+	end
+	textweightvalues=repmat(textweightvalues,1,numtext); textweightvalues(numtext+1:end)=[];
+
+	%3: textsize
+	if exist(options,'textsize'),
+		textsizevalues=getfieldvalue(options,'textsize');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textsizevalues),
+			textsizevalues={textsizevalues};
+		elseif ~iscell(textsizevalues);
+			error('plot error message: ''textsize'' option should be either a number or a cell');
+		end
+	else
+		textsizevalues={14};
+	end
+	textsizevalues=repmat(textsizevalues,1,numtext); textsizevalues(numtext+1:end)=[];
+	%4: textcolor
+	if exist(options,'textcolor'),
+		textcolorvalues=getfieldvalue(options,'textcolor');
+		%ischar if only one textcolor -> create a cell
+		if ischar(textcolorvalues),
+			textcolorvalues={textcolorvalues};
+		elseif ~iscell(textcolorvalues);
+			error('plot error message: ''textcolor'' option should be either a string or a cell');
+		end
+	else
+		textcolorvalues={'k'};
+	end
+	textcolorvalues=repmat(textcolorvalues,1,numtext); textcolorvalues(numtext+1:end)=[];
+	%5: textposition
+	if exist(options,'textposition'),
+		textpositionvalues=getfieldvalue(options,'textposition');
+		%ischar if only one textposition -> create a cell
+		if isnumeric(textpositionvalues),
+			textpositionvalues={textpositionvalues};
+		elseif ~iscell(textpositionvalues);
+			error('plot error message: ''textposition'' option should be either a string or a cell');
+		end
+	else
+		error('plot error message: ''textposition'' option is missing');
+	end
+	%6: textrotation
+	if exist(options,'textrotation'),
+		textrotationvalues=getfieldvalue(options,'textrotation');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textrotationvalues),
+			textrotationvalues={textrotationvalues};
+		elseif ~iscell(textrotationvalues);
+			error('plot error message: ''textrotation'' option should be either a number or a cell');
+		end
+	else
+		textrotationvalues={0};
+	end
+	textrotationvalues=repmat(textrotationvalues,1,numtext); textrotationvalues(numtext+1:end)=[];
+	options=changefieldvalue(options,'text',textvalues);
+	options=changefieldvalue(options,'textsize',textsizevalues);
+	options=changefieldvalue(options,'textweight',textweightvalues);
+	options=changefieldvalue(options,'textcolor',textcolorvalues);
+	options=changefieldvalue(options,'textposition',textpositionvalues);
+	options=changefieldvalue(options,'textrotation',textrotationvalues);
+end
+
+%expdisp
+expdispvaluesarray=cell(0,0);
+expstylevaluesarray=cell(0,0);
+expstylevalues=cell(0,0);
+if exist(options,'expstyle'),
+	expstylevalues=getfieldvalue(options,'expstyle');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expstylevalues),
+		expstylevalues={expstylevalues};
+	end
+end
+if exist(options,'expdisp'),
+	expdispvalues=getfieldvalue(options,'expdisp');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expdispvalues),
+		expdispvalues={expdispvalues};
+	end
+	for i=1:length(expdispvalues)
+		expdispvaluesarray{end+1}=expdispvalues{i};
+		if (length(expstylevalues)>=i),
+			expstylevaluesarray{end+1}=expstylevalues{i};
+		else
+			expstylevaluesarray{end+1}='g-';
+		end
+	end
+end
+options=changefieldvalue(options,'expstyle',expstylevaluesarray);
+options=changefieldvalue(options,'expdisp',expdispvaluesarray);
+
+%latlonnumbering
+if exist(options,'latlonclick'),
+	if strcmpi(getfieldvalue(options,'latlonclick'),'on')
+		options=changefieldvalue(options,'latlonclick',1);
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	if strcmpi(getfieldvalue(options,'northarrow'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'northarrow',[min(md.mesh.x)+1/6*Lx   min(md.mesh.y)+5/6*Ly   1/15*Ly   0.25   1/250*Ly]);
+	end
+end
+
+%scale ruler
+if exist(options,'scaleruler'),
+	if strcmpi(getfieldvalue(options,'scaleruler'),'on')
+		%default values
+		Lx=max(md.mesh.x)-min(md.mesh.x);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'scaleruler',[min(md.mesh.x)+6/8*Lx   min(md.mesh.y)+1/10*Ly   10^(ceil(log10(Lx)))/5 floor(Lx/100) 5]);
+	end
+end
+
+%Log scale (LOTS of changes to be performed
+if exist(options,'log'),
+	if exist(options,'caxis')
+		options=changefieldvalue(options,'caxis',log(getfieldvalue(options,'caxis'))/log(getfieldvalue(options,'log')));
+	end
+	options=changefieldvalue(options,'cutoff',log(getfieldvalue(options,'cutoff',1.5))/log(getfieldvalue(options,'log')));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/checkplotoptions.py	(revision 18231)
@@ -0,0 +1,160 @@
+import numpy as npy
+
+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
+	'''
+
+
+	#units
+	if options.exist('unit'):
+		if 'km' in options.getfieldvalue('unit','km'):
+			options.changefieldvalue('unit',10**-3)
+		elif '100km' in options.getfieldvalue('unit','100km'):
+			options.changefieldvalue('unit',10**-5)
+	
+	#density
+	if options.exist('density'):
+		density=options.getfieldvalue('density')
+		options.changefieldvalue('density',abs(ceil(density)))
+	
+	#show section
+	if options.exist('showsection'):
+		if 'on' in options.getfieldvalue('showsection','on'):
+			options.changefieldvalue('showsection',4)
+	
+	#smooth values
+	if options.exist('smooth'):
+		if 'on' in options.getfieldvalue('smooth','on'):
+			options.changefieldvalue('smooth',0)
+
+	#contouronly values
+	if options.exist('contouronly'):
+		if 'on' in options.getfieldvalue('contouronly','on'):
+			options.changefieldvalue('contouronly',1)
+
+	#colorbar
+	if options.exist('colorbar'):
+		if 'on' in options.getfieldvalue('colorbar','on'):
+			options.changefieldvalue('colorbar',1)
+		elif 'off' in options.getfieldvalue('colorbar','off'):
+			options.changefieldvalue('colorbar',0)
+
+	#text
+	if options.exist('text'):
+
+		# text values (coerce to list for consistent functionality)
+		textlist=[]
+		text=options.getfieldvalue('text','default text')
+		textlist.extend([text] if isinstance(text,str) else text)
+		numtext=len(textlist)
+
+		# text position	
+		textpos=options.getfieldvalue('textposition',[0.5,0.5])
+		if not isinstance(textpos,list):
+			raise Exception('textposition should be passed as a list')
+		textx=[item[0] for item in textpos]
+		texty=[item[1] for item in textpos]
+		if len(textx)!=numtext or len(texty)!=numtext:
+			raise Exception('textposition should contain one list of x,y vertices for every text instance')
+
+		# font size
+		if options.exist('textsize'):
+			textsize=options.getfieldvalue('textsize',12)
+			sizelist=[]
+			sizelist.extend(textsize if isinstance(textsize,list) else [textsize])
+		else:
+			sizelist=[12]
+		if len(sizelist)==1:
+			sizelist=npy.tile(sizelist,numtext)
+
+		# font color
+		if options.exist('textcolor'):
+			textcolor=options.getfieldvalue('textcolor','k')
+			colorlist=[]
+			colorlist.extend(textcolor if isinstance(textcolor,list) else [textcolor])
+		else:
+			colorlist=['k']
+		if len(colorlist)==1:
+			colorlist=npy.tile(colorlist,numtext)
+
+		# textweight
+		if options.exist('textweight'):
+			textweightvalues=options.getfieldvalue('textweight')
+			weightlist=[]
+			weightlist.extend(textweight if isinstance(textwieght,list) else [textweight])
+		else:
+			weightlist=['normal']
+		if len(weightlist)==1:
+			weightlist=npy.tile(weightlist,numtext)
+
+		# text rotation
+		if options.exist('textrotation'):
+			textrotation=options.getfieldvalue('textrotation',0)
+			rotationlist=[]
+			rotationlist.extend(textrotation if isinstance(textrotation,list) else [textrotation])
+		else:
+			rotationlist=[0]
+		if len(rotationlist)==1:
+				rotationlist=npy.tile(rotationlist,numtext)
+
+		options.changefieldvalue('text',textlist)
+		options.addfield('textx',textx)
+		options.addfield('texty',texty)
+		options.changefieldvalue('textsize',sizelist)
+		options.changefieldvalue('textcolor',colorlist)
+		options.changefieldvalue('textweight',weightlist)
+		options.changefieldvalue('textrotation',rotationlist)
+
+	#expdisp
+	expdispvaluesarray=[0,0]
+	expstylevaluesarray=[0,0]
+	expstylevalues=[0,0]
+	if options.exist('expstyle'):
+		expstylevalues=options.getfieldvalue('expstyle')
+	if options.exist('expdisp'):
+		expdispvalues=options.getfieldvalue('expdisp')
+		for i in npy.arange(len(expdispvalues)):
+			expdispvaluesarray.append(expdispvalues[i])
+			if len(expstylevalues)>i+1:
+				expstylevaluesarray.append(expstylevalues[i])
+			else:
+				expstylevaluesarray.append('-k')
+
+	options.changefieldvalue('expstyle',expstylevaluesarray)
+	options.changefieldvalue('expdisp',expdispvaluesarray)
+
+	#latlonnumbering
+	if options.exist('latlonclick'):
+		if 'on' in options.getfieldvalue('latlonclick','on'):
+			options.changefieldvalue('latlonclick',1)
+
+	#northarrow
+	if options.exist('northarrow'):
+		if 'on' in options.getfieldvalue('northarrow','on'):
+			#default values
+			Lx=max(md.mesh.x)-min(md.mesh.x)
+			Ly=max(md.mesh.y)-min(md.mesh.y)
+			options.changefieldvalue('northarrow',[min(md.mesh.x)+1./6.*Lx, min(md.mesh.y)+5./6.*Ly, 1./15.*Ly, 0.25, 1./250.*Ly])
+
+	#scale ruler
+	if options.exist('scaleruler'):
+		if 'on' in options.exist('scaleruler','on'):
+			Lx=max(md.mesh.x)-min(md.mesh.x)
+			Ly=max(md.mesh.y)-min(md.mesh.y)
+			options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**(ceil(log10(Lx)))/5, floor(Lx/100), 5])
+
+	#log scale
+	if options.exist('log'):
+		if options.exist('caxis'):
+			options.changefieldvalue('caxis',log(options.getfieldvalue('caxis'))/log(options.getfieldvalue('log')))
+		options.changefieldvalue('cutoff',log(options.getfieldvalue('cutoff',1.5))/log(options.getfieldvalue('log')))
+
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/cmaptools.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/cmaptools.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/cmaptools.py	(revision 18231)
@@ -0,0 +1,25 @@
+import numpy as npy
+
+try:
+	import matplotlib as mpl
+except ImportError:
+	print 'cannot import matplotlib, no plotting capabilities enabled'
+
+def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
+	'''
+	truncate a colormap within normalized limits [0,1]
+
+	cmap - a matplotlib colormap
+	minval - minimum value, normalized, of cmap to be returned.
+	maxval - maximum value, normalized, of cmap to be returned.
+	n - number of levels to use in constructing the new colormap
+
+	Example:
+		newcmap=truncate_colormap(oldcmap,minval=0.2,maxval=0.8,n=128)
+
+	'''
+
+	new_cmap = mpl.colors.LinearSegmentedColormap.from_list('trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name,
+		a=minval, b=maxval), cmap(npy.linspace(minval, maxval, n)))
+	
+	return new_cmap
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/color_scale.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/color_scale.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/color_scale.m	(revision 18231)
@@ -0,0 +1,74 @@
+function map = color_scale(n, theta, r, dir)
+%COLOR_SCALE Colormap with luminance and hue ramps and constant chroma.
+%   MAP = COLOR_SCALE(N, THETA, R, DIR) computes a colormap that works well 
+%   on color displays and also works well when printed on a grayscale 
+%   printer.
+%   
+%   The color map is computed using a simple path through L*a*b* space that
+%   approximates a uniform ramp in the L* direction, and a semicircular
+%   path in the a*-b* plane.
+%
+%   N is the number of colormap colors.  THETA is the angle (in degrees) in
+%   the a*-b* plane of the first color.  THETA is measured clockwise from
+%   the a* axis.  R is the radius of the semicircular path in the a*-b*
+%   plane.  DIR is either 'cw', for a clockwise traversal, or 'ccw', for a
+%   counterclockwise traversal.
+%
+%   All of the arguments are optional.  The default values are N = 256,
+%   THETA = 0, R = 50, and DIR = 'cw'.
+%
+%   COLOR_SCALE requires the Image Processing Toolbox version 4 or later.
+%
+%   Example
+%   -------
+%   Display a Radon transform image with colormaps produced by color_scale.
+%
+%       I = zeros(100,100);
+%       I(25:75, 25:75) = 1;
+%       theta = 0:180;
+%       [R,xp] = radon(I,theta);
+%       imshow(R,[],'InitialMag','fit')
+%       colormap(color_scale)
+%
+%       % Try it with different parameters.
+%       colormap(color_scale(256,0,88,'ccw'))
+%
+%   See also COLOR_SCALE_TOOL.
+
+%   Steve Eddins
+%   $Revision$  $Date$
+
+if nargin < 4
+    dir = 'cw';
+end
+
+if nargin < 3
+    r = 50;
+end
+
+if nargin < 2
+    theta = 0;
+end
+
+if nargin < 1
+    n = 256;
+end
+
+if strcmp(dir, 'cw')
+    angle_offset = -pi/2;
+else
+    angle_offset = pi/2;
+end
+
+theta = pi * theta / 180;
+theta_vec = linspace(theta, theta + angle_offset, n).';
+
+a = r*cos(theta_vec);
+b = r*sin(theta_vec);
+L = linspace(0, 100, n).';
+
+Lab = [L, a, b];
+
+cform = makecform('lab2srgb');
+
+map = applycform(Lab, cform);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/demmap.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/demmap.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/demmap.m	(revision 18231)
@@ -0,0 +1,79 @@
+function cmap = demmap(ncolors,minZ,maxZ,varargin);
+%DEMMAP - concatenate sea and land color depending on zmin and zmax
+%
+%   Usage:
+%      cmap = demmap(n,zmin,zmax,varargin)
+%
+%   Example:
+%      cmap = demmap(50,-300,1200);
+%      cmap = demmap(50,-300,1200,'dem');
+%      cmap = demmap(50,-300,1200,'ibcao');
+
+%Input checks
+if nargin<3,
+	help landseacolor
+	error('3 or 4 arguments necessary');
+elseif nargin>4,
+	help landseacolor
+	error('3 or 4 arguments necessary');
+end
+
+if nargin==4,
+	colorscheme = varargin{1};
+	if ~ischar(colorscheme), error('color scheme should be a string'); end
+else
+	colorscheme = 'dem';
+end
+
+% determine appropriate number of sea and land colors
+if minZ == maxZ;
+	maxZ = minZ+1;
+end
+
+cmn = minZ;
+cmx = maxZ;
+
+% determine appropriate number of sea and land colors
+if minZ >= 0
+	nsea = 0;
+	nland = ncolors;
+elseif maxZ <= 0
+	nland = 0;
+	nsea = ncolors;
+else
+	% find optimal ratio of land to sea colors
+	maxminratio = maxZ/abs(minZ);
+	n1 = floor(ncolors/2);
+	n2 = ceil(ncolors/2);
+	if maxminratio>1
+		sea = (1:n1)';
+		land = (ncolors-1:-1:n2)';
+	else
+		land = (1:n1)';
+		sea = (ncolors-1:-1:n2)';
+	end
+	ratio = land./sea;
+	errors = abs(ratio - maxminratio) / maxminratio;
+	indx = find(errors == min(min(errors)));
+	nsea = sea(indx);
+	nland = land(indx);
+
+	% determine color limits
+	seaint = abs(minZ)/nsea;
+	landint = maxZ/nland;
+	if seaint >= landint
+		interval = seaint;
+	else
+		interval = landint;
+	end
+	cmn = -nsea*interval*(1 + 1e-9);      % zero values treated as land
+	cmx = nland*interval;
+end
+
+clim = [cmn cmx];
+
+if strcmpi(colorscheme,'dem'),
+	cmap = [seacolor(nsea);landcolor(nland).^1.3];
+elseif strcmpi(colorscheme,'ibcao');
+	cmap = ibcao(nsea,nland);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/getcolormap.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/getcolormap.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/getcolormap.m	(revision 18231)
@@ -0,0 +1,64 @@
+function map = getcolormap(options)
+%GETCOLORMAP - get colormap from options
+%
+%   Usage:
+%      map = getcolormap(options)
+
+%default is jet
+if ~exist(options,'colormap'),
+	map = jet;
+	return
+end
+
+map = getfieldvalue(options,'colormap');
+if isnumeric(map);
+	%user provided a full colormap
+	return;
+end
+
+%OK this is an in-house colormap
+if ~ischar(map), error('colormap format not supported'); end
+
+if strcmpi(map,'Ala'),
+	map = jet(256);
+	map = map(128:end,:);
+elseif strcmpi(map,'damage'),
+	v=ver;
+	if any(strcmp('Image Processing Toolbox',{v.Name})),
+		map = color_scale(256,0,70,'ccw');
+		map = flipud(map);
+		map(1:2,:)=[0.7476    1.0000    1.0000; 0.7476    1.0000    1.0000];
+	else
+		error('damage colormap requires Image Processing Toolbox, please try another colormap');
+	end
+elseif strcmpi(map,'redblue'),
+	map = hsv(128);
+	map = rgb2hsv(map);
+	map(:,2)       = max(min( abs(map(:,1)-0.5)/0.5 ,1),0);
+	map(1:64,1)   = 0.7;
+	map(65:end,1) = 1;
+	map = hsv2rgb(map);
+elseif strcmpi(map,'Rignot'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(128);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+elseif strcmpi(map,'Rignot2'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv;
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+	map=flipud(map);
+elseif strcmpi(map,'Seroussi'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv;
+	map = flipud(map);
+	map = map(1:floor(0.7*size(map,1)),:);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+else
+	eval(['map = ' map ';']);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/haxby.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/haxby.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/haxby.m	(revision 18231)
@@ -0,0 +1,36 @@
+function map = haxby(m)
+%HAXBY - Haxby color map
+%   HAXBY(M) returns an M-by-3 matrix containing a colormap with Haxby's
+%   colors, commonly used for displaying bathymetry data.
+%   HAXBY, by itself, is the same length as the current colormap.
+%
+%   Colormap is based on the colors used by W. F. Haxby's Gravity
+%   field of World's oceans, 1985, developed for geoid and gravity maps.
+%   The version used here is formed from a linear interpolation of
+%   the GMT color table used by MB-System by David W. Caress and Dale N. Chayes.
+%   <http://www.ldeo.columbia.edu/res/pi/MB-System>
+
+if nargin < 1, m = size(get(gcf,'colormap'),1); end
+
+ncolors=11;
+c=[...
+	37     57   175
+	40    127   251
+	50    190   255
+	106   235   255
+	138   236   174
+	205   255   162
+	240   236   121
+	255   189    87
+	255   161    68
+	255   186   133
+	255   255   255];
+
+pp=1:(m-1)/(ncolors-1):m;
+r=interp1(pp,c(:,1),1:m);
+g=interp1(pp,c(:,2),1:m);
+b=interp1(pp,c(:,3),1:m);
+map=[r' g' b']/255;
+
+%Fix bug of interp1 (M. Morlighem)
+map(find(map>1))=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/ibcao.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/ibcao.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/ibcao.m	(revision 18231)
@@ -0,0 +1,68 @@
+function map = ibcap(nsea,nland)
+%IBCAO - IBCAO color map
+%
+%   Usage:
+%      map = ibcap(nsea,nland)
+%
+%Downloaded from http://soliton.vm.bytemark.co.uk/pub/cpt-city/ibcao
+
+Jsea = [ ...
+0.18039 0.29020 0.57255
+0.18039 0.29020 0.57255
+0.05882 0.44314 0.65490
+0.05882 0.44314 0.65490
+0.02745 0.49804 0.73725
+0.02745 0.49804 0.73725
+0.01176 0.54510 0.78824
+0.01176 0.54510 0.78824
+0.00784 0.63529 0.83922
+0.00784 0.63529 0.83922
+0.06667 0.71765 0.86667
+0.06667 0.71765 0.86667
+0.17647 0.75294 1.00000
+0.17647 0.75294 1.00000
+0.23529 0.76471 0.85882
+0.23529 0.76471 0.85882
+0.24314 0.76471 0.83922
+0.24314 0.76471 0.83922
+0.25882 0.76078 0.81176
+0.25882 0.76078 0.81176
+0.27451 0.76078 0.76078
+0.27451 0.76078 0.76078
+0.41961 0.78431 0.74902
+0.41961 0.78431 0.74902
+0.60000 0.83137 0.74902
+0.60000 0.83137 0.74902
+];
+
+Jland = [ ...
+0.85098 0.84314 0.30588
+0.85098 0.84314 0.30588
+0.93333 0.89020 0.41961
+0.93333 0.89020 0.41961
+0.93725 0.80784 0.35686
+0.93725 0.80784 0.35686
+0.89804 0.74510 0.31765
+0.89804 0.74510 0.31765
+0.85098 0.63922 0.21961
+0.85098 0.63922 0.21961
+0.75686 0.55294 0.22353
+0.75686 0.55294 0.22353
+0.71765 0.50980 0.22353
+0.71765 0.50980 0.22353
+0.68627 0.48235 0.21961
+0.68627 0.48235 0.21961
+0.65490 0.45882 0.21569
+0.65490 0.45882 0.21569
+0.58824 0.39608 0.20392
+0.58824 0.39608 0.20392
+1.00000 1.00000 1.00000
+];
+
+lsea = length(Jsea);
+ysea = interp1(1:lsea,Jsea,linspace(1,lsea,nsea),'*linear');
+
+lland = length(Jland);
+yland = interp1(1:lland,Jland,linspace(1,lland,nland),'*linear');
+
+map=[ysea;yland];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/landcolor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/landcolor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/landcolor.m	(revision 18231)
@@ -0,0 +1,77 @@
+function y = landcolor(n)
+%LANDCOLOR Land colormap
+%
+%	Author: Francois Beauducel <beauducel@ipgp.fr>
+%	$Revision: 1.0.0 $   $Date: 2012/05/17 11:22:44 $
+
+J = [ ...
+0.095678 0.53427 0.21682 
+0.15785 0.5979 0.23274 
+0.21286 0.64673 0.2514 
+0.26411 0.68789 0.27268 
+0.32959 0.72416 0.31308 
+0.39794 0.75695 0.36038 
+0.46153 0.7871 0.40624 
+0.52108 0.81516 0.45135 
+0.57702 0.84152 0.49547 
+0.62973 0.86645 0.53891 
+0.67946 0.89016 0.58187 
+0.72647 0.91282 0.62427 
+0.77095 0.93455 0.66619 
+0.81306 0.95546 0.70772 
+0.85292 0.97563 0.7489 
+0.89066 0.99514 0.78976 
+0.88379 0.98595 0.77038 
+0.86389 0.96758 0.73236 
+0.84615 0.94972 0.69623 
+0.8303 0.93233 0.66186 
+0.81612 0.91536 0.6291 
+0.80341 0.8988 0.59784 
+0.79201 0.8826 0.56795 
+0.78191 0.86676 0.53946 
+0.7729 0.85123 0.51224 
+0.76479 0.83602 0.48615 
+0.75747 0.8211 0.46111 
+0.75084 0.80645 0.43704 
+0.74506 0.79206 0.41414 
+0.73981 0.77792 0.39211 
+0.73501 0.76401 0.37089 
+0.73068 0.75033 0.35052 
+0.72683 0.73685 0.33106 
+0.72042 0.72074 0.31228 
+0.71032 0.70085 0.29417 
+0.69761 0.67821 0.27694 
+0.68489 0.65558 0.26026 
+0.67235 0.63313 0.24418 
+0.65997 0.61082 0.22889 
+0.64775 0.58874 0.21406 
+0.63568 0.56689 0.19983 
+0.62376 0.54527 0.18622 
+0.61197 0.52391 0.17299 
+0.60033 0.50283 0.16046 
+0.58881 0.48203 0.14832 
+0.57742 0.46151 0.13667 
+0.56616 0.44133 0.12555 
+0.55502 0.4214 0.11472 
+0.54398 0.4019 0.10456 
+0.53306 0.38266 0.094633 
+0.52226 0.36382 0.085242 
+0.51155 0.3453 0.076179 
+0.50095 0.32714 0.067515 
+0.49045 0.30938 0.059259 
+0.48005 0.29193 0.051294 
+0.46973 0.27495 0.043796 
+0.45951 0.25823 0.0365 
+0.44938 0.24206 0.029715 
+0.43934 0.22609 0.023063 
+0.42938 0.21074 0.016949 
+0.41951 0.19556 0.010917 
+0.40971 0.18105 0.0054326 
+0.4 0.16667 0 
+];
+
+l = length(J);
+if nargin < 1
+	n = 256;
+end
+y = interp1(1:l,J,linspace(1,l,n),'*linear');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/lbmap.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/lbmap.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/lbmap.m	(revision 18231)
@@ -0,0 +1,109 @@
+function map = lbmap(n,scheme)
+%LBMAP Returns specified Light-Bertlein colormap.
+%
+%   LBMAP(N,SCHEME) returns an Nx3 colormap. SCHEME can be one of the
+%   following strings:
+%
+%       'Blue'       Single-hue progression to purlish-blue (default)
+%       'BlueGray'   Diverging progression from blue to gray
+%       'BrownBlue'  Orange-white-purple diverging scheme
+%       'RedBlue'    Modified spectral scheme
+%
+%   If N is not specified, the size of the colormap is determined by the
+%   current figure. If no figure exists, MATLAB creates one.
+%
+%Example 1: 7-color single-hue blue (default)
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(7))
+%   colorbar
+%
+%Example 2: 11-color modified spectrum
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(11,'RedBlue'))
+%   colorbar
+%
+%   See also HSV, GRAY, HOT, BONE, COPPER, PINK, FLAG, COLORMAP, RGBPLOT.
+
+% Reference:
+% A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for
+% Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.
+% http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf
+
+% Copyright 2007-2010 The MathWorks, Inc.
+
+%defensive programming
+error(nargchk(0,2,nargin))
+error(nargoutchk(0,1,nargout))
+
+%defaults
+if nargin<2
+	scheme = 'Blue';
+end
+if nargin<1
+	n = size(get(gcf,'colormap'),1);
+end
+
+%valid schemes
+switch lower(scheme)
+	case 'blue'
+		baseMap = BlueMap;
+	case 'bluegray'
+		baseMap = BlueGrayMap;
+	case 'brownblue'
+		baseMap = BrownBlueMap;
+	case 'redblue'
+		baseMap = RedBlueMap;
+	otherwise
+		error(['Invalid scheme ' scheme])
+	end
+	idx1 = linspace(0,1,size(baseMap,1));
+	idx2 = linspace(0,1,n);
+	map = interp1(idx1,baseMap,idx2);
+
+function baseMap = BlueMap
+	baseMap = [243 246 248;
+	224 232 240;
+	171 209 236;
+	115 180 224;
+	35 157 213;
+	0 142 205;
+	0 122 192]/255;
+
+function baseMap = BlueGrayMap
+	%DivergingBlueGray
+	baseMap = [  0 170 227;
+	53 196 238;
+	133 212 234;
+	190 230 242;
+	217 224 230;
+	146 161 170;
+	109 122 129;
+	65  79  81]/255;
+
+function baseMap = BrownBlueMap
+	baseMap = [144 100  44;
+	187 120  54;
+	225 146  65;
+	248 184 139;
+	244 218 200;
+	241 244 245;
+	207 226 240;
+	160 190 225;
+	109 153 206;
+	70  99 174;
+	24  79 162]/255;
+
+function baseMap = RedBlueMap
+	baseMap = [175  53  71;
+	216  82  88;
+	239 133 122;
+	245 177 139;
+	249 216 168;
+	242 238 197;
+	216 236 241;
+	154 217 238;
+	68 199 239;
+	0 170 226;
+	0 116 188]/255;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/seacolor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/seacolor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/colormaps/seacolor.m	(revision 18231)
@@ -0,0 +1,57 @@
+function y = seacolor(n)
+%SEACOLOR Sea colormap adapted from NGDC ETOPO1
+%
+%	Author: Francois Beauducel <beauducel@ipgp.fr>
+
+J = [ ...
+    0.0392         0    0.4745
+    0.1020         0    0.5373
+    0.1020         0    0.5373
+    0.1490         0    0.5961
+    0.1490         0    0.5961
+    0.1059    0.0118    0.6510
+    0.1059    0.0118    0.6510
+    0.0627    0.0235    0.7059
+    0.0627    0.0235    0.7059
+    0.0196    0.0353    0.7569
+    0.0196    0.0353    0.7569
+         0    0.0549    0.7961
+         0    0.0549    0.7961
+         0    0.0863    0.8235
+         0    0.0863    0.8235
+         0    0.1176    0.8471
+         0    0.1176    0.8471
+         0    0.1529    0.8745
+         0    0.1529    0.8745
+    0.0471    0.2667    0.9059
+    0.0471    0.2667    0.9059
+    0.1020    0.4000    0.9412
+    0.1020    0.4000    0.9412
+    0.0745    0.4588    0.9569
+    0.0745    0.4588    0.9569
+    0.0549    0.5216    0.9765
+    0.0549    0.5216    0.9765
+    0.0824    0.6196    0.9882
+    0.0824    0.6196    0.9882
+    0.1176    0.6980    1.0000
+    0.1176    0.6980    1.0000
+    0.1686    0.7294    1.0000
+    0.1686    0.7294    1.0000
+    0.2157    0.7569    1.0000
+    0.2157    0.7569    1.0000
+    0.2549    0.7843    1.0000
+    0.2549    0.7843    1.0000
+    0.3098    0.8235    1.0000
+    0.3098    0.8235    1.0000
+    0.3686    0.8745    1.0000
+    0.3686    0.8745    1.0000
+    0.5412    0.8902    1.0000
+    0.5412    0.8902    1.0000
+    0.7373    0.9020    1.0000
+];
+
+l = length(J);
+if nargin < 1
+	n = 256;
+end
+y = interp1(1:l,J,linspace(1,l,n),'*linear');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/curvedarrow.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/curvedarrow.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/curvedarrow.m	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/m/plot/googlemaps.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/googlemaps.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/googlemaps.m	(revision 18231)
@@ -0,0 +1,226 @@
+function md = googlemaps(md,ullat,ullon,lrlat,lrlon,varargin)
+%GOOGLEMAPS - Extract image from Google maps for given region
+%
+%   Usage:
+%       md = googlemaps(md)
+%       md = googlemaps(md,ullat,ullon,lrlat,lrlon)
+%       md = googlemaps(md,ullat,ullon,lrlat,lrlon,options)
+%
+%   - ullat,ullon: Upper Left corner latitude and longitude
+%   - lrlat,lrlon: Lower Right corner latitude and longitude
+%
+%   Available options:
+%      - zoom: zoom level, between 1 and 21 (default dynamically calculated)
+
+%Parse inputs
+if nargin<=5,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+if nargin==1,
+	%Get xlim and ylim (used to extract Google maps image)
+	xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+	ylim=getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+
+	%Image corners in lat/long
+	ullat = max(latlist); ullon = min(lonlist);
+	lrlat = min(latlist); lrlon = max(lonlist);
+elseif nargin>1 & nargin<5,
+	help googlemaps
+	error('Wrong usage');
+end
+
+%Get region specific projection parameters
+EPSGgoogle = 'EPSG:3785';   % Mercator       http://www.spatialreference.org/ref/epsg/3785/
+if strcmpi(md.mesh.hemisphere,'n'),
+	EPSGlocal = 'EPSG:3413'; % UPS Greenland  http://www.spatialreference.org/ref/epsg/3413/
+elseif strcmpi(md.mesh.hemisphere,'s'),
+	EPSGlocal = 'EPSG:3031'; % UPS Antarctica http://www.spatialreference.org/ref/epsg/3031/
+else
+	error('field hemisphere should either be ''n'' or ''s''');
+end
+
+%Find optimal zoom
+if exist(options,'zoom'),
+	zoom = getfieldvalue(options,'zoom');
+else
+	zoom = optimalzoom(ullat,ullon,lrlat,lrlon);
+	display(['googlemaps info: default zoom level ' num2str(zoom)]);
+end
+scale   = 1;
+maxsize = 640;
+bottom  = 50;
+
+%convert all these coordinates to pixels
+[ulx, uly]= latlontopixels(ullat, ullon, zoom);
+[lrx, lry]= latlontopixels(lrlat, lrlon, zoom);
+
+%calculate total pixel dimensions of final image
+dx = lrx - ulx;
+dy = uly - lry;
+
+%calculate rows and columns
+cols = ceil(dx/maxsize);
+rows = ceil(dy/(maxsize-bottom));
+
+%calculate pixel dimensions of each small image
+width   = ceil(dx/cols);
+height  = ceil(dy/rows);
+heightplus = height + bottom;
+
+%Initialize final image
+final = zeros(floor(dy),floor(dx),3);%RGB image
+for x=0:cols-1,
+	for y=0:rows-1,
+		dxn = width  * (0.5 + x);
+		dyn = height * (0.5 + y);
+		[latn, lonn] = pixelstolatlon(ulx + dxn, uly - dyn - bottom/2, zoom);
+		position = [num2str(latn) ',' num2str(lonn)];
+		disp(['Google Earth tile: ' num2str(x) '/' num2str(cols-1) ' ' num2str(y) '/' num2str(rows-1) ' (center: ' position ')']);
+		%Google maps API: http://developers.google.com/maps/documentation/staticmaps/
+		params = [...
+			'center=' position ...
+			'&zoom=' num2str(zoom)...
+			'&size=' num2str(width) 'x' num2str(heightplus)...
+			'&maptype=satellite'...
+			'&sensor=false'...
+			'&scale=' num2str(scale)];
+		url = ['http://maps.google.com/maps/api/staticmap?' params];
+		[X, map]=imread(url,'png');
+		X=ind2rgb(X,map);
+		indx1 = floor(x*width)+1;
+		indx2 = min(floor(dx),floor(x*width)+size(X,2));
+		indy1 = floor(y*height)+1;
+		indy2 = min(floor(dy),floor(y*height)+size(X,1));
+		final(indy1:indy2,indx1:indx2,:)=X(1:indy2-indy1+1,1:indx2-indx1+1,:);
+	end
+end
+
+%Write image
+imwrite(final,'temp.png','png')
+[ulmx ulmy]=ll2mercator(ullat,ullon);
+[lrmx lrmy]=ll2mercator(lrlat,lrlon);
+
+%Create Geotiff for Mercator projection 
+[status,result] = system(['gdal_translate -of Gtiff -co "tfw=yes"  -a_ullr '...
+	num2str(ulmx,'%15.8f') ' ' num2str(ulmy,'%15.8f') ' ' num2str(lrmx,'%15.8f') ' ' num2str(lrmy,'%15.8f')...
+	' -a_srs "' EPSGgoogle '" "temp.png" "temp.tiff"']);
+delete('temp.png');
+
+%If not gdal, exit
+if status~=0,
+	disp('googlemaps info: gdal not found or not working properly, the Google image will not be transformed');
+	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
+	[LAT LON]=pixelstolatlon(gX,gY, zoom);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[X Y]=ll2xy(LAT,LON,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+	md.radaroverlay.pwr=final;
+	md.radaroverlay.x=X;
+	md.radaroverlay.y=Y;
+	return
+end
+
+%reproject from mercator (EPSG:3785) to UPS Ant (EPSG:3031)
+[status,result] = system(['gdalwarp  -s_srs ' EPSGgoogle ' -t_srs ' EPSGlocal ' temp.tiff temp2.tiff']);
+delete('temp.tiff','temp.tfw');
+
+%If previous command failed, exit
+if ~isempty(strfind(result,'ERROR')),
+	disp(' ');disp('googlemaps info: gdal not working properly (missing proj.4 library?), Google image will not be transformed');
+	disp(result);
+	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
+	[LAT LON]=pixelstolatlon(gX,gY, zoom);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[X Y]=ll2xy(LAT,LON,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+	md.radaroverlay.pwr=final;
+	md.radaroverlay.x=X;
+	md.radaroverlay.y=Y;
+	return
+end
+
+%Put everything in model
+[status output]=system('gdalinfo temp2.tiff | grep "Upper Left"');
+ul = sscanf(output,'Upper Left  (%f, %f)');
+[status output]=system('gdalinfo temp2.tiff | grep "Lower Right"');
+lr = sscanf(output,'Lower Right (%f, %f)');
+[status output]=system('gdalinfo temp2.tiff | grep "Size is"');
+si = sscanf(output,'Size is %i, %i');
+x_m=linspace(ul(1),lr(1),si(1));
+y_m=linspace(ul(2),lr(2),si(2)); %We need to reverse y_m because the image is read upside down by matlab
+final=imread('temp2.tiff');
+delete('temp2.tiff');
+
+md.radaroverlay.pwr=final;
+md.radaroverlay.x=x_m;
+md.radaroverlay.y=y_m;
+
+end
+function [px py]=latlontopixels(lat, lon, zoom),
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+	ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+	[mx,my]=ll2mercator(lat,lon);
+	res = INITIAL_RESOLUTION / (2^zoom);
+	px = (mx + ORIGIN_SHIFT) / res;
+	py = (my + ORIGIN_SHIFT) / res;
+end
+
+function [lat lon]=pixelstolatlon(px, py, zoom),
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+	ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+	res = INITIAL_RESOLUTION / (2^zoom);
+	mx = px * res - ORIGIN_SHIFT;
+	my = py * res - ORIGIN_SHIFT;
+	[lat lon] = mercator2ll(mx,my);
+end
+function  zoom = optimalzoom(ullat,ullon,lrlat,lrlon)
+
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+
+	optimalsize = 1000; %Number of pixels in final image
+
+	[ulmx ulmy]=ll2mercator(ullat,ullon);
+	[lrmx lrmy]=ll2mercator(lrlat,lrlon);
+	distance = sqrt((lrmx-ulmx)^2 + (lrmy-ulmy)^2);
+
+	zoom1 = floor(log(INITIAL_RESOLUTION*optimalsize/(lrmx-ulmx))/log(2));
+	zoom2 = floor(log(INITIAL_RESOLUTION*optimalsize/(ulmy-lrmy))/log(2));
+
+	zoom=max(zoom1,zoom2);
+
+	zoom = min(max(1,zoom),21);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgridded.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgridded.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgridded.m	(revision 18231)
@@ -0,0 +1,145 @@
+function kmlgridded(md,data,varargin)
+
+%process options
+options=pairoptions(varargin{:});
+
+%process options
+options=changefieldvalue(options,'coord','latlon');
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+%Get xlim and ylim (used to extract radar image)
+xlim=[min(x) max(x)];
+ylim=[min(y) max(y)];
+post=getfieldvalue(options,'posting',diff(xlim)/1000);
+if(diff(xlim)/post>10000),
+	error(['posting too large']);
+end
+
+%Interpolating data on grid
+[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+if size(data_grid,1)<3 | size(data_grid,2)<3,
+	error('data_grid size too small, check posting and units');
+end
+pos=find(isinf(data_grid));
+if ~isempty(pos),
+	disp('Warning: removing Infs from vector (probably log(0)?)');
+	data_grid(pos)=NaN;
+end
+
+%Process data_grid: add white in NaN and correct caxis accordingly
+data_nan=find(isnan(data_grid));
+data_min=min(data_grid(:));
+data_max=max(data_grid(:));
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+end
+
+%Get colormap
+colorm = getcolormap(options);
+len    = size(colorm,1);
+ind = ceil((len-1)*(data_grid-data_min)/(data_max - data_min + eps) +1);
+ind(find(ind>len))=len;
+ind(find(ind<1)  )=1;
+ind(find(isnan(ind)))=1;
+image_rgb=zeros(size(data_grid,1),size(data_grid,2),3);
+r=colorm(:,1); image_rgb(:,:,1)=r(ind); clear r;
+g=colorm(:,2); image_rgb(:,:,2)=g(ind); clear g;
+b=colorm(:,3); image_rgb(:,:,3)=b(ind); clear b;
+
+%Deal with alpha
+alpha=getfieldvalue(options,'alpha',.8);
+alphaMatrix = alpha*ones(size(data_grid));
+alphaMatrix(data_nan) = 0;
+
+%write kml
+kmlfilename=getfieldvalue(options,'kmlfilename','tempfile.kml');
+kmlroot=getfieldvalue(options,'kmlroot','./');
+kmlimagename=getfieldvalue(options,'kmlimagename','tempimage');
+kmlresolution=getfieldvalue(options,'kmlresolution',1);
+kmlfolder=getfieldvalue(options,'kmlfolder','Ground Overlay');
+kmlfolderdescription=getfieldvalue(options,'kmlfolderdescription','');
+kmlgroundoverlayname=getfieldvalue(options,'kmlgroundoverlayname','ground overlay');
+kmlgroundoverlaydescription=getfieldvalue(options,'kmlgroundoverlaydescription','description');
+
+%write png
+imwrite(image_rgb,[kmlimagename '.png'],'png','alpha',alphaMatrix);
+clear image_rgb alphaMatrix
+
+%prepare colorbar
+iscolorbar=0;
+if strcmpi(getfieldvalue(options,'colorbar','on'),'on'),
+	X = linspace(0,1,len)';
+	Xlab = round(linspace(data_min,data_max,len+1));
+	html = ['<TABLE border=' num2str(1) ' bgcolor=#FFFFFF>',10];
+
+	for k=len:-1:1
+		f = (Xlab(k)-data_min)/(data_max-data_min);
+		if f<0, f=0; end
+		if f>1, f=1; end
+		polyColor(1,1) = interp1(X,colorm(:,1),f);
+		polyColor(1,2) = interp1(X,colorm(:,2),f);
+		polyColor(1,3) = interp1(X,colorm(:,3),f);
+		polyColorStr(1:2) = dec2hex(round(polyColor(1)*255),2);
+		polyColorStr(3:4) = dec2hex(round(polyColor(2)*255),2);
+		polyColorStr(5:6) = dec2hex(round(polyColor(3)*255),2);
+		html = [html,'<TR><TD width="15px" bgcolor=#',polyColorStr, '>&nbsp;</TD>','<TD bgcolor=#FFFFFF>'];
+		if k==1
+			html=[html,'&lt;= ',num2str(Xlab(k),'%g')];
+		elseif k==len
+			html=[html,'&gt;= ',num2str(Xlab(k),'%g')];
+		else
+			html=[html,num2str(Xlab(k),'%g'),' to ',num2str(Xlab(k+1),'%g'),'</TD>'];
+		end
+		html = [html,'</TR>',10];
+	end
+	html = [html,'</TABLE>'];
+	iscolorbar = 1;
+end
+
+%now write kml file
+fid=fopen([kmlroot '/' kmlfilename],'w');
+fprintf(fid,'%s\n','<?xml version="1.0" encoding="UTF-8"?>');
+fprintf(fid,'%s\n','<kml xmlns="http://earth.google.com/kml/2.1">');
+fprintf(fid,'%s\n','<Document>');
+fprintf(fid,'%s%s%s\n','<name>',kmlfilename,'</name>');
+if iscolorbar,
+	fprintf(fid,'<Placemark id="colorbar">\n');
+	fprintf(fid,'%s%s%s\n','<name>','click the icon to see the colorbar','</name>');
+	fprintf(fid,'%s%s%s\n','<description>','Ground overlay colorbar','</description>');
+	fprintf(fid,'<visibility>1</visibility>\n');
+	fprintf(fid,['<description>',10,'<![CDATA[' html ']]>',10,'</description>',10,'\n']);
+	fprintf(fid,['<Style><IconStyle><scale>1</scale><Icon><href>http://maps.google.com/mapfiles/kml/shapes/donut.png</href></Icon></IconStyle><ListStyle></ListStyle></Style><Point id="poly_colorbar">\n']);
+	fprintf(fid,'<altitudeMode>clampToGround</altitudeMode>\n');
+	fprintf(fid,'<extrude>1</extrude>\n');
+	fprintf(fid,'<tessellate>1</tessellate>\n');
+	fprintf(fid,'%s%g,%g%s\n','<coordinates>',max(x),mean(y),'</coordinates>');
+	fprintf(fid,'</Point>\n');
+	fprintf(fid,'</Placemark>\n');
+end
+fprintf(fid,'%s\n','<GroundOverlay id="groundoverlay">');
+fprintf(fid,'%s%s%s\n','<name>',kmlgroundoverlayname,'</name>');
+fprintf(fid,'%s\n','<description>',kmlgroundoverlaydescription,'</description>');
+fprintf(fid,'%s%s.%s%s\n','<Icon>',kmlimagename,'png','</Icon>');
+fprintf(fid,'%s\n','<LatLonBox>');
+fprintf(fid,'%s%f%s\n','<north>',max(y_m),'</north>');
+fprintf(fid,'%s%f%s\n','<south>',min(y_m),'</south>');
+fprintf(fid,'%s%f%s\n','<east>',max(x_m),'</east>');
+fprintf(fid,'%s%f%s\n','<west>',min(x_m),'</west>');
+fprintf(fid,'%s\n','<rotation>0</rotation>');
+fprintf(fid,'%s\n','</LatLonBox>');
+fprintf(fid,'%s\n','</GroundOverlay>');
+fprintf(fid,'%s\n','</Document>');
+fprintf(fid,'%s\n','</kml>');
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgroundoverlay.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgroundoverlay.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/kmlgroundoverlay.m	(revision 18231)
@@ -0,0 +1,62 @@
+function kmlgroundoverlay(md,options)
+%KMLGROUNDOVERLAY: create ground overlay image in kml format
+%
+%
+%    options: 
+%         kmlfilename
+%         imagename
+%
+%    Usage: 
+%         kmlgroundoverlay(md,'kmlfilename','temp.kml','imagename','greenland.jpeg');
+%
+
+%first figure out if lat and long were computed!
+if (isempty(md.mesh.lat) | isempty(md.mesh.long)),
+	error('kmlgroundoverlay error message: project x,y onto lat,long fields of model!');
+end
+
+%process kml options
+kmlfilename=getfieldvalue(options,'kmlfilename','tempfile.kml');
+kmlroot=getfieldvalue(options,'kmlroot','./');
+kmlimagename=getfieldvalue(options,'kmlimagename','tempimage');
+kmlimagetype=getfieldvalue(options,'kmlimagetype','png');
+kmlresolution=getfieldvalue(options,'kmlresolution',1);
+kmlfolder=getfieldvalue(options,'kmlfolder','Ground Overlay');
+kmlfolderdescription=getfieldvalue(options,'kmlfolderdescription','');
+kmlgroundoverlayname=getfieldvalue(options,'kmlgroundoverlayname','');
+kmlgroundoverlaydescription=getfieldvalue(options,'kmlgroundoverlaydescription','');
+
+%figure out  min and max for lat and long of this image:
+west=min(md.mesh.long);
+east=max(md.mesh.long);
+south=min(md.mesh.lat);
+north=max(md.mesh.lat);
+
+%print image at high resolution
+export_fig([kmlroot '/' kmlimagename],'-transparent','-zbuffer'); %zbuffer to avoid "Bad data returned by HARDCOPY. Not calling IMWRITE"
+%printmodel([kmlroot '/' kmlimagename],kmlimagetype,'trim','on','resolution',kmlresolution,'margin','off','frame','off');
+
+%now write kml file
+fid=fopen([kmlroot '/' kmlfilename],'w');
+
+fprintf(fid,'%s\n','<?xml version="1.0" encoding="UTF-8"?>');
+fprintf(fid,'%s\n','<kml xmlns="http://www.opengis.net/kml/2.2">');
+fprintf(fid,'%s\n','<Folder>');
+fprintf(fid,'%s%s%s\n','<name>',kmlfolder,'</name>');
+fprintf(fid,'%s%s%s\n','<description>',kmlfolderdescription,'</description>');
+fprintf(fid,'%s\n','<GroundOverlay>');
+fprintf(fid,'%s%s%s\n','<name>',kmlgroundoverlayname,'</name>');
+fprintf(fid,'%s\n','<description>',kmlgroundoverlaydescription,'</description>');
+fprintf(fid,'%s%s.%s%s\n','<Icon>',kmlimagename,kmlimagetype,'</Icon>');
+fprintf(fid,'%s\n','<LatLonBox>');
+fprintf(fid,'%s%f%s\n','<north>',north,'</north>');
+fprintf(fid,'%s%f%s\n','<south>',south,'</south>');
+fprintf(fid,'%s%f%s\n','<east>',east,'</east>');
+fprintf(fid,'%s%f%s\n','<west>',west,'</west>');
+fprintf(fid,'%s\n','<rotation>0</rotation>');
+fprintf(fid,'%s\n','</LatLonBox>');
+fprintf(fid,'%s\n','</GroundOverlay>');
+fprintf(fid,'%s\n','</Folder>');
+fprintf(fid,'%s\n','</kml>');
+
+fclose(fid);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/latlonoverlay.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/latlonoverlay.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/latlonoverlay.m	(revision 18231)
@@ -0,0 +1,148 @@
+function latlonoverlay(md,options)
+%LATLONOVERLAY - overlay latitude and longitude lines on current figure
+%
+%   latstep,lonstep, in latitude and longitude degreees, between two latitudinal, longitudinal profiles.
+%   color: [1 1 1] for example
+%   resolution: profile resolution ( in lat,lon degrees) 
+%   gap: gap (in meters) to plug lat,lon degree numbers;
+%
+%   Usage:
+%      latlonoverlay(options)
+
+%get options
+latlon=getfieldvalue(options,'latlon');
+numbering=getfieldvalue(options,'latlonnumbering','off');
+latlonclick=getfieldvalue(options,'latlonclick',0);
+fontsize=getfieldvalue(options,'fontsize',16);
+
+%recover arguments (set default parameters if needed)
+%1: latlon
+if ~iscell(latlon),
+	if ischar(latlon) & strcmpi(latlon,'on'),
+		%defaults
+		latstep=3; lonstep=3;
+		resolution=0.1;
+		color=[1 0 1];
+	else return; end
+else
+	if length(latlon)<2
+		error('latlonoverlay error message: at least 2 arguments are required, or use ''on'' option.');
+	end
+	if length(latlon)>3, color=latlon{4};      else color=[1 1 1]; end
+	if length(latlon)>2, resolution=latlon{3}; else resolution=0.1;end
+	latstep=latlon{1};
+	lonstep=latlon{2};
+end
+
+%2: numbering
+if ~iscell(numbering) & isnan(numbering),
+	numbering=false;
+else
+	if ~iscell(numbering),
+		if strcmpi(char(numbering),'on'),
+			%defaults
+			latgap=2; longap=2;
+			colornumber=color;
+			latangle=0; lonangle=0;
+			numbering=true;
+		else
+			numbering=false;
+		end
+	else
+		latgap=numbering{1}; longap=numbering{2};
+		colornumber=numbering{3};
+		latangle=numbering{4}; lonangle=numbering{5};
+		numbering=true;
+	end
+end
+
+%what are the x and y limits
+xlimits=getfieldvalue(options,'xlim',xlim);
+ylimits=getfieldvalue(options,'ylim',ylim);
+
+%lat
+for lat=-90:latstep:90
+	longitudes=0:resolution:360;
+	latitudes =lat*ones(size(longitudes));
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if lat<0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if lat>0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else error('field hemisphere should either be ''n'' or ''s'''); end
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering
+		ind=length(x)-2*latgap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+latangle,360);
+			if lat<0, label=[num2str(abs(lat)) '^{\circ} S'];
+			else      label=[num2str(abs(lat)) '^{\circ} N']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-latgap),y(1:ind-latgap),'Color',color);hold on;
+			line(x(ind+latgap:end),y(ind+latgap:end),'Color',color);
+			set(gcf,'InvertHardcopy','off');
+		end
+
+	end
+end
+
+%lon
+for lon=-180:lonstep:180
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		latitudes =0:resolution:90;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		latitudes =-90:resolution:0;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s'''); 
+	end
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering,
+		ind=length(x)-2*longap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+lonangle,360);
+			if lon<0, label=[num2str(abs(lon)) '^{\circ} W'];
+			else      label=[num2str(abs(lon)) '^{\circ} E']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-longap),y(1:ind-longap),'Color',color);hold on;
+			line(x(ind+longap:end),y(ind+longap:end),'Color',color);
+		end
+
+	end
+end
+
+%Back to original limits
+xlim(xlimits);
+ylim(ylimits);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/manualcb.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/manualcb.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/manualcb.m	(revision 18231)
@@ -0,0 +1,128 @@
+function manualcb(zmin,zmax,cmap,varargin)
+%MANUALCB - custom colorbar
+%
+%   Usage:
+%      manualcb(min,max,colormap,options)
+%
+%   Available options:
+%      - 'fontsize'    : default is 12
+%      - 'smallbars'   : bars next to each tick (default is false)
+%      - 'position'    : colorbar position in normalized units
+%      - 'orientation' : 'vertical' (default) or 'horizontal'
+%      - 'title'       : colorbar title
+%      - 'tick'        : specified values of tick labels
+%      - 'ticksep'     : spacing between ticks
+%      - 'inverttickposition' : put ticks on the left hand side for vertical cb
+
+%check inputs
+if nargin<3,
+	help manualcb
+	error('bad usage');
+end
+if zmin>zmax,
+	error('zmin should be smaller than zmax');
+end
+
+%Get plot axes
+mainaxes = gca;
+
+%process options
+options = pairoptions(varargin{:});
+if exist(options,'tick') & exist(options,'ticksep'),
+	error('only one of tick or ticksep can be specified');
+end
+fontsize  = getfieldvalue(options,'fontsize',12);
+smallbars = getfieldvalue(options,'smallbars',false);
+
+%Colorbar position
+if ~exist(options,'position'),
+	position = plotboxpos;
+	xstart   = position(1)+position(3)+0.01;
+	ystart   = position(2);
+	width    = .02;
+	height   = position(4);
+else
+	position = getfieldvalue(options,'position');
+	xstart = position(1);
+	ystart = position(2);
+	width  = position(3);
+	height = position(4);
+end
+axes('Units','normalized','Position',[xstart ystart width height],'XTickLabel','','YTickLabel','','Visible','on');
+xlim([0 1]);
+ylim([0 1]);
+
+%Prepare ticks
+if ~exist(options,'log'),
+	deltaz = getfieldvalue(options,'ticksep',dtick(zmax-zmin));
+	ztick  = getfieldvalue(options,'tick',(deltaz*ceil(zmin/deltaz)):deltaz:zmax);
+	if (any(ztick>zmax) | any(ztick<zmin)),
+		error('one or more specified tick values falls outside of [zmin,zmax]');
+	end
+	ytick  = (ztick-zmin)/(zmax-zmin);
+else
+	ztick = getfieldvalue(options,'tick',round(logspace(log(zmin)/log(10),log(zmax)/log(10),8)));
+	ytick = linspace(0,1,numel(ztick));
+end
+
+%Display colorbar
+hold on
+if strcmpi(getfieldvalue(options,'orientation','vertical'),'vertical'),
+	image_rgb = ind2rgb(repmat(uint16(1:length(cmap))',1,2),cmap);
+else
+	image_rgb = ind2rgb(repmat(uint16(1:length(cmap))',1,2)',cmap);
+end
+imagesc([0 1],[0 1],image_rgb);
+patch([0,0,1,1],[0,1,1,0],'k','FaceColor','none','Clipping','off')
+
+%Add ticks
+if strcmpi(getfieldvalue(options,'orientation','vertical'),'vertical'),
+	%Use FOR LOOP otherwise numbers are not correcly centered
+	if getfieldvalue(options,'inverttickposition',0)==1,
+		for i=1:length(ytick), text(-0.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','right','VerticalAlignment','middle','FontSize',fontsize); end
+	else
+		for i=1:length(ytick), text(1.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',fontsize); end
+	end
+	if smallbars,
+		for i=1:numel(ztick)
+			patch([0.8 1.0],[ytick(i) ytick(i)],'k')
+			patch([0.0 0.2],[ytick(i) ytick(i)],'k')
+		end
+	end
+else
+	%Use FOR LOOP otherwise numbers are not correcly centered
+	for i=1:length(ytick), text(ytick(i),-0.5,num2str(ztick(i)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',fontsize); end
+	if smallbars,
+		for i=1:numel(ztick)
+			patch([ytick(i) ytick(i)],[0.8 1.0],[ytick(i) ytick(i)],'k')
+			patch([ytick(i) ytick(i)],[0.0 0.2],[ytick(i) ytick(i)],'k')
+		end
+	end
+end
+
+if exist(options,'title'),
+	title(getfieldvalue(options,'title'),'FontSize',fontsize);
+end
+if exist(options,'ylabel'),
+	if strcmpi(getfieldvalue(options,'orientation','vertical'),'horizontal'),
+		th=title(getfieldvalue(options,'title'),'FontSize',fontsize);
+		set(th,'Position',[ytick(end)+0.075,-0.3]);
+	else
+		ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize);
+	end
+end
+	
+%Back to original axes
+if getfieldvalue(options,'showregion',0)==0,
+	axes(mainaxes);
+end
+
+function delta = dtick(range)
+%Tick intervals
+m = 10^floor(log10(range));
+p = ceil(range/m);
+if p <= 1,     delta = .1*m;
+elseif p == 2, delta = .2*m;
+elseif p <= 5, delta = .5*m;
+else           delta = m;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/northarrow.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/northarrow.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/northarrow.m	(revision 18231)
@@ -0,0 +1,76 @@
+function northarrow(structure)
+%NORTHARROW - overlay an arrow pointing north on the current plot
+%
+%   Usage:
+%      northarrow(structure)
+
+%Go through structure and fill missing arguments
+if length(structure)<3
+	error('plotmodel error message: the position or the length of the North arrow is missing');
+elseif length(structure)==3
+	structure(4)=0.5; %default ratio headarrow/length
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==4
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==5
+	structure(6)=16; %default fontsize
+elseif length(structure)>6
+	error('plotmodel error message: to many input arguments for northarrow: [x0 y0 length [ratio width fontsize]]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengtharrow=structure(3);
+ratio=structure(4);
+width=structure(5);
+fontsize=structure(6);
+
+%Figure out angle to point towards north
+ang=atan2(y0,x0);
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0;
+y(1)=y0;
+
+x(2)=x(1)+lengtharrow*cos(ang);
+y(2)=y(1)+lengtharrow*sin(ang);
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],'Black');
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],'Black');
+
+%Text North
+xN=max([A(1) D(1) E(1) F(1) G(1)])+ratio/3*abs(lengtharrow);
+yN=mean([A(2) F(2) H(2)]);
+text(xN,yN,'North','FontSize',fontsize,'FontWeight','b');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_BC.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_BC.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_BC.m	(revision 18231)
@@ -0,0 +1,48 @@
+function plot_BC(md,options,width,i,data)
+
+%plot neuman
+plot_icefront(md,options,width,i,data)
+
+hold on
+
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot dirichlets
+dirichleton=getfieldvalue(options,'dirichlet','on');
+if strcmpi(dirichleton,'on'),
+	h1=plot3(...
+		x(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		'ro','MarkerSize',14,'MarkerFaceColor','r');
+	h2=plot3(...
+		x(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		'bo','MarkerSize',10,'MarkerFaceColor','b');
+	h3=plot3(...
+		x(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		'yo','MarkerSize',6 ,'MarkerFaceColor','y');
+end
+
+%update legend
+[legend_h,object_h,plot_h,text_strings]=legend();
+legend('off');
+if strcmpi(dirichleton,'on'),
+	text_strings{end+1}='vx Dirichlet';
+	text_strings{end+1}='vy Dirichlet';
+	if h3, text_strings{end+1}='vz Dirichlet'; end
+	plot_h(end+1)=h1;
+	plot_h(end+1)=h2;
+	if h3, plot_h(end+1)=h3; end
+end
+legend(plot_h,text_strings,'location','NorthEast')
+
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_basaldrag.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_basaldrag.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_basaldrag.m	(revision 18231)
@@ -0,0 +1,53 @@
+function plot_basaldrag(md,options,width,i,type)
+
+%PLOT_BASALDRAG - plot basal drag
+%
+%   Usage:
+%      plot_basaldrag(md,options,width,i,type);
+%
+%   See also: PLOTMODEL
+
+%check layer
+if dimension(md.mesh)==3,
+	if getfieldvalue(options,'layer',1)~=1;
+		disp('plot_basaldrag warning: basal drag is displayed in the lower layer')
+		changefieldvalue(options,'layer',1);
+	end
+end
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+if strcmpi(type,'basal_drag')
+	ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+elseif strcmpi(type,'basal_dragx')
+	ub=md.initialization.vx/md.constants.yts;
+elseif strcmpi(type,'basal_dragy')
+	ub=md.initialization.vy/md.constants.yts;
+end
+
+%compute basal drag
+drag=(max(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base),0)).^r.*(md.friction.coefficient).^2.*ub.^s/1000;
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,drag,options,width,i);
+	return;
+else
+
+	%process data and model
+	[x y z elements is2d isplanet]=processmesh(md,[],options);
+	[basal_drag datatype]=processdata(md,drag,options);
+
+	%plot basaldrag
+	subplot(width,width,i); 
+	plot_unit(x,y,z,elements,basal_drag,is2d,isplanet,datatype,options);
+
+	%apply options
+	options=addfielddefault(options,'title','Basal drag [kPa]');
+	options=addfielddefault(options,'view',2);
+	applyoptions(md,basal_drag,options);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_boundaries.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_boundaries.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_boundaries.m	(revision 18231)
@@ -0,0 +1,39 @@
+function plot_boundaries(md,options,width,i)
+%PLOT_BOUNDARIES - plot mesh boundaries
+%
+%   Usage:
+%      plot_boundaries(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+subplot(width,width,i); 
+
+%process data and model
+if getfieldvalue(options,'layer',0)
+	options=removefield(options,'layer',1);
+end
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');hold on;
+end
+
+%plot rifts if present: 
+if isstruct(md.rifts.riftstruct),
+	for i=1:size(md.rifts.riftstruct,1),
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'r.-');
+		end
+		text(x(segments(floor(size(segments,1)/4),1)),y(segments(floor(size(segments,1)/4),1)),['Rift #' num2str(i)]);
+		%point out the tips
+		plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'b*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'b*');
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh boundaries');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.m	(revision 18231)
@@ -0,0 +1,251 @@
+function plot_contour(md,datain,options)
+%PLOT_CONTOUR - plot contours of a given field
+%
+%   Usage:
+%      plot_contour(md,data,options);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+options=removefield(options,'log',0);
+[data datatype]=processdata(md,datain,options);
+if isempty(data), error('data provided is empty'); end
+
+%check is2d
+if ~is2d,
+	error('plot_contour error message: contour not supported for 3d meshes, project on a layer');
+end
+
+%first, process data: must be on nodes
+if datatype==1,
+	%elements -> take average
+	data=averaging(md,data,0);
+elseif datatype==2,
+	%nodes -> do nothing
+elseif datatype==3,
+	%quiver -> take norm
+	data=sqrt(sum(datain.*datain,2));
+else
+	error('datatype not supported yet');
+end
+
+%prepare colors
+if exist(options,'contouronly')
+	%remove the previous plots
+	cla
+end
+color=getfieldvalue(options,'contourcolor','y');
+linewidth=getfieldvalue(options,'linewidth',1);
+
+%get contours levels
+contourlevels=getfieldvalue(options,'contourlevels');
+if isnumeric(contourlevels),
+	levels=round_ice(linspace(max(data),min(data),contourlevels),2);
+else
+	levels=[];
+	for i=1:length(contourlevels)
+		levels(end+1)=contourlevels{i};
+	end
+	levels=sort(unique(levels),'descend');
+end
+numlevels=length(levels);
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=data(Seg1);
+Data2=data(Seg2);
+Data3=data(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+for i=1:numlevels
+
+	level=levels(i);
+
+	%find the segments that contain this value
+	pos1=(Range1(:,1)<level & Range1(:,2)>level);
+	pos2=(Range2(:,1)<level & Range2(:,2)>level);
+	pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+	%get elements
+	poselem12=(pos1 & pos2);
+	poselem13=(pos1 & pos3);
+	poselem23=(pos2 & pos3);
+	poselem=find(poselem12 | poselem13 | poselem23);
+	numelems=length(poselem);
+
+	%if no element has been flagged, skip to the next level
+	if numelems==0,
+		continue,
+	end
+
+	%go through the elements and build the coordinates for each segment (1 by element)
+	x1=zeros(numelems,1);
+	x2=zeros(numelems,1);
+	y1=zeros(numelems,1);
+	y2=zeros(numelems,1);
+	edge_l=zeros(numelems,2);
+
+	for j=1:numelems,
+
+		weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+		weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+		weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+		if poselem12(poselem(j));
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg2_num(poselem(j));
+
+		elseif poselem13(poselem(j)),
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+
+		elseif poselem23(poselem(j)),
+
+			x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg2_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+		else
+			%it shoud not go here
+		end
+	end
+
+	%now that we have the segments, we must try to connect them...
+
+	%loop over the subcontours
+	while ~isempty(edge_l),
+
+		%take the right edge of the second segment and connect it to the next segments if any
+		e1=edge_l(1,1);   e2=edge_l(1,2);
+		xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+		%erase the lines corresponding to this edge
+		edge_l(1,:)=[];
+		x1(1)=[]; x2(1)=[];
+		y1(1)=[]; y2(1)=[];
+
+		[ro1,co1]=find(edge_l==e1);
+
+		while ~isempty(ro1)
+
+			if co1==1,
+				xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,2);
+
+			else
+				xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro1,:)=[];
+			x1(ro1)=[]; x2(ro1)=[];
+			y1(ro1)=[]; y2(ro1)=[];
+
+			%next connection
+			[ro1,co1]=find(edge_l==e1);
+		end
+
+		%same thing the other way (to the right)
+		[ro2,co2]=find(edge_l==e2);
+
+		while ~isempty(ro2)
+
+			if co2==1,
+				xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,2);
+			else
+				xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro2,:)=[];
+			x1(ro2)=[]; x2(ro2)=[];
+			y1(ro2)=[]; y2(ro2)=[];
+
+			%next connection
+			[ro2,co2]=find(edge_l==e2);
+		end
+
+		%we now have one subcontour ready to be plotted
+		zc=level*ones(length(xc)+1,1);
+		if getfieldvalue(options,'contouronly',0),
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat','linewidth',linewidth)];
+			hold on      
+		else
+			dist = 5000;
+			if (max(xc)-min(xc)+max(yc)-min(yc))<dist, continue; end
+			h=patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth);
+			c = horzcat([level, xc'; length(xc), yc']);
+			%clabel(c,h,'FontSize',10,'labelspacing',20000,'color',color);
+			hold on
+		end
+
+		% Update the CS data structure as per "contours.m"
+		% so that clabel works
+		%c = horzcat(c,[level, xc'; length(xc), yc']);
+
+	end
+end
+
+%labels?
+if (~strcmpi(getfieldvalue(options,'contourticks','on'),'off') & ~isempty(c) & ~isempty(h))
+	if exist(options,'contouronly')
+		clabel(c,h);
+	else
+		%clabel(c,h,'color',color,'FontSize',10,'labelspacing',20000);
+		clabel(c,h,'FontSize',10,'labelspacing',20000);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_contour.py	(revision 18231)
@@ -0,0 +1,38 @@
+from averaging import averaging
+import matplotlib.pyplot as plt
+from processmesh import processmesh
+from processdata import processdata
+
+def plot_contour(md,datain,options,ax):
+	'''
+	plot contours of a given field (called within plotmodel)
+
+	Usage:
+		plot_contour(md,data,options)
+
+	See also: plotmodel
+	'''
+
+	x,y,z,elements,is2d,isplanet=processmesh(md,datain,options)
+	data,datatype=processdata(md,datain,options)
+
+	# process data: must be on nodes
+	if datatype==1: # element data
+		data=averaging(md,data,0)
+	elif datatype==2:
+		pass
+	elif datatype==3: # quiver (vector) data
+		data=npy.sqrt(datain**2)
+	else:
+		raise ValueError('datatype not supported in call to plot_contour')
+
+	# contouronly TODO (cla will also clear an overlay image)
+
+	# retrieve necessary options
+	levels=options.getfieldvalue('contourlevels')
+	colors=options.getfieldvalue('contourcolors')
+	norm=options.getfieldvalue('colornorm')
+	linestyles=options.getfieldvalue('contourlinestyles')
+	linewidths=options.getfieldvalue('contourlinewidths')
+
+	ax.tricontour(x,y,elements,data,levels,colors=colors,norm=norm,linestyles=linestyles,linewidths=linewidths)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_drivingstress.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_drivingstress.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_drivingstress.m	(revision 18231)
@@ -0,0 +1,24 @@
+function plot_drivingstress(md,options,width,i)
+%PLOT_DRIVINGSTRESS - plot driving stress
+%
+%   Usage:
+%      plot_drivingstress(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%get driving stress
+[sx sy s]=drivingstress(md);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[dstress datatype]=processdata(md,s,options);
+dstress=dstress/1000;
+
+%plot mesh quivervel
+subplot(width,width,i); 
+plot_unit(x,y,z,elements,dstress,is2d,isplanet,datatype,options)
+
+%apply options
+options=addfielddefault(options,'title','Driving stress [kPa]');
+options=addfielddefault(options,'view',2);
+applyoptions(md,dstress,options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_edges.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_edges.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_edges.m	(revision 18231)
@@ -0,0 +1,34 @@
+function plot_edges(md,options,width,i,datai)
+%PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_edges(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+edges=md.mesh.edges;
+if isnan(edges)
+	error('edges in NaN')
+end
+
+if dimension(md.mesh)==2,
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+	text(sum(x(edges(:,1:2)),2)/2,sum(y(edges(:,1:2)),2)/2,sum(z(edges(:,1:2)),2)/2,...
+		num2str(transpose(1:size(edges,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	error('plot_edges: 3d plot of edges not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Edges');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementnumbering.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementnumbering.m	(revision 18231)
@@ -0,0 +1,57 @@
+function plot_elementnumbering(md,options,width,i)
+%PLOT_ELEMENTNUMBERING - plot element numbering
+%
+%   Usage:
+%      plot_elementnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:3)),2)/3,sum(y(elements(:,1:3)),2)/3,sum(z(elements(:,1:3)),2)/3,...
+		num2str(elementnumbers),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:6)),2)/6,sum(y(elements(:,1:6)),2)/6,sum(z(elements(:,1:6)),2)/6,...
+		num2str(elementnumbers),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Element numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementstype.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementstype.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_elementstype.m	(revision 18231)
@@ -0,0 +1,139 @@
+function plot_elementstype(md,options,width,i)
+%PLOT_ELEMENTSTYPE - plot elements type
+%
+%   Usage:
+%      plot_elementstype(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,md.flowequation.element_equation,options);
+
+%edgecolor?
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%plot
+subplot(width,width,i);
+
+if is2d
+	%None elements
+	posNONE=find(data==0);
+	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
+	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
+	%SIA elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
+	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSA element
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	%L1L2 element
+	posM=find(data==3);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p4=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	%HO element
+	posP=find(data==4);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
+	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
+	%FS elements
+	posS=find(data==5);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
+	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSAHO element
+	posMP=find(data==6);
+	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
+	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
+	%HOFS elements
+	posPS=find(data==7);
+	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
+	p8=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',7,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSAFS elements
+	posMS=find(data==8);
+	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
+	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
+
+else
+	%None elements
+	PosNONE=find(data==0);
+	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
+	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	%SIA elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
+	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSA elements
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
+	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	%L1L2 elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	%HO elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	%FS elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
+	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSAHO elements
+	posP=find(data==5);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	%HOFS elements
+	PosPS=find(data==7);
+	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
+	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	%SSAFS elements
+	PosMS=find(data==6);
+	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
+	p9=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+
+end
+legend([p1 p2 p3 p4 p5 p6 p7 p8 p9],...
+		'None','SIA','SSA','L1L2','HO',...
+		'SSAHO','FS','SSAFS','HOFS');
+
+%apply options
+options=addfielddefault(options,'title','Elements type');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_googlemaps.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_googlemaps.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_googlemaps.m	(revision 18231)
@@ -0,0 +1,107 @@
+function plot_googlemaps(md,data,options,plotlines,plotcols,i)
+%PLOT_GOOGLEMAPS - superimpose Google maps to a given field
+%
+%   Usage:
+%      plot_googlemaps(md,data,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+if ~any(isnan(md.radaroverlay.x(:))) & ~any(isnan(md.radaroverlay.y(:))) & ~any(isnan(md.radaroverlay.pwr(:))) ...
+		& size(md.radaroverlay.pwr,3)==3 & size(md.radaroverlay.x,2)==size(md.radaroverlay.pwr,2),
+	disp('plot_googlemaps info: the RGB image held by the model is being used');
+else
+	disp('Extracting image from Google maps...');
+
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+
+	%Image corners in lat/long
+	ullat = max(latlist); ullon = min(lonlist);
+	lrlat = min(latlist); lrlon = max(lonlist);
+
+	md=googlemaps(md,ullat,ullon,lrlat,lrlon,options);
+end
+
+%Process image from model
+final = double(md.radaroverlay.pwr)/double(max(md.radaroverlay.pwr(:))); %rescale between 0 and 1
+
+%Get some options
+transparency = getfieldvalue(options,'transparency',.3);
+
+%Prepare grid
+if size(md.radaroverlay.x,1)==1 | size(md.radaroverlay.x,2)==1,
+	xmin=min(md.radaroverlay.x);
+	ymax=max(md.radaroverlay.y);
+	xspacing=md.radaroverlay.x(2)-md.radaroverlay.x(1);
+	yspacing=md.radaroverlay.y(2)-md.radaroverlay.y(1);
+	nlines=length(md.radaroverlay.y);
+	ncols =length(md.radaroverlay.x);
+		[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),...
+			data,xmin,ymax,xspacing,yspacing,nlines,ncols,NaN);
+else
+	X = md.radaroverlay.x;
+	Y = md.radaroverlay.y;
+	data_grid=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X(:),Y(:),'default',NaN); data_grid=reshape(data_grid,size(X));
+	x_m=X(1,:); y_m=Y(:,1);
+end
+data_nan=isnan(data_grid);
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+colorm = getcolormap(options);
+image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(colorm)/(data_max-data_min))),colorm);
+
+alpha=ones(size(data_grid));
+alpha(find(~data_nan))=transparency;
+alpha=repmat(alpha,[1 1 3]);
+
+final=alpha.*final+(1-alpha).*image_rgb;
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+h=imagesc(x_m,y_m,final);
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%Apply options
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'axis','xy equal off'); % default axis
+applyoptions(md,data,options);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_gridded.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_gridded.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_gridded.m	(revision 18231)
@@ -0,0 +1,92 @@
+function plot_gridded(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_gridded(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+%Get xlim and ylim (used to extract radar image)
+xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+post=getfieldvalue(options,'posting',diff(xlim)/1000);
+
+%Interpolating data on grid
+[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+data_grid_save = data_grid;
+if size(data_grid,1)<3 | size(data_grid,2)<3,
+	error('data_grid size too small in plot_gridded, check posting and units');
+end
+
+%Process data_grid: add white in NaN and correct caxis accordingly
+[data_nani data_nanj]=find(isnan(data_grid) | data_grid==-9999);
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+%shading interp;
+map    = getcolormap(options);
+image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(map)/(data_max-data_min))),map);
+if exist(options,'shaded'),
+	a    = -45;
+	scut = 0.2;
+	c    = 1;
+	% computes lighting from elevation gradient
+	[fx,fy] = gradient(data_grid_save,x_m,y_m);
+	fxy = -fx*sind(a) - fy*cosd(a);
+	clear fx fy % free some memory...
+	fxy(isnan(fxy)) = 0;
+
+	% computes maximum absolute gradient (median-style), normalizes, saturates and duplicates in 3-D matrix
+	r = repmat(max(min(fxy/nmedian(abs(fxy),1 - scut/100),1),-1),[1,1,3]);
+
+	% applies contrast using exponent
+	rp = (1 - abs(r)).^c;
+	image_rgb = image_rgb.*rp;
+
+	% lighter for positive gradient
+	k = find(r > 0);
+	image_rgb(k) = image_rgb(k) + (1 - rp(k));
+end
+
+% set novalues / NaN to black color
+if ~isempty(data_nani)
+	nancolor=getfieldvalue(options,'nancolor',[1 1 1]);
+	image_rgb(sub2ind(size(image_rgb),repmat(data_nani,1,3),repmat(data_nanj,1,3),repmat(1:3,size(data_nani,1),1))) = repmat(nancolor,size(data_nani,1),1);
+end
+
+%plot grid
+h=imagesc(xlim,ylim,image_rgb);
+axis xy
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%Apply options
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'axis','xy equal'); % default axis
+applyoptions(md,data,options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightelements.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightelements.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightelements.m	(revision 18231)
@@ -0,0 +1,67 @@
+function plot_highlightelements(md,options,width,i)
+%PLOT_HIGHLIGHTELEMENTS - plot selected elements
+%
+%   Usage:
+%      plot_highlightelements(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+pos=getfieldvalue(options,'highlight',[]);
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+else
+	if size(elements,2)==6, %prisms
+		%plot mesh 
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+		%Highlight
+		A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	elseif size(elements,2)==4, %tetras
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+		patch( 'Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[A B D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[B C D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[C A D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		%Highlight
+		A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4);
+		patch( 'Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',[0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces',[A B D],'Vertices', [x y z],'FaceVertexCData',[0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces',[B C D],'Vertices', [x y z],'FaceVertexCData',[0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+		patch( 'Faces',[C A D],'Vertices', [x y z],'FaceVertexCData',[0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	else
+		error('Not supported');
+	end
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightelements warning : highlight option empty, not element highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Elements');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightvertices.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightvertices.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_highlightvertices.m	(revision 18231)
@@ -0,0 +1,46 @@
+function plot_highlightvertices(md,options,width,i)
+%PLOT_HIGHLIGHTVERTICES - plot selected vertices
+%
+%   Usage:
+%      plot_highlightvertices(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[nodenumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightvertices warning : highlight option empty, not node highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Nodes');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_icefront.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_icefront.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_icefront.m	(revision 18231)
@@ -0,0 +1,67 @@
+function plot_icefront(md,options,width,i,data)
+%PLOT_ICEFRONT - plot segment on neumann BC
+%
+%   Usage:
+%      plot_icefront(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+ice=(md.mask.ice_levelset<0);
+noice=(md.mask.ice_levelset>=0);
+zeroice=(md.mask.ice_levelset==0);
+elementice=sum(ice(md.mesh.elements),2);
+elementnoice=sum(noice(md.mesh.elements),2);
+elementzeroice=sum(zeroice(md.mesh.elements),2);
+
+if dimension(md.mesh)==2,
+	icefront=(elementice & elementnoice) & ~(elementice==2 & elementzeroice);
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	hold on;
+
+	%Plot zero ice_levelset line
+
+else
+	icefront=(elementice & elementnoice) & ~(elementice==4 & elementzeroice);
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h2=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2],'element on ice front')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Neumann boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_importancefactors.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_importancefactors.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_importancefactors.m	(revision 18231)
@@ -0,0 +1,83 @@
+function plot_importancefactors(md,options,width,ii)
+%PLOT_IMPORTANCEFACTORS - plot importance factors
+%
+%   Usage:
+%      plot_importancefactors(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%first recover design variable descriptor
+if exist(options,'designvariable'),
+	descriptor=getfieldvalue(options,'designvariable');
+else
+	error('plot_importancefactors error message: Need to supply design variable descriptor');
+end
+descriptorlength=length(descriptor);
+
+%then recover responsfunction name
+if exist(options,'responsefunction'),
+	responsefunctiondescriptor=getfieldvalue(options,'responsefunction');
+else
+	error('plot_importancefactors error message: Need to supply response function descriptor');
+end
+
+%go through all response functions and find the one corresponding to the correct responsefunctiondescriptor
+responsefunctions=md.qmu.results{2};
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsefunctiondescriptor),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('plot_importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.desvar,1);
+
+%Now recover response to the correct desgin variable
+importancefactors=zeros(md.qmu.numberofpartitions,1);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.desvar{i};
+	if strncmpi(desvar,descriptor,descriptorlength),
+		count=count+1;
+		importancefactors(count)=responsefunctions.impfac(i);
+	end
+end
+if count==0,
+	error('plot_importancefactors error message: could not find to response functions with corresponding design variable');
+end
+
+%log?
+if exist(options,'log'),
+	logvalue=getfieldvalue(options,'log');
+	importancefactors=log(importancefactors)/log(logvalue);
+end
+
+%Ok, get partitioning.
+[epart npart]=MeshPartition(md,md.qmu.numberofpartitions);
+
+%distribute importance factor
+nodeimportance=importancefactors(npart);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%standard plot:
+subplot(width,width,ii);
+
+%ok, plot nodeimportance now.
+if is2d,
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', nodeimportance,'FaceColor','interp','EdgeColor',edgecolor);
+else
+	error('plot_importancefactors error message: 3d meshes not supported yet');
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.m	(revision 18231)
@@ -0,0 +1,218 @@
+function plot_manager(md,options,subplotwidth,nlines,ncols,i)
+%PLOT__MANAGER - distribute the plots, called by plotmodel
+%
+%   Usage:
+%      plot_manager(md,options,subplotwidth,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT
+
+%parse options and get a structure of options. 
+options=checkplotoptions(md,options);
+
+%get data to be displayed
+data=getfieldvalue(options,'data');
+
+%figure out if this is a special plot
+if ischar(data),
+
+	switch data,
+
+		case 'boundaries',
+			plot_boundaries(md,options,subplotwidth,i);
+			return;
+		case 'BC',
+			plot_BC(md,options,subplotwidth,i,data);
+			return;
+		case 'edges'
+			plot_edges(md,options,subplotwidth,i,data)
+			return
+		case 'elementnumbering',
+			plot_elementnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightelements',
+			plot_highlightelements(md,options,subplotwidth,i);
+			return;
+
+		case 'qmumean',
+			plot_qmumean(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmustddev',
+			plot_qmustddev(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmuhistnorm',
+			plot_qmuhistnorm(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmu_mass_flux_segments',
+			plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+			return;
+
+		case 'part_hist',
+			plot_parthist(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_n',
+			plot_parthistn(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_w',
+			plot_parthistw(md,options,nlines,ncols,i);
+			return;
+		case 'elements_type',
+			plot_elementstype(md,options,subplotwidth,i);
+			return;
+		case 'vertexnumbering',
+			plot_vertexnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightvertices',
+			plot_highlightvertices(md,options,subplotwidth,i);
+			return;
+		case {'basal_drag','basal_dragx','basal_dragy'},
+			plot_basaldrag(md,options,subplotwidth,i,data);
+			return;
+		case 'driving_stress',
+			plot_drivingstress(md,options,subplotwidth,i);
+			return;
+		case 'mesh',
+			plot_mesh(md,options,nlines,ncols,i);
+			return;
+		case 'none',
+			if ~exist(options,'overlay'),
+				plot_none(md,options,nlines,ncols,i);
+				return;
+			end
+		case 'penalties',
+			plot_penalties(md,options,subplotwidth,i);
+			return;
+		case 'partition',
+			plot_partition(md,options,nlines,ncols,i);
+			return;
+		case 'referential',
+			plot_referential(md,options,nlines,ncols,i);
+			return;
+		case 'riftvel',
+			plot_riftvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftnumbering',
+			plot_riftnumbering(md,options,nlines,ncols,i);
+			return;
+		case 'rifts',
+			plot_rifts(md,options,nlines,ncols,i);
+			return;
+		case 'riftrelvel',
+			plot_riftrelvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftpenetration',
+			plot_riftpenetration(md,options,nlines,ncols,i);
+			return;
+		case 'riftfraction',
+			plot_riftfraction(md,options,nlines,ncols,i);
+			return;
+		case 'sarpwr',
+			plot_sarpwr(md,options,subplotwidth,i)
+			return
+		case 'time_dependant' ,
+			plot_vstime(md,options,nlines,ncols,i)
+			return
+		case 'icefront'
+			plot_icefront(md,options,subplotwidth,i,data)
+			return
+		case 'segments'
+			plot_segments(md,options,subplotwidth,i,data)
+			return
+
+		case 'quiver'
+			data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
+
+		case {'strainrate_tensor','strainrate','strainrate_principal','strainrate_principalaxis1','strainrate_principalaxis2','strainrate_principalaxis3',...
+				'stress_tensor','stress','stress_principal','stress_principalaxis1','stress_principalaxis2','stress_principalaxis3',...
+				'deviatoricstress_tensor','deviatoricstress','deviatoricstress_principal','deviatoricstress_principalaxis1','deviatoricstress_principalaxis2','deviatoricstress_principalaxis3'},
+			plot_tensor(md,options,subplotwidth,i,data);
+			return;
+		case 'thermaltransient_results',
+			plot_thermaltransient_results(md,options,subplotwidth,i);
+			return;
+		case 'transient_movie',
+			plot_transient_movie(md,options,subplotwidth,i);
+			return;
+		case 'transient_results',
+			plot_transient_results(md,options,subplotwidth,i);
+
+		case 'transient_field',
+			plot_transient_field(md,options,subplotwidth,i);
+			return;
+
+	otherwise,
+
+		if ismember(data,properties('model')),
+			data=eval(['md.' data ';']);
+		else
+			error('plot error message: data provided not supported yet. Type plotdoc for help');
+		end
+	end
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'overlay'),
+	plot_overlay(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'googlemaps'),
+	plot_googlemaps(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'gridded'),
+	plot_gridded(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Profile plot
+if exist(options,'profile')
+	plot_profile(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,data,options);
+[data2 datatype]=processdata(md,data,options);
+
+%standard plot:
+if exist(options,'asymsubplot')
+	id=getfieldvalue(options,'asymsubplot',i);
+	subplot(nlines,ncols,id);
+else
+	subplot(nlines,ncols,i);
+end
+
+%plot unit
+plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options);
+
+%apply all options
+if datatype==3,
+	options=changefieldvalue(options,'colorbar',2);
+	if exist(options,'contourlevels'),
+		data2=data;
+	end
+end
+
+applyoptions(md,data2,options);
+
+%do ground overlay on kml plot_unit? 
+if (strcmpi(getfieldvalue(options,'kmlgroundoverlay','off'),'on')),
+	if ((nlines*ncols~=1) | (i~=1)),
+		error('cannot kmlgroundoverlay on multi-plots');
+	end
+
+	%call routine to build kml file and image that goes with it.
+	kmlgroundoverlay(md,options);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_manager.py	(revision 18231)
@@ -0,0 +1,102 @@
+try:
+	import pylab as p
+	import matplotlib.pyplot as plt
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+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
+
+try:
+	from osgeo import gdal
+	overlaysupport=True
+except ImportError:
+	print 'osgeo/gdal for python not installed, overlay plots are not enabled'
+	overlaysupport=False
+
+if overlaysupport:
+	from plot_overlay import plot_overlay
+
+def plot_manager(md,options,fig,ax):
+	'''
+	PLOT_MANAGER - distribute the plots called by plotmodel
+
+	'fig' is a handle to the figure instance created by plotmodel.
+
+	'ax' is a handle to the axes instance created by plotmodel.  This is
+	currently generated using matplotlib's AxesGrid toolki.
+
+	Usage:
+		plot_manager(md,options,fig,ax);
+
+	See also: PLOTMODEL, PLOT_UNIT
+	'''
+
+	#parse options and get a structure of options
+	options=checkplotoptions(md,options)
+
+	#get data to be plotted
+	data=options.getfieldvalue('data');
+
+	#initialize plot handle variable
+	#handle=None
+
+	# initialize subplot
+	#p.subplot(nrows,ncols,i,aspect='equal')
+
+	##basemap plot
+	#if options.exist('basemap'):
+	#	plot_basemap(md,data,options,nrows,ncols,i)
+
+	#overlay plot
+	if options.exist('overlay') and overlaysupport:
+		plot_overlay(md,data,options,ax)
+		options.addfielddefault('alpha',0.5)
+		options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)])
+		options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)])
+
+	#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,ax)
+			applyoptions(md,[],options,fig,ax)
+			fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact
+			return
+		elif data.lower()=='none':
+			print 'no data provided to plot (TODO: write plot_none.py)'
+			applyoptions(md,[],options,fig,ax)
+			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..."
+
+	#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
+	#if not handle:
+	#	p.subplot(nrows,ncols,i,aspect='equal')
+
+	#plot unit
+	plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)
+
+	#apply all options
+	applyoptions(md,data2,options,fig,ax)
+	
+	#ground overlay on kml plot_unit
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.m	(revision 18231)
@@ -0,0 +1,47 @@
+function plot_mesh(md,options,nlines,ncols,i)
+%PLOT_MESH - plot model mesh
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%retrieve some options
+linewidth=getfieldvalue(options,'linewidth',1);
+edgecolor=getfieldvalue(options,'edgecolor','black');
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+else
+	if size(elements,2)==6, %prisms
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	elseif size(elements,2)==4, %tetras
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+		patch( 'Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces',[A B D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces',[B C D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces',[C A D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	else %triangles (planet)
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+		if (size(elements,2)==4), D=elements(:,4); else D=C; end
+		patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_mesh.py	(revision 18231)
@@ -0,0 +1,29 @@
+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,ax):
+	'''
+	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:
+		ax.triplot(x,y,elements)
+	else:
+		print 'WARNING: only 2D mesh plot is currently implemented'
+	
+	#apply options
+	options.addfielddefault('title','Mesh')
+	options.addfielddefault('colorbar','off')
+	options.addfielddefault('ticklabels','on')
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_none.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_none.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_none.m	(revision 18231)
@@ -0,0 +1,20 @@
+function plot_none(md,options,nlines,ncols,i)
+%PLOT_NONE - plot nothing, just apply options
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+return;
+
+options=addfielddefault(options,'colorbar','none');
+options=addfielddefault(options,'map','none');
+options=addfielddefault(options,'axis','equal');
+
+if exist(options,'overlay'),
+	plot_overlay(md,'none',options,nlines,ncols,i);
+	return;
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.m	(revision 18231)
@@ -0,0 +1,159 @@
+function plot_overlay(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_overlay(md,data,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+if strcmpi(data,'none'),
+	radaronly=1;
+	data=NaN*ones(md.mesh.numberofvertices,1);
+	datatype=1;
+else
+	radaronly=0;
+	[data datatype]=processdata(md,data,options);
+end
+
+%check is2d
+if ~is2d, 
+	error('buildoverlay error message: overlay not supported for 3d meshes, project on a layer');
+end
+if datatype==3,
+	error('buildoverlay error message: overlay not supported for quiver plots');
+end
+
+%radar power
+if ~any(isnan(md.radaroverlay.x)) & ~any(isnan(md.radaroverlay.y)) & ~any(isnan(md.radaroverlay.pwr)),
+	disp('plot_overlay info: the radar image held by the model is being used');
+	xlim=[min(md.radaroverlay.x) max(md.radaroverlay.x)];
+	ylim=[min(md.radaroverlay.y) max(md.radaroverlay.y)];
+else
+	disp('Extracting radar image...');
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)])/getfieldvalue(options,'unit',1);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)])/getfieldvalue(options,'unit',1);
+	options=addfielddefault(options,'xlim',xlim);
+	options=addfielddefault(options,'ylim',ylim);
+	md=radarpower(md,options);
+end
+contrast = getfieldvalue(options,'contrast',1);  
+radar = (md.radaroverlay.pwr).^(contrast);
+radar = radar./max(radar(:));
+if size(radar,3)>1,
+	disp('WARNING: color image converted to greyscale intensity image');
+	radar=sum(radar,3)/3;
+end
+%radar(find(radar==0))=1; %Change background from black to white
+
+%InterpFromMeshToGrid
+xmin=min(md.radaroverlay.x);
+ymax=max(md.radaroverlay.y);
+xspacing=(max(md.radaroverlay.x)-min(md.radaroverlay.x))/(length(md.radaroverlay.x));
+yspacing=(max(md.radaroverlay.y)-min(md.radaroverlay.y))/(length(md.radaroverlay.y));
+nlines=length(md.radaroverlay.y);
+ncols =length(md.radaroverlay.x);
+disp('Interpolating data on grid...');
+if radaronly,
+	x_m=xmin:xspacing:xmin+ncols*xspacing;
+	y_m=ymax-nlines*yspacing:yspacing:ymax;
+	data_grid=NaN*ones(nlines,ncols);
+else
+	[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),...
+		data,xmin,ymax,xspacing,yspacing,nlines,ncols,NaN);
+end
+
+%Process data_grid (For processing, it is better not to have nan)
+pos=find(isinf(data_grid));
+if ~isempty(pos),
+	disp('Warning: removing Infs from vector (probably log(0)?)');
+	data_grid(pos)=NaN;
+end
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+data_nan=find(isnan(data_grid));
+data_grid(data_nan)=data_min; 
+
+%Special colormaps that require hsv treatment
+colorm=getfieldvalue(options,'colormap','Rignot');
+if strcmpi(colorm,'Rignot') | strcmpi(colorm,'Seroussi') | strcmpi(colorm,'redblue')
+	if strcmpi(colorm,'Rignot'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=(data_grid-data_min)/(data_max-data_min+eps);
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'Seroussi'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=1-(data_grid-data_min)/(data_max-data_min+eps)*0.7;
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'redblue')
+		data_mean=data_min+(data_max-data_min)/2;
+		h=1*ones(size(data_grid));
+		h(find(data_grid<data_mean))=0.7;
+		s=max(min(abs(data_grid-data_mean)/(data_max-data_mean) ,1),0);
+	else
+		error('colormap not supported yet. (''Rignot'' and ''redblue'' are the only cupported colormaps)');
+	end
+	%(S) Saturation is 0 in NaNs
+	s(data_nan)=0;
+	%(V) intensity is based on radar image
+	v=radar; %use radar power as intensity
+
+	%Transform HSV to RGB
+	image_hsv=zeros(size(data_grid,1),size(data_grid,2),3);
+	image_hsv(:,:,1)=h; clear h;
+	image_hsv(:,:,2)=s; clear s;
+	image_hsv(:,:,3)=v; clear v;
+	image_rgb=hsv2rgb(image_hsv);
+else
+	colorm = getcolormap(options);
+	len    = size(colorm,1);
+
+	ind = ceil((len-1)*(data_grid-data_min)/(data_max - data_min + eps) +1);
+	ind(find(ind>len))=len;
+	image_rgb=zeros(size(data_grid,1),size(data_grid,2),3);
+	r=colorm(:,1); image_rgb(:,:,1)=r(ind); clear r;
+	g=colorm(:,2); image_rgb(:,:,2)=g(ind); clear g;
+	b=colorm(:,3); image_rgb(:,:,3)=b(ind); clear b;
+
+	%Now add radarmap
+	r = image_rgb(:,:,1).*radar;  r(data_nan) = radar(data_nan);  image_rgb(:,:,1) = r;  clear r;
+	g = image_rgb(:,:,2).*radar;  g(data_nan) = radar(data_nan);  image_rgb(:,:,2) = g;  clear g;
+	b = image_rgb(:,:,3).*radar;  b(data_nan) = radar(data_nan);  image_rgb(:,:,3) = b;  clear b;
+end
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+%Plot: 
+imagesc(md.radaroverlay.x*getfieldvalue(options,'unit',1),md.radaroverlay.y*getfieldvalue(options,'unit',1),image_rgb);set(gca,'YDir','normal');
+
+%last step: mesh overlay?
+if exist(options,'edgecolor'),
+	hold on
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none',...
+		'EdgeColor',getfieldvalue(options,'edgecolor'),'LineWidth',getfieldvalue(options,'linewidth',1));
+end
+
+%Apply options, without colorbar and without grid
+options=changefieldvalue(options,'colormap',colorm);              % We used an HSV colorbar
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'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/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_overlay.py	(revision 18231)
@@ -0,0 +1,109 @@
+import numpy as npy
+from processmesh import processmesh
+from processdata import processdata
+import matplotlib.pyplot as plt
+import matplotlib as mpl
+import os
+try:
+	from osgeo import gdal
+except ImportError:
+	print 'osgeo/gdal for python not installed, plot_overlay is disabled'
+
+def plot_overlay(md,data,options,ax):
+	'''
+	Function for plotting a georeferenced image.  This function is called
+	from within the plotmodel code.
+	'''
+
+	x,y,z,elements,is2d,isplanet=processmesh(md,[],options)
+
+	if data=='none' or data==None:
+		imageonly=1
+		data=npy.float('nan')*npy.ones((md.mesh.numberofvertices,))
+		datatype=1
+	else:
+		imageonly=0
+		data,datatype=processdata(md,data,options)
+
+	if not is2d:
+		raise StandardError('overlay plot not supported for 3D meshes, project on a 2D layer first')
+	if datatype==3:
+		raise StandardError('overlay not yet supported for quiver plots')	
+
+	if not options.exist('geotiff_name'):
+		raise StandardError('overlay error: provide geotiff_name with path to geotiff file')
+	geotiff=options.getfieldvalue('geotiff_name')
+
+	xlim=options.getfieldvalue('xlim',[min(md.mesh.x),max(md.mesh.x)])
+	ylim=options.getfieldvalue('ylim',[min(md.mesh.y),max(md.mesh.y)])
+
+	gtif=gdal.Open(geotiff)
+	trans=gtif.GetGeoTransform()
+	xmin=trans[0]
+	xmax=trans[0]+gtif.RasterXSize*trans[1]
+	ymin=trans[3]+gtif.RasterYSize*trans[5]
+	ymax=trans[3]
+	
+	# allow supplied geotiff to have limits smaller than basemap or model limits
+	x0=max(min(xlim),xmin)
+	x1=min(max(xlim),xmax)
+	y0=max(min(ylim),ymin)
+	y1=min(max(ylim),ymax)
+	inputname='temp.tif'
+	os.system('gdal_translate -quiet -projwin ' + str(x0) + ' ' + str(y1) + ' ' + str(x1) + ' ' + str(y0) + ' ' + geotiff + ' ' + inputname)
+	
+	gtif=gdal.Open(inputname)
+	arr=gtif.ReadAsArray()
+	#os.system('rm -rf ./temp.tif')
+	
+	if gtif.RasterCount>=3:  # RGB array
+		r=gtif.GetRasterBand(1).ReadAsArray()
+		g=gtif.GetRasterBand(2).ReadAsArray()
+		b=gtif.GetRasterBand(3).ReadAsArray()
+		arr=0.299*r+0.587*g+0.114*b
+
+	# normalize array
+	arr=arr/npy.float(npy.max(arr.ravel()))
+
+	if options.getfieldvalue('overlayhist',0)==1:
+		ax=plt.gca()
+		num=2
+		while True:
+			if not plt.fignum_exists(num):
+				break
+			else:
+				num+=1
+		plt.figure(num)
+		plt.hist(arr.flatten(),bins=256,range=(0.,1.))
+		plt.title('histogram of overlay image, use for setting overlaylims')
+		plt.sca(ax) # return to original axes/figure
+		
+	# get parameters from cropped geotiff
+	trans=gtif.GetGeoTransform()
+	xmin=trans[0]
+	xmax=trans[0]+gtif.RasterXSize*trans[1]
+	ymin=trans[3]+gtif.RasterYSize*trans[5]
+	ymax=trans[3]
+	dx=trans[1]
+	dy=trans[5]	
+	
+	xarr=npy.arange(xmin,xmax,dx)
+	yarr=npy.arange(ymin,ymax,-dy) # -dy since origin='upper' (not sure how robust this is)
+	xg,yg=npy.meshgrid(xarr,yarr)
+	if options.exist('basemap'):
+		# TODO get handle to or create basemap instance 
+		# create coordinate grid in map projection units (for plotting)
+		lats,lons=xy2ll(xg,yg,-1,0,71)
+		xgmap,ygmap=m(lons,lats) # map projection units returned by basemap instance
+	else:
+		xgmap=xg
+		ygmap=yg
+	
+	overlaylims=options.getfieldvalue('overlaylims',[min(arr.ravel()),max(arr.ravel())])
+
+	norm=mpl.colors.Normalize(vmin=overlaylims[0],vmax=overlaylims[1])
+
+	pc=ax.pcolormesh(xgmap, ygmap, npy.flipud(arr), cmap=mpl.cm.Greys, norm=norm)
+	#rasterization? 
+	if options.getfieldvalue('rasterized',0):
+		pc.set_rasterized(True)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthist.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthist.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthist.m	(revision 18231)
@@ -0,0 +1,34 @@
+function plot_parthist(md,options,nlines,ncols,i)
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+subplot(2,1,1)
+bar(imin:imax,part(:,1));
+xlim([imin-0.5 imax+0.5])
+title('Number of Nodes in Each Partition')
+
+subplot(2,1,2)
+bar(imin:imax,part(:,2));
+xlim([imin-0.5 imax+0.5])
+title('Total Weight in Each Partition')
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistn.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistn.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistn.m	(revision 18231)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i)
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+%bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Total Weight in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistw.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistw.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_parthistw.m	(revision 18231)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i)
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+%bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Total Weight in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_penalties.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_penalties.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_penalties.m	(revision 18231)
@@ -0,0 +1,48 @@
+function plot_penalties(md,options,width,i)
+%PLOT_PENALTIES - plot penalties
+%
+%   Usage:
+%      plot_penalties(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh penalties
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if dimension(md.mesh)~=3,
+	error('no penalties to plot for ''2d'' model');
+elseif isempty(md.penalties),
+	disp('no penalty applied in this model');
+	return;
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	hold on;
+	for (i=1:size(md.penalties,1)),
+		P1=plot3(x(md.penalties(i,1)),y(md.penalties(i,1)),z(md.penalties(i,1)),'ro','MarkerSize',15,'MarkerFaceColor','r');
+		P2=plot3(x(md.penalties(i,:)),y(md.penalties(i,:)),z(md.penalties(i,:)),'bo-','LineWidth',2,'MarkerSize',8,'MarkerFaceColor','b');
+	end
+	legend([P1 P2],'SSA''s penalized nodes','HO''s penalized nodes');
+end
+
+%apply options
+options=addfielddefault(options,'title','Penalties');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_profile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_profile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_profile.m	(revision 18231)
@@ -0,0 +1,55 @@
+function plot_profile(md,data,options,nlines,ncols,ii)
+%PLOT_SECTION - plot a given field on a profile
+%
+%   Usage:
+%      plot_profile(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+if is2d, error('only 3d model supported'); end
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%Get coordinates
+location=getfieldvalue(options,'profile');
+if ~isnumeric(location) | numel(location)~=2,
+	error('location provided not supported (should be [x y])');
+end
+xprof=location(1);
+yprof=location(2);
+
+%Loop over number of curves
+for i=1:numcurves,
+
+	%Process data
+	[datai datatype]=processdata(md,data(:,i),options);
+
+	%resolution[z,data_interp]=ProfileValues(md,datai,xprof,yprof,resolution);
+	if exist(options,'resolution'),
+		resolution=getfieldvalue(options,'resolution');
+	else %Default resolution
+		resolution=[100];
+		disp(['plot_profile warning: no resolution specified, using default: ' num2str(resolution) ]);
+	end
+
+	%Compute profile value
+	[z,data_interp]=ProfileValues(md,datai,xprof,yprof,resolution);
+
+	%plot profile
+	subplot(nlines,ncols,ii)
+	plot(data_interp,z,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1),'LineStyle','-');
+	hold on;
+end
+
+%apply options
+options=addfielddefault(options,'title','Profile');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'ylabel','z');
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmu_mass_flux_segments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 18231)
@@ -0,0 +1,49 @@
+function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i)
+%PLOT_QMU_MASS_FLUX_SEGMENTS - plot segments from the qmu analysis of mass fluxes
+%
+%   Usage:
+%      plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%
+
+subplot(nlines,ncols,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+allsegments=md.qmu.mass_flux_segments;
+
+if dimension(md.mesh)==2,
+
+	%recover segments
+	hold on
+	for i=1:length(allsegments),
+		segments=allsegments{i};
+
+		%plot semgnets
+		for j=1:length(segments),
+			plot([segments(j,1) segments(j,3)],[segments(j,2) segments(j,4)]);
+		end
+		text(segments(j,1),segments(j,2),['Profile #' num2str(i)]);
+
+		%plot normals
+
+		for j=1:length(segments),
+			xstart=mean([segments(j,1) segments(j,3)]);
+			ystart=mean([segments(j,2) segments(j,4)]);
+			length1=sqrt((segments(j,1)-segments(j,3)).^2 + (segments(j,2)-segments(j,4)).^2);
+			normal(:,1)=cos(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			normal(:,2)=sin(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			xend=xstart+length1.*normal(:,1);
+			yend=ystart+length1.*normal(:,2);
+			plot([xstart xend],[ystart yend],'r-');
+		end
+
+	end
+else
+	error('plot_qmu_mass_flux_segments: 3d plot of segments not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Mass Flux segments and normals');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmuhistnorm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmuhistnorm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmuhistnorm.m	(revision 18231)
@@ -0,0 +1,47 @@
+function plot_qmuhistnorm(md,options,nlines,ncols,index)
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%recover histnorm data
+if ~exist(options,'qmudata')
+	error('plot_qmuhistnorm error message: option qmudata is required');
+else
+	qmudata=getfieldvalue(options,'qmudata');
+end
+
+%process options for the qmu plot: 
+
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%
+
+qmuoptions='';
+
+if exist(options,'hmin'), hmin=getfieldvalue(options,'hmin'); qmuoptions=[qmuoptions ',''hmin'',' num2str(hmin)]; end
+if exist(options,'hmax'), hmax=getfieldvalue(options,'hmax'); qmuoptions=[qmuoptions ',''hmax'',' num2str(hmax)]; end
+if exist(options,'hnint'), hnint=getfieldvalue(options,'hnint'); qmuoptions=[qmuoptions ',''hnint'',' num2str(hnint)]; end
+if exist(options,'ymin1'), ymin1=getfieldvalue(options,'ymin1'); qmuoptions=[qmuoptions ',''ymin1'',' num2str(ymin1)]; end
+if exist(options,'ymax1'), ymax1=getfieldvalue(options,'ymax1'); qmuoptions=[qmuoptions ',''ymax1'',' num2str(ymax1)]; end
+if exist(options,'ymin2'), ymin2=getfieldvalue(options,'ymin2'); qmuoptions=[qmuoptions ',''ymin2'',' num2str(ymin2)]; end
+if exist(options,'ymax2'), ymax2=getfieldvalue(options,'ymax2'); qmuoptions=[qmuoptions ',''ymax2'',' num2str(ymax2)]; end
+if exist(options,'cdfplt'), cdfplt=getfieldvalue(options,'cdfplt'); qmuoptions=[qmuoptions ',''cdfplt'',''' cdfplt '''']; end
+if exist(options,'cdfleg'), cdfleg=getfieldvalue(options,'cdfleg'); qmuoptions=[qmuoptions ',''cdfleg'',''' cdfleg '''']; end
+if exist(options,'nrmplt'), nrmplt=getfieldvalue(options,'nrmplt'); qmuoptions=[qmuoptions ',''nrmplt'',''' nrmplt '''']; end
+if exist(options,'EdgeColor'), EdgeColor=getfieldvalue(options,'EdgeColor'); qmuoptions=[qmuoptions ',''EdgeColor'',''' EdgeColor '''']; end
+if exist(options,'FaceColor'), FaceColor=getfieldvalue(options,'FaceColor'); qmuoptions=[qmuoptions ',''FaceColor'',''' FaceColor '''']; end
+
+%use qmu plot
+eval(['plot_hist_norm(qmudata' qmuoptions ');']);
+
+%apply options
+options=changefieldvalue(options,'colorbar','off');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmumean.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmumean.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmumean.m	(revision 18231)
@@ -0,0 +1,59 @@
+function plot_qmumean(md,options,nlines,ncols,i)
+%PLOT_QMUMEAN - plot mean of a scaled response 
+%
+%   Usage:
+%      plot_qmumean(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmumean error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmumean error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).mean;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Mean distribution of ' descriptor]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmunormplot.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmunormplot.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmunormplot.m	(revision 18231)
@@ -0,0 +1,45 @@
+%
+%  plot a normal probability plot of the response functions.
+%
+%  []=plot_normplot(rfunc)
+%
+function []=plot_qmunormplot(rfunc,width,ii)
+
+if ~nargin
+    help plot_normplot
+    return
+end
+
+%%  assemble the data into a matrix
+
+desc=cell (1,length(rfunc));
+for i=1:length(rfunc)
+    ldata(i)=length(rfunc(i).sample);
+end
+data=zeros(max(ldata),length(rfunc));
+
+for i=1:length(rfunc)
+    desc(i)=cellstr(rfunc(i).descriptor);
+    data(1:ldata(i),i)=rfunc(i).sample;
+end
+
+%standard plot:
+subplot(width,width,ii);
+
+%%  draw the plot
+
+%  draw normal probability plot
+
+normplot(data)
+ax1=gca;
+
+%  add the annotation
+
+title('Normal Probability Plot of Design Variables and/or Response Functions')
+xlabel('Value')
+ylabel('Probability')
+
+hleg1=legend(ax1,desc,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmustddev.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmustddev.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_qmustddev.m	(revision 18231)
@@ -0,0 +1,59 @@
+function plot_qmustddev(md,options,nlines,ncols,i)
+%PLOT_QMUMEAN - plot stddev of a scaled response 
+%
+%   Usage:
+%      plot_qmustddev(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmustddev error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmustddev error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).stddev/allresponses(i).mean*100;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Stddev  distribution of ' descriptor ' in %']);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver.m	(revision 18231)
@@ -0,0 +1,26 @@
+function plot_quiver(x,y,u,v,options),
+%PLOT_QUIVER - quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver(x,y,u,v,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.initialization.vx,md.initialization.vy,options);
+
+%process fields
+[quivers,palette]=quiver_process(x,y,u,v,options);
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+quiver_colorbar(quivers,options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver3.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver3.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_quiver3.m	(revision 18231)
@@ -0,0 +1,104 @@
+function plot_quiver3(x,y,z,u,v,w,options),
+%PLOT_QUIVER3 - 3d quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver3(x,y,z,u,v,w,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.mesh.z,md.initialization.vx,md.initialization.vy,md.initialization.vz,options);
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(z) & ~isnan(u) & ~isnan(v) & ~isnan(w));
+x=x(pos); y=y(pos); z=z(pos);
+u=u(pos); v=v(pos); w=w(pos);
+
+%get norm Min and Max
+Norm=sqrt(u.^2+v.^2+w.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%process options: scaling factor?
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',NaN);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	c=[0 0 1;1 0 0];
+elseif numcolors==3,
+	%blue yellow and red
+	c=[0 0 1;1 1 0;1 0 0];
+else
+	%let jet choose
+	c=colormap(jet(numcolors));
+end
+
+%Scale data
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:numcolors
+	pos=find( (Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	hprime=quiver3(x(pos),y(pos),z(pos),u(pos),v(pos),w(pos),'Color',c(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+if  ~strcmpi(getfieldvalue(options,'colorbar','on'),'off'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(levels));
+	for i=1:length(levels),
+		ticklabel{i}=num2str(round_ice(levels(i),3));
+	end
+	tickpos=1:numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(levels)/10);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_referential.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_referential.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_referential.m	(revision 18231)
@@ -0,0 +1,91 @@
+function plot_referential(md,options,width,i,data)
+%PLOT_PRESSURELOAD - plot segment on neumann BC
+%
+%   Usage:
+%      plot_referential(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+referential=md.stressbalance.referential;
+
+Xhat=md.stressbalance.referential(:,1:3);
+pos=find(sum(isnan(Xhat),2));
+Xhat(pos,:)=repmat([1 0 0],size(pos,1),1);
+Xhatnorm=sqrt(Xhat(:,1).^2+Xhat(:,2).^2+Xhat(:,3).^2);
+Xhat=Xhat./[Xhatnorm Xhatnorm Xhatnorm];
+
+Zhat=md.stressbalance.referential(:,4:6);
+pos=find(sum(isnan(Zhat),2));
+Zhat(pos,:)=repmat([0 0 1],size(pos,1),1);
+Zhatnorm=sqrt(Zhat(:,1).^2+Zhat(:,2).^2+Zhat(:,3).^2);
+Zhat=Zhat./[Zhatnorm Zhatnorm Zhatnorm];
+
+Yhat=cross(Zhat,Xhat);
+
+if dimension(md.mesh)==2,
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	len=min(edgex)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	hx=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	hy=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','red','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy],'local X direction','local Y direction')
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	edgez=max(md.mesh.z(elements),[],2)-min(md.mesh.z(elements),[],2);
+	len=min(edgex)/1.5;
+	lenz=min(edgez)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	zend=zstart+len*Xhat(:,3);
+	hx=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	zend=zstart+len*Yhat(:,3);
+	hy=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','red','ShowArrowHead','on','AutoScale','off');
+	%plot Z axis
+	xend=xstart+lenz*Zhat(:,1);
+	yend=ystart+lenz*Zhat(:,2);
+	zend=zstart+lenz*Zhat(:,3);
+	hz=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','green','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy,hz],'local X direction','local Y direction','local Z direction')
+end
+
+%apply options
+options=addfielddefault(options,'title','Stressbalance referential');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftfraction.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftfraction.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftfraction.m	(revision 18231)
@@ -0,0 +1,48 @@
+function plot_riftfraction(md,options,nlines,ncols,index)
+%PLOT_RIFTFRACTION - plot rift fractions
+%
+%   Usage:
+%      plot_riftfraction(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%check that there is something in riftproperties
+if isnan(md.rifts.riftstruct.riftproperties),
+	error('plot_riftfraction error message: field riftproperies is empty, run the model first')
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%first, build a vector of fractions, over all nodes. 
+fractions=zeros(md.mesh.numberofvertices,1);
+
+%complete the tips.
+for i=1:length(md.rifts.riftstruct), 
+	tips=md.rifts.riftstruct(i).tips;
+	fractions(tips)=1;
+end
+
+hold on;
+for i=1:length(md.rifts.riftstruct), 
+	segments=md.rifts.riftstruct(i).segments(:,1:2)';
+	xc=x(segments(:));
+	yc=y(segments(:));
+	zc=fractions(segments(:));
+	h2=patch('Xdata',xc,'Ydata',yc,'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat');
+end
+legend([h1,h2],'mesh boundaries','rifts')
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift ice/water fraction ???????'); %Eric, could you enter a better title?
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftnumbering.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftnumbering.m	(revision 18231)
@@ -0,0 +1,93 @@
+function plot_riftnumbering(md,options,nlines,ncols,index)
+%PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
+%
+%   Usage:
+%      plot_riftnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+fontsize=getfieldvalue(options,'FontSize',8);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+
+%Now, plot rift vertices numbers.
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	for j=1:size(penaltypairs,1),
+		node=penaltypairs(j,1);
+		t=text(x(node),y(node),[num2str(i) '.' num2str(j)]);
+		set(t,'FontSize',fontsize);
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftpenetration.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftpenetration.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftpenetration.m	(revision 18231)
@@ -0,0 +1,82 @@
+function plot_rifpenetration(md,options,nlines,ncols,index)
+%PLOT_RIFTPENETRATION - plot rift penetration
+%
+%   Usage:
+%      plot_rifpenetration(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftrelvel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftrelvel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftrelvel.m	(revision 18231)
@@ -0,0 +1,116 @@
+function plot_riftrelvel(md,options,nlines,ncols,index)
+%PLOT_RIFTRELVEL - plot rift relative velocities
+%
+%   Usage:
+%      plot_riftrelvel(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%markersize: 
+markersize=getfieldvalue(options,'markersize',1);
+
+%recover vx and vy:
+vx=getfieldvalue(options,'riftrelvel_vx',md.initialization.vx);
+vy=getfieldvalue(options,'riftrelvel_vy',md.initialization.vy);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(md.rifts.riftstruct(i).penaltypairs(:,1))=vx(penaltypairs(:,1))-vx(penaltypairs(:,2));
+	v(md.rifts.riftstruct(i).penaltypairs(:,1))=vy(penaltypairs(:,1))-vy(penaltypairs(:,2));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	hprime=quiver(quivers.x(pos),quivers.y(pos),-quivers.u(pos),-quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+for i=1:size(md.rifts.riftstruct,1),
+
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'k-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=vx(penaltypairs(j,1)); vx2=vx(penaltypairs(j,2)); vy1=vy(penaltypairs(j,1)); vy2=vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'.','MarkerSize',markersize); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k.','MarkerSize',markersize);
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g.','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',faulttitle,rifttitle);
+	elseif isp1
+		l=legend([h1,h2,p1],'mesh boundaries','crack tips',faulttitle);
+	elseif isp2
+		l=legend([h1,h2,p2],'mesh boundaries','crack tips',rifttitle);
+	else
+		l=legend([h1,h2],'mesh boundaries','crack tips');
+	end
+set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift/Fault Relative Velocity');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_rifts.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_rifts.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_rifts.m	(revision 18231)
@@ -0,0 +1,77 @@
+function plot_rifts(md,options,nlines,ncols,index)
+%PLOT_RIFTS - plot rifts in a mesh
+%
+%   Usage:
+%      plot_rifts(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,index); 
+
+%offset to separate rift flanks.
+offset=getfieldvalue(options,'offset',500);
+if isstruct(md.rifts.riftstruct),
+
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+			x(penaltypairs(j,1))=x(penaltypairs(j,1))-normal(1)*offset;
+			y(penaltypairs(j,1))=y(penaltypairs(j,1))-normal(2)*offset;
+		end
+		if length(md.rifts.riftstruct(i).tips)==3,
+			tip=md.rifts.riftstruct(i).tips(3);
+			%who is tip connected to? 
+			if isconnected(md.mesh.elements,penaltypairs(1,1),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+
+			if isconnected(md.mesh.elements,penaltypairs(1,2),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,1),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,2),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+		end
+	end
+end
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+else
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+end
+
+%apply options
+options=addfielddefault(options,'title','Rifts');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftvel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftvel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_riftvel.m	(revision 18231)
@@ -0,0 +1,107 @@
+function plot_riftvel(md,options,nlines,ncols,index)
+%PLOT_RIFTVEL - plot rift velocity
+%
+%   Usage:
+%      plot_riftvel(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(penaltypairs(:))=md.initialization.vx(penaltypairs(:));
+	v(penaltypairs(:))=md.initialization.vy(penaltypairs(:));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+
+for i=1:size(md.rifts.riftstruct,1),
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=md.initialization.vx(penaltypairs(j,1)); vx2=md.initialization.vx(penaltypairs(j,2)); vy1=md.initialization.vy(penaltypairs(j,1)); vy2=md.initialization.vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+
+%legend
+if isp1 & isp2
+	legend([h1,h2,p1,p2],'mesh boundaries','rift tips',' rifts closing','rifts opening')
+elseif isp1
+	legend([h1,h2,p1],'mesh boundaries','rift tips',' rifts closing')
+elseif isp2
+	legend([h1,h2,p2],'mesh boundaries','rift tips','rifts opening')
+else
+	legend([h1,h2],'mesh boundaries','rift tips')
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift Velocities');
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_sarpwr.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_sarpwr.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_sarpwr.m	(revision 18231)
@@ -0,0 +1,26 @@
+function plot_sarpwr(md,options,width,i)
+%PLOT_SARPWR - plot radar image
+%
+%   Usage:
+%      plot_sarpwr(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh sarpwr
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	md.mesh.x=md.mesh.x*unit;
+	md.mesh.y=md.mesh.y*unit;
+	md.mesh.z=md.mesh.z*unit;
+end
+
+imagesc(md.radaroverlay.x,md.radaroverlay.y,double(md.radaroverlay.pwr)),set(gca,'YDir','normal');colormap(gray);
+
+%apply options
+options=addfielddefault(options,'colorbar',0);
+options=changefieldvalue(options,'colormap','gray');
+
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_scatter.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_scatter.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_scatter.m	(revision 18231)
@@ -0,0 +1,91 @@
+function plot_scatter(x,y,level,varargin),
+%PLOT_SCATTER - scatter plot
+%
+%   Usage:
+%      plot_scatter(x,y,level,options);
+%
+%   Available options:
+%      'MarkerSize' : default is 3
+%      'Line'       : use line instead of circles
+%      'Cutoff'     : cut the line if the distance between 2 points is
+%                     greater than Cutoff (default is 1000)
+
+if nargin == 4,
+	options = varargin{1};
+else
+	options=pairoptions(varargin{:}); 
+end
+
+%check input
+if numel(x)~=numel(y) | numel(x)~=numel(level),
+	error('x, y and data should have the same size');
+end
+
+%Some processing
+Min=min(level);
+Max=max(level);
+Siz=length(level);
+nlab=10;
+%Min=0;
+%Max=1300;
+
+%OK, should we create a new colorbar for the occasion?
+if isempty(findobj(gcf,'tag','TMW_COLORBAR')),
+	alreadyplot=false;
+else
+	alreadyplot=true;
+end
+
+%generate levels
+if (alreadyplot),
+	phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
+	h    = phch{1};
+	ylim=get(h,'YLim');
+	palette=colormap;
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(ylim(1),ylim(2),numcolors+1),2);
+else
+	palette=getcolormap(options);
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+end
+
+colorind=ones(Siz,1);
+for i=1:numcolors
+	pos=find((level>=levels(i)) & (level<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(level>levels(end)))=numcolors;
+
+%loop over the number of colors
+hold on
+hp=[];
+if ~exist(options,'line'),
+	for i=1:numcolors
+		pos=find(colorind==i);
+		hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
+			'o','MarkerSize',getfieldvalue(options,'MarkerSize',3),'MarkerEdgeColor',palette(i,:),...
+			'MarkerFaceColor',palette(i,:));
+		hp=[hp;hprime];
+	end
+else
+	distances = sqrt( (x(1:end-1)-x(2:end)).^2 + (y(1:end-1)-y(2:end)).^2);
+	pos=find(distances>getfieldvalue(options,'Cutoff',1000));
+	x(pos,:)=NaN;
+	y(pos,:)=NaN;
+	for j=1:numcolors;
+		pos=find(colorind==j);
+		if(~isempty(pos) & pos(1)==1), pos(1)=[]; end
+		if ~isempty(pos),
+			tempx = [x(pos-1) x(pos) NaN(size(pos))]';
+			tempy = [y(pos-1) y(pos) NaN(size(pos))]';
+			line(tempx(1:end-1),tempy(1:end-1),'color',palette(j,:),'linewidth',getfieldvalue(options,'LineWidth',2));
+		end
+	end
+end
+
+if ~alreadyplot,
+	% format the colorbar
+	h    = colorbar;
+	caxis([min(levels) max(levels)]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_section.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_section.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_section.m	(revision 18231)
@@ -0,0 +1,216 @@
+function plot_section(md,data,options,nlines,ncols,i)
+%PLOT_SECTION - plot a given field on a section
+%
+%   Usage:
+%      plot_section(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%How many subplots?
+if exist(options,'showsection')
+
+	%Compute the indexes of the 2 plots (one for the sectionvalue and one for showsection
+	upperplots=floor((i-1)/ncols);
+	if upperplots==0, leftplots=i-1; else leftplots=i-ncols*upperplots-1; end
+	index1=4*ncols*upperplots+2*leftplots+1;
+	index2=index1+1;
+	ncols=2*ncols;
+else
+	index1=i;
+end
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%replug x and y onto model so that SectionValue treats the problem correctly
+md3d=md;
+if exist(options,'layer')
+	md.mesh.x=md.mesh.x2d; md.mesh.y=md.mesh.y2d; md.mesh.elements=md.mesh.elements2d;
+	md.mesh=mesh2d(md.mesh);
+end
+
+%read contours: 
+profiles=expread(getfieldvalue(options,'sectionvalue'));
+numprofiles=length(profiles);
+
+%Loop over number of profiles: 
+for profile_i=1:numprofiles,
+	profile=profiles(profile_i);
+
+	%Loop over number of curves
+	for i=1:numcurves,
+
+		[datai datatype]=processdata(md3d,data(:,i),options);
+
+		%resolution
+		if exist(options,'resolution'),
+			resolution=getfieldvalue(options,'resolution');
+		else %Default resolution
+			resolution=[1000 10*md.mesh.numberoflayers];
+			disp(['plot_section warning: no resolution specified, use default resolution: [horizontal_resolution vertical_resolution]=[' num2str(resolution)  ']']);
+		end
+
+		%Compute section value
+		[elements,x,y,z,s,data_s]=SectionValues(md,datai,profile,resolution);
+
+		if getfieldvalue(options,'sectionmean',0)==1,
+			disp(['Mean value of data along section: ' num2str(mean(data_s))])
+			disp(['Median value of data along section: ' num2str(median(data_s))])
+			disp(['Standard deviation of data along section: ' num2str(std(data_s))])
+		end
+
+		%units
+		if exist(options,'unit'),
+			unit=getfieldvalue(options,'unit');
+			x=x*unit;
+			y=y*unit;
+			z=z*unit;
+			s=s*unit;
+		end
+
+		%2D
+		if is2d,
+%		%plot section value
+%		hold on;
+%		subplot(nlines,ncols,index1)
+%		%subplot(1,3,[2 3])
+%		plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+%		%3D
+%	else
+%		%plot section value
+%		%if user requested view2: 2d plot with curvilinear coordinate
+%		if (getfieldvalue(options,'view',3)==2 )
+
+			%Show Section if requested by user
+			if exist(options,'showsection')
+
+				%compute number of labels
+				numlabels=min(getfieldvalue(options,'showsection'),length(s));
+				shift=fix(length(s)/numlabels);
+
+				%plot labels on current graph
+				hold on
+				text(s(1),data_s(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(s(1+(i-1)*shift),data_s(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(s(end),data_s(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+				%plot section only with labels
+				subplot(nlines,ncols,index2)
+				plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,isplanet,datatype,options)
+				hold on
+				text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+				plot(x,y,'-r')
+				axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+				view(2)
+			end
+
+			%plot section value
+			if(i==1), subplot(nlines,ncols,index1); end
+			plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+			hold on
+
+			%3D
+		else
+			%plot section value
+			%if user requested view2: 2d plot with curvilinear coordinate
+			if (getfieldvalue(options,'view',3)==2 )
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(s)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(s(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(s(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(s(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [s z zeros(length(s),1)],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+
+			else
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(x)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(x(1),y(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data,is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [x y z],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+				view(3)
+			end
+		end
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Section value');
+if dimension(md.mesh)==2
+	options=addfielddefault(options,'colorbar',0);
+end
+if ((dimension(md.mesh)==2) | getfieldvalue(options,'view',2)==2 )
+	options=addfielddefault(options,'xlabel','Curvilinear coordinate');
+	options=addfielddefault(options,'axis','auto');
+end
+if (dimension(md.mesh)==3 & getfieldvalue(options,'view',2)==2 )
+	options=addfielddefault(options,'ylabel','z');
+	options=addfielddefault(options,'axis','auto');
+end
+applyoptions(md3d,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_segments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_segments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_segments.m	(revision 18231)
@@ -0,0 +1,56 @@
+function plot_segments(md,options,width,i,datai)
+%PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_segments(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+segments=md.mesh.segments;
+
+if dimension(md.mesh)==2,
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=segments(:,end);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	if strcmpi(getfieldvalue(options,'segmentnumbering','off'),'on'),
+		text(sum(x(segments(:,1:2)),2)/2,sum(y(segments(:,1:2)),2)/2,sum(z(segments(:,1:2)),2)/2+1,...
+			num2str(md.mesh.segmentmarkers),...
+			'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+	end
+
+	%display arrows pointing outward
+	xstart=mean(x(segments(:,1:end-1)),2);
+	ystart=mean(y(segments(:,1:end-1)),2);
+	length=sqrt((x(segments(:,1))-x(segments(:,2))).^2 + (y(segments(:,1))-y(segments(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	normal(:,2)=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h3=plot(xstart,ystart,'r*');
+
+else
+	error('plot_segments: 3d plot of segments not supported yet!');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,q],'element on segment','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Segment boundaries');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_streamlines.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_streamlines.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_streamlines.m	(revision 18231)
@@ -0,0 +1,42 @@
+function plot_streamlines(md,options)
+%PLOT_STREAMLINES - plot stream lines on a figure
+%
+%   Usage:
+%      plot_streamlines(md,options)
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+[u datatype]=processdata(md,md.initialization.vx,options);
+[v datatype]=processdata(md,md.initialization.vy,options);
+
+%some checks
+if ~is2d,
+	disp('plot_streamlines error: streamlines option not supported for 3d plots. Project on a layer')
+	return
+end
+
+%initialize flowpath
+streamlines=getfieldvalue(options,'streamlines');
+edgecolor=getfieldvalue(options,'streamlines_color','y');
+if ischar(streamlines) & strcmpi(streamlines,'on');
+	streamlines=60;
+end
+if iscell(streamlines)
+	x0=[]; y0=[];
+	for i=1:size(streamlines,2)
+		coord=streamlines{i};
+		x0=[x0;coord(1)]; y0=[y0;coord(2)];
+	end
+else
+	x0=x(1:ceil(length(x)/streamlines):end);
+	y0=y(1:ceil(length(x)/streamlines):end);
+end
+
+%Get flow lines
+flowpath=flowlines(index,x,y,u,v,x0,y0);
+
+%plot
+hold on
+for i=1:length(flowpath)
+	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor',edgecolor);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor.m	(revision 18231)
@@ -0,0 +1,40 @@
+function plot_tensor(md,options,width,i,type)
+%PLOT_TENSOR - plot tensor components
+%
+%   Usage:
+%      plot_tensor(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+h=subplot(width,width,i); axis off; pos=get(h,'Position');
+
+plot_options.offsetx=pos(1);
+plot_options.offsety=pos(2);
+plot_options.width=pos(3);
+plot_options.height=pos(4);
+
+%Figure out tensor type:
+%FIXME does not work anymore
+if strncmpi(type,'strain',6),
+	tensor=md.results.strainrate;
+elseif strncmpi(type,'stress',6),
+	tensor=md.results.stress;
+elseif strncmpi(type,'deviatoricstress',16),
+	tensor=md.results.deviatoricstress;
+else
+	error('plot_tensor error message: unsupported type of tensor');
+end
+
+%Figure out type of plot being requested
+if strncmpi(fliplr(type),fliplr('tensor'),6) | strcmpi(type,'strainrate') | strcmpi(type,'deviatoricstress') | strcmpi(type,'stress'),
+	plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type),fliplr('principal'),9),
+	plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type(1:end-1)),fliplr('principalaxis'),13),
+	plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+	return;
+else
+	error('plot_tensor error message: unsurported type of plot');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_components.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_components.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_components.m	(revision 18231)
@@ -0,0 +1,78 @@
+function plot_tensor_components(md,options,width,i,tensor,type,plot_options)
+%PLOT_TENSOR_COMPONENT - plot component of a tensor
+%
+%   Usage:
+%      plot_tensor_components(md,options,width,i,tensor,type,plot_option);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if dimension(md.mesh)==2 %3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+elseif dimension(md.mesh)==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.xx datatype]=processdata(md,tensor.xx,options);
+[tensor.yy datatype]=processdata(md,tensor.yy,options);
+[tensor.xy datatype]=processdata(md,tensor.xy,options);
+if  dimension(md.mesh)==3
+	[tensor.xz datatype]=processdata(md,tensor.xz,options);
+	[tensor.yz datatype]=processdata(md,tensor.yz,options);
+	[tensor.zz datatype]=processdata(md,tensor.zz,options);
+end
+
+if dimension(md.mesh)==2,
+	subplot(2*width,2*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(2*width,2*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(2*width,2*width,index3),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+else
+	subplot(3*width,3*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(3*width,3*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(3*width,3*width,index3),
+	plot_unit(x,y,z,elements,tensor.zz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'zz')
+	subplot(3*width,3*width,index4),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+	subplot(3*width,3*width,index5),
+	plot_unit(x,y,z,elements,tensor.xz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xz')
+	subplot(3*width,3*width,index6),
+	plot_unit(x,y,z,elements,tensor.yz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yz')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+	%apply options
+	if ismember('_',type) %user plotet stress_tensor
+		strings=strsplit(type,'_');
+		string=strings{1};
+	else %default plot: user requested stress
+		string=type;
+	end
+	options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+	applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principal.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principal.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principal.m	(revision 18231)
@@ -0,0 +1,77 @@
+function plot_tensor_principal(md,options,width,i,tensor,type,plot_options)
+%PLOT_TENSOR_PRINCIPAL - plot principal values
+%
+%   Usage:
+%      plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (dimension(md.mesh)==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+	index4=index3+1;
+	newwidth=2*width;
+elseif dimension(md.mesh)==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+	newwidth=3*width;
+end
+
+%plot principal axis
+type1=[type 'axis1'];
+plot_tensor_principalaxis(md,options,newwidth,index1,tensor,type1,plot_options);
+type2=[type 'axis2'];
+plot_tensor_principalaxis(md,options,newwidth,index2,tensor,type2,plot_options);
+if  dimension(md.mesh)==3
+	type3=[type 'axis3'];
+	plot_tensor_principalaxis(md,options,newwidth,index3,tensor,type3,plot_options);
+end
+
+%now plot principal values
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.principalvalue1 datatype]=processdata(md,tensor.principalvalue1,options);
+[tensor.principalvalue2 datatype]=processdata(md,tensor.principalvalue2,options);
+if  dimension(md.mesh)==3
+	[tensor.principalvalue3 datatype]=processdata(md,tensor.principalvalue3,options);
+end
+
+if dimension(md.mesh)==2,
+	subplot(2*width,2*width,index3)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(2*width,2*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+else
+	subplot(3*width,3*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(3*width,3*width,index5)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+	subplot(3*width,3*width,index6)
+	plot_unit(x,y,z,elements,tensor.principalvalue3,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 3')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+%apply options
+if ismember('_',type) %user plotet stress_tensor
+	strings=strsplit(type,'_');
+	string=strings{1};
+else %default plot: user requested stress
+	string=type;
+end
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+options=changefieldvalue(options,'colorbar',2);
+applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principalaxis.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_tensor_principalaxis.m	(revision 18231)
@@ -0,0 +1,95 @@
+function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options)
+%PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
+%
+%   Usage:
+%      plot_tensor_principalaxis(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%prepare subplot
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+if dimension(md.mesh)==2,
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2);'])
+	eval(['value=tensor.principalvalue' type(end) ';']);
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[value datatype]=processdata(md,value,options);
+else
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2); Vz=tensor.principalaxis' type(end) '(:,3);'])
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[Vz datatype]=processdata(md,Vz,options);
+	[value datatype]=processdata(md,value,options);
+end
+
+%take the center of each element if ~isonnode
+if datatype==1,
+	x=mean(md.mesh.x(md.mesh.elements'))'; y=mean(md.mesh.y(md.mesh.elements'))'; z=mean(md.mesh.z(md.mesh.elements'))';
+end
+
+%plot quivers
+if dimension(md.mesh)==2,
+
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy;
+
+	pos=find(value>=0);
+	q1=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+
+else
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		z=z(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		Vz=Vz(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy; Vz=scale*Vz;
+
+	pos=find(value>=0);
+	q1=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+end
+
+%legend
+if strcmpi(type(1:6),'strain')
+	legend([q1 q2],'extension','compression')
+elseif strcmpi(type(1:6),'stress')
+	legend([q1 q2],'compression','traction')
+end
+
+%apply options
+strings=strsplit(type,'_');
+string=strings{1};
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' principal axis ' type(end)]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_thermaltransient_results.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_thermaltransient_results.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_thermaltransient_results.m	(revision 18231)
@@ -0,0 +1,23 @@
+function plot_thermaltransient_results(md,options,width,i)
+%PLOT_THERMALTRANSIENT_RESULTS - plot  results of a thermal transient solution
+%
+%   Usage:
+%      plot_thermaltransient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+string='plot(md';
+for i=1:length(md.thermaltransient_results),
+	string=[string ',''data'',''thermaltransient_results(' num2str(i) ').temperature'',''view'',3,''title'',''Temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
+string='plot(md';
+for i=2:length(md.thermaltransient_results),
+	string=[string ',''data'',md.thermaltransient_results(' num2str(i) ').temperature-md.thermaltransient_results(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_field.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_field.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_field.m	(revision 18231)
@@ -0,0 +1,43 @@
+function plot_transient_field(md,options,width,i,data)
+%PLOT_TRANSIENT_FIELD - plot transient results
+%
+%   Usage:
+%      plot_transient_field(md,options,width,i,data);
+%
+%   See also: PLOTMODEL
+
+%Check that they are transient results
+if (~isfield(md.results,'TransientSolution')),
+	error('plot_transient_field error message: no transient results in the model');
+end
+
+%Figure out the iterations to plot and check if it is possible
+transient=md.results.TransientSolution;
+maxiteration=size(transient,2);
+steps=getfieldvalue(options,'steps',1:1:maxiteration);
+
+if max(steps)>maxiteration | min(steps)<1,
+	error(['plot_transient_field error message: problem with the steps requested, must be an interger between 0 and ' num2str(maxiteration)]);
+end
+subplotwidth=ceil(sqrt(length(steps)));
+
+%Figure out the field to plot
+
+field=getfieldvalue(options,'field','Vel');
+
+%process mes only once
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot data for all steps
+for i=1:length(steps),
+
+	%process data and change title if needed
+	[data datatype]=processdata(md,transient(steps(i)).(field),options);
+	options=changefieldvalue(options,'title',[field ' at time ' num2str(transient(steps(i)).time/md.constants.yts) ' a']);
+
+	%create plot of step i
+	subplot(subplotwidth,subplotwidth,i);
+	plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+	applyoptions(md,data,options);
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_movie.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_movie.m	(revision 18231)
@@ -0,0 +1,70 @@
+function plot_transient_movie(md,options,width,i)
+%PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
+%   Usage:
+%      plot_transient_movie(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+	%prepare subplot
+	subplot(width,width,i); 
+
+	%xlim
+	if exist(options,'transient_movie_field'),
+		field=getfieldvalue(options,'transient_movie_field');
+	else
+		error('specify transient_movie_field in options list');
+	end
+
+	results=md.results.TransientSolution;
+	%loop over the time steps
+	if exist(options,'transient_movie_limit'),
+		limit=getfieldvalue(options,'transient_movie_limit');
+		steps=[limit(1):limit(end)];
+	else
+		steps=1:length(results);
+	end
+	results=md.results.TransientSolution;
+	nstep=1;
+	for i=steps
+
+		if ~isempty(results(i).(field)),
+			%process data
+			[x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
+			[data datatype]=processdata(md,results(i).(field),options);
+
+			titlestring=[field ' at time ' num2str(results(i).time/md.constants.yts) ' year'];
+			plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+			apply_options_movie(md,options,titlestring);
+
+			if exist(options,'transient_movie_output'),
+				set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+				if nstep==1,
+					%initialize images and frame
+					frame=getframe(gcf);
+					[images,map]=rgb2ind(frame.cdata,256,'nodither');
+					images(1,1,1,length(steps))=0;
+				else
+					frame=getframe(gcf);
+					images(:,:,1,nstep) = rgb2ind(frame.cdata,map,'nodither');
+				end
+			else
+				pause(0.1)
+			end
+			nstep=nstep+1;
+		end
+	end
+
+	%output movie if requested.
+	if exist(options,'transient_movie_output'),
+		filename=getfieldvalue(options,'transient_movie_output');
+		imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',2),'LoopCount',inf)
+	end
+
+end %function
+
+function apply_options_movie(md,options,titlestring)
+	%apply options
+	options=changefieldvalue(options,'title',titlestring);
+	options=addfielddefault(options,'colorbar',1);
+	applyoptions(md,[],options);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_results.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_results.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_transient_results.m	(revision 18231)
@@ -0,0 +1,77 @@
+function plot_transient_results(md,options,width,i)
+%PLOT_TRANSIENT_RESULTS - plot transient results
+%
+%   Usage:
+%      plot_transient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+fontsize=getfieldvalue(options,'fontsize',14);
+fontweight=getfieldvalue(options,'fontweight','n');
+
+%Prepare window distribution
+%Get screen geometry
+mp = get(0, 'MonitorPositions');
+%Build window sizes
+if size(mp,1)>=2        %several monitors, use the second one
+	bdwidth=mp(2,1)+5; topbdwidth=mp(2,2)+20; W=mp(2,3)/3; H=mp(2,4)/2;
+else                    %only one monitor
+	bdwidth=5;         topbdwidth=20;         W=mp(1,3)/3; H=mp(1,4)/2;
+end
+pos1=[bdwidth  H+bdwidth  W-2*bdwidth  H-bdwidth-topbdwidth];
+pos2=pos1+[W 0 0 0]; pos3=pos1+[2*W 0 0 0]; pos4=pos1+[0 -H 0 0]; pos5=pos1+[W -H 0 0]; pos6=pos1+[2*W -H 0 0];
+%Create windows
+figure(1);close;
+figure('Position',pos1); figure('Position',pos2);figure('Position',pos3);figure('Position',pos4);figure('Position',pos5);figure('Position',pos6);
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness,''title'',''Thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel,''view'',3,''title'',''Velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if dimension(md.mesh)==3,
+	string='plotmodel(md';
+	for i=1:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature,''view'',3,''title'',''Temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',3,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness-md.results.transient(' num2str(i-1) ').thickness,''title'',''Delta thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',4,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel-md.results.transient(' num2str(i-1) ').vel,''view'',3,''title'',''Delta velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',5,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if dimension(md.mesh)==3,
+	string='plotmodel(md';
+	for i=2:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature-md.results.transient(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',6,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.m	(revision 18231)
@@ -0,0 +1,73 @@
+function plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+%PLOT_UNIT - unit plot, display data
+%
+%   Usage:
+%      plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options);
+%
+%   See also: PLOTMODEL, PLOT_MANAGER
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+switch datatype,
+
+	%element plot
+	case 1,
+
+		pos=find(~isnan(data)); %needed for element on water
+		if size(elements,2)==6, %prisms
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		elseif size(elements,2)==4, %tetras
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+			patch( 'Faces',[A B C],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[A B D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[B C D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[C A D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+		if is2d,
+		end
+
+	%node plot
+	case 2,
+
+		if size(elements,2)==6, %prisms
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		elseif size(elements,2)==4, %tetras
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+			patch( 'Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces',[A B D],'Vertices', [x y z],'FaceVertexCData',data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces',[B C D],'Vertices', [x y z],'FaceVertexCData',data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces',[C A D],'Vertices', [x y z],'FaceVertexCData',data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		end
+
+	%quiver plot
+	case 3,
+
+		if is2d,
+			plot_quiver(x,y,data(:,1),data(:,2),options);
+		else
+			plot_quiver3(x,y,z,data(:,1),data(:,2),data(:,3),options);
+		end
+
+	otherwise,
+		error(['case ' num2str(datatype) ' not supported']);
+
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_unit.py	(revision 18231)
@@ -0,0 +1,82 @@
+from cmaptools import truncate_colormap
+try:
+	import pylab as p
+	import matplotlib as mpl
+	import matplotlib.pyplot as plt
+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,ax):
+	"""
+	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',128)
+	
+	alpha=options.getfieldvalue('alpha',1)
+	
+	#colormap
+	# default sequential colormap
+	defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
+	cmap=options.getfieldvalue('colormap',defaultmap)
+	if options.exist('cmap_set_over'):
+	   over=options.getfieldvalue('cmap_set_over','0.5')
+	   cmap.set_over(over)
+	if options.exist('cmap_set_under'):
+	   under=options.getfieldvalue('cmap_set_under','0.5')
+	   cmap.set_under(under)
+	
+	#normalize colormap if clim/caxis specified
+	if options.exist('clim'):
+	   lims=options.getfieldvalue('clim',[min(data),max(data)])
+	elif options.exist('caxis'):
+	   lims=options.getfieldvalue('caxis',[min(data),max(data)])
+	else:
+		if min(data)==max(data):
+			lims=[min(data)-0.5,max(data)+0.5]
+		else:
+			lims=[min(data),max(data)]
+	norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
+	if datatype==1:
+	   #element plot
+		if is2d:
+			tri=ax.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
+		else:
+			raise ValueError('plot_unit error: 3D element plot not supported yet')
+		return 
+	
+	elif datatype==2:
+		#node plot
+		if is2d:
+			tri=ax.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both')
+			if edgecolor != 'None':
+				ax.triplot(x,y,elements,color=edgecolor)
+		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/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vertexnumbering.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vertexnumbering.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vertexnumbering.m	(revision 18231)
@@ -0,0 +1,59 @@
+function plot_vertexnumbering(md,options,width,i)
+%PLOT_VERTEXNUMBERING - plot vertex numbering
+%
+%   Usage:
+%      plot_vertexnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vertexnumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(vertexnumbers),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	if size(elements,2)==6, %prisms
+		%plot mesh 
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	elseif size(elements,2)==4, %tetras
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+		patch( 'Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[A B D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[B C D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+		patch( 'Faces',[C A D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor','black');
+	end
+
+	%numbering
+	text(x,y,z,num2str(vertexnumbers),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Node numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vstime.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vstime.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plot_vstime.m	(revision 18231)
@@ -0,0 +1,55 @@
+function plot_vstime(md,options,nlines,ncols,i)
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%getting the variable structure
+datastruct  = getfieldvalue(options,'Input');
+structnames = strsplit(datastruct,'.');
+
+%getting the position of the to be ploted point
+location=getfieldvalue(options,'position');
+if ~isnumeric(location) | numel(location)~=2,
+	error('location provided not supported (should be [x y])');
+end
+xpoint=location(1);
+ypoint=location(2);
+
+%gathering a few time related parameters
+FirstTime=md.timestepping.start_time;
+LastTime=md.timestepping.final_time;
+Dt=md.timestepping.time_step;
+OutputDt=md.settings.output_frequency*Dt;
+%Constructiion of the result structure(one step above variable in
+%the structure tree)
+solstruct = md;
+for i=2:numel(structnames)-1,
+	solstruct=solstruct.(char(structnames(i)));
+end
+
+timesteps   = numel(solstruct);
+%now build a table with the variable needed in the end plot
+Value(1:timesteps)=NaN*ones(timesteps,1);
+time(1:timesteps)=NaN*ones(timesteps,1);
+
+for t=1:timesteps,
+	
+	data=solstruct(t).(char(structnames(numel(structnames))));
+
+	[TimeData datatype]=processdata(md,data,options);
+	clear data
+	Value(t)=PointValues(md,TimeData,xpoint,ypoint);
+	time(t)=FirstTime+(t-1)*OutputDt+Dt;
+end
+
+plot(time,Value);
+clear Value time
+
+options=addfielddefault(options,'title',md.miscellaneous.name);
+options=addfielddefault(options,'ylabel',char(structnames(numel(structnames))));
+options=addfielddefault(options,'xlabel','Time');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'axis','auto');
+options=addfielddefault(options,'xlim',[FirstTime LastTime]);
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotboxpos.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotboxpos.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotboxpos.m	(revision 18231)
@@ -0,0 +1,91 @@
+function pos = plotboxpos(h)
+%PLOTBOXPOS Returns the position of the plotted axis region
+%
+% pos = plotboxpos(h)
+%
+% This function returns the position of the plotted region of an axis,
+% which may differ from the actual axis position, depending on the axis
+% limits, data aspect ratio, and plot box aspect ratio.  The position is
+% returned in the same units as the those used to define the axis itself.
+% This function can only be used for a 2D plot.  
+%
+% Input variables:
+%
+%   h:      axis handle of a 2D axis (if ommitted, current axis is used).
+%
+% Output variables:
+%
+%   pos:    four-element position vector, in same units as h
+
+% Copyright 2010 Kelly Kearney
+
+% Check input
+
+if nargin < 1
+    h = gca;
+end
+
+if ~ishandle(h) || ~strcmp(get(h,'type'), 'axes')
+    error('Input must be an axis handle');
+end
+
+% Get position of axis in pixels
+
+currunit = get(h, 'units');
+set(h, 'units', 'pixels');
+axisPos = get(h, 'Position');
+set(h, 'Units', currunit);
+
+% Calculate box position based axis limits and aspect ratios
+
+darismanual  = strcmpi(get(h, 'DataAspectRatioMode'),    'manual');
+pbarismanual = strcmpi(get(h, 'PlotBoxAspectRatioMode'), 'manual');
+
+if ~darismanual && ~pbarismanual
+    
+    pos = axisPos;
+    
+else
+
+    dx = diff(get(h, 'XLim'));
+    dy = diff(get(h, 'YLim'));
+    dar = get(h, 'DataAspectRatio');
+    pbar = get(h, 'PlotBoxAspectRatio');
+
+    limDarRatio = (dx/dar(1))/(dy/dar(2));
+    pbarRatio = pbar(1)/pbar(2);
+    axisRatio = axisPos(3)/axisPos(4);
+
+    if darismanual
+        if limDarRatio > axisRatio
+            pos(1) = axisPos(1);
+            pos(3) = axisPos(3);
+            pos(4) = axisPos(3)/limDarRatio;
+            pos(2) = (axisPos(4) - pos(4))/2 + axisPos(2);
+        else
+            pos(2) = axisPos(2);
+            pos(4) = axisPos(4);
+            pos(3) = axisPos(4) * limDarRatio;
+            pos(1) = (axisPos(3) - pos(3))/2 + axisPos(1);
+        end
+    elseif pbarismanual
+        if pbarRatio > axisRatio
+            pos(1) = axisPos(1);
+            pos(3) = axisPos(3);
+            pos(4) = axisPos(3)/pbarRatio;
+            pos(2) = (axisPos(4) - pos(4))/2 + axisPos(2);
+        else
+            pos(2) = axisPos(2);
+            pos(4) = axisPos(4);
+            pos(3) = axisPos(4) * pbarRatio;
+            pos(1) = (axisPos(3) - pos(3))/2 + axisPos(1);
+        end
+    end
+end
+
+% Convert plot box position to the units used by the axis
+
+temp = axes('Units', 'Pixels', 'Position', pos, 'Visible', 'off', 'parent', get(h, 'parent'));
+set(temp, 'Units', currunit);
+pos = get(temp, 'position');
+delete(temp);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotdoc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotdoc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotdoc.m	(revision 18231)
@@ -0,0 +1,174 @@
+function plotdoc()
+%PLOTDOC - plot documentation
+%
+%   Usage:
+%      plotdoc()
+
+disp(' ');
+disp('   Plot usage: plotm(model,varargin)');
+disp('   Options: ');
+disp('       ''figure'': figure number');
+disp('       ''data'' : what we want to plot');
+disp('                Available values for ''data'' are: ');
+disp('                  - any field of the model structure. ex: plot(md,''data'',''vel''), or plot(md,''data'',md.initialization.vel)');
+disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa) based on the velocity in md.initialization');
+disp('                  - ''basal_dragx'' or ''basal_dragy'' : plot a component of the basal drag on the bed (in kPa)');
+disp('                  - ''boundaries'': this will draw all the segment boundaries to the model, including rifts.');
+disp('                  - ''icefront'': this will show segments that are used to define the icefront of the model (Neumann boundary conditions).');
+disp('                  - ''BC'': this will draw all the boundary conditions (Dirichlet and Neumann).');
+disp('                  - ''deviatoricstress_tensor'': plot the components of the deviatoric stress tensor (tauxx,tauyy,tauzz,tauxy,tauxz,tauyz) if computed');
+disp('                  - ''deviatoricstress_principal'': plot the deviatoricstress tensor principal axis and principal values');
+disp('                  - ''deviatoricstress_principalaxis1'': arrow plot the first principal axis of the deviatoricstress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''driving_stress'': plot the driving stress (in kPa)');
+disp('                  - ''elements_type'': model used for each element');
+disp('                  - ''elementnumbering'': numbering of elements');
+disp('                  - ''vertexnumbering'': numbering of vertices');
+disp('                  - ''highlightelements'': to highlight elements to highlight the element list');
+disp('                  - ''highlightvertices'': to highlight vertices (use highlight option to enter the vertex list');
+disp('                  - ''mesh'': draw mesh using trisurf');
+disp('                  - ''referential'': stressbalance referential');
+disp('                  - ''riftvel'': velocities along rifts');
+disp('                  - ''riftrelvel'': relative velocities along rifts');
+disp('                  - ''riftpenetration'': penetration levels for a fault');
+disp('                  - ''riftfraction'': fill fractions for every node of the rifts');
+disp('                  - ''rifts'': plot mesh with an offset so that rifts are visible');
+disp('                  - ''strainrate_tensor'': plot the components of the strainrate tensor (exx,eyy,ezz,exy,exz,eyz) if computed');
+disp('                  - ''strainrate_principal'': plot the strainrate tensor principal axis and principal values)');
+disp('                  - ''strainrate_principalaxis1'': arrow plot the first principal axis of the strainrate tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''stress_tensor'': plot the components of stress tensor (sxx,syy,szz,sxy,sxz,syz) if computed');
+disp('                  - ''stress_principal'': plot the stress tensor principal axis and principal values');
+disp('                  - ''stress_principalaxis1'': arrow plot the first principal axis of the stress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''transient_results'': this will display all the time steps of a transient run (use steps to specify the steps requested)');
+disp('                  - ''transient_vel'': this will display the velocity for the time steps requested in ''steps'' of a transient run');
+disp('                  - ''transient_vel'': vel can be by any field of the transient results (vx, vy, vz, vel, temperature, melting, pressure, bed, thickness, surface)');
+disp('                  - ''transient_field'': dynamic plot of results. specify ''steps'' option, as fell as ''field'' (defaults are all steps, for ''Vel'' field)');
+disp('                  - ''transient_movie'': this will display the time steps of a given field of a transient run');
+disp('                  - ''transient_movie_field'': field to be displayed when doing  transient_movie data display');
+disp('                  - ''transient_movie_output'': filename if output is desired for movie');
+disp('                  - ''transient_movie_time'': time for each image (default 2 seconds)');
+disp('                  - ''thermaltransient_results'': this will display all the time steps of a thermal transient run');
+disp('                  - ''qmuhistnorm'': histogram normal distribution. needs option qmudata');
+disp('                  - ''qmumean'': plot of mean distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''qmustddev'': plot of stddev distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''part_hist'': partitioning node and area histogram');
+disp('                  - ''quiver'': quiver plot');
+
+disp('       ''alloptions'': apply the options to all subplots if ''on''');
+disp('       ''axis'': same as standard matlab option (''equal'',''off'',''equal on'',...)');
+disp('       ''basin'': zoom on a given basin (''pineislandglacier'',''ronneiceshelf'', use isbasin to identify a basin');
+disp('                 ''hemisphere'': specify +1 or -1');
+disp('                 ''basindeltax'': in m');
+disp('                 ''showbasins'': write lables for every existing basin name around the center of the plot');
+disp('       ''caxis'': modify  colorbar range. (array of type [a b] where b>=a)');
+disp('       ''backgroundcolor'': plot background color. (default is ''w'')');
+disp('       ''figurebackgroundcolor'': figure background color. (default is ''none'')');
+disp('       ''coord'':  ''xy'' (default) or ''latlon''');
+disp('       ''colorlevels'':  N or {value1,valu2,value3,...} used if quiver, use different colors for the given number of colors or limits');
+disp('       ''colorbar'': add colorbar (string ''on'' or ''off'')');
+disp('       ''colorbartitle'': colorbar title (string)');
+disp('       ''colorbarYlabel'': colorbar Y label (string)');
+disp('       ''colorbarpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''colorbarcornerposition'': ''West'',''North'',etc ...');
+disp('       ''colorbartitlerotation'': -90, etc ...');
+disp('       ''colorbarfontsize'': specify colorbar fontsize');
+disp('       ''colorbarwidth'': multiplier (default 1) to the default width colorbar');
+disp('       ''colorbarheight'': multiplier (default 1) to the default height colorbar');
+disp('       ''colormap'': same as standard matlab option (''jet'',''hsv'',''cool'',''spring'',''gray'',''Ala'',''Rignot'',...)');
+disp('       ''contourlevels'': N or {value1,valu2,value3,...} add the contours of the specified values or N contours');
+disp('       ''contourticks'': ''on'' or ''off'' to display the ticks of the contours');
+disp('       ''contouronly'': ''on'' or ''off'' to display the contours on a white background');
+disp('       ''contourcolor'': ticks and contour color');
+disp('       ''density'': density of quivers (one arrow every N nodes, N integer)');
+disp('       ''inset'': add an inset (zoom) of the current figure if 1 (use ''insetx'', ''insety'' and ''insetpos'' to determine the inset position and content)');
+disp('       ''insetx'': [min(x) max(x)] where min(x) and max(x) are values determining the inset content');
+disp('       ''insety'': [min(y) max(y)] where min(y) and max(y) are values determining the inset content');
+disp('       ''insetpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''streamlines'': N (number of stream lines) or {[x1 y1],...} (coordinates of seed points) add streanlines on current figure');
+disp('       ''edgecolor'': same as standard matlab option EdgeColor (color name: ''black'' or RGB array: [0.5 0.2 0.8])');
+disp('       ''fontsize'': same as standard matlab option (10,14,...)');
+disp('       ''fontweight'': same as standard matlab option (normal: ''n'',bold: ''b'',light: ''l'',demi: ''d'')');
+disp('       ''fontcolor'': same as standard matlab option');
+disp('       ''highlight'': highlights certain nodes or elements when using ''nodenumbering'' or ''elementnumbering'' or ''highlightnodes '' or ''highlightelements'' option');
+disp('       ''resolution'': resolution used by section value (array of type [horizontal_resolution vertical_resolution])');
+disp('                       horizontal_resolution must be in meter, and vertical_resolution a number of layers');
+disp('       ''showsection'': show section used by ''sectionvalue'' (string ''on'' or a number of labels)');
+disp('       ''sectionvalue'': give the value of data on a profile given by an Argus file (string ''Argusfile_name.exp'')');
+disp('       ''profile'': give the value of data along a vertical profile ([xlocation ylocation])');
+disp('       ''smooth'': smooth element data (string ''yes'' or integer)');
+disp('       ''title'': same as standard matlab option');
+disp('       ''view'': same as standard matlab option (ex: 2, 3 or [90 180]');
+disp('       ''xlim'': same as standard matlab option (ex: [0 500])');
+disp('       ''ylim'': same as standard matlab option');
+disp('       ''zlim'': same as standard matlab option');
+disp('       ''xlabel'': same as standard matlab option (ex:''km'')');
+disp('       ''ylabel'': same as standard matlab option');
+disp('       ''xticklabel'': specifiy xticklabel');
+disp('       ''yticklabel'': specifiy yticklabel');
+disp('       ''overlay'': yes or no. This will overlay a radar amplitude image behind');
+disp('       ''overlay_image'': path to overlay image. provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options also');
+disp('       ''contrast'': (default 1) coefficient to add contrast to the radar amplitude image used in overlays');
+disp('       ''highres'': resolution of overlayed radar amplitude image (default is 0, high resolution is 1).');
+disp('       ''hem'': specify hemisphere ''n'' or ''s'' (default is ''s'').');
+disp('       ''alpha'': transparency coefficient (the higher, the more transparent). Default is 1.5');
+disp('       ''scaling'': scaling factor used by quiver plots. Default is 0.4');
+disp('       ''autoscale'': set to ''off'' to have all the quivers with the same size. Default is ''on''');
+disp('       ''expdisp'': plot exp file on top of a data plot. provide exp file as an argument (use a cell of strings if more than one)');
+disp('       ''expstyle'': marker style for expdisp plot (use a cell of strings if more than one)');
+disp('       ''linewidth'': line width for expdisp plot (use a cell of strings if more than one)');
+disp('       ''border'': size of display border (in pixels). active only for overlay plots');
+disp('       ''text'': print string, use a cell of strings if more than one');
+disp('       ''textposition'': [x y] position of text, use a cell of strings if more than one');
+disp('       ''textsize'':  same as standard ''FontSize'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textweight'':  same as standard ''FontWeight'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textcolor'':  same as standard ''color'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textrotation'':  same as standard ''Rotation'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''mask'': list of flags of size numberofnodes or numberofelements. Only ''true'' values are plotted ');
+disp('       ''nan'': value assigned to NaNs (convenient when plotting BC)');
+disp('       ''partitionedges'': ''off'' by default. overlay plot of partition edges');
+disp('       ''log'': value of log');
+disp('       ''latlon'': ''on'' or {latstep lonstep [resolution [color]]} where latstep,longstep and resolution are in degrees, color is a [r g b] array');
+disp('       ''latlonnumbering'': ''on'' or {latgap longap colornumber latangle lonangle} where latgap and longap are pixel gaps for the numbers,'); 
+disp('       ''latlonclick'': ''on'' to click on latlon ticks positions');
+disp('                   colornumber is a [r g b] array and latangle and lonangle are angles to flip the numbers');
+disp('       ''northarrow'': add an arrow pointing north, ''on'' for default value or [x0 y0 length [ratio width fontsize]] where (x0,y0) are the coordinates of the base, ratio=headlength/length');
+disp('       ''offset'': mesh offset used by ''rifts'', default is 500');
+disp('       ''scaleruler'': add a scale ruler, ''on'' for default value or [x0 y0 length width numberofticks] where (x0,y0) are the coordinates of the lower left corner');
+disp('       ''showregion'': show domain in Antarctica on an inset, use ''insetpos'' properties');
+disp('       ''visible'': ''off'' to make figure unvisible, default is ''on''');
+disp('       ''wrapping'': repeat ''n'' times the colormap (''n'' must be an integer)');
+disp('       ''unit'': by default, in m, otherwise, ''km'' is available');
+disp('       ''legend_position'': by default, ''NorthEasth''');
+disp('       ''qmudata'': data for qmu  plots.');
+disp('                  {dresp1   ,dresp2  ,hmin,hmax,hnint} or {samp,desc,mu,sigma,hmin,hmax,hnint}');
+disp('                  where dresp1 is a structure array of responses (where we need samp and desc), ');
+disp('                  dresp2 is a structure array of responses (where we only need mu and sigma)');
+disp('                  hmin,hmax and hnint are the minimum, maximum and number of intervals of the histogram (optional)');
+disp('       ''figposition'': position of figure: ''fullscreen'', ''halfright'', ''halfleft'', ''portrait'', ''landscape'',... (hardcoded in applyoptions.m)');
+disp('       ''offsetaxispos'': offset of current axis position to get more space (ex: [-0.02 0  0.04 0])');
+disp('       ''axispos'': axis position to get more space');
+disp('       ''hmin'': (numeric, minimum for histogram)');
+disp('       ''hmax'': (numeric, maximum for histogram)');
+disp('       ''hnint'': (numeric, number of intervals for histogram)');
+disp('       ''ymin1'': (numeric, minimum of histogram y-axis)');
+disp('       ''ymax1'': (numeric, maximum of histogram y-axis)');
+disp('       ''ymin2'': (numeric, minimum of cdf y-axis)');
+disp('       ''ymax2'': (numeric, maximum of cdf y-axis)');
+disp('       ''cdfplt'': (char, ''off'' to turn off cdf line plots)');
+disp('       ''cdfleg'': (char, ''off'' to turn off cdf legends)');
+disp('       ''segmentnumbering'': (''off'' by default)');
+disp('       ''kmlgroundoverlay'': (''off'' by default)');
+disp('       ''kmlfilename'': (''tempfile.kml'' by default)');
+disp('       ''kmlroot'': (''./'' by default)');
+disp('       ''kmlimagename'': (''tempimage'' by default)');
+disp('       ''kmlimagetype'': (''png'' by default)');
+disp('       ''kmlresolution'': (1 by default)');
+disp('       ''kmlfolder'': (''Ground Overlay'' by default)');
+disp('       ''kmlfolderdescription'': ('''' by default)');
+disp('       ''kmlgroundoverlayname'': ('''' by default)');
+disp('       ''kmlgroundoverlaydescription'': ('''' by default)');
+
+disp('       any options (except ''data'') can be followed by ''#i'' where ''i'' is the subplot number, or ''#all'' if applied to all plots');
+disp('  ');
+disp('   Examples:');
+disp('       plotmodel(md,''data'',''vel'',''data'',''mesh'',''view#2'',3,''colorbar#all'',''on'',''axis#1'',''off equal'')');
+disp('       plotmodel(md,''data'',''highlightelements'',''highlight'',[1 4 10],''expdisp'',{''domain1.exp'' ''domain2.exp'' ''domain3.exp''})');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.m	(revision 18231)
@@ -0,0 +1,100 @@
+function plotmodel(md,varargin)
+%At command prompt, type plotdoc for help on documentation.
+
+%First process options
+options=plotoptions(varargin{:});
+
+%get number of subplots
+subplotwidth=ceil(sqrt(options.numberofplots));
+
+%Get figure number and number of plots
+figurenumber=options.figurenumber;
+numberofplots=options.numberofplots;
+
+%if nlines and ncols specified, then bypass.
+if exist(options.list{1},'nlines'),
+	nlines=getfieldvalue(options.list{1},'nlines');
+else 
+	nlines=ceil(numberofplots/subplotwidth);
+end
+
+if exist(options.list{1},'ncols'),
+	ncols=getfieldvalue(options.list{1},'ncols');
+else 
+	ncols=subplotwidth;
+end
+
+%check that nlines and ncols were given at the same time!
+if ((exist(options.list{1},'ncols') & ~exist(options.list{1},'ncols')) | (~exist(options.list{1},'ncols') & exist(options.list{1},'ncols')))
+	error('plotmodel error message: nlines and ncols  need to be specified together, or not at all');
+end
+
+%go through subplots
+if numberofplots,
+
+	%Create figure 
+	f=figure(figurenumber);clf;
+	if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
+		set(f,'Visible','Off');
+	end
+
+	if exist(options.list{1},'figposition'), % {{{
+		figposition=getfieldvalue(options.list{1},'figposition');
+		if ischar(figposition),
+			if strcmpi(figposition,'larour'),
+				set(gcf,'Position',[1604 4 1594 1177]);
+			elseif strcmpi(figposition,'larour2'),
+				set(gcf,'Position',[756    62   827   504]);
+			elseif strcmpi(figposition,'mathieu'),
+				set(gcf,'Position',[300 1 1580 1150]);
+			elseif strcmpi(figposition,'fullscreen'),
+				set(gcf,'Position',get(0,'ScreenSize'));
+			elseif strcmpi(figposition,'halfright'),
+				screen=get(0,'ScreenSize');
+				left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+				set(gcf,'Position',fix([left+widt/2 bott widt/2 heig]));
+			elseif strcmpi(figposition,'halfleft'),
+				screen=get(0,'ScreenSize');
+				left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+				set(gcf,'Position',fix([left bott widt/2 heig]));
+			elseif strcmpi(figposition,'square'),
+				screen=get(0,'ScreenSize');
+				left=screen(1); bott=screen(2); widt=min(screen(3)-25,screen(4)-25);
+				set(gcf,'Position',fix([left+(screen(3)-widt) bott widt widt]));
+			elseif strcmpi(figposition,'portrait'),
+				%reformat with letter paper size (8.5" x 11")
+				screen=get(0,'ScreenSize');
+				left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+				portrait=fix([left+widt-(heig*8.5/11) bott heig*8.5/11 heig]);
+				set(gcf,'Position',portrait)
+			elseif strcmpi(figposition,'landscape'),
+				%reformat with letter paper size (8.5" x 11")
+				screen=get(0,'ScreenSize');
+				left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+				landscape=fix([left+widt-(heig*11/8.5) bott heig*11/8.5 heig]);
+				set(gcf,'Position',landscape)
+			else
+				disp('''figposition'' string not supported yet');
+			end
+		else
+			set(gcf,'Position',figposition);
+		end
+	end % }}}
+
+	%Use zbuffer renderer (snoother colors) and white background
+	set(f,'Renderer','zbuffer','color',getfieldvalue(options.list{1},'figurebackgroundcolor','w'));
+
+	%Go through all data plottable and close window if an error occurs
+	try,
+		for i=1:numberofplots,
+			plot_manager(getfieldvalue(options.list{i},'model',md),options.list{i},subplotwidth,nlines,ncols,i);
+			%List all unused options
+			displayunused(options.list{i})
+		end
+	catch me,
+		%figure(figurenumber),close;
+		rethrow(me);
+	end
+else
+	error('plotmodel error message: no output data found. ');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/plotmodel.py	(revision 18231)
@@ -0,0 +1,99 @@
+import numpy as npy
+from plotoptions import plotoptions
+
+try:
+	import pylab as p
+	import matplotlib.pyplot as plt
+	from mpl_toolkits.axes_grid1 import ImageGrid
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+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))
+	
+	#Get figure number and number of plots
+	figurenumber=options.figurenumber
+	numberofplots=options.numberofplots
+
+	#get hold
+	hold=options.list[0].getfieldvalue('hold',False)
+
+	#if nrows and ncols specified, then bypass
+	if options.list[0].exist('nrows'):
+		nrows=options.list[0].getfieldvalue('nrows')
+		nr=True
+	else:
+		nrows=npy.ceil(numberofplots/subplotwidth)
+		nr=False
+	
+	if options.list[0].exist('ncols'):
+		ncols=options.list[0].getfieldvalue('ncols')
+		nc=True
+	else:
+		ncols=int(subplotwidth)
+		nc=False
+	ncols=int(ncols)
+	nrows=int(nrows)
+	
+	#check that nrows and ncols were given at the same time!
+	if not nr==nc:
+		raise StandardError('error: nrows and ncols need to be specified together, or not at all')
+	
+	#Go through plots
+	if numberofplots:
+		
+		#if plt.fignum_exists(figurenumber): 
+		#	plt.cla()
+
+		#if figsize specified
+		if options.list[0].exist('figsize'):
+			figsize=options.list[0].getfieldvalue('figsize')
+			fig=plt.figure(figurenumber,figsize=(figsize[0],figsize[1]),tight_layout=True)
+		else:
+			fig=plt.figure(figurenumber,tight_layout=True)
+		fig.clf()
+
+		# options needed to define plot grid
+		direction=options.list[0].getfieldvalue('direction','row') # row,column
+		axes_pad=options.list[0].getfieldvalue('axes_pad',0.25)
+		add_all=options.list[0].getfieldvalue('add_all',True) # True,False
+		share_all=options.list[0].getfieldvalue('share_all',True) # True,False
+		label_mode=options.list[0].getfieldvalue('label_mode','1') # 1,L,all
+		cbar_mode=options.list[0].getfieldvalue('cbar_mode','each') # none,single,each
+		cbar_location=options.list[0].getfieldvalue('cbar_location','right') # right,top
+		cbar_size=options.list[0].getfieldvalue('cbar_size','5%')
+		cbar_pad=options.list[0].getfieldvalue('cbar_pad','2.5%') # None or %
+		
+		axgrid=ImageGrid(fig, 111,
+				nrows_ncols=(nrows,ncols),
+				direction=direction,
+				axes_pad=axes_pad,
+				add_all=add_all,
+				share_all=share_all,
+				label_mode=label_mode,
+				cbar_mode=cbar_mode,
+				cbar_location=cbar_location,
+				cbar_size=cbar_size,
+				cbar_pad=cbar_pad
+				)
+
+		if cbar_mode=='none':
+			for ax in axgrid.cbar_axes: fig._axstack.remove(ax)
+
+		for i in xrange(numberofplots):
+			plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid[i])
+
+		fig.show()
+	else:
+		raise StandardError('plotmodel error message: no output data found.')
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.m	(revision 18231)
@@ -0,0 +1,184 @@
+function [data datatype]=processdata(md,data,options)
+%PROCESSDATA - process data to be plotted
+%
+%   datatype = 1 -> elements
+%   datatype = 2 -> nodes
+%   datatype = 3 -> node quivers
+%   datatype = 4 -> patch
+%
+%   Usage:
+%      [data datatype]=processdata(md,data,options);
+%
+%   See also: PLOTMODEL, PROCESSMESH
+
+%check format
+if (iscell(data) | isempty(data) | length(data)==0 | (length(data)==1 & ~isstruct(data) & isnan(data))),
+	error('plotmodel error message: data provided is empty');
+end
+
+%Process NaN if any (do not know before mask is applied)
+if exist(options,'nan')
+	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+end
+
+%special case for mesh 2dvertical
+if strcmp(domaintype(md.mesh),'2Dvertical'),
+	[data datatype] = processdata(md.mesh,md,data,options);
+	return;
+end
+
+%needed later on
+if isprop(md.mesh,'numberofvertices2d'), 
+	numberofvertices2d=md.mesh.numberofvertices2d; 
+	numberofelements2d=md.mesh.numberofelements2d; 
+else 
+	numberofvertices2d=NaN;
+	numberofelements2d=NaN;
+end
+
+%initialize datatype
+datatype=0;
+
+%get datasize
+datasize=size(data);
+
+%transpose data if necessary
+if (size(data,2) > size(data,1)),
+	data=data';
+end
+datasize=size(data);
+
+%convert to double if necessary
+if ~isnumeric(data);
+	disp('processdata info message: data is not numeric (logical?). Converted to double');
+	data=double(data);
+end
+
+%check length
+if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (strcmp(md.mesh.domaintype(),'3D') & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
+	error('plotmodel error message: data not supported yet');
+end
+
+%quiver?
+if datasize(2)>1,
+	datatype=3;
+
+	%check number of columns, add zeros if necessary,
+	if (dimension(md.mesh)==3)
+		if datasize(2)==2,
+			data=[data, zeros(datasize(1),1)];
+		elseif datasize(2)~=3,
+			error('plotmodel error message: data provided should have 2 or 3 columns for quiver plot, and 1 for regular plot');
+		end
+	end
+end
+
+%treat the case datasize(1)=6*nodes
+if datasize(1)==6*md.mesh.numberofvertices
+	%keep the only norm of data
+	data1=data(1:6:md.mesh.numberofvertices*6,:);
+	data2=data(2:6:md.mesh.numberofvertices*6,:);
+	data=sqrt(data1.^2+data2.^2);
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
+end
+
+%treat the case datasize(1)=nodes2d
+if (dimension(md.mesh)==3 & datasize(1)==numberofvertices2d),
+	data=project3d(md,'vector',data,'type','node');
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
+end
+
+%treat the case datasize(1)=nodes2d
+if (dimension(md.mesh)==3 & datasize(1)==numberofelements2d),
+	data=project3d(md,'vector',data,'type','element');
+	datasize(1)=md.mesh.numberofelements;
+	%---> go to node data
+end
+
+%smoothing?
+if exist(options,'smooth')
+	data=averaging(md,data,getfieldvalue(options,'smooth'));
+	datasize(1)=md.mesh.numberofvertices;
+	%---> go to node data
+end
+
+%element data
+if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+
+	%Initialize datatype if non patch
+	if datatype~=4 & datatype~=5,
+		datatype=1;
+	end
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+			data(pos2,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(pos,:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+		data(find(data<bounds(1)))=bounds(1);
+		if any(data<=0),
+			error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		end
+		pos=find(~isnan(data));
+		data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+	end
+end
+
+%node data
+if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+	datatype=2;
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			data(pos,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(md.mesh.elements(pos,:),:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		%if any(data<=0),
+		%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		%end
+		data=log(data)/log(getfieldvalue(options,'log'));
+	end
+end
+
+%layer projection? 
+if getfieldvalue(options,'layer',0)>=1,
+	data=project2d(md,data,getfieldvalue(options,'layer')); %project onto 2d mesh
+end
+
+%control arrow density if quiverplot
+if datatype==3 & exist(options,'density')
+	databak=data;
+	data=NaN*ones(datasize);
+	density=getfieldvalue(options,'density');
+	data(1:density:end,:)=databak(1:density:end,:);
+	clear databak
+end
+
+%OK, if datatype=0 error out
+if datatype==0,
+	error(['data provided not recognized or not supported']);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processdata.py	(revision 18231)
@@ -0,0 +1,91 @@
+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 'numberofvertices2d' in dir(md.mesh):
+		numberofvertices2d=md.mesh.numberofvertices2d
+		numberofelements2d=md.mesh.numberofelements2d
+	else:
+		numberofvertices2d=npy.nan
+		numberofelements2d=npy.nan
+
+	procdata=npy.copy(data)
+
+	#process patch
+
+	#initialize datatype
+	datatype=0
+
+	#get datasize
+	if npy.ndim(procdata)==1:
+		datasize=npy.array([len(procdata),1])
+	else:
+		datasize=npy.shape(procdata)
+	
+	#process NaN's if any
+	nanfill=options.getfieldvalue('nan',-9999)
+	if npy.any(npy.isnan(procdata)):
+		lb=npy.min(data[~npy.isnan(data)])
+		ub=npy.max(data[~npy.isnan(data)])
+		if lb==ub:
+			lb=lb-0.5
+			ub=ub+0.5
+			nanfill=lb-1
+		procdata[npy.isnan(procdata)]=nanfill
+		options.addfielddefault('clim',[lb,ub])
+		options.addfielddefault('cmap_set_under','1')
+		print "WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan',nan_fill_value in plotmodel call"
+
+	#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(procdata)==2 and npy.shape(procdata)[1]==1:
+		procdata=procdata.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 procdata, datatype
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.m	(revision 18231)
@@ -0,0 +1,82 @@
+function [x y z elements is2d isplanet]=processmesh(md,data,options)
+%PROCESSMESH - process mesh to be plotted
+%
+%   Usage:
+%      [x y z elements is2d]=processmesh(md,data,options)
+%
+%   See also: PLOTMODEL, PROCESSDATA
+
+%some checks
+if md.mesh.numberofvertices==0,
+	error('plot error message: mesh is empty')
+end
+if md.mesh.numberofvertices==md.mesh.numberofelements
+	error(['plot error message: the number of elements is the same as the number of nodes...']);
+end
+
+%special case for mesg 2dvertical
+if strcmp(domaintype(md.mesh),'2Dvertical'),
+	[x y z elements is2d isplanet] = processmesh(md.mesh,options);
+	return;
+end
+
+%first load x,y, etc ... to speed up plot
+if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+	x=md.mesh.x;
+	if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
+	y=md.mesh.y;
+	if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+else
+	x=md.mesh.long;
+	y=md.mesh.lat;
+end
+
+if isprop(md.mesh,'z'),
+	z=md.mesh.z;
+else
+	z=zeros(size(x));
+end
+z=getfieldvalue(options,'z',z);
+if ischar(z),
+	z=md.(z);
+end
+
+if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
+elements=md.mesh.elements;
+
+%is it a 2d plot?
+if md.mesh.dimension()==2,
+	is2d=1;
+else
+	if getfieldvalue(options,'layer',0)>=1,
+		is2d=1;
+	else
+		is2d=0;
+	end
+end
+
+%layer projection? 
+if getfieldvalue(options,'layer',0)>=1,
+	if strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+		error('processmesh error message: cannot work with 3D meshes for now');
+	end
+	%we modify the mesh temporarily to a 2d mesh from which the 3d mesh was extruded. 
+	x=x2d;
+	y=y2d;
+	z=zeros(size(x2d));
+	elements=elements2d;
+end
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if isa(md,'planet'),
+	isplanet=1;
+else
+	isplanet=0;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/processmesh.py	(revision 18231)
@@ -0,0 +1,83 @@
+from math import isnan
+import MatlabFuncs as m
+import numpy as npy
+
+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 'x2d' in dir(md.mesh): x2d=md.mesh.x2d
+			y=md.mesh.y
+			if 'y2d' in dir(md.mesh): y2d=md.mesh.x2d
+		else:
+			x=md.mesh.long
+			y=md.mesh.lat
+
+		if 'z' in dir(md.mesh):
+			z=md.mesh.z
+		else:
+			z=npy.zeros_like(md.mesh.x)
+		
+		if 'elements2d' in dir(md.mesh): 
+			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
+		else:
+			if options.getfieldvalue('layer',0)>=1:
+				is2d=1
+			else:
+				is2d=0
+
+		#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/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_colorbar.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_colorbar.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_colorbar.m	(revision 18231)
@@ -0,0 +1,41 @@
+function quiver_colorbar(quivers,options)
+%QUIVER_COLORBAR - colorbar for quiver plots
+%
+%   Usage:
+%      quiver_colorbar(quivers,options)
+
+if  strcmpi(getfieldvalue(options,'colorbar','on'),'on'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(quivers.levels));
+	for i=1:length(quivers.levels),
+		ticklabel{i}=num2str(round_ice(quivers.levels(i),3));
+	end
+	tickpos=1:quivers.numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(quivers.levels)/4);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+
+	if exist(options,'colorbartitle'),
+		backup=gca;
+		axes(hcb);lab=title(getfieldvalue(options,'colorbartitle'));
+		set(lab,'Rotation',getfieldvalue(options,'colorbartitlerotation',0));
+		set(lab,'VerticalAlignment','bottom');
+		axes(backup);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_process.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_process.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/quiver_process.m	(revision 18231)
@@ -0,0 +1,70 @@
+function [quivers,palette]=quiver_process(x,y,u,v,options)
+%QUIVER_PROCESS - process data for color quiver plot
+%
+%   Usage:
+%      [quivers,palette]=quiver_process(x,y,u,v,options)
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(u) & ~isnan(v));
+x=x(pos); y=y(pos);
+u=u(pos); v=v(pos);
+
+%get Norm Min and Max
+Norm=sqrt(u.^2+v.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%Scale data
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',30);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%create colorind for colors
+colorind=ones(length(u),1);
+for i=1:numcolors
+	pos=find((Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(Norm>levels(end)))=numcolors;
+
+%build output
+quivers=struct('x',x,'y',y,'u',u,'v',v,'levels',levels,'colorind',colorind,'numcolors',numcolors);
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	palette=colormap([0 0 1;1 0 0]);
+elseif numcolors==3,
+	%blue yellow and red
+	palette=colormap([0 0 1;1 1 0;1 0 0]);
+else
+	%let jet choose
+	palette=colormap(jet(numcolors));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/radarpower.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/radarpower.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/radarpower.m	(revision 18231)
@@ -0,0 +1,167 @@
+function md=radarpower(md,varargin)
+%RADARPOWER - overlay a power radar image on an existing mesh
+%
+%   This routine will overlay a power radar image on an existing mesh.
+%   The power amplitude will be output to vel for now.
+%   In the future, think about a field to hold this value.
+%
+%   Usage:
+%      md=radarpower(md,options);
+%      md=radarpower(md)
+
+%Parse inputs
+if nargin==1,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+
+geotiff_name = getfieldvalue(options,'geotiff_name','');
+highres = getfieldvalue(options,'highres',0);
+xlim    = getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+ylim    = getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+posting = getfieldvalue(options,'posting',0); % 0 -> image posting default
+a = getfieldvalue(options,'overlay_adjust_a',0);
+b = getfieldvalue(options,'overlay_adjust_b',1);
+c = getfieldvalue(options,'overlay_adjust_c',0);
+d = getfieldvalue(options,'overlay_adjust_d',1);
+
+%find gdal coordinates
+x0=min(xlim); x1=max(xlim);
+y0=min(ylim); y1=max(ylim);
+
+%figure out if we should go look for Greenland or Antarctica geotiff, or if user provided one.
+if ~exist(options,'overlay_image'),
+	if strcmpi(md.mesh.hemisphere,'n'),
+		%if ~exist(['/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=['/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');
+		%jpgim='/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Russel_asar2010.png';
+		%geom=load('/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Russel_asar2010.pngw');
+
+		%%geom:   xposting nbcols nbrows yposting xmin ymax
+		%xmin=max(geom(5),x0);
+		%xmax=min(geom(5)+geom(1)*geom(2),x1);
+		%ymin=max(geom(6)-geom(3)*geom(4),y0);
+		%ymax=min(geom(6),y1);
+
+		%firstcol=max(1,floor((xmin-geom(5))/geom(1))); %x min
+		%firstrow=max(1,floor((geom(6)-ymax)/geom(4))); %y max
+		%numcols=floor((xmax-xmin)/geom(1)); % x posting
+		%numrows=floor((ymax-ymin)/geom(4)); % y posting
+		%pixelskip=max(1,ceil(posting/geom(1)));
+
+		%%Read and crop file
+		%disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+		%im=imread(jpgim);
+		%im=im(firstrow:firstrow+numrows-1,firstcol:firstcol+numcols-1);
+		%md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		%md.radaroverlay.x=(xmin:(xmax-xmin)/(size(md.radaroverlay.pwr,2)-1):xmax);
+		%md.radaroverlay.y=(ymin:(ymax-ymin)/(size(md.radaroverlay.pwr,1)-1):ymax);
+		if ~exist(options,'geotiff_name'),
+			if highres,
+				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=['/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif'];
+			else
+				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=['/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif'];
+			end
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		%adjust contrast and brightness
+		%im=imadjust(im,[a b],[c d]);
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		if size(im,3)==1,
+			md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		else
+			md.radaroverlay.pwr=double(im(1:pixelskip:end,1:pixelskip:end,1:pixelskip:end));
+			md.radaroverlay.pwr(:,:,1)=flipud(md.radaroverlay.pwr(:,:,1));
+			md.radaroverlay.pwr(:,:,2)=flipud(md.radaroverlay.pwr(:,:,2));
+			md.radaroverlay.pwr(:,:,3)=flipud(md.radaroverlay.pwr(:,:,3));
+		end
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if ~exist(options,'geotiff_name'),
+			if highres,
+				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=['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
+			else
+				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=['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
+			end
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		%adjust contrast and brightness
+		%im=imadjust(im,[a b],[c d]);
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+else
+	%user provided an image. check we also have overlay_xlim and overlay_ylim  options, to know what range of coordinates the image covers.
+	if (~exist(options,'overlay_xlim') | ~exist(options,'overlay_xlim')| ~exist(options,'overlay_xposting')| ~exist(options,'overlay_yposting')),
+		error('radarpower error message: please provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options together with overlay_image option');
+	end
+	overlay_image=getfieldvalue(options,'overlay_image');
+	overlay_xlim=getfieldvalue(options,'overlay_xlim');
+	overlay_ylim=getfieldvalue(options,'overlay_ylim');
+	overlay_xposting=getfieldvalue(options,'overlay_xposting');
+	overlay_yposting=getfieldvalue(options,'overlay_yposting');
+
+	sizex=floor((x1-x0)/overlay_xposting);
+	sizey=floor((y1-y0)/overlay_yposting);
+	topleftx=floor((x0-overlay_xlim(1))/overlay_xposting); % x min
+	toplefty=floor((overlay_ylim(2)-y1)/overlay_yposting); % y max
+
+	%Read and crop file
+	disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	im=imread(overlay_image);
+	%adjust contrast and brightness
+	%im=imadjust(im,[a b],[c d]);
+	im=im(toplefty:toplefty+sizey,topleftx:topleftx+sizex);
+	md.radaroverlay.pwr=double(flipud(im));
+	md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+	md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/scaleruler.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/scaleruler.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/scaleruler.m	(revision 18231)
@@ -0,0 +1,77 @@
+function scaleruler(options)
+%SCALERULER - overlay a scale ruler on current plot
+%
+%   Usage:
+%      scaleruler(options)
+
+%get options
+structure  = getfieldvalue(options,'scaleruler');
+fontcolor  = getfieldvalue(options,'fontcolor','k');
+fontweight = getfieldvalue(options,'fontweight','n');
+fontsize   = getfieldvalue(options,'scaleruler_fontsize',16);
+unitscale  = getfieldvalue(options,'unit',1.);
+
+%Go through structure and fill missing arguments
+if length(structure)~=5
+	error('plotmodel error message: bad number of input arguments for scaleruler: [x0 y0 length thickness numberofticks]');
+end
+
+%retrieve scale parameters
+x0            = double(structure(1))/unitscale;
+y0            = double(structure(2))/unitscale;
+lengthscale   = double(structure(3))/unitscale;
+widthscale    = double(structure(4))/unitscale;
+numberofticks = double(structure(5));
+
+%If only one tick, just draw a rectangle
+if numberofticks==1,
+	text(x0+lengthscale/2,y0+2*widthscale,2,[num2str(lengthscale*unitscale/1000) ' km'],...
+		'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+	patch([x0 x0+lengthscale x0+lengthscale x0],[y0 y0 y0+widthscale y0+widthscale],2*ones(1,4),fontcolor,'Edgecolor',fontcolor);
+else
+	%initialize some coordinates
+	unitlength=lengthscale/(numberofticks -1);
+	flag=-1;
+
+	Bd=[x0 y0];
+	Bu=[x0 y0+widthscale];
+	Tick=0;
+
+	%Text
+	xt=Bu(1);
+	yt=Bu(2)+widthscale;
+	text(xt,yt,2,num2str(Tick),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+
+	%loope over the patches
+	for i=1:numberofticks-1,
+		Au=Bu;
+		Ad=Bd;
+		Bu=[Au(1)+unitlength Ad(2)+widthscale];
+		Bd=[Ad(1)+unitlength Ad(2)];
+		Tick=(Tick+unitlength)*unitscale;
+
+		%pathes
+		if flag==-1
+			p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],2*ones(1,4),'Black');
+		else
+			p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],2*ones(1,4),'White');
+		end
+
+		%flip flag
+		flag=-flag;
+
+		%Text
+		xt=Bu(1);
+		yt=Bu(2)+widthscale;
+		if i~=numberofticks-1,
+			text(xt,yt,2,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+		end
+	end
+	text(xt,yt,2,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+	% add leading spaces depending on length of label string
+	str=' km';
+	for i=1:numel(num2str(round_ice(Tick/1000,3))),
+		str=[' ' str];
+	end
+	text(xt,yt,2,str,'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','left','VerticalAlignment','baseline');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/showregion.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/showregion.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/showregion.m	(revision 18231)
@@ -0,0 +1,34 @@
+function showregion(md,insetpos)
+%SHOWREGION - show region on plot
+%
+%   Usage:
+%      showregion(md,insetpos);
+
+%get inset relative position (x,y,width,height)
+%insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+
+%get current plos position
+cplotpos=get(gca,'pos');
+%compute inset position
+PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+axes('pos',PosInset);
+axis equal off
+%box off
+if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+	A=expread(['/u/astrid-r1b/ModelData/Exp/Greenland.exp']);
+elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+	A=expread(['/u/astrid-r1b/ModelData/Exp/Antarctica.exp']);
+else
+	error('applyoptions error message: hemisphere not defined');
+end
+
+Ax=[min(A.x) max(A.x)];
+Ay=[min(A.y) max(A.y)];
+
+mdx=[min(md.mesh.x) max(md.mesh.x)];
+mdy=[min(md.mesh.y) max(md.mesh.y)];
+
+line(A.x,A.y,'color','b');
+patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
+patch( [mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+colorbar('off');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/squarezoom.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/squarezoom.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/squarezoom.m	(revision 18231)
@@ -0,0 +1,20 @@
+function squarezoom()
+%SQUAREZOOM - zoom on a part of a figure
+%
+%   Usage:
+%      squarezoom()
+
+disp('Click twice to define a square where you want to zoom. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+dx=x(2)-x(1);
+dy=y(1)-y(2);
+
+if dx>dy,
+	delta=dx-dy;
+	xlim([x(1) x(2)]);
+	ylim([y(2)-delta/2 y(1)+delta/2]);
+else
+	delta=dy-dx;
+	xlim([x(1)-delta/2 x(2)+delta/2]);
+	ylim([y(2) y(1)]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/subplotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/subplotmodel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/subplotmodel.m	(revision 18231)
@@ -0,0 +1,41 @@
+function ha=subplotmodel(nlines,ncols,num,options)
+%SUBPLOTMODEL -  tight subplot that includes margins
+%
+%   Usage:
+%      h=subplotmodel(nlines,ncols,i,options)
+
+%Regular subplot
+if ~exist(options,'tightsubplot')
+	if exist(options,'asymsubplot')
+		id=getfieldvalue(options,'asymsubplot',num);
+		subplot(nlines,ncols,id);
+		return
+	else
+		subplot(nlines,ncols,num);
+		return;
+	end
+end
+
+gap     = getfieldvalue(options,'gap',[.01 .01]);
+hmargin = getfieldvalue(options,'hmargin',[.01 .01]);
+vmargin = getfieldvalue(options,'vmargin',[.01 .01]);
+
+height = (1-sum(vmargin)-(nlines-1)*gap(1))/nlines; 
+width  = (1-sum(hmargin)-(ncols-1)*gap(2))/ncols;
+ymin   = 1-vmargin(2)-height; 
+
+for i = 1:nlines
+	xmin = hmargin(1);
+	for j = 1:ncols
+		if(((i-1)*ncols+j)==num)
+			ha = axes('Units','normalized', ...
+				'Position',[xmin ymin width height],'XTickLabel','','YTickLabel','','Visible','off');
+			return
+		end
+		xmin = xmin+width+gap(2);
+	end
+	ymin = ymin-height-gap(1);
+end
+
+%Activate new axes
+axes(ha);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/vim.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/vim.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/plot/vim.m	(revision 18231)
@@ -0,0 +1,3 @@
+function vim(index,x,y,field)
+
+trisurf(index,x,y,field),view(2),shading interp, colorbar;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/print/export_geotiff.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/print/export_geotiff.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/print/export_geotiff.m	(revision 18231)
@@ -0,0 +1,24 @@
+function export_geotiff(filename,ref)
+%EXPORT_GEOTIF - export geotiff 
+%
+%   Usage:
+%      export_geotif(filename,ref);
+%
+%      This function must be called after plotmodel
+%      filname: no extension
+%      ref:     UPS Greenland  EPSG:3413 (http://www.spatialreference.org/ref/epsg/3413/)
+%               UPS Antarctica EPSG:3031 (http://www.spatialreference.org/ref/epsg/3031/)
+%
+%   Example:
+%      export_geotif('Greenland','EPSG:3413');
+
+%Get axis limits and convert to strings
+XLIM = xlim(); x0 = num2str(XLIM(1)); x1 = num2str(XLIM(2));
+YLIM = ylim(); y0 = num2str(YLIM(1)); y1 = num2str(YLIM(2));
+
+%first export the figure
+export_fig([filename '.jpg']);
+
+%call gdal on this: 
+system(['gdal_translate -a_srs ' ref ' -of GTiff -co "INTERLEAVE=PIXEL" -a_ullr ' x0 ' ' y1 ' ' x1 ' ' y0 ' ' filename '.jpg ' filename '.tif']);
+system(['rm -rf ' filename '.jpg']);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/print/printmodel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/print/printmodel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/print/printmodel.m	(revision 18231)
@@ -0,0 +1,98 @@
+function printmodel(filename,format,varargin)
+%PRINTMODEL - save an image of current figure
+%
+%   filename: output name of image file (no extension)
+%   format: image format (ex: 'tiff','jpg','pdf') 
+%
+%   List of options to printfmodel: 
+%
+%   figure: number of figure to print (default: current figure)
+%   resolution: use higher resolution to anti-alias (default 2)
+%   margin: add margin around final image  
+%   marginsize: size of margin around final image (default 5)
+%   frame: add frame around final image
+%   framesize: size of frame around final image (default 5)
+%   framecolor: color of frame around final image (default 'black')
+%   trim: trim empty space around image (default 'off')
+%   hardcopy: 'off' to impose MATLAB to use the same colors (default 'off')
+%   
+%   Usage:
+%      printmodel(filename,format,varargin);
+%
+%   Examples:
+%      printmodel('image','tiff')
+%      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'figure','gcf');
+options=addfielddefault(options,'format','tiff');
+options=addfielddefault(options,'resolution',1);
+options=addfielddefault(options,'margin','on');
+options=addfielddefault(options,'marginsize',25);
+options=addfielddefault(options,'frame','on');
+options=addfielddefault(options,'framesize',3);
+options=addfielddefault(options,'framecolor','black');
+options=addfielddefault(options,'trim','on');
+options=addfielddefault(options,'hardcopy','off');
+
+%get fig: 
+fig=getfieldvalue(options,'figure');
+if ischar(fig),
+	fig=gcf;
+else
+	figure(fig);
+	fig=gcf;
+end
+
+%In auto mode, MATLAB prints the figure the same size as it appears on the computer screen, centered on the page
+set(fig, 'PaperPositionMode', 'auto');
+
+%InvertHardcopy off imposes MATLAB to use the same colors
+set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
+
+%we could have several formats, as a cell array of strings.
+formats=format;
+if ~iscell(formats),
+	formats={formats};
+end
+
+%loop on formats:
+for i=1:length(formats),
+	format=formats{i};
+
+	%Use higher resolution to anti-alias and use zbuffer to have smooth colors
+	print(fig, '-zbuffer','-dtiff',['-r' num2str(get(0,'ScreenPixelsPerInch')*getfieldvalue(options,'resolution'))],filename);
+
+	%some trimming involved? 
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'trim'),'on'),
+			system(['convert -trim ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%margin?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'margin'),'on'),
+			marginsize=getfieldvalue(options,'marginsize');
+			system(['convert -border ' num2str(marginsize) 'x' num2str(marginsize) ' -bordercolor "white" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%frame?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'frame'),'on'),
+			framesize=getfieldvalue(options,'framesize');
+			framecolor=getfieldvalue(options,'framecolor');
+			system(['convert -border ' num2str(framesize) 'x' num2str(framesize) ' -bordercolor "' framecolor '" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%convert image to correct format
+	if ~strcmpi(format,'tiff') & ~strcmpi(format,'tif'),
+		system(['convert ' filename '.tif ' filename '.' format]);
+		delete([ filename '.tif']);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/MassFluxProcessProfile.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/MassFluxProcessProfile.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/MassFluxProcessProfile.m	(revision 18231)
@@ -0,0 +1,13 @@
+function segments=MassFluxProcessProfile(md,directory,profilename)
+%MASSFLUXPROCESSPROFILE: process an argus domain outlien profile into a list of segments.
+%
+% Usage: segments=MassFluxProcessProfile(md);
+%
+%
+% See also: PROCESS_QMU_RESPONSE_DATA, PREQMU
+
+%first read the profile points.
+profile=expread([directory '/' profilename]);
+
+%project this profile onto mesh.
+segments=ProfileProjectOntoMesh(md,profile);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_cdfs.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_cdfs.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_cdfs.m	(revision 18231)
@@ -0,0 +1,330 @@
+%
+%  calculate the same cumulative distribution functions that dakota
+%  calculates for given responses, probabilities, reliabilities, and/or
+%  general reliabilities.
+%
+%  [dresp]=dakota_cdfs(method,dresp      ,resp,prob,rel,grel)
+%  [cdf  ]=dakota_cdfs(method,samp       ,resp,prob,rel,grel)
+%  [cdf  ]=dakota_cdfs(method,mean,stddev,resp,prob,rel,grel)
+%
+%  the required input is:
+%    method        (char, 'nond_sampling' or 'nond_local_reliability')
+%    dresp         (structure array, responses)
+%      or
+%    samp          (double array, lists of samples)
+%      or
+%    mean          (double vector, means)
+%    stddev        (double vector, standard deviations)
+%    resp          (double vector, list of responses)
+%    prob          (double vector, list of probabilities)
+%    rel           (double vector, list of reliabilities)
+%    grel          (double vector, list of general reliabilities)
+%
+%  and the optional input is:
+%    alpha         (numeric, confidence interval of 100(1-alpha)%)
+%
+%  the required field of dresp is (for nond_sampling):
+%    sample        (double vector, list of samples)
+%  or (for nond_local_reliability):
+%    mean          (double, mean of samples)
+%    stddev        (double, standard deviation of samples)
+%
+%  the required output is:
+%    dresp         (structure array, responses)
+%      or
+%    cdf(:,4)      (double, array of resp/prob/rel/grel)
+%
+%  and the output fields of dresp are:
+%    cdf(:,4)      (double, array of resp/prob/rel/grel)
+%
+%  for each response (or column of data) in the input array, this
+%  function calculates the responses, probabilities, reliabilities
+%  and general reliabilities for the cumulative distribution function,
+%  the same way as dakota would.  if the input is a structure, the
+%  output is a field in the structure; if the input is arrays, the
+%  output is an array.
+%
+%  dresp data would typically be contained in the dakota tabular
+%  output file from a sampling analysis, or in the dakota output file
+%  from a local reliability analysis, either read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [varargout]=dakota_cdfs(varargin)
+
+if ~nargin
+    help dakota_cdfs
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if ischar(varargin{iarg})
+    method=varargin{iarg};
+    iarg=iarg+1;
+    if ~strncmpi(method,'nond_s',6) && ~strncmpi(method,'nond_l',6)
+        error(['Method ''' method ''' is unrecognized.']);
+    end
+else
+    method='';
+end
+
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+else
+    if     strncmpi(method,'nond_s',6)
+        samp=varargin{iarg};
+        iarg=iarg+1;
+    elseif strncmpi(method,'nond_l',6)
+        mean  =varargin{iarg};
+        iarg=iarg+1;
+        stddev=varargin{iarg};
+        iarg=iarg+1;
+    end
+end
+
+if iarg <= nargin && isnumeric(varargin{iarg})
+    resp=varargin{iarg};
+    iarg=iarg+1;
+else
+    resp=[];
+end
+if iarg <= nargin && isnumeric(varargin{iarg})
+    prob=varargin{iarg};
+    iarg=iarg+1;
+else
+    prob=[];
+end
+if iarg <= nargin && isnumeric(varargin{iarg})
+    rel =varargin{iarg};
+    iarg=iarg+1;
+else
+    rel =[];
+end
+if iarg <= nargin && isnumeric(varargin{iarg})
+    grel=varargin{iarg};
+    iarg=iarg+1;
+else
+    grel=[];
+end
+
+%%  calculate the cumulative distribution functions by input type
+
+if     exist('dresp','var') && ~isempty(dresp)
+    if     strncmpi(method,'nond_s',6)
+        for i=1:length(dresp)
+            [dresp(i).cdf]=cdfs_samp_calc(dresp(i).sample,...
+                resp,prob,rel,grel);
+        end
+    elseif strncmpi(method,'nond_l',6)
+        for i=1:length(dresp)
+            [dresp(i).cdf]=cdfs_lr_calc(dresp(i).mean,dresp(i).stddev,...
+                resp,prob,rel,grel);
+        end
+    end
+
+    varargout{1}=dresp;
+
+elseif exist('samp','var') && ~isempty(samp)
+    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),...
+              4,size(samp,2));
+
+    for i=1:size(samp,2)
+        [cdf(:,:,i)]=cdfs_samp_calc(samp(:,i),...
+            resp,prob,rel,grel);
+    end
+
+    varargout{1}=cdf;
+
+elseif exist('mean','var'  ) && ~isempty(mean  ) && ...
+       exist('stddev','var') && ~isempty(stddev)
+    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),...
+              4,length(mean));
+
+    for i=1:length(mean)
+        [cdf(:,:,i)]=cdfs_lr_calc(mean(i),stddev(i),...
+            resp,prob,rel,grel);
+    end
+
+    varargout{1}=cdf;
+else
+    error(['Empty data ''' inputname(2) ''' of type ''' class(varargin{2}) '''.']);
+end
+
+end
+
+%%  function to calculate the results for a sampling analysis
+
+function [cdf]=cdfs_samp_calc(samp,resp,prob,rel,grel)
+
+%  sort the samples and remove any NaN padding (should only occur at end)
+
+    samp=sort(samp(~isnan(samp(:))),'ascend');
+    nsamp=length(samp);
+
+    mu   =mean(samp);
+    sigma=std(samp);
+
+    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),4);
+    cdf(:,:)=NaN;
+    irow=0;
+
+%  compute quantities, given response levels
+
+    for i=1:length(resp)
+        irow=irow+1;
+        indx=bin_search_val(resp(i),samp);
+        cdf(irow,1)=resp(i);
+        cdf(irow,2)=indx/nsamp;
+        cdf(irow,3)=(mu-resp(i))/sigma;
+%        cdf(irow,4)=-sqrt(2)*erfinv((indx-nsamp/2)/(nsamp/2));
+        cdf(irow,4)=sqrt(2)*erfcinv(indx/(nsamp/2));
+    end
+
+%  compute response levels, given probabilities
+
+    for i=1:length(prob)
+        irow=irow+1;
+%  why not round(prob(i)*(nsamp-1)+1)?
+        indx=ceil(prob(i)*(nsamp));
+        if     (indx < 1)
+            indx=1;
+        elseif (indx > nsamp)
+            indx=nsamp;
+        end
+        cdf(irow,1)=samp(indx);
+        cdf(irow,2)=prob(i);
+    end
+
+%  compute response levels, given reliabilities
+
+    for i=1:length(rel)
+        irow=irow+1;
+        cdf(irow,1)=mu-sigma*rel(i);
+        cdf(irow,3)=rel(i);
+    end
+
+%  compute response levels, given general reliabilities
+
+    for i=1:length(grel)
+        irow=irow+1;
+%         indx=ceil(nsamp/2+nsamp/2*erf(-grel(i)/sqrt(2)));
+        indx=ceil((nsamp/2)*erfc(grel(i)/sqrt(2)));
+        if     (indx < 1)
+            indx=1;
+        elseif (indx > nsamp)
+            indx=nsamp;
+        end
+        cdf(irow,1)=samp(indx);
+        cdf(irow,4)=grel(i);
+    end
+
+end
+
+%%  function to calculate the results for a local reliability analysis
+
+function [cdf]=cdfs_lr_calc(mu,sigma,resp,prob,rel,grel)
+
+    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),4);
+    irow=0;
+
+%  compute quantities, given response levels
+
+    for i=1:length(resp)
+        irow=irow+1;
+        cdf(irow,1)=resp(i);
+        cdf(irow,2)=normcdf_issm(resp(i),mu,sigma);
+        cdf(irow,3)=(mu-resp(i))/sigma;
+        cdf(irow,4)=(mu-resp(i))/sigma;
+    end
+
+%  compute quantities, given probabilities
+
+    for i=1:length(prob)
+        irow=irow+1;
+        cdf(irow,1)=norminv_issm(prob(i),mu,sigma);
+        cdf(irow,2)=prob(i);
+        cdf(irow,3)=-norminv_issm(prob(i),0,1);
+        cdf(irow,4)=-norminv_issm(prob(i),0,1);
+    end
+
+%  compute quantities, given reliabilities
+
+    for i=1:length(rel)
+        irow=irow+1;
+        cdf(irow,1)=mu-sigma*rel(i);
+        cdf(irow,2)=normcdf_issm(-rel(i),0,1);
+        cdf(irow,3)=rel(i);
+        cdf(irow,4)=rel(i);
+    end
+
+%  compute quantities, given general reliabilities
+
+    for i=1:length(grel)
+        irow=irow+1;
+        cdf(irow,1)=mu-sigma*grel(i);
+        cdf(irow,2)=normcdf_issm(-grel(i),0,1);
+        cdf(irow,3)=grel(i);
+        cdf(irow,4)=grel(i);
+    end
+
+end
+%%
+%  function to perform a recursive binary search for a matrix of values
+%  in an ordered vector (loop separately outside of recursion for
+%  efficiency purposes)
+%
+%  function [ind]=bin_search(val,vect)
+%
+function [ind]=bin_search(val,vect)
+
+ind=zeros(size(val));
+
+for i=1:numel(val)
+    ind(i)=bin_search_val(val(i),vect);
+end
+
+end
+%%
+%  function to perform a recursive binary search in an ordered vector,
+%  returning low if value does not exist (more efficient than find or
+%  ismember, which must use linear searches and/or sort)
+%
+%  function [ind]=bin_search_val(val,vect)
+%
+function [ind]=bin_search_val(val,vect)
+
+imid=floor((1+length(vect))/2);
+
+if (val == vect(imid))
+    ind=imid;
+elseif (val < vect(imid))
+    if (imid > 1)
+        ind=     bin_search(val,vect(1:imid-1));
+    else
+        ind=0;
+    end
+elseif (val > vect(imid))
+    if (imid < length(vect))
+        ind=imid+bin_search(val,vect(imid+1:length(vect)));
+    else
+        ind=length(vect);
+    end
+else
+    ind=NaN;
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_data.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_data.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_data.m	(revision 18231)
@@ -0,0 +1,122 @@
+%
+%  define the data to write the dakota .in and .m files.
+%
+%  []=dakota_in_data(dmeth,variables,responses,dparams,filei,varargin)
+%
+%  where the required input is:
+%    dmeth         (dakota_method, method class object)
+%    variables     (structure array, variable class objects)
+%    responses     (structure array, response class objects)
+%    dparams       (structure array, method-independent parameters)
+%    filei         (character, name of .in and .m files)
+%
+%  params may be empty, in which case defaults will be used.
+%
+%  the optional varargin are passed directly through to the
+%  QmuUpdateFunctions brancher to be used by the analysis
+%  package.  for example, this could be model information.
+%
+%  this function defines the data to write the dakota .in and
+%  .m files.  it is necessary for multiple reasons.  first,
+%  it collects the parameters and applies some defaults that
+%  are unique to the environment.  second, some analysis package
+%  variables and/or responses may be treated differently by
+%  dakota.  for example, an analysis package variable may be
+%  defined as an array, so the QmuSetupDesign brancher will
+%  create dakota variables for each element of the array.
+%  finally it calls the functions to write the .in and .m files.
+%  this function is independent of the particular analysis
+%  package.
+%
+%  this data would typically be generated by a matlab script
+%  for a specific model, using the method, variable, and
+%  response class objects.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=dakota_in_data(dmeth,variables,responses,dparams,filei,varargin)
+
+if ~nargin
+    help dakota_in_data
+    return
+end
+
+%%  parameters
+
+%  get default set of parameters
+
+params=dakota_in_params(struct());
+
+%  merge specified parameters into default set, whether or not
+%  they already exist
+
+fnames=fieldnames(dparams);
+
+for i=1:numel(fnames)
+    if ~isfield(params,fnames{i})
+        warning('dakota_in_data:unknown_param',...
+            'No parameter ''%s'' in default parameter set.',...
+            fnames{i});
+    end
+    params.(fnames{i})=dparams.(fnames{i});
+end
+
+if params.direct && ...
+   isempty(params.analysis_driver)
+    params.analysis_driver='matlab';
+end
+
+if strcmpi(params.analysis_driver,'matlab') && ...
+   isempty(params.analysis_components)
+    [pathstr,name,ext] = fileparts(filei);
+    params.analysis_components=fullfile(pathstr,[name '.m']);
+end
+
+%  merge method parameters, though they shouldn't be in dparams
+
+% dmeth=dmeth_params_merge(dmeth,dparams)
+
+%%  variables
+
+fnames=fieldnames(variables);
+
+for i=1:length(fnames)
+
+%  currently all variable types can just be copied
+	dvar.(fnames{i})=variables.(fnames{i});
+
+end
+
+%%  responses
+
+fnames=fieldnames(responses);
+
+for i=1:length(fnames)
+%     fhandle=str2func([class(responses.(fnames{i})) '.empty']);
+%     dresp.(fnames{i})=fhandle();
+%     for j=1:length(responses.(fnames{i}))
+%         dresp.(fnames{i})(j)=responses.(fnames{i})(j);
+%     end
+
+%  currently all response types can just be copied
+
+    dresp.(fnames{i})=responses.(fnames{i});
+end
+
+%%  write files
+
+%Write in file
+dakota_in_write(dmeth,dvar,dresp,params,filei,varargin{:});
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_params.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_params.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_params.m	(revision 18231)
@@ -0,0 +1,210 @@
+%
+%  populate a Dakota parameter structure.
+%
+%  [params]=dakota_in_params(params)
+%
+%  where the optional input is:
+%    params        (structure array, method-independent parameters)
+%
+%  and the output is the same.
+%
+%  this function takes a structure of method-independent dakota
+%  parameters, which may be empty, and adds default parameters
+%  for those parameters which do not exist.
+%
+%  the field names of the structure are identical to the dakota
+%  parameter names (and are in fact used to write them to the
+%  files).  logical values are used for parameters which have
+%  no associated data and are determined only by their presence
+%  or absence.
+%
+%  note that the method-dependent parameters are contained in
+%  the dakota_method class object.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [params]=dakota_in_params(params)
+
+if ~nargin
+    help dakota_in_params
+    return
+end
+
+%%  process the input parameters
+
+if ~exist('params','var')
+    params=struct();
+end
+
+%%  strategy section
+
+if ~isfield(params,'graphics')
+    params.graphics=false;
+end
+if ~isfield(params,'tabular_graphics_data')
+    params.tabular_graphics_data=false;
+end
+% could use unique file name rather than 'dakota_tabular.dat'
+if ~isfield(params,'tabular_graphics_file')
+    params.tabular_graphics_file=false;
+end
+
+%%  method section
+
+%  nearly all method parameters are in the dakota_method class
+%  or result from the response level lists
+
+if ~isfield(params,'compute')
+    params.compute='probabilities';
+end
+if ~isfield(params,'distribution')
+    params.distribution='cumulative';
+end
+
+%%  model section
+
+%%  interface section
+
+if ~isfield(params,'system')
+    params.system=false;
+end
+if ~isfield(params,'fork')
+    params.fork=false;
+end
+if ~isfield(params,'direct')
+    params.direct=false;
+end
+
+%  interface parallelism controls
+
+if ~isfield(params,'asynchronous')
+    params.asynchronous=true;
+end
+if ~isfield(params,'evaluation_concurrency')
+    params.evaluation_concurrency=false;
+end
+if ~isfield(params,'analysis_concurrency')
+    params.analysis_concurrency=false;
+end
+if ~isfield(params,'evaluation_servers')
+    params.evaluation_servers=false;
+end
+if ~isfield(params,'evaluation_self_scheduling')
+    params.evaluation_self_scheduling=false;
+end
+if ~isfield(params,'evaluation_static_scheduling')
+    params.evaluation_static_scheduling=true;
+end
+
+if ~isfield(params,'analysis_servers')
+    params.analysis_servers=false;
+end
+if ~isfield(params,'analysis_self_scheduling')
+    params.analysis_self_scheduling=false;
+end
+if ~isfield(params,'analysis_static_scheduling')
+    params.analysis_static_scheduling=false;
+end
+
+%  algebraic mappings
+
+if ~isfield(params,'algebraic_mappings')
+    params.algebraic_mappings=false;
+end
+
+%  simulation interface controls
+
+if ~isfield(params,'analysis_driver')
+    params.analysis_driver='';
+end
+if ~isfield(params,'analysis_components')
+    params.analysis_components='';
+end
+if ~isfield(params,'input_filter')
+    params.input_filter='';
+end
+if ~isfield(params,'output_filter')
+    params.output_filter='';
+end
+
+if ~isfield(params,'failure_capture')
+    params.failure_capture='abort';
+end
+if ~isfield(params,'deactivate')
+    params.deactivate='evaluation_cache restart_file';
+end
+
+%  system call or fork interface
+
+if ~isfield(params,'parameters_file')
+    params.parameters_file='params.in';
+end
+if ~isfield(params,'results_file')
+    params.results_file='results.out';
+end
+if ~isfield(params,'verbatim')
+    params.verbatim=false;
+end
+if ~isfield(params,'aprepro')
+    params.aprepro=false;
+end
+if ~isfield(params,'file_tag')
+    params.file_tag=true;
+end
+if ~isfield(params,'file_save')
+    params.file_save=true;
+end
+
+%  direct function interface
+
+if ~isfield(params,'processors_per_analysis')
+    params.processors_per_analysis=false;
+end
+
+%%  responses section
+
+if ~isfield(params,'numerical_gradients')
+    params.numerical_gradients=false;
+end
+if ~isfield(params,'method_source')
+    params.method_source='dakota';
+end
+if ~isfield(params,'interval_type')
+    params.interval_type='forward';
+end
+if ~isfield(params,'fd_gradient_step_size')
+    params.fd_gradient_step_size=0.001;
+end
+if ~isfield(params,'analytic_gradients')
+    params.analytic_gradients=false;
+end
+%  mixed_gradients not fully implemented
+if ~isfield(params,'mixed_gradients')
+    params.mixed_gradients=false;
+end
+if ~isfield(params,'id_analytic_gradients')
+    params.id_analytic_gradients=false;
+end
+if ~isfield(params,'id_numerical_gradients')
+    params.id_numerical_gradients=false;
+end
+%  hessians not fully implemented
+if ~isfield(params,'numerical_hessians')
+    params.numerical_hessians=true;
+end
+if ~isfield(params,'hessian_gradient_step_size')
+    params.hessian_gradient_step_size=0.001;
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_parse.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_parse.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_parse.m	(revision 18231)
@@ -0,0 +1,803 @@
+%
+%  read a Dakota .in input file and parse it.
+%
+%  [method,dvar,dresp]=dakota_in_parse(filei)
+%
+%  where the required input is:
+%    filei         (character, name of .in file)
+%
+%  the required output is:
+%    method        (character, dakota method name)
+%    dvar          (structure array, variables)
+%    dresp         (structure array, responses)
+%
+%  the filei will be prompted if empty.  the fields of dvar and
+%  dresp are particular to the data contained within the file.
+%
+%  this function reads a dakota .in input file and parses it
+%  into the matlab workspace.  it operates in a content-driven
+%  fashion, where it parses whatever input data it encounters
+%  in the file, rather than searching for data based on the
+%  particular method.  (this makes it independent of method.)
+%
+%  as of now, parameters are generally not parsed.  also, the
+%  variable and response classes are not used for output.
+%
+%  this data would typically be used for modifying and submitting
+%  a subsequent dakota run.  it could also be used with output
+%  data for post-processing or annotation purposes.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [method,dvar,dresp]=dakota_in_parse(filei)
+
+if ~nargin
+    help dakota_in_parse
+    return
+end
+
+if ~exist('filei' ,'var') || isempty(filei)
+    filei=input('Input file?  ','s');
+end
+fidi=fopen(sprintf('%s',filei),'r');
+if (fidi < 0)
+    error('%s could not be opened.',filei);
+end
+
+%%  loop through the file to find the Dakota method
+
+method=[];
+fseek(fidi,0,'bof');
+[fline]=findline(fidi,'method');
+if ~ischar(fline)
+    return
+end
+
+[ntokens,tokens]=fltokens(fline);
+itoken=1;
+[tokens,itoken]=nextkey(fidi,tokens,itoken);
+method=tokens{1}{itoken};
+display(sprintf('Dakota method=%s.',method));
+
+%%  loop through the file to find the Dakota variables
+
+fseek(fidi,0,'bof');
+[fline]=findline(fidi,'variables');
+if ~ischar(fline)
+    error('No Dakota variables in file %s.',filei);
+end
+
+[ntokens,tokens]=fltokens(fline);
+itoken=1;
+[dvar]=variables_parse(fidi,tokens,itoken);
+
+%%  loop through the file to find the Dakota responses
+
+fseek(fidi,0,'bof');
+[fline]=findline(fidi,'responses');
+if ~ischar(fline)
+    error('No Dakota responses in file %s.',filei);
+end
+
+[ntokens,tokens]=fltokens(fline);
+itoken=1;
+[dresp]=responses_parse(fidi,tokens,itoken);
+
+%%  loop through the file to find the Dakota response and probability levels
+%   (even though they're in method section, process after responses)
+
+fseek(fidi,0,'bof');
+[fline]=findline(fidi,'method');
+
+[ntokens,tokens]=fltokens(fline);
+itoken=1;
+[dresp]=resplevels(fidi,tokens,itoken,dresp);
+
+%%  loop through the file to verify the end
+
+display('End of file successfully reached.');
+fclose(fidi);
+
+end
+
+%%  function to parse the dakota variables
+
+function [dvar]=variables_parse(fidi,tokens,itoken)
+
+display('Reading Dakota variables.');
+dvar=[];
+ncdv=0;
+nnuv=0;
+ncsv=0;
+
+%  read next keyword
+
+[tokens,itoken]=nextkey(fidi,tokens,itoken);
+if ~itoken
+    warning('variables_parse:empty',...
+        'Dakota variables section is empty.');
+end
+
+%  process current keyword
+%  (note that this is using dakota 4.1 keywords.  dakota 4.2
+%  keywords are order-dependent.)
+
+while itoken
+    keyword=tokens{1}{itoken};
+    display(sprintf('  Dakota keyword=%s.',keyword));
+
+%  switch according to the keyword
+
+    switch lower(keyword)
+        case 'continuous_design'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            ncdv=tlist;
+            dvar.cdv=[];
+            display(sprintf('    Number of Dakota %s variables=%d.',...
+                    'continuous_design',ncdv));
+        case 'cdv_initial_point'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.cdv(i).initpt    =tlist(i);
+            end
+        case 'cdv_lower_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.cdv(i).lower     =tlist(i);
+            end
+        case 'cdv_upper_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.cdv(i).upper     =tlist(i);
+            end
+        case 'cdv_descriptors'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.cdv(i).descriptor=char(tlist(i));
+            end
+
+        case 'normal_uncertain'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nnuv=tlist;
+            dvar.nuv=[];
+            display(sprintf('    Number of Dakota %s variables=%d.',...
+                    'normal_uncertain',nnuv));
+        case 'nuv_means'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.nuv(i).mean      =tlist(i);
+            end
+        case 'nuv_std_deviations'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.nuv(i).stddev    =tlist(i);
+            end
+        case 'nuv_lower_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.nuv(i).lower     =tlist(i);
+            end
+        case 'nuv_upper_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.nuv(i).upper     =tlist(i);
+            end
+        case 'nuv_descriptors'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.nuv(i).descriptor=char(tlist(i));
+            end
+
+        case 'continuous_state'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            ncsv=tlist;
+            dvar.csv=[];
+            display(sprintf('    Number of Dakota %s variables=%d.',...
+                    'continuous_state',ncsv));
+        case 'csv_initial_state'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.csv(i).initst    =tlist(i);
+            end
+        case 'csv_lower_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.csv(i).lower     =tlist(i);
+            end
+        case 'csv_upper_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.csv(i).upper     =tlist(i);
+            end
+        case 'csv_descriptors'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dvar.csv(i).descriptor=char(tlist(i));
+            end
+
+        otherwise
+            warning('variables_parse:unrec_key',...
+                'Unrecognized keyword ''%s''.',keyword);
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+    end
+
+%  check for eof or start of new section
+
+    if (~itoken) || ...
+       strncmpi(tokens{1}{itoken},'strategy' ,8) || ...
+       strncmpi(tokens{1}{itoken},'method'   ,6) || ...
+       strncmpi(tokens{1}{itoken},'model'    ,5) || ...
+       strncmpi(tokens{1}{itoken},'variables',9) || ...
+       strncmpi(tokens{1}{itoken},'interface',9) || ...
+       strncmpi(tokens{1}{itoken},'responses',9)
+
+%  supply default descriptors if necessary
+
+        if isfield(dvar,'cdv') && ~isfield(dvar.cdv,'descriptor')
+            for i=1:ncdv
+                dvar.cdv(i).descriptor=sprintf('cdv_%d',i);
+            end
+        end
+        if isfield(dvar,'nuv') && ~isfield(dvar.nuv,'descriptor')
+            for i=1:nnuv
+                dvar.nuv(i).descriptor=sprintf('nuv_%d',i);
+            end
+        end
+        if isfield(dvar,'csv') && ~isfield(dvar.csv,'descriptor')
+            for i=1:ncsv
+                dvar.csv(i).descriptor=sprintf('csv_%d',i);
+            end
+        end
+        return;
+    end
+end
+
+end
+
+%%  function to parse the dakota responses
+
+function [dresp]=responses_parse(fidi,tokens,itoken)
+
+display('Reading Dakota responses.');
+dresp=[];
+nof =0;
+nlst=0;
+nnic=0;
+nnec=0;
+nrf =0;
+
+%  read next keyword
+
+[tokens,itoken]=nextkey(fidi,tokens,itoken);
+if ~itoken
+    warning('responses_parse:empty',...
+        'Dakota responses section is empty.');
+end
+
+%  process current keyword
+
+while itoken
+    keyword=tokens{1}{itoken};
+    display(sprintf('  Dakota keyword=%s.',keyword));
+
+%  switch according to the keyword
+
+    switch lower(keyword)
+        case 'num_objective_functions'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nof =tlist;
+            dresp.of =[];
+            display(sprintf('    Number of Dakota %s=%d.',...
+                    'objective_functions',nof));
+        case 'objective_function_scale_types'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.of(i).scale_type=char(tlist(i));
+            end
+        case 'objective_function_scales'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.of(i).scale     =tlist(i);
+            end
+        case 'multi_objective_weights'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.of(i).weight    =tlist(i);
+            end
+
+        case 'num_least_squares_terms'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nlst=tlist;
+            dresp.lst=[];
+            display(sprintf('    Number of Dakota %s=%d.',...
+                    'least_squares_terms',nlst));
+        case 'least_squares_term_scale_types'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.lst(i).scale_type=char(tlist(i));
+            end
+        case 'least_squares_term_scales'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.lst(i).scale     =tlist(i);
+            end
+        case 'least_squares_weights'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.lst(i).weight    =tlist(i);
+            end
+
+        case 'num_nonlinear_inequality_constraints'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nnic=tlist;
+            dresp.nic=[];
+            display(sprintf('    Number of Dakota %s=%d.',...
+                    'nonlinear_inequality_constraints',nnic));
+        case 'nonlinear_inequality_scale_types'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nic(i).scale_type=char(tlist(i));
+            end
+        case 'nonlinear_inequality_scales'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nic(i).scale     =tlist(i);
+            end
+        case 'nonlinear_inequality_lower_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nic(i).lower     =tlist(i);
+            end
+        case 'nonlinear_inequality_upper_bounds'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nic(i).upper     =tlist(i);
+            end
+
+        case 'num_nonlinear_equality_constraints'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nnec=tlist;
+            dresp.nec=[];
+            display(sprintf('    Number of Dakota %s=%d.',...
+                    'nonlinear_equality_constraints',nnec));
+        case 'nonlinear_equality_scale_types'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nec(i).scale_type=char(tlist(i));
+            end
+        case 'nonlinear_equality_scales'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nec(i).scale     =tlist(i);
+            end
+        case 'nonlinear_equality_targets'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            for i=1:length(tlist)
+                dresp.nec(i).target    =tlist(i);
+            end
+
+        case 'num_response_functions'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nrf =tlist;
+            dresp.rf =[];
+            display(sprintf('    Number of Dakota %s=%d.',...
+                    'response_functions',nrf));
+
+        case 'response_descriptors'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            desc=tlist;
+        otherwise
+            warning('responses_parse:unrec_key',...
+                'Unrecognized keyword ''%s''.',keyword);
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+    end
+
+%  check for eof or start of new section
+
+    if (~itoken) || ...
+       strncmpi(tokens{1}{itoken},'strategy' ,8) || ...
+       strncmpi(tokens{1}{itoken},'method'   ,6) || ...
+       strncmpi(tokens{1}{itoken},'model'    ,5) || ...
+       strncmpi(tokens{1}{itoken},'variables',9) || ...
+       strncmpi(tokens{1}{itoken},'interface',9) || ...
+       strncmpi(tokens{1}{itoken},'responses',9)
+
+%  assign specified or supply default descriptors
+
+        if exist('desc','var')
+            idesc=0;
+            if isfield(dresp,'of' )
+                for i=1:nof
+                    idesc=idesc+1;
+                    dresp.of(i).descriptor=char(desc(idesc));
+                end
+            end
+            if isfield(dresp,'lst')
+                for i=1:nlst
+                    idesc=idesc+1;
+                    dresp.lst(i).descriptor=char(desc(idesc));
+                end
+            end
+            if isfield(dresp,'nic')
+                for i=1:nnic
+                    idesc=idesc+1;
+                    dresp.nic(i).descriptor=char(desc(idesc));
+                end
+            end
+            if isfield(dresp,'nec')
+                for i=1:nnec
+                    idesc=idesc+1;
+                    dresp.nec(i).descriptor=char(desc(idesc));
+                end
+            end
+            if isfield(dresp,'rf' )
+                for i=1:nrf
+                    idesc=idesc+1;
+                    dresp.rf(i).descriptor=char(desc(idesc));
+                end
+            end
+
+        else
+            if isfield(dresp,'of' )
+                for i=1:nof
+                    dresp.of(i).descriptor=sprintf('obj_fn_%d',i);
+                end
+            end
+            if isfield(dresp,'lst')
+                for i=1:nlst
+                    dresp.lst(i).descriptor=sprintf('least_sq_term_%d',i);
+                end
+            end
+            if isfield(dresp,'nic')
+                for i=1:nnic
+                    dresp.nic(i).descriptor=sprintf('nln_ineq_con_%d',i);
+                end
+            end
+            if isfield(dresp,'nec')
+                for i=1:nnec
+                    dresp.nec(i).descriptor=sprintf('nln_eq_con_%d',i);
+                end
+            end
+            if isfield(dresp,'rf' )
+                for i=1:nrf
+                    dresp.rf(i).descriptor=sprintf('response_fn_%d',i);
+                end
+            end
+        end
+        return;
+    end
+end
+
+end
+
+%%  function to read the number and levels of responses
+
+function [dresp]=resplevels(fidi,tokens,itoken,dresp)
+
+display('Reading Dakota response levels.');
+
+%  read next keyword
+
+[tokens,itoken]=nextkey(fidi,tokens,itoken);
+if ~itoken
+    warning('resplevels:empty',...
+        'Dakota method section is empty.');
+end
+
+%  process current keyword
+
+while itoken
+    keyword=tokens{1}{itoken};
+    display(sprintf('  Dakota keyword=%s.',keyword));
+
+%  switch according to the keyword
+
+    switch lower(keyword)
+        case 'nond_sampling'
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+        case 'nond_local_reliability'
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+        case 'num_response_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nresp=tlist;
+        case 'response_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nrespl=tlist;
+        case 'num_probability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nprob=tlist;
+        case 'probability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nprobl=tlist;
+        case 'num_reliability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nrel =tlist;
+        case 'reliability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            nrell =tlist;
+        case 'num_gen_reliability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            ngrel=tlist;
+        case 'gen_reliability_levels'
+            [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+            ngrell=tlist;
+        case 'compute'
+            [tokens,itoken]=nexttoken(fidi,tokens,itoken);
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+        otherwise
+            warning('resplevels:unrec_key',...
+                'Unrecognized keyword ''%s''.',keyword);
+            [tokens,itoken]=nextkey(fidi,tokens,itoken);
+    end
+
+%  check for eof or start of new section
+
+    if (~itoken) || ...
+       strncmpi(tokens{1}{itoken},'strategy' ,8) || ...
+       strncmpi(tokens{1}{itoken},'method'   ,6) || ...
+       strncmpi(tokens{1}{itoken},'model'    ,5) || ...
+       strncmpi(tokens{1}{itoken},'variables',9) || ...
+       strncmpi(tokens{1}{itoken},'interface',9) || ...
+       strncmpi(tokens{1}{itoken},'responses',9)
+
+%  assemble the lists by response
+
+        if exist('nrespl','var') && isfield(dresp,'rf')
+            if ~exist('nresp','var')
+                nresp(1:length(dresp.rf))=floor(length(nrespl)/length(dresp.rf));
+            end
+            ilist=1;
+            for i=1:length(dresp.rf)
+                dresp.rf(i).respl=nrespl(ilist:ilist+nresp(i)-1);
+                ilist=ilist+nresp(i);
+            end
+        end
+
+        if exist('nprobl','var') && isfield(dresp,'rf')
+            if ~exist('nprob','var')
+                nprob(1:length(dresp.rf))=floor(length(nprobl)/length(dresp.rf));
+            end
+            ilist=1;
+            for i=1:length(dresp.rf)
+                dresp.rf(i).probl=nprobl(ilist:ilist+nprob(i)-1);
+                ilist=ilist+nprob(i);
+            end
+        end
+
+        if exist('nrell' ,'var') && isfield(dresp,'rf')
+            if ~exist('nrel' ,'var')
+                nrel (1:length(dresp.rf))=floor(length(nrell )/length(dresp.rf));
+            end
+            ilist=1;
+            for i=1:length(dresp.rf)
+                dresp.rf(i).rell =nrell (ilist:ilist+nrel (i)-1);
+                ilist=ilist+nrel (i);
+            end
+        end
+
+        if exist('ngrell','var') && isfield(dresp,'rf')
+            if ~exist('ngrel','var')
+                ngrel(1:length(dresp.rf))=floor(length(ngrell)/length(dresp.rf));
+            end
+            ilist=1;
+            for i=1:length(dresp.rf)
+                dresp.rf(i).grell=ngrell(ilist:ilist+ngrel(i)-1);
+                ilist=ilist+ngrel(i);
+            end
+        end
+
+        return;
+    end
+end
+
+end
+
+%%  function to find the next keyword
+
+function [tokens,itoken]=nextkey(fidi,tokens,itoken)
+
+%  start with next token
+
+[tokens,itoken]=nexttoken(fidi,tokens,itoken);
+if ~itoken
+    return;
+end
+
+%  check for equal sign and skip subsequent list
+
+if (itoken <= length(tokens{1})) && ...
+   strncmp(tokens{1}{itoken},'=',1)
+    [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken);
+end
+
+end
+
+%%  function to find the next token
+
+function [tokens,itoken]=nexttoken(fidi,tokens,itoken)
+
+%  start with next token
+
+itoken=itoken+1;
+
+%  read next line if necessary
+
+if (itoken > length(tokens{1}))
+    fline=readline(fidi);
+    if isempty(fline)
+        tokens={};
+        itoken=0;
+        return;
+    end
+    [ntokens,tokens]=fltokens(fline);
+    itoken=1;
+end
+
+end
+
+%%  function to read a list of tokens
+
+function [tlist,tokens,itoken]=readtlist(fidi,tokens,itoken)
+
+%  start with next token (which should be equal sign, unless
+%  equal sign was already read to determine existence of list)
+
+itoken=itoken+1;
+
+%  read next line if necessary
+
+if (itoken > length(tokens{1}))
+    fline=readline(fidi);
+    if isempty(fline)
+        tokens={};
+        itoken=0;
+        return;
+    end
+    [ntokens,tokens]=fltokens(fline);
+    itoken=1;
+end
+
+%  check for equal sign and skip
+
+if strncmp(tokens{1}{itoken},'=',1)
+    itoken=itoken+1;
+end
+
+ilist=0;
+
+%  accumulate list until non-numeric and non-quoted-string (or eof)
+%  is encountered
+
+while 1
+    for i=itoken:length(tokens{1})
+        if isnumeric(tokens{1}{i})
+            ilist=ilist+1;
+            tlist(ilist)=tokens{1}{i};
+        elseif ischar(tokens{1}{i}) && ...
+               (strncmp(tokens{1}{i}(1)  ,'''',1) && ...
+                strncmp(tokens{1}{i}(end),'''',1)) || ...
+               (strncmp(tokens{1}{i}(1)  ,'"',1) && ...
+                strncmp(tokens{1}{i}(end),'"',1))
+            ilist=ilist+1;
+            tlist(ilist)=cellstr(tokens{1}{i}(2:end-1));
+        else
+            itoken=i;
+            return
+        end
+    end
+    fline=readline(fidi);
+    if isempty(fline)
+        tokens={};
+        itoken=0;
+        return;
+    end
+    [ntokens,tokens]=fltokens(fline);
+    itoken=1;
+end
+
+end
+
+%%  function to find a file line starting with a specified string
+
+function [fline]=findline(fidi,string)
+
+ipos=ftell(fidi);
+
+while 1
+    fline=readline(fidi);
+    if isempty(fline)
+        break;
+    else
+        if (strncmpi(fline,string,length(string)))
+            return;
+        end
+    end
+end
+
+%  issue warning and reset file position
+
+warning('findline:str_not_found',...
+    'String ''%s'' not found in file.',string);
+fseek(fidi,ipos,'bof');
+
+end
+
+%%  function to read a file line ignoring comments and blanks
+
+function [fline]=readline(fidi)
+
+while 1
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        fline=[];
+        return;
+    end
+
+    for ichar=1:length(fline)
+        if ~strncmp(fline(ichar),' ',1) && ...
+           ~strncmp(fline(ichar),'	',1)
+            break;
+        end
+    end
+    if isempty(fline) || ...
+       (ichar > length(fline)) || ...
+       strncmp(fline(ichar),'#',1)
+        continue;
+    else
+        return;
+    end
+end
+
+end
+
+%%  function to parse a file line into tokens
+
+function [ntokens,tokens]=fltokens(fline)
+
+if ~ischar(fline)
+    ntokens=-1;
+    tokens={};
+    return;
+end
+if isempty(fline)
+    ntokens=0;
+    tokens={};
+    return;
+end
+
+strings=textscan(fline,'%s','delimiter',' :,');
+%for i=1:length(strings{1})
+%    display(sprintf('i=%d; strings{1}{%d}=%s',i,i,strings{1}{i}))
+%end
+ntokens=0;
+tokens{1}{length(strings)}='';
+
+for i=1:length(strings{1})
+    if isempty(strings{1}{i})
+        continue
+    end
+    ntokens=ntokens+1;
+    inum=sscanf(strings{1}{i},'%f');
+    if isempty(inum)
+        tokens{1}{ntokens}=strings{1}{i};
+%         display(sprintf('i=%d; tokens{1}{%d}=%s',...
+%             i,ntokens,tokens{1}{ntokens}))
+    else
+        tokens{1}{ntokens}=inum;
+%         display(sprintf('i=%d; tokens{1}{%d}=%f',...
+%             i,ntokens,tokens{1}{ntokens}))
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_in_write.m	(revision 18231)
@@ -0,0 +1,322 @@
+%
+%  write a Dakota .in input file.
+%
+%  []=dakota_in_write(method,dvar,dresp,params,filei,varargin)
+%  []=dakota_in_write(dmeth ,dvar,dresp,params,filei,varargin)
+%
+%  where the required input is:
+%    method        (character, dakota method name)
+%    dmeth         (dakota_method, method class object)
+%    dvar          (structure array, variable class objects)
+%    dresp         (structure array, response class objects)
+%    params        (structure array, method-independent parameters)
+%    filei         (character, name of .in file)
+%
+%  the method and filei will be prompted if empty.  params
+%  may be empty, in which case defaults will be used.
+%
+%  the optional varargin are not yet used.
+%
+%  this function writes a dakota .in input file to be used
+%  by dakota.  this file is independent of the particular
+%  analysis package.
+%
+%  this data would typically be generated by a matlab script
+%  for a specific model, using the method, variable, and
+%  response class objects.  this function may be called by
+%  dakota_in_data.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=dakota_in_write(method,dvar,dresp,params,filei,varargin)
+
+if ~nargin
+    help dakota_in_write
+    return
+end
+
+%  process the input parameters
+
+if ~exist('method','var') || isempty(method)
+    method=input('Method?  ','s');
+end
+if     ischar(method)
+    dmeth=dakota_method(method);
+elseif isa(method,'dakota_method')
+    dmeth=method;
+else
+    error(['Method ''' inputname(1) ''' is unrecognized class ''' class(method) '''.']);
+end
+
+if ~exist('filei' ,'var') || isempty(filei)
+    filei=input('Dakota input file to write?  ','s');
+end
+[pathstr,name,ext] = fileparts(filei);
+if isempty(ext)
+% fileparts only considers '.in' to be the extension, not '.qmu.in'
+    ext='.qmu.in';
+end
+filei2=fullfile(pathstr,[name ext]);
+
+display(sprintf('Opening Dakota input file ''%s''.',filei2));
+fidi=fopen(sprintf('%s',filei2),'w');
+if (fidi < 0)
+    error('''%s'' could not be opened.',filei2);
+end
+
+if ~exist('params','var')
+    params=struct();
+end
+params=dakota_in_params(params);
+
+%  write the strategy section
+
+strategy_write(fidi,params);
+
+%  write the method section
+
+method_write(fidi,dmeth,dresp,params);
+
+%  write the model section
+
+model_write(fidi);
+
+%  write the variables section
+
+variables_write(fidi,dmeth,dvar);
+
+%  write the interface section
+
+interface_write(fidi,params);
+
+%  write the responses section
+
+responses_write(fidi,dmeth,dresp,params);
+
+fclose(fidi);
+display('End of file successfully written.');
+
+end
+
+%%  function to write the strategy section of the file
+
+function []=strategy_write(fidi,params)
+
+display('Writing strategy section of Dakota input file.');
+
+fprintf(fidi,'strategy,\n');
+fprintf(fidi,'\tsingle_method\n');
+param_write(fidi,'\t  ','graphics','','\n',params);
+param_write(fidi,'\t  ','tabular_graphics_data','','\n',params);
+param_write(fidi,'\t  ','tabular_graphics_file',' ''','''\n',params);
+fprintf(fidi,'\n');
+
+end
+
+%%  function to write the method section of the file
+
+function []=method_write(fidi,dmeth,dresp,params)
+
+display('Writing method section of Dakota input file.');
+
+fprintf(fidi,'method,\n');
+fprintf(fidi,'\t%s\n',dmeth.method);
+
+dmeth_params_write(dmeth,fidi);
+
+%  write response levels
+
+if strcmp(dmeth.type,'nond')
+    for i=1:length(dmeth.responses)
+        fhresp=str2func([dmeth.responses{i} '.dakota_rlev_write']);
+        fhresp(fidi,dresp,params);
+    end
+end
+fprintf(fidi,'\n');
+
+end
+
+%%  function to write the model section of the file
+
+function []=model_write(fidi)
+
+display('Writing model section of Dakota input file.');
+
+fprintf(fidi,'model,\n');
+fprintf(fidi,'\t%s\n\n','single');
+
+end
+
+%%  function to write the variables section of the file
+
+function []=variables_write(fidi,dmeth,dvar)
+
+display('Writing variables section of Dakota input file.');
+
+fprintf(fidi,'variables,\n');
+
+%  variables vary by method
+
+for i=1:length(dmeth.variables)
+    fhvar=str2func([dmeth.variables{i} '.dakota_write']);
+    fhvar(fidi,dvar);
+end
+
+%  linear constraints vary by method
+
+for i=1:length(dmeth.lcspec)
+    fhvar=str2func([dmeth.lcspec{i}    '.dakota_write']);
+    fhvar(fidi,dvar);
+end
+
+fprintf(fidi,'\n');
+
+end
+
+%%  function to write the interface section of the file
+
+function []=interface_write(fidi,params)
+
+display('Writing interface section of Dakota input file.');
+
+fprintf(fidi,'interface,\n');
+
+if     ~params.system && ~params.fork && ~params.direct
+    params.fork=true;
+elseif (params.system+params.fork+params.direct > 1)
+    error('Too many interfaces selected.')
+end
+
+if     params.system || params.fork
+    param_write(fidi,'\t','asynchronous','','\n',params);
+    param_write(fidi,'\t  ','evaluation_concurrency',' = ','\n',params);
+    param_write(fidi,'\t  ','analysis_concurrency','   = ','\n',params);
+    param_write(fidi,'\t  ','evaluation_servers','     = ','\n',params);
+    param_write(fidi,'\t  ','evaluation_self_scheduling','','\n',params);
+    param_write(fidi,'\t  ','evaluation_static_scheduling','','\n',params);
+    param_write(fidi,'\t  ','analysis_servers','       = ','\n',params);
+    param_write(fidi,'\t  ','analysis_self_scheduling','','\n',params);
+    param_write(fidi,'\t  ','analysis_static_scheduling','','\n',params);
+    param_write(fidi,'\t','algebraic_mappings',' = ','\n',params);
+    param_write(fidi,'\t','system','','\n',params);
+    param_write(fidi,'\t','fork','','\n',params);
+    param_write(fidi,'\t  ','analysis_driver',' = ''','''\n',params);
+    if ~isempty(params.input_filter)
+        param_write(fidi,'\t  ','input_filter','    = ''','''\n',params);
+    end
+    if ~isempty(params.output_filter)
+        param_write(fidi,'\t  ','output_filter','   = ''','''\n',params);
+    end
+    param_write(fidi,'\t  ','failure_capture','   ','\n',params);
+    param_write(fidi,'\t  ','deactivate','        ','\n',params);
+    param_write(fidi,'\t  ','parameters_file',' = ''','''\n',params);
+    param_write(fidi,'\t  ','results_file','    = ''','''\n',params);
+    param_write(fidi,'\t  ','verbatim', '','\n',params);
+    param_write(fidi,'\t  ','aprepro', '','\n',params);
+    param_write(fidi,'\t  ','file_tag', '','\n',params);
+    param_write(fidi,'\t  ','file_save','','\n',params);
+elseif params.direct
+%  Error: asynchronous capability not yet supported in direct interfaces.
+    param_write(fidi,'\t','algebraic_mappings',' = ','\n',params);
+    param_write(fidi,'\t','direct','','\n',params);
+    param_write(fidi,'\t  ','analysis_driver','     = ''','''\n',params);
+    param_write(fidi,'\t  ','evaluation_static_scheduling','','\n',params);
+    if ~isempty(params.analysis_components)
+        [pathstr,name,ext] = fileparts(params.analysis_components);
+        if isempty(ext)
+            ext='.m';
+        end
+        params.analysis_components=fullfile(pathstr,[name ext]);
+        param_write(fidi,'\t  ','analysis_components',' = ''','''\n',params);
+    end
+    if ~isempty(params.input_filter)
+        param_write(fidi,'\t  ','input_filter','    = ''','''\n',params);
+    end
+    if ~isempty(params.output_filter)
+        param_write(fidi,'\t  ','output_filter','   = ''','''\n',params);
+    end
+    param_write(fidi,'\t  ','failure_capture','   ','\n',params);
+    param_write(fidi,'\t  ','deactivate','        ','\n',params);
+    param_write(fidi,'\t  ','processors_per_analysis',' = ''','''\n',params);
+end
+
+fprintf(fidi,'\n');
+
+end
+
+%%  function to write the responses section of the file
+
+function []=responses_write(fidi,dmeth,dresp,params)
+
+display('Writing responses section of Dakota input file.');
+
+fprintf(fidi,'responses,\n');
+
+%  functions, gradients, and hessians vary by method
+
+rdesc={};
+
+for i=1:length(dmeth.responses)
+    fhresp=str2func([dmeth.responses{i} '.dakota_write']);
+    [rdesc]=fhresp(fidi,dresp,rdesc);
+end
+
+%  write accumulated response descriptors for all response classes
+
+if ~isempty(rdesc)
+    fprintf(fidi,'\tresponse_descriptors =\n');
+    vector_write(fidi,sprintf('\t  '),rdesc,6,76);
+end
+
+ghspec_write(fidi,params,dmeth.ghspec);
+
+fprintf(fidi,'\n');
+
+end
+
+%%  function to write gradient and hessian specifications
+
+function []=ghspec_write(fidi,params,ghspec)
+
+%  gradients
+
+if find_string(ghspec,'grad')
+    if     ~params.numerical_gradients && ~params.analytic_gradients
+        params.numerical_gradients=true;
+    elseif (params.numerical_gradients+params.analytic_gradients > 1)
+        error('Too many gradients selected.')
+    end
+
+    if     params.numerical_gradients
+        param_write(fidi,'\t','numerical_gradients','','\n',params);
+        param_write(fidi,'\t  ','method_source',' ','\n',params);
+        param_write(fidi,'\t  ','interval_type',' ','\n',params);
+        param_write(fidi,'\t  ','fd_gradient_step_size',' = ','\n',params);
+    elseif params.analytic_gradients
+        param_write(fidi,'\t','analytic_gradients','','\n',params);
+%     elseif params.mixed_gradients
+    end
+else
+    fprintf(fidi,'\tno_gradients\n');
+end
+
+%  hessians (no implemented methods use them yet)
+
+if find_string(ghspec,'hess')
+    error('Hessians needed by method but not provided.');
+else
+    fprintf(fidi,'\tno_hessians\n');
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_m_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_m_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_m_write.m	(revision 18231)
@@ -0,0 +1,296 @@
+%
+%  write a Matlab .m function file to be called by Dakota for
+%  the Matlab direct or external driver.
+%
+%  []=dakota_m_write(method,dmeth,dvar,dresp,params,filem,package,varargin)
+%
+%  where the required input is:
+%    method        (character, dakota method name)
+%    dmeth         (dakota_method, method class object)
+%    dvar          (structure array, variable class objects)
+%    dresp         (structure array, response class objects)
+%    params        (structure array, method-independent parameters)
+%    filem         (character, name of .m file)
+%    package       (character, analysis package)
+%
+%  the method, dmeth, and filem will be prompted if empty.
+%  params may be empty, in which case defaults will be used.
+%
+%  the optional varargin are passed directly through to the
+%  QmuUpdateFunctions brancher to be used by the analysis
+%  package.  for example, this could be model information.
+%
+%  this function writes a matlab .m function file to be called
+%  by dakota for the matlab direct or external driver.  for
+%  the direct driver, dakota is linked with matlab and
+%  automatically starts a matlab session, passing the variables
+%  and responses through the function; for the external driver,
+%  dakota calls a shell script to start the matlab session,
+%  passing the variables and responses through text files.
+%  this function must be tailored to the particular analysis
+%  package.
+%
+%  this data would typically be generated by a matlab script
+%  for a specific model, using the method, variable, and
+%  response class objects.  this function may be called by
+%  dakota_in_data.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=dakota_m_write(method,dmeth,dvar,dresp,params,filem,package,varargin)
+
+if ~nargin
+    help dakota_m_write
+    return
+end
+
+%  process the input parameters
+
+if ~exist('method','var') || isempty(method)
+    method=input('Method?  ','s');
+end
+
+if ~exist('dmeth' ,'var') || isempty(dmeth)
+    dmeth=dakota_method(method);
+end
+
+if ~exist('params','var')
+    params=[];
+end
+
+if ~exist('filem' ,'var') || isempty(filem)
+    filem=input('Matlab m-file to write?  ','s');
+end
+[pathstr,name,ext,versn] = fileparts(filem);
+if isempty(ext)
+    ext='.m';
+end
+filem2=fullfile(pathstr,[name ext versn]);
+
+display(sprintf('Opening Matlab m-file ''%s''.',filem2));
+fidm=fopen(sprintf('%s',filem2),'w');
+if (fidm < 0)
+    error('''%s'' could not be opened.',filem2);
+end
+
+%  write beginning of the Matlab m-file
+
+begin_write(fidm,name,params);
+
+%  write variables into the Matlab m-file
+
+variables_write(fidm,dmeth,dvar,params,varargin{:});
+
+%  write solution into the Matlab m-file
+
+solution_write(fidm,package);
+
+%  write responses into the Matlab m-file
+
+responses_write(fidm,dmeth,params,dresp);
+
+%  write end of the Matlab m-file
+
+end_write(fidm,name,params);
+
+fclose(fidm);
+display('End of file successfully written.');
+
+end
+
+%%  function to write beginning of the Matlab m-file
+
+function []=begin_write(fidm,name,params)
+
+display('Writing beginning of Matlab m-file.');
+
+fprintf(fidm,'%%\n');
+if strcmpi(params.analysis_driver,'matlab')
+    fprintf(fidm,'%%  Run the specified input variables and return the output responses.\n');
+    fprintf(fidm,'%%\n');
+    fprintf(fidm,'function Dakota=%s(Dakota)\n\n',name);
+    fprintf(fidm,'clk=clock;\n');
+    fprintf(fidm,'cpu=cputime;\n\n');
+    fprintf(fidm,'%% Dakota\n\n');
+    fprintf(fidm,'infile=''%s'';\n','Qmu.model');
+else
+    fprintf(fidm,'%%  Run the specified input file and return the output file.\n');
+    fprintf(fidm,'%%\n');
+    fprintf(fidm,'function %s(infile,outfile)\n\n',name);
+    fprintf(fidm,'clk=clock;\n');
+    fprintf(fidm,'cpu=cputime;\n\n');
+end
+fprintf(fidm,'try\n');
+fprintf(fidm,'\tloadmodel(infile);\n\n');
+
+if strcmpi(params.analysis_driver,'matlab')
+	fprintf(fidm,'\tmd=qmuname(md,Dakota.fnEvalId);\n\n');
+else
+	fprintf(fidm,'\tmd=qmuname(md);\n\n');
+end
+
+end
+
+%%  function to write variables into the Matlab m-file
+
+function []=variables_write(fidm,dmeth,dvar,params,varargin)
+
+display('Writing variables for Matlab m-file.');
+
+fprintf(fidm,'%%  Apply the variables.\n\n');
+ixc=0;
+
+%  variables vary by method
+
+ixc=vsets_write(fidm,ixc,dvar,dmeth.variables,params,varargin{:});
+
+end
+
+%%  function to write variable sets into the Matlab m-file
+
+function [ixc]=vsets_write(fidm,ixc,dvar,variables,params,varargin)
+
+for i=1:length(variables)
+    if isfield(dvar,variables{i})
+        ixc=vlist_write(fidm,ixc,variables{i},dvar.(variables{i}),params,varargin{:});
+    end
+end
+
+end
+
+%%  function to write variable list into the Matlab m-file
+
+function [ixc]=vlist_write(fidm,ixc,vtype,dvar,params,varargin)
+
+disp(sprintf('  Writing %d %s variables.',length(dvar),class(dvar)));
+
+for i=1:length(dvar)
+
+	%first find descriptor, without sample number on it.
+	descriptor=discardnum(dvar(i).descriptor);
+
+	%is there a lock on this variable? We don't want to update the variable twice!
+	if exist([descriptor '_lock'],'var'),
+		%lock is in place, do not update! continue;
+		continue;
+	else
+		%first things first, put lock in place
+		eval([descriptor '_lock=1;']);
+
+		%now, we need a string to put in the matlab file, which will update all the variables 
+		%for  this descriptor.
+		[string,ixc]=QmuUpdateFunctions(ixc,descriptor,dvar,params,i,varargin{:});
+
+		%dump this string in the matlab file.
+        fprintf(fidm,'%s',string);
+	end
+end
+
+end
+
+%%  function to write solution into the Matlab m-file
+
+function []=solution_write(fidm,package)
+
+display('Writing solution for Matlab m-file.');
+fprintf(fidm,'%%  Run the solution.\n\n');
+
+fprintf(fidm,['\tmd=solve(md,''stressbalance'',''' package ''');\n\n']);
+
+end
+
+%%  function to write responses into the Matlab m-file
+
+function []=responses_write(fidm,dmeth,params,dresp)
+
+display('Writing responses for Matlab m-file.');
+
+fprintf(fidm,'%%  Calculate the responses.\n\n');
+ifnvals=0;
+
+if ~strcmpi(params.analysis_driver,'matlab')
+    fprintf(fidm,'\tfid=fopen(outfile,''w'');\n\n');
+end
+
+%  responses vary by method
+
+ifnvals=rsets_write(fidm,ifnvals,params,dresp,dmeth.responses);
+
+fprintf(fidm,'\n');
+if ~strcmpi(params.analysis_driver,'matlab')
+    fprintf(fidm,'\tstatus=fclose(fid);\n\n');
+end
+
+end
+
+%%  function to write response sets into the Matlab m-file
+
+function [ifnvals]=rsets_write(fidm,ifnvals,params,dresp,responses)
+
+for i=1:length(responses)
+    if isfield(dresp,responses{i})
+        ifnvals=rlist_write(fidm,ifnvals,params,responses{i},dresp.(responses{i}));
+    end
+end
+
+end
+
+%%  function to write response list into the Matlab m-file
+
+function [ifnvals]=rlist_write(fidm,ifnvals,params,rtype,dresp)
+
+disp(sprintf('  Writing %d %s responses.',length(dresp),class(dresp)));
+for i=1:length(dresp)
+    ifnvals=ifnvals+1;
+    if strcmpi(params.analysis_driver,'matlab')
+        fprintf(fidm,'\tDakota.fnVals(%d)=QmuResponseValue(md,''%s'');\n',ifnvals,dresp(i).descriptor);
+    else
+        fprintf(fidm,'\tfprintf(fid,''%%f\\n'',QmuResponseValue(md,''%s''));\n',dresp(i).descriptor);
+    end
+end
+
+end
+
+%%  function to write end of the Matlab m-file
+
+function []=end_write(fidm,name,params)
+
+display('Writing end of Matlab m-file.');
+
+fprintf(fidm,'%%  Error condition.\n\n');
+
+fprintf(fidm,'catch ME\n');
+fprintf(fidm,'\tME\n');
+fprintf(fidm,'\tfor i=1:length(ME.stack)\n');
+fprintf(fidm,'\t\tdisplay(sprintf(''    file(%%d): %%s'',  i,ME.stack(i).file));\n');
+fprintf(fidm,'\t\tdisplay(sprintf(''    name(%%d): %%s'',  i,ME.stack(i).name));\n');
+fprintf(fidm,'\t\tdisplay(sprintf(''    line(%%d): %%d\\n'',i,ME.stack(i).line));\n');
+fprintf(fidm,'\tend\n');
+if strcmpi(params.analysis_driver,'matlab')
+    fprintf(fidm,'\tDakota.failure=1;\n');
+else
+    fprintf(fidm,'\tif exist(''fid'',''var'')\n');
+    fprintf(fidm,'\t\tstatus=fclose(fid);\n');
+    fprintf(fidm,'\tend\n');
+    fprintf(fidm,'\tfid=fopen(outfile,''w'');\n');
+    fprintf(fidm,'\tfprintf(fid,''fail\\n'');\n');
+    fprintf(fidm,'\tstatus=fclose(fid);\n');
+end
+fprintf(fidm,'end\n\n');
+
+fprintf(fidm,'disp(sprintf(''%s -- %%f CPU seconds; %%f clock seconds\\n'',...\n',name);
+fprintf(fidm,'    cputime-cpu,etime(clock,clk)))\n\n');
+fprintf(fidm,'end\n\n');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_moments.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_moments.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_moments.m	(revision 18231)
@@ -0,0 +1,147 @@
+%
+%  calculate the same moments and confidence intervals that dakota
+%  calculates for a sample.
+%
+%  [dresp                      ]=dakota_moments(dresp,alpha)
+%  [mean,stddev,meanci,stddevci]=dakota_moments(samp ,alpha)
+%
+%  the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    samp          (double array, lists of samples)
+%
+%  and the optional input is:
+%    alpha         (numeric, confidence interval of 100(1-alpha)%)
+%
+%  the required field of dresp is:
+%    sample        (double vector, list of samples)
+%
+%  the required output is:
+%    dresp         (structure array, responses)
+%      or
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%    meanci(2)     (double, confidence interval of mean)
+%    stddevci(2)   (double, confidence interval of standard deviation)
+%
+%  and the output fields of dresp are:
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%    meanci(2)     (double, confidence interval of mean)
+%    stddevci(2)   (double, confidence interval of standard deviation)
+%
+%  for each response (or column of data) in the input array, this
+%  function calculates the mean, standard deviation, and their
+%  confidence intervals for a normal distribution, the same way as
+%  dakota would.  if the input is a structure, the output is fields
+%  in the structure; if the input is an array, the output is arrays.
+%
+%  dresp data would typically be contained in the dakota tabular
+%  output file from a sampling analysis, read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [varargout]=dakota_moments(varargin)
+
+if ~nargin
+    help dakota_moments
+    return
+end
+
+%%  process input data
+
+iarg=1;
+if     isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+elseif isnumeric(varargin{iarg})
+    samp=varargin{iarg};
+    iarg=iarg+1;
+else
+    error(['Unknown data ''' inputname(1) ''' of type ''' class(varargin{1}) '''.']);
+end
+
+if iarg <= nargin && isnumeric(varargin{iarg})
+    alpha=varargin{iarg};
+    iarg=iarg+1;
+else
+%  use dakota default of 95%
+    alpha=0.05;
+end
+
+%%  calculate the moments and confidence intervals by input type
+
+if     exist('dresp','var') && ~isempty(dresp)
+    for i=1:length(dresp)
+        [dresp(i).mean,dresp(i).stddev,...
+         dresp(i).meanci,dresp(i).stddevci]=...
+            moments_calc(dresp(i).sample,alpha);
+    end
+
+    varargout{1}=dresp;
+
+elseif exist('samp','var') && ~isempty(samp)
+    mean    =zeros(1,size(samp,2));
+    stddev  =zeros(1,size(samp,2));
+    meanci  =zeros(2,size(samp,2));
+    stddevci=zeros(2,size(samp,2));
+
+%  could do this using vector math rather than loop, but want to allow
+%  the case of differently sized samples padded by NaN's
+
+    for i=1:size(samp,2)
+        [mean(i),stddev(i),...
+         meanci(:,i),stddevci(:,i)]=...
+            moments_calc(samp(:,i),alpha);
+    end
+
+    varargout{1}=mean;
+    varargout{2}=stddev;
+    varargout{3}=meanci;
+    varargout{4}=stddevci;
+else
+    error(['Empty data ''' inputname(1) ''' of type ''' class(varargin{1}) '''.']);
+end
+
+end
+
+%%  function to calculate the results
+
+function [mu,sigma,muci,sigmaci]=moments_calc(samp,alpha)
+
+%  remove any NaN padding (should only occur at end)
+
+    samp=samp(~isnan(samp(:)));
+    nsamp=length(samp);
+    prob=1-alpha/2;
+
+%  could use Matlab normfit, but make calculations explicit
+%     [mu,sigma,muci,sigmaci]=normfit(samp,alpha);
+
+    mu   =mean(samp);
+    sigma=std(samp);
+
+	try
+        muci(1,1)   =mu-tinv(prob,nsamp-1)*sigma/sqrt(nsamp);
+        muci(2,1)   =mu+tinv(prob,nsamp-1)*sigma/sqrt(nsamp);
+        sigmaci(1,1)=sigma*sqrt((nsamp-1)/chi2inv(prob  ,nsamp-1));
+        sigmaci(2,1)=sigma*sqrt((nsamp-1)/chi2inv(1-prob,nsamp-1));
+	catch me
+        muci(1,1)   =mu;
+        muci(2,1)   =mu;
+        sigmaci(1,1)=sigma;
+        sigmaci(2,1)=sigma;
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_out_parse.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_out_parse.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_out_parse.m	(revision 18231)
@@ -0,0 +1,1013 @@
+%
+%  read a Dakota .out or .dat output file and parse it.
+%
+%  [method,dresp,scm,pcm,srcm,prcm]=dakota_out_parse(filei)
+%
+%  where the required input is:
+%    filei         (character, name of .out file)
+%
+%  the required output is:
+%    method        (character, dakota method name)
+%    dresp         (structure array, responses)
+%
+%  and the optional output is:
+%    scm           (double array, simple correlation matrix)
+%    pcm           (double array, partial correlation matrix)
+%    srcm          (double array, simple rank correlation matrix)
+%    prcm          (double array, partial rank correlation matrix)
+%
+%  the filei will be prompted if empty.  the fields of dresp
+%  are particular to the data contained within the file.  the
+%  scm, pcm, srcm, and prcm are output by dakota only for the
+%  sampling methods.
+%
+%  this function reads a dakota .out output file and parses it
+%  into the matlab workspace.  it operates in a content-driven
+%  fashion, where it skips the intermediate data and then parses
+%  whatever output data it encounters in the order in which it
+%  exists in the file, rather than searching for data based on
+%  the particular method.  (this makes it independent of method.)
+%  it also can read and parse the .dat tabular_output file.
+%
+%  this data would typically be used for plotting and other
+%  post-processing within matlab or excel.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [method,dresp,scm,pcm,srcm,prcm]=dakota_out_parse(filei)
+
+if ~nargin
+    help dakota_out_parse
+    return
+end
+
+if ~exist('filei' ,'var') || isempty(filei)
+    filei=input('Input file?  ','s');
+end
+fidi=fopen(sprintf('%s',filei),'r');
+if (fidi < 0)
+    error('''%s'' could not be opened.',filei);
+end
+
+%%  check the first line for the Dakota tabular output file
+
+method=[];
+fline=fgetl(fidi);
+if ~ischar(fline)
+    error('File ''%s'' is empty.',filei);
+end
+
+if strncmpi(fline,'%eval_id',8)
+    method='unknown';
+    [dresp]=dak_tab_out(fidi,fline);
+    return
+else
+    fseek(fidi,0,'bof');
+end
+
+%%  loop through the file to find the Dakota method name
+
+[fline]=findline(fidi,'methodName = ');
+if ~ischar(fline)
+    return
+end
+% display(['  ' deblank(fline)]);
+
+[ntokens,tokens]=fltokens(fline);
+method=tokens{1}{3};
+display(sprintf('Dakota methodName=''%s''.',method));
+
+dresp=struct([]);
+scm =struct([]);
+pcm =struct([]);
+srcm=struct([]);
+prcm=struct([]);
+
+%%  loop through the file to find the function evaluation summary
+
+fline='';
+[nfeval]=nfeval_read(fidi,fline);
+fline=fgetl(fidi);
+
+%%  process each results section based on content of the file
+
+while ischar(fline)
+%     ipos=ftell(fidi);
+    if     isempty(fline)
+    elseif strncmp(fline,'<<<<< Function evaluation summary',33)
+        [nfeval]=nfeval_read(fidi,fline);
+    elseif strncmp(fline,'Statistics based on ',20)
+        [nsamp]=nsamp_read(fidi,fline);
+    elseif strncmp(fline,'Moments for each response function',34)
+        [dresp]=moments_read(fidi,dresp,fline);
+    elseif strncmp(fline,'Moment-based statistics for each response function',50)
+        [dresp]=mbstats_read(fidi,dresp,fline);
+    elseif strncmp(fline,'95% confidence intervals for each response function',51)
+        [dresp]=cis_read(fidi,dresp,fline);
+    elseif strncmp(fline,'Probabilities for each response function',40) || ...
+           strncmp(fline,'Level mappings for each response function',41)
+        [dresp]=cdfs_read(fidi,dresp,fline);
+    elseif strncmp(fline,'Probability Density Function (PDF) histograms for each response function',72)
+        [dresp]=pdfs_read(fidi,dresp,fline);
+    elseif strncmp(fline,'Simple Correlation Matrix',25)
+        [scm]=corrmat_read(fidi,'Simple Correlation Matrix',fline);
+    elseif strncmp(fline,'Partial Correlation Matrix',26)
+        [pcm]=corrmat_read(fidi,'Partial Correlation Matrix',fline);
+    elseif strncmp(fline,'Simple Rank Correlation Matrix',30)
+        [srcm]=corrmat_read(fidi,'Simple Rank Correlation Matrix',fline);
+    elseif strncmp(fline,'Partial Rank Correlation Matrix',31)
+        [prcm]=corrmat_read(fidi,'Partial Rank Correlation Matrix',fline);
+    elseif strncmp(fline,'MV Statistics for ',18)
+        [dresp]=mvstats_read(fidi,dresp,fline);
+    elseif strncmp(fline,'<<<<< Best ',11)
+        [dresp]=best_read(fidi,dresp,fline);
+    elseif strncmp(fline,'The following lists volumetric uniformity measures',50)
+        [dresp]=vum_read(fidi,dresp,fline);
+    elseif strncmp(fline,'<<<<< Iterator ',15) && ...
+           (length(fline) > 26) && ...
+           ~isempty(strfind(fline(16:end),' completed.'))
+        [method]=itcomp_read(fidi,fline);
+    elseif strncmp(fline,'-----',5)
+    else
+        display(['Unexpected line: ' deblank(fline)]);
+    end
+    fline=fgetl(fidi);
+%     fseek(fidi,ipos,'bof');
+end
+
+%%  loop through the file to verify the end
+
+% [fline]=findline(fidi,'<<<<< Single Method Strategy completed');
+% if ~ischar(fline)
+%     return
+% end
+display('End of file successfully reached.');
+fclose(fidi);
+
+end
+
+%%  function to parse the dakota tabular output file
+
+function [dresp]=dak_tab_out(fidi,fline)
+
+display('Reading Dakota tabular output file.');
+
+%  process column headings of matrix (skipping eval_id)
+
+[ntokens,tokens]=fltokens(fline);
+desc=cell (1,ntokens-1);
+data=zeros(1,ntokens-1);
+
+for i=1:ntokens-1
+    desc(1,i)=cellstr(tokens{1}{i+1});
+end
+display(sprintf('Number of columns (Dakota V+R)=%d.',ntokens-1));
+
+%  process rows of matrix
+
+nrow=0;
+while 1
+    fline=fgetl(fidi);
+    if ~ischar(fline) || isempty(fline)
+        break;
+    end
+    [ntokens,tokens]=fltokens(fline);
+
+%  add row values to matrix (skipping eval_id)
+
+    nrow=nrow+1;
+    for i=1:ntokens-1
+        data(nrow,i)=tokens{1}{i+1};
+    end
+end
+display(sprintf('Number of rows (Dakota func evals)=%d.',nrow));
+
+%  calculate statistics
+
+%  since normfit doesn't have a dim argument, and matlab isvector is true
+%  for a 1xn matrix, handle the case of one row explicitly
+if (size(data,1) > 1)
+    %dmean  =mean   (data);
+    %dstddev=std    (data,0);
+    [dmean,dstddev,dmeanci,dstddevci]=...
+        normfit_issm(data,0.05);
+else
+    dmean    =zeros(1,size(data,2));
+    dstddev  =zeros(1,size(data,2));
+    dmeanci  =zeros(2,size(data,2));
+    dstddevci=zeros(2,size(data,2));
+    for i=1:size(data,2)
+        [dmean(1,i),dstddev(1,i),dmeanci(:,i),dstddevci(:,i)]=...
+            normfit_issm(data(:,i),0.05);
+    end
+end
+
+dmin   =min         (data,[],1);
+dquart1=prctile_issm(data,25,1);
+dmedian=median      (data,1);
+dquart3=prctile_issm(data,75,1);
+dmax   =max         (data,[],1);
+
+%  same as Dakota scm, Excel correl
+dcorrel=corrcoef(data);
+
+%  divide the data into structures for consistency
+
+for i=1:length(desc)
+    dresp(i).descriptor=char(desc(i));
+    dresp(i).sample    =data(:,i);
+    dresp(i).mean      =dmean(i);
+    dresp(i).stddev    =dstddev(i);
+    dresp(i).meanci    =dmeanci(:,i);
+    dresp(i).stddevci  =dstddevci(:,i);
+    dresp(i).min       =dmin(i);
+    dresp(i).quart1    =dquart1(i);
+    dresp(i).median    =dmedian(i);
+    dresp(i).quart3    =dquart3(i);
+    dresp(i).max       =dmax(i);
+end
+
+%  draw box plot
+
+% figure
+% subplot(2,1,1)
+% plot_boxplot(dresp);
+
+%  draw normal probability plot
+
+% subplot(2,1,2)
+% plot_normplot(dresp);
+
+end
+
+%%  function to find and read the number of function evaluations
+
+function [nfeval]=nfeval_read(fidi,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'<<<<< Function evaluation summary');
+    if ~ischar(fline)
+        return
+    end
+end
+
+[ntokens,tokens]=fltokens(fline);
+nfeval=tokens{1}{5};
+display(sprintf('  Dakota function evaluations=%d.',nfeval));
+
+end
+
+%%  function to find and read the number of samples
+
+function [nsamp]=nsamp_read(fidi,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'Statistics based on ');
+    if ~ischar(fline)
+        return
+    end
+end
+
+[ntokens,tokens]=fltokens(fline);
+nsamp=tokens{1}{4};
+display(sprintf('  Dakota samples=%d.',nsamp));
+
+end
+
+%%  function to find and read the moments
+
+function [dresp]=moments_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'Moments for each response function');
+    if ~ischar(fline)
+        return
+    end
+end
+
+display('Reading moments for response functions:');
+
+while 1
+    fline=fgetl(fidi);
+    if isempty(fline)
+        break;
+    end
+    [ntokens,tokens]=fltokens(fline);
+
+%  add new response function and moments
+
+    dresp(end+1).descriptor=tokens{1}{ 1};
+    display(sprintf('  %s',dresp(end).descriptor));
+    dresp(end  ).mean      =tokens{1}{ 4};
+    dresp(end  ).stddev    =tokens{1}{ 8};
+    dresp(end  ).coefvar   =tokens{1}{13};
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read the moment-based statistics
+
+function [dresp]=mbstats_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'Moment-based statistics for each response function');
+    if ~ischar(fline)
+        return
+    end
+end
+
+display('Reading moment-based statistics for response functions:');
+
+%  skip column headings of moment-based statistics
+
+    fline=fgetl(fidi);
+
+while 1
+    fline=fgetl(fidi);
+    if isempty(fline)
+        break;
+    end
+    [ntokens,tokens]=fltokens(fline);
+
+%  add new response function and moment-based statistics
+
+    dresp(end+1).descriptor=tokens{1}{ 1};
+    display(sprintf('  %s',dresp(end).descriptor));
+    dresp(end  ).mean      =tokens{1}{ 2};
+    dresp(end  ).stddev    =tokens{1}{ 3};
+    dresp(end  ).skewness  =tokens{1}{ 4};
+    dresp(end  ).kurtosis  =tokens{1}{ 5};
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read the confidence intervals
+
+function [dresp]=cis_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,...
+        '95% confidence intervals for each response function');
+    if ~ischar(fline)
+        return
+    end
+end
+
+display('Reading 95% confidence intervals for response functions:');
+
+while 1
+    fline=fgetl(fidi);
+    if isempty(fline)
+        break;
+    end
+    [ntokens,tokens]=fltokens(fline);
+
+%  check for column headings in Dakota 5.2
+
+    if (ntokens == 4)
+        fline=fgetl(fidi);
+        if isempty(fline)
+            break;
+        end
+        [ntokens,tokens]=fltokens(fline);
+    end
+
+%  find response function associated with confidence intervals
+
+    idresp=0;
+    for i=1:length(dresp)
+        if strcmpi(tokens{1}{ 1},dresp(i).descriptor)
+            idresp=i;
+            break;
+        end
+    end
+    if ~idresp
+        idresp=length(dresp)+1;
+        dresp(idresp).descriptor=tokens{1}{ 1};
+        display(sprintf('  %s',dresp(idresp).descriptor));
+    end
+
+%  add confidence intervals to response functions
+
+    if (ntokens == 14)
+        dresp(i).meanci  (1,1)=tokens{1}{ 5};
+        dresp(i).meanci  (2,1)=tokens{1}{ 6};
+        dresp(i).stddevci(1,1)=tokens{1}{12};
+        dresp(i).stddevci(2,1)=tokens{1}{13};
+    else
+        dresp(i).meanci  (1,1)=tokens{1}{ 2};
+        dresp(i).meanci  (2,1)=tokens{1}{ 3};
+        dresp(i).stddevci(1,1)=tokens{1}{ 4};
+        dresp(i).stddevci(2,1)=tokens{1}{ 5};
+    end
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read the cdf's
+
+function [dresp]=cdfs_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'Probabilities for each response function');
+    if ~ischar(fline)
+        [fline]=findline(fidi,'Level mappings for each response function');
+        if ~ischar(fline)
+            return
+        end
+    end
+end
+
+display('Reading CDF''s for response functions:');
+
+while ischar(fline) && ~isempty(fline)
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        break;
+    end
+
+%  process header line of cdf
+
+    while ischar(fline) && ~isempty(fline)
+        [ntokens,tokens]=fltokens(fline);
+
+%  find response function associated with cdf
+
+        idresp=0;
+        for i=1:length(dresp)
+            if strcmpi(tokens{1}{ 6},dresp(i).descriptor)
+                idresp=i;
+                break;
+            end
+        end
+        if ~idresp
+            idresp=length(dresp)+1;
+            dresp(idresp).descriptor=tokens{1}{ 6};
+            display(sprintf('  %s',dresp(idresp).descriptor));
+        end
+
+%  skip column headings of cdf
+
+        fline=fgetl(fidi);
+        fline=fgetl(fidi);
+
+%  read and add cdf table to response function
+
+        fline=fgetl(fidi);
+        icdf=0;
+        while ischar(fline) && ~isempty(fline) && ...
+              ~strncmpi(fline,'Cumulative Distribution Function',32)
+            [ntokens,tokens]=fltokens(fline);
+            icdf=icdf+1;
+            dresp(idresp).cdf(icdf,1:4)=NaN;
+%  in later versions of Dakota, uncalculated columns are now blank
+            itoken=0;
+            for i=1:length(fline)/19
+                if ~isempty(deblank(fline((i-1)*19+1:i*19)))
+                    itoken=itoken+1;
+                    dresp(idresp).cdf(icdf,i)=tokens{1}{itoken};
+                end
+            end
+            fline=fgetl(fidi);
+        end
+    end
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read the pdf's
+
+function [dresp]=pdfs_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'Probability Density Function (PDF) histograms for each response function');
+    if ~ischar(fline)
+        return
+    end
+end
+
+display('Reading PDF''s for response functions:');
+
+while ischar(fline) && ~isempty(fline)
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        break;
+    end
+
+%  process header line of pdf
+
+    while ischar(fline) && ~isempty(fline)
+        [ntokens,tokens]=fltokens(fline);
+
+%  find response function associated with pdf
+
+        idresp=0;
+        for i=1:length(dresp)
+            if strcmpi(tokens{1}{ 3},dresp(i).descriptor)
+                idresp=i;
+                break;
+            end
+        end
+        if ~idresp
+            idresp=length(dresp)+1;
+            dresp(idresp).descriptor=tokens{1}{ 3};
+            display(sprintf('  %s',dresp(idresp).descriptor));
+        end
+
+%  skip column headings of pdf
+
+        fline=fgetl(fidi);
+        fline=fgetl(fidi);
+
+%  read and add pdf table to response function
+
+        fline=fgetl(fidi);
+        ipdf=0;
+        while ischar(fline) && ~isempty(fline) && ...
+              ~strncmpi(fline,'PDF for', 7)
+            [ntokens,tokens]=fltokens(fline);
+            ipdf=ipdf+1;
+            dresp(idresp).pdf(ipdf,1:3)=NaN;
+            for i=1:3
+                dresp(idresp).pdf(ipdf,i)=tokens{1}{i};
+            end
+            fline=fgetl(fidi);
+        end
+    end
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read a correlation matrix
+
+function [cmat]=corrmat_read(fidi,cmstr,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,cmstr);
+    if ~ischar(fline)
+        cmat=struct([]);
+        return
+    end
+end
+
+display(['Reading ''' fline '''.']);
+
+cmat.title=fline;
+
+while ~isempty(fline)
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        break;
+    end
+
+%  process column headings of matrix
+
+    [ntokens,tokens]=fltokens(fline);
+    cmat.column=cell(1,ntokens);
+    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
+
+    nrow=0;
+    while 1
+        fline=fgetl(fidi);
+        if isempty(fline)
+            break;
+        end
+        [ntokens,tokens]=fltokens(fline);
+
+%  add row heading to matrix
+
+        nrow=nrow+1;
+        cmat.row   (nrow,1)=cellstr(tokens{1}{1});
+
+%  add row values to matrix
+
+        for i=2:ntokens
+            cmat.matrix(nrow,i-1)=tokens{1}{i};
+        end
+    end
+end
+
+end
+
+%%  function to find and read the MV statistics
+
+function [dresp]=mvstats_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'MV Statistics for ');
+    if ~ischar(fline)
+        return
+    end
+end
+
+display('Reading MV statistics for response functions:');
+ndresp=0;
+
+while ischar(fline) && ~isempty(fline) && ...
+        strncmpi(fline,'MV Statistics for ',18)
+
+%  add new response function and moments
+
+    [ntokens,tokens]=fltokens(fline);
+    dresp(end+1).descriptor=tokens{1}{4};
+    display(sprintf('  %s',dresp(end).descriptor));
+    fline=fgetl(fidi);
+    [ntokens,tokens]=fltokens(fline);
+    dresp(end  ).mean      =tokens{1}{5};
+    fline=fgetl(fidi);
+    [ntokens,tokens]=fltokens(fline);
+    dresp(end  ).stddev    =tokens{1}{7};
+
+%  read and add importance factors to response function
+
+	idvar=0;
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        break;
+    end
+
+    while ischar(fline) && ~isempty(fline) && ...
+            strncmpi(fline,'  Importance Factor for variable ',33)
+        [ntokens,tokens]=fltokens(fline);
+        idvar=idvar+1;
+        dresp(end).var   (idvar,1)=cellstr(tokens{1}{ 5});
+        dresp(end).impfac(idvar,1)=        tokens{1}{ 7};
+        if (ntokens >= 10)
+            dresp(end).sens  (idvar,1)=        tokens{1}{10};
+        else
+            dresp(end).sens  (idvar,1)=NaN;
+        end
+
+        fline=fgetl(fidi);
+    end
+
+%  if importance factors missing, skip to cdf
+
+    if ~idvar
+        display('    Importance Factors not available.');
+        dresp(end).var   ={};
+        dresp(end).impfac=[];
+        dresp(end).sens  =[];
+        while ischar(fline) && ...
+                ~strncmpi(fline,'Cumulative Distribution Function',32) && ...
+                ~strncmpi(fline,'MV Statistics for ',18) && ...
+                ~strncmp (fline,'-',1)
+            fline=fgetl(fidi);
+        end
+    end
+
+%  process header line of cdf
+
+    icdf=0;
+
+    while ischar(fline) && ~isempty(fline) && ...
+            strncmpi(fline,'Cumulative Distribution Function',32)
+        [ntokens,tokens]=fltokens(fline);
+
+%  find response function associated with cdf
+
+        idresp=0;
+        for i=1:length(dresp)
+            if strcmpi(tokens{1}{ 6},dresp(i).descriptor)
+                idresp=i;
+                break;
+            end
+        end
+        if ~idresp
+            idresp=length(dresp)+1;
+            dresp(idresp).descriptor=tokens{1}{ 6};
+            display(sprintf('  %s',dresp(idresp).descriptor));
+        end
+
+%  skip column headings of cdf
+
+        fline=fgetl(fidi);
+        fline=fgetl(fidi);
+
+%  read and add cdf table to response function
+
+        fline=fgetl(fidi);
+        while ~isempty(fline) && ...
+                ~strncmpi(fline,'MV Statistics for ',18) && ...
+                ~strncmp (fline,'-',1)
+            [ntokens,tokens]=fltokens(fline);
+            icdf=icdf+1;
+            dresp(idresp).cdf(icdf,1)=tokens{1}{1};
+            dresp(idresp).cdf(icdf,2)=tokens{1}{2};
+            if (ntokens == 4)
+                dresp(idresp).cdf(icdf,3)=tokens{1}{3};
+                dresp(idresp).cdf(icdf,4)=tokens{1}{4};
+            else
+                dresp(idresp).cdf(icdf,3)=NaN;
+                dresp(idresp).cdf(icdf,4)=NaN;
+            end
+            fline=fgetl(fidi);
+        end
+    end
+
+%  if cdf missing, skip to end of response function
+
+    if ~icdf
+        display('    Cumulative Distribution Function not available.');
+        dresp(ndresp).cdf=[];
+        while ischar(fline) && ...
+                ~strncmpi(fline,'MV Statistics for ',18) && ...
+                ~strncmp (fline,'-',1)
+            fline=fgetl(fidi);
+        end
+    end
+
+end
+
+display(sprintf('  Number of Dakota response functions=%d.',...
+    length(dresp)));
+
+end
+
+%%  function to find and read the best evaluation
+
+function [dresp]=best_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'<<<<< Best ');
+    if ~ischar(fline)
+        return
+    end
+end
+
+if isempty(dresp)
+    dresp(end+1).best=[];
+end
+display('Reading values for best function evaluation:');
+
+while ischar(fline) && ~isempty(fline) && ...
+        strncmpi(fline,'<<<<< Best ',11)
+    [ntokens,tokens]=fltokens(fline);
+
+%  read and add best parameter(s)
+
+    if     strncmpi(cellstr(tokens{1}{3}),'parameter', 9)
+        display(['  ' deblank(fline)]);
+
+        fline=fgetl(fidi);
+	    dresp.best.param     =[];
+        dresp.best.descriptor={};
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            [ntokens,tokens]=fltokens(fline);
+            dresp.best.param     (end+1,1)=        tokens{1}{1};
+            dresp.best.descriptor(end+1,1)=cellstr(tokens{1}{2});
+            fline=fgetl(fidi);
+        end
+
+%  read and add best objective function(s)
+
+    elseif strncmpi(cellstr(tokens{1}{3}),'objective', 9) && ...
+           strncmpi(cellstr(tokens{1}{4}),'function' , 8)
+        display(['  ' deblank(fline)]);
+
+        fline=fgetl(fidi);
+	    dresp.best.of=[];
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            [ntokens,tokens]=fltokens(fline);
+            dresp.best.of(end+1,1)=        tokens{1}{1};
+            fline=fgetl(fidi);
+        end
+
+%  read and add best residual norms
+
+    elseif strncmpi(cellstr(tokens{1}{3}),'residual', 8) && ...
+           strncmpi(cellstr(tokens{1}{4}),'norm'    , 4)
+        display(['  ' deblank(fline)]);
+        dresp.best.norm   =        tokens{1}{ 6};
+        dresp.best.hnormsq=        tokens{1}{11};
+
+        fline=fgetl(fidi);
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            fline=fgetl(fidi);
+        end
+
+%  read and add best residual term(s)
+
+    elseif strncmpi(cellstr(tokens{1}{3}),'residual', 8) && ...
+           strncmpi(cellstr(tokens{1}{4}),'term'    , 4)
+        display(['  ' deblank(fline)]);
+
+        fline=fgetl(fidi);
+	    dresp.best.res=[];
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            [ntokens,tokens]=fltokens(fline);
+            dresp.best.res(end+1,1)=        tokens{1}{1};
+            fline=fgetl(fidi);
+        end
+
+%  read and add best constraint value(s)
+
+    elseif strncmpi(cellstr(tokens{1}{3}),'constraint',10) && ...
+           strncmpi(cellstr(tokens{1}{4}),'value'     , 5)
+        display(['  ' deblank(fline)]);
+
+        fline=fgetl(fidi);
+	    dresp.best.nc=[];
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            [ntokens,tokens]=fltokens(fline);
+            dresp.best.nc(end+1,1)=        tokens{1}{1};
+            fline=fgetl(fidi);
+        end
+
+%  read and add best data captured
+
+    elseif strncmpi(cellstr(tokens{1}{3}),'data'    , 4) && ...
+           strncmpi(cellstr(tokens{1}{4}),'captured', 8)
+        display(['  ' deblank(fline)]);
+        dresp.best.eval=        tokens{1}{8};
+
+        fline=fgetl(fidi);
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            fline=fgetl(fidi);
+        end
+
+%  read until next best or blank or end
+
+    else
+        display(['  ' deblank(fline) '  (ignored)']);
+
+        fline=fgetl(fidi);
+
+        while ischar(fline) && ~isempty(fline) && ...
+                ~strncmpi(fline,'<<<<< Best ',11)
+            fline=fgetl(fidi);
+        end
+    end
+end
+
+end
+
+%%  function to find and read the volumetric uniformity measures
+
+function [dresp]=vum_read(fidi,dresp,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    [fline]=findline(fidi,'The following lists volumetric uniformity measures');
+    if ~ischar(fline)
+        return
+    end
+end
+
+if isempty(dresp)
+    dresp(end+1).vum=[];
+end
+display('Reading measures for volumetric uniformity.');
+
+fline=fgetl(fidi);
+fline=fgetl(fidi);
+
+while ischar(fline) && ~isempty(fline)
+	[ntokens,tokens]=fltokens(fline);
+    switch lower(tokens{1}{1})
+        case 'chi'
+            dresp.vum.chi=tokens{1}{4};
+        case 'd'
+            dresp.vum.d  =tokens{1}{4};
+        case 'h'
+            dresp.vum.h  =tokens{1}{4};
+        case 'tau'
+            dresp.vum.tau=tokens{1}{4};
+    end
+    fline=fgetl(fidi);
+end
+
+end
+
+%%  function to find and read the iterator completion
+
+function [method]=itcomp_read(fidi,fline)
+
+if ~exist('fline','var') || isempty(fline) || ~ischar(fline)
+    while 1
+        [fline]=findline(fidi,'<<<<< Iterator ');
+        if ~ischar(fline)
+            return
+        end
+        if (length(fline) > 26) && ...
+           ~isempty(strfind(fline(16:end),' completed.'))
+            break
+        end
+    end
+end
+
+[ntokens,tokens]=fltokens(fline);
+method=tokens{1}{3};
+display(sprintf('Dakota iterator ''%s'' completed.',method));
+
+end
+
+%%  function to find a file line starting with a specified string
+
+function [fline]=findline(fidi,string)
+
+ipos=ftell(fidi);
+
+while 1
+    fline=fgetl(fidi);
+    if ~ischar(fline)
+        break;
+    else
+        if (strncmpi(fline,string,length(string)))
+            return;
+        end
+    end
+end
+
+%  issue warning and reset file position
+
+warning('findline:str_not_found',...
+    'String ''%s'' not found in file.',string);
+fseek(fidi,ipos,'bof');
+
+end
+
+%%  function to parse a file line into tokens
+
+function [ntokens,tokens]=fltokens(fline)
+
+if ~ischar(fline)
+    ntokens=-1;
+    tokens={};
+    return;
+end
+if isempty(fline)
+    ntokens=0;
+    tokens={};
+    return;
+end
+
+strings=textscan(fline,'%s','delimiter',' :');
+%for i=1:length(strings{1})
+%    display(sprintf('i=%d; strings{1}{%d}=%s',i,i,strings{1}{i}))
+%end
+ntokens=0;
+tokens{1}{length(strings)}='';
+
+for i=1:length(strings{1})
+    if isempty(strings{1}{i})
+        continue
+    end
+    ntokens=ntokens+1;
+    inum=sscanf(strings{1}{i},'%f');
+    if isempty(inum)
+        tokens{1}{ntokens}=strings{1}{i};
+%        display(sprintf('i=%d; tokens{1}{%d}=%s',...
+%            i,ntokens,tokens{1}{ntokens}))
+    else
+        tokens{1}{ntokens}=inum;
+%        display(sprintf('i=%d; tokens{1}{%d}=%f',...
+%            i,ntokens,tokens{1}{ntokens}))
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_resp_uconv.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_resp_uconv.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/dakota_resp_uconv.m	(revision 18231)
@@ -0,0 +1,112 @@
+%
+%  convert the units for dakota responses.
+%
+%  [dresp]=dakota_resp_uconv(dresp)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%
+%  the required output is:
+%    dresp         (structure array, responses)
+%
+%  this function reads through a dakota response structure, and
+%  for those quantities whose descriptors are recognized, converts
+%  the units of all the applicable fields.  a "unit" field is added
+%  to the response structure.
+%
+%  this data would typically be read by dakota_out_parse and be used
+%  for plotting and other post-processing within matlab or excel.
+%
+%  "Copyright 2010, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function [dresp]=dakota_resp_uconv(dresp)
+
+if ~nargin
+    help dakota_resp_uconv
+    return
+end
+
+if ~isstruct(dresp)
+    error('''%s'' is not a structure array.',inputname(1));
+end
+if ~isfield(dresp,'descriptor')
+    error('''%s'' does not have a descriptor field.',inputname(1));
+end
+
+%%  define the conversion factors
+
+sec_per_yr=365.2425*24*60*60;    %  mean gregorian year
+m_per_km=1000;
+kg_per_gton=10^12;
+
+%%  loop through the response array
+
+for i=1:numel(dresp)
+    dresp(i).unit='';
+    if     ~isempty(strfind(dresp(i).descriptor,'vel'))    %  in m/sec
+        dresp(i)=drespi_conv(dresp(i),sec_per_yr,'m/yr');
+    elseif ~isempty(strfind(dresp(i).descriptor,'misfit'))    %  in m^2*(m/sec)^2
+        dresp(i)=drespi_conv(dresp(i),1/m_per_km^2*sec_per_yr^2,'km^2*(m/yr)^2');
+    elseif ~isempty(strfind(dresp(i).descriptor,'mass_flux'))    %  in kg/sec
+        dresp(i)=drespi_conv(dresp(i),1/kg_per_gton*sec_per_yr,'Gton/yr');
+    else
+        disp(['Skipping response ''' dresp(i).descriptor '''.']);
+    end
+end
+
+end
+
+%%  function to convert the units of a dakota response
+
+function [dresp]=drespi_conv(dresp,unew_per_uold,ulab)
+
+disp(['Converting response ''' dresp.descriptor ''' to ' ulab '.']);
+
+%  loop over the fields, converting only the appropriate ones
+
+fnames=fieldnames(dresp);
+for i=1:length(fnames)
+    switch fnames{i}
+        case {'sample',...
+              'mean',...
+              'stddev',...
+              'meanci',...
+              'stddevci',...
+              'min',...
+              'quart1',...
+              'median',...
+              'quart3',...
+              'max'}    %  appropriate to convert
+            dresp.(fnames{i})=dresp.(fnames{i})*unew_per_uold;
+        case {'cdf'}    %  only responses, not probs or reliabilities
+            dresp.cdf(:,1)=dresp.cdf(:,1)*unew_per_uold;
+        case {'descriptor',...
+              'coefvar',...
+              'var',...
+              'impfac'}    %  unitless (or non-numeric)
+            continue;
+        case {'best',...
+              'vum',...
+              'unit'}    %  other
+            continue;
+        otherwise
+            disp(['Unrecognized field ''' fnames{i} '''.']);
+    end
+end
+
+if isfield(dresp,'unit')
+    dresp.unit=ulab;
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/README	(revision 18231)
@@ -0,0 +1,3 @@
+Example parameter files to setup QMU (quantification of margins and uncertainties) using Dakota.
+
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/all_parameters.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/all_parameters.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/all_parameters.m	(revision 18231)
@@ -0,0 +1,91 @@
+%  set up some qmu studies, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_ice',917,45.85);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thickness',1,0.05);
+md.qmu.variables.nuv(end+1)=normal_uncertain('drag',1,0.05);
+md.qmu.variables.cdv=continuous_design.empty();
+md.qmu.variables.cdv(end+1)=continuous_design('thickness',1,0.9,1.1);
+md.qmu.variables.cdv(end+1)=continuous_design('drag',1,0.5,1.5);
+md.qmu.variables.csv=continuous_state.empty();
+md.qmu.variables.csv(end+1)=continuous_state('gravity',9.8);
+md.qmu.variables.lic=linear_inequality_constraint.empty();
+md.qmu.variables.lic(end+1)=linear_inequality_constraint([1 2 3],4,5);
+md.qmu.variables.lic(end+1)=linear_inequality_constraint([1 2],4,5);
+md.qmu.variables.lic(end+1)=linear_inequality_constraint([1 2 3 4],4,5);
+md.qmu.variables.lec=linear_equality_constraint.empty();
+md.qmu.variables.lec(end+1)=linear_equality_constraint([1 2 3],4);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[100 200 300],[]);
+md.qmu.responses.rf (end+1)=response_function('max_vel'   ,[100 200 300],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.of =objective_function.empty();
+md.qmu.responses.of (end+1)=objective_function('max_vel');
+md.qmu.responses.lst=least_squares_term.empty();
+md.qmu.responses.lst(end+1)=least_squares_term('max_vel');
+md.qmu.responses.nic=nonlinear_inequality_constraint.empty();
+md.qmu.responses.nic(end+1)=nonlinear_inequality_constraint('max_abs_vx',0,1000);
+md.qmu.responses.nic(end+1)=nonlinear_inequality_constraint('max_abs_vy',0,1000);
+md.qmu.responses.nec=nonlinear_equality_constraint.empty();
+md.qmu.responses.nec(end+1)=nonlinear_equality_constraint('max_abs_vx',500);
+md.qmu.responses.nec(end+1)=nonlinear_equality_constraint('max_abs_vy',500);
+
+%%  a variety of studies
+
+%  a sampling study
+
+md.qmu.method       =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'seed',1234,...
+    'samples',10);
+
+%  a local reliability study
+
+md.qmu.method(end+1)=dakota_method('nond_l');
+
+%  a multidimensional parameter study
+
+md.qmu.method(end+1)=dakota_method('multi');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'partitions',2);
+
+%  an optimization study
+
+md.qmu.method(end+1)=dakota_method('conmin_f');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'max_iterations',10,...
+    'max_function_evaluations',50,...
+    'convergence_tolerance',0.001);
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size=0.001;
+
+md.qmu.numberofpartitions=10;
+md.rifts.numrifts=5;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_2d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_2d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_2d.m	(revision 18231)
@@ -0,0 +1,60 @@
+%
+%  multi-dimensional parameter study for rosenbrock case
+%  (see Users4.2.pdf, Sec. 2.4.1)
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+
+function [dout,ddat]=dakota_rosenbrock_2d()
+
+%  define dakota variables as continuous design
+%  (may use set 1 or set 2 of variables, but not both)
+dvar(1).cdv(1)=continuous_design('x1',0,-2,2);
+dvar(1).cdv(2)=continuous_design('x2',0,-2,2);
+dvar(2).x1=continuous_design('',0,-2,2);
+dvar(2).x2=continuous_design('',0,-2,2);
+
+%  define dakota response as objective function
+%  (may use set 1 or set 2 of responses, but not both)
+dresp(1).of=objective_function('f');
+dresp(2).f=objective_function('');
+
+%  define dakota method and specify method-dependent parameters
+dmeth=dakota_method('multidim');
+dmeth=dmeth_params_set(dmeth,'partitions',[8 8]);
+
+%  specify method-independent parameters
+%  (dakota_in_params does not need to be called, but provides a template)
+dparams=dakota_in_params([]);
+dparams.direct=true;
+dparams.analysis_driver='rosenbrock';
+dparams.tabular_graphics_data=true;
+dparams.tabular_graphics_file='dakota_rosenbrock_2d.dat';
+
+%  write out dakota input file
+dakota_in_write(dmeth,dvar(2),dresp(2),dparams,'dakota_rosenbrock_2d.in')
+
+%  execute dakota
+!dakota -i dakota_rosenbrock_2d.in -o dakota_rosenbrock_2d.out
+
+%  read dakota output and tabular data files
+%  (output file for parameter studies has no interesting info)
+[method,dout]=dakota_out_parse('dakota_rosenbrock_2d.out');
+[~     ,ddat]=dakota_out_parse('dakota_rosenbrock_2d.dat');
+
+%  perform any desired plotting
+plot_rvsv_surf(ddat,{'x1','x2'},ddat,{'f'})
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_ls.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_ls.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_ls.m	(revision 18231)
@@ -0,0 +1,58 @@
+%
+%  least squares study for rosenbrock case
+%  (see Users4.2.pdf, Sec. 2.4.1)
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+
+function [dout,ddat]=dakota_rosenbrock_ls()
+
+%  define dakota variables as continuous design
+dvar.x1=continuous_design('',-1.2,-2,2);
+dvar.x2=continuous_design('', 1.0,-2,2);
+
+%  define dakota response as least-squares terms
+dresp.f1sq=least_squares_term('');
+dresp.f2sq=least_squares_term('');
+
+%  define dakota method and specify method-dependent parameters
+dmeth=dakota_method('nl2sol');
+dmeth=dmeth_params_set(dmeth,'max_iterations',100,...
+                             'convergence_tolerance',1.e-4);
+
+%  specify method-independent parameters
+%  (dakota_in_params does not need to be called, but provides a template)
+dparams=dakota_in_params([]);
+dparams.direct=true;
+dparams.analysis_driver='rosenbrock';
+dparams.tabular_graphics_data=true;
+dparams.tabular_graphics_file='dakota_rosenbrock_ls.dat';
+dparams.analytic_gradients=true;
+
+%  write out dakota input file
+dakota_in_write(dmeth,dvar,dresp,dparams,'dakota_rosenbrock_ls.in')
+
+%  execute dakota
+!dakota -i dakota_rosenbrock_ls.in -o dakota_rosenbrock_ls.out
+
+%  read dakota output and tabular data files
+%  (output file for parameter studies has no interesting info)
+[method,dout]=dakota_out_parse('dakota_rosenbrock_ls.out');
+[~     ,ddat]=dakota_out_parse('dakota_rosenbrock_ls.dat');
+
+%  perform any desired plotting
+% plot_rvsv_surf(ddat,{'x1','x2'},ddat,{'f'})
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_nond.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_nond.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_nond.m	(revision 18231)
@@ -0,0 +1,70 @@
+%
+%  monte carlo sampling for rosenbrock case
+%  (see Users4.2.pdf, Sec. 2.4.9)
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+
+function [dout,ddat,scm,pcm,srcm,prcm]=dakota_rosenbrock_nond()
+
+%  define dakota variables as uniform uncertain
+%  (may use set 1 or set 2 of variables, but not both)
+dvar(1).uuv(1)=uniform_uncertain('x1',-2,2);
+dvar(1).uuv(2)=uniform_uncertain('x2',-2,2);
+dvar(2).x1=uniform_uncertain('',-2,2);
+dvar(2).x2=uniform_uncertain('',-2,2);
+
+%  define dakota response as response function
+%  (may use set 1 or set 2 of responses, but not both)
+dresp(1).rf=response_function('f',[100]);
+dresp(2).f=response_function('',[100]);
+
+%  define dakota method and specify method-dependent parameters
+dmeth=dakota_method('nond_samp');
+dmeth=dmeth_params_set(dmeth,'samples',200,...
+                             'seed',17,...
+                             'sample_type','random');
+
+%  specify method-independent parameters
+%  (dakota_in_params does not need to be called, but provides a template)
+dparams=dakota_in_params([]);
+dparams.direct=true;
+dparams.analysis_driver='rosenbrock';
+dparams.tabular_graphics_data=true;
+dparams.tabular_graphics_file='dakota_rosenbrock_nond.dat';
+
+%  write out dakota input file
+dakota_in_write(dmeth,dvar(2),dresp(2),dparams,'dakota_rosenbrock_nond.in')
+
+%  execute dakota
+!dakota -i dakota_rosenbrock_nond.in -o dakota_rosenbrock_nond.out
+
+%  read dakota output and tabular data files
+[method,dout,scm,pcm,srcm,prcm]=dakota_out_parse('dakota_rosenbrock_nond.out');
+[~     ,ddat                  ]=dakota_out_parse('dakota_rosenbrock_nond.dat');
+
+%  perform any desired plotting
+plot_boxplot(ddat,{'f'})
+plot_normplot(ddat,{'f'})
+plot_sampdist_bars(ddat,{'f'})
+plot_normdist_bars(ddat,{'f'})
+plot_hist_norm(ddat,{'f'})
+plot_hist_norm(ddat,{'f'},'hmin',0,'hmax',200)
+plot_hist_norm_ci(ddat,{'f'})
+plot_hist_norm_ci(ddat,{'f'},'ciplt','line','cdfplt','off','ymin1',0,'ymax1',0.15)
+plot_prob_bars(dout,{'f'})
+plot_rlev_bars_ci(ddat,{'f'},'xtlrot',90)
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_vector.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_vector.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/dakota_rosenbrock_vector.m	(revision 18231)
@@ -0,0 +1,64 @@
+%
+%  vector parameter study for rosenbrock case
+%  (see Users4.2.pdf, Sec. 2.4.2)
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+
+function [dout,ddat]=dakota_rosenbrock_vector()
+
+%  define dakota variables as continuous design
+%  (may use set 1 or set 2 of variables, but not both)
+dvar(1).cdv(1)=continuous_design('x1',-0.3);
+dvar(1).cdv(2)=continuous_design('x2', 0.2);
+dvar(2).x1=continuous_design('',-0.3);
+dvar(2).x2=continuous_design('', 0.2);
+
+%  define dakota response as objective function
+%  (may use set 1 or set 2 of responses, but not both)
+dresp(1).of=objective_function('f');
+dresp(2).f=objective_function('');
+
+%  define dakota method and specify method-dependent parameters
+dmeth=dakota_method('vector');
+%  (ref. manual says step_length is required, but user's doesn't)
+dmeth=dmeth_params_set(dmeth,'final_point',[1.1 1.3],...
+                             'num_steps',10);
+
+%  specify method-independent parameters
+%  (dakota_in_params does not need to be called, but provides a template)
+dparams=dakota_in_params([]);
+dparams.direct=true;
+dparams.analysis_driver='rosenbrock';
+dparams.tabular_graphics_data=true;
+dparams.tabular_graphics_file='dakota_rosenbrock_vector.dat';
+
+%  write out dakota input file
+dakota_in_write(dmeth,dvar(2),dresp(2),dparams,'dakota_rosenbrock_vector.in')
+
+%  execute dakota
+!dakota -i dakota_rosenbrock_vector.in -o dakota_rosenbrock_vector.out
+
+%  read dakota output and tabular data files
+%  (output file for parameter studies has no interesting info)
+[method,dout]=dakota_out_parse('dakota_rosenbrock_vector.out');
+[~     ,ddat]=dakota_out_parse('dakota_rosenbrock_vector.dat');
+clear dum
+
+%  perform any desired plotting
+plot_rvsv_line(ddat,{'x1','x2'},ddat,{'f'})
+plot_rvsv_line(ddat,{'x1','x2'},ddat,{'f'},'nplotr',1,'nplotc',2)
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/direct.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/direct.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/direct.m	(revision 18231)
@@ -0,0 +1,9 @@
+%using library mode of Dakota, only for parallel runs.
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+
+%or for matlab direct driver
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='matlab';
+md.qmu.params.evaluation_concurrency=2; %launch 2 matlabs
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel.m	(revision 18231)
@@ -0,0 +1,55 @@
+%  set up a local reliability study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('RhoIce',917,45.85);
+md.qmu.variables.nuv(end+1)=normal_uncertain('RhoWater',1023,51.15);
+md.qmu.variables.nuv(end+1)=normal_uncertain('HeatCapacity',2009,100.45);
+md.qmu.variables.nuv(end+1)=normal_uncertain('ThermalConductivity',2.2,0.11);
+md.qmu.variables.nuv(end+1)=normal_uncertain('Gravity',9.8,0.49);
+md.qmu.variables.nuv(end+1)=normal_uncertain('Thickness',1,0.05);
+md.qmu.variables.nuv(end+1)=normal_uncertain('Drag',1,0.05);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('min_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  nond_local_reliability study
+
+md.qmu.method     =dakota_method('nond_l');
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size=0.01;
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel_mmf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel_mmf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lrel_mmf.m	(revision 18231)
@@ -0,0 +1,94 @@
+%  set up a local reliability study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+%md.qmu.variables.nuv(end+1)=normal_uncertain('RhoIce',917,45.85);
+%md.qmu.variables.nuv(end+1)=normal_uncertain('RhoWater',1023,51.15);
+%md.qmu.variables.nuv(end+1)=normal_uncertain('HeatCapacity',2009,100.45);
+%md.qmu.variables.nuv(end+1)=normal_uncertain('ThermalConductivity',2.2,0.11);
+%md.qmu.variables.nuv(end+1)=normal_uncertain('Gravity',9.8,0.49);
+md.qmu.variables.nuv(end+1)=normal_uncertain('Thickness',1,0.05);
+%md.qmu.variables.nuv(end+1)=normal_uncertain('Drag',1,0.05);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('min_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux(3)',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux4 (repeat)',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux-5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux^6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('mass_flux[7]',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  create mass flux profile
+
+%plotmodel(md,'data','mesh')
+%expcreateprofile('mass_flux.exp')
+%expdisp('mass_flux.exp')
+%md.qmu.mass_flux_profile='mass_flux.exp';
+%md.qmu.mass_flux_profile={'mass_flux.exp','mass_flux2.exp','mass_flux3.exp'};
+md.qmu.mass_flux_profile={'mass_flux.exp','mass_flux2.exp','mass_flux3.exp','mass_flux.exp','mass_flux5.exp','mass_flux6.exp','mass_flux7.exp'};
+
+%%  nond_local_reliability study
+
+md.qmu.method     =dakota_method('nond_l');
+
+%%  a variety of parameters
+
+%md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size=0.01;
+
+md.qmu.isdakota=1;
+md.qmu.numberofpartitions=10;
+if isempty(md.qmu.adjacency)
+	md=adjacency(md);
+end
+if isempty(md.qmu.partition)
+%    md.qmu.partition=partitioner(md,'package','metis','npart',md.qmu.numberofpartitions);
+    md.qmu.partition=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+% SpawnCore.m assumes partition vector starting at zero
+    md.qmu.partition=md.qmu.partition-1;
+end
+md.eps_rel=1.e-5;
+md.cluster=none;
+
+md.qmu
+
+%%  sample analysis
+
+%md=solve(md,'analysis_type','stressbalance');
+
+%plotmodel(md,'data','mesh')
+%plotmodel(md,'data',md.qmu.partition)
+%plotmodel(md,'data','mesh','partitionedges','on','linewidth',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/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lsq.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lsq.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/lsq.m	(revision 18231)
@@ -0,0 +1,50 @@
+%  set up a least-squares study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.cdv=continuous_design.empty();
+md.qmu.variables.cdv(end+1)=continuous_design('thickness',1,0.9,1.1);
+md.qmu.variables.cdv(end+1)=continuous_design('drag',1,0.5,1.5);
+md.qmu.variables.csv=continuous_state.empty();
+md.qmu.variables.csv(end+1)=continuous_state('gravity',9.8);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.lst=least_squares_term.empty();
+md.qmu.responses.lst(end+1)=least_squares_term('max_vx');
+md.qmu.responses.lst(end+1)=least_squares_term('max_vy');
+
+%%  a least-squares study
+
+md.qmu.method     =dakota_method('nl2sol');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'max_iterations',10,...
+    'max_function_evaluations',50,...
+    'convergence_tolerance',0.01);
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size=0.01;
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/opt.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/opt.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/opt.m	(revision 18231)
@@ -0,0 +1,49 @@
+%  set up an optimization study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.cdv=continuous_design.empty();
+md.qmu.variables.cdv(end+1)=continuous_design('thickness',1,0.9,1.1);
+md.qmu.variables.cdv(end+1)=continuous_design('drag',1,0.5,1.5);
+md.qmu.variables.csv=continuous_state.empty();
+md.qmu.variables.csv(end+1)=continuous_state('gravity',9.8);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.of =objective_function.empty();
+md.qmu.responses.of (end+1)=objective_function('max_vel');
+
+%%  an optimization study
+
+md.qmu.method     =dakota_method('conmin_f');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'max_iterations',10,...
+    'max_function_evaluations',50,...
+    'convergence_tolerance',0.01);
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size=0.01;
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramc.m	(revision 18231)
@@ -0,0 +1,53 @@
+%  set up a centered parameter study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_ice',917,45.85);
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_water',1023,51.15);
+md.qmu.variables.nuv(end+1)=normal_uncertain('heatcapacity',2009,100.45);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thermalconductivity',2.2,0.11);
+md.qmu.variables.cdv=continuous_design.empty();
+md.qmu.variables.cdv(end+1)=continuous_design('thickness',1,0.9,1.1);
+md.qmu.variables.cdv(end+1)=continuous_design('drag',1,0.5,1.5);
+md.qmu.variables.csv=continuous_state.empty();
+md.qmu.variables.csv(end+1)=continuous_state('gravity',9.8);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel'   ,[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  a parameter study
+
+md.qmu.method     =dakota_method('centered');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'percent_delta',10.,...
+    'deltas_per_variable',1);
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/paramm.m	(revision 18231)
@@ -0,0 +1,45 @@
+%  set up a multidim parameter study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_ice',917,45.85,900,1000);
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_water',1023,51.15,1000,1100);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel'   ,[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  a parameter study
+
+md.qmu.method     =dakota_method('multidim');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'partitions',[4 4]);
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp.m	(revision 18231)
@@ -0,0 +1,57 @@
+%  set up a sampling study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_ice',917,45.85);
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_water',1023,51.15);
+md.qmu.variables.nuv(end+1)=normal_uncertain('heatcapacity',2009,100.45);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thermalconductivity',2.2,0.11);
+md.qmu.variables.nuv(end+1)=normal_uncertain('gravity',9.8,0.49);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thickness',1,0.05);
+md.qmu.variables.nuv(end+1)=normal_uncertain('drag',1,0.05);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('min_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  nond_sampling study
+
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'seed',1234,...
+    'samples',20,...
+    'sample_type','lhs');
+
+%%  a variety of parameters
+
+md.qmu.params.evaluation_concurrency=4;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp_direct.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp_direct.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/examples/samp_direct.m	(revision 18231)
@@ -0,0 +1,57 @@
+%  set up a sampling study, like might be done in Pig.par
+
+%%  a variety of variables
+
+%  seems to be a Matlab bug here (on Linux, not WinXP) -- unless
+%  the class has been called, "empty" method can not be found
+normal_uncertain;
+continuous_design;
+continuous_state;
+linear_inequality_constraint;
+linear_equality_constraint;
+response_function;
+objective_function;
+least_squares_term;
+nonlinear_inequality_constraint;
+nonlinear_equality_constraint;
+
+md.qmu.variables=struct();
+md.qmu.variables.nuv=normal_uncertain.empty();
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_ice',917,45.85);
+md.qmu.variables.nuv(end+1)=normal_uncertain('rho_water',1023,51.15);
+md.qmu.variables.nuv(end+1)=normal_uncertain('heatcapacity',2009,100.45);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thermalconductivity',2.2,0.11);
+md.qmu.variables.nuv(end+1)=normal_uncertain('gravity',9.8,0.49);
+md.qmu.variables.nuv(end+1)=normal_uncertain('thickness',1,0.05);
+md.qmu.variables.nuv(end+1)=normal_uncertain('drag',1,0.05);
+
+%%  a variety of responses
+
+md.qmu.responses=struct();
+md.qmu.responses.rf =response_function.empty();
+md.qmu.responses.rf (end+1)=response_function('min_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vx',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_abs_vy',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('min_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.rf (end+1)=response_function('max_vel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  nond_sampling study
+
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+    'seed',1234,...
+    'samples',20,...
+    'sample_type','lhs');
+
+%%  a variety of parameters
+
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandresponses.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandresponses.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandresponses.m	(revision 18231)
@@ -0,0 +1,14 @@
+function dresp=expandresponses(md,responses)
+%EXPANDRESPONSES - expand responses
+
+fnames=fieldnames(responses);
+
+for i=1:length(fnames)
+
+	fhandle=str2func([class(responses.(fnames{i})) '.empty']);
+	dresp.(fnames{i})=fhandle();
+	for j=1:length(responses.(fnames{i}))
+		%call setupdesign
+		dresp.(fnames{i})=QmuSetupResponses(md,dresp.(fnames{i}),responses.(fnames{i})(j));
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandvariables.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandvariables.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/expandvariables.m	(revision 18231)
@@ -0,0 +1,23 @@
+function dvar=expandvariables(md,variables)
+
+fnames=fieldnames(variables);
+
+for i=1:length(fnames)
+
+%  for linear constraints, just copy
+
+    if isa(variables.(fnames{i}),'linear_inequality_constraint') || ...
+       isa(variables.(fnames{i}),'linear_equality_constraint'  )
+        dvar.(fnames{i})=variables.(fnames{i});
+
+%  for variables, call the setup function
+
+    else
+        fhandle=str2func([class(variables.(fnames{i})) '.empty']);
+        dvar.(fnames{i})=fhandle();
+        for j=1:length(variables.(fnames{i}))
+            %call setupdesign
+            dvar.(fnames{i})=QmuSetupVariables(md,dvar.(fnames{i}),variables.(fnames{i})(j));
+        end
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/importancefactors.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/importancefactors.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/importancefactors.m	(revision 18231)
@@ -0,0 +1,63 @@
+function factors=importancefactors(md,variablename,responsename)
+%IMPORTANCEFACTORS - compute importance factors for a certain variable and response.
+%
+%   Usage:
+%      factors=importancefactors(md,variablename,responsename)
+%
+%
+%   Example: factors=importancefactors(md,'drag','max_vel');
+%
+
+variablenamelength=length(variablename);
+
+%go through all response functions and find the one corresponding to the correct responsename
+responsefunctions=md.qmu.results.dresp_out;
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsename),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.var,1);
+
+%Now recover response to the correct design variable
+importancefactors=zeros(1,0);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.var{i};
+	if strncmpi(desvar,variablename,variablenamelength),
+		importancefactors(end+1)=responsefunctions.impfac(i);
+		count=count+1;
+	end
+end
+
+if count==0,
+	error('importancefactors error message: either response does not exist, or importancefactors are empty');
+end
+
+if count==1, %we have scalar
+	factors=importancefactors;
+	return;
+else
+	%distribute importance factor
+	factors=importancefactors(md.qmu.partition'+1); %md.qmu.partition was created to index "c" style
+end
+
+%weight importancefactors by area
+%if numel(factors)==md.mesh.numberofvertices,
+%	%get areas for each vertex.
+%	aire=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+%	num_elements_by_node=md.nodeconnectivity(:,end);
+%	grid_aire=zeros(md.mesh.numberofvertices,1);
+%	for i=1:md.mesh.numberofvertices,
+%		for j=1:num_elements_by_node(i),
+%			grid_aire(i)=grid_aire(i)+aire(md.nodeconnectivity(i,j));
+%		end
+%	end
+%	factors=factors./grid_aire;
+%end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/lclist_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/lclist_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/lclist_write.m	(revision 18231)
@@ -0,0 +1,61 @@
+%
+%  function to write linear constraint list
+%
+function []=lclist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put linear constraints into lists for writing
+
+nvar=0;
+pmatrix=[];
+plower =[];
+pupper =[];
+ptarget=[];
+pstype =[];
+pscale =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pmatrix=[pmatrix prop_matrix(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+end
+
+%  write linear constraints
+
+disp(sprintf('  Writing %d %s linear constraints.',...
+    nvar,cstring));
+
+if ~isempty(pmatrix)
+    fprintf(fidi,'\t  %s_matrix =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmatrix,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/param_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/param_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/param_write.m	(revision 18231)
@@ -0,0 +1,24 @@
+%
+%  function to write a parameter
+%
+function []=param_write(fidi,sbeg,pname,smid,send,params)
+
+if ~isfield(params,pname)
+    warning('param_write:param_not_found',...
+        'Parameter ''%s'' not found in structure.',pname);
+    return
+end
+
+if islogical(params.(pname)) && ~params.(pname)
+    return
+end
+
+if     islogical(params.(pname))
+    fprintf(fidi,[sbeg '%s' send],pname);
+elseif ischar   (params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%s' send],pname,params.(pname));
+elseif isnumeric(params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%g' send],pname,params.(pname));
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_boxplot.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_boxplot.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_boxplot.m	(revision 18231)
@@ -0,0 +1,151 @@
+%
+%  plot a box plot of the responses.
+%
+%  []=plot_boxplot(dresp      ,params)
+%  []=plot_boxplot(dresp,descr,params)
+%  []=plot_boxplot(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%
+%  for each response in the input array, this function plots a
+%  matlab box plot of the list of samples and annotates it
+%  with the description.  the lists of samples need not all be
+%  the same length.
+%
+%  this data would typically be contained in the dakota tabular
+%  output file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_boxplot(varargin)
+
+if ~nargin
+    help plot_boxplot
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  draw the plot
+
+%  draw box plot
+
+figure
+boxplot(sampr,'labels',descr,'notch','on')
+ax1=gca;
+
+%  add the annotation
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+if (size(sampr,2) == 1)
+    tlabc=descr{1};
+else
+    tlabc='Responses';
+end
+title(['Box Plot of ' tlabc],'Interpreter','none');
+xlabel('Response','Interpreter','none');
+ylabel('Value'   ,'Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_cdf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_cdf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_cdf.m	(revision 18231)
@@ -0,0 +1,370 @@
+%
+%  plot the CDF of the responses.
+%
+%  []=plot_cdf(dresp      ,params)
+%  []=plot_cdf(dresp,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    cdf(:,4)      (double matrix, CDF table)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    cplot         (char, 'p'/'r'/'g' to plot prob/reli/genrel)
+%    xmin          (numeric, minimum of x-axis)
+%    xmax          (numeric, maximum of x-axis)
+%    xgrid         (char, 'on' to turn on x-grid lines)
+%    ymin1         (numeric, minimum of y-axis)
+%    ymax1         (numeric, maximum of y-axis)
+%    ygrid1        (char, 'on' to turn on y-grid lines)
+%    ynorm         (char, 'yes' to use normal probability y-axis)
+%    yprob         (double vector, list of probabilities for y-axis)
+%    cline1        (char, 'off'/'no'/'-'/'--'/':'/etc. to change lines)
+%    lwidth1       (numeric, line width in points, default 0.5)
+%    cmark1        (char, 'on'/'yes'/'+'/'o'/'*'/etc. to change markers)
+%    msize1        (numeric, marker size in points, default 6)
+%    ymin2         (numeric, minimum of y-axis)
+%    ymax2         (numeric, maximum of y-axis)
+%    ygrid2        (char, 'on' to turn on y-grid lines)
+%    cline2        (char, 'off'/'no'/'-'/'--'/':'/etc. to change lines)
+%    lwidth2       (numeric, line width in points, default 0.5)
+%    cmark2        (char, 'on'/'yes'/'+'/'o'/'*'/etc. to change markers)
+%    msize2        (numeric, marker size in points, default 6)
+%    pdfplt        (char, 'bar'/'line'/'off' for pdf plots)
+%    pdfleg        (char, 'off' to turn off pdf legends)
+%    cmap          (char or numeric, colormap definition)
+%
+%  for each response in the input array, this function plots
+%  a line plot of the CDF and annotates it with the description.
+%
+%  this data would typically be contained in the dakota output
+%  file and read by dakota_out_parse.
+%
+%  "Copyright 2010, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_cdf(varargin)
+
+if ~nargin
+    help plot_cdf
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+else
+    error(['''' inputname(iarg) ''' is not a structure.']);
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'cplot','xmin','xmax','xgrid',...
+                 'ymin1','ymax1','ygrid1','ynorm','yprob',...
+                 'cline1','lwidth1','cmark1','msize1',...
+                 'ymin2','ymax2','ygrid2',...
+                 'cline2','lwidth2','cmark2','msize2',...
+                 'pdfplt','pdfleg','cmap'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if ~exist('cplot','var') || strncmpi(cplot,'p',1)
+    cplot='Probabilit';
+    iplot=2;
+elseif strncmpi(cplot,'r',1)
+    cplot='Reliabilit';
+    iplot=3;
+elseif strncmpi(cplot,'g',1)
+    cplot='General Reliabilit';
+    iplot=4;
+end
+
+%  assemble data into matrices, based on parameters
+
+descr=cell (1,length(dresp));
+lcdfr=zeros(1,length(dresp));
+for i=1:length(dresp)
+    lcdfr(i)=size(dresp(i).cdf,1);
+end
+xdata=zeros(max(lcdfr),length(dresp));
+xdata(:,:)=NaN;
+ydata=zeros(max(lcdfr),length(dresp));
+ydata(:,:)=NaN;
+
+for i=1:length(dresp)
+    descr(i)=cellstr(dresp(i).descriptor);
+    if ~isempty(dresp(i).cdf)
+        xdata(1:lcdfr(i),i)=dresp(i).cdf(:,1);
+        if strncmpi(cplot,'p',1) && ...
+           exist('ynorm','var') && strncmpi(ynorm,'y',1)
+             ydata(1:lcdfr(i),i)=norminv_issm(dresp(i).cdf(:,iplot),0,1);
+        else
+             ydata(1:lcdfr(i),i)=             dresp(i).cdf(:,iplot);
+        end
+    end
+end
+
+%%  draw the line plot
+
+%newplot();
+figure
+ax1=axes;
+
+if ~exist('cline1','var') || strncmpi(cline1,'on' ,2) || strncmpi(cline1,'y',1)
+    cline1='-';
+elseif strncmpi(cline1,'off',3) || strncmpi(cline1,'n',1)
+    cline1='none';
+end
+if ~exist('lwidth1','var')
+    lwidth1=0.5;
+end
+if ~exist('cmark1','var') || strncmpi(cmark1,'off',3) || strncmpi(cmark1,'n',1)
+    cmark1='none';
+elseif strncmpi(cmark1,'on' ,2) || strncmpi(cmark1,'y',1) || ...
+       (length(cmark1) > 1)
+    cmark1='+';
+end
+if ~exist('msize1','var')
+    msize1=6;
+end
+
+hl1=line(xdata,ydata,'Parent',ax1,'LineStyle',cline1,'LineWidth',lwidth1,...
+         'Marker',cmark1,'MarkerSize',msize1);
+
+%  set lines to have a continuous colormap
+
+if exist('cmap','var')
+    colormap(cmap)
+end
+
+cmap=colormap;
+for i=1:length(hl1)
+    if (length(hl1) > 1)
+        imap=round((i-1)/(length(hl1)-1)*(size(cmap,1)-1))+1;
+    else
+        imap=1;
+    end
+    set(hl1(i),'Color',cmap(imap,:))
+end
+
+xlim('auto')
+[xlims]=xlim;
+if exist('xmin','var')
+    xlims(1)=xmin;
+end
+if exist('xmax','var')
+    xlims(2)=xmax;
+end
+xlim(xlims)
+if exist('xgrid','var') && strncmpi(xgrid,'on',2)
+    set(ax1,'XGrid','on')
+end
+if strncmpi(cplot,'p',1)
+    [ylims]=[0 1];
+else
+    ylim('auto')
+    [ylims]=ylim;
+end
+if exist('ymin1','var')
+    ylims(1)=ymin1;
+end
+if exist('ymax1','var')
+    ylims(2)=ymax1;
+end
+ylim(ylims)
+if exist('ygrid1','var') && strncmpi(ygrid1,'on',2)
+    set(ax1,'YGrid','on')
+end
+
+%  add the annotation
+
+if strncmpi(cplot,'p',1) && ...
+   exist('ynorm','var') && strncmpi(ynorm,'y',1)
+%  copied and adapted from matlab normplot function
+    if ~exist('yprob','var')
+        yprob = [0.001 0.003 0.01 0.02 0.05 0.10 0.25 0.5...
+                 0.75 0.90 0.95 0.98 0.99 0.997 0.999];
+    end
+
+%  matlab docs say str2mat is obsolete, so replace (and eliminate redundancy)
+%     label1= str2mat('0.001','0.003', '0.01','0.02','0.05','0.10','0.25','0.50');
+%     label2= str2mat('0.75','0.90','0.95','0.98','0.99','0.997', '0.999');
+%     label = [label1;label2];
+    label=cell(1,length(yprob));
+    for i=1:length(yprob)
+        label(i)=cellstr(num2str(yprob(i)));
+    end
+
+    tick  = norminv_issm(yprob,0,1);
+    set(ax1,'YTick',tick,'YTickLabel',label);
+    ylim([tick(1) tick(end)])
+end
+
+title([cplot 'ies for Response Levels'])
+xlabel('Response Level')
+ylabel([cplot 'y'])
+
+hleg1=legend(ax1,descr(1:length(hl1)),'Location','NorthWest',...
+             'Color','none','Interpreter','none');
+
+%%  generate the probability distribution functions
+
+if ~exist('pdfplt','var') || ~strcmpi(pdfplt,'off')
+    xpdf =zeros(max(lcdfr)-1,length(dresp));
+    xpdf (:,:)=NaN;
+    ypdf =zeros(max(lcdfr)-1,length(dresp));
+    ypdf (:,:)=NaN;
+    xplot=zeros(2*max(lcdfr),length(dresp));
+    xplot(:,:)=NaN;
+    yplot=zeros(2*max(lcdfr),length(dresp));
+    yplot(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr([dresp(i).descriptor ' pdf']);
+        if ~isempty(dresp(i).cdf) && (lcdfr(i) > 1)
+            xpdf (1:lcdfr(i)-1,i)=(dresp(i).cdf(1:lcdfr(i)-1,1)+...
+                                   dresp(i).cdf(2:lcdfr(i)  ,1))/2;
+            ypdf (1:lcdfr(i)-1,i)=(dresp(i).cdf(2:lcdfr(i)  ,2)-...
+                                   dresp(i).cdf(1:lcdfr(i)-1,2))./...
+                                  (dresp(i).cdf(2:lcdfr(i)  ,1)-...
+                                   dresp(i).cdf(1:lcdfr(i)-1,1));
+            for j=1:lcdfr(i)-1
+                xplot(2*(j-1)+1,i)=dresp(i).cdf(j  ,1);
+                yplot(2*(j-1)+1,i)=ypdf (j,i);
+                xplot(2*(j-1)+2,i)=dresp(i).cdf(j+1,1);
+                yplot(2*(j-1)+2,i)=ypdf (j,i);
+            end
+        end
+    end
+
+    if strcmpi(pdfplt,'line')
+        xplot=xpdf;
+        yplot=ypdf;
+    end
+
+%  draw the line plot
+
+%  (see "Using Multiple X- and Y-Axes" and "Overlaying Other
+%  Plots on Bar Graphs", or search on "YAxisLocation right")
+
+%     hold all
+%     hold on
+%     plot(edges,cdf)
+%     plotyy([],[],edges,cdf)
+
+%  ticks from the bar plot will show through on the right side,
+%  so make equal number of ticks for the line plot on right side
+
+    nytick=length(get(ax1,'YTick'));
+%     ylim('auto')
+%     [ylims]=ylim;
+    [ylims]=[0 ceil(max(max(yplot))/0.1-0.1)*0.1];
+    if exist('ymin2','var')
+        ylims(1)=ymin2;
+    end
+    if exist('ymax2','var')
+        ylims(2)=ymax2;
+    else
+        ylims(2)=ylims(1)+(nytick-1)/(nytick-1-1)*(ylims(2)-ylims(1));
+    end
+%     ylim(ylims)
+    ytinc =(ylims(2)-ylims(1))/(nytick-1);
+
+    ax2=axes('Position',get(ax1,'Position'),...
+             'XLim',get(ax1,'XLim'),...
+             'XTick',get(ax1,'XTick'),...
+             'YLim',ylims,...
+             'YTick',[ylims(1):ytinc:ylims(2)],...
+             'XAxisLocation','bottom','YAxisLocation','right',...
+             'Color','none','Layer','top');
+
+    if ~exist('cline2','var') || strncmpi(cline2,'on' ,2) || strncmpi(cline2,'y',1)
+        cline2='-';
+    elseif strncmpi(cline2,'off',3) || strncmpi(cline2,'n',1)
+        cline2='none';
+    end
+    if ~exist('lwidth2','var')
+        lwidth2=0.5;
+    end
+    if ~exist('cmark2','var') || strncmpi(cmark2,'off',3) || strncmpi(cmark2,'n',1)
+        cmark2='none';
+    elseif strncmpi(cmark2,'on' ,2) || strncmpi(cmark2,'y',1) || ...
+           (length(cmark2) > 1)
+        cmark2='+';
+    end
+    if ~exist('msize2','var')
+        msize2=6;
+    end
+
+    hl2=line(xplot,yplot,'Parent',ax2,'LineStyle',cline2,'LineWidth',lwidth2,...
+             'Marker',cmark2,'MarkerSize',msize2);
+
+%  set line property colors line property
+
+    cmap=colormap;
+    for i=1:length(hl2)
+        if (length(hl2) > 1)
+            imap=round((i-1)/(length(hl2)-1)*(size(cmap,1)-1))+1;
+        else
+            imap=1;
+        end
+        set(hl2(i),'Color',get(hl1(i),'Color'))
+     end
+
+%  add the annotation
+
+    ylabel('Probability Distribution Function');
+
+    if ~exist('cdfleg','var') || ~strcmpi(cdfleg,'off')
+% legend doesn't combine with bar chart above
+        hleg2=legend(ax2,descr(1:length(hl2)),'Location','NorthEast',...
+                     'Color','none','Interpreter','none');
+%         set(hleg2,'Color','white')
+    end
+
+    set(gcf,'PaperPositionMode','auto')
+%     hold off
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm.m	(revision 18231)
@@ -0,0 +1,459 @@
+%
+%  plot a relative histogram and cdf optionally along with
+%  a normal distribution.
+%
+%  []=plot_hist_norm(dresp1      ,dresp2      ,params)
+%  []=plot_hist_norm(dresp1,desc1,dresp2,desc2,params)
+%  []=plot_hist_norm(sampr ,descr,mu,sigma    ,params)
+%
+%  where the required input is:
+%    dresp1        (structure array, responses)
+%      or
+%    dresp1        (structure array, responses)
+%    desc1         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of samples)
+%    descr         (cell array, list of descriptions)
+%
+%  and the optional input is:
+%    dresp2        (structure array, responses)
+%      or
+%    dresp2        (structure array, responses)
+%    desc2         (cell array, list of response descriptions desired)
+%      or
+%    mu            (double vector, means)
+%    sigma         (double vector, standard deviations)
+%
+%  the required fields of dresp1 are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  and the required fields of dresp2 are:
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    nrmplt        (char, 'line' or 'off' to change nrm plots from 'bar')
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%    cmap          (char or numeric, colormap definition)
+%
+%  for each response in the input array, this function
+%  calculates and plots a relative histogram and CDF of the list
+%  of samples, and annotates it with the description.  in
+%  addition, a mean and standard deviation may be supplied or,
+%  if empty, calculated so that a normal distribution and CDF may
+%  be plotted.
+%
+%  dresp1 data would typically be contained in the dakota tabular
+%  output file from a sampling analysis, and dresp2 data would
+%  typically be contained in the dakota output file from a local
+%  sensitivity analysis, both read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_hist_norm(varargin)
+
+if ~nargin
+    help plot_hist_norm
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+%  responses for histograms
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp1=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp1=struc_desc(dresp1,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp1));
+    lsamp=zeros(1,length(dresp1));
+    for i=1:length(dresp1)
+        lsamp(i)=length(dresp1(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp1));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp1)
+        descr(i)=cellstr(dresp1(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp1(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    lsamp(1:size(sampr,2))=size(sampr,1);
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1:size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  responses for normal distributions
+
+if     iarg <= nargin && isstruct(varargin{iarg})
+    dresp2=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp2=struc_desc(dresp2,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    mu   =zeros(1,length(dresp2));
+    sigma=zeros(1,length(dresp2));
+
+    for i=1:length(dresp2)
+        mu   (i)=dresp2(i).mean;
+        sigma(i)=dresp2(i).stddev;
+    end
+elseif iarg+1 <= nargin && ...
+       isnumeric(varargin{iarg}) && isnumeric(varargin{iarg+1})
+    if ~isempty(varargin{iarg})
+        mu   =varargin{iarg};
+    else
+        mu   =mean(sampr);
+        display('Using calculated means.')
+    end
+    iarg=iarg+1;
+    if ~isempty(varargin{iarg})
+        sigma=varargin{iarg};
+    else
+        sigma=std(sampr);
+        display('Using calculated standard deviations.')
+    end
+    iarg=iarg+1;
+else
+    mu   =mean(sampr);
+    display('Using calculated means.')
+    sigma=std(sampr);
+    display('Using calculated standard deviations.')
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'hmin','hmax','hnint',...
+                 'ymin1','ymax1','ymin2','ymax2',...
+                 'nrmplt','EdgeColor','FaceColor','cdfplt','cdfleg','nrmleg','cmap','titleplt','xlabelplt','ylabelplt','FontSize'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  generate the intervals
+
+if ~exist('hmin','var')
+    hmin=min(min(sampr));
+end
+if ~exist('hmax','var')
+    hmax=max(max(sampr));
+end
+if ~exist('hnint','var')
+    hnint=50;
+end
+edges=hmin:(hmax-hmin)/hnint:hmax;
+
+%%  generate the histogram counts and make them relative
+
+%  note that for the histc function:
+%  n(k) counts the value x(i) if edges(k) <= x(i) < edges(k+1).
+%  The last bin counts any values of x that match edges(end).
+%  Values outside the values in edges are not counted.
+%  Use -inf and inf in edges to include all non-NaN values.
+
+dhistc=histc(sampr,edges);
+for i=1:size(sampr,2)
+    dbelow(i)  =length(find(sampr(:,i)<edges(  1)))/lsamp(i);
+    dhistc(:,i)=dhistc(:,i)                        /lsamp(i);
+    dabove(i)  =length(find(sampr(:,i)>edges(end)))/lsamp(i);
+end
+
+ncol=size(sampr,2);
+if exist('mu','var') && exist('sigma','var')
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),mu(i),sigma(i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),mu(i),sigma(i))-...
+            normcdf_issm(edges(1:end-1),mu(i),sigma(i));
+        dabove(end+1)=norminv_issm(edges(end),mu(i),sigma(i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm']};
+        end
+    end
+end
+
+%  draw the bar plot
+
+%figure
+if ~exist('nrmplt','var')
+    nrmplt='bar';
+end
+
+hold all
+% hl1=bar(edges(1:end-1),dhistc(1:end-1,1:2*ncol));
+% hl1=line(edges(1:end-1),dhistc(1:end-1,1:2*ncol));
+if     strncmpi(nrmplt,'b',1)
+    hl1=bar (edges(1:end-1),dhistc(1:end-1,1:2*ncol));
+elseif strncmpi(nrmplt,'l',1)
+    hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
+    hl1(1*ncol+1:2*ncol)=...
+        line(edges(1:end-1),dhistc(1:end-1,1*ncol+1:2*ncol),...
+             'LineWidth',2);
+elseif strncmpi(nrmplt,'off',3)
+    hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
+end
+ax1=gca;
+hold off
+
+%  set barseries properties for clarity
+
+if (ncol > 1) || strncmpi(nrmplt,'b',1)
+    for i=1:length(hl1)
+        if strcmpi(get(hl1(i),'Type'),'hggroup')
+            set(hl1(i),'BarWidth',1,'EdgeColor','none');
+        end
+    end
+end
+
+%set face and edge color
+for i=1:length(hl1)
+	set(hl1(i),'EdgeColor',EdgeColor,'FaceColor',FaceColor);
+end
+
+%  set bars and lines to have a continuous colormap
+%  (if barseries is "flat", must interpolate and round to colormap)
+
+if exist('cmap','var')
+    colormap(cmap)
+end
+
+cmap=colormap;
+for i=1:length(hl1)
+    if (length(hl1) > 1)
+        imap=round((i-1)/(length(hl1)-1)*(size(cmap,1)-1))+1;
+    else
+        imap=1;
+    end
+    if     strcmpi(get(hl1(i),'Type'),'hggroup')
+        if ischar(get(hl1(i),'FaceColor')) && ...
+           strcmpi(get(hl1(i),'FaceColor'),'flat')
+            set(hl1(i),'FaceColor',cmap(imap,:))
+        else
+            set(hl1(i),'FaceColor',get(hl1(i),'FaceColor'))
+        end
+    elseif strcmpi(get(hl1(i),'Type'),'line')
+        set(hl1(i),'Color',cmap(imap,:))
+    end
+end
+
+xlim('auto')
+[xlims]=xlim;
+if exist('hmin','var')
+    xlims(1)=edges(1);
+end
+if exist('hmax','var')
+    xlims(2)=edges(end-1);
+end
+xlim(xlims)
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin1','var')
+    ylims(1)=ymin1;
+end
+if exist('ymax1','var')
+    ylims(2)=ymax1;
+end
+ylim(ylims)
+
+if exist('FontSize','var'),
+	fontsize=FontSize;
+else
+	fontsize=12;
+end
+
+%  add the annotation
+if exist('titleplt','var'),
+	title(titleplt,'FontSize',fontsize);
+else
+	if exist('cdfplt','var') && ...
+	   (strncmpi(cdfplt,'off',3) || strncmpi(cdfplt,'n',1))
+		title('Relative Frequency Histogram','FontSize',fontsize)
+	else
+		title('Relative Frequency Histogram with CDF','FontSize',fontsize)
+	end
+end
+
+if exist('xlabelplt','var'),
+	xlabel(xlabelplt,'FontSize',fontsize);
+else
+	xlabel('Interval Edge Value');
+end
+if exist('ylabelplt','var'),
+	ylabel(ylabelplt,'FontSize',fontsize);
+else
+	ylabel('Relative Frequency');
+end
+if exist('descr','var')
+	if ~strncmpi(cdfleg,'off',3),
+		hleg1=legend(ax1,descr(1:length(hl1)),'Location','Best','Color','none','Interpreter','none');
+	end
+else
+	if ~exist('cdfleg','var') || (~strncmpi(cdfleg,'off',3) || ~strncmpi(cdfleg,'n',1))
+		hleg1=legend(ax1);
+	end
+end
+
+%%  generate the cumulative distribution functions
+
+if ~exist('cdfplt','var') || ...
+   (~strncmpi(cdfplt,'off',3) && ~strncmpi(cdfplt,'n',1))
+%     cdf=zeros(size(dhistc));
+%     cdf(1,:)=dhistc(1,:);
+%     for i=2:size(dhistc,1)
+%         cdf(i,:)=cdf(i-1,:)+dhistc(i,:);
+%     end
+    cdf=cumsum(dhistc);
+    for i=1:size(dhistc,2)
+        cdf(:,i)=dbelow(i)+cdf(:,i);
+    end
+    if exist('descr','var')
+        ncol=length(descr);
+        for i=1:ncol
+            cdescr(i)={[descr{i} ' cdf']};
+        end
+    end
+
+%  draw the line plot
+
+%  (see "Using Multiple X- and Y-Axes" and "Overlaying Other
+%  Plots on Bar Graphs", or search on "YAxisLocation right")
+
+%     hold all
+%     hold on
+%     plot(edges,cdf)
+%     plotyy([],[],edges,cdf)
+
+%  ticks from the bar plot will show through on the right side,
+%  so make equal number of ticks for the line plot on right side
+
+    nytick=length(get(ax1,'YTick'));
+%     ylim('auto')
+%     [ylims]=ylim;
+    [ylims]=[0 ceil(max(max(cdf))/0.1-0.1)*0.1];
+    if exist('ymin2','var')
+        ylims(1)=ymin2;
+    end
+    if exist('ymax2','var')
+        ylims(2)=ymax2;
+    else
+        ylims(2)=ylims(1)+(nytick-1)/(nytick-1-1)*(ylims(2)-ylims(1));
+    end
+%     ylim(ylims)
+    ytinc =(ylims(2)-ylims(1))/(nytick-1);
+
+    ax2=axes('Position',get(ax1,'Position'),...
+             'XLim',get(ax1,'XLim'),...
+             'XTick',get(ax1,'XTick'),...
+             'YLim',ylims,...
+             'YTick',[ylims(1):ytinc:ylims(2)],...
+             'XAxisLocation','bottom','YAxisLocation','right',...
+             'Color','none','Layer','top');
+    hl2=line(edges(1:end-1),cdf(1:end-1,1:length(hl1)),'Parent',ax2);
+
+%  set line property colors to match barseries or line property
+%  (if barseries is "flat", must interpolate and round to colormap)
+
+    cmap=colormap;
+    for i=1:length(hl2)
+        if (length(hl2) > 1)
+            imap=round((i-1)/(length(hl2)-1)*(size(cmap,1)-1))+1;
+        else
+            imap=1;
+        end
+        if     strcmpi(get(hl1(i),'Type'),'hggroup')
+            if ischar(get(hl1(i),'FaceColor')) && ...
+               strcmpi(get(hl1(i),'FaceColor'),'flat')
+                set(hl2(i),'Color',cmap(imap,:))
+            else
+                set(hl2(i),'Color',get(hl1(i),'FaceColor'))
+            end
+        elseif strcmpi(get(hl1(i),'Type'),'line')
+            set(hl2(i),'Color',get(hl1(i),'Color'))
+        end
+    end
+
+%  add the annotation
+
+    ylabel('Cumulative Percent');
+
+    if ~exist('cdfleg','var') || ...
+       (~strncmpi(cdfleg,'off',3) || ~strncmpi(cdfleg,'n',1))
+% legend doesn't combine with bar chart above
+        if exist('cdescr','var')
+            hleg2=legend(ax2,cdescr(1:length(hl2)),'Location','Best',...
+                         'Color','none','Interpreter','none');
+%             set(hleg2,'Color','white')
+        else
+            hleg2=legend(ax2,'Location','Best');
+%             set(hleg2,'Color','white')
+        end
+    end
+
+    set(gcf,'PaperPositionMode','auto')
+%     hold off
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm_ci.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 18231)
@@ -0,0 +1,466 @@
+%
+%  plot a relative histogram and cdf optionally along with a
+%  normal distribution for the sample and confidence intervals.
+%
+%  []=plot_hist_norm_ci(dresp      ,params)
+%  []=plot_hist_norm_ci(dresp,descr,params)
+%  []=plot_hist_norm_ci(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of samples)
+%    descr         (cell array, list of descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  and the optional fields of dresp are:
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%    meanci(2)     (double, confidence interval of mean)
+%    stddevci(2)   (double, confidence interval of standard deviation)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  and the optional input is:
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    nrmplt        (char, 'line' or 'off' to change nrm plots from 'bar')
+%    ciplt         (char, 'line' or 'off' to change ci plots from 'bar')
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%    cmap          (char or numeric, colormap definition)
+%
+%  for each response in the input array, this function
+%  calculates and plots a relative histogram and CDF of the list
+%  of samples, and annotates it with the description.  in
+%  addition, the normal distribution and CDF are plotted, and
+%  four CDF's are plotted for the confidence intervals.
+%
+%  dresp data would typically be contained in the dakota tabular
+%  output file from a sampling analysis, read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_hist_norm_ci(varargin)
+
+if ~nargin
+    help plot_hist_norm_ci
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    mu     =zeros(1,length(dresp));
+    sigma  =zeros(1,length(dresp));
+    muci   =zeros(2,length(dresp));
+    sigmaci=zeros(2,length(dresp));
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+        mu     (i)  =dresp(i).mean;
+        sigma  (i)  =dresp(i).stddev;
+        muci   (:,i)=dresp(i).meanci;
+        sigmaci(:,i)=dresp(i).stddevci;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    lsamp(1:size(sampr,2))=size(sampr,1);
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+
+    mu     =zeros(1,size(sampr,2));
+    sigma  =zeros(1,size(sampr,2));
+    muci   =zeros(2,size(sampr,2));
+    sigmaci=zeros(2,size(sampr,2));
+    for i=1:size(sampr,2)
+%  calculate 95% confidence intervals (same as dakota)
+        [mu(i),sigma(i),muci(:,i),sigmaci(:,i)]=...
+            normfit_issm(sampr(:,i),0.05);
+    end
+    display('Using calculated normal fits.')
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'hmin','hmax','hnint',...
+                 'ymin1','ymax1','ymin2','ymax2',...
+                 'nrmplt','ciplt','cdfplt','cdfleg','cmap'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  generate the intervals
+
+if ~exist('hmin','var')
+    hmin=min(min(sampr));
+end
+if ~exist('hmax','var')
+    hmax=max(max(sampr));
+end
+if ~exist('hnint','var')
+    hnint=50;
+end
+edges=hmin:(hmax-hmin)/hnint:hmax;
+
+%%  generate the histogram counts and make them relative
+
+%  note that for the histc function:
+%  n(k) counts the value x(i) if edges(k) <= x(i) < edges(k+1).
+%  The last bin counts any values of x that match edges(end).
+%  Values outside the values in edges are not counted.
+%  Use -inf and inf in edges to include all non-NaN values.
+
+dhistc=histc(sampr,edges);
+for i=1:size(sampr,2)
+    dbelow(i)  =length(find(sampr(:,i)<edges(  1)))/lsamp(i);
+    dhistc(:,i)=dhistc(:,i)                        /lsamp(i);
+    dabove(i)  =length(find(sampr(:,i)>edges(end)))/lsamp(i);
+end
+
+ncol=size(sampr,2);
+if exist('mu','var') && exist('sigma','var')
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),mu(i),sigma(i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),mu(i),sigma(i))-...
+            normcdf_issm(edges(1:end-1),mu(i),sigma(i));
+        dabove(end+1)=norminv_issm(edges(end),mu(i),sigma(i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm']};
+        end
+    end
+end
+
+if exist('muci','var') && exist('sigmaci','var')
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),muci(1,i),sigmaci(2,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),muci(1,i),sigmaci(2,i))-...
+            normcdf_issm(edges(1:end-1),muci(1,i),sigmaci(2,i));
+        dabove(end+1)=norminv_issm(edges(end),muci(1,i),sigmaci(2,i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm-+']};
+        end
+    end
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),muci(1,i),sigmaci(1,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),muci(1,i),sigmaci(1,i))-...
+            normcdf_issm(edges(1:end-1),muci(1,i),sigmaci(1,i));
+        dabove(end+1)=norminv_issm(edges(end),muci(1,i),sigmaci(1,i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm--']};
+        end
+    end
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),muci(2,i),sigmaci(1,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),muci(2,i),sigmaci(1,i))-...
+            normcdf_issm(edges(1:end-1),muci(2,i),sigmaci(1,i));
+        dabove(end+1)=norminv_issm(edges(end),muci(2,i),sigmaci(1,i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm+-']};
+        end
+    end
+    for i=1:ncol
+        dbelow(end+1)=normcdf_issm(edges(  1),muci(2,i),sigmaci(2,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf_issm(edges(2:end  ),muci(2,i),sigmaci(2,i))-...
+            normcdf_issm(edges(1:end-1),muci(2,i),sigmaci(2,i));
+        dabove(end+1)=norminv_issm(edges(end),muci(2,i),sigmaci(2,i));
+        if exist('descr','var')
+            descr(end+1)={[descr{i} ' norm++']};
+        end
+    end
+end
+
+%  draw the bar plot
+
+figure
+if ~exist('nrmplt','var')
+    nrmplt='bar';
+end
+if ~exist('ciplt','var')
+    ciplt='bar';
+end
+
+hold all
+% hl1=bar(edges(1:end-1),dhistc(1:end-1,1:6*ncol));
+% hl1=line(edges(1:end-1),dhistc(1:end-1,1:6*ncol));
+if     strncmpi(nrmplt,'b',1)
+    if     strncmpi(ciplt,'b',1)
+        hl1=bar (edges(1:end-1),dhistc(1:end-1,1:6*ncol));
+    elseif strncmpi(ciplt,'l',1)
+        hl1=bar (edges(1:end-1),dhistc(1:end-1,1:2*ncol));
+        hl1(2*ncol+1:6*ncol)=...
+            line(edges(1:end-1),dhistc(1:end-1,2*ncol+1:6*ncol),...
+                 'LineWidth',2);
+    elseif strncmpi(ciplt,'off',3) || strncmpi(ciplt,'n',1)
+        hl1=bar (edges(1:end-1),dhistc(1:end-1,1:2*ncol));
+    end
+elseif strncmpi(nrmplt,'l',1)
+    if     strncmpi(ciplt,'b',1) || strncmpi(ciplt,'l',1)
+        hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
+        hl1(1*ncol+1:2*ncol)=...
+            line(edges(1:end-1),dhistc(1:end-1,1*ncol+1:2*ncol),...
+                 'LineWidth',2);
+        hl1(2*ncol+1:6*ncol)=...
+            line(edges(1:end-1),dhistc(1:end-1,2*ncol+1:6*ncol),...
+                 'LineWidth',1);
+    elseif strncmpi(ciplt,'off',3) || strncmpi(ciplt,'n',1)
+        hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
+        hl1(1*ncol+1:2*ncol)=...
+            line(edges(1:end-1),dhistc(1:end-1,1*ncol+1:2*ncol),...
+                 'LineWidth',2);
+    end
+elseif strncmpi(nrmplt,'off',3) || strncmpi(nrmplt,'n',1)
+    hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
+end
+ax1=gca;
+hold off
+
+%  set barseries properties for clarity
+
+if (ncol > 1) || strncmpi(nrmplt,'b',1)
+    for i=1:length(hl1)
+        if strcmpi(get(hl1(i),'Type'),'hggroup')
+            set(hl1(i),'BarWidth',1,'EdgeColor','none');
+        end
+    end
+end
+
+%  set bars and lines to have a continuous colormap
+%  (if barseries is "flat", must interpolate and round to colormap)
+
+if exist('cmap','var')
+    colormap(cmap)
+end
+
+cmap=colormap;
+for i=1:length(hl1)
+    if (length(hl1) > 1)
+        imap=round((i-1)/(length(hl1)-1)*(size(cmap,1)-1))+1;
+    else
+        imap=1;
+    end
+    if     strcmpi(get(hl1(i),'Type'),'hggroup')
+        if ischar(get(hl1(i),'FaceColor')) && ...
+           strcmpi(get(hl1(i),'FaceColor'),'flat')
+            set(hl1(i),'FaceColor',cmap(imap,:))
+        else
+            set(hl1(i),'FaceColor',get(hl1(i),'FaceColor'))
+        end
+    elseif strcmpi(get(hl1(i),'Type'),'line')
+        set(hl1(i),'Color',cmap(imap,:))
+    end
+end
+
+xlim('auto')
+[xlims]=xlim;
+if exist('hmin','var')
+    xlims(1)=edges(1);
+end
+if exist('hmax','var')
+    xlims(2)=edges(end-1);
+end
+xlim(xlims)
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin1','var')
+    ylims(1)=ymin1;
+end
+if exist('ymax1','var')
+    ylims(2)=ymax1;
+end
+ylim(ylims)
+
+%  add the annotation
+
+if exist('cdfplt','var') && ...
+   (strncmpi(cdfplt,'off',3) || strncmpi(cdfplt,'n',1))
+    title('Relative Frequency Histogram')
+else
+    title('Relative Frequency Histogram with CDF')
+end
+xlabel('Interval Edge Value');
+ylabel('Relative Frequency');
+
+if exist('descr','var')
+    hleg1=legend(ax1,descr(1:length(hl1)),'Location','NorthWest',...
+                 'Color','none','Interpreter','none');
+else
+    hleg1=legend(ax1);
+end
+
+%%  generate the cumulative distribution functions
+
+if ~exist('cdfplt','var') || ...
+   (~strncmpi(cdfplt,'off',3) && ~strncmpi(cdfplt,'n',1))
+%     cdf=zeros(size(dhistc));
+%     cdf(1,:)=dhistc(1,:);
+%     for i=2:size(dhistc,1)
+%         cdf(i,:)=cdf(i-1,:)+dhistc(i,:);
+%     end
+    cdf=cumsum(dhistc);
+    for i=1:size(dhistc,2)
+        cdf(:,i)=dbelow(i)+cdf(:,i);
+    end
+    if exist('descr','var')
+        ncol=length(descr);
+        for i=1:ncol
+            cdescr(i)={[descr{i} ' cdf']};
+        end
+    end
+
+%  draw the line plot
+
+%  (see "Using Multiple X- and Y-Axes" and "Overlaying Other
+%  Plots on Bar Graphs", or search on "YAxisLocation right")
+
+%     hold all
+%     hold on
+%     plot(edges,cdf)
+%     plotyy([],[],edges,cdf)
+
+%  ticks from the bar plot will show through on the right side,
+%  so make equal number of ticks for the line plot on right side
+
+    nytick=length(get(ax1,'YTick'));
+%     ylim('auto')
+%     [ylims]=ylim;
+    [ylims]=[0 ceil(max(max(cdf))/0.1-0.1)*0.1];
+    if exist('ymin2','var')
+        ylims(1)=ymin2;
+    end
+    if exist('ymax2','var')
+        ylims(2)=ymax2;
+    else
+        ylims(2)=ylims(1)+(nytick-1)/(nytick-1-1)*(ylims(2)-ylims(1));
+    end
+%     ylim(ylims)
+    ytinc =(ylims(2)-ylims(1))/(nytick-1);
+
+    ax2=axes('Position',get(ax1,'Position'),...
+             'XLim',get(ax1,'XLim'),...
+             'XTick',get(ax1,'XTick'),...
+             'YLim',ylims,...
+             'YTick',[ylims(1):ytinc:ylims(2)],...
+             'XAxisLocation','bottom','YAxisLocation','right',...
+             'Color','none','Layer','top');
+    hl2=line(edges(1:end-1),cdf(1:end-1,1:length(hl1)),'Parent',ax2);
+
+%  set line property colors to match barseries or line property
+%  (if barseries is "flat", must interpolate and round to colormap)
+
+    cmap=colormap;
+    for i=1:length(hl2)
+        if (length(hl2) > 1)
+            imap=round((i-1)/(length(hl2)-1)*(size(cmap,1)-1))+1;
+        else
+            imap=1;
+        end
+        if     strcmpi(get(hl1(i),'Type'),'hggroup')
+            if ischar(get(hl1(i),'FaceColor')) && ...
+               strcmpi(get(hl1(i),'FaceColor'),'flat')
+                set(hl2(i),'Color',cmap(imap,:))
+            else
+                set(hl2(i),'Color',get(hl1(i),'FaceColor'))
+            end
+        elseif strcmpi(get(hl1(i),'Type'),'line')
+            set(hl2(i),'Color',get(hl1(i),'Color'))
+        end
+    end
+
+%  add the annotation
+
+    ylabel('Cumulative Percent');
+
+    if ~exist('cdfleg','var') || ...
+       (~strncmpi(cdfleg,'off',3) && ~strncmpi(cdfleg,'n',1))
+% legend doesn't combine with bar chart above
+        if exist('cdescr','var')
+            hleg2=legend(ax2,cdescr(1:length(hl2)),'Location','NorthEast',...
+                         'Color','none','Interpreter','none');
+%             set(hleg2,'Color','white')
+        else
+            hleg2=legend(ax2);
+%             set(hleg2,'Color','white')
+        end
+    end
+
+    set(gcf,'PaperPositionMode','auto')
+%     hold off
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_bars.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_bars.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_bars.m	(revision 18231)
@@ -0,0 +1,229 @@
+%
+%  plot a stacked bar chart of the importance factors.
+%
+%  []=plot_if_bars(dresp      ,params)
+%  []=plot_if_bars(dresp,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    var           (cell array, variables)
+%    impfac        (double array, importance factors)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    ifmin         (double, minimum importance factor)
+%    isort         (numeric, sort flag:  0, no sorting;
+%                                        1, highest at bottom;
+%                                       -1, lowest at bottom)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the responses, where the bars are
+%  stacked by the importance factors, and annotates it with the
+%  description.  the legend labels are constructed from the
+%  variable list.
+%
+%  this data would typically be contained in the dakota output
+%  file from a local reliability analysis and read by
+%  dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_if_bars(varargin)
+
+if ~nargin
+    help plot_if_bars
+    return
+end
+
+%%  process input data and assemble into matrices
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lifr =zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lifr(i)=length(dresp(i).impfac);
+    end
+    ifr =zeros(length(dresp),max(lifr));
+    dvar=dresp(find(lifr == max(lifr),1,'first')).var;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        ifr(i,1:lifr(i))=dresp(i).impfac;
+    end
+else
+    error(['''' inputname(iarg) ''' is not a structure.']);
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax','ifmin','isort','xtlrot'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if ~exist('ifmin','var') || isempty(ifmin)
+    ifmin=0;
+end
+
+if ~exist('isort','var') || isempty(isort)
+    isort=0;
+end
+
+%%  sort the data, if necessary
+
+if (isort)
+    ifmean=mean(ifr,1);
+    if (isort > 0)
+        [ifmean,index]=sort(ifmean,'descend');
+    else
+        [ifmean,index]=sort(ifmean,'ascend' );
+    end
+    clear ifmean
+
+    dvar=dvar(index);
+    ifr =ifr (:,index);
+end
+
+%%  filter the data, if necessary
+
+if (ifmin > 0)
+    nif=length(dvar);
+    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
+
+    for i=1:nif
+        if (max(ifr(:,i)) < ifmin)
+            ifr(:,nif+1)=ifr(:,nif+1)+ifr(:,i);
+        else
+            nif2=nif2+1;
+            dvar2(nif2)  =dvar(i);
+            ifr2 (:,nif2)=ifr (:,i);
+        end
+    end
+
+%  copy sums
+
+    dvar2(nif2+1)  =dvar(nif+1);
+    ifr2 (:,nif2+1)=ifr (:,nif+1);
+
+%  copy back and truncate filtered rows
+
+    clear dvar ifr
+    if (isort >= 0)
+        dvar(1:nif2+1)  =dvar2(1:nif2+1);
+        ifr (:,1:nif2+1)=ifr2 (:,1:nif2+1);
+    else
+        dvar(1       )  =dvar2(  nif2+1);
+        dvar(2:nif2+1)  =dvar2(1:nif2  );
+        ifr (:,1       )=ifr2 (:,  nif2+1);
+        ifr (:,2:nif2+1)=ifr2 (:,1:nif2  );
+    end
+    clear nif nif2 dvar2 ifr2
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dresp) == 1
+    ifr=[ifr; ifr];
+end
+
+figure
+hl1=bar(ifr,'stacked');
+
+ax1=gca;
+if length(dresp) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+% set(ax1,'ylim',[0 1.2])
+% ylim('auto')
+% [ylims]=ylim;
+[ylims]=[0 1.2];
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Importance Factors')
+xlabel('Response')
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Importance Factor Value')
+
+hleg1=legend(ax1,dvar,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_spec.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_spec.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_if_spec.m	(revision 18231)
@@ -0,0 +1,277 @@
+%
+%  plot a line plot or bar chart of the spectrum of importance factors.
+%
+%  []=plot_if_spec(dresp      ,params)
+%  []=plot_if_spec(dresp,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    var           (cell array, variables)
+%    impfac        (double array, importance factors)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    cplot         (char, 'l'/'b'/'g' to plot line/bar)
+%    cline         (char, 'off'/'no'/'-'/'--'/':'/etc. to change lines)
+%    lwidth        (numeric, line width in points, default 0.5)
+%    cmark         (char, 'on'/'yes'/'+'/'o'/'*'/etc. to change markers)
+%    msize         (numeric, marker size in points, default 6)
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    ygrid         (char, 'on' to turn on y-grid lines)
+%    ylog          (char, 'yes' to use log y-axis)
+%    ifmin         (double, minimum importance factor)
+%    isort         (numeric, sort flag:  0, no sorting;
+%                                        1, highest at right;
+%                                       -1, lowest at right)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%
+%  for each response in the input array, this function plots
+%  a bar plot of the importance factors and annotates it with the
+%  description.  the legend labels are constructed from the
+%  response list.
+%
+%  this data would typically be contained in the dakota output
+%  file from a local reliability analysis and read by
+%  dakota_out_parse.
+%
+%  "Copyright 2010, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_if_spec(varargin)
+
+if ~nargin
+    help plot_if_spec
+    return
+end
+
+%%  process input data and assemble into matrices
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lifr =zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lifr(i)=length(dresp(i).impfac);
+    end
+    ifr =zeros(length(dresp),max(lifr));
+    dvar=dresp(find(lifr == max(lifr),1,'first')).var;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        ifr(i,1:lifr(i))=dresp(i).impfac;
+    end
+else
+    error(['''' inputname(iarg) ''' is not a structure.']);
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'cplot','cline','lwidth','cmark','msize',...
+                 'ymin','ymax','ygrid','ylog',...
+                 'ifmin','isort','xtlrot'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if ~exist('cplot','var') || isempty(cplot)
+    cplot='line';
+end
+
+if ~exist('ifmin','var') || isempty(ifmin)
+    ifmin=0;
+end
+
+if ~exist('isort','var') || isempty(isort)
+    isort=0;
+end
+
+%%  sort the data, if necessary
+
+if (isort)
+    ifmean=mean(ifr,1);
+    if (isort > 0)
+        [ifmean,index]=sort(ifmean,'ascend' );
+    else
+        [ifmean,index]=sort(ifmean,'descend');
+    end
+    clear ifmean
+
+    dvar=dvar(index);
+    ifr =ifr (:,index);
+end
+
+%%  filter the data, if necessary
+
+if (ifmin > 0)
+    nif=length(dvar);
+    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
+
+    for i=1:nif
+        if (max(ifr(:,i)) < ifmin)
+            ifr(:,nif+1)=ifr(:,nif+1)+ifr(:,i);
+        else
+            nif2=nif2+1;
+            dvar2(nif2)  =dvar(i);
+            ifr2 (:,nif2)=ifr (:,i);
+        end
+    end
+
+%  copy sums
+
+    dvar2(nif2+1)  =dvar(nif+1);
+    ifr2 (:,nif2+1)=ifr (:,nif+1);
+
+%  copy back and truncate filtered rows
+
+    clear dvar ifr
+    if (isort >= 0)
+        dvar(1:nif2+1)  =dvar2(1:nif2+1);
+        ifr (:,1:nif2+1)=ifr2 (:,1:nif2+1);
+    else
+        dvar(1       )  =dvar2(  nif2+1);
+        dvar(2:nif2+1)  =dvar2(1:nif2  );
+        ifr (:,1       )=ifr2 (:,  nif2+1);
+        ifr (:,2:nif2+1)=ifr2 (:,1:nif2  );
+    end
+    clear nif nif2 dvar2 ifr2
+end
+
+%%  draw the line or bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dvar) == 1
+    ifr=[ifr; ifr];
+end
+
+%newplot();
+figure
+ax1=axes;
+if strncmpi(cplot,'l',1)
+    if ~exist('cline','var') || strncmpi(cline,'on' ,2) || strncmpi(cline,'y',1)
+        cline='-';
+    elseif strncmpi(cline,'off',3) || strncmpi(cline,'n',1)
+        cline='none';
+    end
+    if ~exist('lwidth','var')
+        lwidth=0.5;
+    end
+    if ~exist('cmark','var') || strncmpi(cmark,'off',3) || strncmpi(cmark,'n',1)
+        cmark='none';
+    elseif strncmpi(cmark,'on' ,2) || strncmpi(cmark,'y',1) || ...
+           (length(cmark) > 1)
+        cmark='+';
+    end
+    if ~exist('msize','var')
+        msize=6;
+    end
+
+    hl1=plot(ax1,ifr','LineStyle',cline,'LineWidth',lwidth,...
+             'Marker',cmark,'MarkerSize',msize);
+else
+    hl1=bar(ax1,ifr');
+end
+
+ax1=gca;
+if length(dvar) == 1
+    set(ax1,'xlim',[0.5 1.5])
+else
+    set(ax1,'xlim',[0.5 length(dvar)+0.5])
+end
+
+if exist('ylog','var') && strncmpi(ylog,'y',1)
+    set(ax1,'yscale','log')
+    ylim('auto')
+    [ylims]=ylim;
+else
+    [ylims]=[0 1.2];
+end
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+if strncmpi(cplot,'b',1) && exist('ylog','var') && strncmpi(ylog,'y',1)
+    set(hl1,'basevalue',ylims(1))
+end
+
+set(ax1,'xtick',1:length(dvar))
+set(ax1,'xticklabel',dvar)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+if length(descr) > 1
+    title('Importance Factors of Responses')
+    hleg1=legend(ax1,descr,'Location','EastOutside',...
+                 'Orientation','vertical','Interpreter','none');
+else
+    title(['Importance Factors of ' descr{1}],'Interpreter','none')
+end
+xlabel('Variable')
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Variable']));
+    clear nskip xlext tlext
+end
+ylabel('Importance Factor Value')
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normdist_bars.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normdist_bars.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normdist_bars.m	(revision 18231)
@@ -0,0 +1,213 @@
+%
+%  plot a stacked bar chart of the sample distributions.
+%
+%  []=plot_normdist_bars(dresp      ,params)
+%  []=plot_normdist_bars(dresp,descr,params)
+%  []=plot_normdist_bars(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  and the optional fields of dresp are:
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    prob          (double vector, probability levels)
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%    lstr          (cell array, legend labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the list of samples, where the bars
+%  are stacked by the given or default probability levels
+%  calculated from a normal distribution, and annotates it with
+%  the description.  the mean and standard deviation will be
+%  calculated from the samples if they do not already exist.
+%  the legend labels can be given or constructed from the
+%  probability levels.
+%
+%  this data would typically be contained in the dakota tabular
+%  output file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_normdist_bars(varargin)
+
+if ~nargin
+    help plot_normdist_bars
+    return
+end
+
+%%  process input data and assemble into dresp as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1:size(sampr,2));
+    end
+
+    dresp=struct([]);
+    for i=1:size(sampr,2)
+        dresp(end+1).sample=samp(:,i);
+        if ~isempty(descr)
+            dresp(i).descriptor=descr{i};
+        else
+            dresp(i).descriptor=['dresp_' num2str(i)];
+        end
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'prob','ymin','ymax','xtlrot','lstr'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  calculate any missing information (noting that dresp is local)
+
+if ~isfield(dresp,'mean') || ~isfield(dresp,'stddev')
+    for i=1:length(dresp)
+        [dresp(i).mean,dresp(i).stddev]=normfit_issm(dresp(i).sample);
+    end
+end
+
+%%  assemble the data into a matrix and calculate the increments
+
+if ~exist('prob','var') || isempty(prob)
+    prob=[0.01 0.25 0.50 0.75 0.99];
+end
+
+descr=cell (1,length(dresp));
+data =zeros(length(dresp),length(prob));
+
+for i=1:length(dresp)
+    descr(i)=cellstr(dresp(i).descriptor);
+    data(i,:)=norminv_issm(prob,dresp(i).mean,dresp(i).stddev);
+end
+
+for j=length(prob):-1:2
+    data(:,j)=data(:,j)-data(:,j-1);
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dresp) == 1
+    data=[data; data];
+end
+
+figure
+hl1=bar(data,'stacked');
+%  set barseries properties for lowest value
+whitebg('white')
+set(hl1(1),'FaceColor','white')
+set(hl1(1),'Visible','off')
+
+ax1=gca;
+if length(dresp) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Normal Distributions of Responses')
+xlabel('Response')
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Value')
+
+if ~exist('lstr','var') || isempty(lstr)
+    lstr=cell(1,length(prob));
+    for i=1:length(prob)
+        lstr(i)=cellstr(sprintf('%g%%',100*prob(i)));
+    end
+end
+
+hleg1=legend(ax1,lstr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normplot.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normplot.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_normplot.m	(revision 18231)
@@ -0,0 +1,154 @@
+%
+%  plot a normal probability plot of the responses.
+%
+%  []=plot_normplot(dresp      ,params)
+%  []=plot_normplot(dresp,descr,params)
+%  []=plot_normplot(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    xmin          (numeric, minimum of x-axis)
+%    xmax          (numeric, maximum of x-axis)
+%
+%  for each response in the input array, this function plots
+%  a matlab normal probability plot of the list of samples
+%  and annotates it with the description.  the lists of samples
+%  need not all be the same length.
+%
+%  this data would typically be contained in the dakota tabular
+%  output file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_normplot(varargin)
+
+if ~nargin
+    help plot_normplot
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'xmin','xmax'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  draw the plot
+
+%  draw normal probability plot
+
+figure
+normplot(sampr)
+ax1=gca;
+
+%  add the annotation
+
+xlim('auto')
+[xlims]=xlim;
+if exist('xmin','var')
+    xlims(1)=xmin;
+end
+if exist('xmax','var')
+    xlims(2)=xmax;
+end
+xlim(xlims)
+
+if (size(sampr,2) == 1)
+    tlabc=descr{1};
+else
+    tlabc='Responses';
+end
+title(['Normal Probability Plot of ' tlabc],'Interpreter','none');
+xlabel('Value'      ,'Interpreter','none');
+ylabel('Probability','Interpreter','none');
+
+hleg1=legend(ax1,descr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_prob_bars.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_prob_bars.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_prob_bars.m	(revision 18231)
@@ -0,0 +1,196 @@
+%
+%  plot a stacked bar chart of the probabilities in the CDF.
+%
+%  []=plot_prob_bars(dresp      ,params)
+%  []=plot_prob_bars(dresp,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    cdf(:,4)      (double matrix, CDF table)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%    cmap          (char, 'stoplight' for 6-color stoplight colormap)
+%    lstr          (cell array, legend labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the responses, where the bars are
+%  stacked by the probabilities corresponding to the given
+%  response levels in the CDF, and annotates it with the
+%  description.  the legend labels can be given or constructed
+%  from the response levels.
+%
+%  this data would typically be contained in the dakota output
+%  file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_prob_bars(varargin)
+
+if ~nargin
+    help plot_prob_bars
+    return
+end
+
+%%  assemble the data into a matrix and calculate the increments
+
+%%  process input data and assemble into matrices and increments
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lcdfr=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lcdfr(i)=size(dresp(i).cdf,1);
+    end
+    cdfr=zeros(length(dresp),max(lcdfr));
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        if ~isempty(dresp(i).cdf)
+            cdfr(i,1)=dresp(i).cdf(1,2);
+            for j=2:size(dresp(i).cdf,1)
+                if (dresp(i).cdf(j,2) > dresp(i).cdf(j-1,2))
+                    cdfr(i,j)=dresp(i).cdf(j,2)-dresp(i).cdf(j-1,2);
+                end
+            end
+        end
+    end
+else
+    error(['''' inputname(iarg) ''' is not a structure.']);
+end
+
+%  convert to percentage
+
+cdfr=cdfr*100.;
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax','xtlrot','cmap','lstr'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dresp) == 1
+    cdfr=[cdfr; cdfr];
+end
+
+figure
+hl1=bar(cdfr,'stacked');
+if exist('cmap','var')
+    if strncmpi(cmap,'stop',4)
+%         set(hl1(1),'FaceColor','green')
+%         set(hl1(2),'FaceColor',[.7 1 0])
+%         set(hl1(3),'FaceColor','yellow')
+%         set(hl1(4),'FaceColor',[1 .7 0])
+%         set(hl1(5),'FaceColor',[1 .5 0])
+%         set(hl1(6),'FaceColor','red')
+        colormap([0 1 0;.7 1 0;1 1 0;1 .7 0;1 .5 0;1 0 0]);
+    else
+        colormap(cmap);
+    end
+end
+
+ax1=gca;
+if length(dresp) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+% set(ax1,'ylim',[0 120])
+% ylim('auto')
+% [ylims]=ylim;
+[ylims]=[0 120];
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Probabilities for Specified Response Levels (RIA)')
+xlabel('Response')
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Percent Below Level')
+
+if ~exist('lstr','var') || isempty(lstr)
+    lstr=cell(1,max(lcdfr));
+    for i=1:max(lcdfr)
+        lstr(i)=cellstr(sprintf('%g',...
+            dresp(find(lcdfr == max(lcdfr),1,'first')).cdf(i,1)));
+    end
+    if ~isempty(find(lcdfr < max(lcdfr)))
+        warning('Variable number of levels for responses.');
+    end
+end
+
+hleg1=legend(ax1,lstr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars.m	(revision 18231)
@@ -0,0 +1,178 @@
+%
+%  plot a stacked bar chart of the response levels in the cdf.
+%
+%  []=plot_rlev_bars(dresp      ,params)
+%  []=plot_rlev_bars(dresp,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    cdf(:,4)      (double matrix, CDF table)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%    lstr          (cell array, legend labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the responses, where the bars are
+%  stacked by the response levels corresponding to the given
+%  probabilities in the CDF, and annotates it with the
+%  description.  the legend labels can be given or constructed
+%  from the probabilities.
+%
+%  this data would typically be contained in the dakota output
+%  file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_rlev_bars(varargin)
+
+if ~nargin
+    help plot_rlev_bars
+    return
+end
+
+%%  process input data and assemble into matrices and increments
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lcdfr=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lcdfr(i)=size(dresp(i).cdf,1);
+    end
+    cdfr=zeros(length(dresp),max(lcdfr));
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        if ~isempty(dresp(i).cdf)
+            cdfr(i,1)=dresp(i).cdf(1,1);
+            for j=2:size(dresp(i).cdf,1)
+                if (dresp(i).cdf(j,1) > dresp(i).cdf(j-1,1))
+                    cdfr(i,j)=dresp(i).cdf(j,1)-dresp(i).cdf(j-1,1);
+                end
+            end
+        end
+    end
+else
+    error(['''' inputname(iarg) ''' is not a structure.']);
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax','xtlrot','lstr'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dresp) == 1
+    cdfr=[cdfr; cdfr];
+end
+
+figure
+hl1=bar(cdfr,'stacked');
+%  set barseries properties for lowest value
+whitebg('white')
+set(hl1(1),'FaceColor','white')
+set(hl1(1),'Visible','off')
+
+ax1=gca;
+if length(dresp) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Response Levels for Specified Probabilities (PMA)')
+xlabel('Response');
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Response Level')
+
+if ~exist('lstr','var') || isempty(lstr)
+    lstr=cell(1,max(lcdfr));
+    for i=1:max(lcdfr)
+        lstr(i)=cellstr(sprintf('%g%%',...
+            100*dresp(find(lcdfr == max(lcdfr),1,'first')).cdf(i,2)));
+    end
+    if ~isempty(find(lcdfr < max(lcdfr),1))
+        warning('Variable number of probabilities for responses.');
+    end
+end
+
+hleg1=legend(ax1,lstr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars_ci.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 18231)
@@ -0,0 +1,269 @@
+%
+%  plot a stacked bar chart of the response levels in the cdf
+%  for the sample and confidence intervals.
+%
+%  []=plot_rlev_bars_ci(dresp      ,params)
+%  []=plot_rlev_bars_ci(dresp,descr,params)
+%  []=plot_rlev_bars_ci(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    cdf(:,4)      (double matrix, CDF table)
+%
+%  and the optional fields of dresp are:
+%    mean          (double, mean of sample)
+%    stddev        (double, standard deviation of sample)
+%    meanci(2)     (double, confidence interval of mean)
+%    stddevci(2)   (double, confidence interval of standard deviation)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%    lstr          (cell array, legend labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the responses, where the bars are
+%  stacked by the response levels corresponding to the given
+%  probabilities in the CDF, and annotates it with the
+%  description.  the response levels for the normal distribution
+%  and the confidence intervals are also plotted.  the legend
+%  labels can be given or constructed from the probabilities.
+%
+%  dresp data would typically be contained in the dakota tabular
+%  output file from a sampling analysis, read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_rlev_bars_ci(varargin)
+
+if ~nargin
+    help plot_rlev_bars_ci
+    return
+end
+
+%%  process input data and assemble into dresp as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1:size(sampr,2));
+    end
+
+    dresp=struct([]);
+    for i=1:size(sampr,2)
+        dresp(end+1).sample=sampr(:,i);
+        if ~isempty(descr)
+            dresp(i).descriptor=descr{i};
+        else
+            dresp(i).descriptor=['dresp_' num2str(i)];
+        end
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax','xtlrot','lstr'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  calculate any missing information (noting that dresp is local)
+
+for i=1:length(dresp)
+    if ~isfield(dresp(i),'mean') || isempty(dresp(i).mean) || ...
+       ~isfield(dresp(i),'stddev') || isempty(dresp(i).stddev) || ...
+       ~isfield(dresp(i),'meanci') || isempty(dresp(i).meanci) || ...
+       ~isfield(dresp(i),'stddevci') || isempty(dresp(i).stddevci)
+%  calculate 95% confidence intervals (same as dakota)
+        [dresp(i).mean,dresp(i).stddev,...
+         dresp(i).meanci,dresp(i).stddevci]=...
+            normfit_issm(sampr(:,i),0.05);
+        display('Using calculated normal fits from sample data.')
+    end
+
+    if ~isfield(dresp(i),'cdf') || isempty(dresp(i).cdf)
+%  use minus/plus integer standard deviations
+        sdvect=[-4 -3 -2 -1 0 1 2 3 4];
+        dresp(i).cdf(:,2)=normcdf_issm(sdvect,0,1);
+        dresp(i).cdf(:,1)=norminv_issm(dresp(i).cdf(:,2),...
+                                       dresp(i).mean,dresp(i).stddev);
+        display('Using integer standard deviations for percentages.')
+
+        if ~exist('lstr','var') || isempty(lstr)
+            lstr=cell(1,size(dresp(i).cdf,1));
+            for j=1:size(dresp(i).cdf,1)
+                if sdvect(j)
+                    lstr{j}=sprintf('mu %+d sigma',sdvect(j));
+                else
+                    lstr{j}='mu';
+                end
+            end
+        end
+    end
+end
+
+%%  assemble the data into a matrix and calculate the increments
+
+descr=cell (1,0);
+lcdfr=zeros(1,length(dresp));
+for i=1:length(dresp)
+    lcdfr(i)=size(dresp(i).cdf,1);
+end
+cdfr=zeros(0,max(lcdfr));
+
+%  fill in the cdf data
+
+for i=1:length(dresp)
+    if ~isempty(dresp(i).cdf)
+        descr(end+1)=cellstr([dresp(i).descriptor]);
+        cdfr(end+1,:)=dresp(i).cdf(:,1);
+        if isfield(dresp(i),'mean'  ) && ~isempty(dresp(i).mean  ) && ...
+           isfield(dresp(i),'stddev') && ~isempty(dresp(i).stddev)
+            descr(end+1)=cellstr([dresp(i).descriptor ' norm']);
+            cdfr(end+1,:)=norminv_issm(dresp(i).cdf(:,2),dresp(i).mean,dresp(i).stddev);
+        end
+        if isfield(dresp(i),'meanci'  ) && ~isempty(dresp(i).meanci  ) && ...
+           isfield(dresp(i),'stddevci') && ~isempty(dresp(i).stddevci)
+            descr(end+1)=cellstr([dresp(i).descriptor ' norm-+']);
+            descr(end+1)=cellstr([dresp(i).descriptor ' norm--']);
+            descr(end+1)=cellstr([dresp(i).descriptor ' norm+-']);
+            descr(end+1)=cellstr([dresp(i).descriptor ' norm++']);
+            cdfr(end+1,:)=norminv_issm(dresp(i).cdf(:,2),dresp(i).meanci(1),dresp(i).stddevci(2));
+            cdfr(end+1,:)=norminv_issm(dresp(i).cdf(:,2),dresp(i).meanci(1),dresp(i).stddevci(1));
+            cdfr(end+1,:)=norminv_issm(dresp(i).cdf(:,2),dresp(i).meanci(2),dresp(i).stddevci(1));
+            cdfr(end+1,:)=norminv_issm(dresp(i).cdf(:,2),dresp(i).meanci(2),dresp(i).stddevci(2));
+        end
+    end
+end
+
+%  calculate the increments
+
+for i=1:size(cdfr,1)
+    for j=find(cdfr(i,:),1,'last'):-1:2
+        cdfr(i,j)=cdfr(i,j)-cdfr(i,j-1);
+    end
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(descr) == 1
+    cdfr=[cdfr; cdfr];
+end
+
+figure
+hl1=bar(cdfr,'stacked');
+%  set barseries properties for lowest value
+whitebg('white')
+set(hl1(1),'FaceColor','white')
+set(hl1(1),'Visible','off')
+
+ax1=gca;
+if length(descr) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Response Levels for Specified Probabilities (PMA)');
+xlabel('Response');
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Response Level');
+
+if ~exist('lstr','var') || isempty(lstr)
+    lstr=cell(1,max(lcdfr));
+    for i=1:max(lcdfr)
+        lstr(i)=cellstr(sprintf('%g%%',...
+            100*dresp(find(lcdfr == max(lcdfr),1,'first')).cdf(i,2)));
+    end
+    if ~isempty(find(lcdfr < max(lcdfr),1,'first'))
+        warning('Variable number of probabilities for responses.');
+    end
+end
+
+hleg1=legend(ax1,lstr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_line.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_line.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_line.m	(revision 18231)
@@ -0,0 +1,265 @@
+%
+%  plot line plots of responses vs. variables.
+%
+%  []=plot_rvsv_line(dvar       ,dresp      ,params)
+%  []=plot_rvsv_line(dvar ,descv,dresp,descr,params)
+%  []=plot_rvsv_line(sampv,descv,sampr,descr,params)
+%
+%  where the required input is:
+%    dvar          (structure array, variables)
+%      or
+%    dvar          (structure array, variables)
+%    descv         (cell array, list of variable descriptions desired)
+%      or
+%    sampv         (double array, lists of variable samples)
+%    descv         (cell array, list of variable descriptions)
+%
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dvar and dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    nplotr        (numeric, number of plot rows)
+%    nplotc        (numeric, number of plot columns)
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    yscat         (char, 'off' to turn off y-axis scattergram)
+%
+%  for each variable/response combination in the input array, this
+%  function plots a line plot.  all of the variables and responses
+%  are plotted on the same axes, if nplotr and nplotc are not
+%  specified, so some scaling might otherwise be desired.
+%
+%  dvar and dresp data would typically be contained in the dakota
+%  tabular output file from a sampling or parametric analysis, and
+%  read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_rvsv_line(varargin)
+
+if ~nargin
+    help plot_rvsv_line
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+%  variables
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dvar=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dvar=struc_desc(dvar,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descv=cell (1,length(dvar));
+    lsamp=zeros(1,length(dvar));
+    for i=1:length(dvar)
+        lsamp(i)=length(dvar(i).sample);
+    end
+    sampv=zeros(max(lsamp),length(dvar));
+    sampv(:,:)=NaN;
+
+    for i=1:length(dvar)
+        descv(i)=cellstr(dvar(i).descriptor);
+        sampv(1:lsamp(i),i)=dvar(i).sample;
+    end
+else
+    sampv=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descv=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descv=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descv=cell(1,size(sampv,2));
+    end
+end
+
+for i=1:length(descv)
+    if isempty(descv{i})
+        descv(i)={['var_' i]};
+    end
+end
+
+%  responses
+
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'nplotr','nplotc',...
+                 'ymin','ymax','yscat'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if     ~exist('nplotr','var') && ~exist('nplotc','var')
+    nplotr=1;
+    nplotc=1;
+elseif ~exist('nplotr','var')
+    nplotr=ceil(size(sampr,2)*size(sampv,2)/nplotc);
+elseif ~exist('nplotc','var')
+    nplotc=ceil(size(sampr,2)*size(sampv,2)/nplotr);
+end
+
+%%  filter, sort, and plot the data
+
+%  while it would be preferable for the outer loop to be responses,
+%  it is more efficient for the outer loop to be variables
+
+figure
+haxes=[];
+hplot=[];
+cdesc={};
+hscat=[];
+
+iplot=0;
+
+for ivar=1:size(sampv,2)
+    [vval,indxv,indxvi]=unique(sampv(:,ivar),'first');
+    indxv2=setdiff(1:size(sampv,1),indxv);
+
+    for iresp=1:size(sampr,2)
+
+%  initialize the subplot
+
+        if (ivar*iresp == 1) || ...
+           (nplotr*nplotc > 1)
+            iplot=iplot+1;
+            haxes(end+1)=subplot(nplotr,nplotc,iplot);
+            hold all
+        end
+
+        hplot(end+1)=plot   (sampv(indxv ,ivar),sampr(indxv ,iresp),'-x');
+        cdesc(end+1)={[descr{iresp} ' wrt ' descv{ivar}]};
+        if ~exist('yscat','var') || ...
+           (~strncmpi(yscat,'off',3) && ~strncmpi(yscat,'n',1))
+            hscat(end+1)=scatter(sampv(indxv2,ivar),sampr(indxv2,iresp),'+k');
+%  see "controlling legends" in Matlab on-line docs
+%         cdesc(end+1)={['constant ' descv{ivar}]};
+            set(get(get(hscat(end),'Annotation'),'LegendInformation'),...
+                'IconDisplayStyle','off'); % Exclude line from legend
+        end
+
+%  add the annotation
+
+        if (ivar*iresp == size(sampv,2)*size(sampr,2)) || ...
+           (nplotr*nplotc > 1)
+            hold off
+
+            ylim('auto')
+            [ylims]=ylim;
+            if exist('ymin','var')
+                ylims(1)=ymin;
+            end
+            if exist('ymax','var')
+                ylims(2)=ymax;
+            end
+            ylim(ylims)
+
+            if (size(sampv,2) == 1) || (nplotr*nplotc > 1)
+                xlabc=descv{ivar};
+            else
+                xlabc='Variables';
+            end
+            if (size(sampr,2) == 1) || (nplotr*nplotc > 1)
+                ylabc=descr{iresp};
+            else
+                ylabc='Responses';
+            end
+            title([ylabc ' vs. ' xlabc],'Interpreter','none');
+            xlabel(xlabc,'Interpreter','none');
+            ylabel(ylabc,'Interpreter','none');
+
+            if (nplotr*nplotc == 1) && (size(sampv,2)*size(sampr,2) > 1)
+                legend(cdesc,'Location','EastOutside','Interpreter','none');
+            end
+        end
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_scat3.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 18231)
@@ -0,0 +1,281 @@
+%
+%  plot 3-d scatter plots of variables vs. responses.
+%
+%  []=plot_rvsv_scat3(dvar       ,dresp      ,params)
+%  []=plot_rvsv_scat3(dvar ,descv,dresp,descr,params)
+%  []=plot_rvsv_scat3(sampv,descv,sampr,descr,params)
+%
+%  where the required input is:
+%    dvar          (structure array, variables)
+%      or
+%    dvar          (structure array, variables)
+%    descv         (cell array, list of variable descriptions desired)
+%      or
+%    sampv         (double array, lists of variable samples)
+%    descv         (cell array, list of variable descriptions)
+%
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dvar and dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    nplotr        (numeric, number of plot rows)
+%    nplotc        (numeric, number of plot columns)
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    zmin          (numeric, minimum of z-axis)
+%    zmax          (numeric, maximum of z-axis)
+%    cmin          (numeric, minimum of colorbar)
+%    cmax          (numeric, maximum of colorbar)
+%    smark         (numeric, size of markers)
+%
+%  for each response in the input array, this function plots a 3-d
+%  scatter plot.  there should be no more than three variables.
+%  each response will be in a separate scatter plot; hence the
+%  need for nplotr and nplotc.
+%
+%  dvar and dresp data would typically be contained in the dakota
+%  tabular output file from a sampling or parametric analysis, and
+%  read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_rvsv_scat3(varargin)
+
+if ~nargin
+    help plot_rvsv_scat3
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+iarg=1;
+
+%  variables
+
+if isstruct(varargin{iarg})
+    dvar=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dvar=struc_desc(dvar,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descv=cell (1,length(dvar));
+    lsamp=zeros(1,length(dvar));
+    for i=1:length(dvar)
+        lsamp(i)=length(dvar(i).sample);
+    end
+    sampv=zeros(max(lsamp),length(dvar));
+    sampv(:,:)=NaN;
+
+    for i=1:length(dvar)
+        descv(i)=cellstr(dvar(i).descriptor);
+        sampv(1:lsamp(i),i)=dvar(i).sample;
+    end
+else
+    sampv=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descv=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descv=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descv=cell(1,size(sampv,2));
+    end
+end
+
+for i=1:length(descv)
+    if isempty(descv{i})
+        descv(i)={['var_' i]};
+    end
+end
+
+if (size(sampv,2) > 3)
+    error('No more than three variables required for 3-d scatter plot.');
+end
+
+%  responses
+
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'nplotr','nplotc',...
+                 'ymin','ymax','zmin','zmax',...
+                 'cmin','cmax','smark'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if     ~exist('nplotr','var') && ~exist('nplotc','var')
+    nplotr=ceil(sqrt(size(sampr,2)));
+    nplotc=ceil(size(sampr,2)/nplotr);
+elseif ~exist('nplotr','var')
+    nplotr=ceil(size(sampr,2)/nplotc);
+elseif ~exist('nplotc','var')
+    nplotc=ceil(size(sampr,2)/nplotr);
+end
+
+if ~exist('smark','var')
+    smark=100;
+end
+
+%%  filter, sort, and plot the data
+
+figure
+haxes =[];
+hscat3=[];
+
+for iresp=1:size(sampr,2)
+
+%  initialize the subplot
+
+    haxes(end+1)=subplot(nplotr,nplotc,iresp);
+    switch size(sampv,2)
+        case 1
+            hscat3(end+1)=scatter (sampv(:,1),sampr(:,iresp),...
+                                   smark,sampr(:,iresp),'filled');
+        case 2
+            hscat3(end+1)=scatter3(sampv(:,1),sampv(:,2),sampr(:,iresp),...
+                                   smark,sampr(:,iresp),'filled');
+        case 3
+            hscat3(end+1)=scatter3(sampv(:,1),sampv(:,2),sampv(:,3),...
+                                   smark,sampr(:,iresp),'filled');
+    end
+
+    ylim('auto')
+    [ylims]=ylim;
+    if exist('ymin','var')
+        ylims(1)=ymin;
+    end
+    if exist('ymax','var')
+        ylims(2)=ymax;
+    end
+    ylim(ylims)
+
+    zlim('auto')
+    [zlims]=zlim;
+    if exist('zmin','var')
+        zlims(1)=zmin;
+    end
+    if exist('zmax','var')
+        zlims(2)=zmax;
+    end
+    zlim(zlims)
+
+%  add the annotation
+
+    switch size(sampv,2)
+        case 1
+            title([descr{iresp} ' wrt ' descv{1}],...
+                  'Interpreter','none');
+            xlabel(descv{1},'Interpreter','none');
+            ylabel(descr{iresp},'Interpreter','none');
+        case 2
+            title([descr{iresp} ' wrt ' descv{1} ' and ' descv{2}],...
+                  'Interpreter','none');
+            xlabel(descv{1},'Interpreter','none');
+            ylabel(descv{2},'Interpreter','none');
+            zlabel(descr{iresp},'Interpreter','none');
+        case 3
+            title([descr{iresp} ' wrt ' descv{1} ' and ' descv{2} ' and ' descv{3}],...
+                  'Interpreter','none');
+            xlabel(descv{1},'Interpreter','none');
+            ylabel(descv{2},'Interpreter','none');
+            zlabel(descv{3},'Interpreter','none');
+    end
+
+    caxis('auto')
+    [cmini,cmaxi]=caxis;
+    if exist('cmin','var')
+        cmini=cmin;
+    end
+    if exist('cmax','var')
+        cmaxi=cmax;
+    end
+    caxis([cmini cmaxi])
+
+    colorbar
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_surf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_surf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_rvsv_surf.m	(revision 18231)
@@ -0,0 +1,248 @@
+%
+%  plot surface plots of variables vs. responses.
+%
+%  []=plot_rvsv_surf(dvar       ,dresp      ,params)
+%  []=plot_rvsv_surf(dvar ,descv,dresp,descr,params)
+%  []=plot_rvsv_surf(sampv,descv,sampr,descr,params)
+%
+%  where the required input is:
+%    dvar          (structure array, variables)
+%      or
+%    dvar          (structure array, variables)
+%    descv         (cell array, list of variable descriptions desired)
+%      or
+%    sampv         (double array, lists of variable samples)
+%    descv         (cell array, list of variable descriptions)
+%
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dvar and dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    nplotr        (numeric, number of plot rows)
+%    nplotc        (numeric, number of plot columns)
+%    zmin          (numeric, minimum of z-axis)
+%    zmax          (numeric, maximum of z-axis)
+%    cmin          (numeric, minimum of colorbar)
+%    cmax          (numeric, maximum of colorbar)
+%
+%  for each response in the input array, this function plots a
+%  surface plot.  there should be two and only two variables.
+%  each response will be in a separate surface plot; hence the
+%  need for nplotr and nplotc.
+%
+%  dvar and dresp data would typically be contained in the dakota
+%  tabular output file from a sampling or parametric analysis, and
+%  read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_rvsv_surf(varargin)
+
+if ~nargin
+    help plot_rvsv_surf
+    return
+end
+
+%%  process input data and assemble into matrices as needed
+
+iarg=1;
+
+%  variables
+
+if isstruct(varargin{iarg})
+    dvar=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dvar=struc_desc(dvar,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descv=cell (1,length(dvar));
+    lsamp=zeros(1,length(dvar));
+    for i=1:length(dvar)
+        lsamp(i)=length(dvar(i).sample);
+    end
+    sampv=zeros(max(lsamp),length(dvar));
+    sampv(:,:)=NaN;
+
+    for i=1:length(dvar)
+        descv(i)=cellstr(dvar(i).descriptor);
+        sampv(1:lsamp(i),i)=dvar(i).sample;
+    end
+else
+    sampv=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descv=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descv=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descv=cell(1,size(sampv,2));
+    end
+end
+
+for i=1:length(descv)
+    if isempty(descv{i})
+        descv(i)={['var_' i]};
+    end
+end
+
+if (size(sampv,2) ~= 2)
+    error('Two and only two variables required for surface plot.');
+end
+
+%  responses
+
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+
+    descr=cell (1,length(dresp));
+    lsamp=zeros(1,length(dresp));
+    for i=1:length(dresp)
+        lsamp(i)=length(dresp(i).sample);
+    end
+    sampr=zeros(max(lsamp),length(dresp));
+    sampr(:,:)=NaN;
+
+    for i=1:length(dresp)
+        descr(i)=cellstr(dresp(i).descriptor);
+        sampr(1:lsamp(i),i)=dresp(i).sample;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1,size(sampr,2));
+    end
+end
+
+for i=1:length(descr)
+    if isempty(descr{i})
+        descr(i)={['resp_' num2str(i)]};
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'nplotr','nplotc',...
+                 'zmin','zmax',...
+                 'cmin','cmax'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+if     ~exist('nplotr','var') && ~exist('nplotc','var')
+    nplotr=ceil(sqrt(size(sampr,2)));
+    nplotc=ceil(size(sampr,2)/nplotr);
+elseif ~exist('nplotr','var')
+    nplotr=ceil(size(sampr,2)/nplotc);
+elseif ~exist('nplotc','var')
+    nplotc=ceil(size(sampr,2)/nplotr);
+end
+
+%%  filter, sort, and plot the data
+
+figure
+haxes=[];
+hsurf=[];
+
+[x,ix,ixi]=unique(sampv(:,1),'first');
+[y,iy,iyi]=unique(sampv(:,2),'first');
+
+for iresp=1:size(sampr,2)
+    z=zeros(length(x),length(y));
+    for i=1:size(sampr,1)
+        z(ixi(i),iyi(i))=sampr(i,iresp);
+    end
+
+%  initialize the subplot
+
+    haxes(iresp)=subplot(nplotr,nplotc,iresp);
+%     hsurf(iresp)=surfc(x,y,z,'FaceColor','interp');
+    surfc(x,y,z,'FaceColor','interp');
+
+    zlim('auto')
+    [zlims]=zlim;
+    if exist('zmin','var')
+        zlims(1)=zmin;
+    end
+    if exist('zmax','var')
+        zlims(2)=zmax;
+    end
+    zlim(zlims)
+
+%  add the annotation
+
+    title([descr{iresp} ' wrt ' descv{1} ' and ' descv{2}],...
+          'Interpreter','none');
+    xlabel(descv{1},'Interpreter','none');
+    ylabel(descv{2},'Interpreter','none');
+    zlabel(descr{iresp},'Interpreter','none');
+
+    caxis('auto')
+    [cmini,cmaxi]=caxis;
+    if exist('cmin','var')
+        cmini=cmin;
+    end
+    if exist('cmax','var')
+        cmaxi=cmax;
+    end
+    caxis([cmini cmaxi])
+
+    colorbar
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_sampdist_bars.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_sampdist_bars.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/plot/plot_sampdist_bars.m	(revision 18231)
@@ -0,0 +1,211 @@
+%
+%  plot a stacked bar chart of the sample distributions.
+%
+%  []=plot_sampdist_bars(dresp      ,params)
+%  []=plot_sampdist_bars(dresp,descr,params)
+%  []=plot_sampdist_bars(sampr,descr,params)
+%
+%  where the required input is:
+%    dresp         (structure array, responses)
+%      or
+%    dresp         (structure array, responses)
+%    descr         (cell array, list of response descriptions desired)
+%      or
+%    sampr         (double array, lists of response samples)
+%    descr         (cell array, list of response descriptions)
+%
+%  the required fields of dresp are:
+%    descriptor    (char, description)
+%    sample        (double vector, list of samples)
+%
+%  and the optional fields of dresp are:
+%    min           (double, minimum of sample)
+%    quart1        (double, first quartile of sample)
+%    median        (double, median of sample)
+%    quart3        (double, third quartile of sample)
+%    max           (double, maximum of sample)
+%
+%  the optional input is:
+%    params        (string/numeric, parameter names and values)
+%
+%  where the optional parameters are:
+%    ymin          (numeric, minimum of y-axis)
+%    ymax          (numeric, maximum of y-axis)
+%    xtlrot        (numeric, rotation in degrees of x-tick labels)
+%    lstr          (cell array, legend labels)
+%
+%  for each response in the input array, this function plots
+%  a stacked bar plot of the list of samples, where the bars
+%  are stacked by the four quartiles, and annotates it with
+%  the description.  the quartiles will be calculated from the
+%  samples if they do not already exist.
+%
+%  this data would typically be contained in the dakota tabular
+%  output file and read by dakota_out_parse.
+%
+%  "Copyright 2009, by the California Institute of Technology.
+%  ALL RIGHTS RESERVED. United States Government Sponsorship
+%  acknowledged. Any commercial use must be negotiated with
+%  the Office of Technology Transfer at the California Institute
+%  of Technology.  (J. Schiermeier, NTR 47078)
+%
+%  This software may be subject to U.S. export control laws.
+%  By accepting this  software, the user agrees to comply with
+%  all applicable U.S. export laws and regulations. User has the
+%  responsibility to obtain export licenses, or other export
+%  authority as may be required before exporting such information
+%  to foreign countries or providing access to foreign persons."
+%
+function []=plot_sampdist_bars(varargin)
+
+if ~nargin
+    help plot_sampdist_bars
+    return
+end
+
+%%  process input data and assemble into dresp as needed
+
+%  responses
+
+iarg=1;
+if isstruct(varargin{iarg})
+    dresp=varargin{iarg};
+    iarg=iarg+1;
+
+%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
+    if iarg <= nargin && iscell(varargin{iarg})
+        dresp=struc_desc(dresp,varargin{iarg});
+        iarg=iarg+1;
+    end
+else
+    sampr=varargin{iarg};
+    iarg=iarg+1;
+
+    if     iarg <= nargin && iscell(varargin{iarg})
+        descr=varargin{iarg};
+        iarg=iarg+1;
+%     elseif iarg <= nargin && ischar(varargin{iarg})
+%         descr=cellstr(varargin{iarg});
+%         iarg=iarg+1;
+    else
+        descr=cell(1:size(sampr,2));
+    end
+
+    dresp=struct([]);
+    for i=1:size(sampr,2)
+        dresp(end+1).sample=sampr(:,i);
+        if ~isempty(descr)
+            dresp(i).descriptor=descr{i};
+        else
+            dresp(i).descriptor=['dresp_' num2str(i)];
+        end
+    end
+end
+
+%  parameters
+
+while (iarg <= nargin-1)
+    if ischar(varargin{iarg})
+        if ~isempty(strmatch(varargin{iarg},...
+                {'ymin','ymax','xtlrot','lstr'},...
+                'exact'))
+            eval([varargin{iarg} '=varargin{iarg+1};']);
+            disp([varargin{iarg} '=' any2str(varargin{iarg+1}) ';']);
+        else
+            warning([varargin{iarg} '=' any2str(varargin{iarg+1}) ' is not recognized.']);
+        end
+    else
+        error(['''' any2str(varargin{iarg}) ''' is not a parameter name.']);
+    end
+    iarg=iarg+2;
+end
+
+%%  calculate any missing information (noting that dresp is local)
+
+if ~isfield(dresp,'min')    || ~isfield(dresp,'quart1') || ...
+   ~isfield(dresp,'median') || ~isfield(dresp,'quart3') || ...
+   ~isfield(dresp,'max')
+    for i=1:length(dresp)
+        dresp(i).min   =min         (dresp(i).sample);
+        dresp(i).quart1=prctile_issm(dresp(i).sample,25);
+        dresp(i).median=median      (dresp(i).sample);
+        dresp(i).quart3=prctile_issm(dresp(i).sample,75);
+        dresp(i).max   =max         (dresp(i).sample);
+    end
+end
+
+%%  assemble the data into a matrix and calculate the increments
+
+descr=cell (1,length(dresp));
+data =zeros(length(dresp),5);
+
+for i=1:length(dresp)
+    descr(i)=cellstr(dresp(i).descriptor);
+    data(i,1)=dresp(i).min;
+    data(i,2)=dresp(i).quart1-dresp(i).min;
+    data(i,3)=dresp(i).median-dresp(i).quart1;
+    data(i,4)=dresp(i).quart3-dresp(i).median;
+    data(i,5)=dresp(i).max   -dresp(i).quart3;
+end
+
+%%  draw the stacked bar plot
+
+%  if there's only one row, Matlab 7.5 interprets it as a column,
+%  so add an extra row, then reduce xlim
+
+if length(dresp) == 1
+    data=[data; data];
+end
+
+figure
+hl1=bar(data,'stacked');
+%  set barseries properties for lowest value
+whitebg('white')
+set(hl1(1),'FaceColor','white')
+set(hl1(1),'Visible','off')
+
+ax1=gca;
+if length(dresp) == 1
+    set(ax1,'xlim',[0.5 1.5])
+end
+
+ylim('auto')
+[ylims]=ylim;
+if exist('ymin','var')
+    ylims(1)=ymin;
+end
+if exist('ymax','var')
+    ylims(2)=ymax;
+end
+ylim(ylims)
+
+set(ax1,'xtick',1:length(descr))
+set(ax1,'xticklabel',descr)
+if exist('xtlrot','var')
+    htl=rotateticklabel(ax1,xtlrot);
+    tlext=zeros(length(htl),4);
+    for i=1:length(htl)
+        tlext(i,:)=get(htl(i),'Extent');
+    end
+end
+
+%  add the annotation
+
+title('Sample Distributions of Responses')
+xlabel('Response')
+if exist('xtlrot','var')
+    xlext=get(get(ax1,'xlabel'),'Extent');
+    nskip=ceil(max(tlext(:,4))/xlext(4));
+    xlabel(cellstr([repmat('        ',nskip,1);'Response']));
+    clear nskip xlext tlext
+end
+ylabel('Value')
+
+if ~exist('lstr','var') || isempty(lstr)
+    lstr={'minimum' 'quartile 1' 'median' 'quartile 3' 'maximum'};
+end
+
+hleg1=legend(ax1,lstr,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/postqmu.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/postqmu.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/postqmu.m	(revision 18231)
@@ -0,0 +1,55 @@
+function md=postqmu(md)
+%INPUT function md=postqmu(md,qmufile,qmudir)
+%Deal with dakota output results in files.
+
+%  check to see if dakota returned errors in the err file
+qmuerrfile=[md.miscellaneous.name '.qmu.err'];
+
+if exist(qmuerrfile,'file')
+   fide=fopen(qmuerrfile,'r');
+   fline=fgetl(fide);
+   if ischar(fline)
+       while ischar(fline)
+           disp(sprintf('%s',fline));
+           fline=fgetl(fide);
+       end
+       status=fclose(fide);
+       cd ../
+       error(['Dakota returned error in ''' qmuerrfile ' file.  ''' qmudir ''' directory retained.'])
+    end
+    status=fclose(fide);
+else
+   cd ../
+   error(['Dakota did not generate ''' qmuerrfile ' file.  ''' qmudir ''' directory retained.'])
+end
+
+%parse inputs and results from dakota
+qmuinfile=[md.miscellaneous.name '.qmu.in'];
+qmuoutfile=[md.miscellaneous.name '.qmu.out'];
+
+%[method,dvar,dresp_in]=dakota_in_parse(qmuinfile);
+%dakotaresults.method   =method;
+%dakotaresults.dvar     =dvar;
+%dakotaresults.dresp_in =dresp_in;
+
+[method,dresp_out,scm,pcm,srcm,prcm]=dakota_out_parse(qmuoutfile);
+dakotaresults.dresp_out=dresp_out;
+dakotaresults.scm      =scm;
+dakotaresults.pcm      =pcm;
+dakotaresults.srcm     =srcm;
+dakotaresults.prcm     =prcm;
+
+if exist('dakota_tabular.dat','file')
+    [method,dresp_dat                  ]=dakota_out_parse('dakota_tabular.dat');
+    dakotaresults.dresp_dat=dresp_dat;
+end
+
+%put dakotaresults in their right location.
+md.results.dakota=dakotaresults;
+
+%  move all the individual function evalutations into zip files
+if ~md.qmu.isdakota,
+	system('zip -mq params.in.zip params.in.[1-9]*');
+	system('zip -mq results.out.zip results.out.[1-9]*');
+	system('zip -mq matlab.out.zip matlab*.out.[1-9]*');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/preqmu.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/preqmu.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/preqmu.m	(revision 18231)
@@ -0,0 +1,109 @@
+function md=preqmu(md,options)
+%QMU - apply Quantification of Margins and Uncertainties techniques 
+%      to a solution sequence (like stressbalance.m, progonstic.m, etc ...), 
+%      using the Dakota software from Sandia.
+%
+%   options come from the solve.m routine. They can include Dakota options:
+%
+%       qmudir:  any directory where to run the qmu analysis
+%       qmufile: input file for Dakota
+%       ivar: selection number for variables input (if several are specified in variables)
+%       iresp: same thing for response functions
+%       imethod: same thing for methods
+%       iparams: same thing for params
+%       overwrite: overwrite qmudir before analysis
+
+disp('preprocessing dakota inputs');
+qmudir    = getfieldvalue(options,'qmudir',['qmu' num2str(feature('GetPid'))]);  % qmudir = ['qmu_' datestr(now,'yyyymmdd_HHMMSS')];
+qmufile   = getfieldvalue(options,'qmufile','qmu');% qmufile cannot be changed unless ????script.sh is also changed
+overwrite = getfieldvalue(options,'overwrite','n');
+ivar      = getfieldvalue(options,'ivar',1);
+iresp     = getfieldvalue(options,'iresp',1);
+imethod   = getfieldvalue(options,'imethod',1);
+iparams   = getfieldvalue(options,'iparams',1);
+
+%first create temporary directory in which we will work
+if strncmpi(overwrite,'y',1)
+	system(['rm -rf ' qmudir '/*']); 
+else
+	%does the directory exist? if so, then error out
+	if exist(qmudir)==7,
+		error('Existing ''%s'' directory, cannot overwrite. Specify ''overwrite'',''y'' option in solve arguments.',options.qmudir);
+	end
+end
+mkdir(qmudir)
+cd(qmudir)
+
+%when running in library mode, the in file needs to be called md.miscellaneous.name.qmu.in
+qmufile=[md.miscellaneous.name ];
+
+%retrieve variables and resposnes for this particular analysis.
+variables=md.qmu.variables(ivar);
+responses=md.qmu.responses(iresp);
+
+%expand variables and responses
+variables=expandvariables(md,variables);
+responses=expandresponses(md,responses);
+
+%go through variables and responses, and check they don't have more than md.qmu.numberofpartitions values. Also determine numvariables and numresponses{{{
+numvariables=0;
+variable_fieldnames=fieldnames(variables);
+for i=1:length(variable_fieldnames),
+	field_name=variable_fieldnames{i};
+	fieldvariables=variables.(field_name);
+	for j=1:numel(fieldvariables)
+		if strncmpi(fieldvariables(j).descriptor,'scaled_',7) && str2int(fieldvariables(j).descriptor,'last')>md.qmu.numberofpartitions,
+			error('preqmu error message: one of the expanded variables has more values than the number of partitions (setup in md.qmu.numberofpartitions)');
+		end
+	end
+	numvariables=numvariables+numel(variables.(field_name));
+end
+
+numresponses=0;
+response_fieldnames=fieldnames(responses);
+for i=1:length(response_fieldnames),
+	field_name=response_fieldnames{i};
+	fieldresponses=responses.(field_name);
+	for j=1:numel(fieldresponses)
+		if strncmpi(fieldresponses(j).descriptor,'scaled_',7) && str2int(fieldresponses(j).descriptor,'last')>md.qmu.numberofpartitions,
+			error('preqmu error message: one of the expanded responses has more values than the number of partitions (setup in md.qmu.numberofpartitions)');
+		end
+	end
+	numresponses=numresponses+numel(responses.(field_name));
+end
+%}}}}
+
+%create in file for dakota
+dakota_in_data(md.qmu.method(imethod),variables,responses,md.qmu.params(iparams),qmufile);
+system(['rm -rf ' md.miscellaneous.name '.m']);
+
+%build a list of variables and responses descriptors. the list is not expanded. {{{
+variabledescriptors={};
+variable_fieldnames=fieldnames(md.qmu.variables(ivar));
+for i=1:length(variable_fieldnames),
+	field_name=variable_fieldnames{i};
+	fieldvariables=md.qmu.variables(ivar).(field_name);
+	for j=1:numel(fieldvariables)
+		variabledescriptors{end+1}=fieldvariables(j).descriptor;
+	end
+end
+
+responsedescriptors={};
+response_fieldnames=fieldnames(md.qmu.responses(iresp));
+for i=1:length(response_fieldnames),
+	field_name=response_fieldnames{i};
+	fieldresponses=md.qmu.responses(iresp).(field_name);
+	for j=1:numel(fieldresponses)
+		responsedescriptors{end+1}=fieldresponses(j).descriptor;
+	end
+end
+%}}}
+
+%register the fields that will be needed by the Qmu model.
+md.qmu.numberofresponses=numresponses;
+md.qmu.variabledescriptors=variabledescriptors;
+md.qmu.responsedescriptors=responsedescriptors;
+
+%now, we have to provide all the info necessary for the solutions to compute the responses. For ex, if mass_flux 
+%is a response, we need a profile of points.  For a misfit, we need the observed velocity, etc ...
+md=process_qmu_response_data(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_options.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_options.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_options.m	(revision 18231)
@@ -0,0 +1,100 @@
+function outoptions=process_qmu_options(options)
+%PROCESS_QMU_OPTIONS - set up default options for qmu phase
+%
+%   Usage:
+%      options=process_qmu_options(options)
+%
+%   See also: QMU,RECOVER_QMU_OPTIONS
+
+%analysis_type: check on this option, error out otherwise
+found=0;
+for i=1:size(options,1),
+	if strcmpi(options{i,1},'analysis_type'),
+		analysis_type=options{i,2};
+		found=1;
+	end
+end
+if ~found,
+	error('recover_qmu_options error message: no ''analysis_type'' was provided');
+end
+
+%package: is there one? default to ''JPL''
+found=0;
+for i=1:size(options,1),
+	if strcmpi(options{i,1},'package'),
+		package=options{i,2};
+		found=1;
+	end
+end
+if ~found,
+	disp('recover_qmu_options info message: no ''package'' was provided, defaulting to ''JPL''');
+	options(end+1,:)={'package' 'JPL'};
+	package='JPL';
+end
+
+if ~ischar(package), 
+	error(['process_qmu_options error message: package ' package ' not supported yet']);
+end
+
+%check solution type is supported
+if ~(strcmpi(analysis_type,'control') |  ...
+		strcmpi(analysis_type,'stressbalance') |  ...
+		strcmpi(analysis_type,'masstransport') |  ...
+		strcmpi(analysis_type,'thermal') |  ...
+		strcmpi(analysis_type,'parameters') |  ...
+		strcmpi(analysis_type,'transient') ),
+	error(['process_qmu_options error message: analysis_type ' analysis_type ' not supported yet!']);
+end
+
+%  process qmu arguments
+
+%first, the defaults
+qmudir ='qmu';% qmudir =['qmu_' datestr(now,'yyyymmdd_HHMMSS')];
+qmufile='qmu';
+ivar   =1;
+iresp  =1;
+imethod=1;
+iparams=1;
+runmpi =false;
+
+for i=1:size(options,1),
+	switch options{i,1},
+	case 'qmudir'
+		qmudir=options{i,2};
+	case 'qmufile'
+		qmufile=options{i,2};
+	case 'ivar'
+		ivar=options{i,2};
+	case 'iresp'
+		iresp=options{i,2};
+	case 'imethod'
+		imethod=options{i,2};
+	case 'iparams'
+		iparams=options{i,2};
+	case 'overwrite'
+		outoptions.overwrite=options{i,2};
+	case 'keep'
+		outoptions.keep=options{i,2};
+	case 'outfiles'
+		outoptions.outfiles=options{i,2};
+	case 'rstfile'
+		outoptions.rstfile=options{i,2}; 
+	case 'rundakota'
+		outoptions.rundakota=options{i,2};
+	case 'runmpi'
+		runmpi=options{i,2};
+	otherwise
+		%nothing
+	end
+end
+
+%setup final options structure
+outoptions.analysis_type=analysis_type;
+outoptions.package=package;
+outoptions.qmudir=qmudir;
+outoptions.qmufile=qmufile;
+outoptions.ivar=ivar;
+outoptions.iresp=iresp;
+outoptions.imethod=imethod;
+outoptions.iparams=iparams;
+outoptions.runmpi=runmpi;
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_response_data.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_response_data.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/process_qmu_response_data.m	(revision 18231)
@@ -0,0 +1,50 @@
+function md=process_qmu_response_data(md)
+%PROCESS_QMU_RESPONSE_DATA - process any data necessary for the solutions to process the data. 
+%
+% Usage: md=process_qmu_response_data(md)
+%
+% See also PREQMU, PRESOLVE
+
+%preliminary data
+process_mass_flux_profiles=0;
+
+num_mass_flux=0;
+
+%loop through response descriptors, and act accordingly
+for i=1:numel(md.qmu.responsedescriptors),
+
+	%Do we have to process  mass flux profiles?
+	if strncmpi(md.qmu.responsedescriptors{i},'indexed_MassFlux',16),
+		num_mass_flux=num_mass_flux+1;
+		process_mass_flux_profiles=1;
+	end
+end
+
+%deal with mass flux profiles
+if process_mass_flux_profiles,
+
+	%we need a profile of points on which to compute the mass_flux, is it here? 
+	if isnans(md.qmu.mass_flux_profiles),
+		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');
+	end
+
+	if isempty(md.qmu.mass_flux_profiles),
+		error('process_qmu_response_data error message: qmu_mass_flux_profiles cannot be empty!');
+	end
+
+	if num_mass_flux~=numel(md.qmu.mass_flux_profiles),
+		error('process_qmu_response_data error message: qmu_mass_flux_profiles should be of the same size as the number of MassFlux responses asked for in the Qmu analysis');
+	end
+
+	%ok, process the domains named in qmu_mass_flux_profiles,  to build a list of segments (MatArray)
+	md.qmu.mass_flux_segments=cell(num_mass_flux,1);
+
+	for i=1:num_mass_flux,
+		md.qmu.mass_flux_segments{i}=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,[md.qmu.mass_flux_profile_directory '/' md.qmu.mass_flux_profiles{i}]);
+	end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmu_correlation.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmu_correlation.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmu_correlation.m	(revision 18231)
@@ -0,0 +1,50 @@
+function factors=qmu_correlation(md,variablename,responsename)
+%QMU_CORRELATION - compute correlation between qmu output and a certain input variable.
+%
+%   Usage:
+%      factors=qmu_correlation(md,variablename,responsename)
+%
+%
+%   Example:
+%      mass_flux_drag_correlation=qmu_correlation(md,'drag','mass_flux');
+
+if ~isfield(md.qmu.results,'dresp_dat'),
+	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;
+
+%go through all the rows and figure which one we are interested in.
+found=0;
+for i=1:numel(data),
+	if strcmpi(data(i).descriptor,responsename),
+		found=i;
+		break;
+	end
+end
+if found==0,
+	error(['qmu_correlation error message: could not find data descriptor for response ' responsename]);
+end
+
+%get the response samples.
+response_samples=data(found).sample;
+
+%now go through variables, and compute correlation coefficient each time: 
+variablenamelength=length(variablename);
+index=[];
+for i=1:numel(data),
+	if strncmpi(variablename,data(i).descriptor,variablenamelength),
+		%this observation is one we are looking for.
+		index=[index;i];
+	end
+end
+
+if isempty(index),
+	error(['qmu_correlation error message: could not find correlation descriptor for variable ' variablename]);
+end
+
+factors=zeros(numel(index),1);
+for i=1:numel(index),
+	matrix=corrcoef(data(index(i)).sample,response_samples);
+	factors(i)=matrix(2,1);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuisdistributed.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuisdistributed.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuisdistributed.m	(revision 18231)
@@ -0,0 +1,11 @@
+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.
+last=string(end);
+
+if ((double(last)<=57) & (double(last)>=48)),
+	found=1;
+else
+	found=0;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmumarshall.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmumarshall.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmumarshall.m	(revision 18231)
@@ -0,0 +1,75 @@
+function qmumarshall(md.qmu.variables,responses)
+%QMUMARSHALL - output ISSM compatible binary file with qmu fields. This is 
+%   in addition to the marshall routine for regular solve routines.
+%   Usage:
+%      qmumarshall(md.qmu.variables,responses)
+% 
+%   where variables and responses are the Dakota variables and responses found in the model @md.
+
+%some checks on list of arguments
+if ((nargin~=3) & (nargout~=0))
+	qmumarshallusage;
+	error('marshall error message');
+end
+
+disp(['qmu marshalling file ' md.miscellaneous.name '.bin']);
+
+%open file for binary adding 
+fid=fopen([ md.miscellaneous.name '.bin'],'ab');
+if fid==-1,
+	error(['qmumarshall error message: could not open ' [md.miscellaneous.name '.bin'],' file for binary adding']);
+end
+
+%deal with variables
+WriteData(fid,md.numvariabledescriptors,'Integer','numvariabledescriptors');
+for i=1:md.numvariabledescriptors,
+	field_name=md.qmu.variabledescriptors{i};
+	WriteData(fid,field_name,'String',['variabledescriptor' num2str(i)]);
+end
+
+%deal with responses
+
+%write number of responses to disk
+WriteData(fid,md.qmu.numberofresponses,'Integer','numberofresponses');
+WriteData(fid,md.qmu.numresponsedescriptors,'Integer','numresponsedescriptors');
+for i=1:md.qmu.numresponsedescriptors,
+	field_name=md.qmu.responsedescriptors{i};
+	WriteData(fid,field_name,'String',['responsedescriptor' num2str(i)]);
+end
+
+%write response specific data
+qmu_segments=0;
+
+for i=1:numel(md.qmu.responsedescriptors),
+	field_name=md.qmu.responsedescriptors{i};
+	if strncmpi(field_name,'indexed_MassFlux',16),
+		qmu_segments=1;
+	end
+end
+
+if qmu_segments,
+	WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
+	for i=1:md.qmu.mass_flux_num_profiles,
+		WriteData(fid,md.qmu.mass_flux_segments{i},'Mat',['qmu_mass_flux_segments' num2str(i)]);
+	end
+else
+	md.qmu.mass_flux_num_profiles=0;
+	WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
+end
+
+%write part and npart to disk
+WriteData(fid,md.qmu.numberofpartitions,'Integer','npart');
+WriteData(fid,md.qmu.partition,'Mat','part');
+
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['qmumarshall error message: could not close file ' [md.miscellaneous.name '.bin']]);
+end
+
+end
+
+function qmumarshallusage()
+disp(' ');
+disp('function qmumarshall(md.qmu.variables,responses)');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuname.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuname.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuname.m	(revision 18231)
@@ -0,0 +1,15 @@
+function md=qmuname(md,varargin)
+%INPUT function md=qmuname(md)
+%Pick up the number from a file, or get it directly from the Dakota structure.  Then modify the name of this 
+%model to reflect this new number.
+
+if nargin==1,
+	fid=fopen('number','r');
+	number=fscanf(fid,'%i',1)
+	fclose(fid);
+else
+	number=varargin{1};
+end
+
+%modify model name by appending number to the name
+md.miscellaneous.name=[md.miscellaneous.name num2str(number)];
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuresponse.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuresponse.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuresponse.m	(revision 18231)
@@ -0,0 +1,116 @@
+function response=qmuresponse(models,results,processedresults,descriptor)
+%QMURESPONSE - compute response function from model results.
+
+if strcmpi(descriptor,'max_vel'),
+	response=max(processedresults.vel);
+elseif strcmpi(descriptor,'min_vel'),
+	response=min(processedresults.vel);
+elseif strcmpi(descriptor,'max_vx'),
+	response=max(processedresults.vx);
+elseif strcmpi(descriptor,'max_abs_vx'),
+	response=max(abs(processedresults.vx));
+elseif strcmpi(descriptor,'min_vx'),
+	response=min(processedresults.vx);
+elseif strcmpi(descriptor,'max_vy'),
+	response=max(processedresults.vy);
+elseif strcmpi(descriptor,'max_abs_vy'),
+	response=max(abs(processedresults.vy));
+elseif strcmpi(descriptor,'min_vy'),
+	response=min(processedresults.vy);
+elseif strncmpi(descriptor,'mass_flux',9),
+	indx=str2int(descriptor(10:end));
+	if isempty(indx) || ~indx
+		indx=1;
+	end
+
+	%call mass flux module.
+	m_dh=models.dh;
+	m_dhu=models.dhu;
+	m_ds=models.ds;
+	isSIA=m_dhu.parameters.isSIA;
+	isSSA=m_dh.parameters.isSSA;
+	isHO=m_dh.parameters.isHO;
+	isFS=m_ds.parameters.isFS;
+	if isSIA,
+
+% for now, separate all segments from double array for parallel to make cells
+		if (length(m_dhu.parameters.qmu_mass_flux_num_segments) > 1)
+			segments=m_dhu.parameters.qmu_mass_flux_segments;
+			m_dhu.parameters.qmu_mass_flux_segments=cell(size(m_dhu.parameters.qmu_mass_flux_num_segments));
+			ipt=1;
+			for i=1:length(m_dhu.parameters.qmu_mass_flux_num_segments)
+				if m_dhu.parameters.qmu_mass_flux_num_segments(i)
+					m_dhu.parameters.qmu_mass_flux_segments{i}=segments(ipt:ipt+m_dhu.parameters.qmu_mass_flux_num_segments(i)-1,:);
+					ipt=ipt+m_dhu.parameters.qmu_mass_flux_num_segments(i);
+				end
+			end
+			clear segments
+		end
+
+		if isnumeric(m_dhu.parameters.qmu_mass_flux_segments)
+			response=MassFlux(m_dhu.elements,m_dhu.nodes,m_dhu.vertices,m_dhu.loads,m_dhu.materials,m_dhu.parameters,results.u_g);
+		else
+			save=m_dhu.parameters.qmu_mass_flux_segments;
+			m_dhu.parameters.qmu_mass_flux_segments=m_dhu.parameters.qmu_mass_flux_segments{indx};
+			response=MassFlux(m_dhu.elements,m_dhu.nodes,m_dhu.vertices,m_dhu.loads,m_dhu.materials,m_dhu.parameters,results.u_g);
+			m_dhu.parameters.qmu_mass_flux_segments=save;
+			clear save
+		end
+
+	elseif isSSA || isHO,
+
+% for now, separate all segments from double array for parallel to make cells
+		if (length(m_dh.parameters.qmu_mass_flux_num_segments) > 1)
+			segments=m_dh.parameters.qmu_mass_flux_segments;
+			m_dh.parameters.qmu_mass_flux_segments=cell(size(m_dh.parameters.qmu_mass_flux_num_segments));
+			ipt=1;
+			for i=1:length(m_dh.parameters.qmu_mass_flux_num_segments)
+				if m_dh.parameters.qmu_mass_flux_num_segments(i)
+					m_dh.parameters.qmu_mass_flux_segments{i}=segments(ipt:ipt+m_dh.parameters.qmu_mass_flux_num_segments(i)-1,:);
+					ipt=ipt+m_dh.parameters.qmu_mass_flux_num_segments(i);
+				end
+			end
+			clear segments
+		end
+
+		if isnumeric(m_dh.parameters.qmu_mass_flux_segments)
+			response=MassFlux(m_dh.elements,m_dh.nodes,m_dh.vertices,m_dh.loads,m_dh.materials,m_dh.parameters,results.u_g);
+		else
+			save=m_dh.parameters.qmu_mass_flux_segments;
+			m_dh.parameters.qmu_mass_flux_segments=m_dh.parameters.qmu_mass_flux_segments{indx};
+			response=MassFlux(m_dh.elements,m_dh.nodes,m_dh.vertices,m_dh.loads,m_dh.materials,m_dh.parameters,results.u_g);
+			m_dh.parameters.qmu_mass_flux_segments=save;
+			clear save
+		end
+
+	elseif isFS,
+
+% for now, separate all segments from double array for parallel to make cells
+		if (length(m_ds.parameters.qmu_mass_flux_num_segments) > 1)
+			segments=m_ds.parameters.qmu_mass_flux_segments;
+			m_ds.parameters.qmu_mass_flux_segments=cell(size(m_ds.parameters.qmu_mass_flux_num_segments));
+			ipt=1;
+			for i=1:length(m_ds.parameters.qmu_mass_flux_num_segments)
+				if m_ds.parameters.qmu_mass_flux_num_segments(i)
+					m_ds.parameters.qmu_mass_flux_segments{i}=segments(ipt:ipt+m_ds.parameters.qmu_mass_flux_num_segments(i)-1,:);
+					ipt=ipt+m_ds.parameters.qmu_mass_flux_num_segments(i);
+				end
+			end
+			clear segments
+		end
+
+		if isnumeric(m_ds.parameters.qmu_mass_flux_segments)
+			response=MassFlux(m_ds.elements,m_ds.nodes,m_ds.vertices,m_ds.loads,m_ds.materials,m_ds.parameters,results.u_g);
+		else
+			save=m_ds.parameters.qmu_mass_flux_segments;
+			m_ds.parameters.qmu_mass_flux_segments=m_ds.parameters.qmu_mass_flux_segments{indx};
+			response=MassFlux(m_ds.elements,m_ds.nodes,m_ds.vertices,m_ds.loads,m_ds.materials,m_ds.parameters,results.u_g);
+			m_ds.parameters.qmu_mass_flux_segments=save;
+			clear save
+		end
+	else
+		error('qmuresponse error message: unsupported analysis type for mass_flux computation!');
+	end
+else
+	error(['qmuresponse error message: unknown descriptor ' descriptor]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuroot.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuroot.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/qmuroot.m	(revision 18231)
@@ -0,0 +1,12 @@
+function root=qmuroot(string)
+%QMUROOT - return root of a distributed descriptor
+
+root='';
+found=0;
+for i=1:length(string),
+	if ((49<=double(string(i))) && (double(string(i)<=57)))
+		break;
+	else
+		root=[root string(i)];
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/recover_qmu_options.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/recover_qmu_options.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/recover_qmu_options.m	(revision 18231)
@@ -0,0 +1,22 @@
+function options=recover_qmu_options(md,varargin)
+%RECOVER_SOLVE_OPTIONS - recover solution options for qmu runs.
+%
+%   Usage:
+%      options=recover_qmu_options(md,varargin);
+%
+%   See also: SOLVE
+
+%initialize options.
+options=cell(0,2);
+
+%make sure length(varargin) is even, ie options come in pairs.
+if mod(length(varargin),2),
+	error('recover_qmu_options error message: an even number of options is necessary');
+end
+
+%go through varargin, extract options 
+for i=1:length(varargin)/2,
+
+	options(end+1,:)={varargin{2*i-1} varargin{2*i}};
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlev_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlev_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlev_write.m	(revision 18231)
@@ -0,0 +1,66 @@
+%
+%  function to write response levels
+%
+function []=rlev_write(fidi,dresp,params)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+
+nresp=0;
+respl={};
+probl={};
+rell ={};
+grell={};
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    [respli,probli,relli,grelli]=prop_levels(dresp.(fnames{i}));
+    respl=[respl respli];
+    probl=[probl probli];
+    rell =[rell  relli ];
+    grell=[grell grelli];
+end
+
+%  write response levels
+
+param_write(fidi,'\t  ','distribution',' ','\n',params);
+if ~isempty(respl)
+    rlevi_write(fidi,'response_levels',respl);
+    param_write(fidi,'\t  ','compute',' ','\n',params);
+end 
+if ~isempty(probl)
+    rlevi_write(fidi,'probability_levels',probl);
+end
+if ~isempty(rell)
+    rlevi_write(fidi,'reliability_levels',rell);
+end
+if ~isempty(grell)
+    rlevi_write(fidi,'gen_reliability_levels',grell);
+end
+
+end
+
+%
+%  function to each type of response level
+%
+function []=rlevi_write(fidi,ltype,levels)
+
+fprintf(fidi,'\t  num_%s =',ltype);
+for i=1:numel(levels)
+    fprintf(fidi,' %d',length(levels{i}));
+end
+fprintf(fidi,'\n');
+
+fprintf(fidi,'\t  %s =\n',ltype);
+
+for i=1:numel(levels)
+    if ~isempty(levels{i})
+        vector_write(fidi,sprintf('\t    '),levels{i},8,76);
+    end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlist_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlist_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/rlist_write.m	(revision 18231)
@@ -0,0 +1,69 @@
+%
+%  function to write response list
+%
+function [rdesc]=rlist_write(fidi,cstring,cstring2,dresp,rdesc)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+%  (and accumulate descriptors into list for subsequent writing)
+
+nresp=0;
+pstype =[];
+pscale =[];
+pweight=[];
+plower =[];
+pupper =[];
+ptarget=[];
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    pstype =[pstype  prop_stype(dresp.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dresp.(fnames{i})) ];
+    pweight=[pweight prop_weight(dresp.(fnames{i}))];
+    plower =[plower  prop_lower(dresp.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dresp.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dresp.(fnames{i}))];
+    rdesc  =[rdesc   prop_desc(dresp.(fnames{i}),fnames{i})];
+end
+
+%  write responses
+
+disp(sprintf('  Writing %d %s responses.',nresp,cstring));
+
+fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pweight)
+    switch cstring2
+        case 'objective_function'
+            fprintf(fidi,'\t  %s_weights =\n','multi_objective');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+        case 'least_squares_term'
+            fprintf(fidi,'\t  %s_weights =\n','least_squares');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+    end
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/sensitivities.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/sensitivities.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/sensitivities.m	(revision 18231)
@@ -0,0 +1,68 @@
+function sens=sensitivies(md,variablename,responsename)
+%SENSITIVIES - compute sensitivities for a certain variable and response.
+%
+%   Usage:
+%      sens=sensitivities(md,variablename,responsename)
+%
+%
+%   Example: sens=sensitivities(md,'DragCoefficient','MaxVel');
+%
+
+variablenamelength=length(variablename);
+
+%go through all response functions and find the one corresponding to the correct responsename
+responsefunctions=md.qmu.results.dresp_out;
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsename),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.var,1);
+
+%Now recover response to the correct design variable
+rawsens=zeros(0,1);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.var{i};
+	if strncmpi(desvar,variablename,variablenamelength),
+		rawsens(end+1,1)=responsefunctions.sens(i);
+		count=count+1;
+	end
+end
+
+%Now, if this was a distributed variable, the sensitivities need to be scaled by means of the input variable.
+if IsScaled(variablename),
+
+	%ipick up the variable in the model
+	switch variablename,
+		case 'thickness', variable = md.geometry.thickness; 
+		otherwise, error(['scaled variable ' variablename  ' not associated to any model field']);
+	end
+
+	%average it onto the partition
+	average_variable=AreaAverageOntoPartition(md,variable);
+
+	%scale the sensitivities: only where the average_variable is not 0 
+	if ~isempty(rawsens),
+		pos=find(average_variable);
+		rawsens(pos)=rawsens(pos)./average_variable(pos);
+	end
+end
+
+if count==0,
+	error('sensitivities error message: either response does not exist, or sensitivities are empty');
+end
+
+if count==1, %we have scalar
+	sens=rawsens;
+	return;
+else
+	%project the sensitivities from the partition onto the mesh
+	sens=rawsens(md.qmu.partition'+1); %md.qmu.partition was created to index "c" style
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/IsScaled.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/IsScaled.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/IsScaled.m	(revision 18231)
@@ -0,0 +1,19 @@
+function status=IsScaled(variablename)
+%ISSCALED decide whether a variable should be scaled or not. 
+
+switch variablename,
+case {'MaterialsRhoIce','MaterialsRhoSeawater','MaterialsHeatCapacity','MaterialsThermalConductivity','Gravity','MaxVel'},
+
+	status=0;
+
+case {'GeometryThickness','GeometrySurface','GeometryBed','FrictionCoefficient','MaterialsRheologyB','MaterialsRheologyBbar'},
+
+	status=1;
+
+case {'RiftsFriction'},
+
+	status=2; %special treatment
+
+otherwise
+	error(['IsScaled error  message: could not find ' variablename]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupResponses.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupResponses.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupResponses.m	(revision 18231)
@@ -0,0 +1,23 @@
+function dresp=QmuSetupResponses(md,dresp,responses)
+
+%get descriptor
+descriptor=responses.descriptor;
+
+%decide whether this is a distributed response, 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:
+if strncmp(descriptor,'scaled_',7),
+	%we have a scaled response, expand it over the partition.
+
+	%ok, dealing with semi-discrete distributed response. Distribute according to how many 
+	%partitions we want
+
+	for j=1:md.qmu.numberofpartitions
+		dresp(end+1)           =responses;
+		dresp(end  ).descriptor=sprintf('%s_%d',responses.descriptor,j);
+	end
+
+else
+	dresp(end+1)=responses;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupVariables.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 18231)
@@ -0,0 +1,45 @@
+function dvar=QmuSetupVariables(md,dvar,variables)
+
+%get descriptor
+descriptor=variables.descriptor;
+
+%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:
+if strncmp(descriptor,'scaled_',7),
+	%we have a scaled variable, expand it over the partition.
+
+	if isa(variables,'uniform_uncertain'),
+		if (length(variables.lower)>md.qmu.numberofpartitions || length(variables.upper)>md.qmu.numberofpartitions)
+			error('QmuSetupDesign error message: stddev should be either a scalar or a ''npart'' length vector');
+		end
+	elseif isa(variables,'normal_uncertain'),
+		if length(variables.stddev)>md.qmu.numberofpartitions,
+			error('QmuSetupDesign error message: stddev should be either a scalar or a ''npart'' length vector');
+		end
+	end
+
+	%ok, dealing with semi-discrete distributed variable. Distribute according to how many 
+	%partitions we want
+
+	for j=1:md.qmu.numberofpartitions
+		dvar(end+1)           =variables;
+		dvar(end  ).descriptor=sprintf('%s_%d',variables.descriptor,j);
+		if isa(variables,'uniform_uncertain'),
+			if length(variables.lower)>1,
+				dvar(end  ).lower=variables.lower(j);
+			end
+			if length(variables.upper)>1,
+				dvar(end  ).upper=variables.upper(j);
+			end
+		elseif isa(variables,'normal_uncertain'),
+			if length(variables.stddev)>1,
+				dvar(end  ).stddev=variables.stddev(j);
+			end
+		end
+	end
+
+else
+	dvar(end+1)=variables;
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/setupriftsfriction.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/setupriftsfriction.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/setupdesign/setupriftsfriction.m	(revision 18231)
@@ -0,0 +1,10 @@
+function dvar=setupriftsfriction(md,dvar,variables)
+
+%we have several rifts.
+
+for j=1:md.rifts.numrifts
+	dvar(end+1)           =variables;
+	dvar(end  ).descriptor=sprintf('%s%d',variables.descriptor,j);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vector_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vector_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vector_write.m	(revision 18231)
@@ -0,0 +1,52 @@
+
+%%  function to write a vector on multiple lines
+
+function []=vector_write(fidi,sbeg,vec,nmax,cmax)
+
+if ~exist('nmax','var') || isempty(nmax)
+    nmax=Inf;
+end
+if ~exist('cmax','var') || isempty(cmax)
+    cmax=Inf;
+end
+
+%  set up first iteration
+
+svec =[];
+nitem=nmax;
+lsvec=cmax;
+
+%  transpose vector from column-wise to row-wise
+
+vec=vec';
+
+%  assemble each line, flushing when necessary
+
+for i=1:numel(vec)
+    if isnumeric(vec(i))
+        sitem=sprintf('%g'    ,vec(i));
+    else
+        sitem=sprintf('''%s''',char(vec(i)));
+    end
+    nitem=nitem+1;
+    lsvec=lsvec+1+length(sitem);
+
+    if (nitem <= nmax) && (lsvec <= cmax)
+        svec=[svec ' ' sitem];
+    else
+        if ~isempty(svec)
+            fprintf(fidi,'%s\n',svec);
+        end
+        svec=[sbeg sitem];
+        nitem=1;
+        lsvec=length(svec);
+    end
+end
+
+%  flush buffer at end, if necessary
+
+if ~isempty(svec)
+    fprintf(fidi,'%s\n',svec);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vlist_write.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vlist_write.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/qmu/vlist_write.m	(revision 18231)
@@ -0,0 +1,80 @@
+%
+%  function to write variable list
+%
+function []=vlist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put variables into lists for writing
+
+nvar=0;
+pinitpt=[];
+plower =[];
+pupper =[];
+pmean  =[];
+pstddev=[];
+pinitst=[];
+pstype =[];
+pscale =[];
+pdesc  =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pinitpt=[pinitpt prop_initpt(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    pmean  =[pmean   prop_mean(dvar.(fnames{i}))  ];
+    pstddev=[pstddev prop_stddev(dvar.(fnames{i}))];
+    pinitst=[pinitst prop_initst(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+    pdesc  =[pdesc   prop_desc(dvar.(fnames{i}),fnames{i})];
+end
+
+%  write variables
+%  (using Dakota 4.1 syntax for backward compatability)
+
+disp(sprintf('  Writing %d %s variables.',nvar,cstring));
+
+fprintf(fidi,'\t%s = %d\n',cstring,nvar);
+if ~isempty(pinitpt)
+    fprintf(fidi,'\t  %s_initial_point =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitpt,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(pmean)
+    fprintf(fidi,'\t  %s_means =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmean  ,6,76);
+end
+if ~isempty(pstddev)
+    fprintf(fidi,'\t  %s_std_deviations =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstddev,6,76);
+end
+if ~isempty(pinitst)
+    fprintf(fidi,'\t  %s_initial_state =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitst,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pdesc)
+    fprintf(fidi,'\t  %s_descriptors =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pdesc  ,6,76);
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrain.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrain.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrain.m	(revision 18231)
@@ -0,0 +1,63 @@
+function md=BasinConstrain(md,domain)
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.stressbalance.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.stressbalance.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.stressbalance.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.stressbalance.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.stressbalance.spcvx(md.stressbalance.icefront(:,1:2))) + ~isnan(md.stressbalance.spcvy(md.stressbalance.icefront(:,1:2))))~=2);
+md.stressbalance.icefront=md.stressbalance.icefront(free_segments,:);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrainShelf.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrainShelf.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/BasinConstrainShelf.m	(revision 18231)
@@ -0,0 +1,74 @@
+function md=BasinConstrainShelf(md,domain)
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.stressbalance.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.stressbalance.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.stressbalance.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.stressbalance.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure any node with NaN velocity is spc'd:
+%we spc to the smoothed value, so that control methods don't go berserk trying to figure out what reaction force to apply for the spc to stand.
+pos=find(isnan(md.inversion.vel_obs_raw));
+md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%iceshelves: any vertex on floating ice is spc'd
+pos=find(md.mask.groundedice_levelset<0.);
+md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.stressbalance.spcvx(md.stressbalance.icefront(:,1:2))) + ~isnan(md.stressbalance.spcvy(md.stressbalance.icefront(:,1:2))) )~=2);
+md.stressbalance.icefront=md.stressbalance.icefront(free_segments,:);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/basinzoom.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/basinzoom.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/basinzoom.m	(revision 18231)
@@ -0,0 +1,94 @@
+function varargout=basinzoom(varargin)
+%ANTZOOM - zoom on a basin in Antarctica or Greenland.
+%
+%   This function zooms on an existing figure describing Antarctica or Greenland 
+%   The zooming depends on the region name provided as input. 
+%
+%   Usage:
+%      varargout=basinzoom(options)
+
+%recover some options, and set defaults
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+unitmultiplier=getfieldvalue(options,'unit',NaN);
+basin=getfieldvalue(options,'basin');
+
+if exist(options,'basindelta'),
+
+	basindeltax=getfieldvalue(options,'basindelta',300); 
+	basindeltay=getfieldvalue(options,'basindelta',300); 
+else
+	basindeltax=getfieldvalue(options,'basindeltax',300); 
+	basindeltay=getfieldvalue(options,'basindeltay',300);
+end
+
+%multiply by 1000 to get kms
+basindeltax=basindeltax*1000;
+basindeltay=basindeltay*1000;
+
+%Ok, find basin we are talking about: 
+load([jplsvn() '/ModelData/Names/Names.mat']);
+
+%Go through names: 
+found=0;
+for i=1:size(names,1),
+	if strcmpi(names{i,1},basin),
+		%ok, we've got the region. Get lat and long: 
+		long=names{i,2};
+		lat=names{i,3};
+		hemisphere=names{i,4};
+		found=1;
+		break;
+	end
+end
+
+if ~found,
+	error(['basinzoom error message: cannot find basin ' basin '. Use isbasin to determine a basin name.']);
+end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Transform lat long into x,y: 
+[xc,yc]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%compute x0,x1 and y0,y1 using basindeltax and basindeltay
+x0=xc-basindeltax/2;
+x1=xc+basindeltax/2;
+y0=yc-basindeltay/2;
+y1=yc+basindeltay/2;
+
+if ~isnan(unitmultiplier)
+	x0=x0*unitmultiplier;
+	x1=x1*unitmultiplier;
+	y0=y0*unitmultiplier;
+	y1=y1*unitmultiplier;
+end
+
+%if output arguments are present, return the limits, 
+%otherwise, set them on the current graphic. 
+if nargout==2,
+	found=1;
+	varargout{1}=[x0 x1];
+	varargout{2}=[y0 y1];
+else
+	xlim([x0 x1]);
+	ylim([y0 y1]);
+	found=1;
+	daspect([1;1;1]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/isbasin.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/isbasin.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/isbasin.m	(revision 18231)
@@ -0,0 +1,17 @@
+function isbasin(name)
+%ISBASIN: figure out if a basin name exists.
+%
+%
+%        Usage:  index=isbasin('jks');
+%
+%
+
+%First, load basin names:
+load([jplsvn '/ModelData/Names/Names.mat']);
+
+%go through names: 
+for i=1:length(names),
+	if ~isempty(strfind(names{i,1},name)),
+		disp(['''' names{i,1} ''' Long:' num2str(names{i,2}) ' Lat:' num2str(names{i,3}) ]);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/plotbasins.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/plotbasins.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/plotbasins.m	(revision 18231)
@@ -0,0 +1,18 @@
+%display all the domain outlines in a directory
+
+basins=listfiles;
+
+hold on
+for i=1:length(basins), 
+	%check whether this is a .exp file
+	basin=basins{i};
+	if strcmpi(basin(end-3:end),'.exp'),
+
+		contour=expread(basin,0);
+		x=contour(1).x;
+		y=contour(1).y;
+		x0=mean(x); y0=mean(y);
+		text(x0,y0,basin(1:end-4),'Fontsize',14);
+		expdisp(basin);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/regionaltransient2d.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/regionaltransient2d.m	(revision 18231)
@@ -0,0 +1,157 @@
+function md2=regionaltransient2d(md1,area,hmin,hmax,err,stepres)
+%regionaltransient2d - extract a model according to an Argus contour or flag list and remesh
+%               at new resolution res
+%
+%   This routine extracts a submodel from a bigger model with respect to a given contour
+%   md must be followed by the corresponding exp domain file (argus type, .exp extension). 
+%   The model will be remeshed at high rsolution hmin and low resolution hmax.  The ice 
+%   boundary velocities will be spc'd to the transient velocities at saved transient steps
+%   at the resolution optionally provided for stepres.  A stepres of 2 means that you wish
+%   to skip every other saved transient step.  This is useful when extracting a long transient.
+%
+%   Usage:
+%      md2=regionaltransient2d(md1,area,hmin,hmax,err);
+%
+%   Examples:
+%      md2=regionaltransient2d(md,'Domain.exp',500,10000,[15 250]);
+%      md2=regionaltransient2d(md,'Domain.exp',3000,15000,[10 300],2);
+%
+%   See also: MODELEXTRACT, EXTRUDE, COLLAPSE
+
+%some checks
+if ((nargin~=5) & (nargin~=6)),
+	help regionaltransient2d 
+	error('regionaltransient2d error message: bad usage');
+end
+
+%get check option
+if (nargin==5),
+	stepres=1;
+end
+
+%take every fields from model
+mde=md1.extract(area);
+mde.private.bamg=[];
+mde.mesh.extractedvertices=nan;
+mde.mesh.extractedelements=nan;
+
+%remesh
+md2=bamg(mde,'hmin',hmin,'hmax',hmax,'field',[mde.inversion.vel_obs mde.geometry.surface],'splitcorner',1,'KeepVertices',0,'err',err);
+md2=setmask(md2,'','');
+
+%automatically modify fields
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+
+		%get field
+		field=md1.(model_fields{i});
+		fieldsize=size(field);
+
+		%copy field, interpolated to new mesh
+		if isobject(field), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			fname=['(model_fields{i}).(object_fields{j})'];
+		else
+			object_fields=field;
+			fname=['(model_fields{i})'];
+		end
+		for j=1:length(object_fields),
+			%get field
+			field=eval(['md2.' fname]);
+			fieldsize=size(field);
+
+			%size = number of nodes * n
+			for n=1:fieldsize(2)
+				if fieldsize(1)==mde.mesh.numberofvertices
+					if(sum(field(:,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=field(1,n)*ones(md2.mesh.numberofvertices,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices,n);']);
+				elseif fieldsize(1)==mde.mesh.numberofvertices+1
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[field(1,n)*ones(md2.mesh.numberofvertices,1); field(end,n)];']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(1:end-1,n),md2.mesh.x,md2.mesh.y); field(end,n)];']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices+1,n)']);
+					%size = number of elements * n
+				elseif fieldsize(1)==mde.mesh.numberofelements
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=field(1,n)*ones(md2.mesh.numberofelements,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofelements,n);']);
+				end
+			end
+		end
+	end
+
+	%Read transient velocities and thickness, looping through only the populated times
+	spcx=[];
+	spcy=[];
+	spct=[];
+	steps=[];
+	nsteps=length(md1.results.TransientSolution);
+	count=0;
+	numElements=arrayfun(@(x) numel(x.step), md1.results.TransientSolution);
+	for t=find(numElements==1)
+		if ~isempty(md1.results.TransientSolution(t).Vel) & mod(count,stepres)==0,
+			vx=md1.results.TransientSolution(t).Vx;
+			vy=md1.results.TransientSolution(t).Vy;
+			thickness=md1.results.TransientSolution(t).Thickness;
+			spcx=[spcx InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
+			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vy,md2.mesh.x,md2.mesh.y)];
+			spct=[spct InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,thickness,md2.mesh.x,md2.mesh.y)];
+			steps=[steps t*md1.timestepping.time_step];
+		end
+		count=count+1;
+	end
+
+	%As long as there are recorded time steps, spc the boundaries with velocities
+	if nsteps > 0
+		md2.stressbalance.spcvx=md2.stressbalance.spcvx*ones(1,size(spcx,2));
+		md2.stressbalance.spcvy=md2.stressbalance.spcvy*ones(1,size(spcy,2));
+		md2.stressbalance.spcvz=md2.stressbalance.spcvz*ones(1,size(spcx,2));
+		md2.masstransport.spcthickness=md2.masstransport.spcthickness*ones(1,size(spct,2));
+		md2.stressbalance.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvz(find(md2.mesh.vertexonboundary),:)=0;
+		md2.masstransport.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvx=[md2.stressbalance.spcvx; steps];
+		md2.stressbalance.spcvy=[md2.stressbalance.spcvy; steps];
+		md2.stressbalance.spcvz=[md2.stressbalance.spcvz; steps];
+		md2.masstransport.spcthickness=[md2.masstransport.spcthickness; steps];
+	end
+
+	%Stressbalance.  Don't spc the icefront vertices.
+	if ~isnan(md2.stressbalance.icefront)
+		md1s=md1.extract(area);
+		%md2.stressbalance.icefront=[md2.mesh.segments 2];
+		e2=md2.mesh.segments(:,end);
+		e1=md1s.mesh.segments(:,end);
+
+		pload = nan*ones(size(md1s.mesh.elements,1),1);
+		pload(md1s.stressbalance.icefront(:,end-1))=md1s.stressbalance.icefront(:,end);
+
+		x2=mean(md2.mesh.x(md2.mesh.elements(e2,:)),2);
+      y2=mean(md2.mesh.y(md2.mesh.elements(e2,:)),2);
+		x1=mean(md1s.mesh.x(md1s.mesh.elements),2);
+      y1=mean(md1s.mesh.y(md1s.mesh.elements),2);
+
+		pload2=griddata(x1,y1,pload,x2,y2,'nearest');
+		md2.stressbalance.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
+		md2.stressbalance.spcvx(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.stressbalance.spcvy(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.stressbalance.spcvz(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.masstransport.spcthickness(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+	end
+
+	%Clear results fields
+	if isstruct(md1.results),
+		md2.results=[];
+	end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/showbasins.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/showbasins.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/regional/showbasins.m	(revision 18231)
@@ -0,0 +1,68 @@
+function showbasins(varargin)
+%SHOWBASINS - return basins that are within the xlim and ylim
+%
+%   Usage:
+%      names=showbasins(options);
+%   Options: 
+%      'unit' default 1
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+%recover some options, and set defaults
+unitmultiplier=getfieldvalue(options,'unit',1);
+fontsize=getfieldvalue(options,'fontsize',12);
+hemisphere=getfieldvalue(options,'hemisphere');
+
+if strcmpi(hemisphere,'s'),
+	hemisphere=-1;
+elseif strcmpi(hemisphere,'n'),
+	hemisphere=+1;
+else
+	error('showbasins error message: hemispehre should be either ''n'' or ''s''');
+	end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Ok, find basin we are talking about: 
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
+
+%Get xlim and ylim, and convert into lat,long: 
+xlimits=xlim; x0=xlimits(1); x1=xlimits(2);
+ylimits=ylim; y0=ylimits(1); y1=ylimits(2);
+
+%Convert names lat and long into x,y:
+lat=cell2mat(names(:,3));
+long=cell2mat(names(:,2));
+
+%Now, convert lat,long into x,y:
+[x,y]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%Find  x,y within xlimits and ylimits: 
+locations=find(x>x0 & x<x1 & y>y0 & y<y1);
+
+%Go through locations, and display the names: 
+for i=1:size(locations,1),
+	hold on,
+	plot(x(locations(i)),y(locations(i)),'r.');
+	t=text(x(locations(i)),y(locations(i)),names{locations(i),1}); 
+	set(t,'FontSize',fontsize);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.m	(revision 18231)
@@ -0,0 +1,48 @@
+function Shp2Exp(expfilename,shapefilename)
+%SHP2EXP- transform shape file to Argus .exp file
+%
+%   Usage:
+%      Shp2Exp(expfilename,shapefilename);
+%
+%   Example:
+%      Shp2Exp('Domain.exp','Domain.shp');
+%
+%   See also EXPMASTER, EXPDOC
+
+	if ~exist(shapefilename,'file'),
+		error(['Shapefile ' shapefilename ' does not exist']);
+	end
+	shp=shaperead(shapefilename);
+
+	expstruct=struct([]);
+	for i=1:length(shp),
+		if strcmpi(shp(i).Geometry,'Polygon'),
+			x=shp(i).X; y=shp(i).Y;
+			ids=find(isnan(x));
+			x(ids)=[]; y(ids)=[];
+			expstruct(end+1).x=x;
+			expstruct(end).y=y;
+			expstruct(end).nods=length(x);
+			expstruct(end).density=1;
+			expstruct(end).closed=1;
+			expstruct(end).name=num2str(shp(i).id);
+		elseif strcmpi(shp(i).Geometry,'Point'),
+			x=shp(i).X; y=shp(i).Y;
+			expstruct(end+1).x=x;
+			expstruct(end).y=y;
+			expstruct(end).nods=length(x);
+			expstruct(end).density=1;
+			expstruct(end).closed=1;
+			%exp(end).name=num2str(shp(i).id);
+		elseif strcmpi(shp(i).Geometry,'Line'),
+			x=shp(i).X; y=shp(i).Y;
+			x(end)=x(1); y(end)=y(1);
+			expstruct(end+1).x=x;
+			expstruct(end).y=y;
+			expstruct(end).nods=length(x);
+			expstruct(end).density=1;
+			expstruct(end).closed=1;
+		end
+	end
+
+	expwrite(expstruct,expfilename);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shp2exp.py	(revision 18231)
@@ -0,0 +1,55 @@
+import shapefile
+import os
+from expwrite import expwrite
+
+def shp2exp(shapefilename,*expfilename):
+	'''
+	Convert a shapefile to an .exp file.  Optionally, expfilename can be
+	specified to give a name for the .exp file to be created, otherwise the
+	.exp file will have the same prefix as the .shp file.
+
+	Usage:
+		shp2exp(shapefilename)
+		shp2exp(shapefilename,expfilename)
+
+	Examples:
+		shp2exp('Domain.shp') % creates Domain.exp
+		shp2exp('Domain.shp','DomainForISSM.exp')
+	'''
+	
+	if not os.path.exists(shapefilename):
+		raise IOError("shp2exp error message: file '%s' not found!" % parametername)
+	if not len(expfilename):
+		expfile=os.path.splitext(shapefilename)[0]+'.exp'
+	else:
+		expfile=expfilename[0]
+
+	shp=shapefile.Reader(shapefilename)
+	expdict=dict(closed=1,density=1)
+
+	x=[]
+	y=[]
+	for i in range(len(shp.shapes())):
+		geom=shp.shapes()[i].shapeType
+		if geom==5: # polygon
+			x=[p[0] for p in shp.shapes()[i].points]
+			y=[q[1] for q in shp.shapes()[i].points]
+			expdict['x']=x
+			expdict['y']=y
+			expdict['nods']=len(x)
+		elif geom==3: # line
+			x=[p[0] for p in shp.shapes()[i].points]
+			y=[q[1] for q in shp.shapes()[i].points]
+			x.append(x[0])
+			y.append(y[0])
+			expdict['x']=x
+			expdict['y']=y
+			expdict['nods']=len(x)
+		elif geom==1: # point
+			x.append(shp.shapes()[i].points[0][0])
+			y.append(shp.shapes()[i].points[0][1])
+			expdict['x']=x
+			expdict['y']=y
+			expdict['nods']=len(x)
+
+	expwrite([expdict],expfile)
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpdisp.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpdisp.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpdisp.m	(revision 18231)
@@ -0,0 +1,57 @@
+function shpdisp(domainoutline,varargin)
+%SHPDISP - plot the contours of a domain outline file
+%
+%   This routine reads in a domain outline file (Shape format) and plots all the contours 
+%
+%   Usage:
+%      shpdisp(domainoutline,varargin)
+%      shpdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%
+%   Example:
+%      shpdisp('Domain.shp',1,'--r',2,10^3);
+%
+%   See also SHPREAD, SHPDOC
+
+%check nargin
+if ~nargin | nargin>5
+	help shpdisp
+	error('shpdisp error message: bad usage');
+end
+
+%parse input
+if nargin<=1,
+	figurenumber=1;
+else
+	figurenumber=varargin{1};
+end
+if nargin<=2
+	linestyle='r-';
+else
+	linestyle=varargin{2};
+end
+if nargin<=3
+	linewidth=1;
+else
+	linewidth=varargin{3};
+end
+if nargin<=4
+	unitmultiplier=1;
+else
+	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
+end
+
+domain=shpread(domainoutline);
+
+figure(figurenumber),hold on
+for i=1:length(domain),
+	if(isfield(domain,'nods'))
+		if (isnumeric(linestyle))
+			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+		else
+			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+	  end
+	else
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'ro','MarkerSize',5);
+	end
+	
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpread.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpread.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpread.m	(revision 18231)
@@ -0,0 +1,80 @@
+function Struct=shpread(filename)
+%SHPREAD - read a shape file and build a Structure
+%
+%   This routine reads a shape file .shp and builds a Structure containing the 
+%   fields x and y corresponding to the coordinates, one for the filename of
+%   the shp file, for the density, for the nodes, and a field closed to 
+%   indicate if the domain is closed. 
+%   If this initial shapefile is point only, the fields closed and
+%   points are ommited
+%   The first argument is the .shp file to be read and the second one (optional) 
+%   indicates if the last point shall be read (1 to read it, 0 not to).
+%
+%   Usage:
+%      Struct=shpread(filename)
+%
+%   Example:
+%      Struct=shpread('domainoutline.shp')
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['shpread error message: file ' filename ' not found!']);
+end
+
+%initialize number of profile
+count=0;
+
+%read shapefile
+shp=shaperead(filename);
+
+Struct=struct([]);
+fields=fieldnames(shp);
+for i=1:length(shp),
+	if strcmpi(shp(i).Geometry,'Polygon'),
+		x=shp(i).X'; y=shp(i).Y';
+		ids=find(isnan(x));
+		x(ids)=[]; y(ids)=[];
+
+		Struct(end+1).x=x;
+		Struct(end).y=y;
+		Struct(end).nods=length(x);
+		Struct(end).density=1;
+		Struct(end).closed=1;
+		if isfield(shp,'id'),
+			Struct(end).name=num2str(shp(i).id);
+		else
+			Struct(end).name='';
+		end
+		for j=1:length(fields),
+			field=fields{j};
+			if ~(strcmpi(field,'X') | strcmpi(field,'Y') | strcmpi(field,'id')),
+				Struct(end).(field)=shp(i).(field);
+			end
+		end
+	end
+
+	if strcmpi(shp(i).Geometry,'Point'),
+		x=shp(i).X'; y=shp(i).Y';
+		ids=find(isnan(x));
+		x(ids)=[]; y(ids)=[];
+
+		Struct(end+1).x=x;
+		Struct(end).y=y;
+		Struct(end).density=1;
+		if isfield(shp,'id'),
+			Struct(end).name=num2str(shp(i).id);
+		else
+			Struct(end).name='';
+		end
+		for j=1:length(fields),
+			field=fields{j};
+			if ~(strcmpi(field,'X') | strcmpi(field,'Y') | strcmpi(field,'id')),
+				Struct(end).(field)=shp(i).(field);
+			end
+		end
+	end
+end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpwrite.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpwrite.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/shp/shpwrite.m	(revision 18231)
@@ -0,0 +1,29 @@
+function shpwrite(shp,filename)
+%SHPWRITE - write a shape file from a contour structure
+%
+%   Usage:
+%      shpwrite(shp,filename)
+%
+%   Example:
+%      shpwrite(shp,'domainoutline.shp')
+%
+%   See also SHPREAD
+
+
+%initialize number of profile
+count=0;
+
+contours=struct([]);
+for i=1:length(shp),
+	if strcmpi(shp(i).Geometry,'Point'),
+		contours(i).Geometry='Point';
+	else strcmpi(shp(i).Geometry,'Polygon'),
+		contours(i).Geometry='Polygon';
+	end
+	contours(i).id=i;
+	contours(i).X=shp(i).x;
+	contours(i).Y=shp(i).y;
+end
+	
+shapewrite(contours,filename);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.m	(revision 18231)
@@ -0,0 +1,284 @@
+function WriteData(fid,varargin)
+%WRITEDATA - write model field in binary file
+%
+%   Usage:
+%      WriteData(fid,varargin);
+
+%process options
+options=pairoptions(varargin{:});
+
+%Get data properties
+if exist(options,'object');
+	%This is a object field, construct enum and data
+	obj       = getfieldvalue(options,'object');
+	fieldname = getfieldvalue(options,'fieldname');
+	classname = getfieldvalue(options,'class',class(obj));
+	if exist(options,'enum'),
+		enum = getfieldvalue(options,'enum');
+	else
+		enum = BuildEnum([classname '_' fieldname]);
+	end
+	data      = obj.(fieldname);
+else
+	%No processing required
+	data = getfieldvalue(options,'data');
+	enum = getfieldvalue(options,'enum');
+end
+format  = getfieldvalue(options,'format');
+mattype = getfieldvalue(options,'mattype',0);    %only required for matrices
+forcinglength = getfieldvalue(options,'forcinglength',-1);
+
+%Process sparse matrices
+if issparse(data),
+	data=full(data);
+end
+
+%Scale data if necesarry
+if exist(options,'scale'),
+	scale = getfieldvalue(options,'scale');
+	if size(data,1)==forcinglength,
+		data(1:end-1,:) = scale.*data(1:end-1,:);
+	else
+		data  = scale.*data;
+	end
+end
+if(size(data,1)==forcinglength),
+	yts=365.0*24.0*3600.0;
+	data(end,:) = data(end,:)*yts;
+end
+
+%Step 1: write the enum to identify this record uniquely
+fwrite(fid,enum,'int'); 
+
+%Step 2: write the data itself.
+if     strcmpi(format,'Boolean'),% {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 bool (disguised as an int)+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int');  %send an int, not easy to send a bool
+	% }}}
+elseif strcmpi(format,'Integer'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 integer + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int'); 
+	% }}}
+elseif strcmpi(format,'Double'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,8+4,'int');  %1 double+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write double
+	fwrite(fid,data,'double'); 
+	% }}}
+elseif strcmpi(format,'String'), % {{{
+	%first write length of record
+	fwrite(fid,length(data)+4+4,'int');  %string + string size + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write string
+	fwrite(fid,length(data),'int'); 
+	fwrite(fid,data,'char'); 
+	% }}}
+elseif strcmpi(format,'BooleanMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'IntMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'DoubleMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	recordlength=4+4+8*s(1)*s(2)+4+4; %2 integers (32 bits) + the double matrix + code + matrix type
+	if recordlength>2^31; error(['field ' EnumToString(enum) ' cannot be marshalled because it is larger than 2^31 bytes!']); end
+	fwrite(fid,recordlength,'int');
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'MatArray'), % {{{
+
+	numrecords=numel(data);
+
+	%first get length of record
+	recordlength=4+4; %number of records + code
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		recordlength=recordlength+4*2+... %row and col of matrix
+			s(1)*s(2)*8; %matrix of doubles
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%write data, first number of records
+	fwrite(fid,numrecords,'int'); 
+
+	%write each matrix: 
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		fwrite(fid,s(1),'int'); 
+		fwrite(fid,s(2),'int'); 
+		fwrite(fid,matrix','double');
+	end
+	% }}}
+elseif strcmpi(format,'StringArray'), % {{{
+
+	%first get length of string array: 
+	num=numel(data);
+	if isnumeric(data) & num==1 & isnan(data),
+		num = 0;
+	end
+
+	%now get length of record: 
+	recordlength=4+4; %for length of array + code
+	for i=1:num,
+		string=data{i};
+		recordlength=recordlength+4+length(string); %for each string
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write length of string array
+	fwrite(fid,num,'int'); 
+
+	%now write the strings
+	for i=1:num,
+		string=data{i};
+		fwrite(fid,length(string),'int'); 
+		fwrite(fid,string,'char'); 
+	end
+	% }}}
+else  % {{{
+	error(['WriteData error message: data type: ' num2str(format) ' not supported yet! (' EnumToString(enum) ')']);
+end % }}}
+end
+
+function enum=BuildEnum(string) % {{{
+%BUILDENUM - build enum out of string
+%
+%   Usage:
+%      enum=BuildEnum(string)
+
+	if findstr(string,'_'),
+		indices=findstr(string,'_');
+		for i=1:length(indices),
+			string(indices(i)+1)=upper(string(indices(i)+1));
+		end
+		string(indices)=[];
+	end
+
+	%take first letter of string and make it uppercase: 
+	string(1)=upper(string(1));
+
+	%Get Enum
+	enum=StringToEnum(string); 
+end % }}}
+function code=FormatToCode(format) % {{{
+%This routine takes the format string, and hardcodes it into an integer, which 
+%is passed along the record, in order to identify the nature of the dataset being 
+%sent.
+	if     strcmpi(format,'Boolean'),
+		code=1;
+	elseif strcmpi(format,'Integer'), 
+		code=2;
+	elseif strcmpi(format,'Double'), 
+		code=3;
+	elseif strcmpi(format,'String'), 
+		code=4;
+	elseif strcmpi(format,'BooleanMat'),
+		code=5;
+	elseif strcmpi(format,'IntMat'),
+		code=6;
+	elseif strcmpi(format,'DoubleMat'),
+		code=7;
+	elseif strcmpi(format,'MatArray'), 
+		code=8;
+	elseif strcmpi(format,'StringArray'),
+		code=9;
+	else 
+		error('FormatToCode error message: data type not supported yet!');
+	end
+end% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/WriteData.py	(revision 18231)
@@ -0,0 +1,344 @@
+import numpy
+import math
+import struct
+import pairoptions
+import MatlabFuncs as m
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def WriteData(fid,*args):
+	"""
+	WRITEDATA - write model field in binary file
+ 
+	   Usage:
+	      WriteData(fid,varargin)
+	"""
+
+	#process options
+	options=pairoptions.pairoptions(*args)
+
+	#Get data properties
+	if options.exist('object'):
+		#This is an object field, construct enum and data
+		obj       = options.getfieldvalue('object')
+		fieldname = options.getfieldvalue('fieldname')
+		classname = options.getfieldvalue('class',str(type(obj)).rsplit('.')[-1].split("'")[0])
+		if options.exist('enum'):
+			enum = options.getfieldvalue('enum')
+		else:
+			enum = BuildEnum(classname+'_'+fieldname)
+		data      = getattr(obj,fieldname)
+	else:
+		#No processing required
+		data = options.getfieldvalue('data')
+		enum = options.getfieldvalue('enum')
+	format  = options.getfieldvalue('format')
+	mattype = options.getfieldvalue('mattype',0)    #only required for matrices
+	forcinglength = options.getfieldvalue('forcinglength',-1)
+
+	#Process sparse matrices
+#	if issparse(data),
+#		data=full(data);
+#	end
+
+	#Scale data if necesarry
+	if options.exist('scale'):
+		scale = options.getfieldvalue('scale')
+		if numpy.size(data) > 1 :
+			if numpy.size(data,0)==forcinglength:
+				data=numpy.array(data)
+				data[0:-1,:] = scale*data[0:-1,:]
+			else:
+				data  = scale*data
+		else:
+			data  = scale*data
+	if numpy.size(data) > 1 :
+		if numpy.size(data,0)==forcinglength:
+			yts=365.0*24.0*3600.0
+			data[-1,:] = yts*data[-1,:]
+
+	#Step 1: write the enum to identify this record uniquely
+	fid.write(struct.pack('i',enum)) 
+
+	#Step 2: write the data itself.
+	if   m.strcmpi(format,'Boolean'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 bool (disguised as an int)+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',int(data)))  #send an int, not easy to send a bool
+		# }}}
+
+	elif m.strcmpi(format,'Integer'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 integer + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',data)) 
+		# }}}
+
+	elif m.strcmpi(format,'Double'):    # {{{
+#		if len(data) !=1:
+#			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
+
+		#first write length of record
+		fid.write(struct.pack('i',8+4))  #1 double+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write double
+		fid.write(struct.pack('d',data)) 
+		# }}}
+
+	elif m.strcmpi(format,'String'):    # {{{
+		#first write length of record
+		fid.write(struct.pack('i',len(data)+4+4))  #string + string size + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write string
+		fid.write(struct.pack('i',len(data))) 
+		fid.write(struct.pack('%ds' % len(data),data)) 
+		# }}}
+
+	elif m.strcmpi(format,'BooleanMat'):    # {{{
+
+		if   isinstance(data,bool):
+			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
+		if numpy.ndim(data) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif m.strcmpi(format,'IntMat'):    # {{{
+
+		if   isinstance(data,(int,long)):
+			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
+		if numpy.ndim(data) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif m.strcmpi(format,'DoubleMat'):    # {{{
+
+		if   isinstance(data,(bool,int,long,float)):
+			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
+		if numpy.ndim(data) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s=(0,0)
+
+		#first write length of record
+		recordlength=4+4+8*s[0]*s[1]+4+4; #2 integers (32 bits) + the double matrix + code + matrix type
+		if recordlength > 2**31 :
+			raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % EnumToString(enum)[0])
+
+		fid.write(struct.pack('i',recordlength))  #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif m.strcmpi(format,'MatArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #number of records + code
+		for matrix in data:
+			if   isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			elif isinstance(matrix,(list,tuple)):
+				matrix=numpy.array(matrix).reshape(-1,1)
+			if numpy.ndim(matrix) == 1:
+				if numpy.size(matrix):
+					matrix=matrix.reshape(numpy.size(matrix),1)
+				else:
+					matrix=matrix.reshape(0,0)
+
+			s=matrix.shape
+			recordlength+=4*2+s[0]*s[1]*8    #row and col of matrix + matrix of doubles
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#write data, first number of records
+		fid.write(struct.pack('i',len(data))) 
+
+		#write each matrix: 
+		for matrix in data:
+			if   isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			elif isinstance(matrix,(list,tuple)):
+				matrix=numpy.array(matrix).reshape(-1,1)
+			if numpy.ndim(matrix) == 1:
+				matrix=matrix.reshape(numpy.size(matrix),1)
+
+			s=matrix.shape
+			fid.write(struct.pack('i',s[0])) 
+			fid.write(struct.pack('i',s[1])) 
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					fid.write(struct.pack('d',float(matrix[i][j])))
+		# }}}
+
+	elif m.strcmpi(format,'StringArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #for length of array + code
+		for string in data:
+			recordlength+=4+len(string)    #for each string
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write length of string array
+		fid.write(struct.pack('i',len(data))) 
+
+		#now write the strings
+		for string in data:
+			fid.write(struct.pack('i',len(string))) 
+			fid.write(struct.pack('%ds' % len(string),string)) 
+		# }}}
+
+	else:    # {{{
+		raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,EnumToString(enum)[0]))
+	# }}}
+
+def BuildEnum(string): # {{{
+	"""
+	BUILDENUM - build enum out of string
+ 
+    Usage:
+       enum=BuildEnum(string)
+	"""
+
+	if '_' in string:
+		substrs=string.split('_')
+		string=''
+		for substr in substrs:
+			string+=substr[0].upper()+substr[1:]
+	else:
+		#take first letter of string and make it uppercase: 
+		string=string[0].upper()+string[1:]
+
+	#Get Enum
+	enum=StringToEnum(string)[0]
+
+	return enum
+# }}}
+
+def FormatToCode(format): # {{{
+	"""
+	This routine takes the format string, and hardcodes it into an integer, which 
+	is passed along the record, in order to identify the nature of the dataset being 
+	sent.
+	"""
+
+	if   m.strcmpi(format,'Boolean'):
+		code=1
+	elif m.strcmpi(format,'Integer'):
+		code=2
+	elif m.strcmpi(format,'Double'):
+		code=3
+	elif m.strcmpi(format,'String'):
+		code=4
+	elif m.strcmpi(format,'BooleanMat'):
+		code=5
+	elif m.strcmpi(format,'IntMat'):
+		code=6
+	elif m.strcmpi(format,'DoubleMat'):
+		code=7
+	elif m.strcmpi(format,'MatArray'):
+		code=8
+	elif m.strcmpi(format,'StringArray'):
+		code=9
+	else:
+		raise InputError('FormatToCode error message: data type not supported yet!')
+
+	return code
+# }}}
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/convert2str.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/convert2str.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/convert2str.m	(revision 18231)
@@ -0,0 +1,130 @@
+function str = convert2str(field)
+
+	str = parsedisplay(field);
+
+end %function
+
+function str = parsedisplay(field) % {{{
+
+	%string
+	if ischar(field),
+
+		if length(field)>30;
+			%str = displayunit('not displayed');
+            str=field;
+		else
+			str = displayunit(['''' field '''']);
+		end
+
+	%cell
+    elseif iscell(field),
+		str = cell_display(field),
+
+    %structure
+	elseif isstruct(field),
+		str = struct_display(field),
+        
+	%numeric
+	elseif isnumeric(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%double
+		if max(fieldsize)==1,
+			str = displayunit(num2str(field)),
+			%matrix
+		else
+			str = displayunit(['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')']),
+        end
+        
+ 	%logical
+	elseif islogical(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%single value
+		if max(fieldsize)==1,
+			if (field)
+				str = displayunit('true');
+			else
+				str = displayunit('false');
+			end
+		%matrix
+		else
+			str = displayunit(name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')']);
+        end    
+        
+    %misc/
+    else
+        str = displayunit(field);
+
+    end
+
+end
+
+function str = displayunit(characterization)% {{{
+
+	%take care of characterization
+	if (strcmp(characterization,['''' '''']) || strcmp(characterization,'NaN')),
+		characterization='N/A';
+	end
+	if length(characterization)>15,
+		characterization=[characterization(1:12) '...'];
+    end
+    
+    str = characterization;
+	
+end% }}}
+
+function str = cell_display(field)
+
+	%initialization
+	string='{';
+
+	%go through the cell and fill string
+	if length(field)<5;
+		for i=1:length(field),
+			if ischar(field{i}),
+				string=[string ''''  field{i} ''','];
+			elseif (isnumeric(field{i}) & length(field{i})==1)
+				string=[string num2str(field{i}) ',' ];
+			else
+				string='{';
+				break
+			end
+		end
+	end
+	if strcmp(string,'{'),
+		string=['(' num2str(size(field,1)) 'x' num2str(size(field,2)) ')'];
+	else
+		string=[string(1:end-1) '}'];
+    end
+    str = string;
+    
+    %disp(sprintf(string));
+end
+
+function str = struct_display(field) % {{{
+
+	if ~isempty(fields(field))
+		displayunit('(structure)'),
+
+		structure_fields=fields(field);
+
+		for i=1:length(structure_fields),
+
+			%get current field
+			sfield=field.(structure_fields{i});
+
+			%display value
+			%parsedisplay(sfield);
+            str = sfield;
+		end
+
+	else
+		%displayunit('N/A'),
+        str = 'N/A';
+	end
+end% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/createxml.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/createxml.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/createxml.m	(revision 18231)
@@ -0,0 +1,42 @@
+function createxml(xmlfilename,md)
+%EXTRUDEXML - output an XML file compatible with inishell for automatic gui generation
+%
+%   The routine creates an XML file that list fields from the underlying classes 
+%   in model, and that can be use to render a GUI using the java code inishell
+%
+%   Usage:
+%      createxml(md,xmlfilename)
+
+disp(['creating XML file ' xmlfilename]);
+
+%open file for binary writing
+fid=fopen(xmlfilename,'w');
+if fid==-1,
+	error(['extrudexml error message: could not open ' xmlfilename,' file for ASCII writing']);
+end
+
+%Go through all model fields: check that it is a class and call checkconsistency
+fields=properties('model');
+fprintf(fid, '<inishell_config application="ISSM prototype">\n\n'); % require header for xml file
+for i=1:length(fields), 
+	field=fields{i};
+
+	%Some properties do not need to XML rendered
+	if ismember(field,{'results' 'radaroverlay' 'toolkits' 'private'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		error(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Create XML file for this subclass
+	createxml(md.(field),fid);
+end
+fprintf(fid, '\n\n</inishell_config>'); % require footer for xml file
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['createxml error message: could not close file ' xmlfilename]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadmultipleresultsfromcluster.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadmultipleresultsfromcluster.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadmultipleresultsfromcluster.m	(revision 18231)
@@ -0,0 +1,34 @@
+function md_list=loadmultipleresultsfromcluster(md_list)
+%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
+%
+%   Usage:
+%      md_list=loadresultsfromcluster(md_list);
+
+nummodels=length(md_list);
+
+%Get cluster settings
+cluster=md_list{1}.cluster;
+name=md_list{1}.name;
+cluster_rc_location=which('cluster.rc');
+[codepath,executionpath,login]=ClusterParameters(cluster,cluster_rc_location);
+
+%Remote tar: 
+disp('tarring results');
+issmssh(cluster,['"cd ' executionpath ' && rm -rf file_list.txt ModelResults.tar.gz && find -iname ''*_*vs*.outbin'' > file_list.txt && tar zcvf ModelResults.tar.gz --files-from file_list.txt  && rm -rf file_list.txt "']);
+
+%copy results from cluster to present directory
+scpin(cluster, executionpath, {'ModelResults.tar.gz'});
+
+%untar:
+!tar -zxvf ModelResults.tar.gz
+
+%ok, go through list and load results from disk: 
+for i=1:nummodels,
+	%load  results for this model
+	md_list{i}=loadresultsfromdisk(md_list{i},[md_list{i}.name '.outbin']);
+
+	delete([name '.outbin']);
+end
+
+%erase files 
+delete('ModelResults.tar.gz');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.m	(revision 18231)
@@ -0,0 +1,60 @@
+function md=loadresultsfromcluster(md,runtimename)
+%LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
+%
+%   Usage:
+%      md=loadresultsfromcluster(md,runtimename);
+
+%retrieve cluster, to be able to call its methods
+cluster=md.cluster;
+
+if nargin==2,
+	md.private.runtimename=runtimename;
+end
+
+%Download outputs from the cluster
+filelist={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+if md.qmu.isdakota,
+	filelist{end+1}=[md.miscellaneous.name '.qmu.err'];
+	filelist{end+1}=[md.miscellaneous.name '.qmu.out'];
+	if isfield(md.qmu.params,'tabular_graphics_data'),
+		if md.qmu.params.tabular_graphics_data==true,
+			filelist{end+1}='dakota_tabular.dat';
+		end
+	end
+else
+	filelist{end+1}=[md.miscellaneous.name '.outbin'];
+end
+Download(cluster,md.private.runtimename,filelist);
+
+%If we are here, no errors in the solution sequence, call loadresultsfromdisk.
+md=loadresultsfromdisk(md,[md.miscellaneous.name '.outbin']);
+
+%erase the log and output files
+if md.qmu.isdakota,
+	delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.outlog']);
+	delete([['qmu' num2str(feature('GetPid')) '/']  md.miscellaneous.name '.errlog']);
+else
+	delete([md.miscellaneous.name '.outlog']);
+	delete([md.miscellaneous.name '.errlog']);
+	delete([md.miscellaneous.name '.outbin']);
+	if ~ispc(),
+		delete([md.private.runtimename '.tar.gz']);
+	end
+end
+
+%erase input file if run was carried out on same platform.
+hostname=oshostname();
+if strcmpi(hostname,cluster.name),
+	if md.qmu.isdakota,
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.bin']);
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.queue']);
+	else
+		delete([md.miscellaneous.name '.bin']);
+		delete([md.miscellaneous.name '.toolkits']);
+		if ~ispc(),
+			delete([md.miscellaneous.name '.queue']);
+		else
+			delete([md.miscellaneous.name '.bat']);
+		end
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromcluster.py	(revision 18231)
@@ -0,0 +1,61 @@
+import os
+import socket
+import MatlabFuncs as m
+from loadresultsfromdisk import loadresultsfromdisk
+
+def loadresultsfromcluster(md,runtimename=False):
+	"""
+	LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
+ 
+	   Usage:
+	      md=loadresultsfromcluster(md,runtimename);
+	"""
+
+	#retrieve cluster, to be able to call its methods
+	cluster=md.cluster
+
+	if runtimename:
+		md.private.runtimename=runtimename
+
+	#Download outputs from the cluster
+	filelist=[md.miscellaneous.name+'.outlog',md.miscellaneous.name+'.errlog']
+	if md.qmu.isdakota:
+		filelist.append(md.miscellaneous.name+'.qmu.err')
+		filelist.append(md.miscellaneous.name+'.qmu.out')
+		if 'tabular_graphics_data' in md.qmu.params:
+			if md.qmu.params['tabular_graphics_data']:
+				filelist.append('dakota_tabular.dat')
+	else:
+		filelist.append(md.miscellaneous.name+'.outbin')
+	cluster.Download(md.private.runtimename,filelist)
+
+	#If we are here, no errors in the solution sequence, call loadresultsfromdisk.
+	md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
+
+	#erase the log and output files
+	if md.qmu.isdakota:
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.outlog'))
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.errlog'))
+	else:
+		os.remove(md.miscellaneous.name+'.outlog')
+		os.remove(md.miscellaneous.name+'.errlog')
+		os.remove(md.miscellaneous.name+'.outbin')
+		if not m.ispc():
+			os.remove(md.private.runtimename+'.tar.gz')
+
+	#erase input file if run was carried out on same platform.
+	hostname=socket.gethostname()
+	if m.strcmpi(hostname,cluster.name):
+		if md.qmu.isdakota:
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.bin'))
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.queue'))
+		else:
+			os.remove(md.miscellaneous.name+'.bin')
+			os.remove(md.miscellaneous.name+'.toolkits')
+			if not m.ispc():
+				os.remove(md.miscellaneous.name+'.queue')
+			else:
+				os.remove(md.miscellaneous.name+'.bat')
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.m	(revision 18231)
@@ -0,0 +1,60 @@
+function md=loadresultsfromdisk(md,filename)
+%LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+%
+%   Usage:
+%      md=loadresultsfromdisk(md,filename);
+
+%check number of inputs/outputs
+if ((nargin~=2) | (nargout~=1)),
+	help loadresultsfromdisk;
+	error('loadresultsfromdisk: error message.');
+end
+
+if ~md.qmu.isdakota,
+
+	%Check that file exists
+	if ~exist(filename,'file'),
+		error(['binary file ' filename ' not found.']);
+	end
+
+	%initialize md.results if not a structure yet
+	if ~isstruct(md.results),
+		md.results=struct();
+	end
+
+	%load results onto model
+	structure=parseresultsfromdisk(filename,~md.settings.io_gather);
+	if isempty(fieldnames(structure)),
+		error(['No result found in binary file ' filename '. Check for solution crash.']);
+	end
+	md.results.(structure(1).SolutionType)=structure;
+
+	%recover solution_type from results
+	md.private.solution=structure(1).SolutionType;
+
+	%read log files onto  fields
+	if exist([md.miscellaneous.name '.errlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).errlog=char(textread([md.miscellaneous.name '.errlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).errlog='';
+	end
+
+	if exist([md.miscellaneous.name '.outlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).outlog=char(textread([md.miscellaneous.name '.outlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).outlog='';
+	end
+
+	if ~isempty(md.results.(structure(1).SolutionType)(1).errlog),
+		disp(['loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields']);
+	end
+
+%post processes qmu results if necessary
+else
+
+	if isscalar(md.private.solution),
+		md.private.solution=EnumToString(md.private.solution);
+	end
+	md=postqmu(md);
+	cd ..
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/loadresultsfromdisk.py	(revision 18231)
@@ -0,0 +1,67 @@
+import os
+from results import results
+from parseresultsfromdisk import parseresultsfromdisk
+from EnumToString import EnumToString
+import MatlabFuncs as m
+
+def loadresultsfromdisk(md,filename):
+	"""
+	LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+ 
+	   Usage:
+	      md=loadresultsfromdisk(md=False,filename=False);
+	"""
+
+	#check number of inputs/outputs
+	if not md or not filename:
+		raise ValueError("loadresultsfromdisk: error message.")
+
+	if not md.qmu.isdakota:
+
+		#Check that file exists
+		if not os.path.exists(filename):
+			raise OSError("binary file '%s' not found." % filename)
+
+		#initialize md.results if not a structure yet
+		if not isinstance(md.results,results):
+			md.results=results()
+
+		#load results onto model
+		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)
+		setattr(md.results,structure[0].SolutionType,structure)
+
+		#recover solution_type from results
+		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:
+				setattr(getattr(md.results,structure[0].SolutionType)[0],'errlog',[line[:-1] for line in f])
+		else:
+			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:
+				setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[line[:-1] for line in f])
+		else:
+			setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[])
+
+		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 m.strcmp(structure[0].SolutionType,'TransientSolution'):
+			setattr(md.results,structure[0].SolutionType,structure[0])
+
+	#post processes qmu results if necessary
+	else:
+
+		if not isinstance(md.private.solution,(str,unicode)):
+			[md.private.solution]=EnumToString(md.private.solution)
+		md=postqmu(md)
+		os.chdir('..')
+
+	return md
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.m	(revision 18231)
@@ -0,0 +1,50 @@
+function marshall(md)
+%MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+%
+%   The routine creates a compatible binary file from @model md
+%   This binary file will be used for parallel runs in JPL-package
+%
+%   Usage:
+%      marshall(md)
+
+if md.verbose.solution,
+	disp(['marshalling file ' md.miscellaneous.name '.bin']);
+end
+
+%open file for binary writing
+fid=fopen([ md.miscellaneous.name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' [md.miscellaneous.name '.bin'],' file for binary writing']);
+end
+
+%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',true,'format','Boolean');
+
+%Go through all model fields: check that it is a class and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be marshalled
+	if ismember(field,{'results' 'radaroverlay' 'toolkits' 'cluster'  'flaim' 'private'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		error(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Marshall current object
+	%disp(['marshalling ' field '...']);
+	marshall(md.(field),md,fid);
+end
+
+%Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',true,'format','Boolean');
+
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' [md.miscellaneous.name '.bin']]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/marshall.py	(revision 18231)
@@ -0,0 +1,52 @@
+from WriteData import WriteData
+from EnumDefinitions import *
+
+def marshall(md):
+	"""
+	MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+
+	   The routine creates a compatible binary file from @model md
+	   This binary file will be used for parallel runs in JPL-package
+
+	   Usage:
+	      marshall(md)
+	"""
+
+	print "marshalling file '%s.bin'." % md.miscellaneous.name
+
+	#open file for binary writing
+	try:
+		fid=open(md.miscellaneous.name+'.bin','wb')
+	except IOError as e:
+		raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name)
+
+	#First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+	WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',True,'format','Boolean')
+
+	#Go through all model fields: check that it is a class and call checkconsistency
+	fields=vars(md)
+
+#	for field in fields.iterkeys():
+	for field in md.properties():
+
+		#Some properties do not need to be marshalled
+		if field in ['results','radaroverlay','toolkits','cluster','flaim','private']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'marshall'):
+			raise TypeError("field '%s' is not an object." % field)
+
+		#Marshall current object
+		#print "marshalling %s ..." % field
+		exec("md.%s.marshall(md,fid)" % field)
+
+	#Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
+	WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',True,'format','Boolean');
+
+	#close file
+	try:
+		fid.close()
+	except IOError as e:
+		raise IOError("marshall error message: could not close file '%s.bin'." % md.miscellaneous.name)
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.m	(revision 18231)
@@ -0,0 +1,233 @@
+function results=parseresultsfromdisk(filename,iosplit)
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdisk(filename,iosplit)
+
+if iosplit,
+	results=parseresultsfromdiskiosplit(filename);
+else
+	results=parseresultsfromdiskioserial(filename);
+end
+
+
+function results=parseresultsfromdiskioserial(filename) % {{{
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskioserial(filename)
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%Read fields until the end of the file.
+result  = ReadData(fid);
+if isempty(result), error(['no results found in binary file ' filename]); end
+counter = 1;
+step    = result.step;
+while ~isempty(result), 
+
+	%Check step, increase counter if this is a new step
+	if(step~=result.step & result.step>1)
+		counter = counter + 1;
+		step    = result.step;
+	end
+
+	%Add result
+	if(result.step==1),
+		index = 1;
+	else
+		index = counter;
+	end
+	results(index).step=result.step;
+	if result.time~=-9999,
+		results(index).time=result.time; 
+	end
+	results(index).(result.fieldname)=result.field;
+
+	%read next result
+	try,
+		result  = ReadData(fid);
+	catch me,
+		disp('WARNING: file corrupted, trying partial recovery');
+		result=[];
+	end
+
+end
+
+fclose(fid);
+% }}}
+function results=parseresultsfromdiskiosplit(filename) % {{{
+%PARSERESULTSFROMDISKIOSPLIT - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskiosplit(filename)
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%if we have done split I/O, ie, we have results that are fragmented across patches, 
+%do a first pass, and figure out the structure of results
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	if result.time~=-9999,
+		results(result.step).time=result.time; 
+	end
+
+	%Add result
+	results(result.step).(result.fieldname)=NaN;
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%do a second pass, and figure out the size of the patches
+fseek(fid,0,-1); %rewind
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%third pass, this time to read the real information
+fseek(fid,0,-1); %rewind
+result=ReadData(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	if result.time~=-9999,
+		results(result.step).time=result.time; 
+	end
+
+	%Add result
+	results(result.step).(result.fieldname)=result.field;
+
+	%read next result
+	try,
+		result=ReadData(fid);
+	catch me,
+		disp('WARNING: file corrupted, results partial recovery');
+		result=[];
+	end
+
+end
+
+%close file
+fclose(fid);
+	% }}}
+function result=ReadData(fid) % {{{
+%READDATA - ...
+%
+%   Usage:
+%      field=ReadData(fid)
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	if type==1,
+		field=fread(fid,M,'double');
+	elseif type==2,
+		field=fread(fid,M,'char');
+		field=char(field(1:end-1)');
+	elseif type==3,
+		N=fread(fid,1,'int');
+		field=transpose(fread(fid,[N M],'double'));
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	%Process units here FIXME: this should not be done here!
+	yts=365.0*24.0*3600.0;
+	if strcmp(fieldname,'BalancethicknessThickeningRate'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Time'),
+		field = field/yts;
+	elseif strcmp(fieldname,'HydrologyWaterVx'),
+		field = field*yts;
+	elseif strcmp(fieldname,'HydrologyWaterVy'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vx'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vy'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vz'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vel'),
+		field = field*yts;
+	elseif strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'),
+		field = field*yts;
+	elseif strcmp(fieldname,'TotalSmb'),
+		field = field/10.^12*yts; %(GigaTon/year)
+	elseif strcmp(fieldname,'SurfaceforcingsMassBalance'),
+		field = field*yts;
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.field=field;
+
+end
+% }}}
+function result=ReadDataDimensions(fid) % {{{
+%READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+%
+%   Usage:
+%      field=ReadDataDimensions(fid)
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	N=1; %default
+	if type==1,
+		fseek(fid,M*8,0);
+	elseif type==2,
+		fseek(fid,M,0);
+	elseif type==3,
+		N=fread(fid,1,'int');
+		fseek(fid,N*M*8,0);
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.M=M;
+	result.N=N;
+end
+% }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/parseresultsfromdisk.py	(revision 18231)
@@ -0,0 +1,238 @@
+import struct
+import numpy
+from collections import OrderedDict
+import results as resultsclass
+import MatlabFuncs as m
+
+def parseresultsfromdisk(filename,iosplit):
+	"""
+	PARSERESULTSFROMDISK - ...
+
+	   Usage:
+	      results=parseresultsfromdisk(filename,iosplit)
+	"""
+
+	if iosplit:
+		results=parseresultsfromdiskiosplit(filename)
+	else:
+		results=parseresultsfromdiskioserial(filename)
+
+	return results
+
+def parseresultsfromdiskioserial(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISK - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskioserial(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results=[]
+
+	#Read fields until the end of the file.
+	result=ReadData(fid)
+	while result:
+		if   result['step'] > len(results):
+			for i in xrange(len(results),result['step']-1):
+				results.append(None)
+			results.append(resultsclass.results())
+		elif results[result['step']-1] is None:
+			results[result['step']-1]=resultsclass.results()
+		#Get time and step
+		setattr(results[result['step']-1],'step',result['step'])
+		setattr(results[result['step']-1],'time',result['time']) 
+	
+		#Add result
+		if hasattr(results[result['step']-1],result['fieldname']) and not m.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
+		result=ReadData(fid)
+
+	fid.close()
+
+	return results
+	# }}}
+def parseresultsfromdiskiosplit(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISKIOSPLIT - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskiosplit(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results=[]
+
+	#if we have done split I/O, ie, we have results that are fragmented across patches, 
+	#do a first pass, and figure out the structure of results
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#Get time and step
+		if 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
+		setattr(results[result['step']-1],result['fieldname'],float('NaN'))
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#do a second pass, and figure out the size of the patches
+	fid.seek(0)    #rewind
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#third pass, this time to read the real information
+	fid.seek(0)    #rewind
+	result=ReadData(fid)
+	while result:
+
+		#Get time and step
+		if result['step']> 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
+		setattr(results[result['step']-1],result['fieldname'],result['field'])
+
+		#read next result
+		result=ReadData(fid)
+
+	#close file
+	fid.close()
+
+	return results
+	# }}}
+def ReadData(fid):    # {{{
+	"""
+	READDATA - ...
+	 
+	    Usage:
+	       field=ReadData(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		if   type==1:
+			field=numpy.array(struct.unpack('%dd' % M,fid.read(M*struct.calcsize('d'))),dtype=float)
+		elif type==2:
+			field=struct.unpack('%ds' % M,fid.read(M))[0][:-1]
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+#			field=transpose(fread(fid,[N M],'double'));
+			field=numpy.zeros(shape=(M,N),dtype=float)
+			for i in xrange(M):
+				field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d')))
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		#Process units here FIXME: this should not be done here!
+		yts=365.0*24.0*3600.0
+		if m.strcmp(fieldname,'BalancethicknessThickeningRate'):
+			field = field*yts
+		elif m.strcmp(fieldname,'Time'):
+			field = field/yts
+		elif m.strcmp(fieldname,'HydrologyWaterVx'):
+			field = field*yts
+		elif m.strcmp(fieldname,'HydrologyWaterVy'):
+			field = field*yts
+		elif m.strcmp(fieldname,'Vx'):
+			field = field*yts
+		elif m.strcmp(fieldname,'Vy'):
+			field = field*yts
+		elif m.strcmp(fieldname,'Vz'):
+			field = field*yts
+		elif m.strcmp(fieldname,'Vel'):
+			field = field*yts
+		elif m.strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'):
+			field = field*yts
+		elif m.strcmp(fieldname,'TotalSmb'):
+			field = field/10.**12.*yts #(GigaTon/year)
+		elif m.strcmp(fieldname,'SurfaceforcingsMassBalance'):
+			field = field*yts
+
+		result=OrderedDict()
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['field']=field
+
+	except struct.error as e:
+		result=None
+
+	return result
+	# }}}
+def ReadDataDimensions(fid):    # {{{
+	"""
+	READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+	 
+	    Usage:
+	       field=ReadDataDimensions(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		N=1    #default
+		if   type==1:
+			fid.seek(M*8,1)
+		elif type==2:
+			fid.seek(M,1)
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+			fid.seek(N*M*8,1)
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		result=OrderedDict()
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['M']=M
+		result['N']=N
+
+	except struct.error as e:
+		result=None
+
+	return result
+	# }}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.m	(revision 18231)
@@ -0,0 +1,141 @@
+function md=solve(md,solutionenum,varargin)
+%SOLVE - apply solution sequence for this model
+%
+%   Usage:
+%      md=solve(md,solutionenum,varargin)
+%      where varargin is a lit of paired arguments of string OR enums
+%
+%   solution types available comprise:
+%		 - StressbalanceSolutionEnum
+%		 - MasstransportSolutionEnum
+%		 - ThermalSolutionEnum
+%		 - SteadystateSolutionEnum
+%		 - TransientSolutionEnum
+%		 - BalancethicknessSolutionEnum
+%		 - BedSlopeSolutionEnum
+%		 - SurfaceSlopeSolutionEnum
+%		 - HydrologySolutionEnum
+%		 - FlaimSolutionEnum
+%
+%  extra options:
+%      - loadonly    : does not solve. only load results
+%      - runtimename : true or false (default is true), makes name unique
+%      - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
+%
+%   Examples:
+%      md=solve(md,StressbalanceSolutionEnum);
+
+%recover and process solve options
+if ~strncmp(fliplr(EnumToString(solutionenum)),fliplr('Solution'),8),
+	error(['solutionenum ' EnumToString(solutionenum) ' not supported!']);
+end
+options=pairoptions(varargin{:},'solutionenum',solutionenum);
+
+%recover some fields
+md.private.solution=solutionenum;
+cluster=md.cluster;
+
+%check model consistency
+if strcmpi(getfieldvalue(options,'checkconsistency','yes'),'yes'),
+	if md.verbose.solution,
+		disp('checking model consistency');
+	end
+	if (solutionenum == FlaimSolutionEnum())
+		md.private.isconsistent=true;
+		md=checkconsistency(md.mesh,md,solutionenum);
+		md=checkconsistency(md.flaim,md,solutionenum);
+		if md.private.isconsistent==false,
+			error('Model not consistent, see messages above');
+		end
+	else
+		ismodelselfconsistent(md),
+	end
+end
+
+%First, build a runtime name that is unique
+if getfieldvalue(options,'runtimename',true),
+	c=clock;
+	md.private.runtimename=sprintf('%s-%02i-%02i-%04i-%02i-%02i-%02i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
+else
+	md.private.runtimename=md.miscellaneous.name;
+end
+
+%if running qmu analysis, some preprocessing of dakota files using models
+%fields needs to be carried out. 
+if md.qmu.isdakota,
+	md=preqmu(md,options);
+end
+
+%flaim analysis (To be removed?)
+if (solutionenum == FlaimSolutionEnum())
+	%fmdir     = getfieldvalue(options,'fmdir',['fm' num2str(feature('GetPid'))]);
+	%overwrite = getfieldvalue(options,'overwrite','n');
+	%keep      = getfieldvalue(options,'keep','y');
+	%latsgn    = getfieldvalue(options,'latsgn',0);
+	%cmap      = getfieldvalue(options,'cmap',[]);
+	md=flaim_sol(md,options);
+	md.private.solution=EnumToString(solutionenum);
+	return;
+end
+
+%Do we load results only?
+if getfieldvalue(options,'loadonly',false),
+	md=loadresultsfromcluster(md);
+	return;
+end
+
+%Write all input files
+marshall(md);                                          % bin file
+ToolkitsFile(md.toolkits,[md.miscellaneous.name '.toolkits']); % toolkits file
+BuildQueueScript(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof); % queue file
+
+%Stop here if batch mode
+if strcmpi(getfieldvalue(options,'batch','no'),'yes')
+	if md.verbose.solution,
+		disp('batch mode requested: not launching job interactively');
+		disp('launch solution sequence on remote cluster by hand');
+	end
+	return;
+end
+
+%Launch job
+modelname = md.miscellaneous.name;
+filelist  = {[modelname '.bin '] [modelname '.toolkits ']};
+if ispc,
+	filelist{end+1}=[modelname '.bat '];
+else
+	filelist{end+1}=[modelname '.queue '];
+end
+
+if md.qmu.isdakota,
+	filelist{end+1} = [modelname '.qmu.in'];
+end
+LaunchQueueJob(cluster,md.miscellaneous.name,md.private.runtimename,filelist);
+
+%wait on lock
+if isnan(md.settings.waitonlock),
+	%load when user enters 'y'
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+	else
+		md=loadresultsfromcluster(md);
+	end
+elseif md.settings.waitonlock>0,
+	%we wait for the done file
+	done=waitonlock(md);
+	if md.verbose.solution,
+		disp('loading results from cluster');
+	end
+	md=loadresultsfromcluster(md);
+elseif md.settings.waitonlock==0,
+	 disp('Model results must be loaded manually with md=loadresultsfromcluster(md);');
+end
+
+%post processes qmu results if necessary
+if md.qmu.isdakota,
+	if ~strncmpi(getfieldvalue(options,'keep','y'),'y',1)
+		system(['rm -rf qmu' num2str(feature('GetPid'))]);
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/solve.py	(revision 18231)
@@ -0,0 +1,115 @@
+import datetime
+import os
+import shutil
+from pairoptions import pairoptions
+from EnumDefinitions import *
+from EnumToString import EnumToString
+from ismodelselfconsistent import ismodelselfconsistent
+from marshall import marshall
+from waitonlock import waitonlock
+from loadresultsfromcluster import loadresultsfromcluster
+import MatlabFuncs as m
+
+def solve(md,solutionenum,*args):
+	"""
+	SOLVE - apply solution sequence for this model
+ 
+	   Usage:
+	      md=solve(md,solutionenum,varargin)
+	      where varargin is a list of paired arguments of string OR enums
+ 
+	   solution types available comprise:
+	      - StressbalanceSolutionEnum
+	      - MasstransportSolutionEnum
+	      - ThermalSolutionEnum
+	      - SteadystateSolutionEnum
+	      - TransientSolutionEnum
+	      - BalancethicknessSolutionEnum
+	      - BedSlopeSolutionEnum
+	      - SurfaceSlopeSolutionEnum
+	      - HydrologySolutionEnum
+	      - FlaimSolutionEnum
+ 
+	   extra options:
+	      - loadonly : does not solve. only load results
+		  - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
+ 
+	   Examples:
+	      md=solve(md,StressbalanceSolutionEnum);
+	"""
+
+	#recover and process solve options
+	if EnumToString(solutionenum)[0][-8:] != 'Solution':
+		raise ValueError("solutionenum '%s' not supported!" % EnumToString(solutionenum)[0])
+	options=pairoptions('solutionenum',solutionenum,*args)
+
+	#recover some fields
+	md.private.solution=solutionenum
+	cluster=md.cluster
+
+	#check model consistency
+	if m.strcmpi(options.getfieldvalue('checkconsistency','yes'),'yes'):
+		print "checking model consistency"
+		if solutionenum == FlaimSolutionEnum():
+			md.private.isconsistent=True
+			md.mesh.checkconsistency(md,solutionenum)
+			md.flaim.checkconsistency(md,solutionenum)
+			if not md.private.isconsistent:
+				raise RuntimeError("Model not consistent, see messages above.")
+		else:
+			ismodelselfconsistent(md)
+
+	#First, build a runtime name that is unique
+	c=datetime.datetime.now()
+	md.private.runtimename="%s-%02i-%02i-%04i-%02i-%02i-%02i-%i" % (md.miscellaneous.name,c.month,c.day,c.year,c.hour,c.minute,c.second,os.getpid())
+
+	#if running qmu analysis, some preprocessing of dakota files using models
+	#fields needs to be carried out. 
+	if md.qmu.isdakota:
+		md=preqmu(md,options)
+
+	#flaim analysis
+	if solutionenum == FlaimSolutionEnum():
+		md=flaim_sol(md,options)
+		[md.private.solution]=EnumToString(solutionenum)
+		return md
+
+	#Do we load results only?
+	if options.getfieldvalue('loadonly',False):
+		md=loadresultsfromcluster(md)
+		return md
+
+	#Write all input files
+	marshall(md)                                           # bin file
+	md.toolkits.ToolkitsFile(md.miscellaneous.name+'.toolkits')    # toolkits file
+	cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof)    # queue file
+
+	#Stop here if batch mode
+	if m.strcmpi(options.getfieldvalue('batch','no'),'yes'):
+		print 'batch mode requested: not launching job interactively'
+		print 'launch solution sequence on remote cluster by hand'
+		return md
+
+	#Launch job
+	modelname = md.miscellaneous.name
+	filelist  = [modelname+'.bin ',modelname+'.toolkits ',modelname+'.queue ']
+	if md.qmu.isdakota:
+		filelist.append(modelname+'.qmu.in')
+	cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist)
+
+	#wait on lock
+	if md.settings.waitonlock>0:
+		#we wait for the done file
+		islock=waitonlock(md)
+		if islock==0:    #no results to be loaded
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+		else:            #load results
+			print 'loading results from cluster'
+			md=loadresultsfromcluster(md)
+
+	#post processes qmu results if necessary
+	if md.qmu.isdakota:
+		if not strncmpi(options['keep'],'y',1):
+			shutil.rmtree('qmu'+str(os.getpid()))
+
+	return md
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.m	(revision 18231)
@@ -0,0 +1,77 @@
+function ispresent=waitonlock(md)
+%WAITONLOCK - wait for a file
+%
+%   This routine will return when a file named 'lockfilename' is written to disk.
+%   Also check for outlog file be cause it might bewritten several seconds
+%   after the lock file.
+%   If the time limit given in input is exceeded, return 0
+%
+%   Usage:
+%      flag=waitonlock(md)
+
+%Return if waitonlock < 0 (no need to wait)
+
+%Get lockfilename (lock file) and options
+executionpath = md.cluster.executionpath;
+timelimit     = md.settings.waitonlock;
+cluster       = md.cluster;
+
+if isa(cluster,'pfe') && cluster.interactive>0
+	lockfilename  = [executionpath '/Interactive' num2str(cluster.interactive) '/' md.miscellaneous.name '.lock'];
+	logfilename   = [executionpath '/Interactive' num2str(cluster.interactive) '/' md.miscellaneous.name '.outlog'];
+else
+	lockfilename  = [executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
+	logfilename   = [executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.outlog'];
+end
+
+
+%If we are using the generic cluster in interactive mode, job is already complete
+if isa(cluster,'generic') & cluster.interactive
+	%We are in interactive mode, no need to check for job completion
+	ispresent=1;
+	return;
+end
+
+%initialize time and file presence test flag
+time=0; ispresent=0; time0=clock;
+disp(['waiting for ' lockfilename ' hold on... (Ctrl+C to exit)'])
+
+%prepare command if the job is not running on the local machine
+if ~strcmpi(oshostname(),cluster.name),
+	login = cluster.login;
+	port  = 0;
+	if isprop(cluster,'port') 
+		port = cluster.port;
+	end
+	if port,
+		command = ['ssh -l ' login ' -p ' num2str(port) ' localhost "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
+	elseif isa(cluster,'cloud')
+		command = [' [ -f ' lockfilename ' ] && [ -f ' logfilename ' ] 2>/dev/null'];
+		command = [starcluster() ' sshmaster ' cluster.name ' --user ' cluster.login ' ''' command ''''];
+	else
+		command = ['ssh -l ' login ' ' cluster.name ' "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
+	end
+end
+
+%loop till file .lock exist or time is up
+while (ispresent==0 & time<timelimit)
+	if strcmpi(oshostname(),cluster.name),
+		pause(1);
+		ispresent=(exist(lockfilename,'file') & exist(logfilename,'file'));
+		time=etime(clock,time0)/60;
+	else
+		pause(5);
+		time=etime(clock,time0);
+		fprintf('\rchecking for job completion (time: %i min %i sec)      ',floor(time/60),floor(rem(time,60)));
+		time=time/60; %converts time from sec to min
+		ispresent=~system(command);
+		if ispresent, fprintf('\n'); end
+	end
+end
+
+%build output
+if (time>timelimit),
+	disp('Time limit exceeded. Increase md.settings.waitonlock');
+	disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+	error(['waitonlock error message: time limit exceeded']);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solve/waitonlock.py	(revision 18231)
@@ -0,0 +1,64 @@
+import os
+from socket import gethostname
+import time
+import MatlabFuncs as m
+
+def waitonlock(md):
+	"""
+	WAITONLOCK - wait for a file
+ 
+	   This routine will return when a file named 'filename' is written to disk.
+	   If the time limit given in input is exceeded, return 0
+ 
+	   Usage:
+	      flag=waitonlock(md)
+	"""
+
+	#Get filename (lock file) and options
+	executionpath=md.cluster.executionpath
+	cluster=md.cluster.name
+	login=md.cluster.login
+	port=md.cluster.port
+	timelimit=md.settings.waitonlock
+	filename=os.path.join(executionpath,md.private.runtimename,md.miscellaneous.name+'.lock')
+
+	#waitonlock will work if the lock is on the same machine only: 
+	if not m.strcmpi(gethostname(),cluster):
+
+		print 'solution launched on remote cluster. log in to detect job completion.'
+		choice=raw_input('Is the job successfully completed? (y/n) ')
+		if not m.strcmp(choice,'y'): 
+			print 'Results not loaded... exiting' 
+			flag=0
+		else:
+			flag=1
+
+	#job is running on the same machine
+	else:
+
+		if 'interactive' in vars(md.cluster) and md.cluster.interactive:
+			#We are in interactive mode, no need to check for job completion
+			flag=1
+			return flag
+		#initialize time and file presence test flag
+		etime=0
+		ispresent=0
+		print "waiting for '%s' hold on... (Ctrl+C to exit)" % filename
+
+		#loop till file .lock exist or time is up
+		while ispresent==0 and etime<timelimit:
+			ispresent=os.path.exist(filename)
+			time.sleep(1)
+			etime+=1/60
+
+		#build output
+		if etime>timelimit:
+			print 'Time limit exceeded. Increase md.settings.waitonlock'
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+			raise RuntimeError('waitonlock error message: time limit exceeded.')
+			flag=0
+		else:
+			flag=1
+
+	return flag
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.m	(revision 18231)
@@ -0,0 +1,19 @@
+function asm=asmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method petsc options
+%
+%   Usage:
+%      options=asmoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+asm=struct();
+
+%default asm options
+asm.toolkit='petsc';
+asm.mat_type=getfieldvalue(options,'mat_type','aij');
+asm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+asm.pc_type=getfieldvalue(options,'pc_type','asm');
+asm.sub_pc_type=getfieldvalue(options,'sub_pc_type','lu');
+asm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+asm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+asm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-30);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/asmoptions.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def asmoptions(*args):
+	#ASMOPTIONS - return ASM petsc options
+	#
+	#   Usage:
+	#      options=asmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsljacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsljacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsljacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsljacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgslsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgslsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgsl');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgsmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgsmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgspbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgspbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgspbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgspbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgssoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgssoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bcgssoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bcgssoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicggamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicggasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicggasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicghypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicghypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicghypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicghypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/bicgsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=bicgsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','bicg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cggamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cggasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cggasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cghypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cghypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cghypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cghypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgneasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgneasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgneasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgneasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnebjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnebjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnebjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnebjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnegamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnegasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnegasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnehypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnehypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnehypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnehypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnejacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnejacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnejacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnejacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnemgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnemgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnemgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnemgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnepbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnepbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnepbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnepbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnesoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnesoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgnesoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgnesoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgne');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgspbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgspbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgspbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgspbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgssoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgssoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/cgssoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=cgssoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/conditionnumberoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/conditionnumberoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/conditionnumberoptions.m	(revision 18231)
@@ -0,0 +1,22 @@
+function cn=conditionnumberoptions(varargin)
+%MULTIGRIDOPTIONS - use Multigrid 
+%
+%   Usage:
+%      options=mgoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+cn=struct();
+cn..toolkit='petsc';
+
+%default  options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+	cn.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	cn.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+	cn.pc_type=getfieldvalue(options,'pc_type','none');
+	cn.ksp_monitor_singular_value=getfieldvalue(options,'ksp_monitor_singular_value','');
+	cn.ksp_gmres_restart=getfieldvalue(options,'ksp_gmres_restart',1000);
+	cn.info=getfieldvalue(options,'info','');
+	cn.log_summary=getfieldvalue(options,'log_summary','');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/crsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=crsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','cr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmreshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmreshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmreshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmreshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmresmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmresmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmrespbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmrespbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmrespbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmrespbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmressoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmressoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/dgmressoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=dgmressoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','dgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmreshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmreshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmreshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmreshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmresmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmresmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmrespbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmrespbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmrespbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmrespbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmressoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmressoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/fgmressoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=fgmressoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','fgmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_');
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gcrsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gcrsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gcr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gltrsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gltrsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gltr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmreshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmreshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmreshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmreshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_');
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmresmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmresmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmrespbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmrespbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmrespbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmrespbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmressoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmressoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/gmressoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=gmressoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','gmres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgsmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgsmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgspbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgspbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgspbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgspbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgssoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgssoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/ibcgssoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=ibcgssoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','ibcgs');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.m	(revision 18231)
@@ -0,0 +1,19 @@
+function iluasm=iluasmoptions(varargin)
+%ILUASMOPTIONS - 
+%
+%   Usage:
+%      options=iluasmoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+iluasm=struct();
+
+%default iluasm options
+iluasm.toolkit='petsc';
+iluasm.mat_type=getfieldvalue(options,'mat_type','aij');
+iluasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+iluasm.pc_type=getfieldvalue(options,'pc_type','asm');
+iluasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','ilu');
+iluasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',5);
+iluasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+iluasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/iluasmoptions.py	(revision 18231)
@@ -0,0 +1,27 @@
+from collections import OrderedDict
+import pairoptions
+
+def iluasmoptions(*args):
+	"""
+	ILUASMOPTIONS - 
+
+	   Usage:
+	      options=iluasmoptions;
+	"""
+			 
+	#retrieve options provided in varargin
+	options=pairoptions.pairoptions(*args)
+	iluasm=OrderedDict()
+
+	#default iluasm options
+	iluasm['toolkit']='petsc'
+	iluasm['mat_type']=options.getfieldvalue('mat_type','aij')
+	iluasm['ksp_type']=options.getfieldvalue('ksp_type','gmres')
+	iluasm['pc_type']=options.getfieldvalue('pc_type','asm')
+	iluasm['sub_pc_type']=options.getfieldvalue('sub_pc_type','ilu')
+	iluasm['pc_asm_overlap']=options.getfieldvalue('pc_asm_overlap',5)
+	iluasm['ksp_max_it']=options.getfieldvalue('ksp_max_it',100)
+	iluasm['ksp_rtol']=options.getfieldvalue('ksp_rtol',1e-15)
+
+	return iluasm
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.m	(revision 18231)
@@ -0,0 +1,15 @@
+function issmoptions=issmgslsolver(varargin)
+%ISSMSOLVER - 
+%
+%   Usage:
+%      options=issmsolver;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+issmoptions=struct();
+
+%default issmoptions options
+issmoptions.toolkit='issm';
+issmoptions.mat_type=getfieldvalue(options,'mat_type','dense');
+issmoptions.vec_type=getfieldvalue(options,'vec_type','seq');
+issmoptions.solver_type=getfieldvalue(options,'solver_type','gsl');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmgslsolver.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def issmgslsolver(*args):
+	#ISSMSOLVE - return issm solver options
+	#
+	#   Usage:
+	#      options=issmsolver;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','issm'],['mat_type','dense'],['vec_type','seq'],['solver_type','gsl']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.m	(revision 18231)
@@ -0,0 +1,15 @@
+function issmoptions=issmmumpssolver(varargin)
+%ISSMSOLVER - 
+%
+%   Usage:
+%      options=issmsolver;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+issmoptions=struct();
+
+%default issmoptions options
+issmoptions.toolkit='issm';
+issmoptions.mat_type=getfieldvalue(options,'mat_type','mpisparse');
+issmoptions.vec_type=getfieldvalue(options,'vec_type','mpi');
+issmoptions.solver_type=getfieldvalue(options,'solver_type','mumps');
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/issmmumpssolver.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def issmmumpssolver(*args):
+	#ISSMSOLVE - return issm solver options
+	#
+	#   Usage:
+	#      options=issmsolver;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi'],['solver_type','mumps']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.m	(revision 18231)
@@ -0,0 +1,19 @@
+function jacobiasm=jacobiasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobiasm=struct();
+
+%default jacobiasm options
+jacobiasm.toolkit='petsc';
+jacobiasm.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobiasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+jacobiasm.pc_type=getfieldvalue(options,'pc_type','asm');
+jacobiasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','jacobi');
+jacobiasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+jacobiasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobiasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobiasmoptions.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def jacobiasmoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobiasmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.m	(revision 18231)
@@ -0,0 +1,16 @@
+function jacobicg=jacobiacgoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobicg=struct();
+
+%default jacobiasm options
+jacobicg.toolkit='petsc';
+jacobicg.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobicg.ksp_type=getfieldvalue(options,'ksp_type','cg');
+jacobicg.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobicg.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/jacobicgoptions.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions 
+
+def jacobicgoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobicgoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lcdsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lcdsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lcd');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/lsqrsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=lsqrsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','lsqr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.m	(revision 18231)
@@ -0,0 +1,13 @@
+function maltab=matlaboptions(varargin)
+%MATLABOPTIONS - return Matlab petsc options
+%
+%   Usage:
+%      options=matlaboptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+maltab=struct();
+
+%default matlab options
+maltab.toolkit='petsc';
+maltab.ksp_type='matlab';
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/matlaboptions.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def matlaboptions(*args):
+	#MATLABOPTIONS - return Matlab petsc options
+	#
+	#   Usage:
+	#      options=matlaboptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','petsc'],['ksp_type','matlab']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minreshypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minreshypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minreshypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minreshypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minresmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minresmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minrespbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minrespbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minrespbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minrespbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minressoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minressoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/minressoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=minressoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','minres');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.m	(revision 18231)
@@ -0,0 +1,31 @@
+function mumps=mumpsoptions(varargin)
+%MUMPSOPTIONS - return MUMPS direct solver  petsc options
+%
+%   Usage:
+%      options=mumpsoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+mumps=struct();
+
+%default mumps options
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_');
+if PETSC_VERSION==2.,
+	mumps.toolkit='petsc';
+	mumps.mat_type=getfieldvalue(options,'mat_type','aijmumps');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+end
+if PETSC_VERSION==3.,
+	mumps.toolkit='petsc';
+	mumps.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.pc_factor_mat_solver_package=getfieldvalue(options,'pc_factor_mat_solver_package','mumps');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+	mumps.mat_mumps_icntl_28=2; %1=serial, 2=parallel
+	mumps.mat_mumps_icntl_29=2; %parallel ordering 1 = ptscotch, 2 = parmetis
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/mumpsoptions.py	(revision 18231)
@@ -0,0 +1,36 @@
+from collections import OrderedDict
+import pairoptions
+from IssmConfig import IssmConfig
+
+def mumpsoptions(*args):
+	"""
+	MUMPSOPTIONS - return MUMPS direct solver  petsc options
+
+	   Usage:
+	      options=mumpsoptions;
+	"""
+
+	#retrieve options provided in varargin
+	options=pairoptions.pairoptions(*args)
+	mumps=OrderedDict()
+
+	#default mumps options
+	PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0]
+	if PETSC_VERSION==2.:
+		mumps['toolkit']='petsc'
+		mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+	if PETSC_VERSION==3.:
+		mumps['toolkit']='petsc'
+		mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+
+	return mumps
+
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsongamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsongasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsongasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/richardsonsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=richardsonsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','richardson');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.m	(revision 18231)
@@ -0,0 +1,17 @@
+function sor=soroptions(varargin)
+%SOROPTIONS - return Relaxation Solver petsc options
+%
+%   Usage:
+%      options=soroptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+sor=struct();
+
+%default sor options
+sor.toolkit='petsc';
+sor.mat_type=getfieldvalue(options,'mat_type','aij');
+sor.ksp_type=getfieldvalue(options,'ksp_type','cg');
+sor.pc_type=getfieldvalue(options,'pc_type','sor');
+sor.pc_sor_omega=getfieldvalue(options,'pc_sor_omega',1.1);
+sor.pc_sor_its=getfieldvalue(options,'pc_sor_its',2);
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/soroptions.py	(revision 18231)
@@ -0,0 +1,29 @@
+import pairoptions
+
+def soroptions(*args):
+	#SOROPTIONS - return Relaxation Solver petsc options
+	#
+	#   Usage:
+	#      options=soroptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+	
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcggamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcggasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcggasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcghypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcghypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcghypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcghypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stcgsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=stcgsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','stcg');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.m	(revision 18231)
@@ -0,0 +1,29 @@
+function stokes=stokesoptions(varargin)
+%STOKESOPTIONS - return STOKES multi-physics solver petsc options
+%
+%   Usage:
+%      options=stokesoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+stokes=struct();
+
+%default stokes options
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0];
+if PETSC_VERSION==2.,
+	error('stokesoptions error message: multi-physics options not supported in Petsc 2');
+end
+if PETSC_VERSION==3.,
+	stokes.toolkit='petsc';
+	stokes.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	stokes.ksp_max_it=getfieldvalue(options,'ksp_max_it',1000);
+	stokes.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+	stokes.pc_type=getfieldvalue(options,'pc_type','fieldsplit');
+	stokes.pc_field_split_type=getfieldvalue(options,'pc_field_split_type','schur');
+	stokes.fieldsplit_0_pc_type=getfieldvalue(options,'fieldsplit_0_pc_type','hypre');
+	stokes.fieldsplit_0_ksp_type=getfieldvalue(options,'fieldsplit_0_ksp_type','gmres');
+	stokes.fieldsplit_0_pc_hypre_type=getfieldvalue(options,'fieldsplit_0_pc_hypre_type','boomerang');
+	stokes.fieldsplit_1_pc_type=getfieldvalue(options,'fieldsplit_1_pc_type','jacobi');
+	stokes.fieldsplit_1_ksp_type=getfieldvalue(options,'fieldsplit_1_ksp_type','preonly');
+	stokes.issm_option_solver=getfieldvalue(options,'issm_option_solver','stokes');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/stokesoptions.py	(revision 18231)
@@ -0,0 +1,39 @@
+import pairoptions
+from IssmConfig import IssmConfig
+
+def stokesoptions(*args):
+	#STOKESOPTIONS - return STOKES multi-physics solver petsc options
+	#
+	#   Usage:
+	#      options=stokesoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions.pairoptions(*args) 
+
+
+	#default stokes options
+	PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0]
+
+	if PETSC_VERSION==2.:
+		raise RuntimeError('stokesoptions error message: multi-physics options not supported in Petsc 2')
+	if PETSC_VERSION==3.:
+		options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_max_it',1000],['ksp_type','gmres'],['pc_type','fieldsplit'],['pc_field_split_type','schur'],\
+	['fieldsplit_0_pc_type','hypre'],['fieldsplit_0_ksp_type','gmres'],['fieldsplit_0_pc_hypre_type','boomerang'],\
+	['fieldsplit_1_pc_type','jacobi'],['fieldsplit_1_ksp_type','preonly'],['issm_option_solver','stokes']]
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/symmlqsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=symmlqsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','symmlq');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'asm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'bjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgamgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgamgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgamgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrgamgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gamg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgasmoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgasmoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrgasmoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrgasmoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'gasm');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrhypreoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrhypreoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrhypreoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrhypreoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'hypre');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'jacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrmgoptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrmgoptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrmgoptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrmgoptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'mg');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrpbjacobioptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrpbjacobioptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrpbjacobioptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrpbjacobioptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'pbjacobi');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrsoroptions.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrsoroptions.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/solvers/tfqmrsoroptions.m	(revision 18231)
@@ -0,0 +1,14 @@
+function solverOptions=tfqmrsoroptions(varargin)
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+solverOptions=struct();
+solverOptions.toolkit='petsc';
+
+
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==3,
+   solverOptions.mat_type=getfieldvalue(options, 'mat_type','mpiaij');
+   solverOptions.ksp_type=getfieldvalue(options, 'ksp_type','tfqmr');
+   solverOptions.pc_type=getfieldvalue(options, 'pc_type',  'sor');
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ddewhite.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ddewhite.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ddewhite.m	(revision 18231)
@@ -0,0 +1,30 @@
+function sout = ddewhite(s)
+%DDEWHITE Double dewhite. Strip both leading and trailing whitespace.
+%
+%   DDEWHITE(S) removes leading and trailing white space and any null
+%   characters from the string S.  A null character is one that has an absolute
+%   value of 0.
+%
+%   See also DEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:57 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error('Input must be a string (char array).');
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(min(c) : max(c));
+   else
+      sout = s(:, min(c) : max(c));
+   end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/dewhite.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/dewhite.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/dewhite.m	(revision 18231)
@@ -0,0 +1,30 @@
+function sout = dewhite(s)
+%DEWHITE Dewhite. Strip trailing whitespace.
+%
+%   DEWHITE(S) removes leading and trailing white space and any null characters
+%   from the string S.  A null character is one that has an absolute value of
+%   0.
+%
+%   See also DDEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:52 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error( 'Input must be a string (char array).' );
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(1:max(c));
+   else
+      sout = s(:,1:max(c));
+   end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/discardnum.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/discardnum.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/discardnum.m	(revision 18231)
@@ -0,0 +1,14 @@
+function string2=discardnum(string)
+%DISCARDNUM -  ??????
+%
+%   Usage:
+%      string2=discardnum(string)
+
+string2=string;
+
+for i=1:length(string),
+	if (((string(i)-0) <=57) & ((string(i)-0) >=48)),
+		string2=string(1:i-1);
+		break;
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ismemberi.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ismemberi.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/ismemberi.m	(revision 18231)
@@ -0,0 +1,26 @@
+function flag=ismemberi(string,list),
+%ISMEMBERI - return 1 if a string belongs to a list (case insensitive)
+%
+%   same function as Matlab's ismember except that it
+%   is case insensitive
+%
+%   Usage:
+%      flag=ismemberi(string,list);
+%
+%   Example:
+%      flag=ismemberi('test','{'test1','test2','test3'});
+
+if ~iscell(list)
+	error('ismemberi error message: the list of string must be a cell!')
+end
+
+%initialize output
+flag=0;
+
+%go through the list
+for i=1:length(list),
+	if strcmpi(string,list{i}),
+		flag=i;
+		return
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit.m	(revision 18231)
@@ -0,0 +1,88 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   This function should be used to split a string of delimiter separated
+%   values.  If all values are numerical values the returned matrix is a
+%   double array but if there is one non numerical value a cell array is
+%   returned.  You can check this with the iscell() function.
+%   inpstr: string containing delimiter separatede numerical values, eg
+%           3498,48869,23908,34.67
+%   Output: An x by 1 matrix containing the splitted values
+%   Delimiter: optional, if omitted the delimiter is , (comma)
+%
+%   Usage:
+%      output = strsplit(inpstr[,delimiter])
+%
+
+%   mailto:    gie.spaepen@ua.ac.be
+
+%Check input arguments
+if(nargin < 1)
+    error('There is no argument defined');
+else
+    if(nargin == 1)
+        strdelim = ',';
+        %Verbose off!! disp 'Delimiter set to ,';
+    else
+        strdelim = delimiter;
+    end
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,strdelim);
+if size(idx) == 0
+    disp 'No delimiter in string, inputString is returned';
+    splittedstring = inpstr;
+else
+    %Define size of the indices
+    sz = size(idx,2);
+    %Define splittedstring
+    tempsplit = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        %Define standard start and stop positions for the start position,
+        %choose 1 as startup position because otherwise you get an array
+        %overflow, for the endposition you can detemine it from the
+        %delimiter position
+        strtpos = 1;
+        endpos = idx(i)-1;
+        %If i is not the beginning of the string get it from the delimiter
+        %position
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        %If i is equal to the number of delimiters get the last element
+        %first by determining the lengt of the string and then replace the
+        %endpos back to a standard position
+        if i == sz
+            endpos = size(inpstr,2); 
+            tempsplit(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        %Add substring to output: splittedstring a cell array
+        tempsplit(i) = {inpstr(strtpos : endpos)};   
+    end
+    %Flag 
+    isallnums = 1;
+    %Check is there are NaN values if matrix elements are converted to
+    %doubles
+    for i = 1:size(tempsplit,2)
+        tempdouble = str2double(tempsplit(i));
+        if(isnan(tempdouble))
+            isallnums = 0;
+        end
+    end
+    %If isallnums = 1 then return a double array otherwise return a cell
+    %array
+    if(isallnums == 1)
+        for i = 1:size(tempsplit,2)
+            splittedstring(i) = str2double(tempsplit(i));
+        end
+    else
+        splittedstring = tempsplit;
+    end
+
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit_strict.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit_strict.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/m/string/strsplit_strict.m	(revision 18231)
@@ -0,0 +1,36 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   Usage:
+%      output = strsplit_strict(inpstr,delimiter)
+
+%Check input arguments
+if(nargin ~= 2)
+    error('There is no argument defined');
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,delimiter);
+if size(idx) == 0
+    splittedstring = {inpstr};
+else
+    sz = size(idx,2);
+    splittedstring = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        strtpos = 1;
+        endpos = idx(i)-1;
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        if i == sz
+            endpos = size(inpstr,2); 
+            splittedstring(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        splittedstring(i) = {inpstr(strtpos : endpos)};   
+    end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/src/mobile/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/mobile/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/mobile/Makefile.am	(revision 18231)
@@ -0,0 +1,3 @@
+if ANDROID
+SUBDIRS = native
+endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Main.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Main.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Main.cpp	(revision 18231)
@@ -0,0 +1,197 @@
+#include "../../c/main/issm.h"
+#include <cstddef>
+#include <stdio.h>
+
+//Android specific header includes: 
+#include <jni.h>
+#include <android/log.h>
+#include <android/log.h>
+
+//iOS specific header includes: 
+
+namespace gov_nasa_jpl_issm
+{
+	/*Global variables{{{*/
+	FemModel *fm;
+	double* xyz; /*keep vertices information here*/
+	/*}}}*/
+	jint Initialize(JNIEnv *env, jclass clazz, jstring jsolution_type, jstring jabsfile, jstring jrelfile) /*{{{*/
+	{
+		
+		/*arguments to constructor: */
+		int argc; //arguments to constructor.
+		char** argv = NULL;
+		const char* issmname = "issm.exe";
+		char *solution_type = NULL;
+		char *absfile = NULL;
+		char *relfile = NULL;
+		ISSM_MPI_Comm    comm=1;
+
+		/*log:*/
+		__android_log_print(ANDROID_LOG_INFO, "Native","Initializing FemModel");
+
+		/*retrieve from java machine: */
+		solution_type = (char*)env->GetStringUTFChars(jsolution_type,0);
+		absfile = (char*)env->GetStringUTFChars(jabsfile,0);
+		relfile = (char*)env->GetStringUTFChars(jrelfile,0);
+
+		/*creat arguments to call constructor for FemModel: */
+		argc=4; 
+		argv=(char**)malloc(argc*sizeof(char*));
+		argv[0]=(char*)issmname;
+		argv[1]=solution_type;
+		argv[2]=absfile;
+		argv[3]=relfile;
+		
+		/*call Model constructor passing in infile as File Descriptor parameter.*/
+		fm  = new FemModel(argc,argv,comm);
+
+		/*we'll need the toolkits activated right away to use matrices: */
+		ToolkitsOptionsFromAnalysis(fm->parameters,NoneAnalysisEnum);
+
+		/*release strings: */
+		env->ReleaseStringUTFChars(jsolution_type, solution_type); //must realease the char*
+		env->ReleaseStringUTFChars(jabsfile, absfile); //must realease the char*
+		env->ReleaseStringUTFChars(jrelfile, relfile); //must realease the char*
+
+		/*figure out size of solution: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Number of elements");
+		jint size = (jint) fm->elements->NumberOfElements();
+
+		/*retrieve vertices x,y and z coordinates: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Retrieving vertices");
+		xyz=fm->vertices->ToXYZ();
+		
+		/*log: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Done Initializing FemModel");
+
+		return size;
+
+	}
+	/*}}}*/
+	void Solve(JNIEnv *env, jclass clazz , jdouble alpha, jobject buf){ /*{{{*/
+
+		int i,count;
+		double x1,y1,z1,vel1;
+		double x2,y2,z2,vel2;
+		double x3,y3,z3,vel3;
+		int    v1,v2,v3,eid;
+		Patch* patch=NULL;
+		
+		/*log:*/
+		__android_log_print(ANDROID_LOG_INFO, "Native","Solving ");
+
+		/*retrieve buffer: */
+		jdouble *dBuf = (jdouble *)env->GetDirectBufferAddress(buf);
+
+		/*reset basal friction to what it was before: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","alpha %g ",alpha);
+		
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok-1");
+
+		InputDuplicatex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,AndroidFrictionCoefficientEnum,FrictionCoefficientEnum);
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok0");
+
+		/*now scale friction by alpha: */
+		InputScalex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,FrictionCoefficientEnum,alpha/100);
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok1");
+
+		/*solve: */
+		fm -> Solve();
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok2");
+
+		/*retrieve results: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Retrieving results ");
+		//fm->elements->ProcessResultsUnits(); we are now in SI units
+		patch=fm->elements->ResultsToPatch();
+
+		/*sort out the velocities: */
+		for(i=0;i<patch->numrows;i++){
+			if ((patch->values[i*patch->numcols+0])==VelEnum){
+
+				/*Each row of the Patch object is made of the following information: 
+				  - the result enum_type, 
+				  - the step and time, 
+				  - the id of the element, 
+				  - the interpolation type, 
+				  - the vertices ids, 
+				  - and the values at the nodes (could be different from the vertices)
+				*/
+				eid=(int)patch->values[i*patch->numcols+3]-1;
+				v1=(int)patch->values[i*patch->numcols+5]; 
+				x1=xyz[3*(v1-1)+0]; y1=xyz[3*(v1-1)+1]; z1=xyz[3*(v1-1)+2];
+				
+				v2=(int)patch->values[i*patch->numcols+6];
+				x2=xyz[3*(v2-1)+0]; y2=xyz[3*(v2-1)+1]; z2=xyz[3*(v2-1)+2];
+				
+				v3=(int)patch->values[i*patch->numcols+7];
+				x3=xyz[3*(v3-1)+0]; y3=xyz[3*(v3-1)+1]; z3=xyz[3*(v3-1)+2];
+
+				vel1=patch->values[i*patch->numcols+8]; 
+				vel2=patch->values[i*patch->numcols+9]; 
+				vel3=patch->values[i*patch->numcols+10]; 
+
+				/*plug into dBuf: */
+				/*vertex 1: */
+				dBuf[12*eid+0]=x1;
+				dBuf[12*eid+1]=y1;
+				dBuf[12*eid+2]=z1;
+
+				/*vertex 2: */
+				dBuf[12*eid+3]=x2;
+				dBuf[12*eid+4]=y2;
+				dBuf[12*eid+5]=z2;
+			
+				/*vertex 3: */
+				dBuf[12*eid+6]=x3;
+				dBuf[12*eid+7]=y3;
+				dBuf[12*eid+8]=z3;
+				
+				/*values at 3 vertices: */
+				dBuf[12*eid+9]=vel1;
+				dBuf[12*eid+10]=vel2;
+				dBuf[12*eid+11]=vel3;
+
+			}
+		}
+
+		/*for(i=0;i<148;i++){
+		__android_log_print(ANDROID_LOG_INFO, "Native","%g %g %g | %g %g %g | %g %g %g | %g %g %g\n",
+				dBuf[12*i+0],dBuf[12*i+1],dBuf[12*i+2],
+				dBuf[12*i+3],dBuf[12*i+4],dBuf[12*i+5],
+				dBuf[12*i+6],dBuf[12*i+7],dBuf[12*i+8],
+				dBuf[12*i+9],dBuf[12*i+10],dBuf[12*i+11]);
+		}*/
+
+		/*delete temporary data:*/
+		delete patch;
+
+	}/*}}}*/
+	static JNINativeMethod method_table[] = /*{{{*/
+	{
+			{"createISSMModel"   ,"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I"  , (void *) Initialize},
+			{"solveISSMModel", "(DLjava/nio/DoubleBuffer;)V", (void *) Solve}
+	};
+	/*}}}*/
+}
+
+using namespace gov_nasa_jpl_issm;
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) /*{{{*/
+{
+    JNIEnv* env;
+    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+        return -1;
+    }
+    else
+    {
+    	jclass clazz = env->FindClass("gov/nasa/jpl/issm/IssmJni");
+    	if(clazz)
+    	{
+    		env->RegisterNatives(clazz, method_table, 3);
+    		env->DeleteLocalRef(clazz);
+    		return JNI_VERSION_1_6;
+    	}
+    	else return -1;
+    }
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/mobile/native/Makefile.am	(revision 18231)
@@ -0,0 +1,7 @@
+#Generate JNI library
+lib_LTLIBRARIES = libIssmJni.la
+
+libIssmJni_la_SOURCES = Main.cpp
+libIssmJni_la_LIBADD = $(ISSM_DIR)/src/c/libISSMCore.a $(ISSM_DIR)/externalpackages/gsl/install/lib/libgsl.a $(ISSM_DIR)/externalpackages/gsl/install/lib/libgslcblas.a
+
+AM_LDFLAGS = -llog
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 18231)
@@ -0,0 +1,64 @@
+/*\file BamgConvertMesh.c
+ *\brief: bamg module.
+ */
+#include "./BamgConvertMesh.h"
+
+void BamgConvertMeshUsage(void){/*{{{*/
+	_printf0_("BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y)\n");
+	_printf0_("      index: index of the mesh\n");
+	_printf0_("      x,y: coordinates of the nodes\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(BamgConvertMesh){
+
+	/*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*/
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	delete bamggeom;
+	delete bamgmesh;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 18231)
@@ -0,0 +1,54 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/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/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 18231)
@@ -0,0 +1,51 @@
+/*\file BamgMesher.c
+ *\brief: mesher that uses the bamg library
+ */
+#include "./BamgMesher.h"
+
+void BamgMesherUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions)\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(BamgMesher){
+
+	/*Intermediary*/
+	BamgOpts *bamgopts     = NULL;
+	BamgMesh *bamgmesh_in  = NULL;
+	BamgGeom *bamggeom_in  = NULL;
+	BamgMesh *bamgmesh_out = NULL;
+	BamgGeom *bamggeom_out = NULL;
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgMesher/BamgMesher.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 18231)
@@ -0,0 +1,61 @@
+/*\file BamgTriangulate.c
+ *\brief: bamg module.
+ */
+#include "./BamgTriangulate.h"
+
+void BamgTriangulateUsage(void){/*{{{*/
+	_printf0_("BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      index=BamgTriangulate(x,y);\n");
+	_printf0_("      index: index of the triangulation\n");
+	_printf0_("      x,y: coordinates of the nodes\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(BamgTriangulate){
+
+	/*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) _printf_("Fetching inputs\n");
+	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) _printf_("Call core\n");
+	BamgTriangulatex(&index,&nels,x,y,nods);
+
+	/*Write output*/
+	WriteData(INDEX,index,nels,3);
+
+	/*Clean up*/
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.cpp	(revision 18231)
@@ -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){/*{{{*/
+	_printf0_("\n");
+	_printf0_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);\n");
+	_printf0_("\n");
+}/*}}}*/
+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_
+	_printf_("nvtxs: " << nvtxs << "\n");
+	_printf_("options: [");
+	for(i=0;i<10;i++)_printf_(options[i] << "|");
+	_printf_("]\n");
+	_printf_("start: \n");
+	for (i=0; i<nvtxs+1;i++)_printf_(start[i] << " ");
+	_printf_("\n");
+	_printf_("adjacency: \n");
+	for (i=0; i<mxGetNzmax(A_IN);i++)_printf_("" <<adjacency[i]<< " ");i++)
+	_printf_("\n");
+	_printf_("nedges: " << nedges << " " << ewgts << "\n");
+	if(ewgts) for (i = 0; i < nedges; i++)_printf_(ewgts[i] << " ");
+	_printf_("\n");
+	_printf_("vwgts:\n");
+	for (i = 0; i < nvtxs; i++)_printf_(vwgts[i] << " ");
+	_printf_("\n");
+	_printf_("nparts: " << nparts[0] << "\n");
+	_printf_("goal: " << goal << "\n");
+	#endif
+	/*}}}*/
+
+	/*Allocate output: */
+	assignment = xNewZeroInit<short>(nvtxs);
+
+    /*Call core: */
+	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options, nparts, goal);
+
+    /*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/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Chaco/Chaco.h	(revision 18231)
@@ -0,0 +1,67 @@
+/*!\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 "../bindings.h" /*Should always come first to avoid python's warnings*/
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 18231)
@@ -0,0 +1,96 @@
+/*! \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){/*{{{*/
+	_printf_("CONTOURTOMESH - Flag the elements or nodes inside a contour\n");
+	_printf_("\n");
+	_printf_("      Usage: \n");
+	_printf_("         [in_nod,in_elem]=ContourToMesh(index,x,y,contourname,interptype,edgevalue)\n");
+	_printf_("\n");
+	_printf_("         index,x,y: mesh triangulation.\n");
+	_printf_("         contourname: name of .exp file containing the contours.\n");
+	_printf_("         interptype: string definining type of interpolation ('element', or 'node').\n");
+	_printf_("         edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.\n");
+	_printf_("         in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', \n");
+	_printf_("            or of size 0 otherwise.\n");
+	_printf_("         in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', \n");
+	_printf_("            or of size 0 otherwise.\n");
+	_printf_("\n");
+	_printf_("      Example: \n");
+	_printf_("         in_nod=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','node',1)\n");
+	_printf_("         in_elements=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element',0)\n");
+	_printf_("         [in_nodes,in_elements]=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element and node',0)\n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(ContourToMesh){
+
+	/* required input: */
+	int       edgevalue;
+	int       nel,nods;
+	double   *index       = NULL;
+	double   *x           = NULL;
+	double   *y           = NULL;
+	char     *interptype  = NULL;
+	Contours *contours    = NULL;
+
+	/* output: */
+	double *in_nod  = NULL;
+	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,nods);
+		WriteData(PLHS1);
+	}
+	else if (strcmp(interptype,"element")==0){
+		WriteData(PLHS0,in_elem,nel);
+		WriteData(PLHS1);
+	}
+	else if (strcmp(interptype,"element and node")==0){
+		WriteData(PLHS0,in_nod,nods);
+		WriteData(PLHS1,in_elem,nel);
+	}
+	else _error_("wrong interpolation type");
+
+	/*Clean up*/
+	xDelete<double>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<char>(interptype);
+	delete contours;
+	delete in_nod;
+	delete in_elem;
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 18231)
@@ -0,0 +1,63 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "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/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 18231)
@@ -0,0 +1,55 @@
+/*! \file  ContourtoNodes
+    \brief: takes a  contour file, and figures out which nodes  (x,y list)
+*/
+
+#include "./ContourToNodes.h"
+
+void ContourToNodesUsage(void){/*{{{*/
+	_printf_("   usage:\n");
+	_printf_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
+	_printf_("   where:\n");
+	_printf_("      x,y: list of nodes.\n");
+	_printf_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.\n");
+	_printf_("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.\n");
+	_printf_("      flags: vector of flags (0 or 1), of size nods.\n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(ContourToNodes){
+
+	/* input: */
+	int       edgevalue,nods;
+	double   *x           = NULL;
+	double   *y           = NULL;
+	char     *contourname = NULL;
+	Contours *contours    = NULL;
+
+	/* output: */
+	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,nods);
+
+	/*Clean up*/
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<char>(contourname);
+	delete contours;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 18231)
@@ -0,0 +1,55 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 18231)
@@ -0,0 +1,45 @@
+/*\file ElementConnectivity.c
+ *\brief: build element connectivity using node connectivity and elements. 
+ */
+
+#include "./ElementConnectivity.h"
+
+void ElementConnectivityUsage(void) {/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(ElementConnectivity){
+
+	/*inputs: */
+	int* elements=NULL;
+	int* nodeconnectivity=NULL;
+	int  nels,nods;
+	int  width;
+
+	/*outputs: */
+	int* elementconnectivity=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&ElementConnectivityUsage);
+
+	/*Input datasets: */
+	FetchData(&elements,&nels,NULL,ELEMENTS);
+	FetchData(&nodeconnectivity,&nods,&width,NODECONNECTIVITY);
+
+	/*!Generate internal degree of freedom numbers: */
+	ElementConnectivityx(&elementconnectivity,elements,nels,nodeconnectivity,nods,width);
+
+	/*write output datasets: */
+	WriteData(ELEMENTCONNECTIVITY,elementconnectivity,nels,3);
+
+	/*Clean up*/
+	xDelete<int>(nodeconnectivity);
+	xDelete<int>(elementconnectivity);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "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/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.cpp	(revision 18231)
@@ -0,0 +1,37 @@
+/*\file EnumToString.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./EnumToString.h"
+
+void EnumToStringUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "string = EnumToString(enum);\n");
+	_printf0_("\n");
+}/*}}}*/
+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);
+
+	/*Clean up*/
+	xDelete<char>(name);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/EnumToString/EnumToString.h	(revision 18231)
@@ -0,0 +1,48 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/shared/Enum/Enum.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 18231)
@@ -0,0 +1,96 @@
+/*\file Exp2Kml.c
+ *\brief: exp to kml file conversion mex module.
+ */
+#include "./Exp2Kml.h"
+
+void Exp2KmlUsage(void){/*{{{*/
+	_printf0_("Exp2Kml - exp to kml file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from exp to kml format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filexp      file name of exp file to be read (char)\n");
+	_printf0_("      filkml      file name of kml file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml', 1);\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Exp2Kml){
+
+	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) _printf_("  cm=" << cm << "\n");
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printf_("  sp=" << sp << "\n");
+	}
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 18231)
@@ -0,0 +1,221 @@
+/*\file ExpSimplify.c
+ *\brief: exp to kml file conversion mex module.
+ */
+#include "./ExpSimplify.h"
+
+void ExpSimplifyUsage(void){/*{{{*/
+	_printf_("ExpSimplify - Simplify Exp contour\n");
+	_printf_("\n");
+	_printf_("   Recursive Douglas-Peucker Polygon Simplification\n");
+	_printf_("\n");
+	_printf_("   Usage:\n");
+	_printf_("      ExpSimplify(expfile,tol);\n");
+	_printf_("      - expfile: name of the exp file\n");
+	_printf_("      - tol:  tolerance (maximal euclidean distance allowed between the new line and a vertex)\n");
+	_printf_("      Additional options:\n");
+	_printf_("      - 'min': minimum number of vertices to save contours in exp file (default is 3)\n");
+	_printf_("\n");
+	_printf_("   Example:\n");
+	_printf_("      ExpSimplify('file.exp',100);\n");
+	_printf_("      ExpSimplify('file.exp',100,'remove1',false);\n");
+}/*}}}*/
+void simplify(Contour<double>* contour,bool* flags,int ind0,int ind1,double tolerance){/*{{{*/
+
+	bool    closed    = false;
+	double  distance,beta,dx,dy;
+	double  maxdistance;
+	int     index  = -1;
+	double *x      = contour->x;
+	double *y      = contour->y;
+
+	/*Some checks*/
+	_assert_(ind0>=0 && ind0<contour->nods);
+	_assert_(ind1>=0 && ind1<contour->nods);
+	_assert_(ind1-ind0>=0);
+
+	/*Check wether this portion is closed*/
+	if(x[ind0]==x[ind1] && y[ind0]==y[ind1]) closed=true;
+
+	if(closed){
+
+		/*calculate the shortest distance of all vertices between ind0 and ind1*/
+		for(int i=ind0;i<ind1-1;i++){
+			distance = sqrt((x[ind0]-x[i+1])*(x[ind0]-x[i+1]) + (y[ind0]-y[i+1])*(y[ind0]-y[i+1]));
+			if(i==ind0 || distance>maxdistance){
+				maxdistance=distance;
+				index = i + 1;
+			}
+		}
+	}
+	else{
+		/*calculate shortest distance of all points to the line from ind0 to ind1
+		 * subtract starting point from other locations
+		 *
+		 * d = || (x-x0) - beta (xend - x0) ||
+		 * <x-x0,xend-x0>      = ||x-x0|| ||xend-x0|| cos(alpha)
+		 * beta ||xend-x0|| = ||x-x0|| cos(alpha)
+		 *
+		 * So: beta = <x-x0,xend-x0>/<xend-x0,xend-x0>  */
+
+		for(int i=ind0+1;i<=ind1;i++){
+			beta = ((x[i]-x[ind0])*(x[ind1]-x[ind0]) + (y[i]-y[ind0])*(y[ind1]-y[ind0]))/((x[ind1]-x[ind0])*(x[ind1]-x[ind0])+(y[ind1]-y[ind0])*(y[ind1]-y[ind0]));
+			dx   = x[i]-beta*x[ind1]+(beta-1.)*x[ind0];
+			dy   = y[i]-beta*y[ind1]+(beta-1.)*y[ind0];
+			distance = sqrt(dx*dx + dy*dy);
+			if(i==ind0+1 || distance>maxdistance){
+				maxdistance = distance;
+				index       = i;
+			}
+		}
+
+	}
+
+	/*if the maximum distance is smaller than the tolerance remove vertices between ind0 and ind1*/
+	if(maxdistance<tolerance){
+		if(ind0!=ind1-1){
+			for(int i=ind0+1;i<ind1;i++) flags[i]=false;
+		}
+	}
+	else{
+		/*if not, call simplifyrec for the segments between ind0 and index
+		 * (index and ind1)*/
+		_assert_(index!=-1);
+		_assert_(index!=ind1);
+		_assert_(index!=ind0);
+		simplify(contour,flags,ind0 ,index,tolerance);
+		simplify(contour,flags,index,ind1, tolerance);
+	}
+
+}/*}}}*/
+WRAPPER(ExpSimplify){
+
+	int i,verbose=1;
+
+	/*input: */
+	char*    expfile  = NULL;
+	double   tolerance;
+	Options *options      = NULL;
+	double   minimumvertices_double;
+	int      minimumvertices;
+
+	/*output*/
+	Contours* oldcontours = NULL;
+	Contours* newcontours = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	/*checks on arguments on the matlab side: */
+	if (nrhs<NRHS || nlhs>NLHS){
+		ExpSimplifyUsage(); _error_("ExpSimplify usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&expfile,  EXPFILE);
+	FetchData(&tolerance,TOLERANCE);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*some checks*/
+	if(tolerance<0) _error_("tolerance must be a positivve scalar");
+
+	/* Run core computations: */
+	Contour<double>* contour = NULL;
+	Contour<double>* newcontour = NULL;
+	int     nods,newnods;
+	bool*   flags = NULL;
+	double* x = NULL;
+	double* y = NULL;
+	double distance;
+
+	/*Process options*/
+	options->Get(&minimumvertices_double,"min",3.);
+	if(minimumvertices_double<1.) _error_("'min' (minimum number of verties) should be a positive integer");
+	minimumvertices = int(minimumvertices_double);
+
+	/*Read old contours and allocate new contours*/
+	oldcontours=ExpRead<double>(expfile);
+	newcontours=new Contours();
+	for(int counter=0;counter<oldcontours->Size();counter++){
+
+		/*Get single contour*/
+		contour = (Contour<double>*)oldcontours->GetObjectByOffset(counter);
+		nods    = contour->nods;
+		x       = contour->x;
+		y       = contour->y;
+		_printf_("   Initial number of vertices in contour #"<<counter+1<<": "<<nods << "\n");
+
+		/*Allocate flags (1=keep, 0=remove)*/
+		if(nods>0) flags   = xNew<bool>(nods);
+
+		if(nods==0){
+			/*Don't do anything*/
+		}
+		else if(nods==1){
+			flags[0] = true;
+		}
+		else if(nods==2){
+			/*check if the distance between both is less than the tolerance
+			 * If so, return the center*/
+			distance = sqrt((x[1]-x[0])*(x[1]-x[0]) + (y[1]-y[0])*(y[1]-y[0]));
+			if(distance<=tolerance){
+				x[0]=(x[0]+x[1])/2.;
+				y[0]=(y[0]+y[1])/2.;
+				flags[0] = true;
+				flags[1] = false;
+			}
+			else{
+				flags[0] = true;
+				flags[1] = true;
+			}
+		}
+		else{
+			/*Start recursive call to simplify*/
+			for(int i=0;i<nods;i++) flags[i]=true;
+			simplify(contour,flags,0,nods-1,tolerance);
+		}
+
+		/*Add new contour to newcontours*/
+		newnods = 0;
+		for(int i=0;i<nods;i++) if(flags[i]) newnods++;
+
+		/*Do we save new profile?*/
+		if(newnods>=minimumvertices){
+			_printf_("   Final   number of vertices in contour #"<<counter+1<<": "<<newnods << "\n");
+			newcontour       = new Contour<double>();
+			newcontour->nods = newnods;
+			newcontour->x    = xNew<double>(newnods);
+			newcontour->y    = xNew<double>(newnods);
+			newnods = 0;
+			for(int i=0;i<nods;i++){
+				if(flags[i]){
+					newcontour->x[newnods] = contour->x[i];
+					newcontour->y[newnods] = contour->y[i];
+					newnods++;
+				}
+			}
+			_assert_(newnods==newcontour->nods);
+
+			/*Add to main dataset*/
+			newcontours->AddObject(newcontour);
+		}
+		else{
+			_printf_("   Final   number of vertices in contour #"<<counter+1<<": "<<newnods<<" (not saved)\n");
+		}
+
+		/*cleanup*/
+		xDelete<bool>(flags);
+	}
+	_printf_("   Initial number of contours: "<<oldcontours->Size() << "\n");
+	_printf_("   Final   number of contours: "<<newcontours->Size() << "\n");
+
+	/*Write data: */
+	ExpWrite(newcontours,expfile);
+
+	/*Clean-up*/
+	xDelete<char>(expfile);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ExpSimplify/ExpSimplify.h	(revision 18231)
@@ -0,0 +1,46 @@
+/*!\file ExpSimplify.h
+ * \brief: prototype for exp to kml file conversion mex module.
+ */
+
+#ifndef _EXPSIMPLIFY_H
+#define _EXPSIMPLIFY_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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ExpSimplify"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define EXPFILE   prhs[0]
+#define TOLERANCE prhs[1]
+/* serial output macros: */
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define EXPFILE   PyTuple_GetItem(args,0)
+#define TOLERANCE PyTuple_GetItem(args,1)
+#endif
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  2
+#undef NLHS
+#define NLHS  0
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 18231)
@@ -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){/*{{{*/
+	_printf0_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a grid onto a list of points based on a bilinear interpolation\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);\n");
+	_printf0_("\n");
+	_printf0_("      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf0_("      x,y: coordinates of matrix data. (x and y must be in increasing order)\n");
+	_printf0_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.\n");
+	_printf0_("      default_value: default value if no data is found (holes).\n");
+	_printf0_("      data_mesh: vector of mesh interpolated data.\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('velocities.mat');\n");
+	_printf0_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(InterpFromGridToMesh){
+
+	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: */
+	IssmSeqVec<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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 18231)
@@ -0,0 +1,59 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 18231)
@@ -0,0 +1,142 @@
+/*!\file InterpFromMesh2d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+
+#include "./InterpFromMesh2d.h"
+
+void InterpFromMesh2dUsage(void){/*{{{*/
+	_printf0_("   usage:\n");
+	_printf0_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
+	_printf0_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
+	_printf0_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
+	_printf0_("   where:\n");
+	_printf0_("      x,y: coordinates of the nodes where data is defined\n");
+	_printf0_("      index: index of the mesh where data is defined\n");
+	_printf0_("      data - vector holding the data to be interpolated onto the points.\n");
+	_printf0_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.\n");
+	_printf0_("      default_value: a scalar or vector of size length(x_prime).\n");
+	_printf0_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.\n");
+	_printf0_("      data_prime:  vector of prime interpolated data.\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(InterpFromMesh2d){
+
+	/*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: */
+	IssmSeqVec<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){
+
+		#ifdef _HAVE_MATLAB_MODULES_
+		/*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=new Contour<double>();
+			//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;
+		}
+		#else
+		_error_("not supported");
+		#endif
+	}
+	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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 18231)
@@ -0,0 +1,59 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 18231)
@@ -0,0 +1,78 @@
+/*\file InterpFromMeshToGrid.c
+ *\brief: compute diff between observed and modeled velocity
+ */
+
+#include "./InterpFromMeshToGrid.h"
+
+void InterpFromMeshToGridUsage(void){/*{{{*/
+	_printf0_("INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a triangular mesh onto a regular grid\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)\n");
+	_printf0_("\n");
+	_printf0_("      index,x,y: delaunay triangulation defining the mesh.\n");
+	_printf0_("      meshdata: vertex values of data to be interpolated.\n");
+	_printf0_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid\n");
+	_printf0_("      default_value: value of points located out of the mesh.\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(InterpFromMeshToGrid){
+
+	/*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: */
+	#ifdef _HAVE_MATLAB_MODULES_
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToGridUsage);
+	#endif
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 18231)
@@ -0,0 +1,74 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 18231)
@@ -0,0 +1,79 @@
+/*\file InterpFromMeshToMesh2d.c
+ *\brief: bamg module.
+ */
+#include "./InterpFromMeshToMesh2d.h"
+
+void InterpFromMeshToMesh2dUsage(void){/*{{{*/
+	_printf0_("INTERFROMMESHTOMESH2D - interpolation from a 2d triangular mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a Delaunay triangulation onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("         data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp);\n");
+	_printf0_("      or data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp,OPTIONS);\n");
+	_printf0_("\n");
+	_printf0_("      index             : index of the mesh where data is defined\n");
+	_printf0_("      x,y               : coordinates of the nodes where data is defined\n");
+	_printf0_("      data              : matrix holding the data to be interpolated onto the mesh. (one column per field)\n");
+	_printf0_("      x_interp,y_interp : coordinates of the points onto which we interpolate.\n");
+	_printf0_("      data_interp       : vector of mesh interpolated data.\n");
+	_printf0_("      Available options :\n");
+	_printf0_("         - 'default' : default value if point is outsite of triangulation (instead of linear interolation)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('temperature.mat');\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y);\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y,'default',253);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(InterpFromMeshToMesh2d){
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 18231)
@@ -0,0 +1,63 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 18231)
@@ -0,0 +1,103 @@
+/*!\file InterpFromMeshToMesh3d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+
+#include "./InterpFromMeshToMesh3d.h"
+
+void InterpFromMeshToMesh3dUsage(void){/*{{{*/
+	_printf0_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a triangular mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);\n");
+	_printf0_("\n");
+	_printf0_("      index: index of the mesh where data is defined\n");
+	_printf0_("      x,y,z: coordinates of the nodes where data is defined\n");
+	_printf0_("      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf0_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.\n");
+	_printf0_("      default_value: default value if no data is found (holes).\n");
+	_printf0_("      data_prime: vector of mesh interpolated data.\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('temperature.mat');\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(InterpFromMeshToMesh3d){
+
+	/*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: */
+	IssmSeqVec<double>*  data_prime=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	#ifdef _HAVE_MATLAB_MODULES_
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToMesh3dUsage);
+	#endif
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 18231)
@@ -0,0 +1,63 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 18231)
@@ -0,0 +1,133 @@
+/*\file IssmConfig.c
+ *\brief: get configuration names
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmConfig.h"
+
+void IssmConfigUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "value = IssmConfig('string');\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(IssmConfig){
+
+	/*input/output*/
+	char       *name     = NULL;
+	bool        isstring = false;
+	IssmDouble  value   = 0.;
+	char       *svalue   = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&IssmConfigUsage);
+
+	/*Fetch inputs: */
+	FetchData(&name,NAME);
+
+	/*Core*/
+	if(strcmp(name,"_HAVE_MPI_")==0){
+		#ifdef _HAVE_MPI_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_DAKOTA_")==0){
+		#ifdef _HAVE_DAKOTA_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_MUMPS_")==0){
+		#ifdef _HAVE_MUMPS_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_GSL_")==0){
+		#ifdef _HAVE_GSL_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_TAO_")==0){
+		#ifdef _HAVE_TAO_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_M1QN3_")==0){
+		#ifdef _HAVE_M1QN3_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_PETSC_")==0){
+		#ifdef _HAVE_PETSC_
+		value = 1.;
+		#endif
+	}
+	else if(strcmp(name,"_PETSC_MAJOR_")==0){
+		#ifdef _PETSC_MAJOR_
+		value = IssmDouble(_PETSC_MAJOR_);
+		#else
+		_error_("_PETSC_MAJOR_ not found in config.h");
+		#endif
+	}
+	else if(strcmp(name,"_DAKOTA_VERSION_")==0){
+		#ifdef _DAKOTA_VERSION_
+		isstring = true;
+		svalue =xNew<char>(strlen(_DAKOTA_VERSION_)+1);
+		xMemCpy<char>(svalue,_DAKOTA_VERSION_,(strlen(_DAKOTA_VERSION_)+1));
+		#else
+		_error_("_DAKOTA_VERSION_ not found in config.h");
+		#endif
+	}
+	else if(strcmp(name,"ISSM_PREFIX")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(ISSM_PREFIX)+1);
+		xMemCpy<char>(svalue,ISSM_PREFIX,(strlen(ISSM_PREFIX)+1));
+	}
+	else if(strcmp(name,"PACKAGE_NAME")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_NAME)+1);
+		xMemCpy<char>(svalue,PACKAGE_NAME,(strlen(PACKAGE_NAME)+1));
+	}
+	else if(strcmp(name,"PACKAGE_VERSION")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_VERSION)+1);
+		xMemCpy<char>(svalue,PACKAGE_VERSION,(strlen(PACKAGE_VERSION)+1));
+	}
+	else if(strcmp(name,"PACKAGE_URL")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_URL)+1);
+		xMemCpy<char>(svalue,PACKAGE_URL,(strlen(PACKAGE_URL)+1));
+	}
+	else if(strcmp(name,"PACKAGE_BUGREPORT")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_BUGREPORT)+1);
+		xMemCpy<char>(svalue,PACKAGE_BUGREPORT,(strlen(PACKAGE_BUGREPORT)+1));
+	}
+	else if(strcmp(name,"PACKAGE_BUILD_DATE")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(PACKAGE_BUILD_DATE)+1);
+		xMemCpy<char>(svalue,PACKAGE_BUILD_DATE,(strlen(PACKAGE_BUILD_DATE)+1));
+	}
+	else{
+		_error_("variable " << name << " not supported yet");
+	}
+
+	/* output: */
+	if(isstring)
+	 WriteData(VALUE,svalue);
+	else
+	 WriteData(VALUE,value);
+
+	/*Clean up*/
+	xDelete<char>(name);
+	xDelete<char>(svalue);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/IssmConfig/IssmConfig.h	(revision 18231)
@@ -0,0 +1,48 @@
+/*!\file:  IssmConfig.h
+ * \brief header file for IssmConfig module.
+ */ 
+
+#ifndef _ISSMCONFIG_H
+#define _ISSMCONFIG_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/shared/Enum/Enum.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "IssmConfig"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define NAME (mxArray*)prhs[0]
+/* serial output macros: */
+#define VALUE (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define NAME PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define VALUE output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _TEST_H */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 18231)
@@ -0,0 +1,127 @@
+/*\file KMLFileRead.c
+ *\brief: KML file reader module.
+ */
+#include "./KMLFileRead.h"
+
+void KMLFileReadUsage(void){/*{{{*/
+	_printf0_("KMLFileRead - KML file reader module:\n");
+	_printf0_("\n");
+	_printf0_("   This module reads a KML file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ierror]=KMLFileRead(kmlfile,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      kmlfile      file name of kml file to be read (char)\n");
+	_printf0_("\n");
+	_printf0_("      echo         echo command (char, optional, 'off'/'on')\n");
+	_printf0_("      deepecho     deep echo command (char, optional, 'off'/'on')\n");
+	_printf0_("      write        write command (char, optional, 'off'/'stdout'/kmlfile)\n");
+	_printf0_("\n");
+	_printf0_("      ierror       return code (non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ierror]=KMLFileRead('file.kml','deepecho','on');\n");
+	_printf0_("      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(KMLFileRead){
+
+	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) _printf_("Opening file \"" << filnam << "\".\n");
+	fidi=fopen(filnam,"r");
+
+	/* Run core computations: */
+	if (verbose) _printf_("Calling core:\n");
+	kobj=KMLFileReadx(fidi);
+
+	if (verbose) _printf_("Closing file \"" << filnam << "\".\n");
+	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) _printf_("Opening file \"" << write << "\".\n");
+				fido=fopen(write,"w");
+				kobj->Write(fido,"");
+				if (verbose) _printf_("Closing file \"" << write << "\".\n");
+				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/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 18231)
@@ -0,0 +1,148 @@
+/*\file KMLMeshWrite.c
+ *\brief: KML mesh writer module.
+ */
+#include "./KMLMeshWrite.h"
+
+void KMLMeshWriteUsage(void){/*{{{*/
+	_printf0_("KMLMeshWrite - KML mesh writer module:\n");
+	_printf0_("\n");
+	_printf0_("   This module writes the mesh of a model as KML polygons into the specified KML file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);\n");
+	_printf0_("\n");
+	_printf0_("      name       model name (string, may be empty)\n");
+	_printf0_("      notes      model notes (string or cell array of strings, may be empty)\n");
+	_printf0_("      elem       elements (double array)\n");
+	_printf0_("      nodecon    nodal connectivity array (double array, may be empty)\n");
+	_printf0_("      lat        nodal latititudes (double vector)\n");
+	_printf0_("      long       nodal longitudes (double vector)\n");
+	_printf0_("      part       nodal partitions (double vector, may be empty)\n");
+	_printf0_("      data       nodal or element data (double vector, may be empty)\n");
+	_printf0_("      cmap       color map (double nx3 array, may be empty)\n");
+	_printf0_("      kmlfile    KML file name (string)\n");
+	_printf0_("\n");
+	_printf0_("      ierror     error flag (double, non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(KMLMeshWrite){
+
+	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/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 18231)
@@ -0,0 +1,65 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 18231)
@@ -0,0 +1,133 @@
+/*\file KMLOverlay.c
+ *\brief: KML file overlay mex module.
+ */
+#include "./KMLOverlay.h"
+
+void KMLOverlayUsage(void){/*{{{*/
+	_printf0_("KMLOverlay - KML file overlay module:\n");
+	_printf0_("\n");
+	_printf0_("   This module reads a list of image files and writes a KML or KMZ overlay file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ierror=KMLOverlay(kmlfile,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      kmlfile     KML or KMZ file name (string)\n");
+	_printf0_("\n");
+	_printf0_("      lataxis     latitude axis (double vector [south north], required)\n");
+	_printf0_("      longaxis    longitude axis (double vector [west east], required)\n");
+	_printf0_("      images      relative or http image file names (string or array of strings or cell array of strings, required)\n");
+	_printf0_("      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)\n");
+	_printf0_("\n");
+	_printf0_("      ierror     error flag (double, non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(KMLOverlay){
+
+	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++) _printf_("  lataxis [" << i << "]=" << lataxis[i] << "\n");
+	options->Get(&longaxis,&nlong,(char*)"longaxis");
+	if (verbose && longaxis) for (i=0; i<nlong; i++) _printf_("  longaxis[" << i << "]=" << longaxis[i] << "\n");
+	options->Get(&pimages,&nimages,(char*)"images");
+	if (verbose && pimages) for (i=0; i<nimages; i++) _printf_("  pimages[" << i << "]=\"" << pimages[i] << "\"\n");
+	options->Get(&dzip,(char*)"zip",0.);
+	if (verbose) _printf_("  dzip=" << dzip << "\n");
+
+	/*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) _printf_("Opening kml overlay file \"" << filkml << "\".\n");
+	fid=fopen(filkml,"w");
+
+	/* Run core computations: */
+	if (verbose) _printf_("Calling core:\n");
+	KMLOverlayx(&ierror,lataxis,longaxis,nimages,pimages,fid);
+
+	if (verbose) _printf_("Closing file \"" << filkml << "\".\n");
+	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) _printf_("Zipping file \"" << filkmz << "\".\n");
+		if (verbose) _printf_(czip << "\n");
+
+		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/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 18231)
@@ -0,0 +1,88 @@
+/*\file Kml2Exp.c
+ *\brief: kml to exp file conversion mex module.
+ */
+#include "./Kml2Exp.h"
+
+void Kml2ExpUsage(void){/*{{{*/
+	_printf0_("Kml2Exp - kml to exp file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from kml to exp format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filkml      file name of kml file to be read (char)\n");
+	_printf0_("      filexp      file name of exp file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp', 1);\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Kml2Exp){
+
+	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) _printf_("  cm=" << cm << "\n");
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printf_("  sp=" << sp << "\n");
+	}
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.cpp	(revision 18231)
@@ -0,0 +1,78 @@
+/*\file Kriging.c
+ *\brief: best linear predictor
+ */
+#include "./Kriging.h"
+
+void KrigingUsage(void){/*{{{*/
+	int num=1;
+#ifdef _MULTITHREADING_
+	num=_NUMTHREADS_;
+#endif
+	_printf0_("\n");
+	_printf0_("   usage: predictions=" << __FUNCT__ << "(x,y,observations,x_interp,y_interp,'options');\n");
+	_printf0_("   available options:\n");
+	_printf0_("      -'model': Available variogram models 'gaussian' (default),'spherical','power','exponential'\n");
+	_printf0_("         -'nugget': nugget effect (default 0.2)\n");
+	_printf0_("         -'range':  for gaussian, spherical and exponential models (default sqrt(3))\n");
+	_printf0_("         -'sill':   for gaussian, spherical and exponential models (default 1)\n");
+	_printf0_("         -'slope':  for power model (default 1)\n");
+	_printf0_("         -'power':  for power model (default 1)\n");
+	_printf0_("      -'searchradius': search radius for each prediction (default is observations span)\n");
+	_printf0_("      -'boxlength':    minimum length of quadtree boxes (useful to decrease the number of observations)\n");
+	_printf0_("      -'maxdata':      minimum number of observations for a prediction (default is 50)\n");
+	_printf0_("      -'mindata':      maximum number of observations for a prediction (default is 1)\n");
+	_printf0_("      -'maxtrimming':  maximum trimming value (default is -1.e+21)\n");
+	_printf0_("      -'mintrimming':  minimum trimming value (default is +1.e+21)\n");
+	_printf0_("      -'minspacing':   minimum distance between observation (default is 0.01)\n");
+	_printf0_("      -'numthreads':   number of threads, default is "<<num << "\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Kriging){
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Kriging/Kriging.h	(revision 18231)
@@ -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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 18231)
@@ -0,0 +1,97 @@
+/*\file Ll2xy.c
+ *\brief: lat/long to x/y coordinate mex module.
+ */
+#include "./Ll2xy.h"
+
+void Ll2xyUsage(void){/*{{{*/
+	_printf0_("Ll2xy - lat/long to x/y coordinate transformation module:\n");
+	_printf0_("\n");
+	_printf0_("   This module transforms lat/long to x/y coordinates.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      lat         latitude coordinates (double vector)\n");
+	_printf0_("      lon         longitude coordinates (double vector)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      x           x coordinates (double vector)\n");
+	_printf0_("      y           y coordinates (double vector)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon, 1);\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Ll2xy){
+
+	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) _printf_("  cm=" << cm << "\n");
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printf_("  sp=" << sp << "\n");
+	}
+
+	/*some checks*/
+	if (verbose) _printf_("Checking inputs:\n");
+	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/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Ll2xy/Ll2xy.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Makefile.am	(revision 18231)
@@ -0,0 +1,12 @@
+SUBDIRS = 
+if WRAPPERS
+
+if MATLAB
+SUBDIRS += matlab
+endif
+
+if PYTHON
+SUBDIRS += python
+endif
+
+endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 18231)
@@ -0,0 +1,95 @@
+/*!\file:  MeshPartition.cpp
+ * \brief: partition mesh according to number of areas, using Metis library.
+*/
+
+#include "./MeshPartition.h"
+
+void MeshPartitionUsage(void){/*{{{*/
+	_printf_("   usage:\n");
+	_printf_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
+	_printf_("   where:\n");
+	_printf_("      element_partitioning is a vector of partitioning area numbers, for every element.\n");
+	_printf_("      node_partitioning is a vector of partitioning area numbers, for every node.\n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(MeshPartition){
+
+	/*Indexing: */
+	int i,j;
+
+	/* required input: */
+	int  meshelementtype;
+	int  numberofelements;
+	int  numberofvertices;
+	int *elements         = NULL;
+	int  elements_width;
+
+	int numberofelements2d;
+	int numberofvertices2d;
+	int* 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(&numberofelements,mxGetAssignedField(MESH,0,"numberofelements"));
+	FetchData(&numberofvertices,mxGetAssignedField(MESH,0,"numberofvertices"));
+	FetchData(&elements,NULL,&elements_width,mxGetAssignedField(MESH,0,"elements"));
+
+	if(strcmp(mxGetClassName(MESH),"mesh3dprisms")==0){
+		meshelementtype = PentaEnum;
+		FetchData(&numberofelements2d,mxGetAssignedField(MESH,0,"numberofelements2d"));
+		FetchData(&numberofvertices2d,mxGetAssignedField(MESH,0,"numberofvertices2d"));
+		FetchData(&elements2d,NULL,NULL,mxGetAssignedField(MESH,0,"elements2d"));
+		FetchData(&numberoflayers,mxGetAssignedField(MESH,0,"numberoflayers"));
+	}
+	else if(strcmp(mxGetClassName(MESH),"mesh2dhorizontal")==0){
+		meshelementtype = TriaEnum;
+		numberoflayers=1;
+	}
+	else if(strcmp(mxGetClassName(MESH),"mesh2dvertical")==0){
+		meshelementtype = TriaEnum;
+		numberoflayers=1;
+	}
+	else{
+		_error_("Mesh type "<<mxGetClassName(MESH)<<" not supported yet");
+	}
+	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,meshelementtype,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/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshPartition/MeshPartition.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "MeshPartition"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define MESH    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 MESH     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/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 18231)
@@ -0,0 +1,93 @@
+/*! \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){/*{{{*/
+	_printf_("   usage:\n");
+	_printf_("   [segments]=MeshProfileIntersection(index,x,y,filename);\n");
+	_printf_("   where:\n");
+	_printf_("   input:\n");
+	_printf_("        index,x,y is a triangulation\n");
+	_printf_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)\n");
+	_printf_("   output:\n");
+	_printf_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremities for a segment \n");
+	_printf_("        belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the \n");
+	_printf_("        mesh.\n");
+}/*}}}*/
+WRAPPER(MeshProfileIntersection){
+
+	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
+	Contours         *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 IssmDenseMat and IssmSeqVec).
+	numcontours=domain->Size();
+	contours=xNew<Contour<double>*>(numcontours);
+	for(i=0;i<numcontours;i++)
+		*(contours+i)=(Contour<double>*)domain->GetObjectByOffset(i);
+
+	/*Run interpolation routine: */
+	MeshProfileIntersectionx(&segments,&numsegs,index,x,y,nel,nods,contours,numcontours);
+
+	/* output: */
+	WriteData(SEGMENTS,segments,numsegs,5);
+
+	/*end module: */
+	MODULEEND();
+
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 18231)
@@ -0,0 +1,41 @@
+/*\file NodeConnectivity.c
+ *\brief: build node connectivity from elements. 
+ */
+
+#include "./NodeConnectivity.h"
+
+void NodeConnectivityUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(NodeConnectivity){
+
+	/*inputs: */
+	int* elements=NULL;
+	int  nels;
+	int  nods;
+
+	/*outputs: */
+	int* connectivity=NULL;
+	int  width;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&NodeConnectivityUsage);
+
+	/*Input datasets: */
+	FetchData(&elements,&nels,NULL,ELEMENTS);
+	FetchData(&nods,NUMNODES);
+
+	/*!Generate internal degree of freedom numbers: */
+	NodeConnectivityx(&connectivity,&width,elements,nels,nods);
+
+	/*write output datasets: */
+	WriteData(CONNECTIVITY,connectivity,nods,width);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#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/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 18231)
@@ -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){/*{{{*/
+	_printf_("   usage:\n");
+	_printf_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
+	_printf_("   where:\n");
+	_printf_("      x,y: list of points.\n");
+	_printf_("      mindistance: minimum distance that should exist between points in the cloud.\n");
+	_printf_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.\n");
+	_printf_("      flags: array of flags (flag==1 means point is within mindistance of another point)\n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(PointCloudFindNeighbors){
+
+	int i,j;
+
+	/* required input: */
+	double *x = NULL;
+	double *y = NULL;
+	int     nods;
+	double  mindistance;
+	double  multithread;
+
+	/* output: */
+	IssmSeqVec<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/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 18231)
@@ -0,0 +1,46 @@
+/*\file PropagateFlagsFromConnectivity.c
+ *\brief: propagate flags onto mesh, element by element, using connectivity.
+ */
+
+#include "./PropagateFlagsFromConnectivity.h"
+
+void PropagateFlagsFromConnectivityUsage(void) {/*{{{*/
+	_printf_("\n");
+	_printf_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);\n");;
+	_printf_("\n");
+}/*}}}*/
+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/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.cpp	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Scotch/Scotch.h	(revision 18231)
@@ -0,0 +1,34 @@
+/*!\file:  Scotch.h
+ * \brief header file for Scotch module.
+ */ 
+
+#ifndef _SCOTCH_H
+#define _SCOTCH_H
+
+#include "../bindings.h" /*Should always come first to avoid python's warnings*/
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 18231)
@@ -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){/*{{{*/
+	_printf0_("Shp2Kml - shp to kml file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from shp to kml format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filshp      file name of shp file to be read (char, extension optional)\n");
+	_printf0_("      filkml      file name of kml file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) -1 (south) or 0 (no translation))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml', 0);\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Shp2Kml){
+
+	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) _printf_("  cm=" << cm << "\n");
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printf_("  sp=" << sp << "\n");
+	}
+
+	/*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/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 18231)
@@ -0,0 +1,51 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.cpp	(revision 18231)
@@ -0,0 +1,91 @@
+/*\file ShpRead.c
+ *\brief: shp to exp 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 "./ShpRead.h"
+#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+#include "shapefil.h"
+#endif
+
+void ShpReadUsage(void){/*{{{*/
+	_printf0_("ShpRead - Read shapefile\n");
+	_printf0_("\n");
+	_printf0_("   This module reads shapefiles and converts them to matlab/python structures\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ShpRead(filename);\n");
+	_printf0_("      filexp      file name of exp file to be written\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      ShpRead('file.shp');\n");
+}/*}}}*/
+WRAPPER(ShpRead){
+
+	/*input: */
+	char *filename= NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
+	_error_("Shapelib not available! Cannot carry out shp file translation!");
+	#else
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs != NLHS){ShpReadUsage(); _error_("ShpRead usage error");}
+	if(nrhs != NRHS){ShpReadUsage(); _error_("ShpRead usage error");}
+
+	/*Input datasets: */
+	FetchData(&filename,SHP_IN);
+
+	/*Open shapefile*/
+	SHPHandle hSHP = SHPOpen( filename, "rb" );
+	if(!hSHP) _error_("Error opening shp/shx files.");
+
+	/*read header and print out file bounds*/
+	int         nShapeType,nEntities;
+	IssmPDouble adfMinBound[4], adfMaxBound[4];
+	SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );
+	_printf_("Shapefile Type: "<<SHPTypeName(nShapeType)<<"   number of Shapes: "<< nEntities<<"\n\n");
+
+	/*Initialize output*/
+	Contours* contours = new Contours();
+
+	/*Read all objects*/
+	for(int i=0; i<nEntities;i++ ){
+
+		SHPObject* psShape = SHPReadObject(hSHP,i);
+		_printf_( "Shape #"<<i<<" ("<<SHPTypeName(psShape->nSHPType)<<") nVertices="<<psShape->nVertices<<", nParts="<<psShape->nParts<<"\n");
+
+		Contour<double> *contour = NULL;
+
+		switch(psShape->nSHPType){
+			case SHPT_ARC:
+				contour=new Contour<double>(0,psShape->nVertices,psShape->padfX,psShape->padfY,false);
+				break;
+			default:
+				_printf_("Shape type "<<SHPTypeName(psShape->nSHPType)<<"not supported yet, skipping...\n");
+		}
+
+		/*Add to contours and clean up*/
+		if(contour) contours->AddObject(contour);
+		SHPDestroyObject(psShape);
+	}
+
+	/*Write output*/
+	WriteData(SHP_OUT,contours);
+
+	/*Clean-up*/
+	delete contours;
+	xDelete<char>(filename);
+
+	#endif
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/ShpRead/ShpRead.h	(revision 18231)
@@ -0,0 +1,47 @@
+/*!\file ShpRead.h
+ * \brief: prototype for shp read mex module.
+ */
+
+#ifndef _SHPREAD_H
+#define _SHPREAD_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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ShpRead"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define SHP_IN  prhs[0]
+/* serial output macros: */
+#define SHP_OUT  (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define SHP_IN PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define SHP_OUT output,0
+#endif
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 18231)
@@ -0,0 +1,34 @@
+/*\file StringToEnum.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./StringToEnum.h"
+
+void StringToEnumUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);\n");
+	_printf0_("\n");
+}/*}}}*/
+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/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/StringToEnum/StringToEnum.h	(revision 18231)
@@ -0,0 +1,48 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/shared/Enum/Enum.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.cpp	(revision 18231)
@@ -0,0 +1,63 @@
+/*
+ * TriMesh: mesh a domain using an .exp file
+ */
+
+#include "./TriMesh.h"
+
+void TriMeshUsage(void){/*{{{*/
+	_printf_("\n");
+	_printf_("   usage: [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,area) \n");
+	_printf_("      where: index,x,y defines a triangulation, segments is an array made \n");
+	_printf_("      of exterior segments to the mesh domain outline, segmentmarkers is an array flagging each segment, \n");
+	_printf_("      outlinefilename an Argus domain outline file, \n");
+	_printf_("      area is the maximum area desired for any element of the resulting mesh, \n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(TriMesh){
+
+	/*intermediary: */
+	double    area;
+	Contours *domain = NULL;
+	Contours *rifts  = NULL;
+
+	/* output: */
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
+	int     nels,nods,nsegs;
+
+	/*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,&nels,&nods,&nsegs,domain,rifts,area);
+
+	/*write outputs: */
+	WriteData(INDEX,index,nels,3);
+	WriteData(X,x,nods);
+	WriteData(Y,y,nods);
+	WriteData(SEGMENTS,segments,nsegs,3);
+	WriteData(SEGMENTMARKERLIST,segmentmarkerlist,nsegs);
+
+	/*free ressources: */
+	delete domain;
+	delete rifts;
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<int>(segments);
+	xDelete<int>(segmentmarkerlist);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMesh/TriMesh.h	(revision 18231)
@@ -0,0 +1,63 @@
+/*
+	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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "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/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\file:  TriMeshProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./TriMeshProcessRifts.h"
+
+void TriMeshProcessRiftsUsage(void){/*{{{*/
+	_printf_("\n");
+	_printf_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessrifts(index1,x1,y1,segments1,segmentmarkers1) \n");
+	_printf_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.\n");
+	_printf_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.\n");
+}/*}}}*/
+WRAPPER(TriMeshProcessRifts){
+
+	/* returned quantities: */
+	RiftStruct *riftstruct = NULL;
+
+	/* input: */
+	int     nel,nods;
+	int    *index          = NULL;
+	double *x              = NULL;
+	double *y              = NULL;
+	int    *segments       = NULL;
+	int    *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/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 18231)
@@ -0,0 +1,65 @@
+/*
+ * 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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 18231)
@@ -0,0 +1,60 @@
+/*\file TriaSearch.c
+ *\brief: TriaSearch module. See TriaSearchx for more details.
+ */
+#include "./TriaSearch.h"
+
+void TriaSearchUsage(void){/*{{{*/
+	_printf0_("TriaSearch- find triangle holding a point (x0,y0) in a mesh\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("         tria=TriaSearch(index,x,y,x0,y0);\n");
+	_printf0_("      index,x,y: mesh triangulatrion\n");
+	_printf0_("      x0,y0: coordinates of the point for which we are trying to find a triangle\n");
+	_printf0_("      x0,y0 can be an array of points\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(TriaSearch){
+
+	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/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/TriaSearch/TriaSearch.h	(revision 18231)
@@ -0,0 +1,56 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 18231)
@@ -0,0 +1,96 @@
+/*\file Xy2ll.c
+ *\brief: x/y to lat/long coordinate mex module.
+ */
+#include "./Xy2ll.h"
+
+void Xy2llUsage(void){/*{{{*/
+	_printf0_("Xy2ll - x/y to lat/long coordinate transformation module:\n");
+	_printf0_("\n");
+	_printf0_("   This module transforms x/y to lat/long coordinates.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      x           x coordinates (double vector)\n");
+	_printf0_("      y           y coordinates (double vector)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      lat         latitude coordinates (double vector)\n");
+	_printf0_("      lon         longitude coordinates (double vector)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y, 1);\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(Xy2ll){
+
+	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) _printf_("  cm=" << cm << "\n");
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printf_("  sp=" << sp << "\n");
+	}
+
+	/*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) _printf_("Calling core:\n");
+	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/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/Xy2ll/Xy2ll.h	(revision 18231)
@@ -0,0 +1,53 @@
+/*!\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 "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.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/branches/trunk-jpl-ad2-integrated/src/wrappers/bindings.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/bindings.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/bindings.h	(revision 18231)
@@ -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_PYTHON_MODULES_
+#include "./python/include/pythonincludes.h"
+#include "./python/include/wrapper_macros.h"
+#include "./python/io/pythonio.h"
+#endif
+
+#ifdef  _HAVE_MATLAB_MODULES_
+#include "./matlab/include/matlabincludes.h"
+#include "./matlab/include/wrapper_macros.h"
+#include "./matlab/io/matlabio.h"
+#endif
+
+#endif
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/include/issm-binding.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/include/issm-binding.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/include/issm-binding.h	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/Makefile.am	(revision 18231)
@@ -0,0 +1,270 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@
+AUTOMAKE_OPTIONS = subdir-objects
+
+EXEEXT=$(MATLABWRAPPEREXT)
+
+#define prefix (from http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Defining-Directories.html)
+AM_CPPFLAGS+=  -DISSM_PREFIX='"$(prefix)"'
+
+#matlab io{{{
+lib_LIBRARIES = libISSMMatlab.a 
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMMatlab.la
+else
+lib_LTLIBRARIES =
+endif
+
+io_sources= ./include/matlabincludes.h\
+				./io/matlabio.h\
+				./io/CheckNumMatlabArguments.cpp\
+				./io/WriteMatlabData.cpp\
+				./io/FetchMatlabData.cpp
+
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_ -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+
+libISSMMatlab_a_SOURCES = $(io_sources)
+libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMMatlab_la_SOURCES = $(io_sources)
+endif
+#}}}
+#api io{{{
+lib_LIBRARIES += libISSMApi.a 
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMApi.la
+else
+lib_LTLIBRARIES +=
+endif
+
+api_sources= ./io/ApiPrintf.cpp
+
+libISSMApi_a_SOURCES = $(api_sources)
+libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMApi_la_SOURCES = $(api_sources)
+endif
+#}}}
+#Wrappers {{{
+if WRAPPERS
+lib_LTLIBRARIES += BamgMesher.la\
+						 BamgConvertMesh.la\
+						 BamgTriangulate.la\
+						 ContourToMesh.la\
+						 ContourToNodes.la\
+						 ElementConnectivity.la\
+						 EnumToString.la\
+						 ExpSimplify.la\
+						 InterpFromGridToMesh.la\
+						 InterpFromMeshToMesh2d.la\
+						 InterpFromMeshToMesh3d.la\
+						 InterpFromMeshToGrid.la\
+						 InterpFromMesh2d.la\
+						 IssmConfig.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\
+				   Exp2Kml.la\
+				   Kml2Exp.la\
+				   ShpRead.la\
+				   Shp2Kml.la
+endif
+endif 
+#}}}
+
+# Dependencies {{{
+deps =  $(MATHLIB)
+
+#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
+
+AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_  -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
+
+if SHAREDLIBS
+deps += ./libISSMMatlab.la ../../c/libISSMModules.la ../../c/libISSMCore.la ./libISSMApi.la
+
+else
+deps += ./libISSMMatlab.a ../../c/libISSMModules.a ../../c/libISSMCore.a ./libISSMApi.a
+if ADOLC
+deps += $(ADOLCLIB)
+endif
+endif
+
+#MEXLIB needs to be the last (undefined references on larsen)
+deps += ${MEXLIB}
+
+#Optimization flags:
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+#}}}
+# Module sources and dependencies {{{
+libISSMMatlab_la_LIBADD = ./../../c/libISSMCore.la ./../../c/libISSMModules.la $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB) 
+libISSMMatlab_la_LDFLAGS = -module -export-dynamic
+
+libISSMApi_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB)
+libISSMApi_la_LDFLAGS = -module -export-dynamic
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
+									  ../BamgTriangulate/BamgTriangulate.h
+BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
+						 ../Chaco/Chaco.h
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(CHACOLIB) $(GSLLIB) $(PETSCLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									../ContourToMesh/ContourToMesh.h
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
+										../InterpFromMesh2d/InterpFromMesh2d.h
+InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
+										../IssmConfig/IssmConfig.h
+IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
+								 ../KMLFileRead/KMLFileRead.h
+KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
+								  ../KMLMeshWrite/KMLMeshWrite.h
+KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
+								../KMLOverlay/KMLOverlay.h
+KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp\
+						 ../Xy2ll/Xy2ll.h
+Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp\
+						 ../Ll2xy/Ll2xy.h
+Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ExpSimplify_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
+							../ExpSimplify/ExpSimplify.h
+ExpSimplify_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
+							../Exp2Kml/Exp2Kml.h
+Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
+							../Kml2Exp/Kml2Exp.h
+Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kriging_la_SOURCES = ../Kriging/Kriging.cpp\
+							../Kriging/Kriging.h
+Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp\
+									../MeshPartition/MeshPartition.h
+MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+												 ../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
+PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
+PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Scotch_la_SOURCES = ../Scotch/Scotch.cpp\
+						  ../Scotch/Scotch.h
+Scotch_la_LIBADD = ${deps} $(SCOTCHLIB) $(MPILIB) $(BLASLAPACKLIB)
+
+ShpRead_la_SOURCES = ../ShpRead/ShpRead.cpp\
+							../ShpRead/ShpRead.h
+ShpRead_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
+							../Shp2Kml/Shp2Kml.h
+Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp\
+								../TriaSearch/TriaSearch.h
+TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/matlabincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/matlabincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/matlabincludes.h	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/wrapper_macros.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/wrapper_macros.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/include/wrapper_macros.h	(revision 18231)
@@ -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();
+
+#define MODULEEND(); }\
+	catch(ErrorException &exception){\
+		mexErrMsgTxt(exception.MatlabReport()); \
+	}\
+	catch (exception &e){\
+		mexErrMsgTxt(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/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/ApiPrintf.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 18231)
@@ -0,0 +1,19 @@
+/* \file ApiPrintf.c:
+ * \brief: API specific symbols from libISSMCore that we need to resolve here
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./matlabio.h"
+
+/*Matlab printf i/o: */
+void ApiPrintf(const char* string){
+
+	/*use mexPrintf in matlab: */
+	mexPrintf(string);
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 18231)
@@ -0,0 +1,22 @@
+/*!\file CheckNumMatlabArguments.cpp:
+ * \brief: check number of arguments and report an usage error message.
+ */
+
+#include "./matlabio.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/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 18231)
@@ -0,0 +1,1214 @@
+/*\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 <cstring> 
+
+/*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")){
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
+			}
+			/*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")){
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
+			}
+			/*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")){
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
+			}
+			/*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 M,N;
+
+	/*Use Fetch matrix*/
+	FetchData(&outvector,&M,&N,dataref) ;
+
+	/*Check that it is a vector*/
+	if(M*N>0 && (M!=1 && N!=1)){
+		_error_("input vector of size " << M << "x" << N << " should have only one column");
+	}
+
+	/*Transpose Row vectors*/
+	if(M==1 && N>1) M=N;
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if(pM)*pM=M;
+}
+/*}}}*/
+/*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: */
+		FetchData(&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: */
+		FetchData(&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: */
+		FetchData(&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(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->random,mxGetField(dataref,0,"random"));
+	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(Contours** pcontours,const mxArray* dataref){{{*/
+void FetchData(Contours** pcontours,const mxArray* dataref){
+
+	int             numcontours,index,test1,test2;
+	char            *contourname = NULL;
+	Contours        *contours    = NULL;
+	Contour<double> *contouri    = NULL;
+
+	if (mxIsClass(dataref,"char")){
+		FetchData(&contourname,dataref);
+		contours=ExpRead<double>(contourname);
+	}
+	else if(mxIsClass(dataref,"struct")){
+
+		contours=new Contours();
+		numcontours=mxGetNumberOfElements(dataref);
+
+		for(int i=0;i<numcontours;i++){
+
+			contouri=new Contour<double>();
+
+			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;
+}
+/*}}}*/
+
+/*Toolkit*/
+/*FUNCTION MatlabMatrixToDoubleMatrix {{{*/
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int        i,j,count,rows,cols;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			/*Now, get ir,jc and pr: */
+			ir=mxGetIr(mxmatrix);
+			jc=mxGetJc(mxmatrix);
+
+			/*Now, start inserting data into double* matrix: */
+			count=0;
+			for(i=0;i<cols;i++){
+				for(j=0;j<(jc[i+1]-jc[i]);j++){
+					matrix[rows*ir[count]+i]=pmxmatrix[count];
+					count++;
+				}
+			}
+		}
+
+	}
+	else if(mxIsClass(mxmatrix,"double")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"single")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		float *pmxmatrix=(float*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"int16")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		short int *pmxmatrix=(short*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"uint8")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		char *pmxmatrix=(char*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else{
+		_error_("Matlab matrix type Not implemented yet");
+	}
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	*pmatrix_rows=rows;
+	*pmatrix_cols=cols;
+
+	return 1;
+}/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	double* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	double  *pr    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+
+		matrix=xNewZeroInit<double>(rows*cols);
+
+		/*Now, get ir,jc and pr: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pr = mxGetPr(mxmatrix);
+
+		/*Now, start inserting data into double* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				*(matrix+rows*ir[count]+i)=pr[count];
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNewZeroInit<double>(numel);
+
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j = IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(double)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	bool* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	bool* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	bool    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		matrix=xNewZeroInit<bool>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+		pm=(bool*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into bool* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(bool*)mxGetData(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<bool>(numel);
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j=IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(bool)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int           i,j,rows,cols;
+	int           numel,ndims;
+	int          *size , *dims;
+	mxChar       *mxmatrix_ptr = NULL;
+	const mwSize *ipt          = NULL;
+
+	/*output: */
+	char* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	char    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+		matrix=xNew<char>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pm = (char*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into char* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=(char)pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=mxGetChars(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<char>(numel+1);
+		matrix[numel]='\0';
+
+		/*looping code adapted from Matlab example explore.c: */
+		int elements_per_page = size[0] * size[1];
+		/* total_number_of_pages = size[2] x size[3] x ... x size[N-1] */
+		int total_number_of_pages = 1;
+		for (i=2; i<ndims; i++) {
+			total_number_of_pages *= size[i];
+		}
+
+		i=0;
+		for (int page=0; page < total_number_of_pages; page++) {
+			int row;
+			/* On each page, walk through each row. */
+			for (row=0; row<size[0]; row++)  {
+				int column;
+				j = (page * elements_per_page) + row;
+
+				/* Walk along each column in the current row. */
+				for (column=0; column<size[1]; column++) {
+					*(matrix+i++)=(char)*(mxmatrix_ptr+j);
+					j += size[0];
+				}
+			}
+		}
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION mxGetAssignedField{{{*/
+mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
+
+	//output
+	mxArray* mxfield=NULL;
+
+	//input
+	mxArray    *inputs[2];
+	mxArray    *pindex      = NULL;
+	const char *fnames[2];
+	mwSize      ndim        = 2;
+	mwSize      onebyone[2] = {1,1};
+
+	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
+	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
+	inputs[0]=(mxArray*)pmxa_array; //this is the model
+
+	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
+	fnames[0] = "type";
+	fnames[1] = "subs";
+	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
+	mxSetField( pindex, 0, "type",mxCreateString("."));
+	mxSetField( pindex, 0, "subs",mxCreateString(field));
+	inputs[1]=pindex;
+
+	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+
+	return mxfield;
+}/*}}}*/
+
+GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+	FetchData(&odouble->value,prhs[0]);
+	odouble->numel=1;
+	odouble->ndims=1;
+	odouble->size=NULL;
+
+	return(odouble);
+}/*}}}*/
+GenericOption<double*>* OptionDoubleArrayParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double*> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double*>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"double")){
+		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&odouble->value,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
+
+	return(odouble);
+}/*}}}*/
+GenericOption<bool*>* OptionLogicalParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<bool*> *ological = NULL;
+
+	/*check and parse the name  */
+	ological=new GenericOption<bool*>();
+	ological->name =xNew<char>(strlen(name)+1);
+	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"logical")){
+		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ological->value,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
+
+	return(ological);
+}/*}}}*/
+GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<char*>  *ochar = NULL;
+
+	/*check and parse the name  */
+	ochar=new GenericOption<char*>();
+	ochar->name =xNew<char>(strlen(name)+1);
+	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"char")){
+		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+
+	return(ochar);
+}/*}}}*/
+GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	char           namei[161];
+	Option*                   option      = NULL;
+	GenericOption<Options**>  *ostruct    = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *structi;
+	mwIndex        sindex;
+
+	/*check and parse the name  */
+	ostruct=new GenericOption<Options**>();
+	ostruct->name =xNew<char>(strlen(name)+1);
+	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"struct")){
+		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	ostruct->numel=mxGetNumberOfElements(prhs[0]);
+	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt           =mxGetDimensions(prhs[0]);
+	ostruct->size =xNew<int>(ostruct->ndims);
+	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
+	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
+
+	/*loop through and process each element of the struct array  */
+	for (sindex=0; sindex<ostruct->numel; sindex++) {
+		ostruct->value[sindex]=new Options;
+
+		/*loop through and process each field for the element  */
+		for (i=0; i<mxGetNumberOfFields(prhs[0]); i++) {
+			sprintf(namei,"%s.%s",name,mxGetFieldNameByNumber(prhs[0],i));
+			structi=mxGetFieldByNumber(prhs[0],sindex,i);
+
+			option=(Option*)OptionParse(namei,&structi);
+			ostruct->value[sindex]->AddObject((Object*)option);
+			option=NULL;
+		}
+	}
+
+	return(ostruct);
+}/*}}}*/
+GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	int           *dims;
+	char           namei[161];
+	char           cstr[81];
+	GenericOption<Options*> *ocell      = NULL;
+	Option        *option     = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *celli;
+	mwIndex        cindex;
+
+	/*check and parse the name  */
+	ocell=new GenericOption<Options*>();
+	ocell->name =xNew<char>(strlen(name)+1);
+	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"cell")){
+		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	ocell->numel=mxGetNumberOfElements(prhs[0]);
+	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt         =mxGetDimensions(prhs[0]);
+	ocell->size =xNew<int>(ocell->ndims);
+	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
+	ocell->value=new Options;
+
+	/*loop through and process each element of the cell array  */
+	dims=xNew<int>(ocell->ndims);
+	for (cindex=0; cindex<ocell->numel; cindex++) {
+		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
+		StringFromDims(cstr,dims,ocell->ndims);
+		#ifdef _INTEL_WIN_
+			_snprintf(namei,161,"%s%s",name,cstr);
+		#else
+			snprintf(namei,161,"%s%s",name,cstr);
+		#endif
+		celli=mxGetCell(prhs[0],cindex);
+
+		option=(Option*)OptionParse(namei,&celli);
+		ocell->value->AddObject((Object*)option);
+		option=NULL;
+	}
+	xDelete<int>(dims);
+
+	return(ocell);
+}/*}}}*/
+Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
+
+	Option  *option = NULL;
+	mxArray *lhs[1];
+
+	/*parse the value according to the matlab data type  */
+	if     (mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])==1))
+	 option=(Option*)OptionDoubleParse(name,prhs);
+	else if(mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])!=1))
+	 option=(Option*)OptionDoubleArrayParse(name,prhs);
+	else if(mxIsClass(prhs[0],"logical"))
+	 option=(Option*)OptionLogicalParse(name,prhs);
+	else if(mxIsClass(prhs[0],"char"))
+	 option=(Option*)OptionCharParse(name,prhs);
+	else if(mxIsClass(prhs[0],"struct"))
+	 option=(Option*)OptionStructParse(name,prhs);
+	else if(mxIsClass(prhs[0],"cell"))
+	 option=(Option*)OptionCellParse(name,prhs);
+	else {
+		_printf0_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".\n");
+		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
+			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
+			mxDestroyArray(lhs[0]);
+		}
+		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	return(option);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 18231)
@@ -0,0 +1,488 @@
+/* \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/datastructures/datastructures.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,int* vector, int M){{{*/
+void WriteData(mxArray** pdataref,int* vector, int M){
+
+	mxArray* dataref       = NULL;
+	double*  vector_matlab = NULL;
+
+	if(vector){
+
+		/*create the matlab vector with Matlab's memory manager */
+		vector_matlab=(double*)mxMalloc(M*sizeof(double));
+		for(int i=0;i<M;i++) vector_matlab[i]=double(vector[i]);
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		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,IssmDenseMat<double>* matrix){{{*/
+void WriteData(mxArray** pdataref,IssmDenseMat<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,IssmSeqVec<double>* vector){{{*/
+void WriteData(mxArray** pdataref,IssmSeqVec<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;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,Contours* contours){{{*/
+void WriteData(mxArray** pdataref,Contours* contours){
+
+	/*Intermediary*/
+
+	int         i;
+	mxArray    *dataref           = NULL;
+	const int   numfields         = 6;
+	const char *fnames[numfields];
+	mwSize      ndim              = 2;
+	mwSize      dimensions[2]     = {1,1};
+	char        id[100];
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "name";
+	fnames[i++] = "nods";
+	fnames[i++] = "density";
+	fnames[i++] = "x";
+	fnames[i++] = "y";
+	fnames[i++] = "closed";
+	_assert_(i==numfields);
+
+	/*Initialize matlab structure of dimension numrifts*/
+	dimensions[0]=contours->Size();
+	dataref=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	for(int i=0;i<contours->Size();i++){
+		Contour<IssmPDouble>* contour=(Contour<IssmPDouble>*)contours->GetObjectByOffset(i);
+
+		/*create a name for this contour from the contour id and set it: */
+		sprintf(id,"%i",contour->id);
+		SetStructureFieldi(dataref,i,"name",id);
+
+		/*number of nods: */
+		SetStructureFieldi(dataref,i,"nods"         ,contour->nods);
+
+		/*density: */
+		SetStructureFieldi(dataref,i,"density"            ,1);
+
+		/*x and y: */
+		SetStructureFieldi(dataref,i,"x"             ,contour->nods, 1,contour->x);
+		SetStructureFieldi(dataref,i,"y"             ,contour->nods, 1,contour->y);
+
+		/*closed: */
+		SetStructureFieldi(dataref,i,"closed"         ,(int)contour->closed);
+	}
+
+	/*Assign output*/
+	*pdataref=dataref;
+}
+/*}}}*/
+
+/*Toolkit*/
+/*FUNCTION SetStructureField(mxArray* dataref,const char* fieldname,int M,int N,double* fieldpointer){{{*/
+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,const char* fieldname,char* string) {{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,char* string){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,string);
+
+	/*Assign to structure*/
+	mxSetField(dataref,i,fieldname,field);
+}
+/*}}}*/
+/*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 M,int N,int* fieldpointer){{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int M,int N,int* 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/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/matlabio.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/matlabio.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/matlab/io/matlabio.h	(revision 18231)
@@ -0,0 +1,81 @@
+/*\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/bamg/bamgobjects.h"
+#include "../../../c/classes/classes.h"
+#include "../../../c/toolkits/toolkits.h"
+#include "../../../c/shared/shared.h"
+
+void WriteData(mxArray** pdataref,IssmDenseMat<double>* matrix);
+void WriteData(mxArray** pdataref,double* matrix, int M,int N);
+void WriteData(mxArray** pdataref,int*    matrix, int M,int N);
+void WriteData(mxArray** pdataref,IssmSeqVec<double>* vector);
+void WriteData(mxArray** pdataref,double* vector, int M);
+void WriteData(mxArray** pdataref,int* vector, int M);
+void WriteData(mxArray** pdataref,int integer);
+void WriteData(mxArray** pdataref,bool boolean);
+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 WriteData(mxArray** pdataref,Contours* contours);
+
+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(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(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(Contours** 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 fieldrows,int fieldcols,int*    fieldpointer);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int field);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,double field);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,char* string);
+int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void ));
+
+/*Matlab to double* routines: */
+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);
+
+/*Print*/
+void ApiPrintf(const char* string);
+#endif	/* _IO_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/Makefile.am	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/Makefile.am	(revision 18231)
@@ -0,0 +1,182 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@ @AMPIINCL@
+#AUTOMAKE_OPTIONS = subdir-objects
+
+EXEEXT=$(PYTHONWRAPPEREXT)
+
+#define prefix (from http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Defining-Directories.html)
+AM_CPPFLAGS+=  -DISSM_PREFIX='"$(prefix)"'
+
+#python io{{{
+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
+#}}}
+#api io{{{
+lib_LIBRARIES += libISSMApi.a 
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMApi.la
+else
+lib_LTLIBRARIES +=
+endif
+
+api_sources= ./io/ApiPrintf.cpp
+
+libISSMApi_a_SOURCES = $(api_sources)
+libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMApi_la_SOURCES = $(api_sources)
+endif
+#}}}
+#Wrappers {{{
+if WRAPPERS
+lib_LTLIBRARIES = BamgConvertMesh.la\
+						BamgMesher.la\
+						ContourToMesh.la\
+						ContourToNodes.la\
+						ElementConnectivity.la\
+						EnumToString.la\
+						InterpFromMeshToMesh2d.la\
+						InterpFromMeshToMesh3d.la\
+						InterpFromGridToMesh.la\
+						InterpFromMeshToGrid.la\
+						IssmConfig.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
+
+if SHAREDLIBS
+deps += ./libISSMApi.la 
+else
+deps += ./libISSMApi.a
+endif
+
+
+
+endif 
+
+#Optimization flags:
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+#}}}
+#Bin sources {{{
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									 ../ContourToMesh/ContourToMesh.h
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+												../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+												../InterpFromMeshToGrid/InterpFromMeshToGrid.h
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
+											 ../IssmConfig/IssmConfig.h
+IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+										../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+#}}}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/pythonincludes.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/pythonincludes.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/pythonincludes.h	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/wrapper_macros.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/wrapper_macros.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/include/wrapper_macros.h	(revision 18231)
@@ -0,0 +1,83 @@
+/* \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();
+
+#define MODULEEND(); }\
+  catch(ErrorException &exception){\
+	  PyErr_SetString(PyExc_TypeError,exception.PythonReport()); \
+	  return NULL;\
+  } \
+	catch (exception &e){\
+		PyErr_SetString(PyExc_TypeError,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/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/ApiPrintf.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/ApiPrintf.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/ApiPrintf.cpp	(revision 18231)
@@ -0,0 +1,21 @@
+/* \file ApiPrintf.c:
+ * \brief: pyton api specific symbols which are unresolved from libISSMCore.a
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./pythonio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/Enum/Enum.h"
+
+/*Python printf i/o: */
+void ApiPrintf(const char* string){
+
+	/*use printf: */
+	printf("%s",string);
+	return;
+}
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 18231)
@@ -0,0 +1,28 @@
+/*!\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"
+
+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/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/FetchPythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/FetchPythonData.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/FetchPythonData.cpp	(revision 18231)
@@ -0,0 +1,824 @@
+/*\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/shared/shared.h"
+
+/*Primitive data types*/
+/*FUNCTION FetchData(double* pscalar,PyObject* py_float){{{*/
+void FetchData(double* pscalar,PyObject* py_float){
+
+	double dscalar;
+
+	/*return internal value: */
+	if      (PyFloat_Check(py_float))
+		dscalar=PyFloat_AsDouble(py_float);
+	else if (PyInt_Check(py_float))
+		dscalar=(double)PyInt_AsLong(py_float);
+	else if (PyLong_Check(py_float))
+		dscalar=PyLong_AsDouble(py_float);
+	else if (PyBool_Check(py_float))
+		dscalar=(double)PyLong_AsLong(py_float);
+	else if (PyTuple_Check(py_float) && (int)PyTuple_Size(py_float)==1)
+		FetchData(&dscalar,PyTuple_GetItem(py_float,(Py_ssize_t)0));
+	else if (PyList_Check(py_float) && (int)PyList_Size(py_float)==1)
+		FetchData(&dscalar,PyList_GetItem(py_float,(Py_ssize_t)0));
+	else
+		_error_("unrecognized float type in input!");
+
+	/*output: */
+	*pscalar=dscalar;
+}
+/*}}}*/
+/*FUNCTION FetchData(int* pscalar,PyObject* py_long){{{*/
+void FetchData(int* pscalar, PyObject* py_long){
+
+	int iscalar;
+
+	/*return internal value: */
+	if      (PyInt_Check(py_long))
+		iscalar=(int)PyInt_AsLong(py_long);
+	else if (PyLong_Check(py_long))
+		iscalar=(int)PyLong_AsLong(py_long);
+	else if (PyFloat_Check(py_long))
+		iscalar=(int)PyFloat_AsDouble(py_long);
+	else if (PyBool_Check(py_long))
+		iscalar=(int)PyLong_AsLong(py_long);
+	else if (PyTuple_Check(py_long) && (int)PyTuple_Size(py_long)==1)
+		FetchData(&iscalar,PyTuple_GetItem(py_long,(Py_ssize_t)0));
+	else if (PyList_Check(py_long) && (int)PyList_Size(py_long)==1)
+		FetchData(&iscalar,PyList_GetItem(py_long,(Py_ssize_t)0));
+	else
+		_error_("unrecognized long type in input!");
+
+	/*output: */
+	*pscalar=iscalar;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool* pscalar,PyObject* py_boolean){{{*/
+void FetchData(bool* pscalar,PyObject* py_boolean){
+
+	bool bscalar;
+
+	/*return internal value: */
+	if      (PyBool_Check(py_boolean))
+		bscalar=(bool)PyLong_AsLong(py_boolean);
+	else if (PyInt_Check(py_boolean))
+		bscalar=(bool)PyInt_AsLong(py_boolean);
+	else if (PyLong_Check(py_boolean))
+		bscalar=(bool)PyLong_AsLong(py_boolean);
+	else if (PyTuple_Check(py_boolean) && (int)PyTuple_Size(py_boolean)==1)
+		FetchData(&bscalar,PyTuple_GetItem(py_boolean,(Py_ssize_t)0));
+	else if (PyList_Check(py_boolean) && (int)PyList_Size(py_boolean)==1)
+		FetchData(&bscalar,PyList_GetItem(py_boolean,(Py_ssize_t)0));
+	else
+		_error_("unrecognized boolean type in input!");
+
+	/*output: */
+	*pscalar=bscalar;
+}
+/*}}}*/
+/*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;
+
+	/*intermediary:*/
+	long* lmatrix=NULL;
+	bool* bmatrix=NULL;
+	int i;
+	PyObject* py_matrix2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
+		if      (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=dims[1];
+		}
+		else if (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=1;
+		}
+		else
+			_error_("expecting an MxN matrix or M vector in input!");
+
+		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_DOUBLE,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dmatrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*copy matrix: */
+				matrix=xNew<double>(M*N);
+//				if (PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+					memcpy(matrix,dmatrix,(M*N)*sizeof(double));
+//				}
+
+//				else {
+//					int j,k,ipt=0;
+//					int mstride,nstride;
+//					mstride=(int)PyArray_STRIDE((PyArrayObject*)py_matrix,0)/PyArray_ITEMSIZE((PyArrayObject*)py_matrix);
+//					if (ndim > 1)
+//						nstride=(int)PyArray_STRIDE((PyArrayObject*)py_matrix,1)/PyArray_ITEMSIZE((PyArrayObject*)py_matrix);
+//					else
+//						nstride=1;
+//					for (i=0; i<M; i++) {
+//						k=i*mstride;
+//						for (j=0; j<N; j++) {
+//							matrix[ipt++]=dmatrix[k];
+//							k+=nstride;
+//						}
+//					}
+//				}
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
+				/*retrieve internal value: */
+				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into double matrix: */
+				matrix=xNew<double>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(double)lmatrix[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bmatrix=(bool*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into double matrix: */
+				matrix=xNew<double>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(double)bmatrix[i];
+			}
+
+			else
+				_error_("unrecognized double pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
+		}
+		else
+			matrix=NULL;
+	}
+
+	else {
+		M=1;
+		N=1;
+		matrix=xNew<double>(M*N);
+		FetchData(&(matrix[0]),py_matrix);
+	}
+
+	/*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: */
+	int* matrix=NULL;
+	int M,N;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*intermediary:*/
+	double* dmatrix=NULL;
+	long* lmatrix=NULL;
+	bool* bmatrix=NULL;
+	int i;
+	PyObject* py_matrix2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
+		if      (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=dims[1];
+		}
+		else if (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=1;
+		}
+		else
+			_error_("expecting an MxN matrix or M vector in input!");
+
+		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_LONG,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				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 if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
+				/*retrieve internal value: */
+				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into integer matrix: */
+				matrix=xNew<int>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(int)lmatrix[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bmatrix=(bool*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into integer matrix: */
+				matrix=xNew<int>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(int)bmatrix[i];
+			}
+
+			else
+				_error_("unrecognized int pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
+		}
+		else
+			matrix=NULL;
+	}
+
+	else {
+		M=1;
+		N=1;
+		matrix=xNew<int>(M*N);
+		FetchData(&(matrix[0]),py_matrix);
+	}
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pN)*pN=N;
+	if(pmatrix)*pmatrix=matrix;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool** pmatrix,int* pM, int* pN, PyObject* py_matrix){{{*/
+void FetchData(bool** pmatrix,int* pM,int *pN,PyObject* py_matrix){
+
+	/*output: */
+	bool* bmatrix=NULL;
+	bool* matrix=NULL;
+	int M,N;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*intermediary:*/
+	double* dmatrix=NULL;
+	long* lmatrix=NULL;
+	int i;
+	PyObject* py_matrix2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
+		if      (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=dims[1];
+		}
+		else if (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+			M=dims[0]; N=1;
+		}
+		else
+			_error_("expecting an MxN matrix or M vector in input!");
+
+		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_BOOL,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dmatrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into bool matrix: */
+				matrix=xNew<bool>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(bool)dmatrix[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
+				/*retrieve internal value: */
+				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*transform into bool matrix: */
+				matrix=xNew<bool>(M*N);
+				for(i=0;i<M*N;i++)matrix[i]=(bool)lmatrix[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bmatrix=(bool*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+				/*copy matrix: */
+				matrix=xNew<bool>(M*N);
+				memcpy(matrix,bmatrix,(M*N)*sizeof(bool));
+			}
+
+			else
+				_error_("unrecognized bool pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
+		}
+		else
+			matrix=NULL;
+	}
+
+	else {
+		M=1;
+		N=1;
+		matrix=xNew<bool>(M*N);
+		FetchData(&(matrix[0]),py_matrix);
+	}
+
+	/*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;
+
+	/*intermediary:*/
+	long* lvector=NULL;
+	bool* bvector=NULL;
+	int i;
+	PyObject* py_vector2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_vector)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
+		if      (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			M=dims[0]; 
+		}
+		else if (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			if (dims[1]==1)
+				M=dims[0]; 
+			else
+				_error_("expecting an Mx1 matrix or M vector in input!");
+		}
+		else
+			_error_("expecting an Mx1 matrix or M vector in input!");
+
+		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_DOUBLE,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*copy vector: */
+				vector=xNew<double>(M);
+				memcpy(vector,dvector,(M)*sizeof(double));
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
+				/*retrieve internal value: */
+				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into double vector: */
+				vector=xNew<double>(M);
+				for(i=0;i<M;i++)vector[i]=(double)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bvector=(bool*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into double vector: */
+				vector=xNew<double>(M);
+				for(i=0;i<M;i++)vector[i]=(double)bvector[i];
+			}
+
+			else
+				_error_("unrecognized double pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
+		}
+		else
+			vector=NULL;
+	}
+
+	else {
+		M=1;
+		vector=xNew<double>(M);
+		FetchData(&(vector[0]),py_vector);
+	}
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pvector)*pvector=vector;
+}
+/*}}}*/
+/*FUNCTION FetchData(int** pvector,int* pM, PyObject* py_vector){{{*/
+void FetchData(int** pvector,int* pM,PyObject* py_vector){
+
+	/*output: */
+	int* vector=NULL;
+	int M;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*intermediary:*/
+	long*   lvector=NULL;
+	bool*   bvector=NULL;
+	double* dvector=NULL;
+	int i;
+	PyObject* py_vector2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_vector)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
+		if      (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			M=dims[0]; 
+		}
+		else if (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			if (dims[1]==1)
+				M=dims[0]; 
+			else
+				_error_("expecting an Mx1 matrix or M vector in input!");
+		}
+		else
+			_error_("expecting an Mx1 matrix or M vector in input!");
+
+		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_LONG,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<int>(M);
+				for(i=0;i<M;i++)vector[i]=(int)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
+				/*retrieve internal value: */
+				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<int>(M);
+				for(i=0;i<M;i++)vector[i]=(int)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bvector=(bool*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<int>(M);
+				for(i=0;i<M;i++)vector[i]=(int)bvector[i];
+			}
+
+			else
+			 _error_("unrecognized int pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
+		}
+		else
+			vector=NULL;
+	}
+
+	else {
+		M=1;
+		vector=xNew<int>(M);
+		FetchData(&(vector[0]),py_vector);
+	}
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pvector)*pvector=vector;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool** pvector,int* pM, PyObject* py_vector){{{*/
+void FetchData(bool** pvector,int* pM,PyObject* py_vector){
+
+	/*output: */
+	bool* bvector=NULL;
+	bool* vector=NULL;
+	int M;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*intermediary:*/
+	double* dvector=NULL;
+	long* lvector=NULL;
+	int i;
+	PyObject* py_vector2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_vector)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
+		if      (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			M=dims[0]; 
+		}
+		else if (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			if (dims[1]==1)
+				M=dims[0]; 
+			else
+				_error_("expecting an Mx1 matrix or M vector in input!");
+		}
+		else
+			_error_("expecting an Mx1 matrix or M vector in input!");
+
+		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_BOOL,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into bool vector: */
+				vector=xNew<bool>(M);
+				for(i=0;i<M;i++)vector[i]=(bool)dvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
+				/*retrieve internal value: */
+				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into bool vector: */
+				vector=xNew<bool>(M);
+				for(i=0;i<M;i++)vector[i]=(bool)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bvector=(bool*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*copy vector: */
+				vector=xNew<bool>(M);
+				memcpy(vector,bvector,(M)*sizeof(bool));
+			}
+
+			else
+				_error_("unrecognized bool pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
+		}
+		else
+			vector=NULL;
+	}
+
+	else {
+		M=1;
+		vector=xNew<bool>(M);
+		FetchData(&(vector[0]),py_vector);
+	}
+
+	/*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->random,PyDict_GetItemString(py_dict,"random"));
+	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 << "\".");
+
+		_printf0_("FetchData for Options not implemented yet, ignoring option \"" << name << "\"!\n");
+
+//		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(Contours** pcontours,PyObject* py_list){{{*/
+void FetchData(Contours** pcontours,PyObject* py_list){
+
+	int              numcontours,test1,test2;
+	char            *contourname = NULL;
+	Contours         *contours    = NULL;
+	Contour<double> *contouri    = NULL;
+	PyObject        *py_dicti    = NULL;
+	PyObject        *py_item     = NULL;
+
+	if (PyString_Check(py_list)){
+		FetchData(&contourname,py_list);
+		contours=ExpRead<double>(contourname);
+	}
+	else if(PyList_Check(py_list)){
+
+		contours=new Contours();
+		numcontours=(int)PyList_Size(py_list);
+
+		for(int i=0;i<numcontours;i++){
+
+			contouri=new Contour<double>();
+			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/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/WritePythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/WritePythonData.cpp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/WritePythonData.cpp	(revision 18231)
@@ -0,0 +1,292 @@
+/* \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/shared/shared.h"
+#include "../../c/shared/Enum/Enum.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, int* matrix, int M, int N){{{*/
+void WriteData(PyObject* tuple, int index, int* matrix, int M,int N){
+
+	npy_intp dims[2]={0,0};
+	PyObject* array=NULL;
+
+	/*intermediary:*/
+	long* lmatrix=NULL;
+	int i;
+
+	/*transform into long matrix: */
+	lmatrix=xNew<long>(M*N);
+	for(i=0;i<M*N;i++)lmatrix[i]=(long)matrix[i];
+
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_INT64,lmatrix);
+
+	PyTuple_SetItem(tuple, index, array);
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, bool* matrix, int M, int N){{{*/
+void WriteData(PyObject* tuple, int index, bool* 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_BOOL,matrix);
+
+	PyTuple_SetItem(tuple, index, array);
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, double* vector, int M){{{*/
+void WriteData(PyObject* py_tuple, int index, double* vector, int M){
+
+	double   *buffer = NULL;
+	npy_intp  dim   = 10;
+	PyObject *array = NULL;
+
+	/*Copy vector*/
+	buffer=xNew<double>(M);
+	for(int i=0;i<M;i++)buffer[i]=vector[i];
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,buffer);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, int* vector, int M){{{*/
+void WriteData(PyObject* py_tuple, int index, int* vector, int M){
+
+	long* lvector=NULL;
+	npy_intp dim=10;
+	PyObject* array=NULL;
+
+	/*transform into long matrix: */
+	lvector=xNew<long>(M);
+	for(int i=0;i<M;i++)lvector[i]=(long)vector[i];
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_INT64,lvector);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index){{{*/
+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,IssmDenseMat<double>* matrix){{{*/
+void WriteData(PyObject* py_tuple,int index,IssmDenseMat<double>* matrix){
+
+	int M,N;
+	double* buffer=NULL;
+	npy_intp dims[2]={0,0};
+	PyObject* array=NULL;
+
+	matrix->GetSize(&M,&N);
+	buffer=matrix->ToSerial();
+
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,buffer);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,IssmSeqVec<double>* vector){{{*/
+void WriteData(PyObject* py_tuple,int index,IssmSeqVec<double>* vector){
+
+	int M;
+	double* buffer=NULL;
+	npy_intp dim=10;
+	PyObject* array=NULL;
+
+	vector->GetSize(&M);
+	buffer=vector->ToMPISerial();
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_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);
+}
+/*}}}*/
+/*FUNCTION PyArrayFromCopiedData(int dimi,int dimj,int* data){{{*/
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,int* data){
+
+	long* 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<long>(dimi*dimj);
+	for(int i=0;i<dimi*dimj;i++) pydata[i]=(long)data[i];
+	return PyArray_SimpleNewFromData(2,pydims,NPY_INT64,pydata);
+}
+/*}}}*/
+/*FUNCTION PyArrayFromCopiedData(int dimi,int dimj,bool* data){{{*/
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,bool* data){
+
+	bool* 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<bool>(dimi*dimj);
+	memcpy(pydata,data,dimi*dimj*sizeof(bool));
+	return PyArray_SimpleNewFromData(2,pydims,NPY_BOOL,pydata);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/pythonio.h
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/pythonio.h	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/src/wrappers/python/io/pythonio.h	(revision 18231)
@@ -0,0 +1,60 @@
+/*\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/bamg/bamgobjects.h"
+#include "../../c/classes/classes.h"
+#include "../../c/shared/shared.h"
+
+void WriteData(PyObject* py_tuple,int index, double* matrix, int M,int N);
+void WriteData(PyObject* py_tuple,int index, int* matrix, int M,int N);
+void WriteData(PyObject* py_tuple,int index, bool* matrix, int M,int N);
+void WriteData(PyObject* py_tuple,int index, int integer);
+void WriteData(PyObject* py_tuple,int index, double* vector, int M);
+void WriteData(PyObject* py_tuple,int index, int* vector, int M);
+void WriteData(PyObject* py_tuple,int index, char* string);
+void WriteData(PyObject* py_tuple,int index);
+void WriteData(PyObject* py_tuple,int index, IssmDenseMat<double>* matrix);
+void WriteData(PyObject* py_tuple,int index, IssmSeqVec<double>* vector);
+void WriteData(PyObject* py_tuple,int index, BamgGeom* bamggeom);
+void WriteData(PyObject* py_tuple,int index, BamgMesh* bamgmesh);
+void WriteData(PyObject* py_tuple,int index, RiftStruct* riftstruct);
+
+void FetchData(double** pmatrix,int* pM,int *pN,PyObject* py_array);
+void FetchData(int** pmatrix,int* pM,int *pN,PyObject* py_matrix);
+void FetchData(bool** pmatrix,int* pM,int *pN,PyObject* py_matrix);
+void FetchData(double** pvector,int* pM,PyObject* py_ref);
+void FetchData(int** pvector,int* pM,PyObject* py_ref);
+void FetchData(bool** pvector,int* pM,PyObject* py_ref);
+void FetchData(char** pstring,PyObject* py_unicode);
+void FetchData(double* pscalar,PyObject* py_float);
+void FetchData(int* pscalar,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(Contours** 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);
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,int* data);
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,bool* data);
+
+/*Print*/
+void ApiPrintf(const char* string);
+
+#endif	/* _IO_H_ */
Index: /issm/branches/trunk-jpl-ad2-integrated/svnversion
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/svnversion	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/svnversion	(revision 18231)
@@ -0,0 +1,1 @@
+18214
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Data/convertmattonc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Data/convertmattonc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Data/convertmattonc.m	(revision 18231)
@@ -0,0 +1,50 @@
+function []=convertmattonc(matfile,ncfile);
+%    convertmattonc -- function to convert mat-format file to nc-format file
+%
+%    usage:
+%        convertmattonc(matfile,ncfile);
+%    where:
+%        matfile    name of mat-format file
+%        ncfile     name of nc-format file (optional)
+%
+
+	if ~exist('matfile','var') || isempty(matfile)
+		help convertmattonc
+		error('convertmattonc usage error.');
+	end
+
+	[pathstr,name,ext]=fileparts(matfile);
+	if isempty(ext)
+		ext='.mat';
+	end
+	matfile=fullfile(pathstr,[name ext]);
+
+	if ~exist('ncfile','var') || isempty(ncfile)
+		ncfile=fullfile(pathstr,[name '.nc']);
+	end
+
+	if exist(ncfile,'file')
+		delete(ncfile);
+	end
+
+	a=load(matfile,'-mat');
+	disp(sprintf('mat-format file ''%s'' read.',matfile));
+	fnames=fieldnames(a);
+
+	for i=1:length(fnames)
+		if isstruct(a.(fnames{i})) || iscell(a.(fnames{i}))
+			warning('field ''%s'' is of class ''%s'' and will not be written.',fnames{i},class(a.(fnames{i})));
+		else
+			% matlab writes the dimensions reversed and matrices transposed into netcdf, so compensate for that
+			nccreate(ncfile,fnames{i},...
+                     'Dimensions',{[fnames{i} '_2'] size(a.(fnames{i}),2) [fnames{i} '_1'] size(a.(fnames{i}),1)},...
+                     'Format','classic');
+			ncwrite(ncfile,fnames{i},transpose(a.(fnames{i})));
+			disp(sprintf('field ''%s'' of class ''%s'' and size [%dx%d] written.',...
+			             fnames{i},class(a.(fnames{i})),size(a.(fnames{i}),1),size(a.(fnames{i}),2)));
+		end
+	end
+	disp(sprintf('nc-format  file ''%s'' written.',ncfile));
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Data/delta18o.data
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Data/delta18o.data	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Data/delta18o.data	(revision 18231)
@@ -0,0 +1,2 @@
+  -3.9010000e-02  -3.9180000e-02  -3.9280000e-02  -3.9320000e-02  -3.9050000e-02  -3.8880000e-02  -3.8680000e-02  -3.8560000e-02  -3.8500000e-02  -3.8520000e-02  -3.8560000e-02
+   0.0000000e+00   2.0000000e+01   4.0000000e+01   6.0000000e+01   8.0000000e+01   1.0000000e+02   1.2000000e+02   1.4000000e+02   1.6000000e+02   1.8000000e+02   2.0000000e+02
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Data/loadnc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Data/loadnc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Data/loadnc.m	(revision 18231)
@@ -0,0 +1,32 @@
+function [s]=loadnc(ncfile);
+%    loadnc -- function to read the variables from an nc-format file
+%
+%    usage:
+%        s=loadnc(ncfile);
+%    where:
+%        ncfile     name of nc-format file
+%
+
+	if ~exist('ncfile','var') || isempty(ncfile)
+		help loadnc
+		error('loadnc usage error.');
+	end
+
+	[pathstr,name,ext]=fileparts(ncfile);
+	if isempty(ext)
+		ext='.nc';
+	end
+	ncfile=fullfile(pathstr,[name ext]);
+
+	a=ncinfo(ncfile);
+	disp(sprintf('nc-format file ''%s'' read.',ncfile));
+
+	for i=1:length(a.Variables)
+		% matlab reads the dimensions reversed and matrices transposed from netcdf, so compensate for that
+		s.(a.Variables(i).Name)=transpose(ncread(ncfile,a.Variables(i).Name));
+		disp(sprintf('field ''%s'' of class ''%s'' and size [%dx%d] read.',...
+		             a.Variables(i).Name,class(s.(a.Variables(i).Name)),size(s.(a.Variables(i).Name),1),size(s.(a.Variables(i).Name),2)));
+	end
+
+end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79North.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79North.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79North.exp	(revision 18231)
@@ -0,0 +1,24 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count Value
+18 1.000000
+# X pos Y pos
+464009.1397656691 -1027407.4008438819
+434858.8796422836 -1057322.8251592305
+420709.3008232680 -1062000.9573566925
+409964.1319456697 -1051906.0405095378
+408368.3147856303 -1063478.2622611541
+403368.0876841737 -1083544.9872134251
+426135.0791674018 -1101272.6460669651
+444221.0069811812 -1107551.1919109272
+462838.8738483069 -1083298.7697293481
+451455.3781066929 -1081082.8123726556
+474328.7574005903 -1040333.8187579215
+490074.1533796453 -1041072.4712101523
+491111.0844876733 -1038645.7820016426
+489754.9899476374 -1026299.4221655356
+477094.8404779918 -1020390.2025476890
+471001.4291198556 -1014587.7884811594
+468158.2643817714 -1015096.5266400346
+464009.1397656691 -1027407.4008438819
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79NorthShelf.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79NorthShelf.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/79NorthShelf.exp	(revision 18231)
@@ -0,0 +1,13 @@
+## Name:IceShelf
+## Icon:0
+# Points Count Value
+7 1.000000
+# X pos Y pos
+434007.7771569293 -1056707.2814490383
+452306.4805920472 -1080467.2686624634
+493584.9511317319 -1048458.9957324605
+496457.4220198027 -1015096.5266400346
+460179.1785815747 -1009310.4157642265
+441667.6995251182 -1023714.1385827276
+434007.7771569293 -1056707.2814490383
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/CrossLineEISMINT.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/CrossLineEISMINT.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/CrossLineEISMINT.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+10000 199999 
+10000 1
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP10000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP10000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP10000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 2500
+10000 2500
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP100000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP100000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP100000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 50000
+100000 50000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP160000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP160000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP160000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 40000
+160000 40000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP20000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP20000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP20000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 5000
+20000 5000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP40000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP40000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP40000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 10000
+40000 10000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP5000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP5000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP5000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 1225
+5000 1225
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP80000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP80000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIP80000.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 20000
+80000 20000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIPE.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIPE.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/ISMIPE.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+5 0 
+5 5000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux1.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux1.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux1.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:MassFlux1
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+200000 400000
+500000 800000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux2.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux2.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux2.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:MassFlux2
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+500000 800000
+800000 400000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux3.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux3.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux3.exp	(revision 18231)
@@ -0,0 +1,7 @@
+## Name:MassFlux3
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+200000 400000
+800000 400000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux4.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux4.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux4.exp	(revision 18231)
@@ -0,0 +1,17 @@
+## Name:circle
+## Icon:0
+# Points Count Value
+11 1.000000
+# X pos Y pos
+800000.0000000000 500000.0000000000
+742705.0983124842 676335.5756877420
+592705.0983124842 785316.9548885461
+407294.9016875158 785316.9548885461
+257294.9016875158 676335.5756877420
+200000.0000000000 500000.0000000001
+257294.9016875158 323664.4243122581
+407294.9016875157 214683.0451114539
+592705.0983124842 214683.0451114539
+742705.0983124842 323664.4243122580
+800000.0000000000 500000.0000000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux5.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux5.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux5.exp	(revision 18231)
@@ -0,0 +1,107 @@
+## Name:circle
+## Icon:0
+# Points Count Value
+101 1.000000
+# X pos Y pos
+700000.0000000000 500000.0000000000
+699605.3456856543 512558.1039058627
+698422.9402628955 525066.6467128609
+696457.4501457377 537476.2629171449
+693716.6322257263 549737.9774329710
+690211.3032590307 561803.3988749895
+685955.2971776503 573624.9105369356
+680965.4104932039 585155.8583130145
+675261.3360087727 596350.7348203431
+668865.5851004031 607165.3589957993
+661803.3988749895 617557.0504584946
+654102.6485551578 627484.7979497380
+645793.7254842822 636909.4211857377
+636909.4211857377 645793.7254842822
+627484.7979497379 654102.6485551578
+617557.0504584946 661803.3988749895
+607165.3589957993 668865.5851004031
+596350.7348203431 675261.3360087727
+585155.8583130145 680965.4104932039
+573624.9105369356 685955.2971776503
+561803.3988749895 690211.3032590307
+549737.9774329709 693716.6322257263
+537476.2629171449 696457.4501457377
+525066.6467128609 698422.9402628955
+512558.1039058627 699605.3456856543
+499999.9999999999 700000.0000000000
+487441.8960941373 699605.3456856543
+474933.3532871392 698422.9402628955
+462523.7370828550 696457.4501457377
+450262.0225670291 693716.6322257263
+438196.6011250105 690211.3032590307
+426375.0894630644 685955.2971776503
+414844.1416869854 680965.4104932039
+403649.2651796569 675261.3360087727
+392834.6410042006 668865.5851004031
+382442.9495415054 661803.3988749895
+372515.2020502621 654102.6485551578
+363090.5788142623 645793.7254842822
+354206.2745157176 636909.4211857377
+345897.3514448421 627484.7979497379
+338196.6011250105 617557.0504584947
+331134.4148995969 607165.3589957993
+324738.6639912273 596350.7348203431
+319034.5895067961 585155.8583130145
+314044.7028223497 573624.9105369356
+309788.6967409693 561803.3988749895
+306283.3677742738 549737.9774329710
+303542.5498542623 537476.2629171449
+301577.0597371045 525066.6467128608
+300394.6543143457 512558.1039058626
+300000.0000000000 500000.0000000000
+300394.6543143457 487441.8960941373
+301577.0597371045 474933.3532871392
+303542.5498542623 462523.7370828551
+306283.3677742737 450262.0225670291
+309788.6967409693 438196.6011250105
+314044.7028223497 426375.0894630644
+319034.5895067961 414844.1416869855
+324738.6639912273 403649.2651796569
+331134.4148995970 392834.6410042007
+338196.6011250105 382442.9495415054
+345897.3514448422 372515.2020502621
+354206.2745157177 363090.5788142623
+363090.5788142623 354206.2745157177
+372515.2020502621 345897.3514448421
+382442.9495415054 338196.6011250105
+392834.6410042006 331134.4148995971
+403649.2651796569 324738.6639912273
+414844.1416869856 319034.5895067960
+426375.0894630644 314044.7028223497
+438196.6011250105 309788.6967409693
+450262.0225670289 306283.3677742738
+462523.7370828551 303542.5498542623
+474933.3532871393 301577.0597371045
+487441.8960941373 300394.6543143457
+499999.9999999999 300000.0000000000
+512558.1039058627 300394.6543143457
+525066.6467128608 301577.0597371045
+537476.2629171450 303542.5498542623
+549737.9774329710 306283.3677742738
+561803.3988749895 309788.6967409693
+573624.9105369357 314044.7028223497
+585155.8583130145 319034.5895067961
+596350.7348203431 324738.6639912273
+607165.3589957993 331134.4148995970
+617557.0504584946 338196.6011250105
+627484.7979497380 345897.3514448422
+636909.4211857377 354206.2745157177
+645793.7254842824 363090.5788142623
+654102.6485551579 372515.2020502621
+661803.3988749895 382442.9495415053
+668865.5851004031 392834.6410042007
+675261.3360087727 403649.2651796569
+680965.4104932039 414844.1416869856
+685955.2971776503 426375.0894630644
+690211.3032590307 438196.6011250105
+693716.6322257263 450262.0225670291
+696457.4501457377 462523.7370828551
+698422.9402628955 474933.3532871393
+699605.3456856543 487441.8960941373
+700000.0000000000 500000.0000000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux6.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux6.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/MassFlux6.exp	(revision 18231)
@@ -0,0 +1,507 @@
+## Name:circle
+## Icon:0
+# Points Count Value
+501 1.000000
+# X pos Y pos
+900000.0000000000 500000.0000000000
+899968.4176815264 505026.4159533411
+899873.6757133200 510052.0381773350
+899715.7890562357 515076.0730679738
+899494.7826424070 520097.7272719078
+899210.6913713086 525116.2078117253
+898863.5601042456 530130.7222111730
+898453.4436572690 535140.4786202973
+897980.4067925201 540144.6859404859
+897444.5242080034 545142.5539493926
+896845.8805257911 550133.2934257217
+896184.5702786604 555116.1162738552
+895460.6978951656 560090.2356483028
+894674.3776831472 565054.8660779535
+893825.7338116821 570009.2235901104
+892914.9002914755 574952.5258342898
+891942.0209536988 579883.9922057628
+890907.2494272774 584802.8439688219
+889810.7491146309 589708.3043797525
+888652.6931658696 594599.5988094899
+887433.2644514524 599475.9548659419
+886152.6555333096 604336.6025159587
+884811.0686344344 609180.7742069301
+883408.7156069503 614007.7049879904
+881945.8178986572 618816.6326308140
+880422.6065180614 623606.7977499790
+878839.3219978977 628377.4439228838
+877196.2143571458 633127.8178091947
+875493.5430615495 637857.1692698068
+873731.5769826449 642564.7514853003
+871910.5943553005 647249.8210738712
+870030.8827337832 651911.6382087205
+868092.7389463482 656549.4667348809
+866096.4690483670 661162.5742854651
+864042.3882739983 665750.2323973137
+861930.8209864078 670311.7166260290
+859762.1006265484 674846.3066603731
+857536.5696605055 679353.2864360129
+855254.5795254178 683831.9442485952
+852916.4905739813 688281.5728661331
+850522.6720175454 692701.4696406862
+848073.5018678103 697090.9366193167
+845569.3668771342 701449.2806543043
+843010.6624774609 705775.8135126026
+840397.7927178767 710069.8519845183
+837731.1702008061 714330.7179915986
+835011.2160168567 718557.7386937076
+832238.3596783250 722750.2465952751
+829413.0390513709 726907.5796507027
+826535.7002868736 731029.0813689070
+823606.7977499790 735114.1009169893
+820626.7939483507 739161.9932230075
+817596.1594591341 743172.1190778422
+814515.3728546476 747143.8452361338
+811384.9206268094 751076.5445162802
+808205.2971103156 754969.5958994759
+804977.0044045792 758822.3846277777
+801700.5522944415 762634.3023011826
+798376.4581696729 766404.7469737006
+795005.2469432696 770133.1232484097
+791587.4509685646 773818.8423714754
+788123.6099551627 777461.3223251220
+784614.2708837141 781059.9879195397
+781059.9879195397 784614.2708837141
+777461.3223251220 788123.6099551627
+773818.8423714754 791587.4509685646
+770133.1232484097 795005.2469432696
+766404.7469737006 798376.4581696729
+762634.3023011826 801700.5522944415
+758822.3846277777 804977.0044045792
+754969.5958994759 808205.2971103156
+751076.5445162802 811384.9206268094
+747143.8452361338 814515.3728546476
+743172.1190778422 817596.1594591341
+739161.9932230075 820626.7939483506
+735114.1009169891 823606.7977499790
+731029.0813689070 826535.7002868736
+726907.5796507025 829413.0390513709
+722750.2465952751 832238.3596783250
+718557.7386937076 835011.2160168567
+714330.7179915986 837731.1702008061
+710069.8519845183 840397.7927178767
+705775.8135126026 843010.6624774609
+701449.2806543044 845569.3668771342
+697090.9366193167 848073.5018678103
+692701.4696406862 850522.6720175454
+688281.5728661331 852916.4905739813
+683831.9442485950 855254.5795254179
+679353.2864360129 857536.5696605055
+674846.3066603731 859762.1006265484
+670311.7166260290 861930.8209864078
+665750.2323973136 864042.3882739983
+661162.5742854651 866096.4690483670
+656549.4667348809 868092.7389463482
+651911.6382087205 870030.8827337832
+647249.8210738711 871910.5943553005
+642564.7514853003 873731.5769826449
+637857.1692698068 875493.5430615495
+633127.8178091947 877196.2143571458
+628377.4439228838 878839.3219978977
+623606.7977499790 880422.6065180614
+618816.6326308140 881945.8178986572
+614007.7049879904 883408.7156069503
+609180.7742069301 884811.0686344344
+604336.6025159588 886152.6555333096
+599475.9548659419 887433.2644514524
+594599.5988094899 888652.6931658696
+589708.3043797525 889810.7491146309
+584802.8439688218 890907.2494272774
+579883.9922057628 891942.0209536988
+574952.5258342898 892914.9002914755
+570009.2235901104 893825.7338116821
+565054.8660779534 894674.3776831472
+560090.2356483028 895460.6978951656
+555116.1162738552 896184.5702786604
+550133.2934257217 896845.8805257911
+545142.5539493926 897444.5242080034
+540144.6859404859 897980.4067925201
+535140.4786202973 898453.4436572690
+530130.7222111732 898863.5601042456
+525116.2078117253 899210.6913713086
+520097.7272719078 899494.7826424070
+515076.0730679738 899715.7890562357
+510052.0381773350 899873.6757133200
+505026.4159533410 899968.4176815264
+500000.0000000000 900000.0000000000
+494973.5840466589 899968.4176815264
+489947.9618226651 899873.6757133200
+484923.9269320262 899715.7890562357
+479902.2727280921 899494.7826424070
+474883.7921882746 899210.6913713086
+469869.2777888268 898863.5601042456
+464859.5213797027 898453.4436572690
+459855.3140595140 897980.4067925201
+454857.4460506073 897444.5242080034
+449866.7065742782 896845.8805257911
+444883.8837261448 896184.5702786604
+439909.7643516972 895460.6978951655
+434945.1339220466 894674.3776831472
+429990.7764098896 893825.7338116821
+425047.4741657102 892914.9002914755
+420116.0077942372 891942.0209536988
+415197.1560311782 890907.2494272774
+410291.6956202475 889810.7491146309
+405400.4011905101 888652.6931658696
+400524.0451340580 887433.2644514524
+395663.3974840412 886152.6555333096
+390819.2257930699 884811.0686344344
+385992.2950120096 883408.7156069505
+381183.3673691860 881945.8178986572
+376393.2022500210 880422.6065180614
+371622.5560771162 878839.3219978977
+366872.1821908053 877196.2143571458
+362142.8307301932 875493.5430615495
+357435.2485146997 873731.5769826449
+352750.1789261288 871910.5943553005
+348088.3617912795 870030.8827337832
+343450.5332651191 868092.7389463482
+338837.4257145349 866096.4690483670
+334249.7676026863 864042.3882739983
+329688.2833739709 861930.8209864078
+325153.6933396268 859762.1006265484
+320646.7135639872 857536.5696605055
+316168.0557514048 855254.5795254179
+311718.4271338669 852916.4905739813
+307298.5303593138 850522.6720175454
+302909.0633806834 848073.5018678103
+298550.7193456957 845569.3668771342
+294224.1864873974 843010.6624774609
+289930.1480154817 840397.7927178766
+285669.2820084015 837731.1702008061
+281442.2613062924 835011.2160168567
+277249.7534047248 832238.3596783250
+273092.4203492973 829413.0390513709
+268970.9186310929 826535.7002868736
+264885.8990830108 823606.7977499790
+260838.0067769924 820626.7939483506
+256827.8809221578 817596.1594591341
+252856.1547638662 814515.3728546475
+248923.4554837199 811384.9206268094
+245030.4041005241 808205.2971103156
+241177.6153722222 804977.0044045791
+237365.6976988174 801700.5522944415
+233595.2530262994 798376.4581696729
+229866.8767515902 795005.2469432696
+226181.1576285245 791587.4509685646
+222538.6776748779 788123.6099551627
+218940.0120804604 784614.2708837142
+215385.7291162859 781059.9879195397
+211876.3900448372 777461.3223251220
+208412.5490314353 773818.8423714754
+204994.7530567305 770133.1232484098
+201623.5418303271 766404.7469737006
+198299.4477055584 762634.3023011826
+195022.9955954208 758822.3846277777
+191794.7028896842 754969.5958994757
+188615.0793731906 751076.5445162803
+185484.6271453524 747143.8452361338
+182403.8405408658 743172.1190778421
+179373.2060516493 739161.9932230075
+176393.2022500210 735114.1009169893
+173464.2997131264 731029.0813689071
+170586.9609486290 726907.5796507025
+167761.6403216749 722750.2465952751
+164988.7839831433 718557.7386937076
+162268.8297991939 714330.7179915986
+159602.2072821232 710069.8519845182
+156989.3375225391 705775.8135126026
+154430.6331228659 701449.2806543044
+151926.4981321897 697090.9366193167
+149477.3279824546 692701.4696406861
+147083.5094260186 688281.5728661329
+144745.4204745822 683831.9442485952
+142463.4303394945 679353.2864360129
+140237.8993734516 674846.3066603731
+138069.1790135922 670311.7166260290
+135957.6117260017 665750.2323973136
+133903.5309516330 661162.5742854651
+131907.2610536519 656549.4667348809
+129969.1172662167 651911.6382087204
+128089.4056446994 647249.8210738711
+126268.4230173552 642564.7514853003
+124506.4569384504 637857.1692698068
+122803.7856428542 633127.8178091946
+121160.6780021022 628377.4439228837
+119577.3934819386 623606.7977499790
+118054.1821013428 618816.6326308140
+116591.2843930496 614007.7049879904
+115188.9313655656 609180.7742069301
+113847.3444666904 604336.6025159588
+112566.7355485476 599475.9548659419
+111347.3068341304 594599.5988094899
+110189.2508853691 589708.3043797524
+109092.7505727226 584802.8439688219
+108057.9790463013 579883.9922057628
+107085.0997085245 574952.5258342898
+106174.2661883179 570009.2235901103
+105325.6223168527 565054.8660779534
+104539.3021048344 560090.2356483028
+103815.4297213395 555116.1162738552
+103154.1194742089 550133.2934257216
+102555.4757919966 545142.5539493926
+102019.5932074799 540144.6859404860
+101546.5563427310 535140.4786202973
+101136.4398957544 530130.7222111730
+100789.3086286914 525116.2078117252
+100505.2173575930 520097.7272719078
+100284.2109437643 515076.0730679738
+100126.3242866800 510052.0381773349
+100031.5823184735 505026.4159533409
+100000.0000000000 500000.0000000002
+100031.5823184735 494973.5840466591
+100126.3242866800 489947.9618226651
+100284.2109437643 484923.9269320263
+100505.2173575929 479902.2727280924
+100789.3086286914 474883.7921882748
+101136.4398957544 469869.2777888271
+101546.5563427310 464859.5213797028
+102019.5932074799 459855.3140595143
+102555.4757919966 454857.4460506075
+103154.1194742089 449866.7065742785
+103815.4297213395 444883.8837261449
+104539.3021048344 439909.7643516974
+105325.6223168527 434945.1339220467
+106174.2661883179 429990.7764098897
+107085.0997085245 425047.4741657103
+108057.9790463013 420116.0077942373
+109092.7505727226 415197.1560311784
+110189.2508853691 410291.6956202477
+111347.3068341304 405400.4011905103
+112566.7355485475 400524.0451340582
+113847.3444666904 395663.3974840415
+115188.9313655656 390819.2257930701
+116591.2843930496 385992.2950120097
+118054.1821013428 381183.3673691861
+119577.3934819385 376393.2022500213
+121160.6780021022 371622.5560771164
+122803.7856428542 366872.1821908055
+124506.4569384503 362142.8307301933
+126268.4230173551 357435.2485147000
+128089.4056446993 352750.1789261290
+129969.1172662167 348088.3617912797
+131907.2610536518 343450.5332651191
+133903.5309516328 338837.4257145352
+135957.6117260017 334249.7676026865
+138069.1790135921 329688.2833739711
+140237.8993734515 325153.6933396269
+142463.4303394944 320646.7135639872
+144745.4204745821 316168.0557514051
+147083.5094260186 311718.4271338672
+149477.3279824545 307298.5303593140
+151926.4981321897 302909.0633806834
+154430.6331228658 298550.7193456959
+156989.3375225390 294224.1864873975
+159602.2072821232 289930.1480154819
+162268.8297991939 285669.2820084015
+164988.7839831432 281442.2613062926
+167761.6403216748 277249.7534047250
+170586.9609486290 273092.4203492975
+173464.2997131264 268970.9186310930
+176393.2022500209 264885.8990830109
+179373.2060516492 260838.0067769926
+182403.8405408658 256827.8809221580
+185484.6271453524 252856.1547638664
+188615.0793731905 248923.4554837200
+191794.7028896842 245030.4041005243
+195022.9955954208 241177.6153722224
+198299.4477055584 237365.6976988175
+201623.5418303271 233595.2530262994
+204994.7530567303 229866.8767515904
+208412.5490314353 226181.1576285246
+211876.3900448372 222538.6776748781
+215385.7291162858 218940.0120804604
+218940.0120804601 215385.7291162860
+222538.6776748779 211876.3900448374
+226181.1576285244 208412.5490314355
+229866.8767515902 204994.7530567305
+233595.2530262992 201623.5418303273
+237365.6976988173 198299.4477055586
+241177.6153722220 195022.9955954211
+245030.4041005242 191794.7028896842
+248923.4554837196 188615.0793731908
+252856.1547638661 185484.6271453525
+256827.8809221577 182403.8405408660
+260838.0067769924 179373.2060516494
+264885.8990830107 176393.2022500210
+268970.9186310926 173464.2997131267
+273092.4203492975 170586.9609486290
+277249.7534047245 167761.6403216751
+281442.2613062924 164988.7839831432
+285669.2820084011 162268.8297991941
+289930.1480154816 159602.2072821233
+294224.1864873973 156989.3375225391
+298550.7193456956 154430.6331228659
+302909.0633806833 151926.4981321898
+307298.5303593136 149477.3279824547
+311718.4271338671 147083.5094260186
+316168.0557514046 144745.4204745823
+320646.7135639869 142463.4303394946
+325153.6933396267 140237.8993734517
+329688.2833739708 138069.1790135922
+334249.7676026862 135957.6117260018
+338837.4257145349 133903.5309516330
+343450.5332651191 131907.2610536519
+348088.3617912793 129969.1172662169
+352750.1789261285 128089.4056446995
+357435.2485146995 126268.4230173553
+362142.8307301930 124506.4569384504
+366872.1821908052 122803.7856428543
+371622.5560771161 121160.6780021023
+376393.2022500210 119577.3934819386
+381183.3673691860 118054.1821013428
+385992.2950120096 116591.2843930496
+390819.2257930696 115188.9313655657
+395663.3974840410 113847.3444666906
+400524.0451340579 112566.7355485476
+405400.4011905100 111347.3068341304
+410291.6956202474 110189.2508853691
+415197.1560311781 109092.7505727226
+420116.0077942372 108057.9790463013
+425047.4741657098 107085.0997085246
+429990.7764098896 106174.2661883179
+434945.1339220463 105325.6223168529
+439909.7643516969 104539.3021048344
+444883.8837261446 103815.4297213395
+449866.7065742782 103154.1194742089
+454857.4460506073 102555.4757919966
+459855.3140595140 102019.5932074799
+464859.5213797027 101546.5563427310
+469869.2777888266 101136.4398957544
+474883.7921882744 100789.3086286914
+479902.2727280919 100505.2173575930
+484923.9269320260 100284.2109437643
+489947.9618226648 100126.3242866800
+494973.5840466588 100031.5823184735
+499999.9999999999 100000.0000000000
+505026.4159533410 100031.5823184735
+510052.0381773350 100126.3242866800
+515076.0730679735 100284.2109437643
+520097.7272719076 100505.2173575929
+525116.2078117251 100789.3086286914
+530130.7222111729 101136.4398957544
+535140.4786202972 101546.5563427310
+540144.6859404859 102019.5932074799
+545142.5539493926 102555.4757919966
+550133.2934257213 103154.1194742088
+555116.1162738553 103815.4297213395
+560090.2356483026 104539.3021048344
+565054.8660779533 105325.6223168527
+570009.2235901102 106174.2661883179
+574952.5258342897 107085.0997085245
+579883.9922057627 108057.9790463013
+584802.8439688218 109092.7505727226
+589708.3043797525 110189.2508853691
+594599.5988094895 111347.3068341304
+599475.9548659420 112566.7355485476
+604336.6025159585 113847.3444666904
+609180.7742069298 115188.9313655656
+614007.7049879903 116591.2843930496
+618816.6326308139 118054.1821013428
+623606.7977499790 119577.3934819385
+628377.4439228838 121160.6780021022
+633127.8178091947 122803.7856428542
+637857.1692698065 124506.4569384502
+642564.7514853000 126268.4230173551
+647249.8210738710 128089.4056446993
+651911.6382087203 129969.1172662167
+656549.4667348808 131907.2610536518
+661162.5742854651 133903.5309516329
+665750.2323973136 135957.6117260017
+670311.7166260288 138069.1790135920
+674846.3066603732 140237.8993734516
+679353.2864360127 142463.4303394944
+683831.9442485949 144745.4204745821
+688281.5728661328 147083.5094260186
+692701.4696406859 149477.3279824545
+697090.9366193166 151926.4981321897
+701449.2806543043 154430.6331228659
+705775.8135126026 156989.3375225391
+710069.8519845180 159602.2072821231
+714330.7179915984 162268.8297991938
+718557.7386937074 164988.7839831432
+722750.2465952750 167761.6403216748
+726907.5796507024 170586.9609486290
+731029.0813689069 173464.2997131263
+735114.1009169891 176393.2022500210
+739161.9932230075 179373.2060516494
+743172.1190778422 182403.8405408658
+747143.8452361336 185484.6271453522
+751076.5445162799 188615.0793731905
+754969.5958994757 191794.7028896842
+758822.3846277776 195022.9955954208
+762634.3023011824 198299.4477055584
+766404.7469737006 201623.5418303271
+770133.1232484097 204994.7530567304
+773818.8423714754 208412.5490314354
+777461.3223251221 211876.3900448373
+781059.9879195394 215385.7291162857
+784614.2708837140 218940.0120804601
+788123.6099551626 222538.6776748779
+791587.4509685645 226181.1576285244
+795005.2469432695 229866.8767515901
+798376.4581696729 233595.2530262993
+801700.5522944415 237365.6976988174
+804977.0044045789 241177.6153722220
+808205.2971103155 245030.4041005239
+811384.9206268091 248923.4554837196
+814515.3728546475 252856.1547638661
+817596.1594591341 256827.8809221577
+820626.7939483506 260838.0067769923
+823606.7977499790 264885.8990830106
+826535.7002868736 268970.9186310929
+829413.0390513709 273092.4203492974
+832238.3596783249 277249.7534047245
+835011.2160168565 281442.2613062921
+837731.1702008059 285669.2820084011
+840397.7927178766 289930.1480154815
+843010.6624774609 294224.1864873973
+845569.3668771341 298550.7193456956
+848073.5018678103 302909.0633806833
+850522.6720175454 307298.5303593139
+852916.4905739813 311718.4271338670
+855254.5795254176 316168.0557514046
+857536.5696605054 320646.7135639869
+859762.1006265483 325153.6933396267
+861930.8209864078 329688.2833739708
+864042.3882739982 334249.7676026862
+866096.4690483670 338837.4257145348
+868092.7389463481 343450.5332651190
+870030.8827337832 348088.3617912795
+871910.5943553005 352750.1789261285
+873731.5769826447 357435.2485146995
+875493.5430615495 362142.8307301929
+877196.2143571457 366872.1821908052
+878839.3219978977 371622.5560771161
+880422.6065180614 376393.2022500209
+881945.8178986572 381183.3673691860
+883408.7156069503 385992.2950120096
+884811.0686344344 390819.2257930696
+886152.6555333094 395663.3974840409
+887433.2644514524 400524.0451340579
+888652.6931658696 405400.4011905100
+889810.7491146307 410291.6956202474
+890907.2494272774 415197.1560311780
+891942.0209536988 420116.0077942371
+892914.9002914755 425047.4741657102
+893825.7338116821 429990.7764098896
+894674.3776831471 434945.1339220463
+895460.6978951655 439909.7643516969
+896184.5702786604 444883.8837261446
+896845.8805257911 449866.7065742781
+897444.5242080034 454857.4460506072
+897980.4067925201 459855.3140595140
+898453.4436572690 464859.5213797027
+898863.5601042456 469869.2777888269
+899210.6913713086 474883.7921882743
+899494.7826424070 479902.2727280919
+899715.7890562357 484923.9269320259
+899873.6757133200 489947.9618226648
+899968.4176815264 494973.5840466588
+900000.0000000000 500000.0000000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Pig.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Pig.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Pig.exp	(revision 18231)
@@ -0,0 +1,14 @@
+## Name:Pig
+## Icon:0
+# Points Count Value
+8 1.000000
+# X pos Y pos
+-1630726.5154549279 -324668.7721082006
+-1596284.8605673832 -324668.7721082006
+-1538422.8803563081 -314529.3627584913
+-1512247.2226417740 -243553.4973105265
+-1556332.5408978313 -148496.5346570023
+-1611439.1887179029 -151031.3869944296
+-1670678.8351244798 -235948.9402982446
+-1630726.5154549279 -324668.7721082006
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigIslands.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigIslands.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigIslands.exp	(revision 18231)
@@ -0,0 +1,68 @@
+## Name:Island
+## Icon:0
+# Points Count  Value
+7 1.000000
+# X pos Y pos
+-1788144.703034 -331058.869467
+-1790984.462389 -330247.509651
+-1790984.462389 -332073.069237
+-1789767.422665 -334507.148684
+-1787739.023126 -336129.868316
+-1786521.983402 -334912.828592
+-1788144.703034 -331058.869467
+
+## Name:Island
+## Icon:0
+# Points Count  Value
+9 1.000000
+# X pos Y pos
+-1751633.511323 -319902.672000
+-1753053.391000 -318279.952368
+-1756095.990310 -318077.112414
+-1754878.950586 -320916.871770
+-1754067.590770 -326190.710572
+-1752647.711092 -326190.710572
+-1751430.671369 -324365.150987
+-1752039.191231 -322133.911493
+-1751633.511323 -319902.672000
+
+## Name:Island
+## Icon:0
+# Points Count  Value
+7 1.000000
+# X pos Y pos
+-1644331.175683 -296576.077296
+-1645548.215407 -297995.956973
+-1645345.375453 -299415.836651
+-1643722.655821 -300024.356513
+-1641694.256282 -298807.316789
+-1642302.776144 -296576.077296
+-1644331.175683 -296576.077296
+
+## Name:Island
+## Icon:0
+# Points Count  Value
+8 1.000000
+# X pos Y pos
+-1641694.256282 -318077.112414
+-1641694.256282 -320105.511954
+-1639868.696696 -321728.231586
+-1637434.617249 -320916.871770
+-1637434.617249 -318685.632276
+-1638043.137111 -316454.392783
+-1640477.216558 -316657.232737
+-1641694.256282 -318077.112414
+
+## Name:Island
+## Icon:0
+# Points Count  Value
+7 1.000000
+# X pos Y pos
+-1658732.812414 -359253.623066
+-1660558.371999 -362499.062330
+-1658327.132506 -366961.541316
+-1652039.093933 -367164.381270
+-1652444.773841 -360673.502744
+-1655081.693242 -359050.783112
+-1658732.812414 -359253.623066
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigShelves.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigShelves.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/PigShelves.exp	(revision 18231)
@@ -0,0 +1,1079 @@
+## Name:
+## Icon:0
+# Points Count Value
+1073 1.000000
+# X pos Y pos
+-1623288.8833276688 -348485.9928101762
+-1596095.2358279999 -341730.0242330000
+-1594724.3783690000 -336371.2178050000
+-1593384.6767620000 -335716.9449280000
+-1591337.9871720001 -334447.5913790000
+-1590800.5631190001 -334607.4475730000
+-1590553.6222590001 -334563.9052400000
+-1590306.6813990001 -334520.3629080000
+-1590059.7405389999 -334476.8205750000
+-1589565.8588200000 -334389.7359090000
+-1589318.9179600000 -334346.1935760000
+-1589071.9771000000 -334302.6512440000
+-1588825.0362400000 -334259.1089110000
+-1588578.0953800001 -334215.5665780000
+-1588287.6121870000 -334418.9651060000
+-1588040.6713280000 -334375.4227730000
+-1587503.2472750000 -334535.2789670000
+-1587256.3064150000 -334491.7366350000
+-1586965.8232219999 -334695.1351620000
+-1586675.3400300001 -334898.5336890000
+-1586384.8568370000 -335101.9322170000
+-1586094.3736439999 -335305.3307440000
+-1585760.3481190000 -335755.6701320000
+-1585469.8649259999 -335959.0686590000
+-1585179.3817330000 -336162.4671860000
+-1584888.8985400000 -336365.8657140000
+-1584598.4153479999 -336569.2642410000
+-1584307.9321550000 -336772.6627680000
+-1584220.8474890001 -337266.5444890000
+-1583930.3642960000 -337469.9430160000
+-1583639.8811039999 -337673.3415440000
+-1583392.9402439999 -337629.7992110000
+-1583145.9993840000 -337586.2568780000
+-1582899.0585240000 -337542.7145450000
+-1582405.1768040000 -337455.6298800000
+-1582158.2359440001 -337412.0875470000
+-1581911.2950850001 -337368.5452140000
+-1581664.3542249999 -337325.0028810000
+-1581417.4133649999 -337281.4605480000
+-1581170.4725050000 -337237.9182160000
+-1580676.5907850000 -337150.8335500000
+-1580429.6499250000 -337107.2912170000
+-1580182.7090660001 -337063.7488850000
+-1579935.7682060001 -337020.2065520000
+-1579601.7426799999 -337470.5459390000
+-1579558.2003470000 -337717.4867990000
+-1579514.6580139999 -337964.4276600000
+-1579471.1156810001 -338211.3685200000
+-1579427.5733490000 -338458.3093800000
+-1579384.0310160001 -338705.2502400000
+-1579296.9463500001 -339199.1319600000
+-1579253.4040170000 -339446.0728210000
+-1579209.8616839999 -339693.0136810000
+-1579166.3193520000 -339939.9545410000
+-1579122.7770189999 -340186.8954010000
+-1578832.2938260001 -340390.2939280000
+-1578788.7514930000 -340637.2347890000
+-1578498.2683000001 -340840.6333160000
+-1578164.2427749999 -341290.9727040000
+-1578120.7004420001 -341537.9135640000
+-1577830.2172490000 -341741.3120910000
+-1577583.2763890000 -341697.7697580000
+-1577292.7931969999 -341901.1682860000
+-1577045.8523370000 -341857.6259530000
+-1576755.3691440001 -342061.0244800000
+-1576261.4874239999 -341973.9398150000
+-1575971.0042310001 -342177.3383420000
+-1575724.0633719999 -342133.7960090000
+-1575433.5801790000 -342337.1945370000
+-1575186.6393190001 -342293.6522040000
+-1574896.1561260000 -342497.0507310000
+-1574649.2152660000 -342453.5083980000
+-1574402.2744070000 -342409.9660660000
+-1573864.8503540000 -342569.8222600000
+-1573617.9094940000 -342526.2799280000
+-1573327.4263009999 -342729.6784550000
+-1573080.4854410000 -342686.1361220000
+-1572833.5445820000 -342642.5937890000
+-1572630.1460549999 -342352.1105960000
+-1572383.2051949999 -342308.5682640000
+-1571932.8658080001 -341974.5427380000
+-1571685.9249480001 -341931.0004050000
+-1571482.5264210000 -341640.5172120000
+-1571235.5855610000 -341596.9748790000
+-1571032.1870339999 -341306.4916860000
+-1570828.7885070001 -341016.0084940000
+-1570421.9914530001 -340435.0421080000
+-1570218.5929260000 -340144.5589150000
+-1570015.1943989999 -339854.0757220000
+-1570058.7367320000 -339607.1348620000
+-1569855.3382049999 -339316.6516690000
+-1569898.8805380000 -339069.7108080000
+-1569695.4820109999 -338779.2276160000
+-1569739.0243430000 -338532.2867550000
+-1569535.6258159999 -338241.8035620000
+-1569579.1681490000 -337994.8627020000
+-1569419.3119550000 -337457.4386490000
+-1569462.8542879999 -337210.4977890000
+-1569259.4557610000 -336920.0145960000
+-1569302.9980939999 -336673.0737360000
+-1569099.5995670001 -336382.5905430000
+-1569143.1418999999 -336135.6496830000
+-1568939.7433730001 -335845.1664900000
+-1568983.2857049999 -335598.2256300000
+-1568779.8871780001 -335307.7424370000
+-1568823.4295109999 -335060.8015770000
+-1568620.0309840001 -334770.3183840000
+-1568663.5733169999 -334523.3775230000
+-1568707.1156500001 -334276.4366630000
+-1568503.7171230000 -333985.9534700000
+-1568547.2594560001 -333739.0126100000
+-1568634.3441210000 -333245.1308900000
+-1568430.9455939999 -332954.6476970000
+-1568474.4879270000 -332707.7068370000
+-1568271.0893999999 -332417.2236440000
+-1568314.6317330000 -332170.2827840000
+-1568358.1740659999 -331923.3419240000
+-1568154.7755390001 -331632.8587310000
+-1568198.3178719999 -331385.9178700000
+-1567994.9193450001 -331095.4346770000
+-1568038.4616779999 -330848.4938170000
+-1567835.0631510001 -330558.0106240000
+-1567878.6054839999 -330311.0697640000
+-1567675.2069560001 -330020.5865710000
+-1567718.7492889999 -329773.6457110000
+-1567515.3507620001 -329483.1625180000
+-1567558.8930949999 -329236.2216580000
+-1567399.0369010000 -328698.7976050000
+-1567442.5792340001 -328451.8567450000
+-1567239.1807070000 -328161.3735520000
+-1567282.7230400001 -327914.4326920000
+-1567079.3245130000 -327623.9494990000
+-1567122.8668460001 -327377.0086390000
+-1566919.4683180000 -327086.5254460000
+-1566963.0106510001 -326839.5845850000
+-1566759.6121240000 -326549.1013920000
+-1566556.2135970001 -326258.6181990000
+-1566599.7559300000 -326011.6773390000
+-1566396.3574029999 -325721.1941460000
+-1566439.8997360000 -325474.2532860000
+-1566236.5012089999 -325183.7700930000
+-1566280.0435420000 -324936.8292330000
+-1566120.1873480000 -324399.4051800000
+-1566163.7296810001 -324152.4643200000
+-1565960.3311530000 -323861.9811270000
+-1566003.8734860001 -323615.0402670000
+-1565800.4749590000 -323324.5570740000
+-1565844.0172919999 -323077.6162140000
+-1565640.6187650000 -322787.1330210000
+-1565684.1610979999 -322540.1921610000
+-1565727.7034310000 -322293.2513000000
+-1565814.7880970000 -321799.3695800000
+-1565858.3304290001 -321552.4287200000
+-1565901.8727620000 -321305.4878600000
+-1565945.4150950001 -321058.5470000000
+-1565988.9574279999 -320811.6061390000
+-1566322.9829539999 -320361.2667520000
+-1566366.5252860000 -320114.3258920000
+-1566410.0676190001 -319867.3850320000
+-1566497.1522850001 -319373.5033110000
+-1566540.6946180000 -319126.5624510000
+-1566337.2960910001 -318836.0792580000
+-1566177.4398970001 -318298.6552050000
+-1565974.0413700000 -318008.1720120000
+-1565770.6428429999 -317717.6888190000
+-1565814.1851750000 -317470.7479590000
+-1565857.7275080001 -317223.8070990000
+-1565944.8121740001 -316729.9253780000
+-1565988.3545070000 -316482.9845180000
+-1566031.8968400001 -316236.0436580000
+-1566075.4391729999 -315989.1027980000
+-1566118.9815050000 -315742.1619380000
+-1566162.5238379999 -315495.2210780000
+-1566249.6085039999 -315001.3393570000
+-1566293.1508370000 -314754.3984970000
+-1566336.6931700001 -314507.4576370000
+-1566380.2355020000 -314260.5167770000
+-1566423.7778350001 -314013.5759170000
+-1566467.3201679999 -313766.6350560000
+-1566510.8625010001 -313519.6941960000
+-1566597.9471670000 -313025.8124760000
+-1566641.4894999999 -312778.8716160000
+-1566685.0318320000 -312531.9307560000
+-1566728.5741650001 -312284.9898950000
+-1566772.1164980000 -312038.0490350000
+-1566815.6588310001 -311791.1081750000
+-1566859.2011640000 -311544.1673150000
+-1566902.7434970001 -311297.2264550000
+-1566699.3449700000 -311006.7432620000
+-1566786.4296349999 -310512.8615420000
+-1566829.9719680001 -310265.9206810000
+-1566873.5143009999 -310018.9798210000
+-1566670.1157740001 -309728.4966280000
+-1566713.6581069999 -309481.5557680000
+-1566466.7172470000 -309438.0134350000
+-1566016.3778599999 -309103.9879100000
+-1565769.4369999999 -309060.4455770000
+-1565522.4961399999 -309016.9032440000
+-1565275.5552800000 -308973.3609110000
+-1565028.6144210000 -308929.8185780000
+-1564781.6735610000 -308886.2762460000
+-1564244.2495080000 -309046.1324400000
+-1563997.3086480000 -309002.5901070000
+-1563750.3677880000 -308959.0477750000
+-1563503.4269290001 -308915.5054420000
+-1563546.9692609999 -308668.5645820000
+-1563343.5707340001 -308378.0813890000
+-1563387.1130669999 -308131.1405290000
+-1563183.7145400001 -307840.6573360000
+-1563227.2568729999 -307593.7164750000
+-1563067.4006790000 -307056.2924220000
+-1563110.9430120001 -306809.3515620000
+-1562907.5444850000 -306518.8683690000
+-1562951.0868180001 -306271.9275090000
+-1562747.6882900000 -305981.4443160000
+-1562791.2306230001 -305734.5034560000
+-1562834.7729559999 -305487.5625960000
+-1562878.3152890000 -305240.6217360000
+-1562921.8576219999 -304993.6808750000
+-1562965.3999550000 -304746.7400150000
+-1563008.9422879999 -304499.7991550000
+-1563052.4846200000 -304252.8582950000
+-1563096.0269530001 -304005.9174350000
+-1563139.5692860000 -303758.9765750000
+-1562979.7130920000 -303221.5525220000
+-1563023.2554250001 -302974.6116610000
+-1563066.7977580000 -302727.6708010000
+-1563110.3400910001 -302480.7299410000
+-1563153.8824229999 -302233.7890810000
+-1563197.4247560001 -301986.8482210000
+-1563240.9670889999 -301739.9073610000
+-1563284.5094220000 -301492.9665000000
+-1563328.0517549999 -301246.0256400000
+-1563371.5940880000 -300999.0847800000
+-1563415.1364200001 -300752.1439200000
+-1563458.6787530000 -300505.2030600000
+-1563792.7042789999 -300054.8636720000
+-1563836.2466120000 -299807.9228120000
+-1563879.7889449999 -299560.9819520000
+-1563923.3312770000 -299314.0410920000
+-1563966.8736099999 -299067.1002320000
+-1564257.3568030000 -298863.7017040000
+-1564547.8399960001 -298660.3031770000
+-1564881.8655210000 -298209.9637890000
+-1565172.3487140001 -298006.5652620000
+-1565462.8319069999 -297803.1667340000
+-1565753.3150990000 -297599.7682070000
+-1566000.2559590000 -297643.3105400000
+-1566537.6800120000 -297483.4543450000
+-1566784.6208720000 -297526.9966780000
+-1567075.1040650001 -297323.5981510000
+-1567162.1887300001 -296829.7164300000
+-1567205.7310629999 -296582.7755700000
+-1567292.8157289999 -296088.8938500000
+-1567583.2989210000 -295885.4953230000
+-1567670.3835870000 -295391.6136020000
+-1567960.8667800000 -295188.2150750000
+-1568004.4091129999 -294941.2742150000
+-1568294.8923050000 -294737.8756870000
+-1568832.3163580000 -294578.0194930000
+-1569122.7995509999 -294374.6209650000
+-1569413.2827430000 -294171.2224380000
+-1569950.7067960000 -294011.3662430000
+-1570241.1899890001 -293807.9677160000
+-1570778.6140409999 -293648.1115210000
+-1571069.0972340000 -293444.7129940000
+-1571359.5804270001 -293241.3144670000
+-1571693.6059520000 -292790.9750790000
+-1571737.1482849999 -292544.0342190000
+-1572027.6314780000 -292340.6356920000
+-1572318.1146710000 -292137.2371640000
+-1572652.1401960000 -291686.8977770000
+-1572695.6825290001 -291439.9569160000
+-1572986.1657219999 -291236.5583890000
+-1573276.6489150000 -291033.1598620000
+-1573857.6152999999 -290626.3628070000
+-1574148.0984930000 -290422.9642800000
+-1574438.5816850001 -290219.5657520000
+-1574772.6072110001 -289769.2263650000
+-1574816.1495439999 -289522.2855050000
+-1574859.6918770000 -289275.3446440000
+-1574946.7765420000 -288781.4629240000
+-1574990.3188750001 -288534.5220640000
+-1575033.8612080000 -288287.5812040000
+-1575077.4035410001 -288040.6403440000
+-1574874.0050140000 -287750.1571510000
+-1574961.0896800000 -287256.2754300000
+-1574757.6911530001 -286965.7922370000
+-1574801.2334850000 -286718.8513770000
+-1574844.7758180001 -286471.9105170000
+-1574684.9196240001 -285934.4864640000
+-1574728.4619570000 -285687.5456040000
+-1574772.0042900001 -285440.6047440000
+-1574815.5466229999 -285193.6638830000
+-1574902.6312879999 -284699.7821630000
+-1574946.1736210000 -284452.8413030000
+-1574989.7159539999 -284205.9004430000
+-1575570.6823390000 -283799.1033880000
+-1575817.6231990000 -283842.6457210000
+-1576311.5049190000 -283929.7303860000
+-1576558.4457789999 -283973.2727190000
+-1576805.3866389999 -284016.8150520000
+-1577299.2683590001 -284103.8997180000
+-1577546.2092180001 -284147.4420500000
+-1577749.6077449999 -284437.9252430000
+-1578199.9471320000 -284771.9507690000
+-1578403.3456590001 -285062.4339620000
+-1578693.8288519999 -284859.0354350000
+-1578780.9135179999 -284365.1537140000
+-1579071.3967100000 -284161.7551870000
+-1579114.9390430001 -283914.8143270000
+-1578664.5996560000 -283580.7888010000
+-1578461.2011289999 -283290.3056080000
+-1577967.3194100000 -283203.2209420000
+-1577763.9208829999 -282912.7377490000
+-1577313.5814960001 -282578.7122240000
+-1577066.6406360001 -282535.1698910000
+-1576616.3012490000 -282201.1443650000
+-1576369.3603890000 -282157.6020320000
+-1575919.0210020000 -281823.5765070000
+-1575715.6224750001 -281533.0933140000
+-1575308.8254209999 -280952.1269280000
+-1575105.4268940000 -280661.6437350000
+-1574902.0283669999 -280371.1605420000
+-1574989.1130329999 -279877.2788220000
+-1574785.7145060000 -279586.7956290000
+-1574582.3159789999 -279296.3124360000
+-1574625.8583110000 -279049.3715750000
+-1574916.3415039999 -278845.9730480000
+-1574959.8838370000 -278599.0321880000
+-1575046.9685030000 -278105.1504680000
+-1575090.5108360001 -277858.2096070000
+-1575380.9940279999 -277654.8110800000
+-1575424.5363610000 -277407.8702200000
+-1575715.0195540001 -277204.4716930000
+-1576252.4436059999 -277044.6154980000
+-1576542.9267990000 -276841.2169710000
+-1576833.4099920001 -276637.8184430000
+-1577123.8931849999 -276434.4199160000
+-1577167.4355170000 -276187.4790560000
+-1577457.9187100001 -275984.0805280000
+-1577791.9442360001 -275533.7411410000
+-1578082.4274279999 -275330.3426130000
+-1578125.9697610000 -275083.4017530000
+-1578416.4529540001 -274880.0032260000
+-1578706.9361469999 -274676.6046980000
+-1578750.4784800000 -274429.6638380000
+-1579084.5040050000 -273979.3244510000
+-1579128.0463380001 -273732.3835910000
+-1579418.5295309999 -273528.9850630000
+-1579462.0718640001 -273282.0442030000
+-1579505.6141959999 -273035.1033430000
+-1579796.0973890000 -272831.7048160000
+-1579839.6397220001 -272584.7639550000
+-1580173.6652470001 -272134.4245680000
+-1580217.2075799999 -271887.4837080000
+-1580507.6907730000 -271684.0851800000
+-1580551.2331060001 -271437.1443200000
+-1580841.7162990000 -271233.7457930000
+-1581132.1994910000 -271030.3472650000
+-1581219.2841570000 -270536.4655450000
+-1581509.7673500001 -270333.0670180000
+-1581800.2505419999 -270129.6684900000
+-1582090.7337350000 -269926.2699630000
+-1582134.2760679999 -269679.3291030000
+-1582424.7592610000 -269475.9305750000
+-1582468.3015940001 -269228.9897150000
+-1582802.3271190000 -268778.6503280000
+-1582845.8694519999 -268531.7094680000
+-1583136.3526450000 -268328.3109400000
+-1583179.8949770001 -268081.3700800000
+-1583470.3781699999 -267877.9715530000
+-1583760.8613630000 -267674.5730250000
+-1583804.4036960001 -267427.6321650000
+-1584138.4292210001 -266977.2927780000
+-1584428.9124139999 -266773.8942500000
+-1584472.4547470000 -266526.9533900000
+-1584762.9379400001 -266323.5548630000
+-1585009.8787990001 -266367.0971960000
+-1585256.8196590000 -266410.6395280000
+-1585750.7013790000 -266497.7241940000
+-1585997.6422389999 -266541.2665270000
+-1586244.5830989999 -266584.8088590000
+-1586491.5239589999 -266628.3511920000
+-1586738.4648190001 -266671.8935250000
+-1586985.4056780001 -266715.4358580000
+-1587479.2873980000 -266802.5205230000
+-1587726.2282580000 -266846.0628560000
+-1587973.1691180000 -266889.6051890000
+-1588220.1099779999 -266933.1475220000
+-1588423.5085050000 -267223.6307150000
+-1588873.8478920001 -267557.6562410000
+-1589077.2464190000 -267848.1394340000
+-1589280.6449460001 -268138.6226260000
+-1589484.0434729999 -268429.1058190000
+-1589440.5011400001 -268676.0466800000
+-1589600.3573340001 -269213.4707330000
+-1589556.8150010000 -269460.4115930000
+-1589760.2135280001 -269750.8947860000
+-1589716.6711960000 -269997.8356460000
+-1589920.0697230001 -270288.3188390000
+-1590123.4682499999 -270578.8020320000
+-1590036.3835839999 -271072.6837520000
+-1590239.7821110000 -271363.1669450000
+-1590443.1806379999 -271653.6501380000
+-1590399.6383050000 -271900.5909980000
+-1590603.0368319999 -272191.0741910000
+-1590806.4353590000 -272481.5573840000
+-1590762.8930259999 -272728.4982440000
+-1590966.2915530000 -273018.9814370000
+-1590922.7492209999 -273265.9222970000
+-1591082.6054150001 -273803.3463510000
+-1591039.0630820000 -274050.2872110000
+-1591242.4616090001 -274340.7704040000
+-1591198.9192760000 -274587.7112640000
+-1591402.3178030001 -274878.1944570000
+-1591605.7163300000 -275168.6776500000
+-1591562.1739970001 -275415.6185100000
+-1591765.5725240000 -275706.1017030000
+-1591722.0301910001 -275953.0425630000
+-1591881.8863860001 -276490.4666160000
+-1591838.3440530000 -276737.4074760000
+-1592041.7425800001 -277027.8906690000
+-1591998.2002470000 -277274.8315290000
+-1592201.5987740001 -277565.3147220000
+-1592695.4804940000 -277652.3993880000
+-1592898.8790209999 -277942.8825810000
+-1593102.2775480000 -278233.3657740000
+-1593392.7607410001 -278029.9672470000
+-1593886.6424600000 -278117.0519120000
+-1594177.1256530001 -277913.6533850000
+-1594467.6088459999 -277710.2548570000
+-1595048.5752310001 -277303.4578030000
+-1595339.0584239999 -277100.0592750000
+-1595629.5416170000 -276896.6607480000
+-1595920.0248090001 -276693.2622210000
+-1595963.5671420000 -276446.3213600000
+-1596297.5926679999 -275995.9819730000
+-1596341.1350010000 -275749.0411130000
+-1596631.6181930001 -275545.6425850000
+-1596675.1605260000 -275298.7017250000
+-1596718.7028590001 -275051.7608650000
+-1596762.2451919999 -274804.8200050000
+-1596805.7875250001 -274557.8791450000
+-1596892.8721900000 -274063.9974240000
+-1596936.4145229999 -273817.0565640000
+-1596979.9568560000 -273570.1157040000
+-1597023.4991890001 -273323.1748440000
+-1597067.0415220000 -273076.2339840000
+-1597648.0079069999 -272669.4369290000
+-1597938.4911000000 -272466.0384020000
+-1598228.9742930001 -272262.6398740000
+-1598316.0589580000 -271768.7581540000
+-1598606.5421509999 -271565.3596270000
+-1598650.0844840000 -271318.4187660000
+-1598693.6268170001 -271071.4779060000
+-1598737.1691490000 -270824.5370460000
+-1598533.7706220001 -270534.0538530000
+-1598577.3129550000 -270287.1129930000
+-1598620.8552880001 -270040.1721330000
+-1598707.9399540001 -269546.2904130000
+-1598751.4822869999 -269299.3495520000
+-1598795.0246190000 -269052.4086920000
+-1598591.6260919999 -268761.9254990000
+-1598635.1684250000 -268514.9846390000
+-1598678.7107579999 -268268.0437790000
+-1598722.2530910000 -268021.1029190000
+-1598518.8545639999 -267730.6197260000
+-1598605.9392299999 -267236.7380050000
+-1598402.5407030000 -266946.2548130000
+-1598446.0830349999 -266699.3139520000
+-1598736.5662280000 -266495.9154250000
+-1599027.0494210001 -266292.5168980000
+-1599608.0158060000 -265885.7198430000
+-1599898.4989990001 -265682.3213160000
+-1600188.9821919999 -265478.9227880000
+-1600479.4653840000 -265275.5242610000
+-1601060.4317699999 -264868.7272060000
+-1601350.9149630000 -264665.3286790000
+-1601641.3981550001 -264461.9301510000
+-1601888.3390150000 -264505.4724840000
+-1602425.7630680001 -264345.6162900000
+-1602716.2462599999 -264142.2177620000
+-1602963.1871199999 -264185.7600950000
+-1603253.6703130000 -263982.3615680000
+-1603500.6111730000 -264025.9039000000
+-1603791.0943660000 -263822.5053730000
+-1604038.0352250000 -263866.0477060000
+-1604531.9169449999 -263953.1323710000
+-1604778.8578049999 -263996.6747040000
+-1605069.3409980000 -263793.2761770000
+-1605316.2818580000 -263836.8185100000
+-1605563.2227179999 -263880.3608420000
+-1605810.1635769999 -263923.9031750000
+-1606057.1044369999 -263967.4455080000
+-1606304.0452970001 -264010.9878410000
+-1606797.9270170000 -264098.0725060000
+-1607044.8678770000 -264141.6148390000
+-1607291.8087370000 -264185.1571720000
+-1607538.7495960000 -264228.6995050000
+-1607785.6904559999 -264272.2418380000
+-1607989.0889830000 -264562.7250310000
+-1608236.0298430000 -264606.2673630000
+-1608686.3692300001 -264940.2928890000
+-1608933.3100900000 -264983.8352220000
+-1609136.7086169999 -265274.3184150000
+-1609383.6494770001 -265317.8607480000
+-1609587.0480040000 -265608.3439410000
+-1609790.4465310001 -265898.8271340000
+-1609993.8450579999 -266189.3103270000
+-1610444.1844450000 -266523.3358520000
+-1610604.0406390000 -267060.7599050000
+-1610807.4391660001 -267351.2430980000
+-1611010.8376930000 -267641.7262910000
+-1611257.7785530000 -267685.2686240000
+-1611461.1770800001 -267975.7518170000
+-1611955.0588000000 -268062.8364830000
+-1612158.4573270001 -268353.3196760000
+-1612405.3981870001 -268396.8620080000
+-1612652.3390470000 -268440.4043410000
+-1612899.2799060000 -268483.9466740000
+-1613436.7039590001 -268324.0904790000
+-1613683.6448190000 -268367.6328120000
+-1613930.5856790000 -268411.1751450000
+-1614177.5265390000 -268454.7174780000
+-1614380.9250660001 -268745.2006710000
+-1614627.8659260001 -268788.7430040000
+-1615078.2053119999 -269122.7685290000
+-1615281.6038400000 -269413.2517220000
+-1615528.5446990000 -269456.7940550000
+-1615731.9432260001 -269747.2772480000
+-1615935.3417529999 -270037.7604410000
+-1615848.2570880000 -270531.6421610000
+-1616051.6556150001 -270822.1253540000
+-1616008.1132819999 -271069.0662140000
+-1615717.6300890001 -271272.4647420000
+-1615674.0877560000 -271519.4056020000
+-1615340.0622310000 -271969.7449890000
+-1615296.5198979999 -272216.6858500000
+-1615006.0367050001 -272420.0843770000
+-1614962.4943720000 -272667.0252370000
+-1614918.9520399999 -272913.9660970000
+-1615122.3505670000 -273204.4492900000
+-1615078.8082340001 -273451.3901500000
+-1614991.7235679999 -273945.2718710000
+-1615195.1220950000 -274235.7550640000
+-1615151.5797619999 -274482.6959240000
+-1615442.0629550000 -274279.2973960000
+-1615935.9446749999 -274366.3820620000
+-1616226.4278670000 -274162.9835350000
+-1616473.3687270000 -274206.5258670000
+-1616763.8519200000 -274003.1273400000
+-1616807.3942529999 -273756.1864800000
+-1617141.4197780001 -273305.8470920000
+-1617431.9029709999 -273102.4485650000
+-1617475.4453040001 -272855.5077050000
+-1617765.9284969999 -272652.1091780000
+-1618012.8693570001 -272695.6515100000
+-1618550.2934089999 -272535.7953160000
+-1618797.2342689999 -272579.3376490000
+-1619044.1751290001 -272622.8799810000
+-1619538.0568490000 -272709.9646470000
+-1619741.4553759999 -273000.4478400000
+-1619988.3962359999 -273043.9901730000
+-1619944.8539030000 -273290.9310330000
+-1620148.2524300001 -273581.4142260000
+-1620104.7100970000 -273828.3550860000
+-1620308.1086240001 -274118.8382790000
+-1620221.0239579999 -274612.7199990000
+-1620424.4224850000 -274903.2031920000
+-1620380.8801520001 -275150.1440520000
+-1620584.2786790000 -275440.6272450000
+-1620540.7363470001 -275687.5681050000
+-1620497.1940140000 -275934.5089660000
+-1620700.5925410001 -276224.9921590000
+-1620657.0502080000 -276471.9330190000
+-1620860.4487350001 -276762.4162120000
+-1620816.9064020000 -277009.3570720000
+-1620976.7625960000 -277546.7811250000
+-1620933.2202639999 -277793.7219850000
+-1621136.6187910000 -278084.2051780000
+-1621093.0764580001 -278331.1460380000
+-1621296.4749850000 -278621.6292310000
+-1621252.9326520001 -278868.5700910000
+-1621456.3311790000 -279159.0532840000
+-1621412.7888460001 -279405.9941440000
+-1621616.1873730000 -279696.4773370000
+-1621529.1027070000 -280190.3590580000
+-1621732.5012340001 -280480.8422510000
+-1621688.9589020000 -280727.7831110000
+-1621645.4165690001 -280974.7239710000
+-1621848.8150960000 -281265.2071640000
+-1621761.7304300000 -281759.0888840000
+-1621965.1289570001 -282049.5720770000
+-1621921.5866240000 -282296.5129370000
+-1621878.0442910001 -282543.4537970000
+-1622081.4428190000 -282833.9369900000
+-1622037.9004860001 -283080.8778510000
+-1621950.8158199999 -283574.7595710000
+-1621907.2734870000 -283821.7004310000
+-1622110.6720139999 -284112.1836240000
+-1622067.1296810000 -284359.1244840000
+-1621776.6464889999 -284562.5230110000
+-1621733.1041560001 -284809.4638720000
+-1621442.6209630000 -285012.8623990000
+-1621108.5954370000 -285463.2017870000
+-1621065.0531049999 -285710.1426470000
+-1620774.5699120001 -285913.5411740000
+-1620731.0275790000 -286160.4820340000
+-1620687.4852460001 -286407.4228940000
+-1620643.9429130000 -286654.3637540000
+-1620600.4005809999 -286901.3046150000
+-1620556.8582480000 -287148.2454750000
+-1620222.8327220001 -287598.5848620000
+-1620179.2903890000 -287845.5257220000
+-1620135.7480560001 -288092.4665830000
+-1620092.2057240000 -288339.4074430000
+-1620048.6633909999 -288586.3483030000
+-1620005.1210580000 -288833.2891630000
+-1619961.5787249999 -289080.2300230000
+-1619918.0363920000 -289327.1708830000
+-1619584.0108670001 -289777.5102710000
+-1619540.4685340000 -290024.4511310000
+-1619496.9262010001 -290271.3919910000
+-1619700.3247280000 -290561.8751840000
+-1619656.7823950001 -290808.8160440000
+-1619613.2400620000 -291055.7569050000
+-1619569.6977299999 -291302.6977650000
+-1619729.5539239999 -291840.1218180000
+-1619686.0115910000 -292087.0626780000
+-1619642.4692579999 -292334.0035380000
+-1619598.9269250000 -292580.9443980000
+-1619802.3254519999 -292871.4275910000
+-1619758.7831190000 -293118.3684510000
+-1619962.1816459999 -293408.8516440000
+-1619918.6393140000 -293655.7925040000
+-1620122.0378409999 -293946.2756970000
+-1620078.4955080000 -294193.2165580000
+-1620281.8940349999 -294483.6997500000
+-1620441.7502290001 -295021.1238040000
+-1620398.2078960000 -295268.0646640000
+-1620601.6064230001 -295558.5478570000
+-1620558.0640900000 -295805.4887170000
+-1620761.4626170001 -296095.9719100000
+-1620964.8611440000 -296386.4551030000
+-1621168.2596710001 -296676.9382960000
+-1621124.7173390000 -296923.8791560000
+-1621328.1158660001 -297214.3623490000
+-1621487.9720600001 -297751.7864020000
+-1621691.3705869999 -298042.2695950000
+-1621647.8282540001 -298289.2104550000
+-1621851.2267809999 -298579.6936480000
+-1622054.6253080000 -298870.1768410000
+-1622258.0238350001 -299160.6600340000
+-1622461.4223620000 -299451.1432270000
+-1622374.3376960000 -299945.0249470000
+-1622577.7362230001 -300235.5081400000
+-1622781.1347500000 -300525.9913330000
+-1622984.5332770001 -300816.4745260000
+-1623187.9318039999 -301106.9577190000
+-1623391.3303310000 -301397.4409120000
+-1623594.7288579999 -301687.9241050000
+-1623754.5850529999 -302225.3481580000
+-1623957.9835800000 -302515.8313510000
+-1624161.3821070001 -302806.3145440000
+-1624408.3229670001 -302849.8568770000
+-1624858.6623529999 -303183.8824020000
+-1625105.6032130001 -303227.4247350000
+-1625396.0864060000 -303024.0262080000
+-1625599.4849330001 -303314.5094010000
+-1625889.9681259999 -303111.1108730000
+-1626427.3921780000 -302951.2546790000
+-1626674.3330379999 -302994.7970110000
+-1626964.8162310000 -302791.3984840000
+-1627008.3585640001 -302544.4576240000
+-1627298.8417570000 -302341.0590970000
+-1627385.9264219999 -301847.1773760000
+-1627676.4096150000 -301643.7788490000
+-1627719.9519479999 -301396.8379890000
+-1627763.4942810000 -301149.8971290000
+-1628097.5198059999 -300699.5577410000
+-1628141.0621390000 -300452.6168810000
+-1628184.6044719999 -300205.6760210000
+-1628765.5708570001 -299798.8789660000
+-1629056.0540499999 -299595.4804390000
+-1629346.5372430000 -299392.0819110000
+-1629433.6219080000 -298898.2001910000
+-1629724.1051010001 -298694.8016640000
+-1629767.6474339999 -298447.8608040000
+-1629811.1897670000 -298200.9199430000
+-1629854.7320999999 -297953.9790830000
+-1629694.8759059999 -297416.5550300000
+-1629738.4182380000 -297169.6141700000
+-1629781.9605709999 -296922.6733100000
+-1629825.5029040000 -296675.7324500000
+-1629622.1043769999 -296385.2492570000
+-1629665.6467100000 -296138.3083970000
+-1629462.2481829999 -295847.8252040000
+-1629549.3328490001 -295353.9434830000
+-1629345.9343220000 -295063.4602900000
+-1629389.4766540001 -294816.5194300000
+-1629186.0781270000 -294526.0362370000
+-1628982.6795999999 -294235.5530440000
+-1628532.3402130001 -293901.5275190000
+-1628328.9416860000 -293611.0443260000
+-1628416.0263520000 -293117.1626050000
+-1628212.6278250001 -292826.6794120000
+-1628793.5942100000 -292419.8823580000
+-1629084.0774030001 -292216.4838300000
+-1629127.6197360000 -291969.5429700000
+-1629461.6452619999 -291519.2035830000
+-1629505.1875940000 -291272.2627220000
+-1629548.7299269999 -291025.3218620000
+-1629592.2722600000 -290778.3810020000
+-1629679.3569260000 -290284.4992820000
+-1629722.8992590001 -290037.5584220000
+-1629766.4415910000 -289790.6175620000
+-1630100.4671169999 -289340.2781740000
+-1630390.9503100000 -289136.8796470000
+-1630928.3743620000 -288977.0234520000
+-1631218.8575550001 -288773.6249250000
+-1631465.7984150001 -288817.1672580000
+-1631669.1969420000 -289107.6504500000
+-1632163.0786619999 -289194.7351160000
+-1632366.4771890000 -289485.2183090000
+-1632613.4180490000 -289528.7606420000
+-1632816.8165760001 -289819.2438350000
+-1633020.2151029999 -290109.7270280000
+-1633514.0968220001 -290196.8116930000
+-1633717.4953490000 -290487.2948860000
+-1633920.8938760001 -290777.7780790000
+-1634167.8347360000 -290821.3204120000
+-1634618.1741229999 -291155.3459380000
+-1634865.1149830001 -291198.8882700000
+-1634908.6573160000 -290951.9474100000
+-1635199.1405090000 -290748.5488830000
+-1635242.6828409999 -290501.6080230000
+-1635329.7675069999 -290007.7263020000
+-1635373.3098400000 -289760.7854420000
+-1635663.7930330001 -289557.3869150000
+-1635707.3353660000 -289310.4460550000
+-1635750.8776980001 -289063.5051950000
+-1636041.3608909999 -288860.1066670000
+-1636375.3864170001 -288409.7672800000
+-1636665.8696089999 -288206.3687520000
+-1636956.3528020000 -288002.9702250000
+-1637246.8359950001 -287799.5716980000
+-1637493.7768550001 -287843.1140300000
+-1637784.2600469999 -287639.7155030000
+-1638278.1417670001 -287726.8001690000
+-1638568.6249599999 -287523.4016410000
+-1638815.5658199999 -287566.9439740000
+-1639106.0490120000 -287363.5454470000
+-1639352.9898719999 -287407.0877800000
+-1639599.9307319999 -287450.6301120000
+-1639890.4139250000 -287247.2315850000
+-1640137.3547850000 -287290.7739180000
+-1640631.2365039999 -287377.8585830000
+-1640878.1773639999 -287421.4009160000
+-1641125.1182240001 -287464.9432490000
+-1641415.6014169999 -287261.5447220000
+-1641662.5422769999 -287305.0870540000
+-1641909.4831369999 -287348.6293870000
+-1642156.4239970001 -287392.1717200000
+-1642359.8225240000 -287682.6549130000
+-1642606.7633829999 -287726.1972460000
+-1643100.6451030001 -287813.2819110000
+-1643347.5859630001 -287856.8242440000
+-1643550.9844899999 -288147.3074370000
+-1643797.9253499999 -288190.8497700000
+-1644001.3238770000 -288481.3329630000
+-1643957.7815439999 -288728.2738230000
+-1644117.6377379999 -289265.6978760000
+-1644074.0954050000 -289512.6387360000
+-1644030.5530729999 -289759.5795960000
+-1643740.0698800001 -289962.9781240000
+-1643652.9852140001 -290456.8598440000
+-1643362.5020220000 -290660.2583710000
+-1643318.9596889999 -290907.1992320000
+-1643275.4173560000 -291154.1400920000
+-1643231.8750229999 -291401.0809520000
+-1643144.7903570000 -291894.9626720000
+-1643101.2480240001 -292141.9035320000
+-1643057.7056920000 -292388.8443920000
+-1643261.1042190001 -292679.3275850000
+-1643217.5618860000 -292926.2684460000
+-1643377.4180800000 -293463.6924990000
+-1643333.8757470001 -293710.6333590000
+-1643537.2742740000 -294001.1165520000
+-1643740.6728010001 -294291.5997450000
+-1643653.5881360001 -294785.4814650000
+-1643856.9866630000 -295075.9646580000
+-1643813.4443300001 -295322.9055180000
+-1643522.9611370000 -295526.3040450000
+-1643435.8764710000 -296020.1857660000
+-1643145.3932790000 -296223.5842930000
+-1643101.8509460001 -296470.5251530000
+-1642811.3677530000 -296673.9236810000
+-1642520.8845599999 -296877.3222080000
+-1642186.8590350000 -297327.6615950000
+-1641896.3758419999 -297531.0601230000
+-1641852.8335090000 -297778.0009830000
+-1641809.2911759999 -298024.9418430000
+-1641765.7488440000 -298271.8827030000
+-1641678.6641780001 -298765.7644240000
+-1641635.1218450000 -299012.7052840000
+-1641591.5795120001 -299259.6461440000
+-1641794.9780390000 -299550.1293370000
+-1641998.3765660000 -299840.6125300000
+-1641911.2919010001 -300334.4942500000
+-1642114.6904279999 -300624.9774430000
+-1642318.0889550000 -300915.4606360000
+-1642811.9706740000 -301002.5453020000
+-1643015.3692010001 -301293.0284940000
+-1643218.7677279999 -301583.5116870000
+-1643509.2509210000 -301380.1131600000
+-1644090.2173070000 -300973.3161050000
+-1644380.7004990000 -300769.9175780000
+-1644424.2428319999 -300522.9767180000
+-1644467.7851650000 -300276.0358580000
+-1644511.3274980001 -300029.0949980000
+-1644554.8698310000 -299782.1541370000
+-1644598.4121630001 -299535.2132770000
+-1644641.9544960000 -299288.2724170000
+-1644685.4968290001 -299041.3315570000
+-1644729.0391619999 -298794.3906970000
+-1644569.1829680000 -298256.9666440000
+-1644612.7253010001 -298010.0257840000
+-1644656.2676339999 -297763.0849230000
+-1644699.8099660000 -297516.1440630000
+-1644743.3522989999 -297269.2032030000
+-1644786.8946320000 -297022.2623430000
+-1644830.4369649999 -296775.3214830000
+-1644873.9792980000 -296528.3806230000
+-1644917.5216310001 -296281.4397620000
+-1644961.0639630000 -296034.4989020000
+-1645004.6062960001 -295787.5580420000
+-1645048.1486289999 -295540.6171820000
+-1644888.2924350000 -295003.1931290000
+-1644931.8347680001 -294756.2522690000
+-1644975.3771009999 -294509.3114090000
+-1645018.9194330000 -294262.3705480000
+-1645062.4617659999 -294015.4296880000
+-1645352.9449590000 -293812.0311610000
+-1645396.4872920001 -293565.0903010000
+-1645440.0296250000 -293318.1494410000
+-1645774.0551499999 -292867.8100530000
+-1645817.5974830000 -292620.8691930000
+-1645861.1398159999 -292373.9283330000
+-1646151.6230090000 -292170.5298050000
+-1646195.1653410001 -291923.5889450000
+-1646529.1908670000 -291473.2495580000
+-1646819.6740600001 -291269.8510300000
+-1647313.5557790000 -291356.9356960000
+-1647807.4374990000 -291444.0203620000
+-1648054.3783590000 -291487.5626940000
+-1648344.8615520000 -291284.1641670000
+-1648882.2856040001 -291124.3079720000
+-1649129.2264640001 -291167.8503050000
+-1649419.7096569999 -290964.4517780000
+-1649957.1337100000 -290804.5955830000
+-1650247.6169020000 -290601.1970560000
+-1650741.4986220000 -290688.2817220000
+-1650944.8971490001 -290978.7649150000
+-1651148.2956760000 -291269.2481070000
+-1651642.1773959999 -291356.3327730000
+-1651845.5759230000 -291646.8159660000
+-1652092.5167830000 -291690.3582990000
+-1652542.8561700000 -292024.3838250000
+-1652789.7970290000 -292067.9261570000
+-1652993.1955560001 -292358.4093500000
+-1653574.1619420000 -291951.6122960000
+-1653864.6451350001 -291748.2137680000
+-1653908.1874670000 -291501.2729080000
+-1653995.2721330000 -291007.3911880000
+-1654038.8144660001 -290760.4503280000
+-1654082.3567989999 -290513.5094670000
+-1654372.8399920000 -290310.1109400000
+-1654706.8655170000 -289859.7715530000
+-1654997.3487100000 -289656.3730250000
+-1655578.3150950000 -289249.5759700000
+-1655868.7982880000 -289046.1774430000
+-1656406.2223410001 -288886.3212490000
+-1656696.7055329999 -288682.9227210000
+-1656987.1887260000 -288479.5241940000
+-1657234.1295860000 -288523.0665270000
+-1657771.5536380000 -288363.2103320000
+-1658018.4944980000 -288406.7526650000
+-1658265.4353580000 -288450.2949980000
+-1658308.9776910001 -288203.3541380000
+-1658599.4608839999 -287999.9556100000
+-1658686.5455489999 -287506.0738900000
+-1658977.0287420000 -287302.6753620000
+-1659020.5710750001 -287055.7345020000
+-1658817.1725480000 -286765.2513090000
+-1658323.2908280001 -286678.1666440000
+-1658119.8923010000 -286387.6834510000
+-1657960.0361070000 -285850.2593980000
+-1657756.6375800001 -285559.7762050000
+-1657553.2390530000 -285269.2930120000
+-1657596.7813860001 -285022.3521520000
+-1657683.8660510001 -284528.4704310000
+-1657727.4083840000 -284281.5295710000
+-1658017.8915770000 -284078.1310440000
+-1658104.9762430000 -283584.2493240000
+-1658395.4594350001 -283380.8507960000
+-1658439.0017680000 -283133.9099360000
+-1659019.9681539999 -282727.1128810000
+-1659310.4513460000 -282523.7143540000
+-1659353.9936790001 -282276.7734940000
+-1659644.4768719999 -282073.3749670000
+-1659731.5615379999 -281579.4932460000
+-1660022.0447300000 -281376.0947190000
+-1660065.5870630001 -281129.1538590000
+-1660646.5534490000 -280722.3568040000
+-1660937.0366410001 -280518.9582770000
+-1661183.9775010000 -280562.5006090000
+-1661677.8592210000 -280649.5852750000
+-1661924.8000810000 -280693.1276080000
+-1662171.7409409999 -280736.6699410000
+-1662375.1394680000 -281027.1531340000
+-1662869.0211870000 -281114.2377990000
+-1663072.4197140001 -281404.7209920000
+-1663028.8773820000 -281651.6618520000
+-1663188.7335760000 -282189.0859050000
+-1663145.1912430001 -282436.0267660000
+-1663101.6489100000 -282682.9676260000
+-1663058.1065770001 -282929.9084860000
+-1662971.0219119999 -283423.7902060000
+-1662927.4795790000 -283670.7310660000
+-1662883.9372459999 -283917.6719260000
+-1662840.3949130001 -284164.6127870000
+-1663043.7934399999 -284455.0959790000
+-1662956.7087739999 -284948.9777000000
+-1663160.1073010000 -285239.4608930000
+-1663116.5649689999 -285486.4017530000
+-1663319.9634960000 -285776.8849460000
+-1663523.3620229999 -286067.3681390000
+-1663726.7605500000 -286357.8513320000
+-1663886.6167440000 -286895.2753850000
+-1664090.0152710001 -287185.7585780000
+-1664293.4137980000 -287476.2417710000
+-1664540.3546579999 -287519.7841030000
+-1664787.2955179999 -287563.3264360000
+-1665324.7195700000 -287403.4702420000
+-1665571.6604299999 -287447.0125750000
+-1665818.6012899999 -287490.5549070000
+-1666109.0844830000 -287287.1563800000
+-1666196.1691480000 -286793.2746600000
+-1666486.6523410000 -286589.8761320000
+-1666690.0508679999 -286880.3593250000
+-1666893.4493950000 -287170.8425180000
+-1667343.7887820001 -287504.8680440000
+-1667547.1873089999 -287795.3512370000
+-1667750.5858360000 -288085.8344300000
+-1667707.0435029999 -288332.7752900000
+-1667663.5011700001 -288579.7161500000
+-1667619.9588380000 -288826.6570100000
+-1667779.8150320000 -289364.0810630000
+-1667736.2726990001 -289611.0219230000
+-1667692.7303660000 -289857.9627840000
+-1667649.1880330001 -290104.9036440000
+-1667605.6457000000 -290351.8445040000
+-1667809.0442270001 -290642.3276970000
+-1667765.5018950000 -290889.2685570000
+-1667721.9595619999 -291136.2094170000
+-1667925.3580890000 -291426.6926100000
+-1667881.8157560001 -291673.6334700000
+-1667838.2734230000 -291920.5743300000
+-1668041.6719500001 -292211.0575230000
+-1667954.5872839999 -292704.9392440000
+-1667911.0449520000 -292951.8801040000
+-1667867.5026189999 -293198.8209640000
+-1668070.9011460000 -293489.3041570000
+-1668027.3588129999 -293736.2450170000
+-1667983.8164800000 -293983.1858770000
+-1668187.2150069999 -294273.6690700000
+-1668143.6726740000 -294520.6099300000
+-1668390.6135340000 -294564.1522630000
+-1668594.0120610001 -294854.6354560000
+-1669087.8937810000 -294941.7201220000
+-1669291.2923079999 -295232.2033150000
+-1669538.2331679999 -295275.7456470000
+-1669741.6316950000 -295566.2288400000
+-1669945.0302220001 -295856.7120330000
+-1670148.4287490000 -296147.1952260000
+-1670642.3104689999 -296234.2798920000
+-1670845.7089960000 -296524.7630850000
+-1671049.1075230001 -296815.2462780000
+-1671005.5651900000 -297062.1871380000
+-1670715.0819969999 -297265.5856650000
+-1670671.5396640000 -297512.5265250000
+-1670584.4549990001 -298006.4082460000
+-1670293.9718060000 -298209.8067730000
+-1670250.4294730001 -298456.7476330000
+-1670206.8871400000 -298703.6884930000
+-1669916.4039469999 -298907.0870210000
+-1669872.8616150001 -299154.0278810000
+-1669829.3192820000 -299400.9687410000
+-1669495.2937560000 -299851.3081280000
+-1669451.7514229999 -300098.2489880000
+-1669161.2682310001 -300301.6475160000
+-1669117.7258979999 -300548.5883760000
+-1669074.1835650001 -300795.5292360000
+-1669030.6412320000 -301042.4700960000
+-1668943.5565660000 -301536.3518170000
+-1668900.0142339999 -301783.2926770000
+-1668856.4719010000 -302030.2335370000
+-1669059.8704280001 -302320.7167300000
+-1669263.2689550000 -302611.1999230000
+-1669176.1842890000 -303105.0816430000
+-1669379.5828160001 -303395.5648360000
+-1669336.0404830000 -303642.5056960000
+-1669292.4981509999 -303889.4465560000
+-1669248.9558180000 -304136.3874160000
+-1669205.4134849999 -304383.3282770000
+-1669118.3288189999 -304877.2099970000
+-1669074.7864860001 -305124.1508570000
+-1669031.2441529999 -305371.0917170000
+-1668987.7018210001 -305618.0325770000
+-1668944.1594880000 -305864.9734370000
+-1669147.5580150001 -306155.4566300000
+-1669104.0156820000 -306402.3974910000
+-1669060.4733490001 -306649.3383510000
+-1668973.3886830001 -307143.2200710000
+-1669176.7872100000 -307433.7032640000
+-1669133.2448780001 -307680.6441240000
+-1669089.7025450000 -307927.5849840000
+-1669046.1602119999 -308174.5258440000
+-1669002.6178790000 -308421.4667050000
+-1668959.0755459999 -308668.4075650000
+-1668871.9908809999 -309162.2892850000
+-1668828.4485480001 -309409.2301450000
+-1668784.9062150000 -309656.1710050000
+-1668741.3638820001 -309903.1118650000
+-1668697.8215490000 -310150.0527260000
+-1668654.2792160001 -310396.9935860000
+-1668363.7960240000 -310600.3921130000
+-1668320.2536909999 -310847.3329730000
+-1668233.1690250000 -311341.2146930000
+-1668189.6266920001 -311588.1555540000
+-1667899.1435000000 -311791.5540810000
+-1667855.6011669999 -312038.4949410000
+-1667565.1179740001 -312241.8934680000
+-1667274.6347810000 -312445.2919960000
+-1666984.1515889999 -312648.6905230000
+-1666737.2107289999 -312605.1481900000
+-1666199.7866760001 -312765.0043850000
+-1665909.3034830000 -312968.4029120000
+-1665618.8202910000 -313171.8014400000
+-1665328.3370980001 -313375.1999670000
+-1665037.8539050000 -313578.5984940000
+-1664747.3707130000 -313781.9970220000
+-1664456.8875200001 -313985.3955490000
+-1664166.4043270000 -314188.7940770000
+-1663875.9211339999 -314392.1926040000
+-1663294.9547490000 -314798.9896590000
+-1663004.4715559999 -315002.3881860000
+-1662713.9883640001 -315205.7867130000
+-1662423.5051710000 -315409.1852410000
+-1662133.0219779999 -315612.5837680000
+-1661842.5387850001 -315815.9822950000
+-1661552.0555930000 -316019.3808230000
+-1661508.5132599999 -316266.3216830000
+-1661218.0300670001 -316469.7202100000
+-1660927.5468740000 -316673.1187380000
+-1660637.0636819999 -316876.5172650000
+-1660549.9790159999 -317370.3989850000
+-1660259.4958230001 -317573.7975130000
+-1659969.0126310000 -317777.1960400000
+-1659678.5294379999 -317980.5945670000
+-1659634.9871050001 -318227.5354270000
+-1623288.8833276688 -348485.9928101762
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Rifts.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Rifts.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Rifts.exp	(revision 18231)
@@ -0,0 +1,126 @@
+## Name:Rifts
+## Icon:0
+# Points Count  Value
+120 1.000000
+# X pos Y pos
+240000.0000000000 210000.0000000000
+243333.3333333333 213763.4408602151
+246666.6666666667 217526.8817204301
+250000.0000000000 221290.3225806452
+253333.3333333333 225053.7634408602
+256666.6666666667 228817.2043010753
+260000.0000000000 232580.6451612903
+263333.3333333334 236344.0860215054
+266666.6666666667 240107.5268817204
+270000.0000000000 243870.9677419355
+273333.3333333333 247634.4086021505
+276666.6666666666 251397.8494623656
+280000.0000000000 255161.2903225806
+283333.3333333334 258924.7311827957
+286666.6666666667 262688.1720430108
+290000.0000000000 266451.6129032259
+293333.3333333333 270215.0537634409
+296666.6666666666 273978.4946236560
+300000.0000000000 277741.9354838710
+304733.3333333334 280394.7772657451
+309466.6666666667 283047.6190476191
+314133.3333333334 284952.3809523809
+318800.0000000000 286857.1428571428
+323466.6666666666 288761.9047619047
+328133.3333333333 290666.6666666667
+332800.0000000000 292571.4285714286
+337466.6666666667 294476.1904761905
+342133.3333333334 296380.9523809524
+346800.0000000000 298285.7142857143
+351466.6666666666 300190.4761904762
+356133.3333333333 302095.2380952381
+360800.0000000000 304000.0000000000
+365466.6666666667 305904.7619047619
+370133.3333333334 307809.5238095238
+374800.0000000000 309714.2857142857
+379466.6666666666 311619.0476190476
+384133.3333333333 313523.8095238095
+388800.0000000000 315428.5714285714
+393466.6666666667 317333.3333333333
+398733.3333333334 318666.6666666666
+404000.0000000000 320000.0000000000
+409000.0000000000 320000.0000000000
+414000.0000000000 320000.0000000000
+419000.0000000000 320000.0000000000
+424000.0000000000 320000.0000000000
+429000.0000000000 320000.0000000000
+434000.0000000000 320000.0000000000
+439000.0000000000 320000.0000000000
+444000.0000000000 320000.0000000000
+449000.0000000000 320000.0000000000
+454000.0000000000 320000.0000000000
+459000.0000000000 320000.0000000000
+464000.0000000000 320000.0000000000
+469000.0000000000 320000.0000000000
+474000.0000000000 320000.0000000000
+479000.0000000000 320000.0000000000
+484000.0000000000 320000.0000000000
+489000.0000000000 320000.0000000000
+494000.0000000000 320000.0000000000
+499000.0000000000 320000.0000000000
+504000.0000000000 320000.0000000000
+509000.0000000000 320000.0000000000
+514000.0000000000 320000.0000000000
+519000.0000000000 320000.0000000000
+524000.0000000000 320000.0000000000
+529000.0000000000 320000.0000000000
+534000.0000000000 320000.0000000000
+539000.0000000000 320000.0000000000
+544000.0000000000 320000.0000000000
+549000.0000000000 320000.0000000000
+554000.0000000000 320000.0000000000
+559000.0000000000 320000.0000000000
+564000.0000000000 320000.0000000000
+569000.0000000000 320000.0000000000
+574000.0000000000 320000.0000000000
+579000.0000000000 320000.0000000000
+584000.0000000000 320000.0000000000
+589000.0000000000 320000.0000000000
+594000.0000000000 320000.0000000000
+599333.3333333333 319047.6190476191
+604666.6666666666 318095.2380952381
+609333.3333333333 316190.4761904762
+614000.0000000000 314285.7142857143
+618666.6666666667 312380.9523809524
+623333.3333333334 310476.1904761905
+628000.0000000000 308571.4285714286
+632666.6666666666 306666.6666666667
+637333.3333333333 304761.9047619047
+642000.0000000000 302857.1428571428
+646666.6666666667 300952.3809523809
+651333.3333333334 299047.6190476191
+656000.0000000000 297142.8571428572
+660666.6666666666 295238.0952380953
+665333.3333333333 293333.3333333334
+670000.0000000000 291428.5714285714
+674666.6666666667 289523.8095238095
+679333.3333333334 287619.0476190476
+684000.0000000000 285714.2857142857
+688666.6666666666 283809.5238095238
+693333.3333333333 281904.7619047619
+698000.0000000000 280000.0000000000
+701333.3333333333 276236.5591397849
+704666.6666666666 272473.1182795699
+708000.0000000000 268709.6774193548
+711333.3333333334 264946.2365591398
+714666.6666666667 261182.7956989247
+718000.0000000000 257419.3548387097
+721333.3333333333 253655.9139784946
+724666.6666666666 249892.4731182796
+728000.0000000000 246129.0322580645
+731333.3333333334 242365.5913978495
+734666.6666666667 238602.1505376344
+738000.0000000000 234838.7096774194
+741333.3333333333 231075.2688172043
+744666.6666666666 227311.8279569892
+748000.0000000000 223548.3870967742
+751333.3333333334 219784.9462365591
+754666.6666666667 216021.5053763441
+758000.0000000000 212258.0645161290
+760000.0000000000 210000.0000000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/RoundFrontEISMINT.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/RoundFrontEISMINT.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/RoundFrontEISMINT.exp	(revision 18231)
@@ -0,0 +1,47 @@
+## Name:
+## Icon:0
+# Points Count Value
+41 1
+# X pos Y pos
+1000000.000000 0.000000
+987688.340595 156434.465040
+951056.516295 309016.994375
+891006.524188 453990.499740
+809016.994375 587785.252292
+707106.781187 707106.781187
+587785.252292 809016.994375
+453990.499740 891006.524188
+309016.994375 951056.516295
+156434.465040 987688.340595
+0.000000 1000000.000000
+-156434.465040 987688.340595
+-309016.994375 951056.516295
+-453990.499740 891006.524188
+-587785.252292 809016.994375
+-707106.781187 707106.781187
+-809016.994375 587785.252292
+-891006.524188 453990.499740
+-951056.516295 309016.994375
+-987688.340595 156434.465040
+-1000000.000000 0.000000
+-987688.340595 -156434.465040
+-951056.516295 -309016.994375
+-891006.524188 -453990.499740
+-809016.994375 -587785.252292
+-707106.781187 -707106.781187
+-587785.252292 -809016.994375
+-453990.499740 -891006.524188
+-309016.994375 -951056.516295
+-156434.465040 -987688.340595
+-0.000000 -1000000.000000
+156434.465040 -987688.340595
+309016.994375 -951056.516295
+453990.499740 -891006.524188
+587785.252292 -809016.994375
+707106.781187 -707106.781187
+809016.994375 -587785.252292
+891006.524188 -453990.499740
+951056.516295 -309016.994375
+987688.340595 -156434.465040
+1000000.000000 0.000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+200000 0
+200000 200000
+0 200000 
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT750000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT750000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareEISMINT750000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-750000 -750000
+750000 -750000
+750000 750000
+-750000 750000 
+-750000 -750000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 999999
+-1000 1100000
+1100000 1100000
+1100000 999999
+-1000 999999
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront2.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront2.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFront2.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+1000 999000
+1000 1100000
+999000 1100000
+999000 999000
+-1000 999000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFrontEISMINT.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFrontEISMINT.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareFrontEISMINT.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 -1000
+-1000 1000
+201000 1000
+201000 -1000
+-1000 -1000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHalfRight.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHalfRight.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHalfRight.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+500000 0
+500000 1000000
+1000000 1000000
+1000000 0 
+500000 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHole.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHole.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareHole.exp	(revision 18231)
@@ -0,0 +1,21 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
+
+## Name:domainoutline
+## Icon:1
+# Points Count  Value
+5 1.
+# X pos Y pos
+400000 400000 
+600000 400000
+600000 600000
+400000 600000
+400000 400000 
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareISMIP.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareISMIP.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareISMIP.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-100000 -100000
+100000 -100000
+100000 100000
+-100000 100000
+-100000 -100000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRifts.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRifts.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRifts.exp	(revision 18231)
@@ -0,0 +1,126 @@
+## Name:Rifts
+## Icon:0
+# Points Count  Value
+120 1.000000
+# X pos Y pos
+240000.0000000000 210000.0000000000
+243333.3333333333 213763.4408602151
+246666.6666666667 217526.8817204301
+250000.0000000000 221290.3225806452
+253333.3333333333 225053.7634408602
+256666.6666666667 228817.2043010753
+260000.0000000000 232580.6451612903
+263333.3333333334 236344.0860215054
+266666.6666666667 240107.5268817204
+270000.0000000000 243870.9677419355
+273333.3333333333 247634.4086021505
+276666.6666666666 251397.8494623656
+280000.0000000000 255161.2903225806
+283333.3333333334 258924.7311827957
+286666.6666666667 262688.1720430108
+290000.0000000000 266451.6129032259
+293333.3333333333 270215.0537634409
+296666.6666666666 273978.4946236560
+300000.0000000000 277741.9354838710
+304733.3333333334 280394.7772657451
+309466.6666666667 283047.6190476191
+314133.3333333334 284952.3809523809
+318800.0000000000 286857.1428571428
+323466.6666666666 288761.9047619047
+328133.3333333333 290666.6666666667
+332800.0000000000 292571.4285714286
+337466.6666666667 294476.1904761905
+342133.3333333334 296380.9523809524
+346800.0000000000 298285.7142857143
+351466.6666666666 300190.4761904762
+356133.3333333333 302095.2380952381
+360800.0000000000 304000.0000000000
+365466.6666666667 305904.7619047619
+370133.3333333334 307809.5238095238
+374800.0000000000 309714.2857142857
+379466.6666666666 311619.0476190476
+384133.3333333333 313523.8095238095
+388800.0000000000 315428.5714285714
+393466.6666666667 317333.3333333333
+398733.3333333334 318666.6666666666
+404000.0000000000 320000.0000000000
+409000.0000000000 320000.0000000000
+414000.0000000000 320000.0000000000
+419000.0000000000 320000.0000000000
+424000.0000000000 320000.0000000000
+429000.0000000000 320000.0000000000
+434000.0000000000 320000.0000000000
+439000.0000000000 320000.0000000000
+444000.0000000000 320000.0000000000
+449000.0000000000 320000.0000000000
+454000.0000000000 320000.0000000000
+459000.0000000000 320000.0000000000
+464000.0000000000 320000.0000000000
+469000.0000000000 320000.0000000000
+474000.0000000000 320000.0000000000
+479000.0000000000 320000.0000000000
+484000.0000000000 320000.0000000000
+489000.0000000000 320000.0000000000
+494000.0000000000 320000.0000000000
+499000.0000000000 320000.0000000000
+504000.0000000000 320000.0000000000
+509000.0000000000 320000.0000000000
+514000.0000000000 320000.0000000000
+519000.0000000000 320000.0000000000
+524000.0000000000 320000.0000000000
+529000.0000000000 320000.0000000000
+534000.0000000000 320000.0000000000
+539000.0000000000 320000.0000000000
+544000.0000000000 320000.0000000000
+549000.0000000000 320000.0000000000
+554000.0000000000 320000.0000000000
+559000.0000000000 320000.0000000000
+564000.0000000000 320000.0000000000
+569000.0000000000 320000.0000000000
+574000.0000000000 320000.0000000000
+579000.0000000000 320000.0000000000
+584000.0000000000 320000.0000000000
+589000.0000000000 320000.0000000000
+594000.0000000000 320000.0000000000
+599333.3333333333 319047.6190476191
+604666.6666666666 318095.2380952381
+609333.3333333333 316190.4761904762
+614000.0000000000 314285.7142857143
+618666.6666666667 312380.9523809524
+623333.3333333334 310476.1904761905
+628000.0000000000 308571.4285714286
+632666.6666666666 306666.6666666667
+637333.3333333333 304761.9047619047
+642000.0000000000 302857.1428571428
+646666.6666666667 300952.3809523809
+651333.3333333334 299047.6190476191
+656000.0000000000 297142.8571428572
+660666.6666666666 295238.0952380953
+665333.3333333333 293333.3333333334
+670000.0000000000 291428.5714285714
+674666.6666666667 289523.8095238095
+679333.3333333334 287619.0476190476
+684000.0000000000 285714.2857142857
+688666.6666666666 283809.5238095238
+693333.3333333333 281904.7619047619
+698000.0000000000 280000.0000000000
+701333.3333333333 276236.5591397849
+704666.6666666666 272473.1182795699
+708000.0000000000 268709.6774193548
+711333.3333333334 264946.2365591398
+714666.6666666667 261182.7956989247
+718000.0000000000 257419.3548387097
+721333.3333333333 253655.9139784946
+724666.6666666666 249892.4731182796
+728000.0000000000 246129.0322580645
+731333.3333333334 242365.5913978495
+734666.6666666667 238602.1505376344
+738000.0000000000 234838.7096774194
+741333.3333333333 231075.2688172043
+744666.6666666666 227311.8279569892
+748000.0000000000 223548.3870967742
+751333.3333333334 219784.9462365591
+754666.6666666667 216021.5053763441
+758000.0000000000 212258.0645161290
+760000.0000000000 210000.0000000000
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRiftsLateral.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRiftsLateral.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareRiftsLateral.exp	(revision 18231)
@@ -0,0 +1,11 @@
+## Name:RiftsLateral
+## Icon:0
+# Points Count  Value
+5 1.000000
+# X pos Y pos
+162237.7622377622 351796.4071856287
+204195.8041958041 474550.8982035927
+226573.4265734265 594311.3772455089
+201398.6013986013 645209.5808383233
+128671.3286713285 696107.7844311377
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareShelf.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareShelf.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/SquareShelf.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 500000
+1000000 500000
+1000000 1000000
+0 1000000 
+0 500000
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_10000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_10000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_10000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+30000 0
+30000 30000
+0 30000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_160000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_160000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_160000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+480000 0
+480000 480000
+0 480000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_20000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_20000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_20000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+60000 0
+60000 60000
+0 60000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_40000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_40000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_40000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+120000 0
+120000 120000
+0 120000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_5000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_5000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_5000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+15000 0
+15000 15000
+0 15000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_80000.exp
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_80000.exp	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Exp/Square_80000.exp	(revision 18231)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+240000 0
+240000 240000
+0 240000
+0 0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.m	(revision 18231)
@@ -0,0 +1,39 @@
+function ids=IdFromString(string),
+%IDFROMSTRING - output ids from a given string
+%
+%   Usage:
+%      ids=IdFromString(string);
+%
+%   Examples:
+%      ids=IdFromString('Parallel');
+%      ids=IdFromString('79North');
+
+%Check input
+if ~ischar(string)
+	error('IdFromString error message: input argument is not a string');
+end
+
+%Initialize output
+ids=[];
+
+%Grep string
+[dummy ids_raw]=system(['cat IdToName.m | grep ' string ' | awk ''{print $2 }'' | sed -e "s/(id==//g" | sed -e "s/),//g"']);
+
+%return if no test found
+if isempty(ids_raw),
+	disp(['No test matches ''' string '''' ]);
+	return
+end
+
+%Process string (delete return carriage);
+ids_raw=strsplit(ids_raw,char(10));
+ids_raw=ids_raw(1:end-1);
+for i=1:length(ids_raw),
+	eval(['ids=[ids ' ids_raw{i} '];']); 
+end
+
+%Display names
+disp([ num2str(length(ids)) ' tests match ''' string '''']);
+for i=1:length(ids)
+	disp([ '   ' num2str(ids(i)) ' : ' IdToName(ids(i)) ]);
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdFromString.py	(revision 18231)
@@ -0,0 +1,36 @@
+#! /usr/bin/env python
+from IdToName import IdToName
+
+def IdFromString(string):
+	"""
+	IDFROMSTRING - output ids from a given string
+ 
+	    Usage:
+	       ids=IdFromString(string)
+ 
+	    Examples:
+	       ids=IdFromString('Parallel')
+	       ids=IdFromString('79North')
+	"""
+
+	#Check input
+	if not isinstance(string,str):
+		raise TypeError('IdFromString error message: input argument is not a string.')
+
+	#Get the dictionary and scan for matches
+	idnames=IdToName(0)
+	ids=[item[0] for item in idnames.iteritems() if string in item[1]]
+
+	#Return if no test found
+	if not ids:
+		print "No test matches '%s'." % string
+		return ids
+
+	#Display names
+	ids.sort()
+	print "%d tests match '%s':" % (len(ids),string)
+	for id in ids:
+		print "   %d : %s" % (id,idnames[id])
+
+	return ids
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.m	(revision 18231)
@@ -0,0 +1,263 @@
+function name=IdToName(id);
+%IDTONAME- return name of test
+%
+%   Usage:
+%      name=IdToName(id);
+
+switch id,
+	case 101, name='SquareShelfConstrainedStressSSA2d';
+	case 102, name='SquareShelfConstrainedStressSSA3d';
+	case 103, name='SquareShelfConstrainedStressHO';
+	case 104, name='SquareShelfConstrainedStressFS';
+	case 105, name='SquareShelfConstrainedMasstransp2d';
+	case 106, name='SquareShelfConstrainedMasstransp2dDG';
+	case 107, name='SquareShelfConstrainedMasstransp3d';
+	case 108, name='SquareShelfConstrainedTherStea';
+	case 109, name='SquareShelfConstrainedTherTran';
+	case 110, name='SquareShelfConstrainedTranSSA2d';
+	case 111, name='SquareShelfConstrainedTranHO';
+	case 112, name='SquareShelfConstrainedSurfSlop2d';
+	case 113, name='SquareShelfConstrainedSurfSlope3d';
+	case 114, name='SquareShelfConstrainedBedSlop2d';
+	case 115, name='SquareShelfConstrainedBedSlop3d';
+	case 116, name='SquareShelfConstrainedBalThic2d';
+	case 117, name='SquareShelfConstrainedBalThic3d';
+	case 118, name='SquareShelfConstrainedBalThic2dDG';
+	case 119, name='SquareBamgMesh';
+	case 120, name='SquareShelfConstrainedEnthalpyStea';
+	case 121, name='SquareShelfConstrainedEnthalpyTran';
+	case 122, name='SquareShelfConstrainedTransHOEnth';
+	case 123, name='SquareShelfConstrainedTranMisfitSurface';
+	case 124, name='SquareShelfConstrainedTranFSFreeSurface';
+	case 201, name='SquareShelfStressSSA2d';
+	case 202, name='SquareShelfStressSSA3d';
+	case 203, name='SquareShelfStressHO';
+	case 204, name='SquareShelfStressFS';
+	case 205, name='SquareShelfStressMHOPenalties';
+	case 206, name='SquareShelfTherStea';
+	case 207, name='SquareShelfTherTran';
+	case 208, name='SquareShelfTranSSA2d';
+	case 209, name='SquareShelfTranSSA3d';
+	case 210, name='SquareShelfTranHO';
+	case 211, name='SquareShelfTranFS';
+	case 212, name='SquareShelfCMBSSA2d';
+	case 213, name='SquareShelfCMBSSA3d';
+	case 214, name='SquareShelfCMBHO';
+	case 215, name='SquareShelfCMBFS';
+	case 216, name='SquareShelfStressSSA2dRift';
+	case 217, name='SquareShelfConstrained';
+	case 218, name='SquareShelfConstrainedDakotaB';
+	case 219, name='SquareShelfStressSSAHOTiling';
+	case 220, name='SquareShelfStressHOFS3dTiling';
+	case 221, name='SquareShelfStressSSAFS3dTiling';
+	case 222, name='SquareShelfStressSSA2dTransientIncrHydro';
+	case 223, name='SquareShelfStressSSA2dTransientIncrNonHydro';
+	case 224, name='SquareShelfStressHOTransientIncrHydro';
+	case 225, name='SquareShelfStressHOTransientIncrNonHydro';
+	case 226, name='SquareShelfTranCflSSA2d';
+	case 227, name='SquareShelfTranCflHO';
+	case 228, name='SquareShelfTranForceNeg2d';
+	case 229, name='SquareShelfTranForcePos2d';
+	case 230, name='SquareShelfTranForceNeg3d';
+	case 231, name='SquareShelfTranForcePos3d';
+	case 232, name='SquareShelfTherTranForcTemp';
+	case 233, name='SquareShelfTranHOForcTemp';
+	case 234, name='SquareShelfTranForceNeg2dDakotaSamp';
+	case 235, name='SquareShelfTranForceNeg2dDakotaLocal';
+	case 236, name='SquareShelfTranIspddIsdeltaSSA2d';
+	case 237, name='SquareShelfTranIspddIsdeltaSSA3d';
+	case 238, name='SquareShelfTranForceNoInterp2d';
+	case 239, name='SquareShelfTranForceNoInterp3d';
+	case 270, name='SquareShelfStressSSA2dDamage';
+	case 271, name='SquareShelfStressSSA2dDamageTran';
+	case 272, name='SquareShelfCMZSSA2dDamage';
+	case 274, name='SquareShelfStressSSA2dDamageRift';
+	case 275, name='SquareShelfDamageEvolutionSSA2d';
+	case 276, name='SquareShelfDamageEvolutionSSA2dP2';
+	case 280, name='SquareShelfStressSSA2dHigherOrder';
+	case 285, name='SquareShelfStressHOHigherOrder';
+	case 290, name='SquareShelfStressFSP2P1';
+	case 291, name='SquareShelfStressFSP4z';
+	case 292, name='SquareShelfTranSSA2dFloatingMeltParam';
+	case 301, name='SquareSheetConstrainedStressSSA2d';
+	case 302, name='SquareSheetConstrainedStressSIA2d';
+	case 303, name='SquareSheetConstrainedStressSIASSA2d';
+	case 304, name='SquareSheetConstrainedStressSSA3d';
+	case 305, name='SquareSheetConstrainedStressSIA3d';
+	case 306, name='SquareSheetConstrainedStressSIASSA3d';
+	case 307, name='SquareSheetConstrainedStressHO';
+	case 308, name='SquareSheetConstrainedStressFS';
+	case 309, name='SquareSheetConstrainedMasstransp2d';
+	case 320, name='SquareSheetConstrainedMasstransp2dDG';
+	case 311, name='SquareSheetConstrainedMasstransp3d';
+	case 312, name='SquareSheetConstrainedTherStea';
+	case 313, name='SquareSheetConstrainedTherTran';
+	case 314, name='SquareSheetConstrainedTranSIA2d';
+	case 315, name='SquareSheetConstrainedTranSIA3d';
+	case 316, name='SquareSheetConstrainedTranSSA2d';
+	case 317, name='SquareSheetConstrainedTranHO';
+	case 318, name='SquareSheetConstrainedSteaSIA3d';
+	case 319, name='SquareSheetConstrainedCMDragSSA2d';
+	case 320, name='SquareSheetConstrainedCMDragSSA3d';
+	case 321, name='SquareSheetConstrainedCMDragHO';
+	case 322, name='SquareSheetConstrainedCMDragFS';
+	case 323, name='SquareSheetConstrainedTranCflSSA2d';
+	case 324, name='SquareSheetConstrainedTranCflSIA3d';
+	case 325, name='SquareSheetConstrainedEnthalpyStea';
+	case 326, name='SquareSheetConstrainedEnthalpyTran';
+	case 327, name='SquareSheetConstrainedTransHOEnth';
+	case 328, name='SquareSheetConstrainedSmbGradients2d';
+	case 329, name='SquareSheetConstrainedSmbGradients3d';
+	case 332, name='SquareSheetConstrainedHydrologyDC';
+	case 333, name='SquareSheetHydrologyDCTwoLayers';
+	case 334, name='SquareSheetConstrainedExtrudedHydrologyDC';
+	case 335, name='SquareSheetExtrudedHydrologyDCTwoLayers';
+	case 336, name='SquareSheetConstrainedSmbComponents2d';
+	case 337, name='SquareSheetConstrainedSmbComponents3d';
+	case 338, name='SquareSheetConstrainedSmbMeltComponents2d';
+	case 339, name='SquareSheetConstrainedSmbMeltComponents3d';
+	case 401, name='SquareSheetShelfStressSSA2d';
+	case 402, name='SquareSheetShelfStressSSA3d';
+	case 403, name='SquareSheetShelfStressHO';
+	case 404, name='SquareSheetShelfStressFS';
+	case 405, name='SquareSheetShelfStressMHOPenalties';
+	case 406, name='SquareSheetShelfTherStea';
+	case 407, name='SquareSheetShelfTherTran';
+	case 408, name='SquareSheetShelfTranSSA2d';
+	case 409, name='SquareSheetShelfTranMHOPenalties';
+	case 410, name='SquareSheetShelfSteaSSA3d';
+	case 411, name='SquareSheetShelfSteaHO';
+	case 412, name='SquareSheetShelfDiadSSA3dDakota';
+	case 413, name='SquareSheetShelfDiadSSA3dDakotaPart';
+	case 414, name='SquareSheetShelfDiadSSA3dDakotaMassFlux';
+	case 415, name='SquareSheetShelfCMDragSteaSSA3d';
+	case 416, name='SquareSheetShelfCMDragSteaHO';
+	case 417, name='SquareSheetShelfDiadSSA3dDakotaSamp';
+	case 418, name='SquareSheetShelfDiadSSA3dDakotaAreaAverage';
+	case 419, name='SquareSheetShelfStressSSAHOTiling';
+	case 420, name='SquareSheetShelfDakotaScaledResponse';
+	case 421, name='SquareSheetShelfStressHOFS3dTiling';
+	case 422, name='SquareSheetShelfStressSSAFS3dTiling';
+	case 423, name='RoundSheetShelfGLMigrationSSA2d';
+	case 424, name='SquareSheetShelfGroundingLine2dAggressive';
+	case 425, name='SquareSheetShelfGroundingLine2dSoft';
+	case 426, name='SquareSheetShelfGroundingLine3dAggressive';
+	case 427, name='SquareSheetShelfGroundingLine3dSoft';
+	case 428, name='SquareSheetShelfStressSSA2dNewton';
+	case 429, name='SquareSheetShelfStressHONewton';
+	case 431, name='SquareSheetShelfSteaEnthalpySSA3d';
+	case 432, name='SquareSheetShelfSteaEnthalpyHO';
+	case 433, name='RoundSheetShelfGLMigrationSSA3d';
+	case 434, name='SquareSheetShelfL1L2';
+	case 435, name='MISMIP3DHO';
+	case 450, name='SquareSheetShelfStressSSAHigherOrder';
+	case 455, name='SquareSheetShelfStressHOHigherOrder';
+	case 501, name='PigStressSSA2d';
+	case 502, name='PigStressHO';
+	case 503, name='PigStressFS';
+	case 504, name='PigTranSSA2d';
+	case 505, name='PigTranSSA3d';
+	case 506, name='PigTranHO';
+	case 507, name='PigTranFS';
+	case 508, name='PigSteaSSA3d';
+	case 509, name='PigSteaHO';
+	case 510, name='PigSteaFS';
+	case 530, name='PigBalVel1';
+	case 531, name='PigBalVel2';
+	case 511, name='PigCMBFS';
+	case 512, name='PigCMDragHO';
+	case 513, name='PigCMDragSteaSSA3d';
+	case 514, name='PigBamgMesh';
+	case 515, name='PigTherTranSUPG';
+	case 516, name='PigTherSteaSUPG';
+	case 601, name='79NorthMasstransp2d';
+	case 602, name='79NorthMasstransp2dDG';
+	case 603, name='79NorthMasstransp3d';
+	case 604, name='79NorthSurfSlop2d';
+	case 605, name='79NorthSurfSlop3d';
+	case 606, name='79NorthBedSlop2d';
+	case 607, name='79NorthBedSlop3d';
+	case 608, name='79NorthBalThic2d';
+	case 609, name='79NorthBalThic2dDG';
+	case 610, name='79NorthBalThic3d';
+	case 611, name='79NorthCMBalThic2dCG';
+	case 613, name='79NorthCMBalThicVxVy';
+	case 701, name='FlowbandFSshelf';
+	case 702, name='FlowbandFSsheetshelf';
+	case 703, name='FlowbandFSsheetshelfTrans';
+	case 801, name='ValleyGlacierLevelsetSSA2d';
+	case 802, name='ValleyGlacierLevelsetThermalSSA3d';
+	case 803, name='ValleyGlacierLevelsetEnthalpyHO3d';
+	case 804, name='ValleyGlacierLevelsetCalvingSIA2d';
+	case 805, name='ValleyGlacierLevelsetEnthCalvingHO3d';
+	case 1101, name='ISMIPAHO';
+	case 1102, name='ISMIPAFS';
+	case 1103, name='ISMIPBHO';
+	case 1104, name='ISMIPBFS';
+	case 1105, name='ISMIPCHO';
+	case 1106, name='ISMIPCFS';
+	case 1107, name='ISMIPDHO';
+	case 1108, name='ISMIPDFS';
+	case 1109, name='ISMIPE';
+	case 1110, name='ISMIPF';
+	case 1201, name='EISMINTMassConservation';
+	case 1202, name='EISMINTStress1';
+	case 1203, name='EISMINTStress2';
+	case 1204, name='EISMINTTran2';
+	case 1205, name='EISMINTRoundIceSheetStaticSIA';
+	case 1206, name='EISMINTRoundIceSheetStaticHO';
+	case 1207, name='EISMINTRoundIceSheetStaticFS';
+	case 1208, name='EISMINTA';
+	case 1301, name='ThermalMelting';
+	case 1302, name='ThermalAdvection';
+	case 1303, name='ThermalConduction';
+	case 1304, name='ThermalGeothermalFlux';
+	case 1401, name='AdaptiveMeshRefinement1';
+	case 1402, name='AdaptiveMeshRefinement2';
+	case 1501, name='SquareShelfTranSawTooth2d';
+	case 1502, name='SquareShelfTranSawTooth3d';
+	case 1601, name='SquareShelfSSA2dRotation';
+	case 1602, name='SquareSheetShelfHORotation';
+	case 2001, name='SquareSheetConstrainedGia2d';
+	case 2051, name='GiaBenchmarksAB2dA1';
+	case 2052, name='GiaBenchmarksAB2dA2';
+	case 2053, name='GiaBenchmarksAB2dA3';
+	case 2061, name='GiaBenchmarksAB2dB1';
+	case 2062, name='GiaBenchmarksAB2dB2';
+	case 2063, name='GiaBenchmarksAB2dB3';
+	case 2071, name='GiaBenchmarksAB2dC1';
+	case 2072, name='GiaBenchmarksAB2dC2';
+	case 2073, name='GiaBenchmarksAB2dC3';
+	case 2081, name='GiaBenchmarksAB2dD1';
+	case 2082, name='GiaBenchmarksAB2dD2';
+	case 2083, name='GiaBenchmarksAB2dD3';
+	case 3001, name='SquareShelfConstrainedStressSSA2dAdolc';
+	case 3002, name='SquareShelfConstrainedStressSSA3dAdolc';
+	case 3003, name='SquareShelfConstrainedStressHOAdolc';
+	case 3004, name='SquareShelfConstrainedStressFSAdolc';
+	case 3005, name='SquareShelfConstrainedMasstransp2dAdolc';
+	case 3006, name='SquareShelfConstrainedMasstransp2dDGAdolc';
+	case 3007, name='SquareShelfConstrainedMasstransp3dAdolc';
+	case 3008, name='SquareShelfConstrainedTherSteaAdolc';
+	case 3009, name='SquareShelfConstrainedTherTranAdolc';
+	case 3010, name='SquareShelfConstrainedTranSSA2dAdolc';
+	case 3015, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifference';
+	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
+	case 3020, name='SquareShelfConstrainedTranAdolcReverseVsForward';
+	case 3101, name='SquareShelfConstrainedStressSSA2dAdolcMumps';
+	case 3102, name='SquareShelfConstrainedStressSSA3dAdolcMumps';
+	case 3103, name='SquareShelfConstrainedStressHOAdolcMumps';
+	case 3104, name='SquareShelfConstrainedStressFSAdolcMumps';
+	case 3105, name='SquareShelfConstrainedMasstransp2dAdolcMumps';
+	case 3106, name='SquareShelfConstrainedMasstransp2dDGAdolcMumps';
+	case 3107, name='SquareShelfConstrainedMasstransp3dAdolcMumps';
+	case 3108, name='SquareShelfConstrainedTherSteaAdolcMumps';
+	case 3109, name='SquareShelfConstrainedTherTranAdolcMumps';
+	case 3110, name='SquareShelfConstrainedTranSSA2dAdolcMumps';
+	case 3115, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps';
+	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
+	case 3120, name='SquareShelfConstrainedTranAdolcReverseVsForwardMumps';
+
+
+	otherwise, name='N/A';
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/IdToName.py	(revision 18231)
@@ -0,0 +1,255 @@
+#! /usr/bin/env python
+
+def IdToName(id):
+	"""
+	IDTONAME- return name of test
+ 
+	    Usage:
+	       name=IdToName(id)
+	"""
+
+	idname={
+	101 : 'SquareShelfConstrainedStressSSA2d',
+	102 : 'SquareShelfConstrainedStressSSA3d',
+	103 : 'SquareShelfConstrainedStressHO',
+	104 : 'SquareShelfConstrainedStressFS',
+	105 : 'SquareShelfConstrainedMasstransp2d',
+	106 : 'SquareShelfConstrainedMasstransp2dDG',
+	107 : 'SquareShelfConstrainedMasstransp3d',
+	108 : 'SquareShelfConstrainedTherStea',
+	109 : 'SquareShelfConstrainedTherTran',
+	110 : 'SquareShelfConstrainedTranSSA2d',
+	111 : 'SquareShelfConstrainedTranHO',
+	112 : 'SquareShelfConstrainedSurfSlop2d',
+	113 : 'SquareShelfConstrainedSurfSlope3d',
+	114 : 'SquareShelfConstrainedBedSlop2d',
+	115 : 'SquareShelfConstrainedBedSlop3d',
+	116 : 'SquareShelfConstrainedBalThic2d',
+	117 : 'SquareShelfConstrainedBalThic3d',
+	118 : 'SquareShelfConstrainedBalThic2dDG',
+	119 : 'SquareBamgMesh',
+	120 : 'SquareShelfConstrainedEnthalpyStea',
+	121 : 'SquareShelfConstrainedEnthalpyTran',
+	122 : 'SquareShelfConstrainedTransHOEnth',
+	201 : 'SquareShelfStressSSA2d',
+	202 : 'SquareShelfStressSSA3d',
+	203 : 'SquareShelfStressHO',
+	204 : 'SquareShelfStressFS',
+	205 : 'SquareShelfStressMHOPenalties',
+	206 : 'SquareShelfTherStea',
+	207 : 'SquareShelfTherTran',
+	208 : 'SquareShelfTranSSA2d',
+	209 : 'SquareShelfTranSSA3d',
+	210 : 'SquareShelfTranHO',
+	211 : 'SquareShelfTranFS',
+	212 : 'SquareShelfCMBSSA2d',
+	213 : 'SquareShelfCMBSSA3d',
+	214 : 'SquareShelfCMBHO',
+	215 : 'SquareShelfCMBFS',
+	216 : 'SquareShelfStressSSA2dRift',
+	217 : 'SquareShelfConstrained',
+	218 : 'SquareShelfConstrainedDakotaB',
+	219 : 'SquareShelfStressSSAHOTiling',
+	220 : 'SquareShelfStressHOFS3dTiling',
+	221 : 'SquareShelfStressSSAFS3dTiling',
+	222 : 'SquareShelfStressSSA2dTransientIncrHydro',
+	223 : 'SquareShelfStressSSA2dTransientIncrNonHydro',
+	224 : 'SquareShelfStressHOTransientIncrHydro',
+	225 : 'SquareShelfStressHOTransientIncrNonHydro',
+	226 : 'SquareShelfTranCflSSA2d',
+	227 : 'SquareShelfTranCflHO',
+	228 : 'SquareShelfTranForceNeg2d',
+	229  : 'SquareShelfTranForcePos2d',
+	230  : 'SquareShelfTranForceNeg3d',
+	231  : 'SquareShelfTranForcePos3d',
+	232  : 'SquareShelfTherTranForcTemp',
+	233  : 'SquareShelfTranHOForcTemp',
+	234  : 'SquareShelfTranForceNeg2dDakotaSamp',
+	235  : 'SquareShelfTranForceNeg2dDakotaLocal',
+	236  : 'SquareShelfTranIspddIsdeltaSSA2d',
+	237  : 'SquareShelfTranIspddIsdeltaSSA3d',
+	270  : 'SquareShelfStressSSA2dDamage',
+	272  : 'SquareShelfCMZSSA2dDamage',
+	274  : 'SquareShelfStressSSA2dDamageRift',
+	275  : 'SquareShelfDamageEvolutionSSA2d',
+	276  : 'SquareShelfDamageEvolutionSSA2dP2',
+	280  : 'SquareShelfStressSSA2dHigherOrder',
+	285  : 'SquareShelfStressHOHigherOrder',
+	290  : 'SquareShelfStressFSP2P1',
+	291  : 'SquareShelfStressFSP4z',
+	292  : 'SquareShelfTranSSA2dFloatingMeltParam',
+	301  : 'SquareSheetConstrainedStressSSA2d',
+	302  : 'SquareSheetConstrainedStressSIA2d',
+	303  : 'SquareSheetConstrainedStressSIASSA2d',
+	304  : 'SquareSheetConstrainedStressSSA3d',
+	305  : 'SquareSheetConstrainedStressSIA3d',
+	306  : 'SquareSheetConstrainedStressSIASSA3d',
+	307  : 'SquareSheetConstrainedStressHO',
+	308  : 'SquareSheetConstrainedStressFS',
+	309  : 'SquareSheetConstrainedMasstransp2d',
+	320  : 'SquareSheetConstrainedMasstransp2dDG',
+	311  : 'SquareSheetConstrainedMasstransp3d',
+	312  : 'SquareSheetConstrainedTherStea',
+	313  : 'SquareSheetConstrainedTherTran',
+	314  : 'SquareSheetConstrainedTranSIA2d',
+	315  : 'SquareSheetConstrainedTranSIA3d',
+	316  : 'SquareSheetConstrainedTranSSA2d',
+	317  : 'SquareSheetConstrainedTranHO',
+	318  : 'SquareSheetConstrainedSteaSIA3d',
+	319  : 'SquareSheetConstrainedCMDragSSA2d',
+	320  : 'SquareSheetConstrainedCMDragSSA3d',
+	321  : 'SquareSheetConstrainedCMDragHO',
+	322  : 'SquareSheetConstrainedCMDragFS',
+	323  : 'SquareSheetConstrainedTranCflSSA2d',
+	324  : 'SquareSheetConstrainedTranCflSIA3d',
+	325  : 'SquareSheetConstrainedEnthalpyStea',
+	326  : 'SquareSheetConstrainedEnthalpyTran',
+	327  : 'SquareSheetConstrainedTransHOEnth',
+	328  : 'SquareSheetConstrainedSmbGradients2d',
+	329  : 'SquareSheetConstrainedSmbGradients3d',
+	332  : 'SquareSheetConstrainedHydrologyDC',
+	333  : 'SquareSheetHydrologyDCTwoLayers',
+	401  : 'SquareSheetShelfStressSSA2d',
+	402  : 'SquareSheetShelfStressSSA3d',
+	403  : 'SquareSheetShelfStressHO',
+	404  : 'SquareSheetShelfStressFS',
+	405  : 'SquareSheetShelfStressMHOPenalties',
+	406  : 'SquareSheetShelfTherStea',
+	407  : 'SquareSheetShelfTherTran',
+	408  : 'SquareSheetShelfTranSSA2d',
+	409  : 'SquareSheetShelfTranMHOPenalties',
+	410  : 'SquareSheetShelfSteaSSA3d',
+	411  : 'SquareSheetShelfSteaHO',
+	412  : 'SquareSheetShelfDiadSSA3dDakota',
+	413  : 'SquareSheetShelfDiadSSA3dDakotaPart',
+	414  : 'SquareSheetShelfDiadSSA3dDakotaMassFlux',
+	415  : 'SquareSheetShelfCMDragSteaSSA3d',
+	416  : 'SquareSheetShelfCMDragSteaHO',
+	417  : 'SquareSheetShelfDiadSSA3dDakotaSamp',
+	418  : 'SquareSheetShelfDiadSSA3dDakotaAreaAverage',
+	419  : 'SquareSheetShelfStressSSAHOTiling',
+	420  : 'SquareSheetShelfDakotaScaledResponse',
+	421  : 'SquareSheetShelfStressHOFS3dTiling',
+	422  : 'SquareSheetShelfStressSSAFS3dTiling',
+	423  : 'RoundSheetShelfGLMigrationSSA2d',
+	424  : 'SquareSheetShelfGroundingLine2dAggressive',
+	425  : 'SquareSheetShelfGroundingLine2dSoft',
+	426  : 'SquareSheetShelfGroundingLine3dAggressive',
+	427  : 'SquareSheetShelfGroundingLine3dSoft',
+	428  : 'SquareSheetShelfStressSSA2dNewton',
+	429  : 'SquareSheetShelfStressHONewton',
+	431  : 'SquareSheetShelfSteaEnthalpySSA3d',
+	432  : 'SquareSheetShelfSteaEnthalpyHO',
+	433  : 'RoundSheetShelfGLMigrationSSA3d',
+	434  : 'SquareSheetShelfL1L2',
+	450  : 'SquareSheetShelfStressSSAHigherOrder',
+	455  : 'SquareSheetShelfStressHOHigherOrder',
+	501  : 'PigStressSSA2d',
+	502  : 'PigStressHO',
+	503  : 'PigStressFS',
+	504  : 'PigTranSSA2d',
+	505  : 'PigTranSSA3d',
+	506  : 'PigTranHO',
+	507  : 'PigTranFS',
+	508  : 'PigSteaSSA3d',
+	509  : 'PigSteaHO',
+	510  : 'PigSteaFS',
+	511  : 'PigCMBFS',
+	512  : 'PigCMDragHO',
+	513  : 'PigCMDragSteaSSA3d',
+	514  : 'PigBamgMesh',
+	515  : 'PigTherTranSUPG',
+	516  : 'PigTherSteaSUPG',
+	530  : 'PigBalVel1',
+	531  : 'PigBalVel2',
+	601  : '79NorthMasstransp2d',
+	602  : '79NorthMasstransp2dDG',
+	603  : '79NorthMasstransp3d',
+	604  : '79NorthSurfSlop2d',
+	605  : '79NorthSurfSlop3d',
+	606  : '79NorthBedSlop2d',
+	607  : '79NorthBedSlop3d',
+	608  : '79NorthBalThic2d',
+	609  : '79NorthBalThic2dDG',
+	610  : '79NorthBalThic3d',
+	611  : '79NorthCMBalThic2dCG',
+	613  : '79NorthCMBalThicVxVy',
+	801  : 'ValleyGlacierLevelsetSSA2d',	
+	802  : 'ValleyGlacierLevelsetThermalSSA3d',	
+	803  : 'ValleyGlacierLevelsetEnthalpyHO3d',	
+	804  : 'ValleyGlacierLevelsetCalvingSIA2d',	
+	805  : 'ValleyGlacierLevelsetEnthCalvingHO3d',	
+	1101 : 'ISMIPAHO',
+	1102 : 'ISMIPAFS',
+	1103 : 'ISMIPBHO',
+	1104 : 'ISMIPBFS',
+	1105 : 'ISMIPCHO',
+	1106 : 'ISMIPCFS',
+	1107 : 'ISMIPDHO',
+	1108 : 'ISMIPDFS',
+	1109 : 'ISMIPE',
+	1110 : 'ISMIPF',
+	1201 : 'EISMINTMassConservation',
+	1202 : 'EISMINTStress1',
+	1203 : 'EISMINTStress2',
+	1204 : 'EISMINTTran2',
+	1205 : 'EISMINTRoundIceSheetStaticSIA',
+	1206 : 'EISMINTRoundIceSheetStaticHO',
+	1207 : 'EISMINTRoundIceSheetStaticFS',
+	1208 : 'EISMINTA',
+	1301 : 'ThermalMelting',
+	1302 : 'ThermalAdvection',
+	1303 : 'ThermalConduction',
+	1304 : 'ThermalGeothermalFlux',
+	1401 : 'AdaptiveMeshRefinement1',
+	1402 : 'AdaptiveMeshRefinement2',
+	1501 : 'SquareShelfTranSawTooth2d',
+	1502 : 'SquareShelfTranSawTooth3d',
+	1601 : 'SquareShelfSSA2dRotation',
+	1602 : 'SquareSheetShelfHORotation',
+	2001 : 'SquareSheetConstrainedGia2d',
+	2051 : 'GiaBenchmarksAB2dA1',
+	2052 : 'GiaBenchmarksAB2dA2',
+	2053 : 'GiaBenchmarksAB2dA3',
+	2061 : 'GiaBenchmarksAB2dB1',
+	2062 : 'GiaBenchmarksAB2dB2',
+	2063 : 'GiaBenchmarksAB2dB3',
+	2071 : 'GiaBenchmarksAB2dC1',
+	2072 : 'GiaBenchmarksAB2dC2',
+	2073 : 'GiaBenchmarksAB2dC3',
+	2081 : 'GiaBenchmarksAB2dD1',
+	2082 : 'GiaBenchmarksAB2dD2',
+	2083 : 'GiaBenchmarksAB2dD3',
+	3001 : 'SquareShelfConstrainedStressSSA2dAdolc',
+	3002 : 'SquareShelfConstrainedStressSSA3dAdolc',
+	3003 : 'SquareShelfConstrainedStressHOAdolc',
+	3004 : 'SquareShelfConstrainedStressFSAdolc',
+	3005 : 'SquareShelfConstrainedMasstransp2dAdolc',
+	3006 : 'SquareShelfConstrainedMasstransp2dDGAdolc',
+	3007 : 'SquareShelfConstrainedMasstransp3dAdolc',
+	3008 : 'SquareShelfConstrainedTherSteaAdolc',
+	3009 : 'SquareShelfConstrainedTherTranAdolc',
+	3010 : 'SquareShelfConstrainedTranSSA2dAdolc',
+	3015 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifference',
+	3019 : 'SquareShelfConstrainedTherTranAdolcReverseVsForward',
+	3020 : 'SquareShelfConstrainedTranAdolcReverseVsForward',
+	3101 : 'SquareShelfConstrainedStressSSA2dAdolcMumps',
+	3102 : 'SquareShelfConstrainedStressSSA3dAdolcMumps',
+	3103 : 'SquareShelfConstrainedStressHOAdolcMumps',
+	3104 : 'SquareShelfConstrainedStressFSAdolcMumps',
+	3105 : 'SquareShelfConstrainedMasstransp2dAdolcMumps',
+	3106 : 'SquareShelfConstrainedMasstransp2dDGAdolcMumps',
+	3107 : 'SquareShelfConstrainedMasstransp3dAdolcMumps',
+	3108 : 'SquareShelfConstrainedTherSteaAdolcMumps',
+	3109 : 'SquareShelfConstrainedTherTranAdolcMumps',
+	3110 : 'SquareShelfConstrainedTranSSA2dAdolcMumps',
+	3115 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps',
+	3119 : 'SquareShelfConstrainedTherTranAdolcReverseVsForwardMumps',
+	3120 : 'SquareShelfConstrainedTranAdolcReverseVsForwardMumps',
+	3300 : 'SquareSheetHydrologyDCTwoLayersVolumeControl',
+	}
+
+	if not id == 0:
+		return idname.get(id,'N/A')
+	else:
+		return idname
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/Makefile
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/Makefile	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/Makefile	(revision 18231)
@@ -0,0 +1,2 @@
+clean: 
+	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.toolkits *.run valgrind.log* *.bat *.lock qmu*
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/README
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/README	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/README	(revision 18231)
@@ -0,0 +1,36 @@
+
+# running a test
+-----------------
+
+To run a test, just type: testxxx in matlab
+To check that the results of a test are similar to the Archive, type: runme('id',xxx)
+Several tests can be run at the same time.
+If no id if specified, all the tests will be done.
+All the archives are contained in ../Archives
+To update a test archive, use runme('procedure','update','id',xxx)
+Once again, if no id is specified, all the archives will be updated.
+
+
+# How to create a new test
+--------------------------
+
+This directory contains all the tests that run every night to check the code.
+The file IdToName associate a test id to its name.
+All the files necessary to run the tests can be found in:
+../Exp/ for the exp files (domains, contours, ...)
+../Par/ for the parameter files (to parameterize a model)
+../Data/ for the datasets needed to initialize a model
+To add a test, create a new testxxx.m and a testxxx_nightly.m
+
+The first number of the id correspond to the type of test:
+1: SquareShelfConstrained (no icefront)
+2: SquareShelf (with an icefront)
+3: SquareSheetConstrained (no icefront)
+4: SquareSheetShelf (Marine ice sheet with an ice shelf at the end)
+5: Pine Island Glacier
+6: 79North
+Add the id and testname in IdToName.m (incresing order)
+We try not to create too many .par and .exp files, so try to use the existing ones as much as possible.
+To modify some characteristics, do it in the testxxx.m file.
+Specify the field_names the field_values and the tolerance at the end of the test file.
+Don't forget to commit the archive (Archivexxx.nc in ../Archives)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad.m	(revision 18231)
@@ -0,0 +1,30 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','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);
+	%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)
+	};
+
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad_maxalloc.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad_maxalloc.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/ad_maxalloc.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/android.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/android.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/android.m	(revision 18231)
@@ -0,0 +1,32 @@
+md=triangle(model(),'../Exp/Square.exp',40000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('mprocessor',true,'module',true,'solution',true,'solver',true,'convergence',true,'control',true,'qmu',true,'autodiff',true);
+md.stressbalance.requested_outputs={'StressTensor'};
+md=solve(md,StressbalanceSolutionEnum());
+
+	
+index=md.mesh.elements;
+nel=length(index);
+x=md.mesh.x;
+y=md.mesh.y;
+z=md.mesh.z;
+vel=md.results.StressbalanceSolution.Vel;
+
+patch=zeros(nel,12);
+for i=1:nel,
+	patch(i,1)=x(index(i,1));
+	patch(i,2)=y(index(i,1));
+	patch(i,3)=z(index(i,1));
+	patch(i,4)=x(index(i,2));
+	patch(i,5)=y(index(i,2));
+	patch(i,6)=z(index(i,2));
+	patch(i,7)=x(index(i,3));
+	patch(i,8)=y(index(i,3));
+	patch(i,9)=z(index(i,3));
+	patch(i,10)=vel(index(i,1));
+	patch(i,11)=vel(index(i,2));
+	patch(i,12)=vel(index(i,3));
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_skipped_tests.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_skipped_tests.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_skipped_tests.txt	(revision 18231)
@@ -0,0 +1,22 @@
+%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
+
+test1401,test1402
+Roundoff error in ComputeHessian and ComputeMetric causes different meshes
+from matlab, specifically in the handling of 0/0=nan, eps/0=inf, etc.  Since
+the mesh is of a different size, NR fails.  (Note Matlab test1402 currently
+fails.)
+
+test1109,test1110
+Ugly crashes in solver, but same behavior as Matlab.
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_test_guidelines.txt
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_test_guidelines.txt	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/python_test_guidelines.txt	(revision 18231)
@@ -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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.m	(revision 18231)
@@ -0,0 +1,272 @@
+function varargout=runme(varargin)
+%RUNME - test deck for ISSM nightly runs
+%
+%   In a test deck directory (tests/Vertification/NightlyRun for example)
+%   The following command will launch all the existing tests:
+%   >> runme
+%   To run the tests 101 and 102:
+%   >> runme('id',[101 102])
+%   etc...
+%
+%   Available options:
+%      'id'            followed by the list of ids requested
+%      'exclude'       ids to be excluded from the test
+%      'benchmark'     'all' (all of them)
+%                      'nightly' (nightly run)
+%                      'ismip'  : validation of ismip-hom tests
+%                      'eismint': validation of eismint tests
+%                      'thermal': validation of thermal tests
+%                      'mesh'   : validation of mesh tests
+%                      'adolc'   : validation of adolc tests
+%                      'gia'   : validation of gia tests
+%                      ...
+%      'procedure'     'check' :   run the test (default)
+%                      'update':   update the archive
+%                      'valgrind': check for memory leaks (default value of md.debug.valgrind needs to be changed manually)
+%      'stoponerror'   1 or 0
+%
+%   Usage:
+%      runme(varargin);
+%
+%   Examples:
+%      runme;
+%      runme('exclude',101);
+%      runme('id',102,'procedure','update');
+
+%Get ISSM_DIR variable
+ISSM_DIR=issmdir();
+
+%Check inputs
+% {{{
+if nargout>1
+	help runme
+	error('runme error message: bad usage');
+end
+
+%recover options
+options=pairoptions(varargin{:});
+% }}}
+
+%Process options
+%GET benchmark {{{
+benchmark=getfieldvalue(options,'benchmark','nightly');
+if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia'})
+	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
+	benchmark='nightly';
+end
+% }}}
+%GET procedure {{{
+procedure=getfieldvalue(options,'procedure','check');
+if ~ismember(procedure,{'check','update','valgrind'})
+	disp('runme warning: procedure not supported, defaulting to test ''check''')
+	procedure='check';
+end
+% }}}
+%GET output {{{
+output=getfieldvalue(options,'output','none');
+if ~ismember(output,{'nightly','none'})
+	disp('runme warning: output not supported, defaulting to test ''none''')
+	output='none';
+end
+% }}}
+%GET RANK and NUMPROCS for multithreaded runs  {{{
+rank=getfieldvalue(options,'rank',1);
+numprocs=getfieldvalue(options,'numprocs',1);
+if (numprocs<rank), numprocs=1; end
+% }}}
+%GET ids  {{{
+flist=dir;%use dir, as it seems to act OS independent
+list_ids=[];
+for i=1:numel(flist),
+	if ( strncmp(flist(i).name,'test',4) &...                         %File name must start with 'test'
+			strncmp(fliplr(flist(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
+			~strcmp(flist(i).name,'test.m'))                            %File name must be different than 'test.m'
+		id=str2num(flist(i).name(5:end-2));
+		if isempty(id),
+			disp(['WARNING: ignore file ' flist(i).name ]);
+		else
+			list_ids(end+1)=eval(flist(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
+		end
+	end
+end
+[i1,i2]=parallelrange(rank,numprocs,length(list_ids));               %Get tests for this cpu only
+list_ids=list_ids(i1:i2);
+
+test_ids=getfieldvalue(options,'id',list_ids);
+test_ids=intersect(test_ids,list_ids);
+% }}}
+%GET exclude {{{
+exclude_ids=getfieldvalue(options,'exclude',[]);
+exclude_ids=[exclude_ids];
+pos=find(ismember(test_ids,exclude_ids));
+test_ids(pos)=[];
+% }}}
+%Process Ids according to benchmarks{{{
+if strcmpi(benchmark,'nightly'),
+	test_ids=intersect(test_ids,[1:999]);
+elseif strcmpi(benchmark,'validation'),
+	test_ids=intersect(test_ids,[1001:1999]);
+elseif strcmpi(benchmark,'ismip'),
+	test_ids=intersect(test_ids,[1101:1199]);
+elseif strcmpi(benchmark,'eismint'),
+	test_ids=intersect(test_ids,[1201:1299]);
+elseif strcmpi(benchmark,'thermal'),
+	test_ids=intersect(test_ids,[1301:1399]);
+elseif strcmpi(benchmark,'mesh'),
+	test_ids=intersect(test_ids,[1401:1499]);
+elseif strcmpi(benchmark,'tranforcing'),
+	test_ids=intersect(test_ids,[1501:1502]);
+elseif strcmpi(benchmark,'referential'),
+	test_ids=intersect(test_ids,[1601:1602]);
+elseif strcmpi(benchmark,'gia'),
+	test_ids=intersect(test_ids,[2001:2100]);
+elseif strcmpi(benchmark,'adolc'),
+	test_ids=intersect(test_ids,[3001:3200]);
+end
+% }}}
+
+%Loop over tests and launch sequence
+root=pwd;
+for id=test_ids,
+	try,
+
+		%Execute test
+		eval(['cd ' root ]);
+		id_string=IdToName(id);
+		disp(sprintf('%s%i%s','----------------starting:',id,'-----------------------'));
+		eval(['test' num2str(id)]);
+
+		%UPDATE ARCHIVE?
+		archive_name=['Archive' num2str(id) ];
+		if strcmpi(procedure,'update'),
+			delete(['../Archives/' archive_name '.nc'])
+			for k=1:length(field_names),
+				field=field_values{k};
+				% matlab writes the dimensions reversed and matrices transposed into netcdf, so compensate for that
+				nccreate(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)],...
+				         'Dimensions',{[archive_name '_field' num2str(k) '_2'] size(field,2) [archive_name '_field' num2str(k) '_1'] size(field,1)},...
+				         'Format','classic');
+				ncwrite(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)],transpose(field));
+			end
+			disp(sprintf(['File ./../Archives/' archive_name '.nc saved\n']));
+
+		%CHECK for memory leaks?
+		elseif strcmpi(procedure,'valgrind'),
+			fields = fieldnames(md.results);
+			for i=1:numel(fields)
+				if ~isfield(md.results.(fields{i}),'errlog'),
+					disp(['Skipping ' fields{i}]);
+					continue;
+				else
+					disp(['Extracting results of ' fields{i}]);
+				end
+				results = md.results.(fields{i});
+				errlog  = cellstr(results(1).errlog);
+
+				%Check leaks
+				lines  = strfind(errlog,'definitely lost:');
+				lines  = find(~cellfun(@isempty,lines));
+				leaks   = 0;
+				for j=1:numel(lines)
+					Line    = errlog(lines(j));
+					Numbers = sscanf(Line{1},'==%i==   definitely lost: %s bytes in %i blocks',[1 Inf]);
+					leaks   = leaks + str2num(strrep(char(Numbers(2:end-1)),',',''));
+				end
+				%Check conditional jumps
+				lines  = strfind(errlog,'Conditional jump or move depends on uninitialised value');
+				lines  = find(~cellfun(@isempty,lines));
+				jumps   = numel(lines);
+				%Check invalid read/write
+				lines  = strfind(errlog,'Invalid');
+				lines  = find(~cellfun(@isempty,lines));
+				inval  = numel(lines);
+				if leaks==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind mem. leaks'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind mem. leaks'],leaks,id,id_string));
+					disp('STOP');
+					return;
+				end
+				if jumps==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind cond. jumps'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind cond. jumps'],jumps,id,id_string));
+					disp('STOP');
+					return;
+				end
+				if inval==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind invalid read/write'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind invalid read/write'],inval,id,id_string));
+					disp('STOP');
+					return;
+				end
+			end
+
+		%ELSE: CHECK TEST
+		else,
+			for k=1:length(field_names),
+
+				try,
+					%Get field and tolerance
+					field=field_values{k};
+					fieldname=field_names{k};
+					tolerance=field_tolerances{k};
+
+					%compare to archive
+					% matlab reads the dimensions reversed and matrices transposed from netcdf, so compensate for that
+					archive=transpose(ncread(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)]));
+					error_diff=full(max(abs(archive(:)-field(:)))/(max(abs(archive))+eps));
+
+					%disp test result
+					if (error_diff>tolerance);
+						disp(sprintf(['ERROR   difference: %-7.2g > %7.2g test id: %i test name: %s field: %s'],...
+							error_diff,tolerance,id,id_string,fieldname));
+						if(getfieldvalue(options,'stoponerror',0)), disp('STOP'); return; end
+					else
+						disp(sprintf(['SUCCESS difference: %-7.2g < %7.2g test id: %i test name: %s field: %s'],...
+							error_diff,tolerance,id,id_string,fieldname));
+					end
+
+				catch me2
+
+					%something went wrong, print failure message:
+					message=getReport(me2);
+					fprintf('%s',message);
+					if strcmpi(output,'nightly')
+						fid=fopen([ISSM_DIR '/nightlylog/matlaberror.log'], 'at');
+						fprintf(fid,'%s',message);
+						fprintf(fid,'\n------------------------------------------------------------------\n');
+						fclose(fid);
+						disp(sprintf(['FAILURE difference: N/A test id: %i test name: %s field: %s'],id,id_string,fieldname));
+					else
+						disp(sprintf(['FAILURE difference: N/A test id: %i test name: %s field: %s'],id,id_string,fieldname));
+						fprintf('%s',message);
+						if(getfieldvalue(options,'stoponerror',0)), disp('STOP'); return; end
+					end
+					continue;
+				end
+			end
+		end
+		
+		disp(sprintf('%s%i%s','----------------finished:',id,'-----------------------'));
+
+	catch me,
+
+		%something went wrong, print failure message:
+		message=getReport(me);
+		fprintf('%s',message);
+		if strcmpi(output,'nightly')
+			fid=fopen([ISSM_DIR '/nightlylog/matlaberror.log'], 'at');
+			fprintf(fid,'%s',message);
+			fprintf(fid,'\n------------------------------------------------------------------\n');
+			fclose(fid);
+			disp(sprintf(['FAILURE difference: N/A test id: %i test name: %s field: %s'],id,id_string,'N/A'));
+		else
+			disp(sprintf(['FAILURE difference: N/A test id: %i test name: %s field: %s'],id,id_string,'N/A'));
+			rethrow(me);
+			if(getfieldvalue(options,'stoponerror',0)), disp('STOP'); return; end
+		end
+		disp(sprintf('%s%i%s','----------------finished:',id,'-----------------------'));
+	end
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/runme.py	(revision 18231)
@@ -0,0 +1,278 @@
+#! /usr/bin/env python
+import os
+import glob
+import socket
+import numpy
+import netCDF4
+import sys
+
+def runme(id=None,exclude=None,benchmark='nightly',procedure='check',output='none',rank=1,numprocs=1):
+	"""
+	RUNME - test deck for ISSM nightly runs
+ 
+	    In a test deck directory (tests/Vertification/NightlyRun for example)
+	    The following command will launch all the existing tests:
+	    >>> runme()
+	    To run the tests 101 and 102:
+	    >>> runme(id=[101,102])
+	    etc...
+ 
+	    Available options:
+	       'id'            followed by the list of ids requested
+	       'exclude'       ids to be excluded from the test
+	       'benchmark'     'all' (all of the tests)
+		                   'nightly' (nightly run/ daily run)
+	                       'ismip'  : validation of ismip-hom tests
+	                       'eismint': validation of eismint tests
+	                       'thermal': validation of thermal tests
+	                       'mesh'   : validation of mesh tests
+						   'adolc'   : validation of adolc tests
+                           'gia'   : validation of gia tests
+
+	                       ...
+	       'procedure'     'check' : run the test (default)
+	                       'update': update the archive
+ 
+	    Usage:
+	       runme(varargin);
+ 
+	    Examples:
+	       runme()
+	       runme(exclude=101)
+	       runme(id=102,procedure='update')
+	"""
+
+	from parallelrange import parallelrange
+	from IdToName import IdToName
+	from MatlabFuncs import strcmpi
+	from MatlabFuncs import ismember
+
+	#Get ISSM_DIR variable
+	ISSM_DIR=os.environ['ISSM_DIR']
+
+	#Process options
+	#GET benchmark {{{
+	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia']):
+		print "runme warning: benchmark '%s' not supported, defaulting to test 'nightly'." % benchmark
+		benchmark='nightly'
+	# }}}
+	#GET procedure {{{
+	if not ismember(procedure,['check','update']):
+		print "runme warning: procedure '%s' not supported, defaulting to test 'check'." % procedure
+		procedure='check'
+	# }}}
+	#GET output {{{
+	if not ismember(output,['nightly','daily','none']):
+		print "runme warning: output '%s' not supported, defaulting to test 'none'." % output
+		output='none'
+	# }}}
+	#GET RANK and NUMPROCS for multithreaded runs {{{
+	if (numprocs<rank):
+		numprocs=1
+	# }}}
+	#GET ids  {{{
+	flist=glob.glob('test*.py')    #File name must start with 'test' and must end by '.py' and must be different than 'test.py'
+	list_ids=[int(file[4:-3]) for file in flist if not file == 'test.py']    #Keep test id only (skip 'test' and '.py')
+	#print 'list_ids =',list_ids
+
+	i1,i2=parallelrange(rank,numprocs,len(list_ids))    #Get tests for this cpu only
+	list_ids=list_ids[i1:i2+1]
+	#print 'list_ids after parallelrange =',list_ids
+
+	if id:
+		if isinstance(id,list):
+			test_ids=id
+		else:
+			test_ids=[id]
+		test_ids=set(test_ids).intersection(set(list_ids))
+	else:
+		test_ids=set(list_ids)
+	#print 'test_ids after list =',test_ids
+	# }}}
+	#GET exclude {{{
+	if exclude:
+		if isinstance(exclude,list):
+			exclude_ids=exclude
+		else:
+			exclude_ids=[exclude]
+		test_ids=test_ids.difference(set(exclude_ids))
+#	print 'test_ids after exclude =',test_ids
+	# }}}
+	#Process Ids according to benchmarks {{{
+	if   strcmpi(benchmark,'nightly'):
+		test_ids=test_ids.intersection(set(range(1,1000)))
+	elif strcmpi(benchmark,'validation'):
+		test_ids=test_ids.intersection(set(range(1001,2000)))
+	elif strcmpi(benchmark,'ismip'):
+		test_ids=test_ids.intersection(set(range(1101,1200)))
+	elif strcmpi(benchmark,'eismint'):
+		test_ids=test_ids.intersection(set(range(1201,1300)))
+	elif strcmpi(benchmark,'thermal'):
+		test_ids=test_ids.intersection(set(range(1301,1400)))
+	elif strcmpi(benchmark,'mesh'):
+		test_ids=test_ids.intersection(set(range(1401,1500)))
+	elif strcmpi(benchmark,'tranforcing'):
+		test_ids=test_ids.intersection(set(range(1501,1503)))
+	elif strcmpi(benchmark,'referential'):
+		test_ids=test_ids.intersection(set(range(1601,1603)))
+	elif strcmpi(benchmark,'gia'):
+		test_ids=test_ids.intersection(set(range(2001,2100)))
+	elif strcmpi(benchmark,'adolc'):
+		test_ids=test_ids.intersection(set(range(3001,3200)))
+	#print 'test_ids after benchmark =',test_ids
+	test_ids=list(test_ids)
+	test_ids.sort()
+	#print 'test_ids after sort =',test_ids
+	# }}}
+
+	#Loop over tests and launch sequence
+	root=os.getcwd()
+	for id in test_ids:
+		try:
+
+			#Execute test
+			os.chdir(root)
+			id_string=IdToName(id)
+			print "----------------starting:%i-----------------------" % id
+			execfile('test'+str(id)+'.py',globals())
+
+			#UPDATE ARCHIVE?
+			archive_name='Archive'+str(id)
+			if strcmpi(procedure,'update'):
+				archive=os.path.join('..','Archives',archive_name+'.nc')
+				if os.path.isfile(archive):
+					os.remove(archive)
+				f = netCDF4.Dataset(archive,'w',format='NETCDF3_CLASSIC')
+				for k,fieldname in enumerate(field_names):
+					field=numpy.array(field_values[k],dtype=float)
+					if len(field.shape) == 1:
+						if numpy.size(field):
+							field=field.reshape(numpy.size(field),1)
+						else:
+							field=field.reshape(0,0)
+					elif len(field.shape) == 0:
+						field=field.reshape(1,1)
+					# Matlab uses base 1, so use base 1 in labels
+					f.createDimension(archive_name+'_field'+str(k+1)+'_1',numpy.size(field,0))
+					f.createDimension(archive_name+'_field'+str(k+1)+'_2',numpy.size(field,1))
+					v = f.createVariable(archive_name+'_field'+str(k+1),field.dtype,(archive_name+'_field'+str(k+1)+'_1',archive_name+'_field'+str(k+1)+'_2'))
+					v[:] = field
+				f.close()
+				print "File '%s' saved.\n" % os.path.join('..','Archives',archive_name+'.nc')
+
+			#ELSE: CHECK TEST
+			else:
+
+				#load archive
+				if os.path.exists(os.path.join('..','Archives',archive_name+'.nc')):
+					f = netCDF4.Dataset(os.path.join('..','Archives',archive_name+'.nc'),'r')
+				else:
+					raise IOError("Archive file '"+os.path.join('..','Archives',archive_name+'.nc')+"' does not exist.")
+
+				for k,fieldname in enumerate(field_names):
+
+					try:
+						#Get field and tolerance
+						field=numpy.array(field_values[k])
+						if len(field.shape) == 1:
+							if numpy.size(field):
+								field=field.reshape(numpy.size(field),1)
+							else:
+								field=field.reshape(0,0)
+						tolerance=field_tolerances[k]
+
+						#compare to archive
+						# Matlab uses base 1, so use base 1 in labels
+						if archive_name+'_field'+str(k+1) in f.variables:
+							archive=f.variables[archive_name+'_field'+str(k+1)][:]
+						else:
+							raise NameError("Field name '"+archive_name+'_field'+str(k+1)+"' does not exist in archive file.")
+						error_diff=numpy.amax(numpy.abs(archive-field),axis=0)/ \
+								   (numpy.amax(numpy.abs(archive),axis=0)+sys.float_info.epsilon)
+
+						#disp test result
+						if (numpy.any(error_diff>tolerance)):
+							print 'ERROR   difference: %-7.2g > %7.2g test id: %i test name: %s field: %s' % \
+								(error_diff,tolerance,id,id_string,fieldname)
+						else:
+							print 'SUCCESS difference: %-7.2g < %7.2g test id: %i test name: %s field: %s' % \
+								(error_diff,tolerance,id,id_string,fieldname)
+
+					except Exception as me2:
+
+						#something went wrong, print failure message:
+						directory=os.getcwd().split('/')    #  not used?
+						message=me2
+						if   strcmpi(output,'nightly'):
+							fid=open(os.path.join(ISSM_DIR,'nightlylog','pythonerror.log'), 'a')
+							fid.write('%s' % message)
+							fid.write('\n------------------------------------------------------------------\n')
+							fid.close()
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+						elif strcmpi(output,'daily'):
+							fid=open(os.path.join(ISSM_DIR,'dailylog','pythonerror.log'), 'a')
+							fid.write('%s' % message)
+							fid.write('\n------------------------------------------------------------------\n')
+							fid.close()
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+						else:
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+							raise RuntimeError(me2)
+
+				f.close()
+				print "----------------finished:%i-----------------------" % id
+
+		except Exception as me:
+
+			#something went wrong, print failure message:
+			directory=os.getcwd().split('/')    #  not used?
+			message=me
+			if   strcmpi(output,'nightly'):
+				fid=open(os.path.join(ISSM_DIR,'nightlylog','pythonerror.log'), 'a')
+				fid.write('%s' % message)
+				fid.write('\n------------------------------------------------------------------\n')
+				fid.close()
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+			elif strcmpi(output,'daily'):
+				fid=open(os.path.join(ISSM_DIR,'dailylog','pythonerror.log'), 'a')
+				fid.write('%s' % message)
+				fid.write('\n------------------------------------------------------------------\n')
+				fid.close()
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+			else:
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+				raise RuntimeError(me)
+			print "----------------finished:%i-----------------------" % id
+
+	return
+
+import argparse
+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
+
+	parser = argparse.ArgumentParser(description='RUNME - test deck for ISSM nightly runs')
+	parser.add_argument('-i','--id', nargs='*', type=int, help='followed by the list of ids requested', default=[])
+	parser.add_argument('-e','--exclude', nargs='+', type=int, help='ids to be excluded from the test', default=[])
+	parser.add_argument('-b','--benchmark', help='nightly/ismip/eismint/thermal/mesh/...', default='nightly')
+	parser.add_argument('-p','--procedure', help='check/update', default='check')
+	parser.add_argument('-o','--output', help='nightly/daily/none', default='none')
+	parser.add_argument('-r','--rank', type=int, help='rank', default=1)
+	parser.add_argument('-n','--numprocs', type=int, help='numprocs', default=1)
+	args = parser.parse_args()
+
+	md = runme(args.id, args.exclude, args.benchmark, args.procedure, args.output, args.rank, args.numprocs)
+
+	from MatlabFuncs import strcmpi
+	if strcmpi(args.output,'nightly'):
+		print "PYTHONEXITEDCORRECTLY"
+
+	exit(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.m	(revision 18231)
@@ -0,0 +1,40 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',2);
+
+%output
+md.stressbalance.requested_outputs={'default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
+md.outputdefinition.definitions={...
+	massfluxatgate('MassFlux1',['../Exp/MassFlux1.exp']),...
+	massfluxatgate('MassFlux2',['../Exp/MassFlux2.exp']),...
+	massfluxatgate('MassFlux3',['../Exp/MassFlux3.exp']),...
+	massfluxatgate('MassFlux4',['../Exp/MassFlux4.exp']),...
+	massfluxatgate('MassFlux5',['../Exp/MassFlux5.exp']),...
+	massfluxatgate('MassFlux6',['../Exp/MassFlux6.exp'])...
+	};
+
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
+field_tolerances={2e-13,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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.DeviatoricStressxx),...
+	(md.results.StressbalanceSolution.DeviatoricStressyy),...
+	(md.results.StressbalanceSolution.DeviatoricStressxy),...
+	(md.results.StressbalanceSolution.MassFlux1),...
+	(md.results.StressbalanceSolution.MassFlux2),...
+	(md.results.StressbalanceSolution.MassFlux3),...
+	(md.results.StressbalanceSolution.MassFlux4),...
+	(md.results.StressbalanceSolution.MassFlux5),...
+	(md.results.StressbalanceSolution.MassFlux6)...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test101.py	(revision 18231)
@@ -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 *
+from massfluxatgate import massfluxatgate
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',50000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#outputs
+md.stressbalance.requested_outputs=['default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
+md.outputdefinition.definitions=[
+		massfluxatgate('MassFlux1','../Exp/MassFlux1.exp'),
+		massfluxatgate('MassFlux2','../Exp/MassFlux2.exp'),
+		massfluxatgate('MassFlux3','../Exp/MassFlux3.exp'),
+		massfluxatgate('MassFlux4','../Exp/MassFlux4.exp'),
+		massfluxatgate('MassFlux5','../Exp/MassFlux5.exp'),
+		massfluxatgate('MassFlux6','../Exp/MassFlux6.exp')
+		]
+
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure',\
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
+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 ]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.DeviatoricStressxx,\
+	md.results.StressbalanceSolution.DeviatoricStressyy,\
+	md.results.StressbalanceSolution.DeviatoricStressxy,\
+	md.results.StressbalanceSolution.MassFlux1,\
+	md.results.StressbalanceSolution.MassFlux2,\
+	md.results.StressbalanceSolution.MassFlux3,\
+	md.results.StressbalanceSolution.MassFlux4,\
+	md.results.StressbalanceSolution.MassFlux5,\
+	md.results.StressbalanceSolution.MassFlux6 ]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test102.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.m	(revision 18231)
@@ -0,0 +1,27 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+md=solve(md,StressbalanceSolutionEnum());
+
+%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-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test103.py	(revision 18231)
@@ -0,0 +1,36 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+md=solve(md,StressbalanceSolutionEnum())
+
+#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-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-06,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test104.py	(revision 18231)
@@ -0,0 +1,27 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2.)
+md=setflowequation(md,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,1e-06,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.m	(revision 18231)
@@ -0,0 +1,13 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test105.py	(revision 18231)
@@ -0,0 +1,22 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test106.py	(revision 18231)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=meshconvert(md)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,5,3.);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test107.py	(revision 18231)
@@ -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,'SSA','all')
+md.extrude(5,3.)
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-5};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test108.py	(revision 18231)
@@ -0,0 +1,25 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-5]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test109.py	(revision 18231)
@@ -0,0 +1,28 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.m	(revision 18231)
@@ -0,0 +1,40 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs={'IceVolume'};
+
+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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test110.py	(revision 18231)
@@ -0,0 +1,49 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.requested_outputs=['IceVolume']
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].IceVolume,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.m	(revision 18231)
@@ -0,0 +1,128 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+printingflag=false;
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+minvx=[];
+maxvx=[];
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=20; %numberof nodes in x direction
+	ny=20;
+	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=setflowequation(md,'HO','all');
+
+	%Create dirichlet on the bed only
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x)); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
+	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
+
+	%Now plot vx, vy, vz and vx on a cross section
+	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag, 
+		set(gcf,'Color','w')
+		printmodel(['ismipaHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag, 
+		set(gcf,'Color','w')
+		printmodel(['ismipaHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag, 
+		set(gcf,'Color','w')
+		printmodel(['ismipaHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+
+	if(L==5000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 18],'xlim',[0 5000],'title','','xlabel','')
+	elseif(L==10000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 30],'xlim',[0 10000],'title','','xlabel','')
+	elseif(L==20000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 50],'xlim',[0 20000],'title','','xlabel','')
+	elseif(L==40000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 80],'xlim',[0 40000],'title','','xlabel','')
+	elseif(L==80000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 100],'xlim',[0 80000],'title','','xlabel','')
+	elseif(L==160000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	end
+	if printingflag, 
+		set(gcf,'Color','w')
+		printmodel(['ismipaHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+end
+
+%Now plot the min and max values of vx for each size of the square
+plot([5 10 20 40 80 160],minvx);ylim([0 18]);xlim([0 160])
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel('ismipaHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+end
+plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel('ismipaHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-08,1e-08,1e-08,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1101.py	(revision 18231)
@@ -0,0 +1,153 @@
+import numpy
+import shutil
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+printingflag=False
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+minvx=[]
+maxvx=[]
+
+for L in L_list:
+	nx=20    #numberof nodes in x direction
+	ny=20
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPA.py')
+	md.extrude(9,1.)
+
+	md=setflowequation(md,'HO','all')
+
+	#Create dirichlet on the bed only
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+
+	#Create MPCs to have periodic boundary conditions
+	posx=numpy.nonzero(md.mesh.x==0.)[0]
+	posx2=numpy.nonzero(md.mesh.x==numpy.max(md.mesh.x))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
+	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
+
+	#Now plot vx, vy, vz and vx on a cross section
+#	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+	if   (L==5000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 18],'xlim',[0 5000],'title','','xlabel','')
+	elif (L==10000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 30],'xlim',[0 10000],'title','','xlabel','')
+	elif (L==20000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 50],'xlim',[0 20000],'title','','xlabel','')
+	elif (L==40000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 80],'xlim',[0 40000],'title','','xlabel','')
+	elif (L==80000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 100],'xlim',[0 80000],'title','','xlabel','')
+	elif (L==160000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+#Now plot the min and max values of vx for each size of the square
+#plot([5 10 20 40 80 160],minvx);ylim([0 18]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipaHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipaHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-09,1e-09,1e-09,\
+	1e-10,1e-10,1e-09,\
+	1e-09,1e-09,1e-09,\
+	1e-09,1e-08,1e-09,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-07,1e-08,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.m	(revision 18231)
@@ -0,0 +1,138 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+printingflag=false;
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+minvx=[];
+maxvx=[];
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=20; %numberof nodes in x direction
+	ny=20;
+	md=model();
+	md=squaremesh(md,L,L,nx,ny);
+	md=setmask(md,'',''); %ice sheet test
+
+%	%Find elements at the corner and extract model
+%	posnodes=find((md.mesh.x==0. | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0. | md.mesh.y==max(md.mesh.y)));
+%	[a,b]=find(ismember(md.mesh.elements,posnodes));
+%	elements=ones(md.mesh.numberofelements,1);
+%	elements(a)=0;
+%	md=modelextract(md,elements);
+
+	md=parameterize(md,'../Par/ISMIPA.par');
+	md=extrude(md,10,1.);
+	md=setflowequation(md,'FS','all');
+
+	%Create dirichlet on the bed only
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
+
+%	%Create MPCs to have periodic boundary conditions
+%	posx=find(md.mesh.x==0.);
+%	posx2=find(md.mesh.x==max(md.mesh.x));
+%	posx=find(md.mesh.x==0. & md.mesh.y~=0. & md.mesh.y~=max(md.mesh.y) & ~md.mesh.vertexonbase);
+%	posx2=find(md.mesh.x==max(md.mesh.x) &  md.mesh.y~=0. & md.mesh.y~=max(md.mesh.y) & ~md.mesh.vertexonbase);
+
+%	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x) & ~md.mesh.vertexonbase); %Don't take the same nodes two times
+%	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x) & ~md.mesh.vertexonbase);
+
+%	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the stressbalance
+	md.stressbalance.abstol=NaN;
+	md.stressbalance.reltol=NaN;
+	md.stressbalance.restol=1.;
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	pressure=(md.results.StressbalanceSolution.Pressure);
+	results{i}=md.results.StressbalanceSolution;
+	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
+	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
+
+	%Now plot vx, vy, vz and vx on a cross section
+	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipaFSvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipaFSvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipaFSvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+
+	if(L==5000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 18],'xlim',[0 5000],'title','','xlabel','')
+	elseif(L==10000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 30],'xlim',[0 10000],'title','','xlabel','')
+	elseif(L==20000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 50],'xlim',[0 20000],'title','','xlabel','')
+	elseif(L==40000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 80],'xlim',[0 40000],'title','','xlabel','')
+	elseif(L==80000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 100],'xlim',[0 80000],'title','','xlabel','')
+	elseif(L==160000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	end
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipaFSvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	end
+end
+
+%Now plot the min and max values of vx for each size of the square
+plot([5 10 20 40 80 160],minvx);ylim([0 18])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipaFSminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaFSminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+end
+plot([5 10 20 40 80 160],maxvx);ylim([0 120])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipaFSmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaFSmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-12,1e-11,1e-12,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1102.py	(revision 18231)
@@ -0,0 +1,163 @@
+import numpy
+import shutil
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+printingflag=False
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+minvx=[]
+maxvx=[]
+
+for L in L_list:
+	nx=20    #numberof nodes in x direction
+	ny=20
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+
+#	#Find elements at the corner and extract model
+#	posnodes=numpy.nonzero(numpy.logical_and(numpy.logical_or(md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x)),numpy.logical_or(md.mesh.y==0.,md.mesh.y==numpy.max(md.mesh.y))))
+#	a=numpy.nonzero(ismember(md.mesh.elements,posnodes))[0]
+#	elements=numpy.ones((md.mesh.numberofelements),int)
+#	elements[a]=0
+#	md.modelextract(elements)
+
+	md=parameterize(md,'../Par/ISMIPA.py')
+	md.extrude(10,1.)
+	md=setflowequation(md,'FS','all')
+
+	#Create dirichlet on the bed only
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
+
+#	#Create MPCs to have periodic boundary conditions
+#	posx=numpy.nonzero(md.mesh.x==0.)[0]
+#	posx2=numpy.nonzero(md.mesh.x==numpy.max(md.mesh.x))[0]
+#	posx=numpy.nonzero(logical_and_n(md.mesh.x==0.,md.mesh.y!=0.,md.mesh.y!=numpy.max(md.mesh.y),numpy.logical_not(md.mesh.vertexonbase)))[0]
+#	posx2=numpy.nonzero(logical_and_n(md.mesh.x==numpy.max(md.mesh.x),md.mesh.y!=0.,md.mesh.y!=numpy.max(md.mesh.y),numpy.logical_not(md.mesh.vertexonbase)))[0]
+
+#	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x),numpy.logical_not(md.mesh.vertexonbase)))[0]    #Don't take the same nodes two times
+#	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x),numpy.logical_not(md.mesh.vertexonbase)))[0]
+
+#	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Compute the stressbalance
+	md.stressbalance.abstol=float('NaN')
+	md.stressbalance.reltol=float('NaN')
+	md.stressbalance.restol=1.
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	pressure=md.results.StressbalanceSolution.Pressure
+	results.append(md.results.StressbalanceSolution)
+	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
+	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
+
+	#Now plot vx, vy, vz and vx on a cross section
+#	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaFSvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaFSvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaFSvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+	if   (L==5000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 18],'xlim',[0 5000],'title','','xlabel','')
+	elif (L==10000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 30],'xlim',[0 10000],'title','','xlabel','')
+	elif (L==20000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 50],'xlim',[0 20000],'title','','xlabel','')
+	elif (L==40000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 80],'xlim',[0 40000],'title','','xlabel','')
+	elif (L==80000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 100],'xlim',[0 80000],'title','','xlabel','')
+	elif (L==160000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipaFSvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvxsec.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+#Now plot the min and max values of vx for each size of the square
+#plot([5 10 20 40 80 160],minvx);ylim([0 18])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipaFSminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaFSminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#plot([5 10 20 40 80 160],maxvx);ylim([0 120])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipaFSmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaFSmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-11,1e-12,\
+	1e-12,1e-11,1e-12,\
+	1e-12,1e-11,1e-12,\
+	1e-12,1e-11,1e-12,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.m	(revision 18231)
@@ -0,0 +1,121 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+printingflag=false;
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+minvx=[];
+maxvx=[];
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=20; %numberof nodes in x direction
+	ny=20;
+	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=setflowequation(md,'HO','all');
+
+	%Create dirichlet on the bed only
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x)); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
+	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
+
+	%Now plot vx, vy, vz and vx on a cross section
+	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipbHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+	end
+	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipbHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+	end
+
+	if(L==5000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[6 16],'xlim',[0 5000],'title','','xlabel','')
+	elseif(L==10000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 40],'xlim',[0 10000],'title','','xlabel','')
+	elseif(L==20000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 60],'xlim',[0 20000],'title','','xlabel','')
+	elseif(L==40000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 100],'xlim',[0 40000],'title','','xlabel','')
+	elseif(L==80000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 120],'xlim',[0 80000],'title','','xlabel','')
+	elseif(L==160000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	end
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipbHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+	end
+end
+
+%Now plot the min and max values of vx for each size of the square
+plot([5 10 20 40 80 160],minvx);ylim([0 14]);xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipbHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+end
+plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipbHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-08,1e-07,1e-07,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1103.py	(revision 18231)
@@ -0,0 +1,146 @@
+import numpy
+import shutil
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+printingflag=False
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+minvx=[]
+maxvx=[]
+
+for L in L_list:
+	nx=20    #numberof nodes in x direction
+	ny=20
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPB.py')
+	md.extrude(10,1.)
+
+	md=setflowequation(md,'HO','all')
+
+	#Create dirichlet on the bed only
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+
+	#Create MPCs to have periodic boundary conditions
+	posx=numpy.nonzero(md.mesh.x==0.)[0]
+	posx2=numpy.nonzero(md.mesh.x==numpy.max(md.mesh.x))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+	minvx.append(numpy.min(vx[md.mesh.numberofvertices2d:]))
+	maxvx.append(numpy.max(vx[md.mesh.numberofvertices2d:]))
+
+	#Now plot vx, vy, vz and vx on a cross section
+#	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipbHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipbHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+
+	if   (L==5000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[6 16],'xlim',[0 5000],'title','','xlabel','')
+	elif (L==10000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 40],'xlim',[0 10000],'title','','xlabel','')
+	elif (L==20000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 60],'xlim',[0 20000],'title','','xlabel','')
+	elif (L==40000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 100],'xlim',[0 40000],'title','','xlabel','')
+	elif (L==80000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 120],'xlim',[0 80000],'title','','xlabel','')
+	elif (L==160000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 120],'xlim',[0 160000],'title','','xlabel','')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipbHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+
+#Now plot the min and max values of vx for each size of the square
+#plot([5 10 20 40 80 160],minvx);ylim([0 14]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipbHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipbHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipbHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipbHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-09,1e-09,1e-09,\
+	1e-09,1e-09,1e-09,\
+	1e-09,1e-09,1e-09,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-07,1e-07,\
+	1e-07,1e-06,1e-07,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.m	(revision 18231)
@@ -0,0 +1,72 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=20; %numberof nodes in x direction
+	ny=20;
+	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=setflowequation(md,'HO','all');
+
+	%Create dirichlet on the bed only
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x)); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the stressbalance
+	md.stressbalance.abstol=NaN;
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+	pos=find(md.mesh.x==0. | md.mesh.y==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y));
+	md.stressbalance.spcvx(pos)=md.results.StressbalanceSolution.Vx(pos);
+	md.stressbalance.spcvy(pos)=md.results.StressbalanceSolution.Vy(pos);
+	md.stressbalance.vertex_pairing=[];
+	md=setflowequation(md,'FS','all');
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-08,1e-07,1e-08,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1104.py	(revision 18231)
@@ -0,0 +1,90 @@
+import numpy
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+
+for L in L_list:
+	nx=20    #numberof nodes in x direction
+	ny=20
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPB.py')
+	md.extrude(10,1.)
+	md=setflowequation(md,'HO','all')
+
+	#Create dirichlet on the bed only
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+
+	#Create MPCs to have periodic boundary conditions
+	posx=numpy.nonzero(md.mesh.x==0.)[0]
+	posx2=numpy.nonzero(md.mesh.x==numpy.max(md.mesh.x))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Compute the stressbalance
+	md.stressbalance.abstol=float('NaN')
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+	pos=numpy.nonzero(logical_or_n(md.mesh.x==0.,md.mesh.y==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==numpy.max(md.mesh.y)))
+	md.stressbalance.spcvx[pos]=md.results.StressbalanceSolution.Vx[pos]
+	md.stressbalance.spcvy[pos]=md.results.StressbalanceSolution.Vy[pos]
+	md.stressbalance.vertex_pairing=numpy.empty((0,2),int)
+	md=setflowequation(md,'FS','all')
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+
+#	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-07,1e-08,\
+	1e-07,1e-07,1e-07,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.m	(revision 18231)
@@ -0,0 +1,151 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+printingflag=false;
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+minvx=[];
+maxvx=[];
+
+for i=1:length(L_list),
+	L=L_list{i};  %in m (3 times the desired length for BC problems)  
+	nx=30; %number of nodes in x direction
+	ny=30;
+	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=setflowequation(md,'HO','all');
+
+	%Create MPCs to have periodic boundary conditions
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	posx=find(md.mesh.x==0. & md.mesh.y~=0. & md.mesh.y~=L);
+	posx2=find(md.mesh.x==L & md.mesh.y~=0. & md.mesh.y~=L);
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=L); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==L & md.mesh.x~=0. & md.mesh.x~=L);
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Add spc on the corners
+	pos=find((md.mesh.x==0. | md.mesh.x==L) & (md.mesh.y==0. | md.mesh.y==L) & md.mesh.vertexonbase);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	if(L==5000.),
+		md.stressbalance.spcvx(pos)=15.66;
+		md.stressbalance.spcvy(pos)=-0.1967;
+	elseif(L==10000.),
+		md.stressbalance.spcvx(pos)=16.04;
+		md.stressbalance.spcvy(pos)=-0.1977;
+	elseif(L==20000.),
+		md.stressbalance.spcvx(pos)=16.53;
+		md.stressbalance.spcvy(pos)=-1.27;
+	elseif(L==40000.),
+		md.stressbalance.spcvx(pos)=17.23;
+		md.stressbalance.spcvy(pos)=-3.17;
+	elseif(L==80000.),
+		md.stressbalance.spcvx(pos)=16.68;
+		md.stressbalance.spcvy(pos)=-2.69;
+	elseif(L==160000.),
+		md.stressbalance.spcvx(pos)=16.03;
+		md.stressbalance.spcvy(pos)=-1.27;
+	end
+	
+	%Spc the bed at zero for vz
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvz(pos)=0.;
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
+	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
+
+	%Now plot vx, vy, vz and vx on a cross section
+	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipcHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	end
+	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipcHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	end
+	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipcHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	end
+
+	if(L==5000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 20],'xlim',[0 5000],'title','','xlabel','','figure',5)
+	elseif(L==10000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[13 18],'xlim',[0 10000],'title','','xlabel','')
+	elseif(L==20000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[14 22],'xlim',[0 20000],'title','','xlabel','')
+	elseif(L==40000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 40],'xlim',[0 40000],'title','','xlabel','')
+	elseif(L==80000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 80],'xlim',[0 80000],'title','','xlabel','')
+	elseif(L==160000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 200],'xlim',[0 160000],'title','','xlabel','')
+	end
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipcHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	end
+end
+
+%Now plot the min and max values of vx for each size of the square
+plot([5 10 20 40 80 160],minvx);ylim([4 18]);xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipcHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+end
+plot([5 10 20 40 80 160],maxvx);ylim([0 200]); xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipcHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-09,1e-08,1e-08,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1105.py	(revision 18231)
@@ -0,0 +1,175 @@
+import numpy
+import shutil
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+printingflag=False
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+minvx=[]
+maxvx=[]
+
+for L in L_list:    #in m (3 times the desired length for BC problems)  
+	nx=30    #number of nodes in x direction
+	ny=30
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPC.py')
+	md.extrude(10,1.)
+
+	md=setflowequation(md,'HO','all')
+
+	#Create MPCs to have periodic boundary conditions
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+
+	posx=numpy.nonzero(logical_and_n(md.mesh.x==0.,md.mesh.y!=0.,md.mesh.y!=L))[0]
+	posx2=numpy.nonzero(logical_and_n(md.mesh.x==L,md.mesh.y!=0.,md.mesh.y!=L))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=L))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==L,md.mesh.x!=0.,md.mesh.x!=L))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Add spc on the corners
+	pos=numpy.nonzero(logical_and_n(numpy.logical_or(md.mesh.x==0.,md.mesh.x==L),numpy.logical_or(md.mesh.y==0.,md.mesh.y==L),md.mesh.vertexonbase))
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	if   (L==5000.):
+		md.stressbalance.spcvx[pos]=15.66
+		md.stressbalance.spcvy[pos]=-0.1967
+	elif (L==10000.):
+		md.stressbalance.spcvx[pos]=16.04
+		md.stressbalance.spcvy[pos]=-0.1977
+	elif (L==20000.):
+		md.stressbalance.spcvx[pos]=16.53
+		md.stressbalance.spcvy[pos]=-1.27
+	elif (L==40000.):
+		md.stressbalance.spcvx[pos]=17.23
+		md.stressbalance.spcvy[pos]=-3.17
+	elif (L==80000.):
+		md.stressbalance.spcvx[pos]=16.68
+		md.stressbalance.spcvy[pos]=-2.69
+	elif (L==160000.):
+		md.stressbalance.spcvx[pos]=16.03
+		md.stressbalance.spcvy[pos]=-1.27
+	
+	#Spc the bed at zero for vz
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvz[pos]=0.
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
+	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
+
+	#Now plot vx, vy, vz and vx on a cross section
+#	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipcHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipcHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipcHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+
+	if   (L==5000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 20],'xlim',[0 5000],'title','','xlabel','','figure',5)
+	elif (L==10000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[13 18],'xlim',[0 10000],'title','','xlabel','')
+	elif (L==20000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[14 22],'xlim',[0 20000],'title','','xlabel','')
+	elif (L==40000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 40],'xlim',[0 40000],'title','','xlabel','')
+	elif (L==80000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 80],'xlim',[0 80000],'title','','xlabel','')
+	elif (L==160000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 200],'xlim',[0 160000],'title','','xlabel','')
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipcHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+
+#Now plot the min and max values of vx for each size of the square
+#plot([5 10 20 40 80 160],minvx);ylim([4 18]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipcHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipcHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#plot([5 10 20 40 80 160],maxvx);ylim([0 200]); xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipcHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipcHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-08,1e-07,1e-07,\
+	1e-09,1e-07,1e-07,\
+	1e-09,1e-09,1e-07,\
+	1e-09,1e-09,1e-08,\
+	1e-09,1e-08,1e-08,\
+	1e-09,1e-08,1e-08,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.m	(revision 18231)
@@ -0,0 +1,70 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+
+for i=1:length(L_list),
+	L=L_list{i};  
+	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.);
+
+	%Add spc on the borders
+	pos=find(md.mesh.x==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==0. | md.mesh.y==max(md.mesh.y));
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	if(L==5000.),
+		md.stressbalance.spcvx(pos)=15.66;
+		md.stressbalance.spcvy(pos)=-0.1967;
+	elseif(L==10000.),
+		md.stressbalance.spcvx(pos)=16.04;
+		md.stressbalance.spcvy(pos)=-0.1977;
+	elseif(L==20000.),
+		md.stressbalance.spcvx(pos)=16.53;
+		md.stressbalance.spcvy(pos)=-1.27;
+	elseif(L==40000.),
+		md.stressbalance.spcvx(pos)=17.23;
+		md.stressbalance.spcvy(pos)=-3.17;
+	elseif(L==80000.),
+		md.stressbalance.spcvx(pos)=16.68;
+		md.stressbalance.spcvy(pos)=-2.69;
+	elseif(L==160000.),
+		md.stressbalance.spcvx(pos)=16.03;
+		md.stressbalance.spcvy(pos)=-1.27;
+	end
+
+	md=setflowequation(md,'FS','all');
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-11,2e-12,3e-12,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1106.py	(revision 18231)
@@ -0,0 +1,87 @@
+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 *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+
+for L in L_list:
+	md=triangle(model(),"../Exp/Square_%d.exp" % L,L/10.)    #size 3*L 
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPC.py')
+	md.friction.coefficient=numpy.sqrt(md.constants.yts*(1000.+1000.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/L)*numpy.sin(md.mesh.y.reshape(-1,1)*2.*numpy.pi/L)))
+	md.extrude(10,1.)
+
+	#Add spc on the borders
+	pos=numpy.nonzero(logical_or_n(md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==0.,md.mesh.y==numpy.max(md.mesh.y)))
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	if   (L==5000.):
+		md.stressbalance.spcvx[pos]=15.66
+		md.stressbalance.spcvy[pos]=-0.1967
+	elif (L==10000.):
+		md.stressbalance.spcvx[pos]=16.04
+		md.stressbalance.spcvy[pos]=-0.1977
+	elif (L==20000.):
+		md.stressbalance.spcvx[pos]=16.53
+		md.stressbalance.spcvy[pos]=-1.27
+	elif (L==40000.):
+		md.stressbalance.spcvx[pos]=17.23
+		md.stressbalance.spcvy[pos]=-3.17
+	elif (L==80000.):
+		md.stressbalance.spcvx[pos]=16.68
+		md.stressbalance.spcvy[pos]=-2.69
+	elif (L==160000.):
+		md.stressbalance.spcvx[pos]=16.03
+		md.stressbalance.spcvy[pos]=-1.27
+
+	md=setflowequation(md,'FS','all')
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+
+#	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-12,1e-12,1e-11,\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-12,1e-12,\
+	1e-12,1e-11,1e-12,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.m	(revision 18231)
@@ -0,0 +1,140 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+printingflag=false;
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+minvx=[];
+maxvx=[];
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=30; %numberof nodes in x direction
+	ny=30;
+	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=setflowequation(md,'HO','all');
+
+	%We need one grd on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0. & ~(md.mesh.y==0. & md.mesh.vertexonbase) & ~(md.mesh.y==L & md.mesh.vertexonbase));
+	posx2=find(md.mesh.x==max(md.mesh.x) & ~(md.mesh.y==0. & md.mesh.vertexonbase) & ~(md.mesh.y==L & md.mesh.vertexonbase));
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x)); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Add spc on the corners
+	pos=find((md.mesh.x==0. | md.mesh.x==L) & (md.mesh.y==0. | md.mesh.y==L) & md.mesh.vertexonbase);
+	md.stressbalance.spcvy(:)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	if(L==5000.),
+		md.stressbalance.spcvx(pos)=16.0912;
+	elseif(L==10000.),
+		md.stressbalance.spcvx(pos)=16.52;
+	elseif(L==20000.),
+		md.stressbalance.spcvx(pos)=17.77;
+	elseif(L==40000.),
+		md.stressbalance.spcvx(pos)=19.88;
+	elseif(L==80000.),
+		md.stressbalance.spcvx(pos)=18.65;
+	elseif(L==160000.),
+		md.stressbalance.spcvx(pos)=16.91;
+	end
+	
+	%Spc the bed at zero for vz
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvz(pos)=0.;
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
+	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
+
+	%Now plot vx, vy, vz and vx on a cross section
+	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipdHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+	end
+	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipdHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+	end
+
+	if(L==5000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 20],'xlim',[0 5000],'title','','xlabel','','figure',4)
+	elseif(L==10000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 20],'xlim',[0 10000],'title','','xlabel','','figure',4)
+	elseif(L==20000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 30],'xlim',[0 20000],'title','','xlabel','','figure',4)
+	elseif(L==40000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[10 60],'xlim',[0 40000],'title','','xlabel','','figure',4)
+	elseif(L==80000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 200],'xlim',[0 80000],'title','','xlabel','','figure',4)
+	elseif(L==160000.),
+		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+			'resolution',[10 10],'ylim',[0 400],'xlim',[0 160000],'title','','xlabel','','figure',4)
+	end
+	if printingflag,
+		set(gcf,'Color','w')
+		printmodel(['ismipdHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+	end
+end
+
+%Now plot the min and max values of vx for each size of the square
+plot([5 10 20 40 80 160],minvx);ylim([2 18]);xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipdHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+end
+plot([5 10 20 40 80 160],maxvx);ylim([0 300]);xlim([0 160])
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('ismipdHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-08,1e-08,1e-07,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1107.py	(revision 18231)
@@ -0,0 +1,166 @@
+import numpy
+import shutil
+from model import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+printingflag=False
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+minvx=[]
+maxvx=[]
+
+for L in L_list:
+	nx=30    #numberof nodes in x direction
+	ny=30
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPD.py')
+	md.extrude(10,1.)
+
+	md=setflowequation(md,'HO','all')
+
+	#We need one grd on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+
+	#Create MPCs to have periodic boundary conditions
+#	posx=find(md.mesh.x==0. & ~(md.mesh.y==0. & md.mesh.vertexonbase) & ~(md.mesh.y==L & md.mesh.vertexonbase));
+	posx=numpy.nonzero(logical_and_n(md.mesh.x==0.,numpy.logical_not(numpy.logical_and(md.mesh.y==0.,md.mesh.vertexonbase)),numpy.logical_not(numpy.logical_and(md.mesh.y==L,md.mesh.vertexonbase))))[0]
+#	posx2=find(md.mesh.x==max(md.mesh.x) & ~(md.mesh.y==0. & md.mesh.vertexonbase) & ~(md.mesh.y==L & md.mesh.vertexonbase));
+	posx2=numpy.nonzero(logical_and_n(md.mesh.x==numpy.max(md.mesh.x),numpy.logical_not(numpy.logical_and(md.mesh.y==0.,md.mesh.vertexonbase)),numpy.logical_not(numpy.logical_and(md.mesh.y==L,md.mesh.vertexonbase))))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Add spc on the corners
+	pos=numpy.nonzero(logical_and_n(numpy.logical_or(md.mesh.x==0.,md.mesh.x==L),numpy.logical_or(md.mesh.y==0.,md.mesh.y==L),md.mesh.vertexonbase))
+	md.stressbalance.spcvy[:]=0.
+	md.stressbalance.spcvx[pos]=0.
+	if   (L==5000.):
+		md.stressbalance.spcvx[pos]=16.0912
+	elif (L==10000.):
+		md.stressbalance.spcvx[pos]=16.52
+	elif (L==20000.):
+		md.stressbalance.spcvx[pos]=17.77
+	elif (L==40000.):
+		md.stressbalance.spcvx[pos]=19.88
+	elif (L==80000.):
+		md.stressbalance.spcvx[pos]=18.65
+	elif (L==160000.):
+		md.stressbalance.spcvx[pos]=16.91
+	
+	#Spc the bed at zero for vz
+	pos=numpy.nonzero(md.mesh.vertexonbase)
+	md.stressbalance.spcvz[pos]=0.
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
+	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
+
+	#Now plot vx, vy, vz and vx on a cross section
+#	plotmodel(md,'data',vx,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',2)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipdHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipdHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+
+	if   (L==5000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP5000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 20],'xlim',[0 5000],'title','','xlabel','','figure',4)
+	elif (L==10000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP10000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 20],'xlim',[0 10000],'title','','xlabel','','figure',4)
+	elif (L==20000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP20000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 30],'xlim',[0 20000],'title','','xlabel','','figure',4)
+	elif (L==40000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP40000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[10 60],'xlim',[0 40000],'title','','xlabel','','figure',4)
+	elif (L==80000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP80000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 200],'xlim',[0 80000],'title','','xlabel','','figure',4)
+	elif (L==160000.):
+		pass
+#		plotmodel(md,'data',vx,'sectionvalue','../Exp/ISMIP160000.exp','layer',md.mesh.numberoflayers,...
+#			'resolution',[10 10],'ylim',[0 400],'xlim',[0 160000],'title','','xlabel','','figure',4)
+	if printingflag:
+		pass
+#		set(gcf,'Color','w')
+#		printmodel(['ismipdHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+
+#Now plot the min and max values of vx for each size of the square
+#plot([5 10 20 40 80 160],minvx);ylim([2 18]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipdHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipdHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#plot([5 10 20 40 80 160],maxvx);ylim([0 300]);xlim([0 160])
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('ismipdHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipdHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-07,1e-08,1e-06,\
+	1e-08,1e-08,1e-06,\
+	1e-08,1e-08,1e-07,\
+	1e-08,1e-08,1e-07,\
+	1e-08,1e-08,1e-07,\
+	1e-07,1e-08,1e-06,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.m	(revision 18231)
@@ -0,0 +1,79 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%Pattyn and Payne 2006
+
+%L_list={5000.,10000.,20000.,40000.,80000.,160000.};
+L_list={80000.};
+results={};
+
+for i=1:length(L_list),
+	L=L_list{i};
+	nx=30; %numberof nodes in x direction
+	ny=30;
+	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=setflowequation(md,'HO','all');
+
+	%We need one grid on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	
+	pos=find(md.mesh.vertexonbase & (md.mesh.x==0. | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0. | md.mesh.y==max(md.mesh.y)));
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+
+	posy=find(md.mesh.y==0. & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x)); %Don't take the same nodes two times
+	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+	md.stressbalance.reltol=NaN;
+	md.stressbalance.abstol=NaN;
+	md.stressbalance.vertex_pairing=[];
+	%We need one grd on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.y==0. | md.mesh.x==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y)); %Don't take the same nodes two times
+	md.stressbalance.spcvx(pos)=md.results.StressbalanceSolution.Vx(pos);
+	md.stressbalance.spcvy(pos)=md.results.StressbalanceSolution.Vy(pos);
+	md=setflowequation(md,'FS','all');
+	md=solve(md,StressbalanceSolutionEnum());
+
+	%Plot the results and save them
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Vx80km','Vy80km','Vz80km'
+};
+field_tolerances={...
+	1e-08,1e-07,1e-07,...
+};
+field_values={};
+for i=1:1,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1108.py	(revision 18231)
@@ -0,0 +1,98 @@
+import numpy
+from model import *
+from bamg import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from PythonFuncs import *
+
+"""
+This test is a test from the ISMP-HOM Intercomparison project.
+Pattyn and Payne 2006
+"""
+
+L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
+results=[]
+
+for L in L_list:
+	nx=30    #numberof nodes in x direction
+	ny=30
+	md=model()
+	md=squaremesh(md,L,L,nx,ny)
+	md=setmask(md,'','')    #ice sheet test
+	md=parameterize(md,'../Par/ISMIPD.py')
+	md.extrude(10,1.)
+
+	md=setflowequation(md,'HO','all')
+
+	#We need one grd on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	
+	pos=numpy.nonzero(logical_and_n(md.mesh.vertexonbase,numpy.logical_or(md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x)),numpy.logical_or(md.mesh.y==0.,md.mesh.y==numpy.max(md.mesh.y))))
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
+
+	#Create MPCs to have periodic boundary conditions
+	posx=numpy.nonzero(md.mesh.x==0.)[0]
+	posx2=numpy.nonzero(md.mesh.x==numpy.max(md.mesh.x))[0]
+
+	posy=numpy.nonzero(logical_and_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
+
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+
+	#Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8)
+	md.verbose=verbose('convergence',True)
+	md=solve(md,StressbalanceSolutionEnum())
+	md.stressbalance.reltol=float('NaN')
+	md.stressbalance.abstol=float('NaN')
+	md.stressbalance.vertex_pairing=numpy.empty((0,2))
+	#We need one grid on dirichlet: the 4 corners are set to zero
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	pos=numpy.nonzero(logical_or_n(md.mesh.y==0.,md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==numpy.max(md.mesh.y)))    #Don't take the same nodes two times
+	md.stressbalance.spcvx[pos]=md.results.StressbalanceSolution.Vx[pos]
+	md.stressbalance.spcvy[pos]=md.results.StressbalanceSolution.Vy[pos]
+	md=setflowequation(md,'FS','all')
+	md=solve(md,StressbalanceSolutionEnum())
+
+	#Plot the results and save them
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
+
+#	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+
+#Fields and tolerances to track changes
+field_names     =[\
+	'Vx5km','Vy5km','Vz5km',\
+	'Vx10km','Vy10km','Vz10km',\
+	'Vx20km','Vy20km','Vz20km',\
+	'Vx40km','Vy40km','Vz40km',\
+	'Vx80km','Vy80km','Vz80km',\
+	'Vx160km','Vy160km','Vz160km'
+]
+field_tolerances=[\
+	1e-07,1e-07,1e-07,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-07,1e-07,\
+	1e-08,1e-08,1e-08,\
+	1e-08,1e-07,1e-07,\
+	1e-07,1e-06,1e-07,\
+]
+field_values=[]
+for result in results:
+	field_values=field_values+[\
+		result.Vx,\
+		result.Vy,\
+		result.Vz,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1109.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1109.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1109.m	(revision 18231)
@@ -0,0 +1,110 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%TestE 
+%Four tests to run: - Pattyn frozen
+%                   - Stokes frozen
+%                   - Pattyn with some sliding
+%                   - Stokes with some sliding
+printingflag=false;
+results={};
+
+for i=1:4,
+	Lx=10.; %in m
+	Ly=5000.; %in m
+	nx=3; %number of nodes in x direction
+	ny=51;
+	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.);
+
+	if i==1 | i==3,
+		md=setflowequation(md,'HO','all');
+	elseif i==2 | i==4,
+		md=setflowequation(md,'FS','all');
+	end
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+	md.stressbalance.vertex_pairing=[posx,posx2];
+
+	%Create spcs on the bed 
+	pos=find(md.mesh.vertexonbase);
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
+
+	%Remove the spc where there is some sliding (case 3 and 4):
+	if i==3 | i==4,
+		pos=find(md.mesh.y/max(md.mesh.y)>=0.44 & md.mesh.y/max(md.mesh.y)<=0.5);
+		md.stressbalance.spcvx(pos)=NaN;
+		md.stressbalance.spcvy(pos)=NaN;
+		md.stressbalance.spcvz(pos)=NaN;
+	end
+
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,StressbalanceSolutionEnum());
+
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
+
+	if i==1,
+		plotmodel(md,'data',vy,'ylim',[-10 80],'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIPE.exp','resolution',[10 10],'title','','xlabel','')
+		if printingflag,
+			set(gcf,'Color','w')
+			printmodel('ismipeHOvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeHOvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+		end
+	elseif i==2,
+		plotmodel(md,'data',vy,'ylim',[-10 80],'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIPE.exp','resolution',[10 10],'title','','xlabel','')
+		if printingflag,
+			set(gcf,'Color','w')
+			printmodel('ismipeFSvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeFSvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+		end
+	elseif i==3,
+		plotmodel(md,'data',vy,'ylim',[-50 200],'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIPE.exp','resolution',[10 10],'title','','xlabel','')
+		if printingflag,
+			set(gcf,'Color','w')
+			printmodel('ismipeHOvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeHOvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+		end
+	elseif i==4,
+		plotmodel(md,'data',vy,'ylim',[-50 200],'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIPE.exp','resolution',[10 10],'title','','xlabel','')
+		if printingflag,
+			set(gcf,'Color','w')
+			printmodel('ismipeFSvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeFSvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+		end
+	end
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'VyPattynSliding','VzPattynSliding',...
+	'VxStokesSliding','VyStokesSliding','VzStokesSliding',...
+	'VyPattynFrozen','VzPattynFrozen',...
+	'VxStokesFrozen','VyStokesFrozen','VzStokesFrozen'
+};
+field_tolerances={...
+	1e-05,1e-05,...
+	1e-05,1e-06,1e-06,...
+	1e-05,1e-04,...
+	1e-05,1e-05,1e-06,...
+};
+field_values={};
+for i=1:4,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.m	(revision 18231)
@@ -0,0 +1,53 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs={'IceVolume'};
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','Volume1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','Volume2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3','Volume3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-13,...
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,...
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test111.py	(revision 18231)
@@ -0,0 +1,62 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.requested_outputs=['IceVolume']
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=[\
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','Volume1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','Volume2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3','Volume3']
+field_tolerances=[\
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-13,\
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,\
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[2].IceVolume,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1110.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1110.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1110.m	(revision 18231)
@@ -0,0 +1,129 @@
+%This test is a test from the ISMP-HOM Intercomparison project.
+%TestF 
+printingflag=false;
+results={};
+
+for i=1:4,
+	L=100000.; %in m
+	nx=30; %numberof nodes in x direction
+	ny=30;
+	md=model();
+	md=squaremesh(md,L,L,nx,ny);
+%	md=triangle(md,'../Exp/SquareISMIP.exp',5500.);
+	md=setmask(md,'',''); %ice sheet test
+	md=parameterize(md,'../Par/ISMIPF.par');
+	md=extrude(md,4,1.);
+
+	if (i==1 | i==2),
+		md=setflowequation(md,'HO','all');
+	else
+		md=setflowequation(md,'FS','all');
+	end
+
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	if (i==1 | i==3),
+		%Create dirichlet on the bed if no slip
+		pos=find(md.mesh.vertexonbase);
+		md.stressbalance.spcvx(pos)=0.;
+		md.stressbalance.spcvy(pos)=0.;
+		md.stressbalance.spcvz(pos)=0.;
+	else
+		pos=find(md.mesh.vertexonbase & (md.mesh.x==0. | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0. | md.mesh.y==max(md.mesh.y)));
+		md.stressbalance.spcvx(pos)=100.; %because we need a dirichlet somewhere
+		md.stressbalance.spcvy(pos)=0.;
+		md.stressbalance.spcvz(pos)=0.;
+	end
+	pos=find(~md.mesh.vertexonbase);
+	md.thermal.spctemperature(pos)=255.;
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0.);
+	posx2=find(md.mesh.x==max(md.mesh.x));
+
+	posy=find(md.mesh.y==0.);
+	posy2=find(md.mesh.y==max(md.mesh.y));
+
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+	md.masstransport.vertex_pairing=[posx,posx2;posy,posy2];
+
+	md.timestepping.time_step=3.;
+	md.timestepping.final_time=300.;
+	md.settings.output_frequency=50;
+	md.masstransport.stabilization=1;
+	md.stressbalance.maxiter=1;
+	
+	%Compute the stressbalance
+	md.cluster=generic('name',oshostname(),'np',8);
+	md.verbose=verbose('convergence',true,'solution',true);
+	md=solve(md,TransientSolutionEnum());
+
+	%save the results
+	results{i}=md.results.TransientSolution(end);
+	
+	%Now plot vx and delta surface 
+	if (i==1 | i==3),
+		plotmodel(md,'data',(md.results.TransientSolution(end).Vx),'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Velocity (m/yr)','linewidth',3,'grid','on','unit','km','ylim',[91 100])
+	elseif (i==2 | i==4),
+		plotmodel(md,'data',(md.results.TransientSolution(end).Vx),'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Velocity (m/yr)','linewidth',3,'grid','on','unit','km','ylim',[185 200])
+	end
+	if printingflag,
+		set(gcf,'Color','w')
+		if i==1,
+			printmodel('ismipfHOvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==2,
+			printmodel('ismipfHOvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==3,
+			printmodel('ismipfFSvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==4,
+			printmodel('ismipfFSvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		end
+	end
+
+	plotmodel(md,'data',(md.results.TransientSolution(end).Surface)-md.geometry.surface,'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Surface (m)','linewidth',3,'grid','on','unit','km','ylim',[-30 50])
+	if printingflag,
+		set(gcf,'Color','w')
+		if i==1,
+			printmodel('ismipfHOdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==2,
+			printmodel('ismipfHOdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==3,
+			printmodel('ismipfFSdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		elseif i==4,
+			printmodel('ismipfFSdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+		end
+	end
+end
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'VxPattynFrozen','VyPattynFrozen','VzPattynFrozen','SurfacePattynFrozen',...
+	'VxPattynSliding','VyPattynSliding','VzPattynSliding','SurfacePattynSliding',...
+	'VxStokesFrozen','VyStokesFrozen','VzStokesFrozen','SurfaceStokesFrozen',...
+	'VxStokesSliding','VyStokesSliding','VzStokesSliding','SurfaceStokesSliding'
+};
+field_tolerances={...
+	1e-10,1e-09,1e-09,1e-10,...
+	1e-10,1e-09,1e-09,1e-10,...
+	1e-08,1e-09,1e-08,1e-09,...
+	1e-08,2e-09,1e-08,1e-09,...
+};
+field_values={};
+for i=1:4,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		(result.Surface)-md.geometry.surface,...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test112.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,SurfaceSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test113.py	(revision 18231)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(5,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,SurfaceSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test114.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BedSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['BedSlopeX','BedSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test115.py	(revision 18231)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(5,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BedSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['BedSlopeX','BedSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test116.py	(revision 18231)
@@ -0,0 +1,26 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+#Add boundary conditions on thickness on the border
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.m	(revision 18231)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1.);
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test117.py	(revision 18231)
@@ -0,0 +1,27 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(5,1.)
+#Add boundary conditions on thickness on the border
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md.balancethickness.stabilization=3;
+md.initialization.vy=md.initialization.vy+400;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test118.py	(revision 18231)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=meshconvert(md)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.balancethickness.stabilization=3
+md.initialization.vy=md.initialization.vy+400.
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.m	(revision 18231)
@@ -0,0 +1,30 @@
+
+%Simple mesh
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.,'rand',false);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%hVertices
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',[10000. 100000. 400000. 100000.]','rand',false);
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%big mesh
+t0=clock;
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.,'rand',false);
+nbelements=md.mesh.numberofelements;
+if nbelements>267895-50 & nbelements<267895+50
+	nbewithinrange = 1.;
+else
+	nbewithinrange = 0.;
+end
+elapsedtime=etime(clock,t0);
+
+%Fields and tolerances to track changes
+field_names     ={'x1','y1','x2','y2','nbelements','elapsed time'};
+field_tolerances={2e-9,2e-9,1e-13,1e-13,1e-13,4.};
+field_values={...
+	x1, y1,...
+	x2, y2,...
+	nbewithinrange,elapsedtime...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test119.py	(revision 18231)
@@ -0,0 +1,34 @@
+import numpy
+import time
+from model import *
+from bamg import *
+from MatlabFuncs import *
+
+#Simple mesh
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.,'rand',False)
+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),'rand',False)
+x2=md.mesh.x
+y2=md.mesh.y
+
+#big mesh
+t0=time.time()
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.,'rand',False)
+nbelements=md.mesh.numberofelements
+elapsedtime=time.time()-t0
+if nbelements>267895-50 and nbelements<267895+50:
+	nbewithinrange = 1.
+else:
+	nbewithinrange = 0.
+
+#Fields and tolerances to track changes
+field_names     =['x1','y1','x2','y2','nbelements','elapsed time']
+field_tolerances=[2e-9,2e-9,1e-13,1e-13,1e-13,4.0]
+field_values=[\
+	x1, y1,\
+	x2, y2,\
+	nbewithinrange,elapsedtime,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=0;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,2e-10,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Enthalpy),...
+	(md.results.ThermalSolution.Waterfraction),...
+	(md.results.ThermalSolution.Temperature),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test120.py	(revision 18231)
@@ -0,0 +1,32 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.timestepping.time_step=0
+md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+md.initialization.watercolumn=numpy.zeros(md.mesh.numberofvertices)
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Enthalpy','Waterfraction','Temperature']
+field_tolerances=[1e-13,2e-10,1e-13]
+field_values=[\
+	md.results.ThermalSolution.Enthalpy,\
+	md.results.ThermalSolution.Waterfraction,\
+	md.results.ThermalSolution.Temperature,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.m	(revision 18231)
@@ -0,0 +1,67 @@
+%This test is a test from the EISMINT for Ice shelves Vincent Rommelaere 1996.
+printingflag=false;
+
+results={};
+
+for stabilization=1:3;
+	%The goal is to test the masstransport model
+	md=bamg(model(),'domain','../Exp/SquareEISMINT.exp','hmax',3000.);
+	md=setmask(md,'all','');
+	md=parameterize(md,'../Par/SquareEISMINT.par');
+	md.surfaceforcings.mass_balance(:)=0.;
+	md=setflowequation(md,'SSA','all');
+	md.cluster=generic('name',oshostname(),'np',8);
+
+	disp('      initial velocity');
+	md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+	md.initialization.vy=-400.*ones(md.mesh.numberofvertices,1);
+
+	%Stabilization
+	if stabilization==2,
+		md.masstransport.stabilization=0;
+	else
+		md.masstransport.stabilization=stabilization;
+	end
+
+	%spc thickness
+	pos=find(md.mesh.y>199999.9);
+	times=0:1:500;
+	md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices+1,length(times));
+	md.masstransport.spcthickness(end,:)=times;
+	md.masstransport.spcthickness(pos,:)=repmat(500.+100.*sin(2.*pi*times/200.),length(pos),1);
+	if stabilization==3,
+		pos=find(isnan(md.masstransport.spcthickness)); md.masstransport.spcthickness(pos)=500.; %No NaN for DG
+	end
+
+	%solve
+	md.transient.isstressbalance=0;
+	md.settings.output_frequency=500; %keep only last step
+	md.verbose=verbose();
+	md=solve(md,TransientSolutionEnum());
+	results{stabilization}=(md.results.TransientSolution(end).Thickness);
+end
+
+%plot results
+[elements,x,y,z,s,h1]=SectionValues(md,results{1},'../Exp/CrossLineEISMINT.exp',100.);
+[elements,x,y,z,s,h2]=SectionValues(md,results{2},'../Exp/CrossLineEISMINT.exp',100.);
+[elements,x,y,z,s,h3]=SectionValues(md,results{3},'../Exp/CrossLineEISMINT.exp',100.);
+[elements,x,y,z,s,hth]=SectionValues(md, 500+100*sin(2*pi/200*(500-md.mesh.y/400)),'../Exp/CrossLineEISMINT.exp',100.);
+plot(s,h1,'r',s,h2,'b',s,h3,'g',s,hth,'k')
+legend('Art. diff.','No Art. diff.','D.G.','Theoretical')
+if printingflag,
+	set(gcf,'Color','w')
+	export_fig([issmdir() '/website/doc_pdf/validation/Images/EISMINT/IceShelf/eismintmasscthickness.pdf']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={ ...
+	'ThicknessArtDiff','ThicknessNoArtDiff','ThicknessDG' ...
+};
+field_tolerances={...
+	1e-13, 1e-13, 1e-13...
+};
+field_values={
+	results{1}, ...
+	results{2}, ...
+	results{3}, ...
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1201.py	(revision 18231)
@@ -0,0 +1,78 @@
+import numpy
+from model import *
+from bamg import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+"""
+This test is a test from the EISMINT for Ice shelves Vincent Rommelaere 1996.
+"""
+
+printingflag=False
+
+results=[]
+
+for stabilization in xrange(1,4):
+	#The goal is to test the masstransport model
+	md=bamg(model(),'domain','../Exp/SquareEISMINT.exp','hmax',3000.)
+	md=setmask(md,'all','')
+	md=parameterize(md,'../Par/SquareEISMINT.py')
+	md.surfaceforcings.mass_balance[:]=0.
+	md=setflowequation(md,'SSA','all')
+	md.cluster=generic('name',oshostname(),'np',8)
+
+	print "      initial velocity"
+	md.initialization.vx=numpy.zeros((md.mesh.numberofvertices,1))
+	md.initialization.vy=-400.*numpy.ones((md.mesh.numberofvertices,1))
+
+	#Stabilization
+	if stabilization==2:
+		md.masstransport.stabilization=0
+	else:
+		md.masstransport.stabilization=stabilization
+
+	#spc thickness
+	pos=numpy.nonzero(md.mesh.y>199999.9)[0]
+	times=numpy.arange(0,501)
+	md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices+1,numpy.size(times)))
+	md.masstransport.spcthickness[-1,:]=times
+	md.masstransport.spcthickness[pos,:]=numpy.tile(500.+100.*numpy.sin(2.*numpy.pi*times/200.),(numpy.size(pos),1))
+	if stabilization==3:
+		pos=numpy.nonzero(numpy.isnan(md.masstransport.spcthickness))
+		md.masstransport.spcthickness[pos]=500.    #No NaN for DG
+
+	#solve
+	md.transient.isstressbalance=False
+	md.settings.output_frequency=500    #keep only last step
+	md.verbose=verbose()
+	md=solve(md,TransientSolutionEnum())
+	results.append(md.results.TransientSolution[-1].Thickness)
+
+#plot results
+#[elements,x,y,z,s,h1]=SectionValues(md,results[0],'../Exp/CrossLineEISMINT.exp',100.);
+#[elements,x,y,z,s,h2]=SectionValues(md,results[1],'../Exp/CrossLineEISMINT.exp',100.);
+#[elements,x,y,z,s,h3]=SectionValues(md,results[2],'../Exp/CrossLineEISMINT.exp',100.);
+#[elements,x,y,z,s,hth]=SectionValues(md, 500+100*sin(2*pi/200*(500-md.mesh.y/400)),'../Exp/CrossLineEISMINT.exp',100.);
+#plot(s,h1,'r',s,h2,'b',s,h3,'g',s,hth,'k')
+#legend('Art. diff.','No Art. diff.','D.G.','Theoretical')
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	export_fig([issmdir() '/website/doc_pdf/validation/Images/EISMINT/IceShelf/eismintmasscthickness.pdf']);
+
+#Fields and tolerances to track changes
+field_names     =[ \
+	'ThicknessArtDiff','ThicknessNoArtDiff','ThicknessDG' \
+]
+field_tolerances=[\
+	1e-13, 1e-13, 1e-13\
+]
+field_values=[
+	results[0], \
+	results[1], \
+	results[2], \
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.m	(revision 18231)
@@ -0,0 +1,41 @@
+%Test on the stressbalance model and the masstransport in 2d.
+printingflag=false;
+
+%tests 3 and 4: using Glen's flow law
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareEISMINT.par');
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
+
+%Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+%plot results
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
+
+plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,60,100,120,140,160,180,-20,-40,-60,-80,-100,-120,-140,-160,-180}, ...
+	'contourcolor','k')
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eismintdiag1vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eismintdiag1vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+plotmodel(md,'data',vy,'contourlevels',{-100,-200,-300,-400,-500,-600,-700,-800,-900,-1000},...
+	'contourcolor','k')
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eismintdiag1vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eismintdiag1vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	vx, ...
+	vy, ...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1202.py	(revision 18231)
@@ -0,0 +1,54 @@
+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 *
+
+"""
+Test on the stressbalance model and the masstransport in 2d
+"""
+
+printingflag=False
+
+#tests 3 and 4: using Glen's flow law
+md=model()
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareEISMINT.py')
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
+
+#Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+#plot results
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
+
+#plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,60,100,120,140,160,180,-20,-40,-60,-80,-100,-120,-140,-160,-180}, ...
+#	'contourcolor','k')
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eismintdiag1vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eismintdiag1vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#plotmodel(md,'data',vy,'contourlevels',{-100,-200,-300,-400,-500,-600,-700,-800,-900,-1000},...
+#	'contourcolor','k')
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eismintdiag1vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eismintdiag1vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	vx, \
+	vy, \
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.m	(revision 18231)
@@ -0,0 +1,44 @@
+%Test on the stressbalance model and the masstransport in 2d
+printingflag=false;
+
+%test 5 and 6: 
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',5100.); %test3
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareEISMINT.par');
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
+
+%Impose a non zero velocity on the upper boundary condition (y=max(y))
+pos=find(md.mesh.y==max(md.mesh.y));
+md.stressbalance.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
+
+%Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
+
+%plot results
+plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,80,100,-20,-40,-60,-80,-100},...
+	'contourcolor','k')
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eismintdiag2vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eismintdiag2vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+plotmodel(md,'data',vy,'contourlevels',{-100,-200,-300,-400,-500,-600,-700,-800,-900,-1000},...
+	'contourcolor','k')
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eismintdiag2vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eismintdiag2vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	vx, ...
+	vy, ...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1203.py	(revision 18231)
@@ -0,0 +1,58 @@
+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 *
+
+"""
+Test on the stressbalance model and the masstransport in 2d
+"""
+
+printingflag=False
+
+#test 5 and 6: 
+md=model()
+md=triangle(md,'../Exp/SquareEISMINT.exp',5100.)    #test3
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareEISMINT.py')
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
+
+#Impose a non zero velocity on the upper boundary condition (y=max(y))
+pos=numpy.nonzero(md.mesh.y==numpy.max(md.mesh.y))
+md.stressbalance.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
+
+#Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
+
+#plot results
+#plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,80,100,-20,-40,-60,-80,-100},...
+#	'contourcolor','k')
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eismintdiag2vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eismintdiag2vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+#plotmodel(md,'data',vy,'contourlevels',{-100,-200,-300,-400,-500,-600,-700,-800,-900,-1000},...
+#	'contourcolor','k')
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eismintdiag2vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eismintdiag2vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	vx, \
+	vy, \
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.m	(revision 18231)
@@ -0,0 +1,56 @@
+%Test on the stressbalance model and the masstransport in 2d
+printingflag=false;
+
+%tests 3 and 4: using Glen's flow law
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareEISMINT.par');
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
+
+%Impose a non zero velocity on the upper boundary condition (y=max(y))
+pos=find(md.mesh.y==max(md.mesh.y));
+md.stressbalance.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
+
+%Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+%plot results
+md.initialization.vx=(md.results.StressbalanceSolution.Vx);
+md.initialization.vy=(md.results.StressbalanceSolution.Vy);
+
+md.timestepping.time_step=1.;
+md.timestepping.final_time=5000.;
+md.masstransport.stabilization=1;
+md=solve(md,TransientSolutionEnum());
+
+plotmodel(md,'data',(md.results.TransientSolution(end).Vx))
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eisminttrans2vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eisminttrans2vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+plotmodel(md,'data',(md.results.TransientSolution(end).Vy))
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eisminttrans2vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eisminttrans2vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+plotmodel(md,'data',(md.results.TransientSolution(end).Thickness))
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('eisminttrans2thickness','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+	system(['mv eisminttrans2thickness.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Thickness'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(end).Vx), ...
+	(md.results.TransientSolution(end).Vy), ...
+	(md.results.TransientSolution(end).Thickness), ...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1204.py	(revision 18231)
@@ -0,0 +1,70 @@
+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 *
+
+"""
+Test on the stressbalance model and the masstransport in 2d
+"""
+
+printingflag=False
+
+#tests 3 and 4: using Glen's flow law
+md=model()
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareEISMINT.py')
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
+
+#Impose a non zero velocity on the upper boundary condition (y=max(y))
+pos=numpy.nonzero(md.mesh.y==max(md.mesh.y))
+md.stressbalance.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
+
+#Compute solution for SSA's model 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+#plot results
+md.initialization.vx=md.results.StressbalanceSolution.Vx
+md.initialization.vy=md.results.StressbalanceSolution.Vy
+
+md.timestepping.time_step=1.
+md.timestepping.final_time=5000.
+md.masstransport.stabilization=1
+md=solve(md,TransientSolutionEnum())
+
+#plotmodel(md,'data',(md.results.TransientSolution(end).Vx))
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eisminttrans2vx','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eisminttrans2vx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#plotmodel(md,'data',(md.results.TransientSolution(end).Vy))
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eisminttrans2vy','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eisminttrans2vy.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#plotmodel(md,'data',(md.results.TransientSolution(end).Thickness))
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('eisminttrans2thickness','png','margin','on','marginsize',25,'frame','off','resolution',2,'hardcopy','off');
+#	system(['mv eisminttrans2thickness.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceShelf ']);
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Thickness']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[-1].Vx, \
+	md.results.TransientSolution[-1].Vy, \
+	md.results.TransientSolution[-1].Thickness, \
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.m	(revision 18231)
@@ -0,0 +1,98 @@
+%The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+printingflag=false;
+
+numlayers=10;
+resolution=30000.;
+
+%To begin with the numerical model
+md=model();
+md=roundmesh(md,750000.,resolution);
+md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.par');
+
+%Calculation of the analytical 2d velocity field
+constant=0.3;
+vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+
+%We extrude the model to have a 3d model
+md=extrude(md,numlayers,1.);
+md=setflowequation(md,'SIA','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+for i=1:md.mesh.numberofvertices2d
+	node_vel=0.;
+	for j=1:md.mesh.numberoflayers-1
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*...
+			(sqrt(vx(i+j*md.mesh.numberofvertices2d,1).^2+vy(i+j*md.mesh.numberofvertices2d,1).^2)+...
+			sqrt(vx(i+(j-1)*md.mesh.numberofvertices2d,1).^2+vy(i+(j-1)*md.mesh.numberofvertices2d,1).^2));
+	end
+	vel(i,1)=node_vel;
+end
+
+%Plot of the velocity from the exact and calculated solutions
+figure(1)
+set(gcf,'Position',[1 1 1580 1150])
+subplot(2,2,1)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel,'FaceColor','interp','EdgeColor','none');
+title('Modelled velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+   
+subplot(2,2,2)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel_obs,'FaceColor','interp','EdgeColor','none');
+title('Analytical velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+
+subplot(2,2,3)
+hold on;
+plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+legend('calculated velocity','exact velocity');
+axis([0 750000 0 200]);
+hold off;
+
+subplot(2,2,4)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+colorbar;
+caxis([0 100]);
+
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('SIAstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv SIAstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={ ...
+	'Vx','Vy','Vel', ...
+};
+field_tolerances={ ...
+	1e-13,1e-13,1e-13, ...
+};
+field_values={ ...
+	vx,vy,vel, ...
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1205.py	(revision 18231)
@@ -0,0 +1,109 @@
+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 *
+
+"""
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+"""
+
+printingflag=False
+
+numlayers=10
+resolution=30000.
+
+#To begin with the numerical model
+md=model()
+md=roundmesh(md,750000.,resolution)
+md=setmask(md,'','')    #We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.py')
+
+#Calculation of the analytical 2d velocity field
+constant=0.3
+vx_obs=constant/2.*md.mesh.x*(md.geometry.thickness)**-1
+vy_obs=constant/2.*md.mesh.y*(md.geometry.thickness)**-1
+vel_obs=numpy.sqrt((md.inversion.vx_obs)**2+(md.inversion.vy_obs)**2)
+
+#We extrude the model to have a 3d model
+md.extrude(numlayers,1.);
+md=setflowequation(md,'SIA','all')
+
+#Spc the nodes on the bed
+pos=numpy.nonzero(md.mesh.vertexonbase)
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
+
+#Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Calculate the depth averaged velocity field (2d):
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
+vel=numpy.zeros((md.mesh.numberofvertices2d,1))
+
+for i in xrange(0,md.mesh.numberofvertices2d):
+	node_vel=0.
+	for j in xrange(0,md.mesh.numberoflayers-1):
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*\
+			(numpy.sqrt(vx[i+(j+1)*md.mesh.numberofvertices2d,0]**2+vy[i+(j+1)*md.mesh.numberofvertices2d,0]**2)+\
+			numpy.sqrt(vx[i+j*md.mesh.numberofvertices2d,0]**2+vy[i+j*md.mesh.numberofvertices2d,0]**2))
+	vel[i,0]=node_vel
+
+#Plot of the velocity from the exact and calculated solutions
+#figure(1)
+#set(gcf,'Position',[1 1 1580 1150])
+#subplot(2,2,1)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel,'FaceColor','interp','EdgeColor','none');
+#title('Modelled velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+   
+#subplot(2,2,2)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel_obs,'FaceColor','interp','EdgeColor','none');
+#title('Analytical velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+
+#subplot(2,2,3)
+#hold on;
+#plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+#plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+#title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+#xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+#ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+#legend('calculated velocity','exact velocity');
+#axis([0 750000 0 200]);
+#hold off;
+
+#subplot(2,2,4)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+#title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+#colorbar;
+#caxis([0 100]);
+
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('SIAstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv SIAstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+
+#Fields and tolerances to track changes
+field_names     =[ \
+	'Vx','Vy','Vel', \
+]
+field_tolerances=[ \
+	1e-13,1e-13,1e-13, \
+]
+field_values=[ \
+	vx,vy,vel, \
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.m	(revision 18231)
@@ -0,0 +1,97 @@
+%The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+printingflag=false;
+
+numlayers=10;
+resolution=30000.;
+
+%To begin with the numerical model
+md=model();
+md=roundmesh(md,750000.,resolution);
+md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.par');
+
+%Calculation of the analytical 2d velocity field
+constant=0.3;
+vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+
+%We extrude the model to have a 3d model
+md=extrude(md,numlayers,1.);
+md=setflowequation(md,'HO','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+for i=1:md.mesh.numberofvertices2d
+	node_vel=0.;
+	for j=1:md.mesh.numberoflayers-1
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*...
+			(sqrt(vx(i+j*md.mesh.numberofvertices2d,1).^2+vy(i+j*md.mesh.numberofvertices2d,1).^2)+...
+			sqrt(vx(i+(j-1)*md.mesh.numberofvertices2d,1).^2+vy(i+(j-1)*md.mesh.numberofvertices2d,1).^2));
+	end
+	vel(i,1)=node_vel;
+end
+
+%Plot of the velocity from the exact and calculated solutions
+figure(1)
+subplot(2,2,1)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel,'FaceColor','interp','EdgeColor','none');
+title('Modelled velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+   
+subplot(2,2,2)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel_obs,'FaceColor','interp','EdgeColor','none');
+title('Analytical velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+
+subplot(2,2,3)
+hold on;
+plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+legend('calculated velocity','exact velocity');
+axis([0 750000 0 200]);
+hold off;
+
+subplot(2,2,4)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+colorbar;
+caxis([0 100]);
+
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('HOstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv HOstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={ ...
+	'Vx','Vy','Vel', ...
+};
+field_tolerances={ ...
+	1e-12,1e-12,1e-12, ...
+};
+field_values={ ...
+	vx,vy,vel, ...
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1206.py	(revision 18231)
@@ -0,0 +1,108 @@
+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 *
+
+"""
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+"""
+
+printingflag=False
+
+numlayers=10
+resolution=30000.
+
+#To begin with the numerical model
+md=model()
+md=roundmesh(md,750000.,resolution)
+md=setmask(md,'','')    #We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.py')
+
+#Calculation of the analytical 2d velocity field
+constant=0.3
+vx_obs=constant/2.*md.mesh.x.reshape(-1,1)*(md.geometry.thickness)**-1
+vy_obs=constant/2.*md.mesh.y.reshape(-1,1)*(md.geometry.thickness)**-1
+vel_obs=numpy.sqrt((md.inversion.vx_obs)**2+(md.inversion.vy_obs)**2)
+
+#We extrude the model to have a 3d model
+md.extrude(numlayers,1.)
+md=setflowequation(md,'HO','all')
+
+#Spc the nodes on the bed
+pos=numpy.nonzero(md.mesh.vertexonbase)
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
+
+#Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Calculate the depth averaged velocity field (2d):
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
+vel=numpy.zeros((md.mesh.numberofvertices2d,1))
+
+for i in xrange(0,md.mesh.numberofvertices2d):
+	node_vel=0.
+	for j in xrange(0,md.mesh.numberoflayers-1):
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*\
+			(numpy.sqrt(vx[i+(j+1)*md.mesh.numberofvertices2d,0]**2+vy[i+(j+1)*md.mesh.numberofvertices2d,0]**2)+\
+			numpy.sqrt(vx[i+j*md.mesh.numberofvertices2d,0]**2+vy[i+j*md.mesh.numberofvertices2d,0]**2))
+	vel[i,0]=node_vel
+
+#Plot of the velocity from the exact and calculated solutions
+#figure(1)
+#subplot(2,2,1)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel,'FaceColor','interp','EdgeColor','none');
+#title('Modelled velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+   
+#subplot(2,2,2)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel_obs,'FaceColor','interp','EdgeColor','none');
+#title('Analytical velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+
+#subplot(2,2,3)
+#hold on;
+#plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+#plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+#title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+#xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+#ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+#legend('calculated velocity','exact velocity');
+#axis([0 750000 0 200]);
+#hold off;
+
+#subplot(2,2,4)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+#title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+#colorbar;
+#caxis([0 100]);
+
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('HOstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv HOstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+
+#Fields and tolerances to track changes
+field_names     =[ \
+	'Vx','Vy','Vel', \
+]
+field_tolerances=[ \
+	1e-12,1e-12,1e-12, \
+]
+field_values=[ \
+	vx,vy,vel, \
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.m	(revision 18231)
@@ -0,0 +1,97 @@
+%The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+printingflag=false;
+
+numlayers=10;
+resolution=30000.;
+
+%To begin with the numerical model
+md=model();
+md=roundmesh(md,750000.,resolution);
+md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.par');
+
+%Calculation of the analytical 2d velocity field
+constant=0.3;
+vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+
+%We extrude the model to have a 3d model
+md=extrude(md,numlayers,1.);
+md=setflowequation(md,'FS','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+for i=1:md.mesh.numberofvertices2d
+	node_vel=0.;
+	for j=1:md.mesh.numberoflayers-1
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*...
+			(sqrt(vx(i+j*md.mesh.numberofvertices2d,1).^2+vy(i+j*md.mesh.numberofvertices2d,1).^2)+...
+			sqrt(vx(i+(j-1)*md.mesh.numberofvertices2d,1).^2+vy(i+(j-1)*md.mesh.numberofvertices2d,1).^2));
+	end
+	vel(i,1)=node_vel;
+end
+
+%Plot of the velocity from the exact and calculated solutions
+figure(1)
+subplot(2,2,1)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel,'FaceColor','interp','EdgeColor','none');
+title('Modelled velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+   
+subplot(2,2,2)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+vel_obs,'FaceColor','interp','EdgeColor','none');
+title('Analytical velocity','FontSize',14,'FontWeight','bold')
+colorbar; 
+caxis([0 200]);
+
+subplot(2,2,3)
+hold on;
+plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+legend('calculated velocity','exact velocity');
+axis([0 750000 0 200]);
+hold off;
+
+subplot(2,2,4)
+p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+colorbar;
+caxis([0 100]);
+
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('FSstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv FSstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+end
+
+%Fields and tolerances to track changes
+field_names     ={ ...
+	'Vx','Vy','Vel', ...
+};
+field_tolerances={ ...
+	1e-12,1e-12,1e-12, ...
+};
+field_values={ ...
+	vx,vy,vel, ...
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1207.py	(revision 18231)
@@ -0,0 +1,108 @@
+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 *
+
+"""
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
+"""
+
+printingflag=False
+
+numlayers=10
+resolution=30000.
+
+#To begin with the numerical model
+md=model()
+md=roundmesh(md,750000.,resolution)
+md=setmask(md,'','')    #We can not test iceshelves nor ice rises with this analytical solution
+md=parameterize(md,'../Par/RoundSheetStaticEISMINT.py')
+
+#Calculation of the analytical 2d velocity field
+constant=0.3
+vx_obs=constant/2.*md.mesh.x.reshape(-1,1)*(md.geometry.thickness)**-1
+vy_obs=constant/2.*md.mesh.y.reshape(-1,1)*(md.geometry.thickness)**-1
+vel_obs=numpy.sqrt((md.inversion.vx_obs)**2+(md.inversion.vy_obs)**2)
+
+#We extrude the model to have a 3d model
+md.extrude(numlayers,1.)
+md=setflowequation(md,'FS','all')
+
+#Spc the nodes on the bed
+pos=numpy.nonzero(md.mesh.vertexonbase)
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
+
+#Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Calculate the depth averaged velocity field (2d):
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
+vel=numpy.zeros((md.mesh.numberofvertices2d,1))
+
+for i in xrange(0,md.mesh.numberofvertices2d):
+	node_vel=0.
+	for j in xrange(0,md.mesh.numberoflayers-1):
+		node_vel=node_vel+1./(2.*(md.mesh.numberoflayers-1))*\
+			(numpy.sqrt(vx[i+(j+1)*md.mesh.numberofvertices2d,0]**2+vy[i+(j+1)*md.mesh.numberofvertices2d,0]**2)+\
+			numpy.sqrt(vx[i+j*md.mesh.numberofvertices2d,0]**2+vy[i+j*md.mesh.numberofvertices2d,0]**2))
+	vel[i,0]=node_vel
+
+#Plot of the velocity from the exact and calculated solutions
+#figure(1)
+#subplot(2,2,1)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel,'FaceColor','interp','EdgeColor','none');
+#title('Modelled velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+   
+#subplot(2,2,2)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#vel_obs,'FaceColor','interp','EdgeColor','none');
+#title('Analytical velocity','FontSize',14,'FontWeight','bold')
+#colorbar; 
+#caxis([0 200]);
+
+#subplot(2,2,3)
+#hold on;
+#plot(sqrt((md.mesh.x(1:md.mesh.numberofvertices2d)).^2+(md.mesh.y(1:md.mesh.numberofvertices2d)).^2),vel,'r.');
+#plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+#title('Analytical vs calculated velocity','FontSize',14,'FontWeight','bold');
+#xlabel('distance to the center of the icesheet [m]','FontSize',14,'FontWeight','bold');
+#ylabel('velocity [m/yr]','FontSize',14,'FontWeight','bold');
+#legend('calculated velocity','exact velocity');
+#axis([0 750000 0 200]);
+#hold off;
+
+#subplot(2,2,4)
+#p=patch('Faces',md.mesh.elements2d,'Vertices',[md.mesh.x2d md.mesh.y2d],'FaceVertexCData',...
+#abs(vel-vel_obs)./vel_obs*100,'FaceColor','interp','EdgeColor','none');
+#title('Relative misfit [%]','FontSize',14,'FontWeight','bold')
+#colorbar;
+#caxis([0 100]);
+
+if printingflag:
+	pass
+#	set(gcf,'Color','w')
+#	printmodel('FSstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv FSstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+
+#Fields and tolerances to track changes
+field_names     =[ \
+	'Vx','Vy','Vel', \
+]
+field_tolerances=[ \
+	1e-12,1e-12,1e-12, \
+]
+field_values=[ \
+	vx,vy,vel, \
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.m	(revision 18231)
@@ -0,0 +1,45 @@
+%EISMINT benchmark experiment A
+numlayers=8;
+resolution=50000.;
+
+%To begin with the numerical model
+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=setflowequation(md,'SIA','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
+
+%Adapt the time steps to the resolution
+md.timestepping.time_step=15.;
+md.settings.output_frequency=500;
+md.timestepping.final_time=30000.;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,3e-07};
+field_values={...
+	(md.results.TransientSolution(end).Vx),...
+	(md.results.TransientSolution(end).Vy),...
+	(md.results.TransientSolution(end).Vz),...
+	(md.results.TransientSolution(end).Vel),...
+	(md.results.TransientSolution(end).Pressure),...
+	(md.results.TransientSolution(end).Thickness),...
+	(md.results.TransientSolution(end).Base),...
+	(md.results.TransientSolution(end).Surface),...
+	(md.results.TransientSolution(end).Temperature),...
+	(md.results.TransientSolution(end).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1208.py	(revision 18231)
@@ -0,0 +1,58 @@
+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 *
+
+"""
+EISMINT benchmark experiment A
+"""
+
+numlayers=8
+resolution=50000.
+
+#To begin with the numerical model
+md=triangle(model(),'../Exp/SquareEISMINT750000.exp',resolution)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/RoundSheetEISMINT.py')
+
+#We extrude the model to have a 3d model
+md.extrude(numlayers,1.)
+md=setflowequation(md,'SIA','all')
+
+#Spc the nodes on the bed
+pos=numpy.nonzero(md.mesh.vertexonbase)
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
+
+#Adapt the time steps to the resolution
+md.timestepping.time_step=15.
+md.settings.output_frequency=500
+md.timestepping.final_time=30000.
+md.masstransport.stabilization=1
+md.thermal.stabilization=1
+
+#Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8)
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-07]
+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].Thickness,\
+	md.results.TransientSolution[-1].Base,\
+	md.results.TransientSolution[-1].Surface,\
+	md.results.TransientSolution[-1].Temperature,\
+	md.results.TransientSolution[-1].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.m	(revision 18231)
@@ -0,0 +1,32 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=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-9,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	(md.results.TransientSolution(3).Temperature),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test121.py	(revision 18231)
@@ -0,0 +1,41 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=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-9,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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.m	(revision 18231)
@@ -0,0 +1,56 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+md.thermal.stabilization=2;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test122.py	(revision 18231)
@@ -0,0 +1,65 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
+md.thermal.stabilization=2
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2',\
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3']
+field_tolerances=[\
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.TransientSolution[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].Base,\
+	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].Base,\
+	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].Base,\
+	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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test123.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test123.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test123.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+fake_surface=[[md.geometry.surface+100;1.1],...
+[md.geometry.surface+200;2.1],...
+[md.geometry.surface+300;2.5]];
+
+md.transient.requested_outputs={'default','SurfaceMisfit'};
+md.outputdefinition.definitions={misfit('name','SurfaceMisfit', 'model_enum',SurfaceEnum,'observation_enum',SurfaceObservationEnum,'observation',fake_surface,'timeinterpolation','nearestneighbor','weights',ones(md.mesh.numberofvertices,1),'weights_enum',WeightsSurfaceObservationEnum)};
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceMisfitFirstStep','SurfaceMisfitSecondStep','SurfaceMisfitThirdStep'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).SurfaceMisfit),...
+	(md.results.TransientSolution(2).SurfaceMisfit),...
+	(md.results.TransientSolution(3).SurfaceMisfit)
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test124.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test124.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test124.m	(revision 18231)
@@ -0,0 +1,47 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+
+%Free surface
+md.masstransport.isfreesurface=1;
+md.timestepping.time_step=0.00001;
+md.timestepping.final_time=0.00005;
+
+%Go solve
+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-09,3e-10,3e-10,1e-10,1e-13,1e-13,1e-13,...
+	1e-09,3e-10,3e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,3e-10,3e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.m	(revision 18231)
@@ -0,0 +1,46 @@
+% 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.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','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=find(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.BasalforcingsGroundediceMeltingRate;
+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-07};
+field_values    ={comp_melting};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1301.py	(revision 18231)
@@ -0,0 +1,60 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from paterson import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs 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,'HO','all')
+
+#Some conditions specific to melting test
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1),int)
+md.initialization.temperature=273.15*numpy.ones((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+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.BasalforcingsGroundediceMeltingRate
+relative=numpy.abs((comp_melting-melting)/melting)*100.
+relative[numpy.nonzero(comp_melting==melting)[0]]=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:
+	pass
+#	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 ']);
+
+#Fields and tolerances to track changes
+field_names     =['BasalMelting']
+field_tolerances=[1e-08]
+field_values    =[comp_melting]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.m	(revision 18231)
@@ -0,0 +1,49 @@
+% 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.par');
+md=extrude(md,30,1.);   %NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%)
+md=setflowequation(md,'HO','all');
+
+%Thermal boundary conditions
+pos1=find(md.mesh.elementonbase);     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10.;
+pos2=find(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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1302.py	(revision 18231)
@@ -0,0 +1,65 @@
+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 *
+
+"""
+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,'HO','all')
+
+#Thermal boundary conditions
+pos1=numpy.nonzero(md.mesh.elementonbase)[0]
+md.thermal.spctemperature[md.mesh.elements[pos1,0:3]-1]=10.
+pos2=numpy.nonzero(md.mesh.elementonsurface)[0]
+md.thermal.spctemperature[md.mesh.elements[pos2,3:6]-1]=0.
+md.initialization.vz=0.1*numpy.ones((md.mesh.numberofvertices,1))
+md.initialization.vel=numpy.sqrt( md.initialization.vx**2+ md.initialization.vy**2+ md.initialization.vz**2)
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1),int)
+
+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./(numpy.exp(alpha*(-1000.))-1.)    #A=T(bed)/(exp(alpha*bed)-1)  with bed=-1000 T(bed)=10
+B=-A
+md.initialization.temperature=A*numpy.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=numpy.abs((comp_temp-md.initialization.temperature)/md.initialization.temperature)*100.
+relative[numpy.nonzero(comp_temp==md.initialization.temperature)[0]]=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:
+	pass
+#	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 ']);
+
+#Fields and tolerances to track changes
+field_names     =['AdvectionTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.m	(revision 18231)
@@ -0,0 +1,44 @@
+% 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.par');
+md=extrude(md,11,2.);
+md=setflowequation(md,'HO','all');
+
+pos1=find(md.mesh.elementonbase);     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10.;
+pos2=find(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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1303.py	(revision 18231)
@@ -0,0 +1,60 @@
+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 *
+
+"""
+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,'HO','all')
+
+pos1=numpy.nonzero(md.mesh.elementonbase)[0]
+md.thermal.spctemperature[md.mesh.elements[pos1,0:3]-1]=10.
+pos2=numpy.nonzero(md.mesh.elementonsurface)[0]
+md.thermal.spctemperature[md.mesh.elements[pos2,3:6]-1]=0.
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1),int)
+
+#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=numpy.abs((comp_temp-md.initialization.temperature)/md.initialization.temperature)*100.
+relative[numpy.nonzero(comp_temp==md.initialization.temperature)[0]]=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:
+	pass
+#	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 ']);
+
+#Fields and tolerances to track changes
+field_names     =['ConductionTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.m	(revision 18231)
@@ -0,0 +1,44 @@
+% 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.par');
+md=extrude(md,11,1.);
+md=setflowequation(md,'HO','all');
+
+pos2=find(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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1304.py	(revision 18231)
@@ -0,0 +1,59 @@
+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 *
+
+"""
+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,'HO','all')
+
+pos2=numpy.nonzero(md.mesh.elementonsurface)[0]
+md.thermal.spctemperature[md.mesh.elements[pos2,3:6]-1]=0.
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1),int)
+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=numpy.abs((comp_temp-md.initialization.temperature)/md.initialization.temperature)*100.
+relative[numpy.nonzero(comp_temp==md.initialization.temperature)[0]]=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:
+	pass
+#	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 ']);
+
+#Fields and tolerances to track changes
+field_names     =['GeothermalFluxTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1401.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1401.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1401.m	(revision 18231)
@@ -0,0 +1,79 @@
+%test the anisotropic mesh adaptation
+%function to capture = exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+printingflag=false;
+
+%create square mesh
+L=1.; %in m
+nx=70; %numberof nodes in x direction
+ny=70;
+md=model();
+
+%mesh adaptation loop YAMS
+md=squaremesh(md,L,L,nx,ny);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_yams1','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_yams1.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md=YamsCall(md,md.inversion.vel_obs,0.001,0.3,1.3,10.^-4);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_yams2','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_yams2.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md=YamsCall(md,md.inversion.vel_obs,0.001,0.3,2.5,0.008);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_yams3','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_yams3.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%mesh adaptation loop BAMG
+md=squaremesh(md,L,L,nx,ny);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_bamg1','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_bamg1.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md.private.bamg=NaN;
+md=bamg(md,'field',md.inversion.vel_obs,'hmin',0.001,'hmax',0.3,'gradation',1.3,'err',10.^-4);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_bamg2','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_bamg2.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md.private.bamg=NaN;
+md=bamg(md,'field',md.inversion.vel_obs,'hmin',0.001,'hmax',0.3,'gradation',2.5,'err',0.008);
+md.inversion.vel_obs=exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh1_bamg3','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh1_bamg3.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%Fields and tolerances to track changes
+field_names     ={'xyams','yyams','xbamg','ybamg'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	x1, y1,...
+	x2, y2,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1402.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1402.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1402.m	(revision 18231)
@@ -0,0 +1,109 @@
+%test the anisotropic mesh adaptation
+printingflag=false;
+
+%create square mesh
+L=1.; %in m
+nx=30; %numberof nodes in x direction
+ny=30;
+md=model();
+
+%mesh adaptation loop YAMS
+md=squaremesh(md,L,L,nx,ny);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_yams1','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_yams1.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md=YamsCall(md,md.inversion.vel_obs,0.005,0.3,2.3,10.^-2);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_yams2','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_yams2.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md=YamsCall(md,md.inversion.vel_obs,0.005,0.3,3,0.005);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_yams3','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_yams3.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%mesh adaptation loop BAMG
+md=squaremesh(md,L,L,nx,ny);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_bamg1','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_bamg1.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md.private.bamg=NaN;
+md=bamg(md,'field',md.inversion.vel_obs,'hmin',0.005,'hmax',0.3,'gradation',2.3,'err',10.^-2);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_bamg2','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_bamg2.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md.private.bamg=NaN;
+md=bamg(md,'field',md.inversion.vel_obs,'hmin',0.005,'hmax',0.3,'gradation',3,'err',0.005);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_bamg3','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_bamg3.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+
+md.private.bamg=NaN;
+md=bamg(md,'field',md.inversion.vel_obs,'hmin',0.005,'hmax',0.3,'gradation',1.5,'err',0.003,'anisomax',1);
+u=4.*md.mesh.x-2.; v=4.*md.mesh.y-2.;
+md.inversion.vel_obs=tanh(30.*(u.^2+v.^2-0.25)) ...
+	+tanh(30.*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30.*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30.*((u+0.75).^2+(v+0.75).^2-0.25));
+plotmodel(md,'data',md.inversion.vel_obs,'data',md.inversion.vel_obs,'nlines',1,'ncols',2,'title','','figposition',[500 500 1000 500],'axis#all','equal','xlim#all',[0 1],'ylim#all',[0 1],'edgecolor#1','w'); pause(0.5);
+if printingflag,
+	set(gcf,'Color','w')
+	printmodel('mesh2_bamgiso','png','margin','on','marginsize',25,'frame','off','resolution',1,'hardcopy','off');
+	system(['mv mesh2_bamgiso.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Mesh/ ']);
+end
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%Fields and tolerances to track changes
+field_names     ={'xyams','yyams','xbamg','ybamg'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	x1, y1,...
+	x2, y2,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.m	(revision 18231)
@@ -0,0 +1,207 @@
+printingflag = false;
+
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','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,MasstransportSolutionEnum());
+
+for i=1:10
+	 md=solve(md,MasstransportSolutionEnum());
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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 mean(md.results.TransientSolution(t).Thickness.value,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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1501.py	(revision 18231)
@@ -0,0 +1,222 @@
+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 *
+
+printingflag = False
+
+md=triangle(model(),'../Exp/Square.exp',350000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isthermal=False
+
+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.*numpy.ones((md.mesh.numberofvertices,1))
+md.surfaceforcings.mass_balance= smb
+md.basalforcings.melting_rate= smb
+
+md=solve(md,MasstransportSolutionEnum())
+
+for i in xrange(1,11):
+	 md=solve(md,MasstransportSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness)
+
+#Set up transient
+smb = md.surfaceforcings.mass_balance
+
+#tooth= [ [ones(400,1)*(smb') - 10.]' [ones(400,1)*(smb')]' ];
+tooth=numpy.hstack((numpy.tile(smb-10.,(1,400)),numpy.tile(smb,(1,400))))
+#smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
+smb=numpy.hstack((numpy.tile(smb,(1,399)),smb,tooth,tooth))
+
+#md.surfaceforcings.mass_balance= smb;
+#md.surfaceforcings.mass_balance(end+1,:)=[1.:2000.];
+md.surfaceforcings.mass_balance=numpy.vstack((smb,numpy.arange(1,2001)))
+
+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-1].Vx,\
+	md.results.TransientSolution[400-1].Vy,\
+	md.results.TransientSolution[400-1].Vel,\
+	md.results.TransientSolution[400-1].Pressure,\
+	md.results.TransientSolution[400-1].Base,\
+	md.results.TransientSolution[400-1].Surface,\
+	md.results.TransientSolution[400-1].Thickness,\
+	md.results.TransientSolution[400-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[800-1].Vx,\
+	md.results.TransientSolution[800-1].Vy,\
+	md.results.TransientSolution[800-1].Vel,\
+	md.results.TransientSolution[800-1].Pressure,\
+	md.results.TransientSolution[800-1].Base,\
+	md.results.TransientSolution[800-1].Surface,\
+	md.results.TransientSolution[800-1].Thickness,\
+	md.results.TransientSolution[800-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1200-1].Vx,\
+	md.results.TransientSolution[1200-1].Vy,\
+	md.results.TransientSolution[1200-1].Vel,\
+	md.results.TransientSolution[1200-1].Pressure,\
+	md.results.TransientSolution[1200-1].Base,\
+	md.results.TransientSolution[1200-1].Surface,\
+	md.results.TransientSolution[1200-1].Thickness,\
+	md.results.TransientSolution[1200-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1600-1].Vx,\
+	md.results.TransientSolution[1600-1].Vy,\
+	md.results.TransientSolution[1600-1].Vel,\
+	md.results.TransientSolution[1600-1].Pressure,\
+	md.results.TransientSolution[1600-1].Base,\
+	md.results.TransientSolution[1600-1].Surface,\
+	md.results.TransientSolution[1600-1].Thickness,\
+	md.results.TransientSolution[1600-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2000-1].Vx,\
+	md.results.TransientSolution[2000-1].Vy,\
+	md.results.TransientSolution[2000-1].Vel,\
+	md.results.TransientSolution[2000-1].Pressure,\
+	md.results.TransientSolution[2000-1].Base,\
+	md.results.TransientSolution[2000-1].Surface,\
+	md.results.TransientSolution[2000-1].Thickness,\
+	md.results.TransientSolution[2000-1].SurfaceforcingsMassBalance,\
+	]
+
+if printingflag:
+	pass
+
+	"""
+	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 mean(md.results.TransientSolution(t).Thickness.value,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)
+	"""
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.m	(revision 18231)
@@ -0,0 +1,213 @@
+printingflag = false;
+
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,3,1.);
+md.cluster=generic('name',oshostname(),'np',1);
+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,MasstransportSolutionEnum());
+
+for i=1:10
+	 md=solve(md,MasstransportSolutionEnum());
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(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 mean(md.results.TransientSolution(t).Thickness.value,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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1502.py	(revision 18231)
@@ -0,0 +1,228 @@
+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 *
+
+printingflag = False
+
+md=triangle(model(),'../Exp/Square.exp',450000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.extrude(3,1.)
+md.cluster=generic('name',oshostname(),'np',2)
+md.transient.isthermal=False
+
+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.*numpy.ones((md.mesh.numberofvertices,1))
+md.surfaceforcings.mass_balance= smb
+md.basalforcings.melting_rate= smb
+
+md=solve(md,MasstransportSolutionEnum())
+
+for i in xrange(1,11):
+	 md=solve(md,MasstransportSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness)
+
+#Set up transient
+smb = md.surfaceforcings.mass_balance
+
+#tooth= [ [ones(400,1)*(smb') - 10.]' [ones(400,1)*(smb')]' ];
+tooth=numpy.hstack((numpy.tile(smb-10.,(1,400)),numpy.tile(smb,(1,400))))
+#smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
+smb=numpy.hstack((numpy.tile(smb,(1,399)),smb,tooth,tooth))
+
+#md.surfaceforcings.mass_balance= smb;
+#md.surfaceforcings.mass_balance(end+1,:)=[1.:2000.];
+md.surfaceforcings.mass_balance=numpy.vstack((smb,numpy.arange(1,2001)))
+
+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-1].Vx,\
+	md.results.TransientSolution[400-1].Vy,\
+	md.results.TransientSolution[400-1].Vz,\
+	md.results.TransientSolution[400-1].Vel,\
+	md.results.TransientSolution[400-1].Pressure,\
+	md.results.TransientSolution[400-1].Base,\
+	md.results.TransientSolution[400-1].Surface,\
+	md.results.TransientSolution[400-1].Thickness,\
+	md.results.TransientSolution[400-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[800-1].Vx,\
+	md.results.TransientSolution[800-1].Vy,\
+	md.results.TransientSolution[800-1].Vz,\
+	md.results.TransientSolution[800-1].Vel,\
+	md.results.TransientSolution[800-1].Pressure,\
+	md.results.TransientSolution[800-1].Base,\
+	md.results.TransientSolution[800-1].Surface,\
+	md.results.TransientSolution[800-1].Thickness,\
+	md.results.TransientSolution[800-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1200-1].Vx,\
+	md.results.TransientSolution[1200-1].Vy,\
+	md.results.TransientSolution[1200-1].Vz,\
+	md.results.TransientSolution[1200-1].Vel,\
+	md.results.TransientSolution[1200-1].Pressure,\
+	md.results.TransientSolution[1200-1].Base,\
+	md.results.TransientSolution[1200-1].Surface,\
+	md.results.TransientSolution[1200-1].Thickness,\
+	md.results.TransientSolution[1200-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1600-1].Vx,\
+	md.results.TransientSolution[1600-1].Vy,\
+	md.results.TransientSolution[1600-1].Vz,\
+	md.results.TransientSolution[1600-1].Vel,\
+	md.results.TransientSolution[1600-1].Pressure,\
+	md.results.TransientSolution[1600-1].Base,\
+	md.results.TransientSolution[1600-1].Surface,\
+	md.results.TransientSolution[1600-1].Thickness,\
+	md.results.TransientSolution[1600-1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2000-1].Vx,\
+	md.results.TransientSolution[2000-1].Vy,\
+	md.results.TransientSolution[2000-1].Vz,\
+	md.results.TransientSolution[2000-1].Vel,\
+	md.results.TransientSolution[2000-1].Pressure,\
+	md.results.TransientSolution[2000-1].Base,\
+	md.results.TransientSolution[2000-1].Surface,\
+	md.results.TransientSolution[2000-1].Thickness,\
+	md.results.TransientSolution[2000-1].SurfaceforcingsMassBalance,\
+	]
+
+if printingflag:
+	pass
+	"""
+
+	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 mean(md.results.TransientSolution(t).Thickness.value,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)
+	"""
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.m	(revision 18231)
@@ -0,0 +1,45 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.stressbalance.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,StressbalanceSolutionEnum());
+vel0=md.results.StressbalanceSolution.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.stressbalance.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.stressbalance.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,StressbalanceSolutionEnum());
+vel1=md.results.StressbalanceSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+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.stressbalance.referential(:)=NaN;
+md.stressbalance.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1);
+md.stressbalance.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1);
+md=solve(md,StressbalanceSolutionEnum());
+vel2=md.results.StressbalanceSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1601.py	(revision 18231)
@@ -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,'SSA','all')
+md.stressbalance.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,StressbalanceSolutionEnum())
+vel0=md.results.StressbalanceSolution.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.stressbalance.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.stressbalance.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,StressbalanceSolutionEnum())
+vel1=md.results.StressbalanceSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+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.stressbalance.referential[:]=float('NaN')
+md.stressbalance.referential[pos,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(len(pos),1))
+md.stressbalance.referential[pos,3: ]=numpy.tile([0,0,1],(len(pos),1))
+md=solve(md,StressbalanceSolutionEnum())
+vel2=md.results.StressbalanceSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'HO','all');
+md.stressbalance.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,StressbalanceSolutionEnum());
+vel0=md.results.StressbalanceSolution.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.stressbalance.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.stressbalance.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,StressbalanceSolutionEnum());
+vel1=md.results.StressbalanceSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test1602.py	(revision 18231)
@@ -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,'HO','all')
+md.stressbalance.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,StressbalanceSolutionEnum())
+vel0=md.results.StressbalanceSolution.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.stressbalance.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.stressbalance.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,StressbalanceSolutionEnum())
+vel1=md.results.StressbalanceSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.m	(revision 18231)
@@ -0,0 +1,29 @@
+%GIA test, inspired on test101
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2400000; %2,400 kyr :: EVALUATION TIME
+% to get rid of default final_time: make sure final_time>start_time
+md.timestepping.final_time=2500000; %2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness; 0.0],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2001.py	(revision 18231)
@@ -0,0 +1,44 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#Define a model 
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+
+#Indicate what you want to compute 
+md.gia.cross_section_shape=1    # for square-edged x-section 
+
+#Define loading history (see test2001.m for the description)
+md.timestepping.start_time=2400000 # 2,400 kyr
+md.timestepping.final_time=2500000 # 2,500 kyr
+md.geometry.thickness=[\
+	[md.geometry.thickness*0.0; 0.0],\
+	[md.geometry.thickness/2.0; 0.1],\
+	[md.geometry.thickness; 0.2],\
+	[md.geometry.thickness; 1.0],\
+	[md.geometry.thickness; md.timestepping.start_time],\
+	]
+
+#Solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3)
+md.verbose=verbose('1111111')
+md=solve(md,GiaSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['GiaW','GiadWdt']
+field_tolerances=[1e-13,1e-13]
+field_values    =[\
+		md.results.GiaSolution.GiaW,\
+		md.results.GiaSolution.GiadWdt,\
+		]
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test201.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test202.py	(revision 18231)
@@ -0,0 +1,31 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test203.py	(revision 18231)
@@ -0,0 +1,31 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[2e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.m	(revision 18231)
@@ -0,0 +1,27 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.stressbalance.shelf_dampening=1;
+md.timestepping.time_step=0;
+md1=solve(md,StressbalanceSolutionEnum());
+md.stressbalance.shelf_dampening=0;
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Vx_damp','Vy_damp','Vz_damp','Vel_damp','Pressure_damp'};
+field_tolerances={1e-08,1e-08,2e-06,1e-08,1e-08,1e-08,1e-08,2e-07,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md1.results.StressbalanceSolution.Vx),...
+	(md1.results.StressbalanceSolution.Vy),...
+	(md1.results.StressbalanceSolution.Vz),...
+	(md1.results.StressbalanceSolution.Vel),...
+	(md1.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test204.py	(revision 18231)
@@ -0,0 +1,35 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.shelf_dampening=1;
+md.timestepping.time_step=0;
+md1=solve(md,StressbalanceSolutionEnum())
+md.stressbalance.shelf_dampening=0;
+md=solve(md,StressbalanceSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,2e-06,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test205.py	(revision 18231)
@@ -0,0 +1,31 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA','coupling','penalties')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-05,1e-05,1e-05,1e-05,1e-05]
+field_values=[\
+md.results.StressbalanceSolution.Vx,\
+md.results.StressbalanceSolution.Vy,\
+md.results.StressbalanceSolution.Vz,\
+md.results.StressbalanceSolution.Vel,\
+md.results.StressbalanceSolution.Pressure,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2051.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2051.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2051.m	(revision 18231)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2002100; % after 2 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2052.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2052.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2052.m	(revision 18231)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2005100; % after 5 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2053.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2053.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2053.m	(revision 18231)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2010100; % after 10 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,5e-6};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test206.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,5e-6]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={1e-13,1e-6,1e-13,1e-6,1e-13,1e-6};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test207.py	(revision 18231)
@@ -0,0 +1,34 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2071.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2071.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2071.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=0.3;     % for t \approx 0 kyr : to get eleastic response!   
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2072.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2072.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2072.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=1000.3;  % for t \approx 1 kyr 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2073.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2073.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2073.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2400000; % for t \approx \infty 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.m	(revision 18231)
@@ -0,0 +1,33 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test208.py	(revision 18231)
@@ -0,0 +1,46 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2081.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2081.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2081.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge  
+
+%% define loading history 
+md.timestepping.start_time=0.3;     % for t \approx 0 kyr : to get eleastic response!   
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2082.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2082.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2082.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge 
+
+%% define loading history 
+md.timestepping.start_time=1000.3;  % for t \approx 1 kyr 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2083.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2083.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test2083.m	(revision 18231)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge 
+
+%% define loading history 
+md.timestepping.start_time=2400000; % for t \approx \infty 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.m	(revision 18231)
@@ -0,0 +1,48 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+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,3e-9,1e-13,3.8e-11,3.85e-11,3.85e-11,3.85e-11,1e-13,2e-8,...
+	5e-11,6e-12,1e-08,6e-12,3.9e-11,1e-10,1e-10,1e-10,9e-12,5e-8};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test209.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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,3e-9,1e-13,3.8e-11,3.85e-11,3.85e-11,3.85e-11,1e-13,2e-8,\
+	5e-11,6e-12,1e-08,6e-12,3.9e-11,1e-10,1e-10,1e-10,9e-12,5e-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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.m	(revision 18231)
@@ -0,0 +1,48 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test210.py	(revision 18231)
@@ -0,0 +1,61 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.m	(revision 18231)
@@ -0,0 +1,50 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+md.stressbalance.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','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
+	5e-07,5e-07,5e-05,1e-07,1e-08,1e-08,1e-08,1e-08,5e-08,2e-06,...
+	5e-06,5e-06,5e-05,5e-06,5e-07,5e-07,5e-07,1e-07,1e-06,5e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test211.py	(revision 18231)
@@ -0,0 +1,63 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'FS','all')
+md.stressbalance.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','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+field_tolerances=[\
+	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,\
+	5e-07,5e-07,5e-05,1e-07,1e-08,1e-08,1e-08,1e-08,5e-08,2e-06,\
+	5e-06,5e-06,5e-05,5e-06,1e-07,5e-07,5e-07,5e-07,1e-06,5e-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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','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;
+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.verbose.control=true;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test212.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','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]
+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,StressbalanceSolutionEnum())
+
+
+# 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.StressbalanceSolution.Gradient1,\
+md.results.StressbalanceSolution.J,\
+md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+md.results.StressbalanceSolution.Pressure,\
+md.results.StressbalanceSolution.Vel,\
+md.results.StressbalanceSolution.Vx,\
+md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.m	(revision 18231)
@@ -0,0 +1,37 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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;
+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.verbose.control=true;
+md.verbose.solution=true;
+
+md.cluster=generic('name',oshostname(),'np',1);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	md.results.StressbalanceSolution.J,...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test213.py	(revision 18231)
@@ -0,0 +1,52 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','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]
+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,StressbalanceSolutionEnum())
+
+
+# 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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','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;
+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,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test214.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','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]
+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,StressbalanceSolutionEnum())
+
+
+# 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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','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;
+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,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy'};
+field_tolerances={1e-08,1e-09,2e-09,1e-09,2e-09,5e-09,2e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test215.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'FS','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]
+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,StressbalanceSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names     =['Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy']
+field_tolerances=[1e-08,1e-09,2e-09,1e-09,2e-09,5e-09,2e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.m	(revision 18231)
@@ -0,0 +1,24 @@
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
+md=meshprocessrifts(md,'../Exp/Square.exp');
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%rift settings
+md.rifts.riftstruct.fill=MelangeEnum();
+md.rifts.riftstruct.fraction=0;
+md.stressbalance.rift_penalty_lock=2;
+md.stressbalance.rift_penalty_threshold=0;
+md.rifts.riftstruct.fractionincrement=.1;
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={8e-7,5e-8,7e-8,2e-11};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test216.py	(revision 18231)
@@ -0,0 +1,38 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.)
+md=meshprocessrifts(md,'../Exp/Square.exp')
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf2.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+# rift settings
+
+md.rifts.riftstruct[0]['fill']=MelangeEnum()
+md.rifts.riftstruct[0]['fraction']=0
+md.stressbalance.rift_penalty_lock=2
+md.stressbalance.rift_penalty_threshold=0
+md.rifts.riftstruct[0]['fractionincrement']=0.1
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vel','Pressure']
+field_tolerances=[4e-11,2e-11,4e-11,2e-11]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.m	(revision 18231)
@@ -0,0 +1,67 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%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.stressbalance.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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+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.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+md.mask.ice_levelset=-1+nodeonicefront;
+
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vy)};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test217.py	(revision 18231)
@@ -0,0 +1,82 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+# 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.stressbalance.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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+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.stressbalance.spcvx=float(nan)*ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvy=float(nan)*ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvz=float(nan)*ones((md.mesh.numberofvertices,1))
+
+# constrain flanks to 0 normal velocity
+pos=numpy.nonzero(numpy.logical_or(md.mesh.x==xmin,md.mesh.x==xmax))
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvz[pos]=float(nan)
+
+# constrain grounding line to 0 velocity
+pos=numpy.nonzero(md.mesh.y==ymin)
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvy[pos]=0
+
+# icefront
+nodeonicefront=zeros(md.mesh.numberofvertices)
+pos=numpy.nonzero(md.mesh.y==ymax)
+nodeonicefront[pos]=1
+md.mask.ice_levelset=-1+nodeonicefront
+
+md=solve(md,StressbalanceSolutionEnum())
+
+# 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.StressbalanceSolution.Vy,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test218.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test218.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test218.m	(revision 18231)
@@ -0,0 +1,85 @@
+md=squaremesh(model(),1000000,1000000,5,5);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=setflowequation(md,'SSA','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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+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.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+%Dakota options
+%variables
+md.qmu.variables.rheology_B=normal_uncertain('scaled_MaterialsRheologyB',1,.05);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.stressbalance.reltol=10^-10; %tighten for qmu analysese
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,StressbalanceSolutionEnum(),'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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test219.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',120000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,5e-06,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test220.py	(revision 18231)
@@ -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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',120000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf2.py')
+md.extrude(2,1.)
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,5e-06,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',120000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.viscosity_overshoot=0;
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,5e-06,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test221.py	(revision 18231)
@@ -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/SquareShelf2.py')
+md.extrude(2,1.)
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.viscosity_overshoot=0
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,5e-06,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test222.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.m	(revision 18231)
@@ -0,0 +1,35 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.geometry.base=md.geometry.base+50.; md.geometry.surface=md.geometry.surface+50.;
+md.cluster=generic('name',oshostname(),'np',1);
+md.masstransport.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test223.py	(revision 18231)
@@ -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,'SSA','all')
+md.geometry.base=md.geometry.base+50.
+md.geometry.surface=md.geometry.surface+50.
+md.cluster=generic('name',oshostname(),'np',1)
+md.masstransport.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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.m	(revision 18231)
@@ -0,0 +1,49 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test224.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.hydrostatic_adjustment='Incremental'
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.m	(revision 18231)
@@ -0,0 +1,50 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md.geometry.base=md.geometry.base+50.; md.geometry.surface=md.geometry.surface+50.;
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	2e-09,1e-09,2e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test225.py	(revision 18231)
@@ -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.base=md.geometry.base+50.
+md.geometry.surface=md.geometry.surface+50.
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.hydrostatic_adjustment='Incremental'
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+field_tolerances=[\
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
+	2e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.m	(revision 18231)
@@ -0,0 +1,35 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1.;
+md.timestepping.final_time=10.;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test226.py	(revision 18231)
@@ -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,'SSA','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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.m	(revision 18231)
@@ -0,0 +1,50 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1.;
+md.timestepping.final_time=15.;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+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-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test227.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_adapt=1.
+md.timestepping.final_time=15.
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.m	(revision 18231)
@@ -0,0 +1,63 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test228.py	(revision 18231)
@@ -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,'SSA','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=False
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.m	(revision 18231)
@@ -0,0 +1,63 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test229.py	(revision 18231)
@@ -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,'SSA','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=False
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.m	(revision 18231)
@@ -0,0 +1,68 @@
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test230.py	(revision 18231)
@@ -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,'SSA','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=False
+
+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']
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.m	(revision 18231)
@@ -0,0 +1,68 @@
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test231.py	(revision 18231)
@@ -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,'SSA','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=False
+
+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']
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.m	(revision 18231)
@@ -0,0 +1,28 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5., md.thermal.spctemperature+10., md.thermal.spctemperature+15.; 1.5 2.5 3.5 4.];
+md.timestepping.time_step=1;
+md.timestepping.final_time=4;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3','Temperature4','BasalforcingsGroundediceMeltingRate4'};
+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),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test232.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.thermal.spctemperature=numpy.vstack((numpy.hstack((md.thermal.spctemperature, md.thermal.spctemperature+5., md.thermal.spctemperature+10., md.thermal.spctemperature+15.)), [1.5,2.5,3.5,4.]))
+md.timestepping.time_step=1.
+md.timestepping.final_time=4.
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3','Temperature4','BasalforcingsGroundediceMeltingRate4']
+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].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[3].Temperature,\
+	md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.m	(revision 18231)
@@ -0,0 +1,62 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5.; 1. 2.];
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=2.;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4'};
+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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test233.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.thermal.spctemperature=numpy.vstack((numpy.hstack((md.thermal.spctemperature, md.thermal.spctemperature+5.)), [1.,2.]))
+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','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3', \
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4']
+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-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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].Temperature,\
+	md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test234.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test234.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test234.m	(revision 18231)
@@ -0,0 +1,77 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,0.1);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%%  nond_sampling study
+md.qmu.method=dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'seed',1234,'samples',20,'sample_type','lhs');
+dver=textscan(IssmConfig('_DAKOTA_VERSION_'),'%[0123456789].%[0123456789].%[0123456789]');
+if ((str2num(dver{1}{1})==4 && str2num(dver{2}{1})>2) || str2num(dver{1}{1})>4)
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'rng','rnum2');
+end
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.params.tabular_graphics_data=true;
+md.qmu.isdakota=1;
+
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs={'IceVolume'};
+
+%solve
+md=solve(md,TransientSolutionEnum(),'overwrite','y');
+md.qmu.results=md.results.dakota;
+
+%Fields and tolerances to track changes
+md.results.dakota.moments=[];
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'moments'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.moments,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test235.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test235.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test235.m	(revision 18231)
@@ -0,0 +1,72 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,100);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size='0.1';
+md.qmu.isdakota=1;
+
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs={'IceVolume'};
+
+%solve
+md=solve(md,TransientSolutionEnum(),'overwrite','y');
+md.qmu.results=md.results.dakota;
+
+%Fields and tolerances to track changes
+md.results.dakota.moments=[];
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'moments'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.moments,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.m	(revision 18231)
@@ -0,0 +1,85 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+
+% Use of ispdd and isdelta18o methods
+md.surfaceforcings = SMBpdd();
+md.surfaceforcings.isdelta18o=1;
+
+% Add temperature, precipitation and delta18o needed to measure the surface mass balance
+% creating delta18o
+load '../Data/delta18o.data'
+md.surfaceforcings.delta18o=delta18o;
+% creating delta18oSurface
+md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
+md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
+
+% creating Present day and lgm temperatures
+% Same temperature over the all region:
+tmonth(1:12)=238.15+20.;
+for imonth=0:11
+    md.surfaceforcings.temperatures_presentday(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1);
+    md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1)-20.;
+    % Time for the last line:
+    md.surfaceforcings.temperatures_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.temperatures_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=mean(md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1:12),2); %-10*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=repmat(md.thermal.spctemperature,1,md.timestepping.final_time/md.timestepping.time_step);
+itemp=0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
+md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1); %*ones(md.mesh.numberofvertices,1);
+
+% creating precipitation
+for imonth=0:11
+    md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% time steps and resolution
+md.timestepping.time_step=20;
+md.timestepping.final_time=60;
+
+% 
+md.transient.requested_outputs={'default','SurfaceforcingsMonthlytemperatures'};
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test236.py	(revision 18231)
@@ -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','')
+md=parameterize(md,'../Par/SquareShelf.py')
+
+# Use of ispdd and isdelta18o methods
+md.surfaceforcings = SMBpdd();
+md.surfaceforcings.isdelta18o=1
+
+# 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.transient.requested_outputs=['default','SurfaceforcingsMonthlytemperatures']
+md=setflowequation(md,'SSA','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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMonthlytemperatures,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.m	(revision 18231)
@@ -0,0 +1,100 @@
+md=triangle(model(),'../Exp/Square.exp',600000.);%180000
+md=setmask(md,'all','');
+
+% Use of ispdd and isdelta18o methods
+md.surfaceforcings = SMBpdd();
+md.surfaceforcings.isdelta18o=1;
+
+md=parameterize(md,'../Par/SquareShelf.par');
+
+% Add temperature, precipitation and delta18o needed to measure the surface mass balance
+% creating delta18o
+load '../Data/delta18o.data'
+md.surfaceforcings.delta18o=delta18o;
+% creating delta18oSurface
+md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
+md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
+
+% creating Present day and lgm temperatures
+% Same temperature over the all region:
+tmonth(1:12)=238.15+20.;
+for imonth=0:11
+    md.surfaceforcings.temperatures_presentday(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1);
+    md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1)-20.;
+    % Time for the last line:
+    md.surfaceforcings.temperatures_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.temperatures_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=mean(md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1:12),2); %-10*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=repmat(md.thermal.spctemperature,1,md.timestepping.final_time/md.timestepping.time_step);
+itemp=0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
+md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1); %*ones(md.mesh.numberofvertices,1);
+
+% creating precipitation
+for imonth=0:11
+    md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% time steps and resolution
+md.timestepping.time_step=20;
+md.settings.output_frequency=1;
+md.timestepping.final_time=60;
+
+%
+md.transient.requested_outputs={'default','SurfaceforcingsMonthlytemperatures'};
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	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),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(2).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(3).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test237.py	(revision 18231)
@@ -0,0 +1,112 @@
+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 *
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',600000)    #180000
+md=setmask(md,'all','')
+
+# Use of ispdd and isdelta18o methods
+md.surfaceforcings = SMBpdd();
+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].reshape(-1,1)   #*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.transient.requested_outputs=['default','SurfaceforcingsMonthlytemperatures']
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[2].SurfaceforcingsMonthlytemperatures,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.m	(revision 18231)
@@ -0,0 +1,64 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+md.timestepping.interp_forcings=0;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test238.py	(revision 18231)
@@ -0,0 +1,73 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+md.timestepping.interp_forcings=False
+
+#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=False
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.m	(revision 18231)
@@ -0,0 +1,70 @@
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+md.timestepping.interp_forcings=0;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test239.py	(revision 18231)
@@ -0,0 +1,79 @@
+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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+md.timestepping.interp_forcings=False
+
+#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=False
+
+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']
+field_tolerances=[\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.m	(revision 18231)
@@ -0,0 +1,20 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md.materials=matdamageice();
+md=parameterize(md,'../Par/SquareShelf.par');
+md.damage.isdamage=1;
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test270.py	(revision 18231)
@@ -0,0 +1,32 @@
+import numpy
+from model import model
+from triangle import triangle
+from setmask import setmask
+from parameterize import parameterize
+from setflowequation import setflowequation
+from EnumDefinitions import StressbalanceSolutionEnum
+from solve import solve
+from matdamageice import matdamageice
+from generic import generic
+from socket import gethostname as oshostname
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md.materials=matdamageice()
+md=parameterize(md,'../Par/SquareShelf.py')
+md.damage.isdamage=1
+md.damage.D=0.5*numpy.ones(md.mesh.numberofvertices)
+md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.m	(revision 18231)
@@ -0,0 +1,29 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md.materials=matdamageice();
+md=parameterize(md,'../Par/SquareShelf.par');
+md.damage.isdamage=1;
+md.damage.D=zeros(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.law=1;
+
+%boundary conditions for damage, to be put in SquareShelf.par
+boundary=zeros(md.mesh.numberofvertices,1);
+boundary(md.mesh.segments(:,1:2))=1;
+pos=find(~md.mask.ice_levelset==0 & boundary==1);
+md.damage.spcdamage(pos)=0.5;
+md.damage.stabilization=1;
+
+md.damage.requested_outputs={'default','DamageF'};
+
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DamageEvolutionSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'D','F'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+		(md.results.DamageEvolutionSolution.DamageDbar),...
+		(md.results.DamageEvolutionSolution.DamageF),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test271.py	(revision 18231)
@@ -0,0 +1,38 @@
+import numpy 
+from triangle import triangle
+from model import model
+from setmask import setmask
+from parameterize import parameterize
+from verbose import verbose
+from setflowequation import setflowequation
+from generic import generic
+from socket import gethostname as oshostname
+from solve import solve
+from EnumDefinitions import DamageEvolutionSolutionEnum
+from matdamageice import matdamageice
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md.materials=matdamageice()
+md=parameterize(md,'../Par/SquareShelf.py')
+md.damage.isdamage=1
+md.damage.D=numpy.zeros(md.mesh.numberofvertices)
+md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
+md.damage.law=1
+md.damage.stabilization=1;
+
+pos=numpy.nonzero(numpy.logical_and(md.mask.ice_levelset!=0,md.mesh.vertexonboundary==1))
+md.damage.spcdamage[pos]=0.5;
+
+md.damage.requested_outputs=['default','DamageF']
+
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,DamageEvolutionSolutionEnum())
+
+field_names=['D','F']
+field_tolerances=[1.e-13,1.e-13]
+field_values=[\
+		md.results.DamageEvolutionSolution.DamageDbar,\
+		md.results.DamageEvolutionSolution.DamageF,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.m	(revision 18231)
@@ -0,0 +1,39 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md.materials=matdamageice();
+md=parameterize(md,'../Par/SquareShelf.par');
+md.damage.isdamage=1;
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md=setflowequation(md,'SSA','all');
+md.verbose=verbose('control',true);
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'DamageDbar'};
+md.inversion.min_parameters=zeros(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=(1-10^-13)*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101;
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=0.9*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2.*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; 
+md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','DamageDbar','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.StressbalanceSolution.Gradient1),...
+   (md.results.StressbalanceSolution.J),...
+   (md.results.StressbalanceSolution.DamageDbar),...
+   (md.results.StressbalanceSolution.Pressure),...
+   (md.results.StressbalanceSolution.Vel),...
+   (md.results.StressbalanceSolution.Vx),...
+   (md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test272.py	(revision 18231)
@@ -0,0 +1,50 @@
+import numpy
+from model import model
+from triangle import triangle
+from setmask import setmask
+from parameterize import parameterize
+from setflowequation import setflowequation
+from EnumDefinitions import StressbalanceSolutionEnum
+from solve import solve
+from socket import gethostname as oshostname
+from matdamageice import matdamageice
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md.materials=matdamageice()
+md=parameterize(md,'../Par/SquareShelf.py')
+md.damage.isdamage=1
+md.damage.D=0.5*numpy.ones(md.mesh.numberofvertices)
+md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
+md=setflowequation(md,'SSA','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['DamageDbar']
+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]
+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,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Gradient','Misfits','DamageDbar','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.StressbalanceSolution.Gradient1,\
+   md.results.StressbalanceSolution.J,\
+   md.results.StressbalanceSolution.DamageDbar,\
+   md.results.StressbalanceSolution.Pressure,\
+   md.results.StressbalanceSolution.Vel,\
+   md.results.StressbalanceSolution.Vx,\
+   md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
+md=meshprocessrifts(md,'../Exp/Square.exp');
+md=setmask(md,'all','');
+md.materials=matdamageice();
+md=parameterize(md,'../Par/SquareShelf2.par');
+md.damage.isdamage=1;
+md.damage.D=0.5*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md=setflowequation(md,'SSA','all');
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={7e-8,3e-8,3e-8,1e-11};
+field_values={...
+	   (md.results.StressbalanceSolution.Vx),...
+	   (md.results.StressbalanceSolution.Vy),...
+	   (md.results.StressbalanceSolution.Vel),...
+	   (md.results.StressbalanceSolution.Pressure),...
+	   };
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test274.py	(revision 18231)
@@ -0,0 +1,35 @@
+import numpy
+from model import model
+from triangle import triangle
+from setmask import setmask
+from parameterize import parameterize
+from setflowequation import setflowequation
+from EnumDefinitions import StressbalanceSolutionEnum
+from solve import solve
+from socket import gethostname as oshostname
+from matdamageice import matdamageice
+from meshprocessrifts import meshprocessrifts
+from generic import generic
+
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.)
+md=meshprocessrifts(md,'../Exp/Square.exp')
+md=setmask(md,'all','')
+md.materials=matdamageice()
+md=parameterize(md,'../Par/SquareShelf2.py')
+md.damage.isdamage=1
+md.damage.D=0.5*numpy.ones(md.mesh.numberofvertices)
+md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
+md=setflowequation(md,'SSA','all')
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure']
+field_tolerances=[7e-8,3e-8,3e-8,1e-11]
+field_values=[\
+	   md.results.StressbalanceSolution.Vx,\
+	   md.results.StressbalanceSolution.Vy,\
+	   md.results.StressbalanceSolution.Vel,\
+	   md.results.StressbalanceSolution.Pressure,\
+	   ]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.m	(revision 18231)
@@ -0,0 +1,28 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md.materials=matdamageice();
+md=parameterize(md,'../Par/SquareShelf.par');
+md.damage.isdamage=1;
+md.damage.D=0.1*ones(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+md.damage.law=1;
+
+md.damage.c1=1.e-11;
+md.damage.c2=0.4;
+md.damage.c3=1.e-3;
+md.damage.healing=0.4;
+md.damage.stress_threshold=1e5;
+md.damage.stabilization=1;
+
+md.damage.requested_outputs={'default','DamageF'};
+
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DamageEvolutionSolutionEnum());
+
+field_names={'D','F'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+		(md.results.DamageEvolutionSolution.DamageDbar),...
+		(md.results.DamageEvolutionSolution.DamageF),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test275.py	(revision 18231)
@@ -0,0 +1,41 @@
+import numpy
+from triangle import triangle
+from model import model
+from setmask import setmask
+from parameterize import parameterize
+from verbose import verbose
+from setflowequation import setflowequation
+from generic import generic
+from socket import gethostname as oshostname
+from solve import solve
+from EnumDefinitions import DamageEvolutionSolutionEnum
+from matdamageice import matdamageice
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md.materials=matdamageice()
+md=parameterize(md,'../Par/SquareShelf.py')
+md.damage.isdamage=1
+md.damage.D=0.1*numpy.ones(md.mesh.numberofvertices)
+md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
+md.damage.law=1
+
+md.damage.c1=1.e-11
+md.damage.c2=0.4
+md.damage.c3=1.e-3
+md.damage.healing=0.4
+md.damage.stress_threshold=1.e5
+md.damage.stabilization=1
+
+md.damage.requested_outputs=['default','DamageF']
+
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,DamageEvolutionSolutionEnum())
+
+field_names=['D','F']
+field_tolerances=[1.e-13,1.e-13]
+field_values=[\
+		md.results.DamageEvolutionSolution.DamageDbar,\
+		md.results.DamageEvolutionSolution.DamageF,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P2'}
+	md.flowequation.fe_SSA=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},1e-12,1e-13,1e-13,1e-13};
+	field_values={field_values{:},...
+		(md.results.StressbalanceSolution.Vx),...
+		(md.results.StressbalanceSolution.Vy),...
+		(md.results.StressbalanceSolution.Vel),...
+		(md.results.StressbalanceSolution.Pressure),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test280.py	(revision 18231)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P2']:
+	md.flowequation.fe_SSA=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-12,1e-13,1e-13,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4'}
+	md.flowequation.fe_HO=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},6e-08,5e-08,2e-08,5e-08,1e-13};
+	field_values={field_values{:},...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test285.py	(revision 18231)
@@ -0,0 +1,32 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.py');
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4']:
+	md.flowequation.fe_HO=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[6e-08,5e-08,2e-08,5e-08,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vz,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={5e-5,5e-5,8e-5,5e-5,1e-7};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test290.py	(revision 18231)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.py');
+md.extrude(3,2.)
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+#Fields and tolerances to track changes
+field_names     =['Vx', 'Vy', 'Vz', 'Vel','Pressure'];
+field_tolerances=[5e-5,5e-5,8e-5,5e-5,1e-7]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	];
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='OneLayerP4z';
+md.cluster=generic('name',oshostname(),'np',1);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={5e-5,5e-5,8e-5,5e-5,1e-7};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test291.py	(revision 18231)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(2,1.)
+md=setflowequation(md,'FS','all')
+md.flowequation.fe_FS='OneLayerP4z'
+md.cluster=generic('name',oshostname(),'np',1)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx', 'Vy', 'Vz', 'Vel','Pressure'];
+field_tolerances=[5e-5,5e-5,8e-5,5e-5,1e-7]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	];
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.basalforcings=linearbasalforcings(md.basalforcings);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test292.py	(revision 18231)
@@ -0,0 +1,47 @@
+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 *
+from generic import generic
+from linearbasalforcings import linearbasalforcings
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.basalforcings=linearbasalforcings(md.basalforcings)
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.m	(revision 18231)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.stressbalance.requested_outputs={'default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.DeviatoricStressxx),...
+	(md.results.StressbalanceSolution.DeviatoricStressyy),...
+	(md.results.StressbalanceSolution.DeviatoricStressxy),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3001.py	(revision 18231)
@@ -0,0 +1,33 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.stressbalance.requested_outputs=['default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy']
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure',\
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
+	1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.DeviatoricStressxx,\
+	md.results.StressbalanceSolution.DeviatoricStressyy,\
+	md.results.StressbalanceSolution.DeviatoricStressxy,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3002.py	(revision 18231)
@@ -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,2.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.autodiff.isautodiff=True
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.m	(revision 18231)
@@ -0,0 +1,30 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3003.py	(revision 18231)
@@ -0,0 +1,38 @@
+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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,3e-07,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3004.py	(revision 18231)
@@ -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,2.)
+md=setflowequation(md,'FS','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,3e-07,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3005.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3006.py	(revision 18231)
@@ -0,0 +1,28 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.m	(revision 18231)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,5,3.);
+md.cluster=generic('name',oshostname(),'np',1);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3007.py	(revision 18231)
@@ -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,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.extrude(5,3.)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',1);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md=solve(md,ThermalSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3008.py	(revision 18231)
@@ -0,0 +1,27 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.timestepping.time_step=0
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3009.py	(revision 18231)
@@ -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,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.autodiff.isautodiff=True
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test301.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.m	(revision 18231)
@@ -0,0 +1,43 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.transient.requested_outputs={'IceVolume'};
+
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3010.py	(revision 18231)
@@ -0,0 +1,51 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+md.transient.requested_outputs=['IceVolume']
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].IceVolume,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.m	(revision 18231)
@@ -0,0 +1,78 @@
+%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,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.masstransport.requested_outputs={'IceVolume'};
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+%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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,MasstransportSolutionEnum());
+V0=md.results.MasstransportSolution.IceVolume;
+
+%backward
+md=md2;
+md.autodiff.isautodiff=false;
+md.geometry.thickness(index)=h2;
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,MasstransportSolutionEnum());
+V2=md.results.MasstransportSolution.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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,MasstransportSolutionEnum());
+%retrieve directly
+dVdh_ad=md.results.MasstransportSolution.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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3015.py	(revision 18231)
@@ -0,0 +1,92 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.requested_outputs=['IceVolume']
+md.verbose=verbose('autodiff',True)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+
+#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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,MasstransportSolutionEnum())
+V0=md.results.MasstransportSolution.IceVolume
+
+#backward
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=False
+md.geometry.thickness[index]=h2
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,MasstransportSolutionEnum())
+V2=md.results.MasstransportSolution.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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,MasstransportSolutionEnum())
+#retrieve directly
+dVdh_ad=md.results.MasstransportSolution.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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.m	(revision 18231)
@@ -0,0 +1,35 @@
+%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,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+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-8,1e-8,1e-6};
+field_values={jac_forward,jac_reverse,jac_forward-jac_reverse};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3019.py	(revision 18231)
@@ -0,0 +1,47 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SIA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test302.py	(revision 18231)
@@ -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,'SIA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.m	(revision 18231)
@@ -0,0 +1,85 @@
+%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,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.transient.requested_outputs={'IceVolume','MaxVelEnum'};
+md.verbose=verbose('autodiff',true);
+md.stressbalance.restol=1e-4;
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+%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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+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-8,1e-7};
+field_values={dVdh_ad-dVdh_an,dMaxVdh_an-dMaxVdh_ad};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3020.py	(revision 18231)
@@ -0,0 +1,99 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.transient.requested_outputs=['IceVolume','MaxVel']
+md.verbose=verbose('autodiff',True)
+md.stressbalance.restol=0.000001
+md.toolkits.DefaultAnalysis=issmgslsolver()
+
+#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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3021.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3021.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3021.m	(revision 18231)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'StressTensorxx','StressTensoryy','StressTensorxy'};
+md.autodiff.isautodiff=false;
+md.toolkits.DefaultAnalysis=issmsolver();
+md.verbose=verbose('all');
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test303.py	(revision 18231)
@@ -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,'SIA','../Exp/SquareHalfRight.exp','fill','SSA')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test304.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,2.);
+md=setflowequation(md,'SIA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test305.py	(revision 18231)
@@ -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,'SIA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,2.);
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test306.py	(revision 18231)
@@ -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,'SIA','../Exp/SquareHalfRight.exp','fill','SSA')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,2e-10,2e-10,1e-10};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test307.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,2e-10,2e-10,1e-10]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test308.py	(revision 18231)
@@ -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,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.m	(revision 18231)
@@ -0,0 +1,13 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test309.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test310.py	(revision 18231)
@@ -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,'SSA','all')
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.m	(revision 18231)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.DeviatoricStressxx),...
+	(md.results.StressbalanceSolution.DeviatoricStressyy),...
+	(md.results.StressbalanceSolution.DeviatoricStressxy),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3101.py	(revision 18231)
@@ -0,0 +1,33 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.requested_outputs=['default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy']
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure',\
+	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
+	1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.DeviatoricStressxx,\
+	md.results.StressbalanceSolution.DeviatoricStressyy,\
+	md.results.StressbalanceSolution.DeviatoricStressxy,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3102.py	(revision 18231)
@@ -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,2.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.autodiff.isautodiff=True
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.m	(revision 18231)
@@ -0,0 +1,30 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.requested_outputs={'default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3103.py	(revision 18231)
@@ -0,0 +1,38 @@
+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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.requested_outputs=['default','StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,2.9e-07,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3104.py	(revision 18231)
@@ -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,2.)
+md=setflowequation(md,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,2e-07,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3105.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=meshconvert(md);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md.verbose=verbose('autodiff',true);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3106.py	(revision 18231)
@@ -0,0 +1,28 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.m	(revision 18231)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,5,3.);
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3107.py	(revision 18231)
@@ -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,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.extrude(5,3.)
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,ThermalSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3108.py	(revision 18231)
@@ -0,0 +1,27 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.timestepping.time_step=0
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3109.py	(revision 18231)
@@ -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,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.autodiff.isautodiff=True
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,5,0.5);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test311.py	(revision 18231)
@@ -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,'SSA','all')
+md.extrude(5,0.5)
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.m	(revision 18231)
@@ -0,0 +1,43 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs={'IceVolume'};
+
+md.autodiff.isautodiff=true;
+md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmmumpssolver();
+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).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3110.py	(revision 18231)
@@ -0,0 +1,51 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmmumpssolver()
+md.transient.requested_outputs=['IceVolume']
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].IceVolume,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.m	(revision 18231)
@@ -0,0 +1,25 @@
+%test reverse scalar driver 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,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.toolkits.DefaultAnalysis=issmgslsolver();
+
+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;
+
+%Fields and tolerances to track changes
+field_names     ={'Jac Reverse'};
+field_tolerances={1e-8};
+field_values={jac_reverse,};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3119.py	(revision 18231)
@@ -0,0 +1,37 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.toolkits.DefaultAnalysis=issmgslsolver()
+
+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
+
+#Fields and tolerances to track changes
+field_names     =['Jac Reverse']
+field_tolerances=[1e-13]
+field_values=[jac_reverse]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-8};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test312.py	(revision 18231)
@@ -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,'SSA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-8]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.m	(revision 18231)
@@ -0,0 +1,20 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('convergence',true,'solution',true);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test313.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.verbose=verbose('convergence',True,'solution',True)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.m	(revision 18231)
@@ -0,0 +1,33 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SIA','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,1.5e-13,1.5e-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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test314.py	(revision 18231)
@@ -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,'SIA','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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.m	(revision 18231)
@@ -0,0 +1,47 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,1.2);
+md=setflowequation(md,'SIA','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','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+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,2e-13,2e-13,2e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test315.py	(revision 18231)
@@ -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,'SIA','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','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',\
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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,2e-13,2e-13,2e-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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.m	(revision 18231)
@@ -0,0 +1,33 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test316.py	(revision 18231)
@@ -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,'SSA','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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.m	(revision 18231)
@@ -0,0 +1,47 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,5e-10,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test317.py	(revision 18231)
@@ -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,'HO','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','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',\
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,5e-10,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,1.);
+md=setflowequation(md,'SIA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13,4e-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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test318.py	(revision 18231)
@@ -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,'SIA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13,1.5e-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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.m	(revision 18231)
@@ -0,0 +1,33 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test319.py	(revision 18231)
@@ -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,'SSA','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=[103,501]
+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,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.FrictionCoefficient,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test320.py	(revision 18231)
@@ -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,'SSA','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=[103,501]
+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,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.FrictionCoefficient,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test321.py	(revision 18231)
@@ -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,'HO','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=[102,501]
+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,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.FrictionCoefficient,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[104  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
+field_tolerances={5e-05,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,5e-08,5e-08,5e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test322.py	(revision 18231)
@@ -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,'FS','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=[104,501]
+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,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy']
+field_tolerances=[5e-05,1e-08,1e-08,1e-09,5e-08,5e-08,5e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.FrictionCoefficient,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.m	(revision 18231)
@@ -0,0 +1,35 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=650.;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test323.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_adapt=1
+md.timestepping.final_time=650.
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.m	(revision 18231)
@@ -0,0 +1,49 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,1.2);
+md=setflowequation(md,'SIA','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','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
+	%'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+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,1.5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+	%1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+%	(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).Base),...
+%	(md.results.TransientSolution(3).Surface),...
+%	(md.results.TransientSolution(3).Thickness),...
+%	(md.results.TransientSolution(3).Temperature),...
+%	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test324.py	(revision 18231)
@@ -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,'SIA','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','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+	#'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+#	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].Base,\
+#	md.results.TransientSolution[2].Surface,\
+#	md.results.TransientSolution[2].Thickness,\
+#	md.results.TransientSolution[2].Temperature,\
+#	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=0.;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.thermal.isenthalpy = 1;
+md.thermal.isdynamicbasalspc = 1;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,5e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Enthalpy),...
+	(md.results.ThermalSolution.Waterfraction),...
+	(md.results.ThermalSolution.Temperature),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test325.py	(revision 18231)
@@ -0,0 +1,32 @@
+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,'SSA','all')
+md.timestepping.time_step=0.
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.thermal.isenthalpy = 1
+md.thermal.isdynamicbasalspc = 1
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Enthalpy','Waterfraction','Temperature']
+field_tolerances=[1e-13,5e-13,1e-13]
+field_values=[\
+	md.results.ThermalSolution.Enthalpy,\
+	md.results.ThermalSolution.Waterfraction,\
+	md.results.ThermalSolution.Temperature,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.m	(revision 18231)
@@ -0,0 +1,32 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy1','Waterfraction1','Temperature1',...
+	'Enthalpy2','Waterfraction2','Temperature2',...
+	'Enthalpy3','Waterfraction3','Temperature3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	(md.results.TransientSolution(3).Temperature),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test326.py	(revision 18231)
@@ -0,0 +1,42 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.m	(revision 18231)
@@ -0,0 +1,59 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.initialization.temperature(:)=272.;
+md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272.;
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=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-4,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test327.py	(revision 18231)
@@ -0,0 +1,67 @@
+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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.temperature[:]=272.
+md.thermal.spctemperature[numpy.nonzero(md.mesh.vertexonsurface)[0]]=272.
+md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=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-4,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].Base,\
+	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].Base,\
+	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].Base,\
+	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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.m	(revision 18231)
@@ -0,0 +1,42 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.surfaceforcings = SMBgradients();
+md.surfaceforcings.b_pos=-100. + 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.href=md.geometry.surface;
+md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
+md.transient.requested_outputs={'default','TotalSmb'};
+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,1.5e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1).TotalSmb),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).TotalSmb),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test328.py	(revision 18231)
@@ -0,0 +1,53 @@
+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,'SSA','all')
+md.surfaceforcings = SMBgradients();
+md.surfaceforcings.b_pos=-100. + 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.transient.requested_outputs=['default','TotalSmb']
+md.surfaceforcings.href=copy.deepcopy(md.geometry.surface).reshape(-1)
+md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
+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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].TotalSmb,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.m	(revision 18231)
@@ -0,0 +1,51 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.surfaceforcings = SMBgradients();
+md.surfaceforcings.b_pos=-100. + 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.href=md.geometry.surface;
+md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
+md.transient.requested_outputs={'default','TotalSmb'};
+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','TotalSmb2','Vx3','Vy3','Vz3','Vel3','Bed3','Surface3','Thickness3','Temperature3','SMB3','TotalSmb3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).TotalSmb),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test329.py	(revision 18231)
@@ -0,0 +1,62 @@
+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,'HO','all')
+md.surfaceforcings = SMBgradients();
+md.surfaceforcings.b_pos=-100. + 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.href=copy.deepcopy(md.geometry.surface).reshape(-1)
+md.surfaceforcings.smbref= 1000. - 0.001*md.mesh.x - 0.005*md.mesh.y;
+md.transient.requested_outputs=['default','TotalSmb']
+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','TotalSmb2','Vx3','Vy3','Vz3','Vel3','Bed3','Surface3','Thickness3','Temperature3','SMB3','TotalSmb3']
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3300.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3300.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test3300.m	(revision 18231)
@@ -0,0 +1,57 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+md.hydrology.isefficientlayer=1;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=400.0;
+md.hydrology.sediment_thickness=20.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=1.5e-4*ones(md.mesh.numberofvertices,1);
+
+md.initialization.epl_head=0.0*ones(md.mesh.numberofvertices,1);
+md.initialization.epl_thickness=1.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
+md.hydrology.mask_eplactive_node=0*ones(md.mesh.numberofvertices,1);
+
+md.hydrology.epl_conductivity=1.5e-2;
+md.hydrology.epl_initial_thickness=1.0;
+md.hydrology.epl_max_thickness=5.0;
+
+md.hydrology.transfer_flag=1;
+md.hydrology.leakage_factor=500;
+
+times=0:0.2:8.0;
+md.basalforcings.melting_rate=ones(md.mesh.numberofvertices+1,length(times));
+
+for i=1:length(times)
+	if(times(i)<1.2)
+		md.basalforcings.melting_rate(:,i)=1.0;
+	elseif(times(i)<6.0)
+		md.basalforcings.melting_rate(:,i)=-0.2;
+	else
+		md.basalforcings.melting_rate(:,i)=0.0;
+ end
+end	
+
+md.basalforcings.melting_rate(end,:)=times;
+
+
+md.timestepping.time_step=0.2;
+md.timestepping.final_time=8.0;
+
+md=solve(md,TransientSolutionEnum());
+
+field_names     ={'SedimentWaterHead5','EplWaterHead5','SedimentWaterHead40','EplWaterHead40'};
+field_tolerances={1e-13, 1e-13, 1e-13, 1e-13, 1e-13};
+field_values={md.results.TransientSolution(5).SedimentHead, ...
+							md.results.TransientSolution(5).EplHead,...
+							md.results.TransientSolution(40).SedimentHead,...
+							md.results.TransientSolution(40).EplHead};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test332.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test332.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test332.m	(revision 18231)
@@ -0,0 +1,30 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+md.hydrology.isefficientlayer=0;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=8000.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==0);
+md.hydrology.spcsediment_head(pos)=0.0;
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
+md.timestepping.time_step=0;
+md.timestepping.final_time=1.0;
+md=solve(md,HydrologySolutionEnum());
+
+%Fields and tolerances to track changes
+%you can also compare with an analitic solution, but it is exact
+%only if no limits are applied
+%analitic=(md.mesh.y.^2-2*md.mesh.y*1.0e6)*(-2.0/(2*md.constants.yts*md.hydrology.sediment_transmitivity))
+field_names     ={'SedimentWaterHead','SedimentHeadResidual'};
+field_tolerances={1e-13, 3e-10};
+field_values={md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test333.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test333.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test333.m	(revision 18231)
@@ -0,0 +1,61 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+md.hydrology.isefficientlayer=1;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=800.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
+
+md.initialization.epl_head=0.0*ones(md.mesh.numberofvertices,1);
+md.initialization.epl_thickness=1.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
+md.hydrology.mask_eplactive_node=0*ones(md.mesh.numberofvertices,1);
+md.hydrology.epl_conductivity=30;
+md.hydrology.epl_initial_thickness=1;
+md.hydrology.epl_max_thickness=1;
+md.timestepping.time_step=0.2;
+md.timestepping.final_time=2.0;
+
+%md.verbose.solution=1;
+
+md=solve(md,TransientSolutionEnum());
+
+%store=md.constants.g*md.hydrology.sediment_porosity*md.materials.rho_freshwater*((md.hydrology.sediment_compressibility/md.hydrology.sediment_porosity)+md.hydrology.water_compressibility);
+%sedstore=20.0*store;
+%for i=1:10
+%diff=(mean(md.results.HydrologySolution(i).EplHead)*store+ ...
+%			mean(md.results.HydrologySolution(i).SedimentHead)*sedstore-0.4*i)
+%end
+
+%Fields and tolerances to track changes
+field_names     ={'SedimentWaterHead1','EplWaterHead1','SedimentHeadResidual1',...
+						'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',...
+						'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',...
+						'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9'};
+field_tolerances={...
+	1e-13, 1e-13, 1e-13,...
+	1e-13, 1e-13, 1e-13,...
+	1e-13, 5e-12, 8e-12,...
+	1e-13, 5e-12, 1e-11};
+field_values={md.results.TransientSolution(1).SedimentHead, ...
+							md.results.TransientSolution(1).EplHead,...
+							md.results.TransientSolution(1).SedimentHeadResidual,...
+							md.results.TransientSolution(4).SedimentHead,...
+							md.results.TransientSolution(4).EplHead,...
+							md.results.TransientSolution(4).SedimentHeadResidual, ...
+							md.results.TransientSolution(5).SedimentHead,...
+							md.results.TransientSolution(5).EplHead,...
+							md.results.TransientSolution(5).SedimentHeadResidual, ...
+							md.results.TransientSolution(9).SedimentHead,...
+							md.results.TransientSolution(9).EplHead,...
+							md.results.TransientSolution(9).SedimentHeadResidual};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test334.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test334.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test334.m	(revision 18231)
@@ -0,0 +1,32 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+md.hydrology.isefficientlayer=0;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=8000.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==0);
+md.hydrology.spcsediment_head(pos)=0.0;
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity= 3.0*ones(md.mesh.numberofvertices,1);
+md.timestepping.time_step=0;
+md.timestepping.final_time=1.0;
+%md.verbose=verbose('1111111');
+md=extrude(md,3,1.1);
+md=solve(md,HydrologySolutionEnum());
+
+%Fields and tolerances to track changes
+%you can also compare with an analitic solution, but it is exact
+%only if no limits are applied
+%analitic=(md.mesh.y.^2-2*md.mesh.y*1.0e6)*(-2.0/(2*md.constants.yts*md.hydrology.sediment_transmitivity))
+field_names     ={'SedimentWaterHead','SedimentHeadResidual'};
+field_tolerances={1e-13, 3e-10};
+field_values={md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test335.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test335.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test335.m	(revision 18231)
@@ -0,0 +1,67 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md.transient=deactivateall(md.transient);
+md.transient.ishydrology=1;
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology=initialize(md.hydrology,md);
+md.hydrology.isefficientlayer=1;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=800.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
+
+md.initialization.epl_head=0.0*ones(md.mesh.numberofvertices,1);
+md.initialization.epl_thickness=1.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
+md.hydrology.mask_eplactive_node=0*ones(md.mesh.numberofvertices,1);
+md.hydrology.epl_conductivity=30;
+md.hydrology.epl_initial_thickness=1;
+md.hydrology.epl_max_thickness=1;
+md.timestepping.time_step=0.2;
+md.timestepping.final_time=2.0;
+
+%md.verbose.solution=1;
+md=extrude(md,3,1.1);
+md=solve(md,TransientSolutionEnum());
+
+%store=md.constants.g*md.hydrology.sediment_porosity* ...
+%			md.materials.rho_freshwater*((md.hydrology.sediment_compressibility/md.hydrology.sediment_porosity)+md.hydrology.water_compressibility)
+
+%sed=ones(1,size(md.results.HydrologySolution,2));
+%epl=ones(1,size(md.results.HydrologySolution,2));
+%res=ones(1,size(md.results.HydrologySolution,2));
+%input=ones(1,size(md.results.HydrologySolution,2));
+%for i= 1:size(md.results.HydrologySolution,2)
+%	sed(i)=mean(md.results.HydrologySolution(i).SedimentHead);
+%	res(i)=mean(md.results.HydrologySolution(i).SedimentHeadResidual);
+%	epl(i)=mean(md.results.HydrologySolution(i).EplHead);
+%	input(i)=2.0*(i*0.2);
+%end
+
+%Fields and tolerances to track changes
+field_names     ={'SedimentWaterHead1','EplWaterHead1','SedimentHeadResidual1',...
+						'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',...
+						'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',...
+						'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9'};
+field_tolerances={1e-13, 1e-13, 1e-13,...
+						1e-13, 1e-13, 1e-13,...
+						1e-13, 5e-12, 9e-12,...
+						1e-13, 5e-12, 1e-11};
+field_values={md.results.TransientSolution(1).SedimentHead, ...
+							md.results.TransientSolution(1).EplHead,...
+							md.results.TransientSolution(1).SedimentHeadResidual,...
+							md.results.TransientSolution(4).SedimentHead,...
+							md.results.TransientSolution(4).EplHead,...
+							md.results.TransientSolution(4).SedimentHeadResidual, ...
+							md.results.TransientSolution(5).SedimentHead,...
+							md.results.TransientSolution(5).EplHead,...
+							md.results.TransientSolution(5).SedimentHeadResidual, ...
+							md.results.TransientSolution(9).SedimentHead,...
+							md.results.TransientSolution(9).EplHead,...
+							md.results.TransientSolution(9).SedimentHeadResidual};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.m	(revision 18231)
@@ -0,0 +1,65 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=[smb*2; [1.5 3.]];
+md.surfaceforcings.runoff=[smb/2; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test336.py	(revision 18231)
@@ -0,0 +1,75 @@
+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,'SSA','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=SMBcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb*2, [1.5,3.]));
+md.surfaceforcings.runoff=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.transient.isthermal=False
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.m	(revision 18231)
@@ -0,0 +1,67 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=[smb*2; [1.5 3.]];
+md.surfaceforcings.runoff=[smb/2; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [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={...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test337.py	(revision 18231)
@@ -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',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','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=SMBcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb*2, [1.5,3.]));
+md.surfaceforcings.runoff=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.transient.isthermal=False
+
+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=[\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.m	(revision 18231)
@@ -0,0 +1,66 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=[smb; [1.5 3.]];
+md.surfaceforcings.melt=[smb/2; [1.5 3.]];
+md.surfaceforcings.refreeze=[smb; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test338.py	(revision 18231)
@@ -0,0 +1,76 @@
+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,'SSA','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=SMBmeltcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.melt=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.refreeze=numpy.vstack((smb, [1.5,3.]));
+md.transient.isthermal=False
+
+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].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.m	(revision 18231)
@@ -0,0 +1,68 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=[smb; [1.5 3.]];
+md.surfaceforcings.melt=[smb/2; [1.5 3.]];
+md.surfaceforcings.refreeze=[smb; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [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-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(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test339.py	(revision 18231)
@@ -0,0 +1,78 @@
+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.extrude(3,1.)
+md=setflowequation(md,'HO','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=SMBmeltcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.melt=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.refreeze=numpy.vstack((smb, [1.5,3.]));
+md.transient.isthermal=False
+
+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-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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test401.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test402.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test403.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[2e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={5e-07,5e-07,2e-06,1e-06,1e-07};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test404.py	(revision 18231)
@@ -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,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[5e-07,4e-07,2e-06,1e-06,1e-07]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={5e-05,5e-05,5e-05,5e-05,1e-05};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test405.py	(revision 18231)
@@ -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,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[5e-05,5e-05,5e-05,5e-05,1e-05]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-5};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test406.py	(revision 18231)
@@ -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,'HO','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-5]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test407.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.m	(revision 18231)
@@ -0,0 +1,33 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test408.py	(revision 18231)
@@ -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,'SSA','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].Base,\
+	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].Base,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.m	(revision 18231)
@@ -0,0 +1,48 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','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','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
+field_tolerances={...
+	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,...
+	1e-03,1e-03,1e-02,1e-03,1e-02,1e-04,1e-01,1e-03,1e-01,1e-01,...
+	1e-02,1e-02,1e-01,1e-02,1e-01,1e-04,1e-04,1e-04,1e-04,1e-01};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test409.py	(revision 18231)
@@ -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,'SSA','../Exp/SquareHalfRight.exp','fill','HO','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','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Temperature,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-08,3e-10,1e-13,3e-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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test410.py	(revision 18231)
@@ -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,'SSA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-09,1e-09,1e-08,1e-09,1e-13,3e-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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.m	(revision 18231)
@@ -0,0 +1,22 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={2e-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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test411.py	(revision 18231)
@@ -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,'HO','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','BasalforcingsGroundediceMeltingRate']
+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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test412.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test412.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test412.m	(revision 18231)
@@ -0,0 +1,44 @@
+md=triangle(model(),'../Exp/Square.exp',300000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.stressbalance.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
+
+%Fields and tolerances to track changes
+md.qmu.results=md.results.dakota;
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test413.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test413.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test413.m	(revision 18231)
@@ -0,0 +1,45 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative!
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
+
+%Fields and tolerances to track changes
+md.qmu.results=md.results.dakota;
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test414.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test414.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test414.m	(revision 18231)
@@ -0,0 +1,70 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.stressbalance.spcvx=zeros(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=zeros(md.mesh.numberofvertices,1);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+
+%solve
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
+md.qmu.results=md.results.dakota;
+
+%Fields and tolerances to track changes
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the moments, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.moments=[];
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'moments'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.moments,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.m	(revision 18231)
@@ -0,0 +1,38 @@
+md=triangle(model(),'../Exp/Square.exp',170000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0.;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-09,1e-9,2e-10,1e-13,1e-09,1e-09,1e-09,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.BasalforcingsGroundediceMeltingRate)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test415.py	(revision 18231)
@@ -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,'SSA','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=[103,501]
+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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-9,1e-9,2e-10,1e-13,1e-09,1e-09,1e-09,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.BasalforcingsGroundediceMeltingRate
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.m	(revision 18231)
@@ -0,0 +1,38 @@
+md=triangle(model(),'../Exp/Square.exp',170000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0.;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
+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.BasalforcingsGroundediceMeltingRate)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test416.py	(revision 18231)
@@ -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,'HO','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=[102,501]
+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','BasalforcingsGroundediceMeltingRate']
+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.BasalforcingsGroundediceMeltingRate
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test417.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test417.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test417.m	(revision 18231)
@@ -0,0 +1,73 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.stressbalance.spcvx(:)=0;
+md.stressbalance.spcvy(:)=1;
+md.stressbalance.spcvz(:)=0;
+
+%Dakota options
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+
+%%  nond_sampling study
+
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+'seed',1234,...
+'samples',20,...
+'sample_type','lhs');
+
+%%  a variety of parameters
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
+
+%Fields and tolerances to track changes
+md.qmu.results=md.results.dakota;
+
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the montecarlo field, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.montecarlo=[];
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'montecarlo'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.montecarlo,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test418.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test418.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test418.m	(revision 18231)
@@ -0,0 +1,21 @@
+%test partitioning, and partition averaging
+md=triangle(model(),'../Exp/Square.exp',30000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%partitioning
+md.qmu.numberofpartitions=100;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+vector=(1:1:md.mesh.numberofvertices)';
+vector_on_partition=AreaAverageOntoPartition(md,vector);
+vector_on_nodes=vector_on_partition(md.qmu.partition+1);
+
+field_names     ={'vector_on_nodes'};
+field_tolerances={1e-11};
+field_values={...
+         vector_on_nodes,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test419.py	(revision 18231)
@@ -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,'SSA','../Exp/SquareHalfRight.exp','fill','HO')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[2e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test420.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test420.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test420.m	(revision 18231)
@@ -0,0 +1,49 @@
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%partitioning
+md.qmu.numberofpartitions=10;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('scaled_Thickness',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='stressbalance';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative! 
+md.stressbalance.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
+md.qmu.results=md.results.dakota;
+
+%test on thickness
+h=zeros(md.qmu.numberofpartitions,1);
+for i=1:md.qmu.numberofpartitions,
+	h(i)=md.qmu.results.dresp_out(i).mean;
+end
+
+%project onto grid
+thickness=h(md.qmu.partition+1);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-10};
+field_values={thickness};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={6e-07,6e-07,2e-05,6e-07,6e-07};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test421.py	(revision 18231)
@@ -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,'FS','../Exp/SquareHalfRight.exp','fill','HO')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[6e-07,6e-07,2e-05,6e-07,6e-07]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.m	(revision 18231)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
+md.cluster=generic('name',oshostname(),'np',3);
+md.stressbalance.reltol=0.4;
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={3e-07,2e-07,2e-06,2e-07,5e-07};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test422.py	(revision 18231)
@@ -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,'FS','../Exp/SquareHalfRight.exp','fill','SSA')
+md.cluster=generic('name',oshostname(),'np',3)
+md.stressbalance.reltol=0.4
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[3e-07,2e-07,2e-06,2e-07,5e-07]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.m	(revision 18231)
@@ -0,0 +1,50 @@
+radius=1.e6;
+shelfextent=2.e5;
+
+md=roundmesh(model(),radius,50000.);
+%fix center node to 0,0
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad==min(rad));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3.;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3.;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+flags(pos)=1;
+md=setmask(md,flags,''); 
+md=parameterize(md,'../Par/RoundSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.transient.isthermal=0;
+md.transient.ismasstransport=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+
+%test different grounding line dynamics.
+md.groundingline.migration='AggressiveMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskGroundediceLevelset);
+vel_agressive=(md.results.TransientSolution.Vel);
+
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskGroundediceLevelset);
+vel_soft=(md.results.TransientSolution.Vel);
+
+md.mask.groundedice_levelset=md.geometry.thickness + md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+md.groundingline.migration='SubelementMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement=(md.results.TransientSolution.MaskGroundediceLevelset);
+vel_subelement=(md.results.TransientSolution.Vel);
+
+md.groundingline.migration='SubelementMigration2';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement2=(md.results.TransientSolution.MaskGroundediceLevelset);
+vel_subelement2=(md.results.TransientSolution.Vel);
+
+%Fields and tolerances to track changes
+field_names     ={'ElementOnIceShelfAggressive','VelAggressive','ElementOnIceShelfSoft','VelSoft','ElementOnIceShelfSubelement','VelSubelement','ElementOnIceShelfSubelement2','VelSubelement2'};
+field_tolerances={1e-13,2e-12,1e-13,2e-12,1e-13,3e-12,1e-13,2e-12};
+field_values={element_on_iceshelf_agressive,vel_agressive,element_on_iceshelf_soft,vel_soft,element_on_iceshelf_subelement,vel_subelement,element_on_iceshelf_subelement2,vel_subelement2};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test423.py	(revision 18231)
@@ -0,0 +1,61 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.transient.isthermal=False
+md.transient.ismasstransport=False
+md.transient.isstressbalance=True
+md.transient.isgroundingline=True
+
+#test different grounding line dynamics.
+md.groundingline.migration='AggressiveMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskGroundediceLevelset
+vel_agressive=md.results.TransientSolution[0].Vel
+
+md.groundingline.migration='SoftMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_soft=md.results.TransientSolution[0].MaskGroundediceLevelset
+vel_soft=md.results.TransientSolution[0].Vel
+
+md.mask.groundedice_levelset=md.geometry.thickness + md.materials.rho_water/md.materials.rho_ice*md.geometry.bed
+md.groundingline.migration='SubelementMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement=md.results.TransientSolution[0].MaskGroundediceLevelset
+vel_subelement=md.results.TransientSolution[0].Vel
+
+md.groundingline.migration='SubelementMigration2'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement2=md.results.TransientSolution[0].MaskGroundediceLevelset
+vel_subelement2=md.results.TransientSolution[0].Vel
+
+#Fields and tolerances to track changes
+field_names     =['ElementOnIceShelfAggressive','VelAggressive','ElementOnIceShelfSoft','VelSoft','ElementOnIceShelfSubelement','VelSubelement','ElementOnIceShelfSubelement2','VelSubelement2']
+field_tolerances=[1e-13,2e-13,1e-13,2e-13,1e-13,2e-13,1e-13,2e-13]
+field_values=[element_on_iceshelf_agressive,vel_agressive,element_on_iceshelf_soft,vel_soft,element_on_iceshelf_subelement,vel_subelement,element_on_iceshelf_subelement2,vel_subelement2]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.m	(revision 18231)
@@ -0,0 +1,46 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.initialization.vx(:)=0.;
+md.initialization.vy(:)=0.;
+md.geometry.base=-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.bed =-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.thickness(:)=1000.;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100.;
+md.transient.isstressbalance=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AggressiveMigration';
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
+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};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).IceVolume),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test424.py	(revision 18231)
@@ -0,0 +1,56 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'SSA','all')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.base=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bed =-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1000.
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md.surfaceforcings.mass_balance[:]=100.
+md.transient.isstressbalance=False
+md.transient.isgroundingline=True
+md.groundingline.migration='AggressiveMigration'
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',\
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',\
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3']
+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]
+field_values=[\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeAboveFloatation,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].IceVolume,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.m	(revision 18231)
@@ -0,0 +1,39 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.initialization.vx(:)=0.;
+md.initialization.vy(:)=0.;
+md.geometry.base=-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.bed =-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.thickness(:)=1300.;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=-150.;
+md.transient.isstressbalance=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test425.py	(revision 18231)
@@ -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,'SSA','all')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.base=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bed =-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1300.
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md.surfaceforcings.mass_balance[:]=-150.
+md.transient.isstressbalance=False
+md.transient.isgroundingline=True
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.m	(revision 18231)
@@ -0,0 +1,47 @@
+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.geometry.base=-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.bed =-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.thickness(:)=1000.;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100.;
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.transient.isstressbalance=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AggressiveMigration';
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
+md.cluster=generic('name',oshostname(),'np',3);
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-11,1e-10,1e-11,3e-11,2e-12,5e-12,...
+	1e-10,1e-10,1e-10,5e-11,2e-12,5e-12};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).IceVolume),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test426.py	(revision 18231)
@@ -0,0 +1,59 @@
+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.base=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bed =-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1000.
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md.surfaceforcings.mass_balance[:]=100.
+md.extrude(3,1.);
+md=setflowequation(md,'SSA','all');
+md.transient.isstressbalance=False
+md.transient.isgroundingline=True
+md.groundingline.migration='AggressiveMigration'
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
+md.cluster=generic('name',oshostname(),'np',3)
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',\
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',\
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3',]
+
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+	1e-11,1e-10,1e-11,3e-11,2e-12,5e-12,\
+	1e-10,1e-10,1e-10,5e-11,2e-12,5e-12]
+
+field_values=[\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeAboveFloatation,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].IceVolume,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.m	(revision 18231)
@@ -0,0 +1,40 @@
+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.geometry.base=-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.bed =-700.-abs(md.mesh.y-500000.)/1000.;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+md=extrude(md,3,1.);
+
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isstressbalance=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,...
+	5e-12,3e-12,7e-12,2e-11,...
+	1e-10,5e-11,1e-10,7e-10};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test427.py	(revision 18231)
@@ -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.base=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bed =-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1300
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md=setflowequation(md,'SSA','all')
+md.extrude(3,1.)
+
+md.surfaceforcings.mass_balance[:]=-150
+md.transient.isstressbalance=False
+md.transient.isgroundingline=True
+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,\
+	5e-12,3e-12,7e-12,2e-11,\
+	1e-10,5e-11,1e-10,7e-10]
+field_values=[\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.stressbalance.isnewton=1;
+md.stressbalance.restol=0.0001;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test428.py	(revision 18231)
@@ -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,'SSA','all')
+md.stressbalance.isnewton=1
+md.stressbalance.restol=0.0001
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#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.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.m	(revision 18231)
@@ -0,0 +1,20 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'HO','all');
+md.stressbalance.isnewton=1;
+md.stressbalance.restol=0.0001;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={2e-06,1e-06,1e-06,1e-06,1e-06};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test429.py	(revision 18231)
@@ -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,'HO','all')
+md.stressbalance.isnewton=1
+md.stressbalance.restol=0.0001
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[2e-06,2e-06,1e-06,2e-06,1e-06]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.m	(revision 18231)
@@ -0,0 +1,26 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0.;
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
+field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.Waterfraction),...
+	(md.results.SteadystateSolution.Enthalpy),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test431.py	(revision 18231)
@@ -0,0 +1,36 @@
+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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_step=0.
+md.thermal.isenthalpy=1
+md.thermal.isdynamicbasalspc=1
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.m	(revision 18231)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0.;
+md.thermal.isenthalpy=1;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.Waterfraction),...
+	(md.results.SteadystateSolution.Enthalpy),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test432.py	(revision 18231)
@@ -0,0 +1,35 @@
+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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_step=0.
+md.thermal.isenthalpy=1
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md=solve(md,SteadystateSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.SteadystateSolution.Vx,\
+	md.results.SteadystateSolution.Vy,\
+	md.results.SteadystateSolution.Vz,\
+	md.results.SteadystateSolution.Vel,\
+	md.results.SteadystateSolution.Pressure,\
+	md.results.SteadystateSolution.Temperature,\
+	md.results.SteadystateSolution.Waterfraction,\
+	md.results.SteadystateSolution.Enthalpy,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.m	(revision 18231)
@@ -0,0 +1,46 @@
+radius=1.e6;
+shelfextent=2.e5;
+
+md=roundmesh(model(),radius,50000.);
+%fix center node to 0,0
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad==min(rad));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3.;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3.;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+flags(pos)=1;
+md=setmask(md,flags,''); 
+md=parameterize(md,'../Par/RoundSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md=extrude(md,3,1);
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.transient.isthermal=0;
+md.transient.ismasstransport=0;
+md.transient.isstressbalance=0;
+md.transient.isgroundingline=1;
+
+%test different grounding line dynamics.
+md.groundingline.migration='AggressiveMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskGroundediceLevelset);
+
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskGroundediceLevelset);
+
+md.groundingline.migration='SubelementMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement=(md.results.TransientSolution.MaskGroundediceLevelset);
+
+md.groundingline.migration='SubelementMigration2';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement2=(md.results.TransientSolution.MaskGroundediceLevelset);
+
+%Fields and tolerances to track changes
+field_names     ={'ElementOnIceShelfAggressive','ElementOnIceShelfSoft','ElementOnIceShelfSubelement','ElementOnIceShelfSubelement'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft,element_on_iceshelf_subelement,element_on_iceshelf_subelement2};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test433.py	(revision 18231)
@@ -0,0 +1,53 @@
+import numpy
+from model import *
+from roundmesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+radius=1.e6
+shelfextent=2.e5
+
+md=roundmesh(model(),radius,50000.)
+#fix center node to 0,0
+rad=numpy.sqrt(md.mesh.x**2+md.mesh.y**2)
+pos=numpy.argmin(rad)
+md.mesh.x[pos]=0.
+md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
+xelem=numpy.mean(md.mesh.x[md.mesh.elements.astype(int)-1],axis=1)
+yelem=numpy.mean(md.mesh.y[md.mesh.elements.astype(int)-1],axis=1)
+rad=numpy.sqrt(xelem**2+yelem**2)
+flags=numpy.zeros(md.mesh.numberofelements)
+pos=numpy.nonzero(rad>=(radius-shelfextent))
+flags[pos]=1
+md=setmask(md,flags,'') 
+md=parameterize(md,'../Par/RoundSheetShelf.py')
+md=setflowequation(md,'SSA','all')
+md.extrude(3,1.)
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.transient.isthermal=False
+md.transient.ismasstransport=False
+md.transient.isstressbalance=False
+md.transient.isgroundingline=True
+
+#test different grounding line dynamics.
+md.groundingline.migration='AggressiveMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskGroundediceLevelset
+
+md.groundingline.migration='SoftMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_soft=md.results.TransientSolution[0].MaskGroundediceLevelset
+
+md.groundingline.migration='SubelementMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement=md.results.TransientSolution[0].MaskGroundediceLevelset
+
+#Fields and tolerances to track changes
+field_names     =['ElementOnIceShelfAggressive','ElementOnIceShelfSoft','ElementOnIceShelfSubelement']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[element_on_iceshelf_agressive,element_on_iceshelf_soft,element_on_iceshelf_subelement]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1.);
+md=setflowequation(md,'L1L2','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-06,1e-06,2e-07,1e-06,1e-07};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test434.py	(revision 18231)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(4,1.)
+md=setflowequation(md,'L1L2','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-06,1e-06,1e-06,1e-06,1e-07]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test435.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test435.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test435.m	(revision 18231)
@@ -0,0 +1,78 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=extrude(md,4,1.);
+md=setflowequation(md,'HO','all');
+
+%Boundary conditions:
+md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(md.mesh.x==max(md.mesh.x)))=0;
+md.stressbalance.spcvx(:)=NaN;
+md.stressbalance.spcvy(:)=NaN;
+md.stressbalance.spcvz(:)=NaN;
+pos=find((md.mesh.y<1000000.1 & md.mesh.y>999999.9) | (md.mesh.y<0.1 & md.mesh.y>-0.1));
+md.stressbalance.spcvy(pos)=0;
+pos2=find(md.mesh.x<0.1 & md.mesh.x>-0.1);
+md.stressbalance.spcvx(pos2)=0;
+md.stressbalance.spcvy(pos2)=0;
+
+md.materials.rheology_B=1/((10^-25)^(1/3))*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_law='None';
+md.friction.coefficient(:)=sqrt(10^7)*ones(md.mesh.numberofvertices,1);
+md.friction.p=3*ones(md.mesh.numberofelements,1);
+md.surfaceforcings.mass_balance(:)=1;
+md.basalforcings.groundedice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=0;
+md.transient.isthermal=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismasstransport=1;
+md.groundingline.migration='SubelementMigration';
+md.timestepping.final_time=30;
+md.timestepping.time_step=10;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3'};
+field_tolerances={2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,6e-10,1e-13,...
+	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-09,1e-10,...
+	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-09,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P2'}
+	md.flowequation.fe_SSA=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},1e-12,1e-13,1e-13,1e-13};
+	field_values={field_values{:},...
+		(md.results.StressbalanceSolution.Vx),...
+		(md.results.StressbalanceSolution.Vy),...
+		(md.results.StressbalanceSolution.Vel),...
+		(md.results.StressbalanceSolution.Pressure),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test450.py	(revision 18231)
@@ -0,0 +1,30 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P2']:
+	md.flowequation.fe_SSA=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-12,1e-13,1e-13,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4'}
+	md.flowequation.fe_HO=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},5e-08,4e-08,1e-08,4e-08,3e-13};
+	field_values={field_values{:},...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test455.py	(revision 18231)
@@ -0,0 +1,32 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4']:
+	md.flowequation.fe_HO=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[5e-08,4e-08,1e-08,4e-08,3e-13]
+	field_values=field_values+[\
+			md.results.StressbalanceSolution.Vx,\
+			md.results.StressbalanceSolution.Vy,\
+			md.results.StressbalanceSolution.Vz,\
+			md.results.StressbalanceSolution.Vel,\
+			md.results.StressbalanceSolution.Pressure,\
+			]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-12,2e-12,2e-12,1e-13};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test501.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vel','Pressure']
+field_tolerances=[1e-12,2e-12,2e-12,1e-13]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,0.9);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test502.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-08,1e-08,1e-08,1e-08,1e-08]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,0.9);
+md=setflowequation(md,'FS','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test503.py	(revision 18231)
@@ -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,'FS','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.m	(revision 18231)
@@ -0,0 +1,26 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,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-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,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).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test504.py	(revision 18231)
@@ -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,'SSA','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-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,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].Base,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.m	(revision 18231)
@@ -0,0 +1,35 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
+field_tolerances={1e-12,1e-12,3e-10,1e-12,1e-13,1e-11,5e-12,9e-12,1e-13,5e-9,...
+						5e-11,5e-11,1e-10,2e-11,7e-12,1e-11,1e-11,5e-12,1e-11,2e-8};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test505.py	(revision 18231)
@@ -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,'SSA','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','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+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,2e-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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.m	(revision 18231)
@@ -0,0 +1,35 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,...
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test506.py	(revision 18231)
@@ -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,'HO','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','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,\
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','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','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
+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,3e-06,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test507.py	(revision 18231)
@@ -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,'FS','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','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+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].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	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].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Pig.exp',35000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.1);
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={5e-08,3e-08,5e-08,3e-08,1e-09,2e-07,8e-07};
+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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test508.py	(revision 18231)
@@ -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',35000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(3,1.1)
+md=setflowequation(md,'SSA','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[5e-08,1.6e-08,5e-08,1.6e-08,1e-09,6e-08,5e-07]
+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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0.;
+md.thermal.penalty_threshold=7;
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
+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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test509.py	(revision 18231)
@@ -0,0 +1,31 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_step=0.
+md.thermal.penalty_threshold=7
+md=solve(md,SteadystateSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
+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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.m	(revision 18231)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','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','BasalforcingsGroundediceMeltingRate'};
+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.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test510.py	(revision 18231)
@@ -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,'FS','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','BasalforcingsGroundediceMeltingRate']
+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.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.m	(revision 18231)
@@ -0,0 +1,39 @@
+md=triangle(model(),'../Exp/Pig.exp',11000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+
+%impose hydrostatic equilibrium (required by Stokes)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=extrude(md,3,1.);
+md=setflowequation(md,'FS','all');
+md=extract(md,md.mask.groundedice_levelset<0.);
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10.^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2.*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101;
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10.^8*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2.*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',1);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','MaterialsRheologyB','Pressure','Vel','Vx','Vy'};
+field_tolerances={5e-11,5e-11,5e-11,1e-09,1e-11,5e-11,1e-11};
+field_values={...
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test511.py	(revision 18231)
@@ -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',11000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+
+#impose hydrostatic equilibrium (required by Stokes)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+md.extrude(3,1.)
+md=setflowequation(md,'FS','all')
+md=md.extract(md.mask.groundedice_levelset<0.)
+
+#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]
+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,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Gradient','Misfits','MaterialsRheologyB','Pressure','Vel','Vx','Vy']
+field_tolerances=[5e-11,5e-11,5e-11,1e-09,1e-11,5e-11,1e-11]
+field_values=[\
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.m	(revision 18231)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%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.StressbalanceSolution.Gradient1),...
+	md.results.StressbalanceSolution.J,...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test512.py	(revision 18231)
@@ -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,'HO','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=[103,501]
+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,StressbalanceSolutionEnum())
+
+# 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.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.FrictionCoefficient,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.m	(revision 18231)
@@ -0,0 +1,39 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.gradient_scaling=3.*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2.*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=0.;
+
+md.thermal.penalty_lock=5;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-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.BasalforcingsGroundediceMeltingRate)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test513.py	(revision 18231)
@@ -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,'SSA','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=[103,501]
+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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-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.BasalforcingsGroundediceMeltingRate
+]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.m	(revision 18231)
@@ -0,0 +1,48 @@
+%Simple mesh 1
+hVertices=10000.*ones(27,1);
+hVertices(1:5)=1000.;
+md=bamg(model(),'domain','../Exp/Pig.exp','hmax',20000.,'hVertices',hVertices,'gradation',3.,'geometricalmetric',1);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%Simple mesh 2
+md=bamg(model(),'domain','../Exp/Pig.exp','hmax',10000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%refine existing mesh 1
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vy_obs,'node');
+metric=ComputeMetric(hessian,2./9.,1.,1000.,25.*10.^3,[]);
+md.miscellaneous.dummy=metric;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1);
+x3=md2.mesh.x;
+y3=md2.mesh.y;
+
+%refine existing mesh 2
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.);
+x4=md2.mesh.x;
+y4=md2.mesh.y;
+
+%refine existing mesh 3
+hVertices=NaN*ones(md.mesh.numberofvertices,1);
+hVertices(find(md.mesh.vertexonboundary))=500;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.,'hVertices',hVertices);
+x5=md2.mesh.x;
+y5=md2.mesh.y;
+
+%refine existing mesh 4
+md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',0,'err',1.);
+x6=md2.mesh.x;
+y6=md2.mesh.y;
+
+%refine existing mesh 5
+md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',1,'err',[10. 100.]); 
+x7=md2.mesh.x;
+y7=md2.mesh.y;
+
+%Fields and tolerances to track changes
+field_names      = {'x1' ,'y1' ,'x2' ,'y2' ,'x3' ,'y3' ,'x4' ,'y4' ,'x5' ,'y5' ,'x6' ,'y6' ,'x7' ,'y7' };
+field_tolerances = {2e-10,7e-10,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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test514.py	(revision 18231)
@@ -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 = [2e-10,7e-10,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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.m	(revision 18231)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.thermal.stabilization=2;
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Temperature2','BasalforcingsGroundediceMeltingRate2'};
+field_tolerances={1e-13,1e-8,1e-13,3e-8};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test515.py	(revision 18231)
@@ -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,'HO','all')
+md.thermal.stabilization=2
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
+md.transient.isthermal=True
+md.transient.isgroundingline=False
+md=solve(md,TransientSolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Temperature2','BasalforcingsGroundediceMeltingRate2']
+field_tolerances=[1e-13,1e-8,1e-13,2e-8]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.m	(revision 18231)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','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','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-11,1e-11};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test516.py	(revision 18231)
@@ -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,'HO','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','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-11,1e-11]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancevelocitySolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
+	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.Vel),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test530.py	(revision 18231)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancevelocitySolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[\
+		md.results.BalancevelocitySolution.SurfaceSlopeX,\
+		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.Vel,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.m	(revision 18231)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancevelocitySolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
+	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.Vel),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test531.py	(revision 18231)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancevelocitySolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[\
+		md.results.BalancevelocitySolution.SurfaceSlopeX,\
+		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.Vel,\
+		]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.m	(revision 18231)
@@ -0,0 +1,13 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test601.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.m	(revision 18231)
@@ -0,0 +1,16 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test602.py	(revision 18231)
@@ -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,'SSA','all')
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,6,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,MasstransportSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.MasstransportSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test603.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,MasstransportSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.MasstransportSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test604.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,SurfaceSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,5,1.5);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test605.py	(revision 18231)
@@ -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,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,SurfaceSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test606.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BedSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['BedSlopeX','BedSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test607.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BedSlopeSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['BedSlopeX','BedSlopeY']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.m	(revision 18231)
@@ -0,0 +1,13 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test608.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-12]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.m	(revision 18231)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+md.balancethickness.stabilization=3;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test609.py	(revision 18231)
@@ -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,'SSA','all')
+md.balancethickness.stabilization=3
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.m	(revision 18231)
@@ -0,0 +1,14 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test610.py	(revision 18231)
@@ -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,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-12]
+field_values=[\
+	md.results.BalancethicknessSolution.Thickness,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.m	(revision 18231)
@@ -0,0 +1,31 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.masstransport.stabilization=1;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50.*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201;
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10./md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','BalancethicknessThickeningRate','Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test611.py	(revision 18231)
@@ -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,'SSA','all')
+
+#control parameters
+md.inversion.nsteps=2
+md.masstransport.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]
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.m	(revision 18231)
@@ -0,0 +1,40 @@
+md=triangle(model(),'../Exp/79North.exp',10000.);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'SSA','all');
+
+%Ice sheet only
+md=extract(md,md.mask.groundedice_levelset>0.);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+
+%control parameters
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.iscontrol=1;
+md.inversion.nsteps=2;
+md.inversion.control_parameters={'Vx','Vy'};
+md.balancethickness.stabilization=1;
+md.inversion.gradient_scaling=[10./md.constants.yts*ones(md.inversion.nsteps,1) 10./md.constants.yts*ones(md.inversion.nsteps,1)];
+md.inversion.min_parameters=[-2000.*ones(md.mesh.numberofvertices,1) -2000.*ones(md.mesh.numberofvertices,1)];
+md.inversion.max_parameters=[+2000.*ones(md.mesh.numberofvertices,1) +2000.*ones(md.mesh.numberofvertices,1)];
+md.inversion.cost_functions=201;
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.verbose.control=1;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient1','Gradient2','Misfits','Vx','Vy','Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	(md.results.BalancethicknessSolution.Gradient2),...
+	(md.results.BalancethicknessSolution.J),...
+	(md.results.BalancethicknessSolution.Vx),...
+	(md.results.BalancethicknessSolution.Vy),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test613.py	(revision 18231)
@@ -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,'SSA','all')
+
+#Ice sheet only
+md=md.extract(md.mask.groundedice_levelset>0.)
+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]
+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/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test701.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test701.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test701.m	(revision 18231)
@@ -0,0 +1,62 @@
+x =[1:100:3000]';
+h=linspace(1000,300,numel(x))';
+b=-917/1023*h;
+
+md=bamgflowband(model(),x,b+h,b,'hmax',80);
+
+%Geometry
+md.geometry.surface   = interp1(x,b+h,md.mesh.x);
+md.geometry.base       = interp1(x,b,md.mesh.x);
+md.geometry.thickness = md.geometry.surface-md.geometry.base;
+
+%mask
+md.mask.ice_levelset  = - ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(vertexflags(md.mesh,2))) = 0;
+md.mask.groundedice_levelset = double(md.mesh.x<0)-.5;
+
+%materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%friction
+md.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(vertexflags(md.mesh,1)))=20;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Boundary conditions
+md.stressbalance.referential  = NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce = 0*ones(md.mesh.numberofvertices,3);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=0;
+md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
+
+%Misc
+md=setflowequation(md,'FS','all');
+md.stressbalance.abstol=NaN;
+md.stressbalance.FSreconditioning=1;
+md.flowequation.augmented_lagrangian_r=10000;
+md.miscellaneous.name = 'flowline';
+md.cluster=generic('np',2);
+
+%Go solve
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'MINI','MINIcondensed','TaylorHood','XTaylorHood','CrouzeixRaviart'}
+	disp(' ');
+	disp(['====== Testing ' i{1} ' Full-Stokes Finite element =====']);
+	md.flowequation.fe_FS=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},1e-5,1e-5,1e-5,1e-10};
+	field_values={field_values{:},...
+		(md.results.StressbalanceSolution.Vx),...
+		(md.results.StressbalanceSolution.Vy),...
+		(md.results.StressbalanceSolution.Vel),...
+		(md.results.StressbalanceSolution.Pressure),...
+		};
+end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test702.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test702.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test702.m	(revision 18231)
@@ -0,0 +1,53 @@
+%mesh parameters
+x =[-5:.5:5]';
+[b h sea]=NowickiProfile(x);
+x = x*10^3;
+h = h*10^3;
+b = (b-sea)*10^3;
+
+%mesh domain
+md=bamgflowband(model(),x,b+h,b,'hmax',150);
+
+%parameterize
+md.geometry.surface   = interp1(x,b+h,md.mesh.x);
+md.geometry.base       = interp1(x,b,md.mesh.x);
+md.geometry.thickness = md.geometry.surface-md.geometry.base;
+md.mask.ice_levelset = - ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(vertexflags(md.mesh,2))) = 0;
+md.mask.groundedice_levelset = double(md.mesh.x<0)-.5;
+
+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.damage.D=zeros(md.mesh.numberofvertices,1);
+md.damage.spcdamage=NaN(md.mesh.numberofvertices,1);
+md.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(vertexflags(md.mesh,1)))=20;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=800;
+md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
+
+%Misc
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.stressbalance.abstol=NaN;
+md.miscellaneous.name = 'flowline';
+
+%Go solve
+md.cluster=generic('np',2);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={2e-08,2e-08,2e-08,2e-08};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure)};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test703.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test703.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test703.m	(revision 18231)
@@ -0,0 +1,125 @@
+%mesh parameters
+x =[-5:.5:5]';
+[b h sea]=NowickiProfile(x);
+x = x*10^3;
+h = h*10^3;
+b = (b-sea)*10^3;
+
+%mesh domain
+md=bamgflowband(model(),x,b+h,b,'hmax',150);
+
+%parameterize
+md.geometry.surface   = interp1(x,b+h,md.mesh.x);
+md.geometry.base       = interp1(x,b,md.mesh.x);
+md.geometry.thickness = md.geometry.surface-md.geometry.base;
+md.mask.ice_levelset  = - ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(vertexflags(md.mesh,2))) = 0;
+md.mask.groundedice_levelset = double(md.mesh.x<0)-.5;
+
+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.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(vertexflags(md.mesh,1)))=20;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=800;
+md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
+
+%Misc
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.stressbalance.abstol=NaN;
+md.miscellaneous.name = 'flowline';
+
+%Transient settings
+md.timestepping.time_step=0.000001;
+md.timestepping.final_time=0.000005;
+md.stressbalance.shelf_dampening=1;
+md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+posb=find((md.mesh.x>0) & md.mesh.vertexonbase);
+md.basalforcings.groundedice_melting_rate(posb)=18;
+md.basalforcings.floatingice_melting_rate(posb)=18;
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+md.transient.isthermal=0;
+md.masstransport.isfreesurface=1;
+
+%Go solve
+md.cluster=generic('np',3);
+md.stressbalance.shelf_dampening=1;
+md1=solve(md,TransientSolutionEnum());
+
+md.stressbalance.shelf_dampening=0;
+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',...
+	'Vx1_damp','Vy1_damp','Vel1_damp','Pressure1_damp','Bed1_damp','Surface1_damp','Thickness1_damp',...
+	'Vx2_damp','Vy2_damp','Vel2_damp','Pressure2_damp','Bed2_damp','Surface2_damp','Thickness2_damp',...
+	'Vx3_damp','Vy3_damp','Vel3_damp','Pressure3_damp','Bed3_damp','Surface3_damp','Thickness3_damp'};
+field_tolerances={...
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,...
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,...
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,...
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10,...
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10,...
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(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).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md1.results.TransientSolution(1).Vx),...
+	(md1.results.TransientSolution(1).Vy),...
+	(md1.results.TransientSolution(1).Vel),...
+	(md1.results.TransientSolution(1).Pressure),...
+	(md1.results.TransientSolution(1).Base),...
+	(md1.results.TransientSolution(1).Surface),...
+	(md1.results.TransientSolution(1).Thickness),...
+	(md1.results.TransientSolution(2).Vx),...
+	(md1.results.TransientSolution(2).Vy),...
+	(md1.results.TransientSolution(2).Vel),...
+	(md1.results.TransientSolution(2).Pressure),...
+	(md1.results.TransientSolution(2).Base),...
+	(md1.results.TransientSolution(2).Surface),...
+	(md1.results.TransientSolution(2).Thickness),...
+	(md1.results.TransientSolution(3).Vx),...
+	(md1.results.TransientSolution(3).Vy),...
+	(md1.results.TransientSolution(3).Vel),...
+	(md1.results.TransientSolution(3).Pressure),...
+	(md1.results.TransientSolution(3).Base),...
+	(md1.results.TransientSolution(3).Surface),...
+	(md1.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.m	(revision 18231)
@@ -0,0 +1,46 @@
+md=triangle(model(),'../Exp/Square.exp',50000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/ValleyGlacierShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Transient;
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=0;
+md.transient.isgroundingline=1;
+md.transient.isgia=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1',...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2',...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,...
+		1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,...
+		1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+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).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test801.py	(revision 18231)
@@ -0,0 +1,56 @@
+from model import *
+from triangle import *
+from squaremesh 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,'','')
+md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=False
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3']
+field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,\
+		1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,\
+		1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
+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].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.m	(revision 18231)
@@ -0,0 +1,54 @@
+md=triangle(model(),'../Exp/Square.exp',50000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/ValleyGlacierShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Thermal model
+pos_surf=find(md.mesh.vertexonsurface);
+md.thermal.spctemperature(pos_surf)=md.initialization.temperature(pos_surf);
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=1;
+md.transient.isgroundingline=1;
+md.transient.isgia=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Temperature1',...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Temperature2',...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Temperature3'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,...
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+		1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	md.results.TransientSolution(1).Vx,...
+	md.results.TransientSolution(1).Vy,...
+	md.results.TransientSolution(1).Vel,...
+	md.results.TransientSolution(1).Pressure,...
+	md.results.TransientSolution(1).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(1).Temperature,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(2).Temperature,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	md.results.TransientSolution(3).Temperature,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test802.py	(revision 18231)
@@ -0,0 +1,64 @@
+from model import *
+from triangle import *
+from squaremesh 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,'','')
+md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#Thermal model
+pos_surf=numpy.nonzero(md.mesh.vertexonsurface)[0]
+md.thermal.spctemperature[pos_surf]=md.initialization.temperature[pos_surf]
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=True
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Temperature1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Temperature2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Temperature3']
+field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,\
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-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].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+	md.results.TransientSolution[2].Temperature,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.m	(revision 18231)
@@ -0,0 +1,59 @@
+md=triangle(model(),'../Exp/Square.exp',50000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/ValleyGlacierShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Thermal model
+pos_surf=find(md.mesh.vertexonsurface);
+md.thermal.spctemperature(pos_surf)=md.initialization.temperature(pos_surf);
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=1;
+md.transient.isgroundingline=1;
+md.transient.isgia=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Enthalpy1','Watercolumn1',...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3'};
+field_tolerances={1e-10,1e-10,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	md.results.TransientSolution(1).Vx,...
+	md.results.TransientSolution(1).Vy,...
+	md.results.TransientSolution(1).Vel,...
+	md.results.TransientSolution(1).Pressure,...
+	md.results.TransientSolution(1).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(1).Enthalpy,...
+	md.results.TransientSolution(1).Watercolumn,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(2).Enthalpy,...
+	md.results.TransientSolution(2).Watercolumn,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	md.results.TransientSolution(3).Enthalpy,...
+	md.results.TransientSolution(3).Watercolumn,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test803.py	(revision 18231)
@@ -0,0 +1,69 @@
+from model import *
+from triangle import *
+from squaremesh 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,'','')
+md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#Thermal model
+pos_surf=numpy.nonzero(md.mesh.vertexonsurface)[0]
+md.thermal.spctemperature[pos_surf]=md.initialization.temperature[pos_surf]
+md.thermal.isenthalpy=True
+md.thermal.isdynamicbasalspc=True
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=True
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Enthalpy1','Watercolumn1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3']
+field_tolerances=[1e-10,1e-10,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-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].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[0].Enthalpy,\
+	md.results.TransientSolution[0].Watercolumn,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[1].Enthalpy,\
+	md.results.TransientSolution[1].Watercolumn,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+	md.results.TransientSolution[2].Enthalpy,\
+	md.results.TransientSolution[2].Watercolumn,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.m	(revision 18231)
@@ -0,0 +1,48 @@
+md=triangle(model(),'../Exp/Square.exp',50000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/ValleyGlacierShelf.par');
+md=setflowequation(md,'SIA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=0;
+md.transient.isgroundingline=1;
+md.transient.isgia=0;
+
+md.masstransport.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1',...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2',...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+		2e-13,2e-13,2e-13,1e-13,1e-13,1e-13,1e-13,...
+		2e-13,2e-13,2e-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).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test804.py	(revision 18231)
@@ -0,0 +1,59 @@
+from model import *
+from triangle import *
+from squaremesh 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,'','')
+md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md=setflowequation(md,'SIA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=False
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+md.masstransport.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+		2e-13,2e-13,2e-13,1e-13,1e-13,1e-13,1e-13,\
+		2e-13,2e-13,2e-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].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.m
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.m	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.m	(revision 18231)
@@ -0,0 +1,61 @@
+md=triangle(model(),'../Exp/Square.exp',50000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/ValleyGlacierShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Thermal model
+pos_surf=find(md.mesh.vertexonsurface);
+md.thermal.spctemperature(pos_surf)=md.initialization.temperature(pos_surf);
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=1;
+md.transient.isgroundingline=1;
+md.transient.isgia=0;
+
+md.masstransport.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Enthalpy1','Watercolumn1',...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,...
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	md.results.TransientSolution(1).Vx,...
+	md.results.TransientSolution(1).Vy,...
+	md.results.TransientSolution(1).Vel,...
+	md.results.TransientSolution(1).Pressure,...
+	md.results.TransientSolution(1).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(1).Enthalpy,...
+	md.results.TransientSolution(1).Watercolumn,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(2).Enthalpy,...
+	md.results.TransientSolution(2).Watercolumn,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	md.results.TransientSolution(3).Enthalpy,...
+	md.results.TransientSolution(3).Watercolumn,...
+	};
Index: /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/NightlyRun/test805.py	(revision 18231)
@@ -0,0 +1,71 @@
+from model import *
+from triangle import *
+from squaremesh 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,'','')
+md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+#Thermal model
+pos_surf=numpy.nonzero(md.mesh.vertexonsurface)[0]
+md.thermal.spctemperature[pos_surf]=md.initialization.temperature[pos_surf]
+md.thermal.isenthalpy=True
+md.thermal.isdynamicbasalspc=True
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=True
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+md.masstransport.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Enthalpy1','Watercolumn1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3']
+field_tolerances=[1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,\
+		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-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].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[0].Enthalpy,\
+	md.results.TransientSolution[0].Watercolumn,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[1].Enthalpy,\
+	md.results.TransientSolution[1].Watercolumn,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+	md.results.TransientSolution[2].Enthalpy,\
+	md.results.TransientSolution[2].Watercolumn,\
+	]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.par	(revision 18231)
@@ -0,0 +1,56 @@
+%Start defining model parameters here
+
+%Geometry and observation
+x=transpose(ncread('../Data/79North.nc','x'));
+y=transpose(ncread('../Data/79North.nc','y'));
+vx=transpose(ncread('../Data/79North.nc','vx'));
+vy=transpose(ncread('../Data/79North.nc','vy'));
+index=transpose(ncread('../Data/79North.nc','index'));
+surface=transpose(ncread('../Data/79North.nc','surface'));
+thickness=transpose(ncread('../Data/79North.nc','thickness'));
+md.initialization.vx =InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy =InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+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.base=md.geometry.surface-md.geometry.thickness;
+clear surface thickness vx vy x y index;
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=50.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Ice shelf melting and surface mass balance 
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate(find(md.mask.groundedice_levelset<0.))=0.;
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.surfaceforcings.mass_balance=15.*ones(md.mesh.numberofvertices,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.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.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.005;
+md.steadystate.reltol=0.005;
+md.stressbalance.abstol=NaN;
+
+%Boundary conditions:
+md=SetMarineIceSheetBC(md);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/79North.py	(revision 18231)
@@ -0,0 +1,68 @@
+import os.path
+import inspect
+import netCDF4
+import numpy
+from verbose import verbose 
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Start defining model parameters here
+
+#Geometry and observation
+f         = netCDF4.Dataset('../Data/79North.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'][:]
+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.base         = md.geometry.surface-md.geometry.thickness
+
+#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))
+md.initialization.temperature=md.initialization.temperature
+
+#Friction
+md.friction.coefficient=50.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Ice shelf melting and surface mass balance 
+md.basalforcings.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.basalforcings.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+md.surfaceforcings.mass_balance=15*numpy.ones((md.mesh.numberofvertices,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3
+md.masstransport.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.stressbalance.restol=0.05
+md.stressbalance.reltol=0.005
+md.steadystate.reltol=0.005
+md.stressbalance.abstol=float('NaN')
+
+#Boundary conditions:
+md=SetMarineIceSheetBC(md)
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md.masstransport.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/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksAB.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksAB.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksAB.par	(revision 18231)
@@ -0,0 +1,71 @@
+%Geometry specific to Experiments A and B 
+rad=600000;
+nv=md.mesh.numberofvertices; 
+for i=1:nv,
+	dist=sqrt(md.mesh.x(i).^2+md.mesh.y(i)^2);
+	if (dist <= rad)
+		md.geometry.thickness(i)=2000.0;
+	else
+		md.geometry.thickness(i)=1.0; % non-zero thickness
+	end
+end
+md.geometry.thickness=md.geometry.thickness';
+md.geometry.base=zeros(md.mesh.numberofvertices,1); 
+md.geometry.surface=md.geometry.thickness+md.geometry.base; 
+
+%Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice=1000; %kg m^3
+
+%GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity=10^21*ones(md.mesh.numberofvertices,1);    %in Pa.s
+md.gia.lithosphere_thickness=100*ones(md.mesh.numberofvertices,1); %in km
+md.materials.lithosphere_shear_modulus=6.7*10^10;                  %in Pa
+md.materials.lithosphere_density=3.36;                             %in g/cm^3
+md.materials.mantle_shear_modulus=1.45*10^11;                      %in Pa
+md.materials.mantle_density=3.38;                                  %in g/cm^3
+
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.nc','index'));
+
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
+md.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksCD.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksCD.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/GiaBenchmarksCD.par	(revision 18231)
@@ -0,0 +1,70 @@
+%Geometry specific to Experiments C and D  
+rad=800000;
+nv=md.mesh.numberofvertices; 
+for i=1:nv,
+	dist=sqrt(md.mesh.x(i).^2+md.mesh.y(i)^2);
+	if (dist <= rad)
+		md.geometry.thickness(i)=3000.0;
+	else
+		md.geometry.thickness(i)=1.0; % non-zero thickness
+	end
+end
+md.geometry.thickness=md.geometry.thickness';
+md.geometry.base=zeros(md.mesh.numberofvertices,1); 
+md.geometry.surface=md.geometry.thickness+md.geometry.base; 
+
+%Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice=1000; %kg m^3
+
+%GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity=10^21*ones(md.mesh.numberofvertices,1);    %in Pa.s
+md.gia.lithosphere_thickness=100*ones(md.mesh.numberofvertices,1); %in km
+md.materials.lithosphere_shear_modulus=6.7*10^10;                  %in Pa
+md.materials.lithosphere_density=3.32;                             %in g/cm^3
+md.materials.mantle_shear_modulus=1.45*10^11;                      %in Pa
+md.materials.mantle_density=3.34;                                  %in g/cm^3
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.nc','index'));
+
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
+md.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
+
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.par	(revision 18231)
@@ -0,0 +1,20 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180.);
+md.geometry.base=md.geometry.surface-1000.+500.*sin(md.mesh.x*2.*pi/max(md.mesh.x)).*sin(md.mesh.y*2.*pi/max(md.mesh.x));
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+disp('      creating drag');
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for stressbalance model');
+%Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPA.py	(revision 18231)
@@ -0,0 +1,23 @@
+import numpy
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+md.geometry.surface=-md.mesh.x.reshape(-1,1)*numpy.tan(0.5*numpy.pi/180.)
+md.geometry.base=md.geometry.surface-1000.+500.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))*numpy.sin(md.mesh.y.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+
+print "      creating drag"
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.8067*10**7*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      boundary conditions for stressbalance model"
+#Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.par	(revision 18231)
@@ -0,0 +1,20 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180.);
+md.geometry.base=md.geometry.surface-1000.+500.*sin(md.mesh.x*2.*pi/max(md.mesh.x));
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+disp('      creating drag');
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for stressbalance model');
+%Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPB.py	(revision 18231)
@@ -0,0 +1,23 @@
+import numpy
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+md.geometry.surface=-md.mesh.x.reshape(-1,1)*numpy.tan(0.5*numpy.pi/180.)
+md.geometry.base=md.geometry.surface-1000.+500.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+
+print "      creating drag"
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.8067*10**7*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      boundary conditions for stressbalance model"
+#Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.par	(revision 18231)
@@ -0,0 +1,21 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=2000.-md.mesh.x*tan(0.1*pi/180.); %to have z>0
+md.geometry.base=md.geometry.surface-1000.;
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+disp('      creating drag');
+%md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x/2.)).*sin(md.mesh.y*2.*pi/max(md.mesh.x/2.)))./(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)));
+md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x)).*sin(md.mesh.y*2.*pi/max(md.mesh.x))));
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for stressbalance model:');
+%Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPC.py	(revision 18231)
@@ -0,0 +1,24 @@
+import numpy
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+md.geometry.surface=2000.-md.mesh.x.reshape(-1,1)*numpy.tan(0.1*numpy.pi/180.)    #to have z>0
+md.geometry.base=md.geometry.surface-1000.
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+
+print "      creating drag"
+#md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x/2.)).*sin(md.mesh.y*2.*pi/max(md.mesh.x/2.)))./(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)));
+md.friction.coefficient=numpy.sqrt(md.constants.yts*(1000.+1000.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))*numpy.sin(md.mesh.y.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.zeros((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.8067*10**7*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      boundary conditions for stressbalance model:"
+#Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.par	(revision 18231)
@@ -0,0 +1,20 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=2000.-md.mesh.x*tan(0.1*pi/180.); %to have z>0
+md.geometry.base=md.geometry.surface-1000.;
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+disp('      creating drag');
+md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x))));
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for stressbalance model:');
+%Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPD.py	(revision 18231)
@@ -0,0 +1,23 @@
+import numpy
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+md.geometry.surface=2000.-md.mesh.x.reshape(-1,1)*numpy.tan(0.1*numpy.pi/180.)    #to have z>0
+md.geometry.base=md.geometry.surface-1000.
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+
+print "      creating drag"
+md.friction.coefficient=numpy.sqrt(md.constants.yts*(1000.+1000.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.zeros((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.8067*10**7*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      boundary conditions for stressbalance model:"
+#Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.par	(revision 18231)
@@ -0,0 +1,30 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+data=transpose(ncread('../Data/ISMIPE.nc','data'));
+md.geometry.surface=zeros(md.mesh.numberofvertices,1);
+md.geometry.base=zeros(md.mesh.numberofvertices,1);
+for i=1:md.mesh.numberofvertices
+	y=md.mesh.y(i);
+	point1=floor(y/100.)+1;
+	point2=min(point1+1,51);
+	coeff=(y-(point1-1.)*100.)/100.;
+	md.geometry.base(i)=(1.-coeff)*data(point1,2)+coeff*data(point2,2);
+	md.geometry.surface(i)=(1.-coeff)*data(point1,3)+coeff*data(point2,3);
+end
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+md.geometry.thickness(find(~md.geometry.thickness))=0.01;
+md.geometry.base=md.geometry.surface-md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=zeros(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for stressbalance model:');
+%Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPE.py	(revision 18231)
@@ -0,0 +1,35 @@
+import numpy
+import netCDF4
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+f = netCDF4.Dataset('../Data/ISMIPE.nc','r')
+data = f.variables['data'][:]
+f.close()
+md.geometry.surface=numpy.zeros((md.mesh.numberofvertices,1))
+md.geometry.base=numpy.zeros((md.mesh.numberofvertices,1))
+for i in xrange(0,md.mesh.numberofvertices):
+	y=md.mesh.y[i]
+	point1=numpy.floor(y/100.)
+	point2=numpy.minimum(point1+1,50)
+	coeff=(y-(point1-1.)*100.)/100.
+	md.geometry.base[i]=(1.-coeff)*data[point1,1]+coeff*data[point2,1]
+	md.geometry.surface[i]=(1.-coeff)*data[point1,2]+coeff*data[point2,2]
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+md.geometry.thickness[numpy.nonzero(numpy.logical_not(md.geometry.thickness))]=0.01
+md.geometry.base=md.geometry.surface-md.geometry.thickness
+
+print "      creating drag"
+md.friction.coefficient=numpy.zeros((md.mesh.numberofvertices,1))
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.8067*10**7*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      boundary conditions for stressbalance model:"
+#Create node on boundary first (because we can not use mesh)
+md=SetIceSheetBC(md)
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.par	(revision 18231)
@@ -0,0 +1,47 @@
+%Ok, start defining model parameters here
+md.verbose=2;
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(3.*pi/180.);
+%md.geometry.base=md.geometry.surface-1000.;
+md.geometry.base=md.geometry.surface-1000.+100.*exp(-((md.mesh.x-max(md.mesh.x)/2.).^2+(md.mesh.y-max(md.mesh.y)/2.).^2)/(10000.^2));
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+disp('      creating drag');
+md.friction.coefficient=sqrt(md.constants.yts/(2.140373*10^-7*1000.))*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=1.4734*10^14*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=1.*ones(md.mesh.numberofelements,1);
+md.materials.rheology_law='None';
+
+disp('      boundary conditions for stressbalance model');
+%Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md);
+md.stressbalance.spcvx=100.*ones(md.mesh.numberofvertices,1);
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.vel=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+md.initialization.temperature=255.*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.x==min(md.mesh.x) | md.mesh.x==max(md.mesh.x) | md.mesh.y==min(md.mesh.y) | md.mesh.y==max(md.mesh.y));
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
+md.thermal.spctemperature=255.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.geothermalflux=0.4*ones(md.mesh.numberofvertices,1);
+
+%Parallel options
+md.mesh.average_vertex_connectivity=200;
+
+%Transient options
+md.timestepping.time_step=1.;
+md.timestepping.final_time=10.;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.thermal.penalty_threshold=10^5;
+md.transient.isthermal=0;
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ISMIPF.py	(revision 18231)
@@ -0,0 +1,50 @@
+import numpy
+from SetIceSheetBC import SetIceSheetBC
+
+#Ok, start defining model parameters here
+md.verbose=2
+
+print "      creating thickness"
+md.geometry.surface=-md.mesh.x.reshape(-1,1)*numpy.tan(3.*numpy.pi/180.)
+#md.geometry.base=md.geometry.surface-1000.
+md.geometry.base=md.geometry.surface-1000.+100.*numpy.exp(-((md.mesh.x.reshape(-1,1)-numpy.max(md.mesh.x)/2.)**2+(md.mesh.y.reshape(-1,1)-numpy.max(md.mesh.y)/2.)**2)/(10000.**2))
+md.geometry.thickness=md.geometry.surface-md.geometry.base
+
+print "      creating drag"
+md.friction.coefficient=numpy.sqrt(md.constants.yts/(2.140373*10**-7*1000.))*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.zeros((md.mesh.numberofelements,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=1.4734*10**14*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=1.*numpy.ones((md.mesh.numberofelements,1))
+md.materials.rheology_law='None'
+
+print "      boundary conditions for stressbalance model"
+#Create node on boundary first (because we cannot use mesh)
+md=SetIceSheetBC(md)
+md.stressbalance.spcvx=100.*numpy.ones((md.mesh.numberofvertices,1))
+md.initialization.vx=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.vy=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.vel=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.temperature=255.*numpy.ones((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(numpy.logical_or(numpy.logical_or(md.mesh.x==numpy.min(md.mesh.x),md.mesh.x==numpy.max(md.mesh.x)),numpy.logical_or(md.mesh.y==numpy.min(md.mesh.y),md.mesh.y==numpy.max(md.mesh.y))))
+md.balancethickness.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.spcthickness[pos]=md.geometry.thickness[pos]
+md.thermal.spctemperature=255.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.geothermalflux=0.4*numpy.ones((md.mesh.numberofvertices,1))
+
+#Parallel options
+md.mesh.average_vertex_connectivity=200
+
+#Transient options
+md.timestepping.time_step=1.
+md.timestepping.final_time=10.
+md.masstransport.stabilization=1
+md.thermal.stabilization=1
+md.thermal.penalty_threshold=10**5
+md.transient.isthermal=0
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.par	(revision 18231)
@@ -0,0 +1,51 @@
+%Start defining model parameters here
+
+%Geometry and observation
+x         = transpose(ncread('../Data/Pig.nc','x'));
+y         = transpose(ncread('../Data/Pig.nc','y'));
+vx_obs    = transpose(ncread('../Data/Pig.nc','vx_obs'));
+vy_obs    = transpose(ncread('../Data/Pig.nc','vy_obs'));
+index     = transpose(ncread('../Data/Pig.nc','index'));
+surface   = transpose(ncread('../Data/Pig.nc','surface'));
+thickness = transpose(ncread('../Data/Pig.nc','thickness'));
+md.inversion.vx_obs   =InterpFromMeshToMesh2d(index,x,y,vx_obs,md.mesh.x,md.mesh.y);
+md.inversion.vy_obs   =InterpFromMeshToMesh2d(index,x,y,vy_obs,md.mesh.x,md.mesh.y);
+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.base=md.geometry.surface-md.geometry.thickness;
+clear surface thickness vx_obs vy_obs x y index;
+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
+md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.timestepping.time_step=1;
+md.timestepping.final_time=2;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=1;
+md.steadystate.reltol=1;
+md.stressbalance.abstol=NaN;
+
+%Boundary conditions:
+md=SetMarineIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/Pig.py	(revision 18231)
@@ -0,0 +1,62 @@
+import os.path
+import inspect
+import netCDF4
+import numpy
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Start defining model parameters here
+
+#Geometry and observation
+f = netCDF4.Dataset('../Data/Pig.nc','r')
+x         = numpy.reshape(f.variables['x'][:],(-1))
+y         = numpy.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.base=md.geometry.surface-md.geometry.thickness
+md.initialization.vx=md.inversion.vx_obs
+md.initialization.vy=md.inversion.vy_obs
+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))
+md.initialization.temperature=md.initialization.temperature
+
+#Friction
+md.friction.coefficient=50.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3
+md.masstransport.stabilization=1.
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.timestepping.time_step=1.
+md.timestepping.final_time=2.
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=1.
+md.steadystate.reltol=1.
+md.stressbalance.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/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.par	(revision 18231)
@@ -0,0 +1,59 @@
+%Ok, start defining model parameters here
+disp('      creating thickness');
+md.geometry.thickness=10.*ones(md.mesh.numberofvertices,1);
+md.geometry.base=zeros(md.mesh.numberofvertices,1);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating temperatures');
+tmin=238.15; %K
+st=1.67*10^-2/1000.; %k/m
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+md.initialization.temperature=(tmin+st*radius);
+md.basalforcings.geothermalflux=4.2*10^-2*ones(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.81*10^7*ones(md.mesh.numberofvertices,1); %to have the same B as the analytical solution 
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+smb_max=0.5; %m/yr
+sb=10^-2/1000.; %m/yr/m
+rel=450.*1000.; %m
+md.surfaceforcings.mass_balance=min(smb_max,sb*(rel-radius));
+
+disp('      creating velocities');
+constant=0.3;
+md.inversion.vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+md.inversion.vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+md.inversion.vel_obs=(sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2));
+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);
+
+%Deal with boundary conditions:
+disp('      boundary conditions for stressbalance model:');
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
+
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+pos=find(radius==min(radius));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
+
+%parallel options
+md.timestepping.final_time=50000.;
+
+%Constants
+md.materials.rho_ice=910.;
+md.materials.thermalconductivity=2.1;
+md.materials.latentheat=3.35*10^5;
+md.materials.beta=8.66*10^-4/(md.materials.rho_ice*md.constants.g); %conversion from K/m to K/Pa
+md.constants.yts=31556926.;
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetEISMINT.py	(revision 18231)
@@ -0,0 +1,63 @@
+import numpy
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Ok, start defining model parameters here
+print "      creating thickness"
+md.geometry.thickness=10.*numpy.ones((md.mesh.numberofvertices,1))
+md.geometry.base=numpy.zeros((md.mesh.numberofvertices,1))
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+print "      creating drag"
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1)) 
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating temperatures"
+tmin=238.15    #K
+st=1.67*10**-2/1000.    #k/m
+radius=numpy.sqrt((md.mesh.x)**2+(md.mesh.y)**2).reshape(-1,1)
+md.initialization.temperature=tmin+st*radius
+md.basalforcings.geothermalflux=4.2*10**-2*numpy.ones((md.mesh.numberofvertices,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.81*10**7*numpy.ones((md.mesh.numberofvertices,1))    #to have the same B as the analytical solution 
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating surface mass balance"
+smb_max=0.5    #m/yr
+sb=10**-2/1000.    #m/yr/m
+rel=450.*1000.    #m
+md.surfaceforcings.mass_balance=numpy.minimum(smb_max*numpy.ones_like(radius),sb*(rel-radius))
+
+print "      creating velocities"
+constant=0.3
+md.inversion.vx_obs=constant/2.*md.mesh.x.reshape(-1,1)*(md.geometry.thickness)**-1
+md.inversion.vy_obs=constant/2.*md.mesh.y.reshape(-1,1)*(md.geometry.thickness)**-1
+md.inversion.vel_obs=numpy.sqrt((md.inversion.vx_obs)**2+(md.inversion.vy_obs)**2)
+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))
+
+#Deal with boundary conditions:
+print "      boundary conditions for stressbalance model:"
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp')
+
+radius=numpy.sqrt((md.mesh.x)**2+(md.mesh.y)**2)
+pos=numpy.nonzero(radius==numpy.min(radius))[0]
+md.mesh.x[pos]=0.
+md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
+
+#parallel options
+md.timestepping.final_time=50000.
+
+#Constants
+md.materials.rho_ice=910.
+md.materials.thermalconductivity=2.1
+md.materials.latentheat=3.35*10**5
+md.materials.beta=8.66*10**-4/(md.materials.rho_ice*md.constants.g)    #conversion from K/m to K/Pa
+md.constants.yts=31556926.
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.par	(revision 18231)
@@ -0,0 +1,119 @@
+%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=sqrt((md.mesh.x).*md.mesh.x+(md.mesh.y).*md.mesh.y);
+ymin=min(radius);
+ymax=max(radius);
+md.geometry.thickness=hmax+(hmin-hmax)*(radius-ymin)/(ymax-ymin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+
+pos=find(md.mask.groundedice_levelset>0.);
+md.geometry.base(pos)=md.geometry.base(pos)-300.*(radius(pos)-(rad-shelfextent))/(rad-shelfextent);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+pos=find(radius<200000);
+md.geometry.thickness(pos)=100.;
+md.geometry.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(pos)+md.geometry.thickness(pos);
+
+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.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(pos)+md.geometry.thickness(pos);
+
+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.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(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=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad<200000.);
+md.geometry.thickness(pos)=100.;
+md.geometry.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(pos)+md.geometry.thickness(pos);
+
+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.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(pos)+md.geometry.thickness(pos);
+
+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.base(pos)=-di*md.geometry.thickness(pos)-20.;
+md.geometry.surface(pos)=md.geometry.base(pos)+md.geometry.thickness(pos);
+
+%Initial velocity 
+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);
+
+%Surface mass balance and basal melting
+md.surfaceforcings.mass_balance=-10.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset>0.);md.basalforcings.groundedice_melting_rate(pos)=10.;
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.geothermalflux=ones(md.mesh.numberofvertices,1);
+
+%Friction
+radius=1.e6;
+shelfextent=2.e5;
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3.;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3.;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=5.;
+md.timestepping.final_time=5.;
+
+%bathymetry and grounding line migration:
+md.groundingline.migration='AggressiveMigration';
+md.geometry.bed=md.geometry.base;
+pos=find(md.mask.groundedice_levelset<0.); md.geometry.bed(pos)=md.geometry.base(pos)-900.;
+
+%Deal with boundary conditions:
+md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+pos=find(md.mesh.x==0 & md.mesh.y==0);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+
+md.mask.ice_levelset(find(md.mesh.vertexonboundary))=0;
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+md.thermal.spctemperature=737.*ones(md.mesh.numberofvertices,1);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetShelf.py	(revision 18231)
@@ -0,0 +1,129 @@
+import os.path
+import numpy
+import copy
+import inspect
+from paterson import paterson
+from verbose import verbose
+
+#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.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+
+pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
+md.geometry.base[pos]=md.geometry.base[pos]-300.*(radius[pos]-(rad-shelfextent))/(rad-shelfextent)
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+pos=numpy.nonzero(radius<200000.)
+md.geometry.thickness[pos]=100.
+md.geometry.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.base[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.base[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.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
+md.basalforcings.groundedice_melting_rate[pos]=10.
+md.basalforcings.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+md.basalforcings.geothermalflux=numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+radius=1.e6
+shelfextent=2.e5
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+xelem=numpy.mean(md.mesh.x[md.mesh.elements.astype(int)-1],axis=1)
+yelem=numpy.mean(md.mesh.y[md.mesh.elements.astype(int)-1],axis=1)
+rad=numpy.sqrt(xelem**2+yelem**2)
+flags=numpy.zeros(md.mesh.numberofelements)
+pos=numpy.nonzero(rad>=(radius-shelfextent))
+md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1
+md.thermal.stabilization=1
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.05
+md.steadystate.reltol=0.05
+md.stressbalance.abstol=float('nan')
+md.timestepping.time_step=5.
+md.timestepping.final_time=5.
+
+#bathymetry and grounding line migration:
+md.groundingline.migration='AggressiveMigration'
+md.geometry.bed=copy.deepcopy(md.geometry.base)
+pos=numpy.nonzero(md.mask.groundedice_levelset<0.)[0]
+md.geometry.bed[pos]=md.geometry.base[pos]-900.
+
+#Deal with boundary conditions:
+md.stressbalance.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+
+pos=numpy.nonzero(numpy.logical_and(md.mesh.x==0,md.mesh.y==0))
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvy[pos]=0
+
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.mask.ice_levelset[pos]=0
+md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+md.thermal.spctemperature=737.*numpy.ones((md.mesh.numberofvertices,1))
+
+#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/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.par	(revision 18231)
@@ -0,0 +1,53 @@
+disp('      creating thickness');
+hmin=0.01;
+hmax=2756.7;
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+radiusmax=max(radius);
+radius(find(radius>(1.-10^-9)*radiusmax))=radiusmax;    %eliminate roundoff issues in next statement
+md.geometry.thickness=hmin*ones(size(md.mesh.x,1),1)+hmax*(4.*((1./2.)^(4./3.)*ones(size(md.mesh.x,1),1)-((radius)./(2.*radiusmax)).^(4./3.))).^(3./8.);
+md.geometry.base=0.*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating temperatures');
+tmin=238.15; %K
+st=1.67*10^-2/1000.; %k/m
+md.initialization.temperature=tmin+st*radius;
+md.basalforcings.geothermalflux=4.2*10^-2*ones(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.81*10^7*ones(md.mesh.numberofvertices,1); %to have the same B as the analytical solution 
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+smb_max=0.5; %m/yr
+sb=10^-2/1000.; %m/yr/m
+rel=450.*1000.; %m
+md.surfaceforcings.mass_balance=min(smb_max,sb*(rel-radius));
+
+disp('      creating velocities');
+constant=0.3;
+md.inversion.vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+md.inversion.vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+md.inversion.vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+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);
+
+%Deal with boundary conditions:
+disp('      boundary conditions for stressbalance model:');
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
+
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+pos=find(radius==min(radius));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/RoundSheetStaticEISMINT.py	(revision 18231)
@@ -0,0 +1,57 @@
+import numpy
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+print "      creating thickness"
+hmin=0.01
+hmax=2756.7
+radius=numpy.sqrt((md.mesh.x)**2+(md.mesh.y)**2).reshape(-1,1)
+radiusmax=numpy.max(radius)
+radius[numpy.nonzero(radius>(1.-10**-9)*radiusmax)]=radiusmax    #eliminate roundoff issues in next statement
+md.geometry.thickness=hmin*numpy.ones((numpy.size(md.mesh.x),1))+hmax*(4.*((1./2.)**(4./3.)*numpy.ones((numpy.size(md.mesh.x),1))-((radius)/(2.*radiusmax))**(4./3.)))**(3./8.)
+md.geometry.base=0.*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+print "      creating drag"
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating temperatures"
+tmin=238.15    #K
+st=1.67*10**-2/1000.    #k/m
+md.initialization.temperature=tmin+st*radius
+md.basalforcings.geothermalflux=4.2*10**-2*numpy.ones((md.mesh.numberofvertices,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=6.81*10**7*numpy.ones((md.mesh.numberofvertices,1))    #to have the same B as the analytical solution 
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating surface mass balance"
+smb_max=0.5    #m/yr
+sb=10**-2/1000.    #m/yr/m
+rel=450.*1000.    #m
+md.surfaceforcings.mass_balance=numpy.minimum(smb_max*numpy.ones_like(radius),sb*(rel-radius))
+
+print "      creating velocities"
+constant=0.3
+md.inversion.vx_obs=constant/2.*md.mesh.x.reshape(-1,1)*(md.geometry.thickness)**-1
+md.inversion.vy_obs=constant/2.*md.mesh.y.reshape(-1,1)*(md.geometry.thickness)**-1
+md.inversion.vel_obs=numpy.sqrt((md.inversion.vx_obs)**2+(md.inversion.vy_obs)**2)
+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))
+
+#Deal with boundary conditions:
+print "      boundary conditions for stressbalance model:"
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp')
+
+radius=numpy.sqrt((md.mesh.x)**2+(md.mesh.y)**2)
+pos=numpy.nonzero(radius==numpy.min(radius))[0]
+md.mesh.x[pos]=0.
+md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.par	(revision 18231)
@@ -0,0 +1,45 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+md.geometry.thickness=500.*ones(md.mesh.numberofvertices,1);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating initial values');
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+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.vel=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=1.7687*10^8*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+md.surfaceforcings.mass_balance=0.2*ones(md.mesh.numberofvertices,1); %0m/a
+md.basalforcings.floatingice_melting_rate=0.*ones(md.mesh.numberofvertices,1); %0m/a
+md.basalforcings.groundedice_melting_rate=0.*ones(md.mesh.numberofvertices,1); %0m/a
+
+disp('      boundary conditions');
+md=SetMarineIceSheetBC(md,'../Exp/SquareFrontEISMINT.exp');
+
+%Evolution of the ice shelf
+pos=find(md.mesh.y==200000.); %nodes on the upper boundary condition
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness(pos)=500.;
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness(pos)=500.;
+md.masstransport.stabilization=0; %Better result with no artificial diffusivity
+md.thermal.stabilization=0;
+md.timestepping.final_time=500.;
+md.timestepping.time_step=1;
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareEISMINT.py	(revision 18231)
@@ -0,0 +1,48 @@
+import numpy
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Ok, start defining model parameters here
+
+print "      creating thickness"
+ymin=numpy.min(md.mesh.y)
+ymax=numpy.max(md.mesh.y)
+md.geometry.thickness=500.*numpy.ones((md.mesh.numberofvertices,1))
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+print "      creating drag"
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating initial values"
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
+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.vel=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=1.7687*10**8*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating surface mass balance"
+md.surfaceforcings.mass_balance=0.2*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
+md.basalforcings.floatingice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
+md.basalforcings.groundedice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
+
+print "      boundary conditions"
+md=SetMarineIceSheetBC(md,'../Exp/SquareFrontEISMINT.exp')
+
+#Evolution of the ice shelf
+pos=numpy.nonzero(md.mesh.y==200000.)    #nodes on the upper boundary condition
+md.balancethickness.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.balancethickness.spcthickness[pos]=500.
+md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.spcthickness[pos]=500.
+md.masstransport.stabilization=0    #Better result with no artificial diffusivity
+md.thermal.stabilization=0
+md.timestepping.final_time=500.
+md.timestepping.time_step=1
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.par	(revision 18231)
@@ -0,0 +1,66 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.nc','index'));
+
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+md.masstransport.calvingrate=zeros(md.mesh.numberofvertices,1);
+
+%Friction
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
+md.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%GIA: 
+md.gia.lithosphere_thickness=100.*ones(md.mesh.numberofvertices,1); % in km
+md.gia.mantle_viscosity=1.0*10^21*ones(md.mesh.numberofvertices,1); % in Pa.s
+md.materials.lithosphere_shear_modulus=6.7*10^10;                   % in Pa
+md.materials.lithosphere_density=3.32;                              % in g/cm^-3
+md.materials.mantle_shear_modulus=1.45*10^11;                       % in Pa
+md.materials.mantle_density=3.34;                                   % in g/cm^-3
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetConstrained.py	(revision 18231)
@@ -0,0 +1,77 @@
+import os.path
+import netCDF4
+import numpy
+import inspect
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson
+from SetIceSheetBC import SetIceSheetBC
+
+#Start defining model parameters here
+
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=numpy.min(md.mesh.y)
+ymax=numpy.max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.
+md.geometry.surface=md.geometry.base+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))
+
+#Masstransport
+md.masstransport.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1.
+md.thermal.stabilization=1.
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.stressbalance.restol=0.05
+md.steadystate.reltol=0.05
+md.stressbalance.reltol=0.05
+md.stressbalance.abstol=float('NaN')
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+
+#GIA:
+md.gia.lithosphere_thickness=100.*numpy.ones((md.mesh.numberofvertices,1)); # in km
+md.gia.mantle_viscosity=1.*10**21*numpy.ones((md.mesh.numberofvertices,1)); # in Pa.s
+md.materials.lithosphere_shear_modulus=6.7*10**10;                          # in Pa
+md.materials.lithosphere_density=3.32;                                      # in g/cm^-3
+md.materials.mantle_shear_modulus=1.45*10**11;                              # in Pa
+md.materials.mantle_density=3.34;                                           # in g/cm^-3
+
+#Boundary conditions:
+md=SetIceSheetBC(md)
+
+#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/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.par	(revision 18231)
@@ -0,0 +1,63 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300.;
+hmax=1000.;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-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.);
+md.geometry.base(pos)=bed_sheet;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+%Accumulation and melting
+md.surfaceforcings.mass_balance=10.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=5.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=5.*ones(md.mesh.numberofvertices,1);
+
+%Friction
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=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
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareSheetShelf.py	(revision 18231)
@@ -0,0 +1,74 @@
+import os.path
+import inspect
+import netCDF4
+import numpy
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson 
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Start defining model parameters here
+
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.base=-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.base[pos]=bed_sheet
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+#Initial velocity 
+f = netCDF4.Dataset('../Data/SquareSheetShelf.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))
+
+#Accumulation and melting
+md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1
+md.thermal.stabilization=1
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.stressbalance.restol=0.05
+md.steadystate.reltol=0.05
+md.stressbalance.reltol=0.05
+md.stressbalance.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/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.par	(revision 18231)
@@ -0,0 +1,55 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity and pressure
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.stressbalance.restol=0.10;
+md.steadystate.reltol=0.02;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'../Exp/SquareFront.exp');
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf.py	(revision 18231)
@@ -0,0 +1,86 @@
+import os.path
+import inspect
+import netCDF4
+import numpy
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
+
+#Start defining model parameters here
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+#Initial velocity and pressure
+iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
+
+x=numpy.reshape(iVelF.variables['x'][:],(-1))
+y=numpy.reshape(iVelF.variables['y'][:],(-1))
+vx=iVelF.variables['vx'][:]
+vy=iVelF.variables['vy'][:]
+index=iVelF.variables['index'][:].astype(int)
+
+#dbg - begin
+# #print 'vars in SquareShelf.nc:'
+# #for v in iVelF.variables:
+# #	print v
+#dbg - end 
+
+iVelF.close()
+
+[md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.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.)*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
+md.friction.coefficient = 20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p = numpy.ones((md.mesh.numberofelements,1))
+md.friction.q = numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot = 0.3
+md.masstransport.stabilization = 1.
+md.thermal.stabilization = 1.
+md.settings.waitonlock = 30
+md.verbose=verbose()
+md.stressbalance.restol = 0.10
+md.steadystate.reltol = 0.02
+md.stressbalance.reltol = 0.02
+md.stressbalance.abstol = float('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/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.par	(revision 18231)
@@ -0,0 +1,55 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity and pressure
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.stressbalance.restol=0.10;
+md.steadystate.reltol=0.02;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'../Exp/SquareFront2.exp');
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelf2.py	(revision 18231)
@@ -0,0 +1,86 @@
+import os.path
+import inspect
+import netCDF4
+import numpy
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
+
+#Start defining model parameters here
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+#Initial velocity and pressure
+iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
+
+x=numpy.reshape(iVelF.variables['x'][:],(-1))
+y=numpy.reshape(iVelF.variables['y'][:],(-1))
+vx=iVelF.variables['vx'][:]
+vy=iVelF.variables['vy'][:]
+index=iVelF.variables['index'][:].astype(int)
+
+#dbg - begin
+# #print 'vars in SquareShelf.nc:'
+# #for v in iVelF.variables:
+# #	print v
+#dbg - end 
+
+iVelF.close()
+
+[md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.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.)*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
+md.friction.coefficient = 20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p = numpy.ones((md.mesh.numberofelements,1))
+md.friction.q = numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot = 0.3
+md.masstransport.stabilization = 1.
+md.thermal.stabilization = 1.
+md.settings.waitonlock = 30
+md.verbose=verbose()
+md.stressbalance.restol = 0.10
+md.steadystate.reltol = 0.02
+md.stressbalance.reltol = 0.02
+md.stressbalance.abstol = float('nan')
+md.timestepping.time_step = 1.
+md.timestepping.final_time = 3.
+
+#Boundary conditions:
+# #md=SetIceShelfBC(md)
+md=SetIceShelfBC(md,'../Exp/SquareFront2.exp')
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name=os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.par	(revision 18231)
@@ -0,0 +1,60 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareShelfConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareShelfConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelfConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelfConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareShelfConstrained.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Surface mass balance and basal melting
+md.surfaceforcings.mass_balance=10*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=5*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=5*ones(md.mesh.numberofvertices,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.abstol=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
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareShelfConstrained.py	(revision 18231)
@@ -0,0 +1,71 @@
+import os.path
+import netCDF4
+import numpy
+import inspect
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
+
+#Start defining model parameters here
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=numpy.min(md.mesh.y)
+ymax=numpy.max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.base+md.geometry.thickness
+
+#Initial velocity 
+f = netCDF4.Dataset('../Data/SquareShelfConstrained.nc','r')
+#Reshape as Rank-1 arrays
+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))
+
+#Surface mass balance and basal melting
+md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1.
+md.thermal.stabilization=1.
+md.verbose = verbose(0)
+md.settings.waitonlock=30
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.05
+md.steadystate.reltol=0.05
+md.stressbalance.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:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.par	(revision 18231)
@@ -0,0 +1,42 @@
+%Ok, start defining model parameters here
+
+md.timestepping.time_step=0;
+
+disp('      creating thickness');
+h=1000.;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.base=-1000.*ones(md.mesh.numberofvertices,1);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating velocities');
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+
+disp('      creating drag');
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating temperatures');
+md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+md.surfaceforcings.mass_balance=ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+md.basalforcings.groundedice_melting_rate=0.*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+md.basalforcings.floatingice_melting_rate=0.*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+
+%Deal with boundary conditions:
+
+disp('      boundary conditions for stressbalance model');
+md=SetMarineIceSheetBC(md,'../Exp/SquareFront.exp');
+
+disp('      boundary conditions for thermal model');
+md.thermal.spctemperature(:)=md.initialization.temperature;
+md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1); 
+md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.))=1.*10^-3; %1 mW/m^2
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/SquareThermal.py	(revision 18231)
@@ -0,0 +1,45 @@
+import numpy
+from paterson import paterson
+from SetMarineIceSheetBC import SetMarineIceSheetBC
+
+#Ok, start defining model parameters here
+
+md.timestepping.time_step=0
+
+print "      creating thickness"
+h=1000.
+md.geometry.thickness=h*numpy.ones((md.mesh.numberofvertices,1))
+md.geometry.base=-1000.*numpy.ones((md.mesh.numberofvertices,1))
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+print "      creating velocities"
+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))
+
+print "      creating drag"
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating temperatures"
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
+
+print "      creating flow law parameter"
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+print "      creating surface mass balance"
+md.surfaceforcings.mass_balance=numpy.ones((md.mesh.numberofvertices,1))/md.constants.yts    #1m/a
+md.basalforcings.melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))/md.constants.yts    #1m/a
+
+#Deal with boundary conditions:
+
+print "      boundary conditions for stressbalance model"
+md=SetMarineIceSheetBC(md,'../Exp/SquareFront.exp')
+
+print "      boundary conditions for thermal model"
+md.thermal.spctemperature[:]=md.initialization.temperature
+md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1)) 
+md.basalforcings.geothermalflux[numpy.nonzero(md.mask.groundedice_levelset>0.)[0]]=1.*10**-3    #1 mW/m^2
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.par
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.par	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.par	(revision 18231)
@@ -0,0 +1,95 @@
+%Start defining model parameters here
+x = md.mesh.x;
+y = md.mesh.y;
+xmin = min(x);
+xmax = max(x);
+ymin = min(y);
+ymax = max(y);
+Lx = (xmax-xmin);
+Ly = (ymax-ymin);
+xm = (xmin+xmax)/2.;
+ym = (ymin+ymax)/2.;
+
+%Geometry: U-shaped valley in y direction
+thk_center = 1000.;
+thk_margin = 0.5*thk_center;
+bmax = 0.;
+bmin = -thk_center*md.materials.rho_ice/md.materials.rho_water;
+
+alpha = 2./3.;
+slope = 0.9*(bmin-bmax)*(x-xmin)/(Lx*alpha) + 0.1*(bmin-bmax)*(y-ymin)/(Ly) + bmax;
+md.geometry.surface = (thk_center+bmax) + slope ;
+md.geometry.base = bmax + slope + 4./Ly^2*(thk_center-thk_margin)*(y-ym).^2;
+md.geometry.thickness = md.geometry.surface - md.geometry.base;
+md.geometry.bed = md.geometry.base;
+
+%Mask
+md.mask.ice_levelset = x - alpha*Lx;
+md.mask.groundedice_levelset = ones(md.mesh.numberofvertices,1);
+
+%Initial velocity 
+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.15-5.)*ones(md.mesh.numberofvertices,1);
+md.initialization.waterfraction = zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn = zeros(md.mesh.numberofvertices,1);
+md.materials.rheology_B = paterson(md.initialization.temperature);
+md.materials.rheology_n = 3.*ones(md.mesh.numberofelements,1);
+
+%Thermal
+md.thermal.isenthalpy = 0;
+md.thermal.spctemperature = NaN(md.mesh.numberofvertices,1);
+
+%Groundingline
+md.groundingline.migration = 'SubelementMigration';
+
+%Surface mass balance and basal melting
+md.surfaceforcings.mass_balance = 0.3*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = md.surfaceforcings.mass_balance;
+md.basalforcings.groundedice_melting_rate = md.surfaceforcings.mass_balance;
+
+%Friction
+md.friction.coefficient = 20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.)) = 0.;
+md.friction.p = ones(md.mesh.numberofelements,1);
+md.friction.q = ones(md.mesh.numberofelements,1);
+
+%Transient
+md.transient.isstressbalance = 1;
+md.transient.islevelset = 1;
+md.transient.ismasstransport = 0;
+md.transient.isthermal = 0;
+md.transient.isgroundingline = 1;
+md.transient.isgia = 0;
+
+%Stressbalance
+md.stressbalance.maxiter = 100;
+md.stressbalance.viscosity_overshoot = 0.0;
+md.stressbalance.restol = 0.05;
+md.stressbalance.reltol = 0.05;
+md.stressbalance.abstol = NaN;
+
+%Masstransport;
+md.masstransport.calvingrate = 0.*ones(md.mesh.numberofvertices,1);
+md.masstransport.stabilization = 1.;
+
+%Numerical parameters
+md.thermal.stabilization = 1.;
+md.settings.waitonlock = 30;
+md.steadystate.reltol = 0.05;
+md.timestepping.time_step = 1.;
+md.timestepping.final_time = 3.;
+
+%Verbose
+md.verbose = verbose(0);
+
+%Deal with boundary conditions:
+md = SetIceShelfBC(md);
+
+%Change name so that no test have the same name;
+A = dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.py
===================================================================
--- /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.py	(revision 18231)
+++ /issm/branches/trunk-jpl-ad2-integrated/test/Par/ValleyGlacierShelf.py	(revision 18231)
@@ -0,0 +1,102 @@
+import os.path
+import netCDF4
+import numpy
+import inspect
+import math
+from verbose import verbose
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import paterson
+from SetIceShelfBC import SetIceShelfBC
+
+#Start defining model parameters here
+x=md.mesh.x.reshape(-1,1)
+y=md.mesh.y.reshape(-1,1)
+xmin, xmax = min(x), max(x)
+ymin, ymax = min(y), max(y)
+Lx=(xmax-xmin)
+Ly=(ymax-ymin)
+xm,ym = (xmin+xmax)/2., (ymin+ymax)/2.
+
+#Geometry: U-shaped valley in y direction
+thk_center = 1000.
+thk_margin = 0.5*thk_center
+bmax=0.
+bmin=-thk_center*md.materials.rho_ice/md.materials.rho_water
+
+alpha=2./3.
+slope = 0.9*(bmin-bmax)*(x-xmin)/(Lx*alpha) + 0.1*(bmin-bmax)*(y-ymin)/(Ly) + bmax
+md.geometry.surface= (thk_center+bmax) + slope 
+md.geometry.base=bmax + slope + 4./Ly**2*(thk_center-thk_margin)*(numpy.power(y-ym,2))
+md.geometry.thickness=md.geometry.surface - md.geometry.base
+md.geometry.bed = md.geometry.base
+
+#Mask
+md.mask.ice_levelset=x - alpha*Lx
+md.mask.groundedice_levelset= numpy.ones((md.mesh.numberofvertices,1))
+
+#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.15-5.)*numpy.ones((md.mesh.numberofvertices,1))
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Thermal
+md.thermal.isenthalpy=False
+md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+
+#Groundingline
+md.groundingline.migration='SubelementMigration'
+
+#Surface mass balance and basal melting
+md.surfaceforcings.mass_balance=0.3*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=md.surfaceforcings.mass_balance
+md.basalforcings.floatingice_melting_rate=md.surfaceforcings.mass_balance
+
+#Friction
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=False
+md.transient.isthermal=False
+md.transient.isgroundingline=True
+md.transient.isgia=False
+
+#Stressbalance
+md.stressbalance.maxiter=100
+md.stressbalance.viscosity_overshoot=0.0
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.05
+md.stressbalance.abstol=float('nan')
+
+#Masstransport
+md.masstransport.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.stabilization=1.
+
+#Numerical parameters
+md.thermal.stabilization=1.
+md.settings.waitonlock=30
+md.steadystate.reltol=0.05
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+
+#Verbose
+md.verbose = verbose(0)
+
+#Deal with boundary conditions:
+md = SetIceShelfBC(md)
+
+#Change name so that no tests have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
